authkit

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 47 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

authkit

check codeql Go Reference

Embeddable authentication for Go backends on net/http, backed by Postgres, with a typed TypeScript client for the browser.

authkit gives a backend the complete account lifecycle as a library: registration with email verification, password and passkey login, TOTP with recovery codes, OAuth/OIDC providers, sessions, account management, a GDPR data export and grace-period deletion. It owns the Postgres schema authkit and the HTTP routes under /auth/* and /account/*; the host keeps its domain data in its own schema and reacts to account events through hooks that run in authkit's transactions.

It exists for backends that want first-party accounts without running a separate identity server: one process, one database, no token juggling, and security defaults that are hard to get right by hand.

Status: pre-1.0. The exported Go API and the HTTP contract may change between minor versions. Every change is listed in CHANGELOG.md; see Versioning.

Features

  • Sign-in methods: email and password (argon2id), passkeys (passwordless and as second factor, conditional UI), TOTP with recovery codes, OAuth2 and OpenID Connect providers (GitHub preset; Google and single-tenant Microsoft as OIDC).
  • Account lifecycle: email verification, password reset and change, email change with a revert link, session list and revocation, sign out everywhere, re-authentication (sudo mode), GDPR export, deletion with a 14-day grace period and restore.
  • Abuse protection: per-IP rate limits, ALTCHA proof of work after repeated failures, a doubling per-IP delay, bounded password hashing, no account lockout and no account enumeration.
  • Integration: middleware for the host's own routes (RequireUser, OptionalUser), credentialed CORS, CSRF and Origin protection, security headers, lifecycle hooks, an observer for metrics, transactional mails in nine languages, embedded migrations, background purge jobs.
  • Browser client: @johnnycube/authkit-client, generated from api/openapi.yaml, with CSRF handling, passkey ceremonies, ALTCHA solving and a session store for plain JavaScript, Svelte and Astro.
  • Testing support: authkittest with a recording mailer, a manual clock, a protocol client and fixtures.

Security model

  • Sessions are 256-bit random tokens in a __Host- cookie (HttpOnly, Secure, SameSite=Lax), stored as HMAC-SHA256 hashes. They slide for 30 days, end 90 days after login, and are revoked instantly by logout, password changes and email reverts (ADR 0002).
  • Requests that change state must come from FRONTEND_ORIGIN and carry a CSRF token, also on the host's routes behind RequireUser.
  • Secrets at rest: passwords as argon2id, every token as a keyed hash, TOTP secrets encrypted with AES-256-GCM.
  • Mail links carry single-use tokens in the URL fragment, so they never reach access logs or Referer headers.
  • Failed logins escalate to ALTCHA and a per-IP delay instead of locking accounts; second factors escalate per account. Registration, reset and resend answer before doing the work, so timing does not reveal accounts.
  • Accounts are never linked by email: OAuth creates accounts only from provider-verified addresses and links identities only from a signed-in session (ADR 0003, ADR 0007).

The threat model, the guarantees and what stays with the host are in docs/security.md. Report vulnerabilities privately, see SECURITY.md.

Requirements

  • Go 1.27 or newer, Postgres 16 or newer (tested on 19), no extensions.
  • An SMTP account for transactional mail, or your own mail.Mailer.
  • The frontend on https://<domain> and the API on a host of the same site, e.g. https://api.<domain>.
  • For the TypeScript client: a bundler that understands ESM; Node.js 22 or newer to build it from source.

Installation

go get github.com/johnnycube/authkit@latest

The TypeScript client is attached to every GitHub release, see Installing the client.

Quickstart

package main

import (
	"context"
	"embed"
	"errors"
	"io/fs"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/sethvargo/go-envconfig/v2"

	"github.com/johnnycube/authkit"
	"github.com/johnnycube/authkit/mail"
)

//go:embed migrations/*.sql
var migrationFiles embed.FS

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
	defer stop()

	// FRONTEND_ORIGIN, PUBLIC_API_URL, SMTP_FROM, SESSION_KEY, ... and SMTP_HOST, SMTP_PORT, SMTP_USERNAME, ...
	cfg, smtp, err := authkit.LoadEnv(ctx, envconfig.OsLookuper())
	if err != nil {
		log.Fatal(err)
	}
	cfg.ProductName = "Example Notes"
	cfg.Languages = []string{"en", "de", "fr"}

	pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	if err := authkit.Migrate(ctx, pool); err != nil { // schema authkit; run before your own migrations
		log.Fatal(err)
	}
	migrations, _ := fs.Sub(migrationFiles, "migrations")
	if err := authkit.MigrateFS(ctx, pool, "notes", migrations); err != nil { // your schema, same goose setup
		log.Fatal(err)
	}
	mailer, err := mail.NewSMTP(smtp)
	if err != nil {
		log.Fatal(err)
	}
	auth, err := authkit.New(cfg, authkit.Deps{Pool: pool, Mailer: mailer, Hooks: authkit.Hooks{ /* see below */ }})
	if err != nil {
		log.Fatal(err)
	}
	go auth.RunJobs(ctx) // purges and cleanup, hourly

	mux := http.NewServeMux()
	auth.Mount(mux) // /auth/* and /account/*
	mux.Handle("GET /notes", auth.RequireUser(http.HandlerFunc(listNotes)))

	srv := &http.Server{Addr: ":8080", Handler: auth.CORS(auth.SecurityHeaders(mux))}
	go func() {
		if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err) // e.g. the port is taken
		}
	}()

	<-ctx.Done() // SIGTERM or SIGINT
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil { // finishes in-flight requests first
		log.Print(err)
	}
	if err := auth.Close(shutdownCtx); err != nil { // then drains queued mail and registration work
		log.Print(err)
	}
}

func listNotes(w http.ResponseWriter, r *http.Request) {
	user, _ := authkit.UserFromContext(r.Context())
	_ = user.ID // scope every query to the user
}

Host tables reference users with user_id uuid NOT NULL REFERENCES authkit.users(id) ON DELETE CASCADE. The package documentation has runnable examples.

Integration guide

Configuration

authkit.Config and mail.SMTPConfig carry env tags for sethvargo/go-envconfig; authkit.LoadEnv(ctx, lookuper) loads both in one call. These names are public surface (ADR 0008):

