Documentation
¶
Overview ¶
chalk -- phase31-slice31-11 admin bootstrap token.
Between `chalkctl init` and the operator's first signup, the reserved admin username was claimable by ANY visitor: the reserved-list exemption keyed on the username alone. This closes that window. Claiming the admin username now additionally requires the one-shot bootstrap token:
CHALK_ADMIN_BOOTSTRAP_TOKEN set by chalkctl init; printed as
https://<domain>/?admin_token=<token>
Fail closed: env unset => the admin username cannot be claimed at all. Naturally one-shot: once the admin account exists, the username-taken check rejects every further attempt, token or not -- so the URL is dead the moment enrollment (password+TOTP, or a passkey added later) is done.
chalk -- phase31-slice31-2 password-login HTTP handlers.
Two endpoints, both mounted in http.go's MountRegistration:
POST /api/auth/login/prelogin {username}
-> {kdf_alg, kdf_mem_kib, kdf_iters, kdf_par, salt_b64}
The client needs the account's Argon2id salt + params BEFORE it can
derive authProof. To avoid becoming a username-existence oracle, this
always returns params: real ones for a password-enrolled account,
deterministic DECOY ones (Addendum: DecoyKDFParams) otherwise.
POST /api/auth/login/password {username, auth_proof_b64}
-> {totp_pending, expires_at}
Verifies authProof in constant time against user_auth.auth_proof_hash
and, on success, issues a short-lived single-use totp_pending token.
It mints NO session: TOTP is mandatory and POST /api/auth/login/totp
(slice 31-3) mints the session. One exception (139-1): on a review
instance ([HTTPDeps.ReviewMode]), for an account with a confirmed TOTP
secret, this endpoint mints the session and answers with the body of
/api/auth/login/totp.
Note on FOR UPDATE: the locked spec calls for the verify to run under s.withTx / FOR UPDATE. That row lock exists to serialise the MUTABLE TOTP counters (failed_totp_count, locked_until, totp_last_step), which are written by the TOTP step in 31-3 -- that is where the lock lands. The password verify here is a pure read with nothing to serialise, so it uses a plain consistent read; adding an empty transaction would be cargo-cult.
chalk -- phase31-slice31-4 TOTP HTTP handlers (staging-aware). (Supersedes the phase31-slice31-3 version: enrollment now STAGES the new secret so any ACTIVE secret keeps working until confirm promotes it.)
POST /api/auth/login/totp {totp_pending, code}
Second factor against the ACTIVE secret; mints the session on success.
A wrong code does not consume the pending token (DB lockout bounds
guessing); the token is consumed only on success.
POST /api/auth/totp/enroll (session) -> {provisioning_uri, secret_b32}
Stages a fresh secret in totp_pending_secret_enc. First-time setup and
reset are the same path; an existing active secret is untouched.
POST /api/auth/totp/confirm (session) {code} -> {confirmed:true}
Verifies the code against the STAGED secret and atomically promotes it
to active (PromotePendingTOTP).
chalk -- phase31-slice31-9 auth-v2 cutover: migration endpoints + gate.
The hard-cutover machinery (docs/phases/PHASE-31-AUTHV2.md). When CHALK_AUTH_V2_REQUIRED is on (the default), a session belonging to a user who has NOT enrolled in auth v2 (password + confirmed TOTP) is rejected with 409 auth_v2_enrollment_required on every session-gated endpoint EXCEPT the small allowlist needed to complete enrollment. The client sees the 409 (or the auth_v2_enrolled=false field on /api/auth/me) and routes the user into the migration wizard.
POST /api/auth/migration/password (session; only while un-enrolled)
{auth_proof_b64, salt_b64, kdf_alg, kdf_mem_kib, kdf_iters, kdf_par}
Installs the password half (UpsertPasswordAuth). Refused once enrolled
-- enrolled accounts change passwords via /password/change, which
demands the current password.
POST /api/auth/migration/complete (session)
Verifies password + confirmed TOTP are both present, then flips
auth_v2_enrolled=true. Idempotent.
Existing v2 signups never touch any of this (enrolled=true from birth).
chalk -- phase31-slice31-2 password auth helpers.
Server-side half of password authentication. The password itself and the key-wrapping KEK never reach the server (see docs/phases/PHASE-31-AUTHV2.md): the client derives authProof = HKDF(Argon2id(password, salt), "chalk/auth") and sends only authProof. The server stores SHA-256(authProof) in user_auth.auth_proof_hash and constant-time compares on login.
Why SHA-256 and not another Argon2 pass: authProof is already a 256-bit high-entropy output of a memory-hard KDF run client-side. A second expensive server hash would add login latency without meaningful security (a preimage of a 256-bit random is infeasible); the offline-attack cost a DB leak faces is the CLIENT Argon2id, governed by the parameter floor below and the >=20-char password policy.
This file is helpers only; the HTTP handlers live in login_password_http.go, the pending-2FA cache in totp_pending.go.
Package auth is chalk's authentication layer. It wraps go-webauthn for passkey ceremonies, handles session minting, recovery-code generation and verification, and the admin-bootstrap flow.
Phase 09b sub-step 2 ships the skeleton: types, interfaces, and the service constructor. HTTP routing arrives in sub-step 3 (registration) and 4 (authentication). The dev-login bypass is wired up in sub-step 5 when ws.go drops ensureDeviceForTesting.
chalk -- phase31-slice31-4 password reset HTTP handlers.
POST /api/auth/password/change (session)
{current_auth_proof_b64, auth_proof_b64, salt_b64, kdf_alg,
kdf_mem_kib, kdf_iters, kdf_par, generation, wrap_suite, wrap_b64}
Change password while logged in. Verifies the CURRENT authProof, then
atomically installs the new proof/salt/params AND the password seed
wrap the client re-sealed under the new password's KEK (the client
unwrapped the entropy with the old KEK first, so E2E is preserved and
the server never sees plaintext entropy). 81-1: every session except
the caller's is revoked in the same transaction.
POST /api/auth/recovery/reset-auth
{username, words|phrase, auth_proof_b64, salt_b64, kdf_alg,
kdf_mem_kib, kdf_iters, kdf_par, reset_totp, totp_code}
Forgot-password path, gated by the RECOVERY phrase (the auth-only
phrase; NOT the encryption phrase, which never leaves the client).
Verifies + consumes the recovery code,
installs the new password, optionally clears TOTP (lost-authenticator
case: reset_totp=true forces re-enrollment via the minted session),
deletes the now-stale password seed wraps, revokes every existing
session (81-1), mints a fresh one, and
returns FRESH recovery words (the old code is consumed; the store
contract requires immediately installing a new one). The client must
afterwards re-create the password seed wrap from the ENCRYPTION
phrase so new devices can unlock keys with the new password.
31-13: unless reset_totp is set, an account with a confirmed TOTP
secret must also send a live totp_code -- the recovery phrase resets
the password, it does not become a single-factor bypass of the second
factor.
chalk -- 85-1 security-event logging for the auth surface.
chalkd used to log authentication only when it broke internally: a failed decrypt, a failed session mint. Everything an operator actually wants to see -- an account being locked out, a rate limit biting, a login flood against one username -- happened silently, and the only trace was the user reporting it hours later.
The lines here fix that. Two rules keep them from becoming the next problem:
- Nothing logs per request. Every event is either rare by construction (a lockout arms once per N failures; a successful login happens once) or goes through secLogThrottled.
- The line says what happened, to whom, and from where, and nothing else. No codes, no proofs, no tokens -- a log file is not a place to put material that was secret a moment ago.
chalk -- phase31-slice31-6a signup v2 (password + TOTP first).
The auth-v2 registration front door. Unlike the passkey-first flow (register/begin + register/finish), signup v2 creates an account from a password and a LIVE-VERIFIED TOTP enrollment; passkeys become an optional later addition (md-4's add-passkey endpoints, session-gated).
POST /api/auth/register/v2/begin
{username, display_name, email, invite_token?}
Runs the same admission checks as the passkey flow (open-reg/invite,
username shape + reserved + taken, email shape + blacklist + taken),
then parks a pending signup in memory and issues a fresh TOTP secret
for it. -> {signup_token, provisioning_uri, secret_b32, expires_at}
Nothing is written to the database at begin time.
POST /api/auth/register/v2/finish
{signup_token, totp_code, auth_proof_b64, salt_b64, kdf_alg,
kdf_mem_kib, kdf_iters, kdf_par}
Verifies the live TOTP code against the pending secret (proof the
authenticator actually works), enforces the Argon2id floor, then
commits users + user_auth (TOTP confirmed, auth_v2_enrolled=true) +
recovery_codes in ONE transaction, marks the invite used, mints a
session, and returns the recovery words (shown once).
PUT /api/auth/seed-wrap (session) {generation, wrap_suite, wrap_b64}
GET /api/auth/seed-wraps (session) ?generation=N
Upload / fetch the password-wrapped encryption-phrase entropy
(identity_seed_wrap). The client calls PUT after the encryption-
phrase step of the wizard, once it holds both the entropy and the
password-derived KEK. GET serves new-device unlock (31-7).
A failed finish (wrong TOTP code) does NOT consume the pending signup: the user re-reads their authenticator and retries. Codes are 6 digits and the signup token is unguessable, so there is no oracle to grind.
chalk -- phase31-slice31-3 TOTP engine (native RFC 6238).
A dependency-free RFC 4226 (HOTP) / RFC 6238 (TOTP) implementation on the standard library, chosen over a third-party module to keep the auth path free of new dependencies (mirroring chalk's hand-rolled BIP-39) and the applier self-contained. Correctness is pinned by the canonical RFC 4226 HOTP vectors in totp_test.go.
Parameters are the authenticator-app defaults so any standard app (Google Authenticator, Aegis, 1Password, ...) interoperates: HMAC-SHA1, 6 digits, 30-second period, 160-bit (20-byte) secret.
TOTP secrets are shared secrets: whoever holds one can mint valid codes. They are stored AES-256-GCM-encrypted at rest under CHALK_TOTP_ENC_KEY (server-symmetric; distinct from E2E -- TOTP is authentication, not key material, so the server is allowed to decrypt it).
chalk -- phase31-slice31-2 pending-2FA token cache.
After the password (or, in 31-3+, passkey) first factor verifies, the server issues a short-lived, single-use totp_pending token and issues NO session. The client presents that token plus a TOTP code to POST /api/auth/login/totp (slice 31-3), which is where the session is finally minted. TOTP is mandatory, so no login path skips this bridge, except password login on a review instance (139-1, HTTPDeps.ReviewMode).
The token bridges two requests seconds apart, so it lives in memory -- modelled on CeremonyCache (one-shot Take, TTL). It is deliberately not DB-backed: on a server restart an in-flight token is lost and the user simply repeats the (cheap) password step. Expiry is enforced at Take time; abandoned entries are swept opportunistically on Issue rather than by a background janitor, so mounting the handlers starts no goroutines (keeps the test harness leak-free).
Index ¶
- Constants
- Variables
- func Argon2ItersFloor() int32
- func Argon2MemFloorKiB() int32
- func Argon2ParFloor() int32
- func AuthV2Required() bool
- func BuildEmailChangeVerifyURL(baseURL string, encodedToken string) string
- func BuildInviteURL(baseURL string, encodedToken string) string
- func ClearSessionCookie(w http.ResponseWriter)
- func DecodeInviteToken(s string) ([]byte, error)
- func DecryptTOTPSecret(blob []byte) ([]byte, error)
- func DevModeBanner() string
- func EncodeInviteToken(token []byte) string
- func EncryptTOTPSecret(plaintext []byte) ([]byte, error)
- func GenerateInviteToken() ([]byte, error)
- func GenerateRecoveryWords() ([]string, error)
- func GenerateTOTPSecret() ([]byte, error)
- func HOTPCode(key []byte, counter uint64, digits int) string
- func HashAuthProof(authProof []byte) []byte
- func HashRecoveryWords(words []string) ([]byte, error)
- func IPFromRequest(r *http.Request) net.IP
- func InviteTTL() time.Duration
- func IsDevMode() bool
- func IsOpenRegistration() bool
- func IsReservedUsername(s string) bool
- func IsValidUsername(s string) bool
- func MintSession(ctx context.Context, st *store.Store, w http.ResponseWriter, userID uuid.UUID, ...) (store.Session, error)
- func NormalizeRecoveryWords(input string) []string
- func ParamsMeetFloor(alg int16, memKiB, iters, par int32) bool
- func ProvisioningURI(account string, secret []byte) string
- func RequireAdmin(st *store.Store, next func(http.ResponseWriter, *http.Request, *SessionUser)) http.HandlerFunc
- func RequireSession(st *store.Store, next func(http.ResponseWriter, *http.Request, *SessionUser)) http.HandlerFunc
- func ReservedUsernames() []string
- func ResolveReviewMode(requested, marked bool) (bool, error)
- func ReviewModeBanner() string
- func ReviewModeRequested() bool
- func SessionTokenFromRequest(r *http.Request) ([]byte, error)
- func SetGuestSessionCookie(w http.ResponseWriter, token []byte, expiresAt time.Time)
- func TOTPCodeAt(secret []byte, t time.Time) string
- func TOTPIssuer() string
- func TOTPLockout() time.Duration
- func TOTPMaxFailures() int
- func TOTPPendingTTL() time.Duration
- func TOTPSecretBase32(secret []byte) string
- func TOTPSkew() int
- func TOTPStep(t time.Time) int64
- func UserAgentFromRequest(r *http.Request) string
- func ValidAvatarFrame(v string) bool
- func ValidateTOTP(secret []byte, code string, now time.Time, skew int) (int64, bool)
- func VerifyAuthProof(storedHash, authProof []byte) bool
- func VerifyRecoveryCodeHash(storedSaltHash []byte, words []string) error
- func VerifyRecoveryWords(words []string) error
- type CeremonyCache
- type CeremonyEntry
- type CeremonyKind
- type Config
- type ConnKicker
- type HTTPDeps
- func (d *HTTPDeps) MountAdmin(mux *http.ServeMux) error
- func (d *HTTPDeps) MountAttachments(mux *http.ServeMux) error
- func (d *HTTPDeps) MountGiphy(mux *http.ServeMux) error
- func (d *HTTPDeps) MountLinkPreview(mux *http.ServeMux) error
- func (d *HTTPDeps) MountNetprobe(mux *http.ServeMux) error
- func (d *HTTPDeps) MountRegistration(mux *http.ServeMux) error
- func (d *HTTPDeps) MountUserLookup(mux *http.ServeMux) error
- type KDFParams
- type PendingTOTP
- type PendingTOTPCache
- type PendingUser
- type Service
- func (s *Service) BeginLogin(user *User, opts ...webauthn.LoginOption) (*protocol.CredentialAssertion, *webauthn.SessionData, error)
- func (s *Service) BeginRegistration(user *User, opts ...webauthn.RegistrationOption) (*protocol.CredentialCreation, *webauthn.SessionData, error)
- func (s *Service) FinishLogin(user *User, sess webauthn.SessionData, ...) (*webauthn.Credential, error)
- func (s *Service) FinishRegistration(user *User, sess webauthn.SessionData, ...) (*webauthn.Credential, error)
- func (s *Service) RPDisplayName() string
- func (s *Service) RPID() string
- func (s *Service) RPOrigins() []string
- type SessionUser
- type SignupV2Cache
- type User
Constants ¶
const CookieName = "chalk_session"
CookieName is the chalk session cookie name. Distinct from a generic "session" so multiple chalk instances on shared dev hosts don't trample each other's cookies via different ports/origins.
const CookiePath = "/"
CookiePath scopes the cookie to the entire chalk app. We don't narrow this to /api because the WS upgrade goes through /ws and must see the cookie.
const DefaultCeremonyTTL = 5 * time.Minute
DefaultCeremonyTTL is the lifetime of a pending ceremony before it's pruned. WebAuthn ceremonies are interactive — the user clicks a button, the authenticator does its work, and the SPA POSTs back — and almost always complete within seconds. 5 minutes is a conservative ceiling.
const DefaultInviteTTLDays = 4
DefaultInviteTTLDays is used when CHALK_INVITE_TTL_DAYS is unset or unparseable. Per phase 09 plan section 9. Picked to be long enough that a casual user can act on it after a weekend, short enough that stale invites don't accumulate.
const DefaultJanitorInterval = 30 * time.Second
DefaultJanitorInterval is how often the janitor scans for expired entries. The cost of a scan is O(entries); for our scale (single- digit concurrent registrations) any value in 10s..1min is fine.
const DefaultTOTPPendingTTL = 5 * time.Minute
DefaultTOTPPendingTTL bounds how long a user has to complete the TOTP step after the first factor. A few minutes is ample for typing a 6-digit code.
const EmailChangeTTL = 24 * time.Hour
EmailChangeTTL is how long the pending email-change is valid. Per the phase 09 plan, 24 hours. Shorter than invite TTL because the user is already authenticated and can easily restart the flow.
const EmailChangeTokenSize = 32
EmailChangeTokenSize is the byte count for verification tokens. Same security margin as invite and session tokens.
const GuestCookieName = "chalk_guest_session"
GuestCookieName is the guest session cookie, deliberately DISTINCT from CookieName: a logged-in member clicking a join link must not have their real session overwritten by a guest one.
const InviteTokenSize = 32
InviteTokenSize is the wire-side byte count for a freshly-generated token. 32 bytes of CSPRNG output, base64url-encoded to 43 chars (without padding). Matches the security margin of the session token in 09b.
const RecoveryWordCount = 24
RecoveryWordCount is the number of words in a chalk recovery phrase. 24 BIP-39 words encode 264 bits (24 × 11 bits) of which 256 are entropy and 8 are a checksum. Per DECISION 5, we use 24 words for the highest entropy tier supported by the BIP-39 spec.
Variables ¶
var ( ErrCeremonyNotFound = errors.New("auth: ceremony not found") ErrCeremonyExpired = errors.New("auth: ceremony expired") )
Errors. Distinguished so callers can return different HTTP statuses (404 for not found, 410 Gone for expired).
var ( ErrPendingNotFound = errors.New("auth: pending 2FA token not found") ErrPendingExpired = errors.New("auth: pending 2FA token expired") )
Errors distinguished so the TOTP handler can return different statuses.
var AvatarFrames = []string{"", "ember", "aurora", "pulse", "matrix", "frost", "gold"}
AvatarFrames is the allowlist, "" first. The client's list (web/src/avatars/frames.ts) names the same set in the same order; a new style is a CSS rule plus a line in each. Order matters only for the picker, which is why the two lists are kept identical rather than merely equal as sets.
var ErrInvalidSession = errors.New("auth: invalid or expired session")
ErrInvalidSession is returned when a cookie is present but the token doesn't decode, doesn't exist in the sessions table, or has expired. Maps to 401 from HTTP handlers.
var ErrNoSession = errors.New("auth: no session cookie")
ErrNoSession is returned when no session cookie is present on the request (the user hasn't logged in, or the cookie was cleared).
var ErrReviewModeUnmarked = errors.New(
"CHALK_REVIEW_MODE is set, but this database is not a review database " +
"(table review_instance is empty). Remove CHALK_REVIEW_MODE, or use " +
"the database that `chalkctl review init` made")
ErrReviewModeUnmarked is the error of ResolveReviewMode when CHALK_REVIEW_MODE is set but the database is not marked as a review database.
var ErrSignupCapacity = errors.New("auth: too many pending signups")
ErrSignupCapacity is returned by SignupV2Cache.Put when the cache is full.
var ErrTOTPEncKeyUnset = errors.New("auth: CHALK_TOTP_ENC_KEY not set (required to store TOTP secrets)")
ErrTOTPEncKeyUnset is returned when CHALK_TOTP_ENC_KEY is required (to store or read a TOTP secret) but is not configured.
Functions ¶
func Argon2ItersFloor ¶ added in v0.3.15
func Argon2ItersFloor() int32
Argon2ItersFloor returns the configured minimum Argon2id iteration count.
func Argon2MemFloorKiB ¶ added in v0.3.15
func Argon2MemFloorKiB() int32
Argon2MemFloorKiB returns the configured minimum Argon2id memory cost.
func Argon2ParFloor ¶ added in v0.3.15
func Argon2ParFloor() int32
Argon2ParFloor returns the configured minimum Argon2id parallelism.
func AuthV2Required ¶ added in v0.3.15
func AuthV2Required() bool
AuthV2Required reports whether the hard cutover is active. Defaults to ON; set CHALK_AUTH_V2_REQUIRED=0 to run the transition period with mixed auth.
func BuildEmailChangeVerifyURL ¶
BuildEmailChangeVerifyURL constructs the URL sent to the new email address during an email-change ceremony. Same baseURL semantics as BuildInviteURL.
func BuildInviteURL ¶
BuildInviteURL constructs the URL an invitee receives via email. The SPA detects ?invite=<token> at boot and renders the pre-registration screen with the email pre-filled.
baseURL is the chalk deployment's externally-visible origin, passed from the http server config (CHALK_PUBLIC_URL or similar). Falls back to / + query if baseURL is empty.
func ClearSessionCookie ¶
func ClearSessionCookie(w http.ResponseWriter)
ClearSessionCookie writes a Set-Cookie header that deletes the chalk session cookie from the browser. The browser deletes a cookie by receiving a Set-Cookie with the same Name/Path and an Expires in the past. The caller is responsible for any database- side cleanup (deleting the row from sessions).
func DecodeInviteToken ¶
DecodeInviteToken parses a base64url string (with or without padding) into raw bytes. Tolerant of both forms because some clients re-encode URLs and add padding back.
Errors:
- "invalid token shape" if the string is empty or decoding fails
- "wrong token length" if the decoded byte count is not InviteTokenSize
func DecryptTOTPSecret ¶ added in v0.3.15
DecryptTOTPSecret opens a blob produced by EncryptTOTPSecret.
func DevModeBanner ¶
func DevModeBanner() string
DevModeBanner returns a single-line stderr-friendly banner that chalkd prints at startup when IsDevMode() is true. The text is stable so log scrapers can match it.
func EncodeInviteToken ¶
EncodeInviteToken renders the token in URL-safe base64 without padding. Callable on tokens of any length; the canonical input is InviteTokenSize bytes producing 43 characters.
func EncryptTOTPSecret ¶ added in v0.3.15
EncryptTOTPSecret seals a TOTP secret as nonce||ciphertext||tag under CHALK_TOTP_ENC_KEY. Returns ErrTOTPEncKeyUnset if the key is not configured.
func GenerateInviteToken ¶
GenerateInviteToken returns InviteTokenSize random bytes from a CSPRNG. Returns an error only on a catastrophic OS-level CSPRNG failure, in which case the caller MUST NOT proceed (returning a non-random token would defeat the entire invite security model).
func GenerateRecoveryWords ¶
GenerateRecoveryWords returns a freshly generated 24-word recovery phrase. The entropy comes from crypto/rand; an OS RNG failure returns an error (never expected in practice, but propagated rather than panicked).
The output is a slice of 24 words. The application formats them as a space-separated string only at display time.
Implementation: BIP-39 mnemonic generation with 256 bits entropy.
- Read 32 random bytes (256 bits).
- Compute SHA-256 checksum; take the top 8 bits (256/32 = 8).
- Append the checksum to the entropy: 264 bits total.
- Split into 24 11-bit groups (big-endian); each group indexes one word in the wordlist.
The result is a valid BIP-39 mnemonic; any standard BIP-39 wallet could decode it. For chalk's purposes that's incidental; we just need a high-entropy, human-readable, well-distributed phrase.
func GenerateTOTPSecret ¶ added in v0.3.15
GenerateTOTPSecret returns a fresh 20-byte random TOTP secret.
func HOTPCode ¶ added in v0.3.15
HOTPCode computes the RFC 4226 HOTP value for key and counter, as a zero-padded decimal string of the given digit count.
func HashAuthProof ¶ added in v0.3.15
HashAuthProof returns the value stored in user_auth.auth_proof_hash for a given client authProof: SHA-256(authProof). Enrollment handlers use this to compute the stored hash; the verify path recomputes and compares.
func HashRecoveryWords ¶
HashRecoveryWords argon2id-hashes the space-joined recovery phrase and returns salt || hash (48 bytes total: 16 salt + 32 hash). Caller stores the result in recovery_codes.hash; verification reads it back and calls VerifyRecoveryCodeHash.
The phrase is normalized (lowercased, single-space joined) before hashing so the verification path tolerates user input variations.
func IPFromRequest ¶
IPFromRequest extracts the client IP. Honors X-Forwarded-For when the PEER is a trusted proxy; otherwise uses RemoteAddr.
80-8: behind chalkctl's Caddy every request used to resolve to the proxy container's address, which turned the join endpoints' per-IP rate limit into one bucket for the entire internet. CHALK_TRUSTED_PROXY names the proxies chalkd may believe: a comma-separated CIDR list, or the value "private" (loopback + RFC1918 + ULA -- the right answer for the stock deployment, where Caddy shares a container network with chalkd). When the peer matches, the LAST X-Forwarded-For entry wins: that is the one the trusted proxy itself appended; anything left of it is client-supplied and forgeable. Unset keeps the old behavior (dev mode trusts XFF, production trusts nothing).
func InviteTTL ¶
InviteTTL returns the configured time-to-live for newly-created invites. Reads CHALK_INVITE_TTL_DAYS; falls back to DefaultInviteTTLDays for empty/unparseable values.
Bounds: clamped to [1, 60] days to prevent operator typo disasters (1-second invites are useless; 1-year invites accumulate stale data). The clamp is silent — if you set 90, you get 60.
func IsDevMode ¶
func IsDevMode() bool
IsDevMode reports whether the dev login bypass is enabled. It reads the CHALK_DEV environment variable; any of "1", "true", "yes", "on" (case-insensitive) enables it. Anything else is dev-off.
Sub-step 5 will wire this into the HTTP layer: a /api/dev/login endpoint that mints a session for a named fixture user without a passkey ceremony, AND a 404 response from that endpoint when IsDevMode() returns false. Sub-step 2 ships only the predicate so other components (e.g. the SPA's "Log in as alice/bob/carol" quick-login buttons) can branch on it once we expose it via the welcome frame.
The plan also describes a //go:build dev tag for compile-time elimination. We deliberately do NOT add that yet: the runtime check is simpler to test, and the cost of the unused endpoint existing in a production binary (when CHALK_DEV is unset) is one extra route registration that returns 404. We can add the build tag later if the security review insists on belt-and-suspenders.
func IsOpenRegistration ¶
func IsOpenRegistration() bool
IsOpenRegistration reports whether chalkd is running in open- registration mode. When true, POST /api/auth/register/begin accepts requests without an invite token, and any caller can claim any (non-reserved, non-taken) username.
Default is OFF. The intended use is initial bootstrap of a self- hosted instance (admin creates their own account before invites exist) and development. Production deploys should leave it off after the admin has registered; once invites land in 09c, the invite path is the only way in.
Read from CHALK_OPEN_REGISTRATION (any truthy variant: 1, true, yes, on; case-insensitive). The cmd/chalkd entry point also exposes a --open-registration flag via the config package; the flag wins over the env var per chalk's standard precedence.
This predicate is the runtime check the HTTP handler consults at request time. The config field is the boot-time-known value; IsOpenRegistration() reads the env directly so tests can use t.Setenv without rebuilding a Config. In production the two agree by construction (chalkd sets the env from its own flag resolution).
func IsReservedUsername ¶
IsReservedUsername reports whether s is on the reserved list. The check is case-insensitive even though the shape requires lowercase, because the input may not have been shape-checked yet.
func IsValidUsername ¶
IsValidUsername reports whether s satisfies the chalk username shape constraint. It does NOT check the reserved-username list or existing-user collisions; those are layered on top by the auth service.
func MintSession ¶
func MintSession( ctx context.Context, st *store.Store, w http.ResponseWriter, userID uuid.UUID, userAgent string, ip net.IP, ) (store.Session, error)
MintSession creates a new session row for userID, sets the Set- Cookie header on w, and returns the populated Session struct so the caller can include session_expires_at in the response body.
userAgent and ip are extracted from the request via the helpers in this file. Pass empty strings when unavailable; the columns allow NULL.
The Set-Cookie attributes are HttpOnly, Secure (in production), and SameSite=Strict. In dev mode (CHALK_DEV=1) Secure is omitted so the cookie works over plain HTTP on localhost — browsers otherwise reject Secure cookies on http:// origins.
func NormalizeRecoveryWords ¶
NormalizeRecoveryWords lowercases, trims, and splits a candidate recovery phrase into its constituent words. Whitespace runs of any kind separate words. Used by the verification HTTP endpoint to tolerate copy-paste artifacts from the SPA's word-input UI.
func ParamsMeetFloor ¶ added in v0.3.15
ParamsMeetFloor reports whether client-submitted Argon2id parameters are at or above the configured floor. Enrollment handlers (later slices) call this to reject a client that lowballs its KDF cost. alg must be 1 (argon2id).
func ProvisioningURI ¶ added in v0.3.15
ProvisioningURI builds the otpauth:// URI the client renders as a QR code.
func RequireAdmin ¶
func RequireAdmin( st *store.Store, next func(http.ResponseWriter, *http.Request, *SessionUser), ) http.HandlerFunc
RequireAdmin wraps RequireSession and additionally enforces that the resolved SessionUser has role == "admin". A non-admin session gets 403 forbidden (NOT 401, because the user IS authenticated; they just lack the privilege). An expired or missing session short-circuits via RequireSession with the usual 401.
The admin singleton (migration 0011) guarantees there is at most one admin row; this middleware doesn't enforce singleton, only "the caller is THAT row." A blocked / soft-deleted admin can never exist by trigger (migration 0019), so we don't have to guard against it here.
func RequireSession ¶
func RequireSession( st *store.Store, next func(http.ResponseWriter, *http.Request, *SessionUser), ) http.HandlerFunc
RequireSession is a middleware-style wrapper. Resolves the session from the request; on success calls next with the SessionUser attached to the context; on failure writes a 401 JSON error and short-circuits. Used for endpoints that strictly require a logged- in user (like /api/auth/me, /api/auth/logout).
Endpoints that *optionally* care about a session (e.g. register/begin to know if the user is already logged in) call ResolveSession directly and branch on the error.
func ReservedUsernames ¶
func ReservedUsernames() []string
ReservedUsernames returns a sorted snapshot of the reserved-username set. Intended for diagnostic output and tests; the application itself uses IsReservedUsername.
func ResolveReviewMode ¶ added in v0.13.0
ResolveReviewMode returns the review mode for chalkd from the two gates:
- requested false: false, nil, whatever marked is
- requested true, marked false: false, ErrReviewModeUnmarked
- requested true, marked true: true, nil
chalkd does not start on the error.
func ReviewModeBanner ¶ added in v0.13.0
func ReviewModeBanner() string
ReviewModeBanner returns the line that chalkd logs at each start in review mode. The text is stable, so that log scrapers can match it.
func ReviewModeRequested ¶ added in v0.13.0
func ReviewModeRequested() bool
ReviewModeRequested reports whether the CHALK_REVIEW_MODE env var asks for review mode. Any of "1", "true", "yes", "on" (case-insensitive) asks for it. Anything else does not.
func SessionTokenFromRequest ¶
SessionTokenFromRequest reads the chalk session cookie from r and returns the decoded raw token. Returns ErrNoSession when the cookie is absent, or ErrInvalidSession when the encoding is bad.
This is the single source of truth for cookie reading; both the HTTP middleware and the WS upgrade path call into it.
func SetGuestSessionCookie ¶ added in v0.7.0
func SetGuestSessionCookie(w http.ResponseWriter, token []byte, expiresAt time.Time)
SetGuestSessionCookie writes the guest cookie. SameSite=Lax rather than Strict: a guest arrives on a cross-site top-level navigation (the link in their mail client), and Strict would make every re-click look logged out.
func TOTPCodeAt ¶ added in v0.3.15
TOTPCodeAt returns the 6-digit TOTP for secret at time t.
func TOTPIssuer ¶ added in v0.3.15
func TOTPIssuer() string
TOTPIssuer is the issuer label in the provisioning URI. CHALK_TOTP_ISSUER, default "Chalk".
func TOTPLockout ¶ added in v0.3.15
TOTPLockout is the lockout duration after too many failures. CHALK_TOTP_LOCKOUT (seconds), default 900, min 1.
func TOTPMaxFailures ¶ added in v0.3.15
func TOTPMaxFailures() int
TOTPMaxFailures is the failed-code count that triggers lockout. CHALK_TOTP_MAX_FAILURES, default 5, min 1.
func TOTPPendingTTL ¶ added in v0.3.15
TOTPPendingTTL reads CHALK_AUTH_TOTP_PENDING_TTL (seconds), defaulting to DefaultTOTPPendingTTL. Env-read to match openreg.go's test-friendly pattern.
func TOTPSecretBase32 ¶ added in v0.3.15
TOTPSecretBase32 renders a secret as unpadded uppercase base32, the form authenticator apps expect for manual entry and inside the otpauth URI.
func TOTPSkew ¶ added in v0.3.15
func TOTPSkew() int
TOTPSkew is the accepted +/- period skew. CHALK_TOTP_SKEW, default 1, min 0.
func UserAgentFromRequest ¶
UserAgentFromRequest returns the User-Agent header, truncated to a reasonable length (some clients send giant UAs that would bloat the sessions table).
func ValidAvatarFrame ¶ added in v0.8.17
ValidAvatarFrame reports whether v is a frame the server will store.
func ValidateTOTP ¶ added in v0.3.15
ValidateTOTP checks code against secret within +/-skew steps of now. On a match it returns the matched step and true; otherwise 0 and false. The per-candidate comparison is constant-time. The caller enforces replay (matched step must exceed the last consumed step) at the DB layer.
func VerifyAuthProof ¶ added in v0.3.15
VerifyAuthProof reports whether authProof hashes to storedHash, in constant time. A zero-length storedHash (no enrollment) always returns false but still performs the compare against a dummy of equal length so callers can keep timing uniform.
func VerifyRecoveryCodeHash ¶
VerifyRecoveryCodeHash returns nil iff the candidate words hash to the stored value. Constant-time comparison. Returns an error if the stored value is malformed or the words don't match.
The application reads the stored hash from recovery_codes.hash (without altering the row) and calls this. After a successful verification, the application calls store.MarkRecoveryCodeUsed and then store.SetRecoveryCode (with a fresh phrase) in the same transaction.
func VerifyRecoveryWords ¶
VerifyRecoveryWords checks that words has exactly RecoveryWordCount entries, that each one is in the BIP-39 wordlist, and (because we generated this phrase ourselves) that the appended checksum bit is correct. Returns nil iff the phrase is well-formed.
This is used as a fast pre-flight check before doing the constant-time argon2 hash comparison: a malformed phrase can be rejected without revealing whether the hashed phrase matched. The final accept/reject decision uses VerifyRecoveryCodeHash.
Types ¶
type CeremonyCache ¶
type CeremonyCache struct {
// contains filtered or unexported fields
}
CeremonyCache is a goroutine-safe, TTL-bounded cache of in-flight WebAuthn ceremonies. Keyed by challenge string.
Concurrency: a single sync.RWMutex protects the map. The Get and Take operations also delete on success (one-shot ceremonies), so they take the write lock; Put always takes the write lock.
Lifecycle: New constructs an empty cache; RunJanitor starts a background goroutine that periodically prunes expired entries. The janitor exits when its context is canceled. Callers wire this into the server's lifecycle context.
func NewCeremonyCache ¶
func NewCeremonyCache(ttl time.Duration) *CeremonyCache
NewCeremonyCache returns an empty cache with the given TTL. Pass zero TTL to use DefaultCeremonyTTL.
func (*CeremonyCache) Len ¶
func (c *CeremonyCache) Len() int
Len returns the current number of entries. Test-only.
func (*CeremonyCache) Prune ¶
func (c *CeremonyCache) Prune() int
Prune removes all expired entries. Returns the number removed. Called periodically by RunJanitor. Idempotent; safe to call from multiple goroutines but the janitor is the only intended caller.
func (*CeremonyCache) Put ¶
func (c *CeremonyCache) Put(challenge string, entry CeremonyEntry) bool
Put stores entry under the challenge key. Overwrites any existing entry with the same challenge (in practice unique by construction — challenges are 32-byte cryptographic randoms from go-webauthn — but we don't rely on that). The entry's ExpiresAt is set from the cache's TTL relative to now.
Returns false when the cache is at capacity (81-4). The register and authenticate begin endpoints are anonymous, so without a ceiling a caller that starts ceremonies and never finishes them grows this map at will; the janitor only reclaims them once their TTL passes. An inline prune runs first, so a full cache means genuinely-live ceremonies, not stale ones.
func (*CeremonyCache) RunJanitor ¶
func (c *CeremonyCache) RunJanitor(ctx context.Context, interval time.Duration)
RunJanitor sweeps expired entries at interval until ctx is canceled. Pass zero interval to use DefaultJanitorInterval. Returns when ctx is done. Run in its own goroutine; the server's lifecycle context is the natural fit.
func (*CeremonyCache) Take ¶
func (c *CeremonyCache) Take(challenge string) (CeremonyEntry, error)
Take fetches and removes the entry for challenge. One-shot semantics: once consumed, the ceremony cannot be re-used. Returns (entry, ErrCeremonyExpired) if the entry exists but its TTL has passed, and (CeremonyEntry{}, ErrCeremonyNotFound) if no entry exists.
Expired entries are removed on lookup; the janitor is for entries that are never looked up (abandoned ceremonies).
type CeremonyEntry ¶
type CeremonyEntry struct {
Kind CeremonyKind
Session webauthn.SessionData
PendingUser PendingUser
ExpiresAt time.Time
}
CeremonyEntry is one in-flight WebAuthn ceremony. It carries enough state from the Begin call to complete the Finish call without trusting any of it from the client at finish time.
The cache key is the WebAuthn challenge string (already a 32-byte random value generated by go-webauthn). Keying on the challenge means:
- SPA doesn't have to round-trip a separate ID (it has the challenge from BeginRegistration's response anyway)
- The cache key is unforgeable: an attacker cannot guess another user's pending registration challenge
- Lookup is one map access
PendingUser carries the username/displayName/email the SPA submitted at begin time. Sub-step 3 uses these at finish time to populate the users row. If we trusted the SPA to resubmit them at finish, a race-then-swap attack could let a registrant create a user with a different username than the one whose passkey they just minted.
type CeremonyKind ¶
type CeremonyKind int
CeremonyKind discriminates entries in the cache. Sub-step 3 only uses KindRegistration; KindLogin lands in sub-step 4.
const ( KindRegistration CeremonyKind = iota + 1 KindLogin )
type Config ¶
type Config struct {
// RPID is the WebAuthn Relying Party ID. For browser ceremonies
// this must be the effective domain of the chalk server (e.g.
// "localhost" in dev, "chalk.example.com" in prod). Browsers
// reject credentials whose RP ID doesn't match the page origin.
//
// Sourced from CHALK_RP_ID env var, defaulting to "localhost".
RPID string
// RPDisplayName is the human-readable RP name shown to the user
// in the authenticator's UI ("Sign in to <RPDisplayName>?").
//
// Sourced from CHALK_RP_NAME env var, defaulting to "chalk".
RPDisplayName string
// RPOrigins is the list of origins allowed to initiate WebAuthn
// ceremonies against this RP. Must include scheme and (if non-
// default) port. For dev: ["http://localhost:8443"]. For prod:
// ["https://chalk.example.com"]. Multiple origins are allowed
// for multi-host deployments; we typically have one.
//
// Currently derived by the application from the listen address
// and TLS mode; the auth.Config takes the final list to keep
// the dependency direction one-way.
RPOrigins []string
}
Config configures the auth service. All fields are required unless noted.
type ConnKicker ¶
ConnKicker is the small subset of *server.Hub the admin endpoints need: terminate every active WebSocket connection bound to a user. Implementations should be cheap and non-blocking (queue closes, don't wait on them).
Defined in this package so the auth-side has its own interface; *server.Hub satisfies it by adding a CloseConnsForUser method in the same patch that wires admin endpoints.
type HTTPDeps ¶
type HTTPDeps struct {
Service *Service // WebAuthn ceremony primitives
Cache *CeremonyCache // in-flight ceremony state
Store *store.Store // user/passkey/recovery persistence
Logger *log.Logger // optional; nil → log.Default()
// AdminUsername, if set, is the one username that may be claimed
// even when it's on the reserved list. Sourced from the
// CHALK_ADMIN_USERNAME env var; falls back to "" (no override)
// when unset. The reserved-username check is exempted only for
// this exact string match.
AdminUsername string
// Mailer delivers invite emails and email-change verification
// links. Required when CHALK_OPEN_REGISTRATION is unset (i.e. in
// invite-only mode) and whenever an authenticated user requests
// an email change. May be nil in tests that don't exercise mail.
Mailer mail.Mailer
// PublicURL is the externally-visible origin used to build invite
// and email-change verification URLs sent in outgoing mail. Empty
// → relative URLs ("/?invite=...") which work but require the
// recipient to be on the same origin as chalkd.
PublicURL string
// Phase 09d-1: Kicker terminates active WS connections for a user
// when admin moderation blocks or soft-deletes them. May be nil;
// when nil, the moderation endpoints still kill sessions and the
// next WS frame will fail at the session check.
Kicker ConnKicker
// att-1: attachment limits, sourced from config.Attachments and plumbed
// in by cmd/chalkd. AttachMaxBytes caps a single upload; AttachChunkBytes
// is the chunk size advertised to clients and the chunk-PUT body bound;
// AttachFetchWindow bounds the eager backfetch list query.
AttachMaxBytes int64
AttachChunkBytes int
AttachFetchWindow time.Duration
// 30-8: uplink probe endpoint (POST /api/netprobe, design Addendum D).
// NetprobeEnabled mirrors CHALK_VOICE_ENABLED && CHALK_VOICE_PROBE_ENABLED;
// NetprobeMaxBytes is CHALK_VOICE_PROBE_BYTES, the server-side body cap.
NetprobeEnabled bool
NetprobeMaxBytes int64
// att-4: Giphy search-proxy client, built from config.Giphy and plumbed
// in by cmd/chalkd. Nil when CHALK_GIPHY_API_KEY is unset; in that case
// the search endpoint answers 503 and /api/auth/config reports
// giphy_enabled=false so the SPA hides the picker. The key lives only
// here, never reaching the client.
GiphyClient *giphy.Client
// 57-1: link-preview fetcher, built from config.LinkPreview and plumbed
// in by cmd/chalkd. Nil when CHALK_LINKPREVIEW_ENABLED=false; the
// endpoints then answer 503 and /api/auth/config reports
// linkpreview_enabled=false. LinkPreviewDomains is the default
// whitelist the SPA auto-offers previews for (a consent/UX control;
// the fetcher's SSRF guards are the security boundary).
LinkPreview *linkpreview.Client
LinkPreviewDomains []string
// 85-1: whether to log security events (lockouts, rate-limit denials,
// login outcomes). Mirrors CHALK_OPLOG_SECURITY, plumbed in by cmd/chalkd.
// secLogLimiter throttles the events whose rate an attacker controls; see
// security_log.go.
SecurityLog bool
// 31-2: pending-2FA token cache bridging the password/passkey first
// factor to the mandatory TOTP step. Lazily defaulted in
// MountRegistration when nil, so existing wiring and tests need no
// change.
PendingTOTP *PendingTOTPCache
// 31-6a: in-flight v2 signups (password+TOTP-first). Lazily
// defaulted in MountRegistration when nil.
SignupV2 *SignupV2Cache
// 80-8: guest magic-link redemption (join_http.go). EphemeralEnabled
// mirrors CHALK_EPHEMERAL_ENABLED; when false the /api/join endpoints
// answer 404 as if they did not exist. JoinStore overrides the store the
// join endpoints use (tests); nil means d.Store.
EphemeralEnabled bool
JoinStore joinStoreAPI
// 65-3: true if Web Push is on (CHALK_PUSH_ENABLED with a valid VAPID
// key). Only this boolean reaches /api/auth/config. The VAPID public
// key will travel over the sealed WebSocket (65-4).
PushEnabled bool
// 139-1: ReviewMode is true only on a review instance for app review.
// cmd/chalkd sets it at startup from [ResolveReviewMode]. When true,
// password login gives a session without the TOTP step, and
// /api/auth/config reports review_mode=true. Nothing else changes.
ReviewMode bool
// OnGuestJoined is called after a FIRST redemption materializes a guest,
// so the server can push member_added to the room's members (their
// clients otherwise show the guest's messages under a UUID stub until
// reconnect). Wired in cmd/chalkd like Kicker; may be nil in tests.
OnGuestJoined func(channelID, guestID uuid.UUID)
// contains filtered or unexported fields
}
HTTPDeps bundles the dependencies the HTTP handlers need. Held by the server's lifecycle and passed in once at construction time.
func (*HTTPDeps) MountAdmin ¶
MountAdmin registers the admin moderation endpoints on mux. The admin bootstrap endpoint (which is unauthenticated and uses the bootstrap token) is mounted by MountAdminBootstrap separately, because the auth model differs.
Returns an error if HTTPDeps.Store is nil. ConnKicker may be nil in tests; when nil, the block / soft-delete handlers still set the timestamp and delete sessions but cannot close active WS connections (the next message attempt will fail at the session check).
func (*HTTPDeps) MountAttachments ¶
MountAttachments registers the attachment endpoints on mux. Requires Store to be set (the chunked endpoints are pure persistence; no WebAuthn service is involved). Returns an error if Store is nil so a misconfigured server fails at construction rather than at first upload.
func (*HTTPDeps) MountGiphy ¶
MountGiphy registers the Giphy search-proxy endpoint (att-4).
The route is always mounted when called. If no API key is configured (d.GiphyClient == nil) it answers 503 so a misconfigured client gets a clear signal; GET /api/auth/config separately reports giphy_enabled so the SPA hides the picker entirely in that case and never calls here.
Route:
GET /api/giphy/search?q=... → { "results": [ ... ] } (session required)
Why proxy at all: the API key is a server-only secret, and proxying means Giphy sees only chalkd's IP during SEARCH, never the end user. The render fetch (the unavoidable URL-reference leak) happens client-side and only for users who opted in.
func (*HTTPDeps) MountLinkPreview ¶ added in v0.4.8
MountLinkPreview registers the link-preview fetch endpoints (57-1).
The routes are always mounted when called. If the feature is disabled (d.LinkPreview == nil) they answer 503; GET /api/auth/config separately reports linkpreview_enabled so the SPA never offers previews in that case.
Routes (session required):
GET /api/linkpreview?url=... → Preview JSON (OpenGraph metadata) GET /api/linkpreview/image?url=... → thumbnail bytes
Why the server fetches at all: the SENDER's client calls these for a URL it is about to send, embeds the result in the E2E-encrypted body, and recipients render without any network fetch. The linked site sees only chalkd's IP; chalkd sees the URL and the requesting user, never the channel. See docs/phases/PHASE-57-LINKPREVIEW.md.
func (*HTTPDeps) MountNetprobe ¶
MountNetprobe registers the pre-stream uplink probe endpoint (30-8, design Addendum D §D1). Clients time an upload here BEFORE any media flows to pick a sane starting quality tier -- because chalk media is coturn-relayed and coturn sits with chalkd, uplink-to-server is a sound proxy for the relay uplink the media actually uses. In-call re-checks are passive getStats reads client-side; this endpoint is never hit mid-call.
Route:
POST /api/netprobe → { "bytes": n, "millis": m, "bps": b } (session required)
The body is read and DISCARDED, capped at NetprobeMaxBytes (CHALK_VOICE_PROBE_BYTES) so the endpoint cannot be used to soak the server; timing is server-side so the client's request-setup overhead does not deflate the number. Answers 503 when voice or the probe is disabled (CHALK_VOICE_ENABLED / CHALK_VOICE_PROBE_ENABLED) -- clients also learn this from voice_join_ack.adaptive and simply never call.
func (*HTTPDeps) MountRegistration ¶
MountRegistration registers the auth HTTP endpoints on mux.
Routes:
POST /api/auth/register/begin → BeginRegistration
POST /api/auth/register/finish → FinishRegistration
GET /api/auth/config → public RP config for the SPA
POST /api/auth/authenticate/begin → BeginLogin
POST /api/auth/authenticate/finish → FinishLogin
POST /api/auth/logout → DeleteSession + clear cookie
GET /api/auth/me → identity from session cookie
POST /api/auth/recovery/regenerate → rotate recovery code
POST /api/invites → create invite (session)
GET /api/invites/mine → list my invites (session)
DELETE /api/invites/{token} → revoke my invite (session)
GET /api/auth/invite/{token} → peek invite (no auth)
POST /api/auth/email-change → start email change (session)
POST /api/auth/verify-email-change/{token} → finalize email change
The handlers are stateless apart from the *CeremonyCache; the service is reused across requests.
func (*HTTPDeps) MountUserLookup ¶
MountUserLookup registers GET /api/users/lookup and (59-1) the user directory. Call from the HTTP wiring in cmd/chalkd alongside the other Mount* calls. Returns nil unconditionally; the signature matches MountAdmin / MountRegistration so the wiring in internal/server/server.go can treat them uniformly.
type KDFParams ¶ added in v0.3.15
KDFParams are the client-side Argon2id parameters plus salt for one account. They are PUBLIC (a login client must fetch them before it can derive authProof); secrecy rests entirely on the password. Alg is the user_auth.kdf_alg tag (1 = argon2id).
func DecoyKDFParams ¶ added in v0.3.15
DecoyKDFParams returns deterministic decoy params for username, used by prelogin when the account does not exist or has no password enrolled.
type PendingTOTP ¶ added in v0.3.15
PendingTOTP is one issued-but-unconsumed first-factor pass. Method records which first factor was used ("password"; "passkey" in 31-3+), carried through so the TOTP step can log/branch on it if needed.
type PendingTOTPCache ¶ added in v0.3.15
type PendingTOTPCache struct {
// contains filtered or unexported fields
}
PendingTOTPCache is a goroutine-safe, TTL-bounded, one-shot cache of pending second-factor passes, keyed by an opaque random token.
func NewPendingTOTPCache ¶ added in v0.3.15
func NewPendingTOTPCache(ttl time.Duration) *PendingTOTPCache
NewPendingTOTPCache returns an empty cache. Pass zero TTL to use TOTPPendingTTL() (which itself falls back to DefaultTOTPPendingTTL).
func (*PendingTOTPCache) Issue ¶ added in v0.3.15
Issue mints a new random token for userID/method, stores it with the cache TTL, and returns the token. It opportunistically prunes expired entries so abandoned passes do not accumulate without a background janitor.
func (*PendingTOTPCache) Len ¶ added in v0.3.15
func (c *PendingTOTPCache) Len() int
Len reports the current entry count. Test-only.
func (*PendingTOTPCache) Peek ¶ added in v0.3.15
func (c *PendingTOTPCache) Peek(token string) (PendingTOTP, error)
Peek returns the entry for token WITHOUT consuming it, so a wrong second factor does not force redoing the first factor. Same errors as Take. The caller consumes the token via Take only on success; the DB-side lockout bounds guessing.
func (*PendingTOTPCache) Take ¶ added in v0.3.15
func (c *PendingTOTPCache) Take(token string) (PendingTOTP, error)
Take fetches and removes the entry for token. One-shot: a token cannot be reused. Returns ErrPendingNotFound if unknown, ErrPendingExpired if present but past its TTL (also removed).
type PendingUser ¶
type PendingUser struct {
ID uuid.UUID
Username string
DisplayName string
Email string
InviteToken []byte
// md-4: add-passkey ceremony. When IsAddPasskey is true the
// finish handler attaches the freshly minted credential to the
// EXISTING user identified by ID (the authenticated session user)
// via store.AddPasskey, and mints no new user, recovery code, or
// session. ID is the session user's ID, not a fresh UUID.
IsAddPasskey bool
}
PendingUser bundles the form fields the SPA submits at register/begin that we need to remember through to register/finish. None of these have been validated against the database yet — that happens at finish time inside the transaction (collision checks, etc).
Phase 09c: InviteToken (if non-nil) is the raw 32-byte invite token that authorized this registration. At finish-time the registration transaction marks it as used. Nil in open-registration mode.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is chalk's auth surface. Wraps go-webauthn for the ceremony primitives plus chalk-specific glue (reserved-username checks, recovery code generation, session minting in sub-step 4).
Sub-step 2 ships construction only. The HTTP-layer wiring that turns these primitives into the actual /api/auth/* endpoints arrives in sub-step 3 (registration) and 4 (authentication).
Service is safe for concurrent use; underneath, the go-webauthn *WebAuthn instance is read-only after construction.
func NewService ¶
NewService constructs an auth service from config. Validates the config and the underlying webauthn library setup; returns an error for any misconfiguration.
The returned *Service is the only handle the rest of the program should hold. It does not own a database connection; storage is passed in per-call by sub-step 3 (the application keeps the Store reference in the server layer and threads it into the auth methods).
func (*Service) BeginLogin ¶
func (s *Service) BeginLogin(user *User, opts ...webauthn.LoginOption) (*protocol.CredentialAssertion, *webauthn.SessionData, error)
BeginLogin starts a WebAuthn authentication ceremony for an existing user. Returns the credential-request options for navigator.credentials.get(), and a SessionData to persist until FinishLogin. The caller MUST populate user.Credentials with the user's existing passkeys (loaded via store.GetPasskeysForUser); without them, the library can't construct the allowCredentials list and the ceremony will not succeed.
func (*Service) BeginRegistration ¶
func (s *Service) BeginRegistration(user *User, opts ...webauthn.RegistrationOption) (*protocol.CredentialCreation, *webauthn.SessionData, error)
BeginRegistration starts a WebAuthn registration ceremony for the given user. Returns the credential-creation options the SPA must pass to navigator.credentials.create(), and a SessionData that must be persisted server-side until the ceremony's finish call.
For a brand-new user (registration via invite), the caller constructs *User with a server-generated UUID and nil Credentials. For "add another passkey" on an existing user, the caller passes the existing user's UUID + loaded credentials so the library can build excludeCredentials (refusing to re-enroll an existing authenticator on the same account).
The UV preference is "preferred"; the resident-key requirement is left at the library default (no specific requirement). These can be tuned via the options arg if a future caller needs to.
func (*Service) FinishLogin ¶
func (s *Service) FinishLogin(user *User, sess webauthn.SessionData, parsedResponse *protocol.ParsedCredentialAssertionData) (*webauthn.Credential, error)
FinishLogin completes a WebAuthn authentication ceremony. The library validates the assertion signature and the sign-count progression (clone detection). The returned Credential includes the updated sign_count, which the caller must persist via store.UpdateSignCount.
Like FinishRegistration, this accepts the parsed protocol struct rather than *http.Request to keep the auth package free of HTTP dependencies.
func (*Service) FinishRegistration ¶
func (s *Service) FinishRegistration(user *User, sess webauthn.SessionData, parsedResponse *protocol.ParsedCredentialCreationData) (*webauthn.Credential, error)
FinishRegistration completes a WebAuthn registration ceremony. The caller provides the SessionData from BeginRegistration and the parsed credential response from the SPA. Returns the credential to be persisted via store.AddPasskey.
The library validates the attestation signature, RP ID match, and challenge nonce. A successful return means the credential is good to store; the caller still has to call store.AddPasskey AND, for the registration-via-invite path, create the users row in the same transaction.
Note: the parsedResponse argument type comes from protocol.ParsedCredentialCreationData, which the application produces from the *http.Request body in the HTTP handler layer. We accept it pre-parsed so this method is decoupled from net/http (consistent with internal/auth's no-HTTP-routing scope in sub-step 2).
func (*Service) RPDisplayName ¶
RPDisplayName returns the configured display name.
type SessionUser ¶
type SessionUser struct {
UserID uuid.UUID
Username string
DisplayName string
Email string
Role string
Session store.Session // copy of the session row, without the raw token
// 80-9: ephemeral guest identity. IsGuest is true when the request was
// authorized by a chalk_guest_session cookie (ephemeral_sessions);
// GuestChannelID is then the ONE channel the guest exists for. Every
// consumer that must not serve guests checks this flag -- and the WS
// layer routes guest connections onto the restricted store.
IsGuest bool
GuestChannelID uuid.UUID
}
SessionUser is the resolved identity for a request. The auth layer returns this; downstream handlers consume it. We don't pass the raw session token through Context — too easy to leak.
func ResolveSession ¶
ResolveSession looks up the session named by the cookie on r, confirms it's unexpired, refreshes last_used_at, and returns the populated SessionUser. Returns ErrNoSession / ErrInvalidSession on the respective failure modes.
The user row is joined in so the caller doesn't have to do a second query. Most endpoints want username/display_name/role to echo back to the client; doing it in one query keeps the hot path simple.
last_used_at is refreshed BEFORE returning so even a panicking downstream handler doesn't leave a stale timestamp. The refresh is best-effort — a failure to bump the timestamp doesn't fail the request.
type SignupV2Cache ¶ added in v0.3.15
type SignupV2Cache struct {
// contains filtered or unexported fields
}
SignupV2Cache is a goroutine-safe TTL cache of pending v2 signups, keyed by an opaque random signup token. Modelled on PendingTOTPCache: no janitor goroutine; expired entries are swept opportunistically on Put.
func NewSignupV2Cache ¶ added in v0.3.15
func NewSignupV2Cache() *SignupV2Cache
NewSignupV2Cache returns an empty cache.
func (*SignupV2Cache) Peek ¶ added in v0.3.15
func (c *SignupV2Cache) Peek(token string) (pendingSignup, error)
Peek returns the entry without consuming it (finish retries on a wrong TOTP code). Expired entries are removed on lookup.
func (*SignupV2Cache) Put ¶ added in v0.3.15
func (c *SignupV2Cache) Put(p pendingSignup) (string, error)
Put stores a pending signup under a fresh random token and returns it. Returns ErrSignupCapacity when the cache is full: with open registration an anonymous caller drives insertions directly, and entries live for 15 minutes, so a cap is the only thing standing between a signup flood and the server's memory (81-4).
func (*SignupV2Cache) Take ¶ added in v0.3.15
func (c *SignupV2Cache) Take(token string)
Take consumes the entry (successful finish).
type User ¶
type User struct {
// ID is the immutable user UUID. For registration, the server
// generates this before BeginRegistration; for login, it's the
// existing users.id. The WebAuthn user handle is the UUID's
// 16-byte binary encoding.
ID uuid.UUID
// Name is the chalk username (immutable, login key). Goes on the
// wire in the credential's userHandle context.
Name string
// DisplayName is the mutable, free-form display_name. Shown to
// the user in the authenticator's UI ("Sign in to chalk as Bob").
DisplayName string
// Credentials is the user's currently-registered passkeys. Nil
// for the registration path (no credentials exist yet); non-nil
// for login and add-passkey paths.
Credentials []webauthn.Credential
}
User adapts a chalk user identity to the webauthn.User interface expected by github.com/go-webauthn/webauthn. The library uses this in BeginRegistration / BeginLogin / FinishRegistration / FinishLogin to compute the user handle on the wire and the allowCredentials / excludeCredentials lists.
Two construction modes:
Registration (no existing user row): the application has collected username + display_name from a form, generated a UUID server-side, and is about to call BeginRegistration. There are no credentials yet; Credentials is nil. The library uses ID, Name, and DisplayName to build the registration challenge.
Login or add-passkey (existing user row + stored passkeys): the application has loaded the user from store.GetUserBy* and the user's passkeys from store.GetPasskeysForUser. Credentials must reflect those passkeys so the library can compute the correct allowCredentials list for the assertion ceremony.
User is constructed by code that knows which mode it's in; this type does not enforce a particular shape. The auth service's registration and login flows construct it both ways.
func (*User) WebAuthnCredentials ¶
func (u *User) WebAuthnCredentials() []webauthn.Credential
WebAuthnCredentials returns the user's existing credentials. Empty slice (not nil — the library prefers a non-nil slice for the JSON shape) during a fresh registration.
func (*User) WebAuthnDisplayName ¶
WebAuthnDisplayName returns the user's display name. Used by the library as the credential's "displayName" field.
func (*User) WebAuthnID ¶
WebAuthnID returns the user handle as raw bytes. WebAuthn requires it to be a stable, opaque identifier (NOT username or email; those can change). We use the UUID's 16-byte representation.
Note: the WebAuthn spec recommends the user handle be a 64-byte random opaque value, but the spec ALLOWS smaller values; a UUID is the standard chalk identifier already, so we use it. If we ever want to support user handle rotation, this can become a separate field on users without breaking existing credentials.
func (*User) WebAuthnName ¶
WebAuthnName returns the username. Used by the library as the credential's "name" field.
Source Files
¶
- admin_bootstrap.go
- admin_http.go
- admin_settings_http.go
- anon_limit.go
- attachments_http.go
- avatar_frame_http.go
- cache.go
- devlogin.go
- email_change_http.go
- giphy_http.go
- http.go
- invite.go
- invites_http.go
- join_http.go
- linkpreview_http.go
- login_password_http.go
- login_totp_http.go
- migration_http.go
- netprobe_http.go
- openreg.go
- passkey_add_http.go
- password.go
- recovery.go
- reserved.go
- reset_http.go
- review.go
- security_log.go
- service.go
- sessions.go
- signup_v2_http.go
- stepup.go
- totp.go
- totp_pending.go
- user.go
- user_directory_http.go
- user_lookup_http.go