Variable Field Meaning
FRONTEND_ORIGIN Config.FrontendOrigin required; the only origin allowed for CORS and state-changing requests, https://<domain>
PUBLIC_API_URL Config.PublicAPIURL required; public URL of the API host; OAuth callbacks go to <PUBLIC_API_URL>/auth/oauth/<name>/callback
WEBAUTHN_RP_ID Config.WebAuthnRPID passkey relying party ID; defaults to the host of FRONTEND_ORIGIN
SMTP_FROM Config.MailFrom required; sender, e.g. Example Notes <noreply@example.com>
TRUSTED_PROXY_CIDRS Config.TrustedProxyCIDRs proxies whose X-Forwarded-For is trusted (comma separated)
SESSION_KEY Config.SessionKey required; keys the hashes of session and mail tokens (base64, 32 bytes)
CSRF_KEY Config.CSRFKey required; signs CSRF tokens (base64, 32 bytes)
TOTP_ENCRYPTION_KEY Config.TOTPEncryptionKey required; AES-256-GCM key for TOTP secrets (base64, 32 bytes)
ALTCHA_HMAC_KEY Config.AltchaHMACKey required; signs ALTCHA challenges (base64, 32 bytes)
DEV_INSECURE_COOKIES Config.DevInsecureCookies local plain-HTTP development only: drops Secure, the __Host- prefix and HSTS
DEV_DISABLE_RATE_LIMITS Config.DevDisableRateLimits local e2e suites only: no rate limits, login backoff or failed-login ALTCHA; refused unless DEV_INSECURE_COOKIES is set, logs a warning
SMTP_HOST SMTPConfig.Host required; SMTP server
SMTP_PORT SMTPConfig.Port default 587
SMTP_USERNAME SMTPConfig.Username enables SMTP authentication when set
SMTP_PASSWORD SMTPConfig.Password SMTP password
SMTP_TLS SMTPConfig.TLS starttls (default, mandatory STARTTLS), tls (implicit TLS) or none (local Mailpit only)
SMTP_TIMEOUT SMTPConfig.Timeout connection and per-command timeout, default 15s

Generate keys with openssl rand -base64 32.

Set in code: ProductName (required), Languages, DefaultLanguage, AccentColor, Paths or Link for the frontend pages mails link to, OAuthProviders, MailOverlay, MaxConcurrentHashes (4) and HashQueueTimeout (3 s), and the durations (defaults: session 30 days sliding, at most 90 days after login (SessionMaxAge), re-auth window 5 minutes, verification link 24 h, reset link 1 h, revert link 7 days, unverified purge 7 days, deletion grace 14 days). authkit.LinkKinds() and authkit.DefaultPath(kind) list the pages below.

Frontend pages

Mails link to FrontendOrigin + path, with the token in the URL fragment (#token=…) so it never reaches access logs or Referer headers. Defaults, overridable per kind with Config.Paths ({lang} is replaced by the user's language, e.g. /{lang}/verify) or completely with Config.Link:

Kind Default path Page calls
verify /verify POST /auth/verify
reset /reset-password POST /auth/password/reset/confirm
email_change /email-change POST /auth/email/confirm
email_revert /email-revert POST /auth/email/revert
deletion_cancel /cancel-deletion POST /auth/deletion/cancel
login /login linked from the "account exists" mail
oauth_result /oauth/callback receives ?status= or ?error= after an OAuth round trip
Browser contract
  1. GET /auth/csrf once per page load; send the token as X-CSRF-Token on every non-GET request. Use credentials: "include" on every request.
  2. Register and request resets with an ALTCHA payload from GET /auth/altcha (ALTCHA widget v3 / protocol v2).
  3. POST /auth/login answers status: ok (with the full account, the same document as GET /account), mfa_required (then /auth/login/totp or /auth/login/passkey/*) or restore_required (then /auth/login/restore to cancel a pending deletion). After 3 failures per account or IP the answer carries altcha_required: true and the next attempt needs a payload; see Abuse protection.
  4. Sensitive operations answer 403 reauth_required outside the 5-minute window; call POST /account/reauth (password or TOTP), the passkey re-auth ceremony or OAuth with mode: reauth, then retry.
  5. Endpoints that hash a password may answer 503 server_busy with Retry-After under load; retry after it.

All errors are {"error": "<code>"}; api/openapi.yaml lists the codes per endpoint.

Migrations

authkit.Migrate(ctx, pool) creates and migrates schema authkit with embedded goose migrations; its version table is authkit.goose_db_version. Run it on start, before your own migrations: it takes a Postgres session lock, so concurrent replicas migrate once. authkit.MigrateFS(ctx, pool, schema, fsys) applies your goose SQL files (at the root of fsys) with the same setup into your own schema (<schema>.goose_db_version). The authkit schema is not public API: read and change accounts through authkit, and in tests through authkittest. Every release names its migrations in the CHANGELOG (ADR 0005).

Hooks
authkit.Hooks{
	// In the transaction that inserts the user; an error rolls the account back. Self-registration runs after
	// the 202 answer (timing must not reveal accounts), so a failure there is logged, not returned. Keep it fast.
	OnUserCreated: func(ctx context.Context, tx pgx.Tx, u authkit.User) error { return nil },
	// Hide public data while the account waits for deletion; restore it on cancel.
	OnDeletionRequested: func(ctx context.Context, tx pgx.Tx, u authkit.User) error { return nil },
	OnDeletionCancelled: func(ctx context.Context, tx pgx.Tx, u authkit.User) error { return nil },
	// In the purge transaction right before the user row is deleted (7-day unverified and 14-day deletion purges).
	// An error skips this user only; it is retried on the next job run while everyone else is purged.
	OnUserDeleted: func(ctx context.Context, tx pgx.Tx, u authkit.User) error { return nil },
	// Project data for GET /account/export (GDPR Art. 20), embedded under "project".
	Export: func(ctx context.Context, u authkit.User) (any, error) { return nil, nil },
}

A hook error inside a request rolls the transaction back and the client gets 500 internal; panics are not recovered. Project tables reference users with user_id uuid NOT NULL REFERENCES authkit.users(id) ON DELETE CASCADE, so the purge removes domain rows even without a hook; use OnUserDeleted for anything outside Postgres. RunJobsOnce returns a JobReport (with PurgeFailed) and the joined error of every failed step.

Observer

Deps.Observer receives operational signals for metrics without a Prometheus dependency: Event(ctx, name) for every audit event (login, login_failed, rate_limited, hash_busy, user_purged, ...), Mail(ctx, kind, err) for each delivery attempt and Jobs(ctx, report, err) for each job run. Mail is at most once: a failed send is logged and reported, not retried; users recover with "resend verification" or a new reset request.

Abuse protection
  • Per-IP rate limits key IPv4 clients by address and IPv6 clients by their /64.
  • Failed password logins never lock an account. After 3 failures per account or per IP every attempt needs an ALTCHA, and the IP waits a delay that doubles from 1 s to 5 minutes between attempts.
  • Failed TOTP or recovery codes count per account in Postgres (across logins, decaying after a day): from the fifth on, each attempt needs an ALTCHA and waits a delay that doubles from 1 s to 15 minutes; a pending login allows 5 attempts; a code is accepted once.
  • argon2id (19 MiB per run) is bounded by MaxConcurrentHashes; requests wait up to HashQueueTimeout, then get 503 server_busy. Unknown accounts run a dummy hash through the same queue.
  • Register, reset and resend answer before doing the account work, so timing does not reveal accounts.
Email change and revert

A change needs sudo mode and a link to the new address (24 h). The link works without a session, but only while the account still has the address and security version it was requested under: a password reset, password change or logout-all cancels the pending change. The old address gets a 7-day revert link that restores the address, signs out everywhere, removes the password and every passkey, TOTP setup and OAuth link added since the change was requested, and mails a link to set a new password (ADR 0006).

OAuth providers

Config.OAuthProviders takes OIDC providers (Issuer, discovery and ID-token verification) and plain OAuth2 providers (AuthURL, TokenURL, UserInfoURL, claim names). authkit.GitHub(id, secret) configures GitHub, which takes the primary address from /user/emails. An account is created only from an address the provider marks verified; otherwise the callback answers ?error=email_unverified and the user registers with a password and links the provider later (ADR 0007). Not supported yet: Apple (form_post callback, rotating JWT client secret) and Microsoft multi-tenant issuers ({tenantid}); single-tenant Microsoft and Google work as OIDC providers.

Testing with authkittest

github.com/johnnycube/authkit/authkittest (test files only) replaces hand-written fixtures: authkittest.NewMailer() records mails and extracts links and tokens (Token(t, mail.KindVerifyEmail, to)), NewClock is a manual clock for Deps.Now, NewClient speaks Origin, CSRF and ALTCHA (SignUp, Login, Altcha), and CreateUser / Session create an account and a session cookie without SQL against authkit's tables (they skip OnUserCreated; use Client.SignUp when the hook must run). For local e2e suites set DEV_DISABLE_RATE_LIMITS=true next to DEV_INSECURE_COOKIES=true.

Middleware
  • auth.Mount(mux) / auth.Handler(): the authkit routes, with security headers, body limit, Origin and CSRF checks.
  • auth.RequireUser(h): 401 without a session; also enforces Origin and CSRF on non-GET requests.
  • auth.OptionalUser(h): attaches the user when signed in.
  • authkit.UserFromContext(ctx): the signed-in authkit.User.
  • auth.CORS(h): credentialed CORS for FrontendOrigin only; wrap the whole mux.
  • auth.SecurityHeaders(h), auth.Protect(h), auth.ClientIP(r).

connect-go services mount next to authkit on the same mux and wrap their handler with auth.RequireUser; the client sends X-CSRF-Token on every call.

Mail texts and branding

Mails are sent in the user's stored language (en, de, fr, es, it, pt, ja, nb, zh), as HTML and plain text. Set Config.MailOverlay to an fs.FS holding <lang>.json files to replace whole message kinds or add a language, and layout.html.tmpl / layout.text.tmpl to replace the layouts; see mail/templates. The renderer validates every kind in every language at startup. A language that only the overlay adds borrows missing kinds from the default language (logged as a warning at startup), so a new mail kind in authkit does not break it. mail.SupportedLanguages() and mail.AllKinds() list the built-in languages and kinds.

Operating notes
  • Replicas and rate limiting. Sessions, tokens, flows, the second-factor failure count and ALTCHA replay records live in Postgres, and the jobs take an advisory lock, so any number of replicas share them. Rate limits, the login failure counter and the hashing queue are in-process (ratelimit.Memory, ratelimit.MemoryFailures): correct for one replica, while N replicas allow N times the configured rates. Pass shared implementations of ratelimit.Limiter and ratelimit.FailureCounter in Deps before scaling out.
  • Memory. Each argon2id run takes 19 MiB; MaxConcurrentHashes (4) bounds the peak. Size the container for it.
  • Trusted proxies. Set TRUSTED_PROXY_CIDRS to the proxies in front of the backend, otherwise every client shares the proxy's address in the rate limits.
  • Migrations run on start under a session lock; releases only expand the schema (ADR 0005), so rolling updates and rollbacks keep working.
  • Shutdown. Call Close after http.Server.Shutdown returned: it waits for queued mail and registration work.
  • Health and metrics belong to the host: authkit serves no /healthz or /metrics; use Deps.Observer for counters.
  • Keys. Rotating SESSION_KEY ends every session; rotating TOTP_ENCRYPTION_KEY makes stored TOTP secrets unreadable. See docs/security.md.

TypeScript client

client/ holds @johnnycube/authkit-client, a framework-agnostic ESM package for the browser: a typed method per endpoint, credentials: "include" on every request, the CSRF token fetched once and refreshed after csrf_failed, passkey ceremonies through @simplewebauthn/browser, ALTCHA solving through the official altcha package, a session store and helpers for the mail-link pages. Request and response types are generated from api/openapi.yaml (make client-gen); make check fails when they drift.

Installing the client

The client is not published to the npm registry. Each release vX.Y.Z carries the packed client as johnnycube-authkit-client-X.Y.Z.tgz, with its .sha256, a keyless cosign bundle (.sigstore.json), an SPDX SBOM, SLSA build provenance and a signed SHA256SUMS. Depend on the tarball URL; the lockfile records its integrity hash.

npm install https://github.com/johnnycube/authkit/releases/download/v0.1.0/johnnycube-authkit-client-0.1.0.tgz
// package.json
"dependencies": {
  "@johnnycube/authkit-client": "https://github.com/johnnycube/authkit/releases/download/v0.1.0/johnnycube-authkit-client-0.1.0.tgz"
}

Verify a downloaded tarball: the signature ties it to this repository's release workflow, the attestation to the commit it was built from.

cosign verify-blob --bundle johnnycube-authkit-client-0.1.0.tgz.sigstore.json \
  --certificate-identity-regexp '^https://github.com/johnnycube/authkit/\.github/workflows/release\.yml@refs/tags/v' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com \
  johnnycube-authkit-client-0.1.0.tgz
gh attestation verify johnnycube-authkit-client-0.1.0.tgz -R johnnycube/authkit

The Go module and the client share one version (the tag): pair @johnnycube/authkit-client X.Y.Z with github.com/johnnycube/authkit vX.Y.Z.

Keeping the client current

Renovate updates the Go module through its gomod manager, but does not follow tarball URLs on its own. A regex manager with the github-releases datasource keeps the URL on the latest release:

{
  "customManagers": [
    {
      "customType": "regex",
      "description": "@johnnycube/authkit-client tarball from the authkit GitHub release",
      "managerFilePatterns": ["/(^|/)package\\.json$/"],
      "matchStrings": [
        "\"@johnnycube/authkit-client\":\\s*\"https://github\\.com/johnnycube/authkit/releases/download/(?<currentValue>v[^/]+)/johnnycube-authkit-client-[^\"]+\\.tgz\""
      ],
      "depNameTemplate": "johnnycube/authkit",
      "datasourceTemplate": "github-releases",
      "autoReplaceStringTemplate": "\"@johnnycube/authkit-client\": \"https://github.com/johnnycube/authkit/releases/download/{{{newValue}}}/johnnycube-authkit-client-{{{replace '^v' '' newValue}}}.tgz\""
    }
  ],
  "packageRules": [
    {
      "description": "authkit: Go module and TypeScript client in one PR",
      "matchPackageNames": ["github.com/johnnycube/authkit", "johnnycube/authkit"],
      "groupName": "authkit"
    }
  ]
}

Renovate then rewrites only package.json; run npm install (or let Renovate's postUpgradeTasks do it) so the lockfile follows.

Usage
import { createAuthClient, isAuthkitError } from "@johnnycube/authkit-client";

export const auth = createAuthClient({ baseUrl: "https://api.example.com" });

const r = await auth.login({ email, password, altcha }); // altcha only once the server asked for it
if (r.status === "mfa_required") await auth.loginSecondFactor({ code: "123456" }); // or { recovery_code }, loginWithPasskey()
if (r.status === "restore_required") await auth.restoreAccount();

try {
  await auth.login({ email, password });
} catch (e) {
  if (isAuthkitError(e, "invalid_credentials") && e.altchaRequired) showAltcha();
  if (isAuthkitError(e, "rate_limited")) wait(e.retryAfter);
}

// Sensitive actions: re-authenticate when the server answers reauth_required, then retry once.
await auth.withReauth(() => auth.requestDeletion(), () => auth.reauth({ password: prompt("Password") ?? "" }));
  • Methods: register, verifyEmail, resendVerification, login, loginSecondFactor, loginWithPasskey, restoreAccount, passkeyLogin({ autofill }), logout, logoutAll, listSessions, revokeSession, requestPasswordReset, confirmPasswordReset, changePassword, requestEmailChange, confirmEmailChange, revertEmailChange, listPasskeys, registerPasskey, renamePasskey, deletePasskey, enrollTotp, confirmTotp, disableTotp, regenerateRecoveryCodes, listOAuthProviders, startOAuth, redirectToOAuth, listIdentities, linkIdentity, unlinkIdentity, reauth, reauthWithPasskey, reauthWithOAuth, withReauth, requestDeletion, cancelDeletion, exportData, getAccount, updateAccount. Bodies and results use the wire format of the OpenAPI spec (snake_case).
  • Errors: every failure is an AuthkitError with the server's code (typed union AuthkitErrorCode), status, retryAfter and altchaRequired; client-side failures use status 0 (network_error, webauthn_cancelled, webauthn_failed, altcha_failed, unexpected_response).
  • Session store: auth.session is a Svelte store (subscribe calls back at once and on every change) and works in plain JS (get(), refresh()). Its state is { status: "unknown" | "signed_in" | "signed_out", account }; the first subscription in a browser loads GET /account, a successful login sets it from the response (which carries the full account), account changes refresh it, signIn(account) sets it by hand, logout, deletion, password reset, email revert and a 401 from /account/* clear it.
  • ALTCHA: auth.solveAltcha() fetches a challenge and solves it (main thread, or Web Workers with { createWorker }); the solver loads lazily, or import it from @johnnycube/authkit-client/altcha. With the widget, use <altcha-widget challenge={auth.altchaChallengeUrl}> and take detail.payload from its verified event.
  • Mail links: readLinkToken() reads #token= on the verify, reset, email-change, email-revert and cancel-deletion pages, clearLinkToken() drops it from the history; readOAuthResult() reads ?status=/?error= on the OAuth result page.
  • Own API: auth.fetch adds credentials and the CSRF header to unsafe requests, e.g. as the fetch of a connect-web transport; auth.csrfToken() returns the token.
SvelteKit
// src/lib/auth.ts
import { PUBLIC_API_BASE } from "$env/static/public";
import { createAuthClient } from "@johnnycube/authkit-client";

export const auth = createAuthClient({ baseUrl: PUBLIC_API_BASE });
export const session = auth.session; // a Svelte store; loads on first use in the browser
<!-- src/routes/login/+page.svelte -->
<script lang="ts">
  import "altcha";
  import { goto } from "$app/navigation";
  import { isAuthkitError } from "@johnnycube/authkit-client";
  import { auth, session } from "$lib/auth";

  let email = $state(""), password = $state(""), code = $state("");
  let altcha = $state<string>(), needAltcha = $state(false), step = $state<"password" | "mfa">("password");

  async function submit() {
    try {
      const r = await auth.login(altcha ? { email, password, altcha } : { email, password });
      if (r.status === "mfa_required") step = "mfa";
      else if (r.status === "restore_required") await auth.restoreAccount();
    } catch (e) {
      needAltcha = isAuthkitError(e) && (e.altchaRequired || e.code === "altcha_required");
    }
  }
</script>

{#if $session.status === "signed_in"}
  <p>Signed in as {$session.account?.email}</p>
  <button onclick={() => auth.logout()}>Sign out</button>
{:else if step === "mfa"}
  <form onsubmit={(e) => { e.preventDefault(); auth.loginSecondFactor({ code }).then(() => goto("/")); }}>
    <input bind:value={code} inputmode="numeric" autocomplete="one-time-code" />
  </form>
{:else}
  <form onsubmit={(e) => { e.preventDefault(); submit(); }}>
    <input bind:value={email} type="email" autocomplete="username webauthn" />
    <input bind:value={password} type="password" autocomplete="current-password" />
    {#if needAltcha}
      <altcha-widget challenge={auth.altchaChallengeUrl} onverified={(e) => (altcha = e.detail.payload)}></altcha-widget>
    {/if}
    <button>Sign in</button>
    <button type="button" onclick={() => auth.passkeyLogin()}>Use a passkey</button>
  </form>
{/if}
Astro
---
// src/pages/verify.astro: the page the verification mail links to (#token=...)
---
<p id="status">Verifying…</p>
<script>
  import { createAuthClient, readLinkToken, clearLinkToken, isAuthkitError } from "@johnnycube/authkit-client";

  const auth = createAuthClient({ baseUrl: import.meta.env.PUBLIC_API_BASE });
  const status = document.getElementById("status")!;
  const token = readLinkToken();
  clearLinkToken();
  if (!token) {
    status.textContent = "This link is incomplete.";
  } else {
    auth.verifyEmail(token).then(
      () => (status.textContent = "Address confirmed. You can sign in now."),
      (e) => (status.textContent = isAuthkitError(e, "invalid_token") ? "This link has expired." : "Please try again."),
    );
  }
</script>

Astro islands share one client through a module such as src/lib/auth.ts; auth.session.subscribe(...) updates the header of every island. Pages render statically, so the session loads in the browser only.

Client development
make client-install      # npm ci (lockfile enforced, install scripts off via client/.npmrc)
make client-check        # spec drift, biome, tsc, Vitest with coverage >= 85 %, build, knip, npm audit, licenses
make client-integration  # Vitest against the Go server (client/test/server) with Postgres, as for the Go tests
make client-gen          # regenerate client/src/generated after changing api/openapi.yaml

The unit tests run the client against a fake server that checks every request and response against api/openapi.yaml; the integration tests do the same against the real handlers.

Versioning

authkit follows Semantic Versioning. Before v1.0, a minor release (0.x.0) may change the public surface, a patch release (0.x.y) only fixes and adds without breaking. The public surface is the exported Go API of authkit, authkit/mail, authkit/ratelimit and authkit/authkittest, the environment variable names, the HTTP contract in api/openapi.yaml and the TypeScript client; the database schema and internal/ are not (ADR 0008). make check compares every change against the previous release with gorelease and oasdiff. Releases are immutable and signed; see docs/upgrading.md for the upgrade procedure.

Documentation

Development

make tools       # pinned golangci-lint, govulncheck, go-licenses, sqlc, gorelease, oasdiff, gitleaks, fleetlint
make check-fast  # format, lint, unit tests (no database)
make check       # the gate: sqlc drift, lint, race tests, coverage >= 85 %, audit, build, API compatibility,
                 # TS client, fleetlint
make fuzz        # fuzz the token, cookie and client IP parsers
make sqlc        # regenerate internal/db after changing migrations or queries

Integration tests start Postgres 19 (and Mailpit for the SMTP test) with testcontainers-go, through Docker or rootless podman (the Makefile points DOCKER_HOST at the podman user socket when it is unset). CI uses service containers and sets AUTHKIT_TEST_DATABASE_URL and AUTHKIT_TEST_MAILPIT_HOST instead. See CONTRIBUTING.md.

Security

Report vulnerabilities privately through GitHub's private vulnerability reporting, see SECURITY.md.

License

MIT

Documentation

Overview

Package authkit is embeddable authentication for Go backends on net/http, backed by Postgres.

It provides the HTTP handlers for registration with email verification, password and passkey login, TOTP with recovery codes, OAuth2/OIDC providers with explicit account linking, sessions, re-authentication (sudo mode), password reset, email change with a revert link, grace-period deletion and a GDPR data export. The browser talks to it with JSON over fetch; api/openapi.yaml describes every endpoint and the TypeScript client @johnnycube/authkit-client is generated from it.

Ownership

authkit owns the Postgres schema "authkit" (created and migrated by Migrate) and the routes under /auth/ and /account/ (registered by Auth.Mount). The host keeps its domain data in its own schema, references authkit.users(id) with ON DELETE CASCADE and reacts to account events through Hooks, which run inside authkit's transactions. authkit has no process of its own: the host constructs it with New, mounts its handlers, wraps its own routes with Auth.RequireUser and runs the background jobs with Auth.RunJobs.

Security model

Sessions are opaque random tokens in a __Host- cookie, stored as HMAC-SHA256 hashes and revocable at once. State-changing requests must come from Config.FrontendOrigin and carry a CSRF token. Failed logins never lock an account; they escalate to a proof-of-work challenge (ALTCHA) and a per-IP delay. Password hashing (argon2id) runs behind a bounded queue. Mail links carry their token in the URL fragment, tokens are single use and hashed at rest, TOTP secrets are encrypted. Rate limits and failure counters are in-process by default, which suits one replica; pass shared implementations of the ratelimit ports in Deps to scale out.

Configuration

Config holds the environment-driven settings (origins, keys, SMTP sender, trusted proxies) and the code-driven ones (product name, languages, frontend paths, OAuth providers, durations). LoadEnv reads the environment and the [mail.SMTPConfig] in one call. Every key is 32 random bytes, base64 encoded.

Package github.com/johnnycube/authkit/authkittest provides a recording mailer, a clock, a protocol client and fixtures for the host's own tests.

Example

A complete host: configuration from the environment, migrations, the authkit routes, a protected route of the host and the background jobs.

package main

import (
	"context"
	"embed"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os/signal"
	"syscall"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/sethvargo/go-envconfig/v2"

	"github.com/johnnycube/authkit"
	"github.com/johnnycube/authkit/mail"
)

// migrations would hold the host's own goose migrations, e.g. //go:embed migrations/*.sql.
var migrations embed.FS

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
	defer stop()

	cfg, smtp, err := authkit.LoadEnv(ctx, envconfig.OsLookuper())
	if err != nil {
		log.Fatal(err)
	}
	cfg.ProductName = "Example"

	pool, err := pgxpool.New(ctx, "postgres://app@localhost/app")
	if err != nil {
		log.Fatal(err)
	}
	defer pool.Close()
	if err := authkit.Migrate(ctx, pool); err != nil {
		log.Fatal(err)
	}
	if err := authkit.MigrateFS(ctx, pool, "app", migrations); err != nil {
		log.Fatal(err)
	}

	mailer, err := mail.NewSMTP(smtp)
	if err != nil {
		log.Fatal(err)
	}
	auth, err := authkit.New(cfg, authkit.Deps{Pool: pool, Mailer: mailer})
	if err != nil {
		log.Fatal(err)
	}
	go func() { _ = auth.RunJobs(ctx) }()

	mux := http.NewServeMux()
	auth.Mount(mux)
	mux.Handle("GET /notes", auth.RequireUser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, _ := authkit.UserFromContext(r.Context())
		fmt.Fprintf(w, "notes of %s", user.ID)
	})))

	srv := &http.Server{Addr: ":8080", Handler: auth.CORS(auth.SecurityHeaders(mux))}
	go func() {
		if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()

	<-ctx.Done()
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil { // finishes in-flight requests first
		log.Print(err)
	}
	if err := auth.Close(shutdownCtx); err != nil { // then drains queued mail and registration work
		log.Print(err)
	}
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultPath

func DefaultPath(kind LinkKind) string

DefaultPath is the frontend path used when Config.Paths leaves kind out; {lang} is replaced by the language.

Example

Mail links point at pages of the frontend; {lang} becomes the user's language.

package main

import (
	"fmt"

	"github.com/johnnycube/authkit"
)

func main() {
	cfg := authkit.Config{Paths: map[authkit.LinkKind]string{authkit.LinkVerify: "/{lang}/verify"}}
	_ = cfg
	for _, kind := range authkit.LinkKinds() {
		fmt.Println(kind, authkit.DefaultPath(kind))
	}
}
Output:
verify /verify
login /login
reset /reset-password
email_change /email-change
email_revert /email-revert
deletion_cancel /cancel-deletion
oauth_result /oauth/callback

func Migrate

func Migrate(ctx context.Context, pool *pgxpool.Pool) error

Migrate applies authkit's schema migrations (schema "authkit").

func MigrateFS

func MigrateFS(ctx context.Context, pool *pgxpool.Pool, schema string, fsys fs.FS) error

MigrateFS applies the host's goose SQL migrations from fsys the way authkit migrates its own: schema is created if missing, the version table is <schema>.goose_db_version, and a Postgres session lock serialises replicas. Run Migrate first when the host's tables reference authkit.users.

Types

type Auth

type Auth struct {
	// contains filtered or unexported fields
}

Auth is a configured authkit instance.

func New

func New(cfg Config, deps Deps) (*Auth, error)

New validates cfg and builds an Auth. Run Migrate before serving.

func (*Auth) CORS

func (a *Auth) CORS(next http.Handler) http.Handler

CORS allows credentialed requests from FrontendOrigin only; wrap the host's whole mux with it.

func (*Auth) ClientIP

func (a *Auth) ClientIP(r *http.Request) netip.Addr

ClientIP returns the client address, honouring X-Forwarded-For only when the peer is a trusted proxy.

func (*Auth) Close

func (a *Auth) Close(ctx context.Context) error

Close waits for queued mails and background registration work (bounded by ctx) and stops background helpers.

func (*Auth) Handler

func (a *Auth) Handler() http.Handler

Handler serves every /auth/* and /account/* route.

func (*Auth) Mount

func (a *Auth) Mount(mux *http.ServeMux)

Mount registers authkit's handlers under /auth/ and /account/ on mux.

func (*Auth) OptionalUser

func (a *Auth) OptionalUser(next http.Handler) http.Handler

OptionalUser attaches the user when a valid session exists and enforces Origin and CSRF checks on state-changing requests.

func (*Auth) Protect

func (a *Auth) Protect(next http.Handler) http.Handler

Protect enforces the Origin check and the CSRF token on state-changing requests.

func (*Auth) RequireUser

func (a *Auth) RequireUser(next http.Handler) http.Handler

RequireUser answers 401 without a valid session and enforces Origin and CSRF checks on state-changing requests.

func (*Auth) RunJobs

func (a *Auth) RunJobs(ctx context.Context) error

RunJobs runs the purge and cleanup jobs every JobInterval until ctx ends.

func (*Auth) RunJobsOnce

func (a *Auth) RunJobsOnce(ctx context.Context) (JobReport, error)

RunJobsOnce purges unverified accounts past UnverifiedTTL and deleted accounts past DeletionGrace, then removes expired sessions, tokens, flows and ALTCHA records. A failing user or step does not stop the others: every step runs, and the joined error and JobReport.PurgeFailed say what failed. It is skipped while another replica holds the lock.

func (*Auth) SecurityHeaders

func (a *Auth) SecurityHeaders(next http.Handler) http.Handler

SecurityHeaders sets restrictive headers suited to a JSON API.

type Config

type Config struct {
	// FrontendOrigin is the only origin allowed for CORS and state-changing requests, e.g. https://example.com.
	FrontendOrigin string `env:"FRONTEND_ORIGIN, required"`
	// PublicAPIURL is the public base URL of the API host, used for OAuth callbacks.
	PublicAPIURL string `env:"PUBLIC_API_URL, required"`
	// WebAuthnRPID defaults to the host of FrontendOrigin.
	WebAuthnRPID string `env:"WEBAUTHN_RP_ID"`
	// MailFrom is the sender address, e.g. "Example <noreply@example.com>".
	MailFrom string `env:"SMTP_FROM, required"`
	// TrustedProxyCIDRs lists the proxies whose X-Forwarded-For is trusted.
	TrustedProxyCIDRs []netip.Prefix `env:"TRUSTED_PROXY_CIDRS"`
	// SessionKey keys the hashes of session, mail and flow tokens at rest.
	SessionKey Key `env:"SESSION_KEY, required"`
	// CSRFKey signs CSRF tokens.
	CSRFKey Key `env:"CSRF_KEY, required"`
	// TOTPEncryptionKey encrypts TOTP secrets at rest (AES-256-GCM).
	TOTPEncryptionKey Key `env:"TOTP_ENCRYPTION_KEY, required"`
	// AltchaHMACKey signs ALTCHA challenges.
	AltchaHMACKey Key `env:"ALTCHA_HMAC_KEY, required"`

	// ProductName appears in mails, TOTP issuer and WebAuthn RP name.
	ProductName string
	// AccentColor is the mail button colour.
	AccentColor string
	// Languages the host accepts for users; default all of mail.SupportedLanguages().
	Languages []string
	// DefaultLanguage is used when a request names none; default en.
	DefaultLanguage string
	// Paths overrides DefaultPath per link kind.
	Paths map[LinkKind]string
	// Link fully overrides how frontend links are built; it receives the kind and language and returns a URL.
	Link func(kind LinkKind, lang string) string
	// OAuthProviders lists enabled OAuth2/OIDC providers; none by default.
	OAuthProviders []OAuthProvider

	SessionTTL     time.Duration // default 30 days, sliding
	SessionMaxAge  time.Duration // default 90 days; absolute lifetime of a session, however active
	ReauthWindow   time.Duration // default 5 minutes
	VerifyTTL      time.Duration // default 24 hours
	ResetTTL       time.Duration // default 1 hour
	EmailChangeTTL time.Duration // default 24 hours
	RevertTTL      time.Duration // default 7 days
	UnverifiedTTL  time.Duration // default 7 days
	DeletionGrace  time.Duration // default 14 days
	PendingTTL     time.Duration // default 5 minutes, for MFA, restore and ceremonies
	JobInterval    time.Duration // default 1 hour

	// AltchaCost is the PBKDF2 iteration count per ALTCHA attempt; default 5000.
	AltchaCost int
	// AltchaMaxCounter bounds the ALTCHA work counter, drawn from [max/2, max); default 10000.
	AltchaMaxCounter int
	// AltchaFailures is the number of failed logins per account or IP after which ALTCHA is required; default 3.
	AltchaFailures int
	// PasswordMinLength defaults to 10; the maximum is 256 bytes.
	PasswordMinLength int
	// MaxBodyBytes caps request bodies; default 64 KiB.
	MaxBodyBytes int64
	// MaxConcurrentHashes bounds concurrent argon2id runs (19 MiB each) process-wide; default 4.
	MaxConcurrentHashes int
	// HashQueueTimeout is how long a request waits for a hashing slot before it gets 503 server_busy; default 3 s.
	HashQueueTimeout time.Duration
	// DevInsecureCookies drops Secure and the __Host- prefix for plain-HTTP local development. Never in production.
	DevInsecureCookies bool `env:"DEV_INSECURE_COOKIES"`
	// DevDisableRateLimits turns off rate limits, login backoff and the failed-login ALTCHA for local e2e suites.
	// It is refused unless DevInsecureCookies is set too.
	DevDisableRateLimits bool `env:"DEV_DISABLE_RATE_LIMITS"`
	// MailOverlay may hold <lang>.json and layout files overriding the built-in mail texts.
	MailOverlay fs.FS
}

Config configures authkit. Tagged fields load from environment variables with sethvargo/go-envconfig (see LoadEnv); the rest are set in code by the host.

func LoadEnv

func LoadEnv(ctx context.Context, lookuper envconfig.Lookuper) (Config, mail.SMTPConfig, error)

LoadEnv reads the environment-backed fields of Config and the SMTP settings in one call, through lookuper (envconfig.OsLookuper() for the process environment). Set the code-only fields afterwards.

Example

LoadEnv reads Config and the SMTP settings in one call; any envconfig.Lookuper works, here a map.

package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"log"

	"github.com/sethvargo/go-envconfig/v2"

	"github.com/johnnycube/authkit"
)

func main() {
	key := base64.StdEncoding.EncodeToString(make([]byte, 32)) // real keys: openssl rand -base64 32
	env := envconfig.MapLookuper(map[string]string{
		"FRONTEND_ORIGIN":     "https://example.com",
		"PUBLIC_API_URL":      "https://api.example.com",
		"SMTP_FROM":           "Example <noreply@example.com>",
		"SMTP_HOST":           "smtp.example.com",
		"SESSION_KEY":         key,
		"CSRF_KEY":            key,
		"TOTP_ENCRYPTION_KEY": key,
		"ALTCHA_HMAC_KEY":     key,
	})
	cfg, smtp, err := authkit.LoadEnv(context.Background(), env)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(cfg.FrontendOrigin, len(cfg.SessionKey))
	fmt.Println(smtp.Host, smtp.Port, smtp.TLS)
}
Output:
https://example.com 32
smtp.example.com 587 starttls

type Deps

type Deps struct {
	// Pool is required; its database must have been migrated with Migrate.
	Pool *pgxpool.Pool
	// Mailer is required and delivers every transactional mail, e.g. mail.NewSMTP.
	Mailer mail.Mailer
	// Logger receives JSON audit and error logs; default slog.Default().
	Logger *slog.Logger
	// Limiter defaults to an in-process limiter (single replica).
	Limiter ratelimit.Limiter
	// Failures counts failed logins for the ALTCHA threshold and the per-IP backoff; default in-process, 15 minute window.
	Failures ratelimit.FailureCounter
	// Hooks are optional; the zero value does nothing.
	Hooks Hooks
	// Observer is optional; the zero value does nothing.
	Observer Observer
	// Now is the clock; default time.Now.
	Now func() time.Time
	// HTTPClient is used for OAuth provider calls; default a client with a 10 s timeout.
	HTTPClient *http.Client
}

Deps are the collaborators authkit needs.

type Hooks

type Hooks struct {
	// OnUserCreated runs in the transaction that inserts the user; registration runs it after the response was sent.
	OnUserCreated func(ctx context.Context, tx pgx.Tx, u User) error
	// OnDeletionRequested runs in the transaction that locks the account for deletion; hide public data here.
	OnDeletionRequested func(ctx context.Context, tx pgx.Tx, u User) error
	// OnDeletionCancelled runs in the transaction that restores the account.
	OnDeletionCancelled func(ctx context.Context, tx pgx.Tx, u User) error
	// OnUserDeleted runs in the purge transaction right before the user row is deleted. An error skips that user
	// only; the purge is retried on the next job run while every other user and cleanup step goes on.
	OnUserDeleted func(ctx context.Context, tx pgx.Tx, u User) error
	// Export returns the host's data of the user for the GDPR export; it must be JSON-encodable.
	Export func(ctx context.Context, u User) (any, error)
}

Hooks let the host react to account lifecycle events. Hooks that receive a pgx.Tx run inside the authkit transaction: returning an error rolls it back and the client gets 500 internal. Panics are not recovered.

Example

Hooks run inside authkit's transactions, so host rows change atomically with the account.

package main

import (
	"context"

	"github.com/jackc/pgx/v5"

	"github.com/johnnycube/authkit"
)

func main() {
	hooks := authkit.Hooks{
		OnUserCreated: func(ctx context.Context, tx pgx.Tx, u authkit.User) error {
			_, err := tx.Exec(ctx, `INSERT INTO app.profiles (user_id) VALUES ($1)`, u.ID)
			return err
		},
		OnDeletionRequested: func(ctx context.Context, tx pgx.Tx, u authkit.User) error {
			_, err := tx.Exec(ctx, `UPDATE app.profiles SET public = false WHERE user_id = $1`, u.ID)
			return err
		},
		Export: func(ctx context.Context, u authkit.User) (any, error) {
			return map[string]any{"notes": []string{}}, nil
		},
	}
	_ = authkit.Deps{Hooks: hooks}
}

type JobReport

type JobReport struct {
	// UnverifiedPurged counts accounts deleted for never verifying their address within UnverifiedTTL.
	UnverifiedPurged int64
	// DeletedPurged counts accounts deleted after their deletion grace period.
	DeletedPurged int64
	// PurgeFailed counts users whose purge failed (e.g. OnUserDeleted returned an error); they are retried next run.
	PurgeFailed int64
	// SessionsExpired counts removed expired sessions.
	SessionsExpired int64
	// TokensExpired counts removed expired or used mail tokens.
	TokensExpired int64
	// FlowsExpired counts removed expired multi-step flows (second factor, passkey, OAuth).
	FlowsExpired int64
	// AltchaExpired counts removed expired ALTCHA replay records.
	AltchaExpired int64
	// Skipped reports that another instance held the job lock, so nothing ran.
	Skipped bool
}

JobReport counts what one job run removed.

type Key

type Key []byte

Key is a 32-byte secret, base64-encoded in the environment.

func (*Key) EnvDecode

func (k *Key) EnvDecode(_ context.Context, val string) error

EnvDecode implements envconfig.DecoderCtx.

type LinkKind

type LinkKind string

LinkKind names a frontend page that mails link to.

const (
	LinkVerify         LinkKind = "verify"
	LinkLogin          LinkKind = "login"
	LinkReset          LinkKind = "reset"
	LinkEmailChange    LinkKind = "email_change"
	LinkEmailRevert    LinkKind = "email_revert"
	LinkDeletionCancel LinkKind = "deletion_cancel"
	LinkOAuthResult    LinkKind = "oauth_result"
)

Frontend pages authkit links to.

func LinkKinds

func LinkKinds() []LinkKind

LinkKinds returns every frontend page authkit links to, in a stable order.

type OAuthProvider

type OAuthProvider struct {
	// Name is the URL slug, e.g. google.
	Name string `json:"name"`
	// DisplayName is shown to users, e.g. Google.
	DisplayName string `json:"display_name"`
	// ClientID is the OAuth client ID registered with the provider.
	ClientID string `json:"client_id"`
	// ClientSecret is the OAuth client secret.
	ClientSecret string `json:"client_secret"`
	// Issuer selects OpenID Connect: endpoints come from its discovery document and ID tokens are verified.
	Issuer string `json:"issuer"`
	// AuthURL is the authorization endpoint of a plain OAuth2 provider (no Issuer).
	AuthURL string `json:"auth_url"`
	// TokenURL is the token endpoint of a plain OAuth2 provider (no Issuer).
	TokenURL string `json:"token_url"`
	// UserInfoURL returns the subject and email claims of a plain OAuth2 provider (no Issuer).
	UserInfoURL string `json:"userinfo_url"`
	// Scopes requested at the provider; with Issuer the default is openid and email.
	Scopes []string `json:"scopes"`
	// SubjectClaim names the stable user ID in the userinfo response of a plain OAuth2 provider; default sub.
	SubjectClaim string `json:"subject_claim"`
	// EmailClaim names the address claim of a plain OAuth2 provider; default email.
	EmailClaim string `json:"email_claim"`
	// EmailVerifiedClaim names the verified flag of a plain OAuth2 provider; default email_verified.
	EmailVerifiedClaim string `json:"email_verified_claim"`
	// EmailsURL is a GitHub-style endpoint listing the user's addresses as [{email, primary, verified}]; when set,
	// the primary address and its verified flag replace the userinfo email claims.
	EmailsURL string `json:"emails_url"`
}

OAuthProvider configures one OAuth2 or OpenID Connect provider. With Issuer set, endpoints come from discovery and the ID token is verified; otherwise AuthURL, TokenURL and UserInfoURL describe a plain OAuth2 provider.

func GitHub

func GitHub(clientID, clientSecret string) OAuthProvider

GitHub returns the provider configuration for GitHub OAuth apps. The account address is the user's primary email, and only when GitHub reports it verified.

Example

GitHub is a preset for a plain OAuth2 provider; OIDC providers only need an Issuer.

package main

import (
	"fmt"

	"github.com/johnnycube/authkit"
)

func main() {
	providers := []authkit.OAuthProvider{
		authkit.GitHub("client-id", "client-secret"),
		{Name: "google", DisplayName: "Google", ClientID: "id", ClientSecret: "secret", Issuer: "https://accounts.google.com"},
	}
	for _, p := range providers {
		fmt.Println(p.Name, p.Issuer != "")
	}
}
Output:
github false
google true

type Observer

type Observer struct {
	// Event receives every audit event name (login, login_failed, rate_limited, user_purged, ...).
	Event func(ctx context.Context, event string)
	// Mail reports each delivery attempt; mail is at most once, a failed send is not retried.
	Mail func(ctx context.Context, kind mail.Kind, err error)
	// Jobs reports each RunJobsOnce result that was not skipped.
	Jobs func(ctx context.Context, rep JobReport, err error)
}

Observer receives operational signals, e.g. for metrics; every field is optional and must not block.

Example

Observer turns authkit's audit events, mail deliveries and job runs into metrics without a metrics dependency.

package main

import (
	"context"
	"encoding/json"
	"log"

	"github.com/johnnycube/authkit"
	"github.com/johnnycube/authkit/mail"
)

func main() {
	counts := map[string]int{}
	obs := authkit.Observer{
		Event: func(_ context.Context, event string) { counts[event]++ }, // must not block; use a mutex or atomic counters
		Mail: func(_ context.Context, kind mail.Kind, err error) {
			if err != nil {
				log.Printf("mail %s failed: %v", kind, err)
			}
		},
		Jobs: func(_ context.Context, rep authkit.JobReport, err error) {
			b, _ := json.Marshal(rep)
			log.Printf("jobs: %s %v", b, err)
		},
	}
	_ = authkit.Deps{Observer: obs}
}

type User

type User struct {
	// ID is stable for the account's lifetime; host tables reference it.
	ID uuid.UUID `json:"id"`
	// Email is the current, normalised address.
	Email string `json:"email"`
	// EmailVerified reports whether the address was confirmed by mail or a trusted provider.
	EmailVerified bool `json:"email_verified"`
	// Language is the user's language for mails, one of Config.Languages.
	Language string `json:"language"`
	// CreatedAt is when the account was registered.
	CreatedAt time.Time `json:"created_at"`
	// DeletionRequestedAt is set while the account is in its deletion grace period.
	DeletionRequestedAt *time.Time `json:"deletion_requested_at,omitempty"`
}

User is the public view of an authkit account.

func UserFromContext

func UserFromContext(ctx context.Context) (User, bool)

UserFromContext returns the user that RequireUser or OptionalUser attached.

Directories

Path Synopsis
Package authkittest helps hosts test code that sits behind authkit: a recording mailer with link extraction, a controllable clock, an HTTP client that speaks authkit's Origin, CSRF and ALTCHA protocol, and fixtures that create users and sessions without SQL against authkit's tables (whose layout is not public API).
Package authkittest helps hosts test code that sits behind authkit: a recording mailer with link extraction, a controllable clock, an HTTP client that speaks authkit's Origin, CSRF and ALTCHA protocol, and fixtures that create users and sessions without SQL against authkit's tables (whose layout is not public API).
internal
db
secretbox
Package secretbox encrypts small secrets with AES-256-GCM.
Package secretbox encrypts small secrets with AES-256-GCM.
token
Package token generates, parses and hashes opaque random tokens.
Package token generates, parses and hashes opaque random tokens.
Package mail renders authkit's transactional mails and delivers them through a pluggable Mailer.
Package mail renders authkit's transactional mails and delivers them through a pluggable Mailer.
Package ratelimit defines the rate limiting and failure counting ports authkit uses, with in-process implementations.
Package ratelimit defines the rate limiting and failure counting ports authkit uses, with in-process implementations.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址