Skip to content

feat: reconcile the nest-auth keyspace and ship five security items - #95

Open
msalvatti wants to merge 108 commits into
mainfrom
feat/parity-hardening
Open

feat: reconcile the nest-auth keyspace and ship five security items#95
msalvatti wants to merge 108 commits into
mainfrom
feat/parity-hardening

Conversation

@msalvatti

@msalvatti msalvatti commented Jul 26, 2026

Copy link
Copy Markdown
Member

What this is

The rust half of a two-repo change. nest-auth and this crate can back the same deployment over
one Redis, so anything touching keys, stored record shapes, JWT claims or Lua scripts is a
contract between them — and conformance/wire-contract.json is held byte-identical in both, with
a test on each side that reads it.

Companion PR: bymaxone/nest-auth#44.

Part 1 — parity and the credential path

Family-lineage reuse detection lands (PR #71's branch, reconciled with the keyspace this
branch rewrote). revoke_family prunes the prefixed index member (rt:{hash}), not the bare
hash — the index format changed underneath it, and pruning a bare hash would have left every
revoked session listed until the index itself expired.

Three findings, each red-checked (the test was confirmed to fail without the fix):

  1. A grace pointer could resurrect a revoked lineage. Reuse detection only proves the
    replayed token's own pointer expired; a pointer planted by an earlier rotation of the same
    lineage can still be live. Recovering from it minted a session carrying the revoked family id.
    A recovery now requires its family index to still exist.
  2. The grace window was replayable — the pointer was served on every request inside the
    window, so one captured consumed token could mint a session repeatedly. Single-shot now,
    matching nest-auth.
  3. Replaying a consumed token after a revoke-all now reports Reused rather than Invalid:
    the cf: marker deliberately outlives both the pointer and the revoke-all, so a replay stays a
    theft signal. It still never mints a session.

The rotation scripts no longer decode stored records. nest-auth drives its end-to-end tier
against an in-memory Redis whose Lua VM has no cjson, so a script that decodes JSON is one the
shared contract cannot be exercised against on that side. The grace record's family and the family
owner's id are parsed by the caller instead, with a real parser.

Part 2 — the five security items

What Default
1 Origin check on cookie-authenticated writes, as a tower layer. SameSite covers this for Lax/Strict; it does not for None. on; trusted_origins required with SameSite::None
2 Breached-password refusal via PasswordBreachChecker, with a bundled HIBP implementation over the crate's existing HttpClient seam (feature breach). Fails open by contract. off — AllowAllBreachChecker
3 Per-route rate limits pinned to the shared contract. This adapter already enforced them; what was missing was the agreement — 21 numbers duplicated across two repos with nothing checking they matched. unchanged
4 Absolute session lifetime. refresh_expires_in_days bounds a token, not a session. off
5 email_verified on the OAuth profile. create_with_oauth was called with Some(true) unconditionally.

Item 2 adds no HTTP stack: the checker runs over the same seam the OAuth flows use, so a
deployment supplies the transport it already has. Only SHA-1 comes in, behind the breach
feature, and it is the corpus's index rather than a security primitive — storage is still the
configured KDF. The trait returns bool, not Result, because fail-open is the contract and not
a policy the caller gets to choose.

Item 5 has no bug today — the bundled Google provider refuses an unverified profile before
building one — but the first third-party provider written against the old contract would have
created a verified account from an address nobody proved they owned.

The rate-limit storage difference is recorded in the contract as deliberate and outside it:
nest-auth counts in Redis and shares the limit across instances, this adapter counts in process
memory and does not. Under horizontal scale the Redis one is the stricter of the two.

The mutation sweep

The gate's configuration was never being read. cargo-mutants loads .cargo/mutants.toml
and nothing else; the file sat at the repository root, where it is ignored in silence. So
examine_globs scoped nothing, bindings/, examples/ and fuzz/ were being mutated despite
the excludes, and CI had been running the same way. Moved, with the requirement written into its
header and a one-line check (cargo mutants --list must print only crates/ paths). One
follow-on: with the file finally read, additional_cargo_args supplies --all-features, and
cargo refuses the flag twice — the copy on CI's command line failed the baseline build, so it is
gone.

With the correct scope the sweep surfaced a class of test rather than a class of bug: tests that
cannot see their own subject.

Survivor Why it passed
clear_session -> () the logout test asserted no cookie carried a value — an absent Set-Cookie satisfies that too
clamp_secs / refresh_max_age_secs -> constant nothing read a cookie's Max-Age; a session cookie would log every user out when they closed the tab
platform_auth -> None every platform test recovers the service with let Some(..) else { return }, so the whole tier skipped itself
token_key, setup_key, challenge_bf_id, disable_bf_id, state_key -> a constant every one is written and read back through itself, so a colliding key round-trips perfectly with one user in play
mfa_encryption_key -> [0; 32] the MFA tests only round-trip through the same resolver, so one shared key still decrypts
the entropy / scrypt / argon2 floors each was exercised well away from its limit, never on it
assert_user_active, revoke_other_user_sessions -> Ok(()) asserted only from the admitting side — an active account, a single live session where the call is a no-op either way
refresh_ttl_secs arithmetic the in-memory store discarded the TTL, so a session that never expired looked identical to a correct one

The five key-derivation survivors are the ones worth reading twice, because each collapse is an
attack rather than a cosmetic gap: one shared MFA setup slot hands the second caller the winner's
record — their authenticator enrols against someone else's account, and they learn its TOTP secret
and recovery codes; one shared challenge or management counter lets anyone freeze any account's
MFA by failing their own attempts five times; and one shared OAuth state key means any forged
state finds the stored PKCE verifier, which is the entire CSRF protection. Each is now pinned
with two users in play.

Three mutants are genuinely equivalent and are recorded in .cargo/mutants.toml with the reason
each cannot be killed — XOR over already-masked bits, a Default that calls the body being
replaced, and an "inactive" arm the wildcard answers identically. Two more are recorded as
untestable under this gate rather than equivalent: they live behind cfg(not(feature = …))
and the sweep builds --all-features, so those lines are never compiled into the suite measuring
them. The patterns stay narrow so the killable mutants of the same functions are still generated;
where two cfg twins share a mutant name the entry is anchored to the line, and a shift makes it
reappear as a survivor rather than disappear silently.

Also in here

  • handlers.ts in packages/rust-auth had no tests at all — the one module that writes
    Set-Cookie back to a browser. Now at 100% lines, and the package runs under a coverage ratchet
    in CI (68.7% → 86.06% statements) so it can only go up.
  • One commit reverts a live cargo mutants --in-place mutation that a git add -A swept into a
    docs commit. --in-place edits the working tree; nothing may be staged while it runs.

Gates

  • cargo test --workspace --all-features green across 30 suites, 100% lines and functions
    under cargo llvm-cov --fail-under-lines 100
  • cargo fmt --check and clippy --all-targets -D warnings clean
  • The Redis end-to-end tier runs against a real redis:8 container
  • The mutation sweep ran 1 577 of 1 653 mutants locally (the tail is the container-backed
    Redis store, ~2 min per mutant here); every survivor it reported is closed — killed by a
    test or recorded with its reason. Re-running --iterate over the survivors is what caught
    four of my own fixes asserting the wrong thing, so each of those is red-checked by hand: the
    test fails with the mutation applied and passes without it. CI runs the full sweep post-merge.

After the audit

main landed the per-user token epoch (#71) while this branch was rebuilding the refresh-token
lineage on the shared keyspace, so the two touched the same 15 files. The branch carries the
later revision of that shared work — family lineage on nest-auth's fam:/cf: prefixes,
cjson-free Lua so the scripts run on any EVAL-capable backend, the resurrection guard moved to
the host where the recovered record already names its family — so those hunks keep the branch's
version, and what main added on top is ported: TOKEN_EPOCH_RETENTION_SECS with its startup
rule, and the optional epoch in the generated TypeScript.

A line-by-line audit of the two implementations against each other then found five behavioural
divergences the conformance tier could not see — it proves both sides write the same bytes, not
that both sides refuse, clean up, or report the same things. Three land here:

  • Header sanitization was three names against nest-auth's fifteen plus a suffix rule. The
    sanitized map goes to host-supplied hooks, so a host wiring one audit sink behind both backends
    received x-api-key, proxy-authorization and every forwarded-identity header from this side
    and not the other. nest-auth's regex is reproduced as a suffix test — no regex dependency —
    matching it exactly, down to declining a bare x-token.
  • Security logging was three events against roughly seventy. Lockouts, invalid credentials,
    rejected MFA codes, refresh-token reuse, a completed password reset, and every best-effort
    cleanup that failed now emit, with mask_email reproducing nest-auth's masking.
    SessionNotFound on the logout path stays silent: it is the ordinary outcome for a session
    already rotated, and logging it would bury the outage it exists to surface.
  • recordEncodings and accessTokenClaims were never asserted — the two contract sections
    that decide whether a record written by one backend is readable by the other.

Making the swallowed failures visible put their branches under the 100% line gate for the first
time, which they could not meet against a double that always succeeds — hence
InMemoryStores::fail_next_cleanup_writes, which turns "swallowed and presumed handled" into
"swallowed and asserted". The in-memory store's grace window turned out to be weaker than the
Redis one it stands in for, too: neither single-shot nor lineage-checked, in the very double the
conformance tier and nest-auth's end-to-end tier both run against.

The remaining pair (the epoch-retention bound, which was missing on both sides, plus the logout
grace pointer, the OAuth 409 and the server-only guard) lands in the companion PR.

msalvatti added 30 commits July 11, 2026 17:01
…ation

Refresh rotation used a 30s grace window but never detected the replay of
an already-consumed token: an in-grace replay forked a parallel session
and a post-grace replay was rejected as a plain invalid, so a stolen
refresh token stayed usable and theft was never surfaced (OWASP rotation
with automatic reuse detection was not implemented).

Track a refresh-token family (login lineage) minted at login and inherited
unchanged across every rotation. On rotation the store now plants a
consumed-token marker (`cf:`) that outlives the grace pointer and moves the
hash in a family index (`fam:`). Presenting a consumed token past its grace
window is therefore caught as a reuse: the store returns RotateOutcome::Reused
carrying the compromised family, and the token manager revokes the entire
family (every live descendant) before rejecting, forcing re-authentication.

The atomic-rotation + grace-window concurrency semantics are preserved: an
in-grace replay still recovers, and only a post-grace replay trips reuse.
Legacy records with no family are handled gracefully (no marker, no index,
never a reuse target).

- SessionRecord gains `family_id` (serde-default, omitted when empty)
- RotateOutcome gains `Reused(family_id)`; SessionStore gains `revoke_family`
- refresh_rotate.lua plants the consumed marker + family index and detects
  reuse; new revoke_family.lua deletes a lineage atomically
- in-memory test store mirrors the semantics for the core unit tier

Tests prove: post-grace reuse revokes the live descendant (dashboard,
platform, in-memory and Redis tiers); an in-grace concurrent rotation still
succeeds; and a legacy no-family session never trips reuse. Coverage stays
100% on every changed file; clippy, cargo-deny, and the security-invariant
gate pass.
…er-user epoch

A password reset revoked the refresh sessions but left already-issued,
stateless access JWTs valid for the remainder of their (up to 15-minute)
lifetime: the jti-blacklist used on logout can only revoke a token you
hold, and a reset does not possess the user's active access-token jtis —
there is no per-user registry of them.

Add a per-user token **epoch** (generation counter): stamped into the
Dashboard/Platform claims at issuance (and rotation), read on every
verification, and bumped on a password reset. A token stamped below the
user's current epoch was issued before the reset and is now rejected on
its next request, so a reset takes effect immediately instead of lingering
for the access-token lifetime. The refresh sessions are revoked as before.

Backward-safe: a legacy token with no epoch claim and a user with no stored
epoch both read as 0, so the mechanism is inert (0 < 0 is false) until a
first bump — no existing session is locked out. The epoch is server-internal
(never surfaced in AuthResult); the edge WASM verifier carries the claim but
does not consult it (no store), exactly like the jti-blacklist.

- DashboardClaims/PlatformClaims gain `epoch` (serde-default); TS bindings regenerated
- SessionStore gains current_epoch/bump_epoch; keys ep/pep; redis + in-memory impls
- the dashboard password-reset flow bumps the epoch after revoking sessions

Scope note: MFA-state changes and session revoke-all keep their existing
"revoke other refresh sessions, current session continues" semantics and do
not bump the epoch; the platform epoch mechanism is complete and symmetric,
awaiting a platform credential-reset flow to trigger it.

Tests prove a pre-reset access token is rejected after the bump (dashboard
and platform), that a post-bump token still verifies, that the reset flow
advances the epoch, and that a legacy no-epoch token stays valid. Coverage
stays 100% on every changed file; clippy, cargo-deny, ts-export staleness,
and the security-invariant gate pass.
Rotation minted access claims with `mfa_enabled: false` hardcoded, and the
session record had no field to carry the real value. The MFA gate refuses a
token only when `mfa_enabled && !mfa_verified`, so one routine refresh — every
~15 minutes for a normal client — produced a token that cleared every MFA-gated
route without the holder ever completing a challenge. The bypass applied to the
dashboard and platform planes alike, including the WebSocket ticket endpoint.

- add `mfaEnabled` to SessionRecord, written at issuance from the account and
  inherited unchanged by `identity_record` / `platform_identity_record` so it
  survives every rotation. Field is `serde(default)`, so sessions written before
  it existed read back as `false` instead of failing the whole record and
  logging the live user base out.
- read the flag in `rotated_claims` / `rotated_platform_claims` instead of
  hardcoding it. `mfa_verified` still resets to `false` by design: the second
  factor must be re-acquired through the challenge, only the enrollment state
  carries over.
- populate the flag on the hook/eviction projections so a consumer's
  after-session-created payload reports the account's real MFA state.

Wire parity: `mfaEnabled` is emitted unconditionally and sits last in the
record, matching the field order nest-auth already writes to the shared Redis.

Regression tests pin the invariant on both planes, plus the unenrolled mirror
(so the flag is read, never hardcoded true) and a legacy-payload read.
…gate

The proxy returned NextResponse.next() for any request it classified as a
framework background fetch — on the unauthenticated path and, via
redirectToLogin, on the blocked-status and RBAC-forbidden paths too. But the
signals that classify a request as background (RSC, Next-Router-Prefetch,
Next-Router-State-Tree, Purpose, Sec-Purpose) are plain request headers and
therefore client-forgeable. Sending `RSC: 1` was enough to walk past the
middleware's auth, account-status, and RBAC checks on any protected route and
have the page's server components execute for an unauthenticated caller.

- an unauthenticated background request now gets a bare 401 with
  `Cache-Control: no-store, no-cache`, matching nest-auth byte for byte. The
  redirect is still avoided (it would poison the client router cache), but the
  request is refused rather than admitted.
- redirectToLogin no longer short-circuits on background requests, so blocked
  and forbidden callers get their refusal whatever headers they send.
- detect Next-Router-State-Tree as a background signal, which nest-auth already
  treats as one. It carries a serialised tree, so presence is the signal.

The classifier's doc now states the result is a hint about response shape only,
never grounds to admit a request.

Tests pin each path, including the headline case: a forged RSC header on a
protected route with no session receives 401, not next(). Reverting the fix
fails exactly these tests.
The brute-force lockout identifier is an HMAC of the email, and login, register,
password reset, email verification, and platform login all derived it from the
caller's raw input. Each casing of one address therefore had its own failure
budget while resolving the same account, so rotating the spelling — user@x.com,
USER@X.COM, User@X.Com — handed an attacker an unbounded supply of attempts and
the lockout never fired. The same split let a single account own several
concurrent OTP, cooldown, and reset records.

Add a normalize_email helper (trim, then lowercase) and apply it at the engine
boundary of every flow that accepts an address, before any identifier, lookup,
or stored record is derived from it.

Full Unicode lowercasing, not ASCII-only: nest-auth canonicalizes with
JavaScript's Unicode-aware toLowerCase() and the two backends share one Redis,
so an ASCII-only fold would make a non-ASCII address canonicalize differently
per backend and split its keyspace. The invitation flow, which already
normalized inline with to_ascii_lowercase, now routes through the same helper
so that divergence cannot reappear.

Password reset normalizes on both the initiate and confirm legs: the confirm
step compares the supplied address against the one stored in the reset context,
so canonicalizing only one side would break every reset.

Tests spend the whole lockout budget across five different casings and assert
the next attempt is already locked, and pin that an account still authenticates
when the caller types it in a different case.
The two backends HMAC the same Redis identifiers with a key each derives from
the JWT secret, but they derived it differently, and either difference alone was
enough to make the keys disagree:

- this side hashed `label || secret` with no separator, leaving the preimage
  ambiguous, while nest-auth hashes `label + ":" + secret`.
- this side keyed the HMAC with the raw 32-byte digest, while nest-auth keys it
  with the 64-character hex TEXT of that digest.

The result was that every keyed identifier landed in a different Redis slot per
backend: brute-force lockout, OTP, resend cooldown, MFA setup, and the anti-replay
record. On a shared Redis a lockout accrued through one backend was invisible to
the other, so an attacker could halve the effective attempt budget by alternating
which backend they hit.

Adopt nest-auth's derivation verbatim. It is the published one (npm v1.0.11), so
changing it there instead would have briefly cleared every in-flight lockout on
live deployments — a worse trade for no cryptographic gain, since a hex-text key
and a raw-byte key are equally sound. The separator is kept because the domain
separation it provides is real.

The key is written straight into a fixed-size buffer, so no heap copy of the key
material outlives the derivation; the secret buffer and the intermediate digest
are both zeroized.

Both repos now carry the same known-answer vectors — a fixed secret, its derived
key, and one identifier — so a drift on either side turns exactly one suite red
instead of surfacing later as sessions and lockouts that silently miss each other.
The MFA temp token outlives the login-time status gate by its whole TTL, so an
account blocked in that window could still clear the second factor and receive a
full session. Revoking access must not depend on how far through the login the
holder already was.

Re-check the status once the account is loaded, before the code is verified, on
both the dashboard and platform challenge paths. Ordering matters twice: a
blocked account must be refused whatever it submits, and the recovery-code path
costs one key derivation per stored code, so gating first also denies a revoked
account that work.

Extract the status gate into a shared status_gate module. There were already two
copies of the status-to-error mapping (dashboard login and platform login) and
this would have been a third; one implementation means the three planes cannot
drift into different notions of "blocked". MfaService now carries the configured
blocked statuses, wired from the resolved config by the builder.
Four Redis-contract divergences, one of which was a security bug rather than a
parity gap.

Session-index members were the bare token hash; nest-auth stores full key
suffixes (`rt:{hash}`, `prt:{hash}`) and also indexes the rotation grace
pointers (`rp:`/`prp:`). A bare hash cannot say which keyspace it belongs to, so
revoke_all was structurally unable to delete grace pointers: a refresh token
that had just been rotated away survived a logout-all for its entire grace
window and kept recovering sessions from it. Members now carry their own
prefix, the Lua deletes `{ns}:{member}` directly, and list_sessions filters to
the live prefix and strips it before building the detail key. The separate
`psess:`/`psd:` platform keyspace stays — only the member format converged.

`sd:`/`psd:` timestamps were RFC 3339 strings; nest-auth writes Unix
milliseconds and its listing rejects any record whose timestamps are not
numbers — then SREMs the member. So the divergence was not merely unreadable,
it was destructive: nest-auth evicted sessions this backend had written. Added
a `unix_millis` serde adapter for those two fields. `SessionRecord.created_at`
deliberately keeps RFC 3339, which is what nest-auth writes there.

Password-reset prefixes `pr:`/`prv:` renamed to `pw_reset:`/`pw_vtok:`, so a
reset link emailed by one backend resolves against the other.

The stored invitation gained `createdAt`, which nest-auth writes and validates.
Consumption is a single-use GETDEL, so nest-auth read an invitation written
here, failed validation on the missing field, and the token was already gone —
the invitation was destroyed instead of accepted. Encoding verified against
nest-auth rather than assumed: it writes an ISO string there, not the epoch
milliseconds the session detail uses.

The spec already described the prefixed-member format at §12.5; the
implementation had drifted from its own specification, not only from nest-auth.
…ts legacy tokens

Two cross-backend credential formats that did not line up.

The TOTP secret was encrypted as raw bytes; nest-auth encrypts the Base32 text.
Both backends read the same `mfaSecret` column and the same `mfa_setup:` record,
so decrypting a nest-written secret here handed Base32 ASCII to HMAC-SHA-1 as
the key and rejected every code the user's authenticator produced — and the
reverse broke the same way. Encrypting the presentation form is marginally
redundant, but the published side already stores it that way and re-encrypting
live MFA credentials to save twelve bytes is not a trade worth making. A
`decrypt_secret` helper now owns the decrypt-then-decode step so no call site
can reintroduce the mismatch, and every failure still collapses to one opaque
error rather than a format oracle.

The refresh-token shape guard accepted only the 256-bit hex form. nest-auth
minted UUID v4 before both sides converged, and those tokens live in the shared
Redis for a full refresh lifetime — seven days by default — so refusing the
shape refused to rotate sessions that were still valid with their `rt:{sha256}`
record right there. The legacy shape is accepted alongside the current one; it
grants nothing by itself, since the token still has to hash to a stored session.
Tests pin that the allowance is one exact shape and not "anything with dashes".
Everything this branch converged — key prefixes, index member shapes, record
encodings, credential formats, the derived identifier key — is a contract
between two implementations that can back the same deployment over one Redis.
Nothing enforced it, which is how the divergences reached this point: each side
was internally consistent and green.

Add `conformance/wire-contract.json`, held byte-identical in both repos, and
assert this implementation against it. The prefix catalog is checked against the
`Prefix` enum, and the identifier-key known-answer vectors now come from the
contract instead of being repeated in the test, so there is one copy of the
truth rather than two that drift apart quietly.

The contract records the parts that are easy to get wrong from either side: the
two identity planes must never share an index prefix; the timestamp encoding is
deliberately NOT uniform (the session detail is epoch milliseconds because the
reader guards on a numeric type and evicts a member whose detail fails to parse,
while everything else is an ISO string); `mfaEnabled` must ride on the refresh
session or a rotation silently disables the second factor; and the invitation
needs `createdAt` because a single-use GETDEL destroys a record the reader
rejects.

Changing a value there is a breaking change to the shared keyspace and has to
land in both repos together.
Seven response-shape divergences from the published sibling, whose client
contract is already fixed. Two of them were more than cosmetic.

- logout accepted the refresh token only from a cookie. In a bearer deployment
  there is no cookie, so the refresh session survived logout entirely — the
  access token was blacklisted while the credential that mints new ones stayed
  live. It now reads a body `refreshToken` as nest-auth does, cookie as fallback.
- POST /auth/mfa/challenge required the temp token in the body with no cookie
  fallback, while this crate's own OAuth callback plants that token as an
  HttpOnly cookie. The browser OAuth+MFA flow was therefore a dead end: the SPA
  cannot read the cookie and the body was empty. The field is now optional with
  the cookie behind it, a request carrying neither fails with the MFA temp-token
  error rather than a generic validation 400, and the cookie is cleared on the
  same policy nest-auth uses.

The rest are shapes a shared client would break on: GET /auth/me and
/auth/platform/me return the safe account as the top-level body instead of
wrapping it in `{ user }`; GET /auth/sessions returns the bare array instead of
`{ sessions }`; the platform auth body names the account `admin` and is
unconditionally bearer; both refresh endpoints echo the account alongside the
tokens; and both MFA setup routes answer 201.

The platform field name and the always-bearer delivery were already what this
crate's own specification called for at §7.11.1 — the implementation had drifted
from its spec, not only from nest-auth.

Also fixes the namespaced-key catalog test, which enumerates every allowed
prefix and so still listed the pre-rename `pr:`/`prv:` reset keys. It only
surfaced once a Docker daemon was available to run the Redis integration tier.
Two round-trip tests unwrapped `serde_json::from_str` with `?` on a multi-line
call, which puts the operator's error arm on a line of its own. The literal being
parsed always succeeds, so that arm is unreachable and the CI gate — which fails
under 100% line coverage — tripped on it. The gate only surfaced this once the
Docker-backed Redis tier was actually executing, since before that the run
aborted earlier.

Assert on the `Result` with `matches!` instead, which is the idiom the rest of
this codebase already uses for exactly this reason and keeps the same
assertions. Line coverage is back to 100.00% (16971/16971) with functions at
100%; `cargo llvm-cov --fail-under-lines 100` exits clean.
…eyspace

Brings PR #71 (fix/refresh-reuse-detection) into the parity work and reconciles
it with the keyspace this branch rewrote:

- revoke_family prunes the PREFIXED session-index member (`rt:{hash}` /
  `prt:{hash}`), not the bare hash. The index format changed under the branch;
  pruning a bare hash would leave every revoked session listed until the index
  itself expired.
- The e2e catalog keeps `pw_reset:`/`pw_vtok:` (the branch still carried the old
  `pr:`/`prv:`) and gains `cf`/`fam`/`pcf`/`pfam`/`ep`/`pep`.
- SessionRecord carries both `mfaEnabled` (this branch) and `familyId` (the
  merged branch); both are omitted-or-defaulted for legacy records.

Replaying a consumed token after a revoke-all is now reported as Reused rather
than Invalid: the `cf:` marker deliberately outlives both the grace pointer and
the revoke-all, so a replayed consumed token stays a theft signal even after the
user logged everything out. It still never mints a session.
Reuse detection deletes the family's live sessions, but a grace pointer planted
by an EARLIER rotation of the same lineage can still be inside its window when
the reuse fires: detection only proves the REPLAYED token's own pointer expired,
which says nothing about a younger sibling's. Recovering from that pointer minted
a fresh session carrying the revoked family id and handed the thief back the
lineage the revocation had just killed.

The rotation script now decodes the recovered record and refuses the recovery
when its family index is gone, so a recovery is valid only while its lineage is
alive. A legacy record with no family recovers as before. The e2e test builds the
three-token lineage and fails without the guard (verified by reverting it).

Also closes the two uncovered lines the merge left in the failing-revoke test
double: llvm-cov is back to 100% lines and 100% functions.
… the grace window

Three changes that converge the rotation semantics with nest-auth:

- The scripts no longer decode a stored record. The grace record's family and
  the family owner's id are parsed by the caller instead, with a real parser.
  nest-auth drives its end-to-end tier against an in-memory Redis whose Lua VM
  has no `cjson`, so a script that decodes JSON is one the shared contract
  cannot be exercised against on that side.
- The grace window is now single-shot: the pointer is consumed on use. It used
  to be served on every request inside the window, so one captured consumed
  token could mint a fresh session over and over for the whole window. nest-auth
  already consumed it; this closes the divergence in the stricter direction.
- The family-alive check on a grace recovery moves from the script into the
  store, where it reads the same. The revocation is monotonic, so checking it
  next to the recovery is no weaker than checking it inside the script — the
  session is created after the script returns either way.
Mirror of the nest-auth change: the shared contract gains the six new prefixes,
the bare-hash family member shape, `familyId` on the session record, the `epoch`
claim, and the rotation semantics both sides implement. The catalog test now
asserts every prefix in the enum rather than a subset, so adding a keyspace on
one side without the other turns this side red.

Spec sections 7.3.3 / 12.4 / 12.5 are brought in line with the code: the
rotation flow as it now runs (single atomic script, single-shot grace, reuse
detection, family revocation), the new catalog rows, and the renumbered Lua
subsections.
The three route handlers that bridge the browser's cookie session to the
backend had no tests at all — 0% of `handlers.ts`, in the one module of this
package that writes `Set-Cookie` back to a browser. Nine tests pin the contract
that matters there: the rotated cookies are relayed verbatim, a failed refresh
clears the session rather than leaving the browser holding cookies the backend
no longer honors, a backend that is down fails the same way as a rejected
refresh, and an attacker-supplied `redirectTo` cannot become the `Location`.

The package now runs under a coverage ratchet — thresholds pinned just under
what the suite reaches (86/78/90/88), so this layer can only go up. It is
deliberately not 100%: the Rust crates are, this layer is the laggard, and a
threshold that lies about where it is would be worse than one that admits it.
CI runs `test:cov` instead of `test`.

Coverage on the package: 68.7% -> 86.06% statements, and `handlers.ts` from
0% to 100% lines.
The parity half of the nest-auth change. `SameSite=None` is the one posture
where the browser attaches the session cookie to a cross-site request, and it is
the one this adapter had no second line of defense for.

A tower layer, innermost so it sees the request exactly as the handler would,
decides on headers a page cannot forge: safe methods pass, a request carrying no
auth cookie passes (a bearer client has no ambient credential to spend),
`Sec-Fetch-Site: same-origin`/`none` passes, and an `Origin` must appear in
`cookies.trusted_origins`. Neither header at all is a non-browser caller and
passes — a page cannot make a browser omit `Origin` cross-site, so the absence is
evidence, not evasion. The request's own origin is never rebuilt from `Host`.

Config validation refuses either half without the other, and refuses an entry
that is not a bare absolute origin: a trailing slash, a path, a naked hostname or
embedded userinfo can never equal an `Origin` header, so the origin the operator
meant to allow would be silently blocked instead. The origin shape is checked
with the crate's existing hand-rolled URL helpers rather than pulling in `url` —
the dependency budget is a feature here.

New `AuthError::UntrustedOrigin` / `auth.untrusted_origin`, 403, byte-identical
to the nest-auth code.
The parity half of the nest-auth change: `PasswordBreachChecker` is consulted at
the three places a password is set — register, reset, invitation acceptance — and
never at login, where refusing a breached password someone already has would lock
them out of the account they need to get into to change it.

A seam, not a dependency. The default `AllowAllBreachChecker` approves everything
and touches no network, so a crate upgrade never starts contacting a third party.
The bundled `HibpBreachChecker` (feature `breach`) runs over the crate's existing
`HttpClient` seam, so enabling the check pulls in no HTTP stack of its own — the
deployment supplies the transport it already has. Only SHA-1 is added, behind the
same feature, and it is the corpus's index rather than a security primitive:
storage is still the configured KDF.

The trait returns `bool`, not `Result`, because fail-open is the contract and not
a policy the caller gets to choose: a corpus that is down, rate-limiting or
answering garbage must approve the password. There is no error the engine would
be right to act on.

Also covers three lines the origin-check work left uncovered: a legacy record
still recovers through its grace window (there is no family to check), and the
family-owner walk skips a member whose record is gone, unreadable, or names no
owner at all — an empty owner would build an index key every ownerless family
would share.

New `AuthError::PasswordCompromised` / `auth.password_compromised` (400),
byte-identical to nest-auth. Coverage back to 100% lines and functions.
This adapter already enforces its limits — a governor layer per route, not a
recommendation — so there was nothing to add. What was missing is the agreement:
21 numbers duplicated across two repos with nothing checking they matched.

The contract now carries the table and both sides assert against it, so a limit
changed on one side turns that side red rather than surfacing as the same client
being throttled at different points depending on which backend answered.

The storage difference is written down as deliberate and outside the contract:
nest-auth counts in Redis and therefore shares the limit across instances, this
adapter counts in process memory and therefore does not. Under horizontal scale
the Redis one is the stricter of the two.
The parity half of the nest-auth change. `refresh_expires_in_days` bounds a
single refresh token, not a session: a client rotating every fifteen minutes
renews that lifetime indefinitely, so a session established once never has to be
established again.

`family_created_at` is stamped at login and carried unchanged through every
rotation — deliberately not `created_at`, which is this session's own and resets
each time; measuring from that would make the cap unreachable while looking like
it worked. The rotation is refused once `jwt.absolute_session_lifetime_days` has
passed, before the script runs, so nothing is consumed on the holder's behalf,
and refused as a plain invalid refresh: the remedy is the same as any other, and
a distinct code would only tell whoever holds the token how old the session is.

Off by default, matching nest-auth: switching it on ends sessions already older
than the cap, which is a deployment's decision rather than an upgrade's. A record
written before the field carries no birth time and is not capped.

The serde adapter is `Option`-aware so a legacy record round-trips as `None`
instead of failing the whole record — but a present-and-malformed value is still
an error, because a birth time that cannot be read is a cap that cannot be
judged, and dropping it quietly would uncap the session.
… profile

`create_with_oauth` was called with `email_verified: Some(true)` unconditionally,
and `OAuthProfile` had no field for a provider to say otherwise. No bug today —
the only bundled provider is Google's, which refuses an unverified profile before
building one — but the first third-party provider written against that contract
would have created a verified account from an address nobody proved they owned.

That account belongs to whoever controls the OAuth account, not to whoever
controls the mailbox, and marking it verified makes the consumer's "this email is
proven" invariant false from the first login — which is how an account is taken
over by registering with someone else's address at a provider that does not
check.

The profile now carries `email_verified` and the engine passes it through.
Google's provider reports `true` unconditionally, which is honest precisely
because its own guard already refused everything else. `MockOAuthProvider` gains
an `unverified` constructor so the path can be driven end to end — the bundled
provider structurally cannot produce it.

Parity with the nest-auth change; the field cannot be defaulted to `true` without
reintroducing exactly the assumption this removes.
Reuse detection, the token epoch, the absolute session lifetime, the cross-site
check, the breach checker and the contract-pinned rate limits — all of which have
a nest-auth counterpart, which is the point.
The previous commit swept in a live `cargo mutants --in-place` mutation: the
token source had been replaced with `None`, which would have made every
cookie-and-bearer read return nothing. Restores the real match.

Lesson recorded in the run itself — `--in-place` mutates the working tree, so
nothing may be staged while it runs.
Six survivors from `cargo mutants`, each a real gap rather than an equivalent:

- `clear_session` could be replaced by a no-op: the logout test asserted no cookie
  carried a value, which an absent `Set-Cookie` satisfies just as well. It now asserts
  each cookie is expired back on the Path it was set with — a clearing header on the
  wrong path leaves a ghost cookie the browser keeps sending.
- `clamp_secs` and `refresh_max_age_secs` could return any constant: no test read a
  cookie's Max-Age. A session cookie instead would log every user out when they closed
  the tab.
- The refresh-name comparison in `carries_auth_cookie` could be inverted unnoticed:
  every cross-site test carried the access cookie, so the second clause was never
  decisive. Covered now from both sides — the refresh cookie alone is a credential, the
  session-signal cookie alone is not.
- `forgot_password` and `resend_otp` could be replaced by an empty 200: the anti-
  enumeration test read only the status, and the two-step flow *skipped* itself when no
  OTP was minted. The uniform body is asserted, and a missing OTP now fails.

`DEFAULT_MAX_BODY_BYTES` was asserted against itself, which accepts whatever the
expression produces; it is pinned to the literal.
…uivalents

The v4 layout test drew a single UUID, so a broken mask left the version and variant
nibbles correct often enough to pass by luck — two of the four bit-twiddling mutants
survived on a lucky draw. It draws 64 now, which makes the assertion deterministic.

`AuthEngine::platform_auth` could return `None` unnoticed: every platform test recovers
the service with `let Some(..) else { return }`, so the whole tier skipped itself instead
of failing. It is asserted from an engine built the same way the disabled-domain test
builds one, where nothing can skip.

Three mutants are genuinely equivalent and are recorded in `mutants.toml` with the reason
each cannot be killed — the XOR/OR pair on already-masked bits, the builder whose
`Default` calls the body being replaced, and the `"inactive"` arm the wildcard already
answers identically. The patterns stay narrow so the killable mutants of the same
functions are still generated.
The fake answered `Ok(())` and the test asserted only that — so a repository that
stored nothing would have let every platform test built on it pass while asserting
nothing. Each update is now read back through `find_by_id`.
`token_key` could be replaced by a constant without failing anything: every test stored
and consumed one token at a time, so a colliding key round-trips perfectly. Two live
tokens are now asserted not to collide.

The fake's `remaining_lockout_secs` guarded on a counter being positive, which it always
is — `record_failure` inserts and increments under one lock and `reset` removes the entry
— so the entry's existence was already the whole condition.
The enrolment gate is built on exactly those two operations — the first writer wins the
setup slot, the completion reads it away so only one caller can finish — and neither was
asserted against the double. A double that swallowed the value or always reported
"already there" would make that gate untestable while every test stayed green.
The secret-entropy rule was only exercised well away from its floor, so tightening the
comparison to reject a secret *at* 3.5 bits/char would have gone unnoticed — the boundary
secret is built to land on the constant exactly, with no rounding.

`mfa_encryption_key` could return a fixed or zeroed key without failing anything: the MFA
tests only ever round-trip through the same resolver, so every deployment's TOTP secrets
sealed under one shared key would still decrypt. It is asserted byte for byte, and absent
when no MFA is configured.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 106 out of 107 changed files in this pull request and generated no new comments.

Files not reviewed (1)
  • packages/rust-auth/package-lock.json: Generated file
Comments suppressed due to low confidence (2)

crates/bymax-auth-axum/src/routes/mod.rs:114

  • The sensitive_header_names doc says the redaction set “always matches what sanitize_headers strips”, but sanitize_headers now uses is_sensitive_header (which includes the x-...-(token|secret|...) suffix rule). As written, this comment is no longer accurate and may mislead readers about what gets redacted vs only withheld from hook context.
/// The sensitive headers as typed [`HeaderName`]s, for the `SetSensitiveRequestHeadersLayer`
/// that masks them in `tracing` spans/events. Derived from [`SENSITIVE_HEADERS`] so the
/// redaction set always matches what [`sanitize_headers`] strips. Any entry that is not a
/// valid header name is skipped (the const holds only valid lowercase names).

crates/bymax-auth-axum/src/trusted_origin.rs:55

  • enforce_trusted_origin clones the full ResolvedCookies (including trusted_origins) on every non-safe request. This adds avoidable per-request allocations/copies; you can borrow the cookies config instead.
    let cookies = state.config().cookies.clone();
    if !carries_auth_cookie(&request, &cookies.access_name, &cookies.refresh_name) {
        return next.run(request).await;
    }

The resolver is documented as authoritative over the body's `tenant_id` when
configured — that is the whole anti-spoofing promise. Only `login` and
`register` called it. `initiate_reset`, `reset_password`, `verify_reset_otp`,
`resend_reset_otp`, `verify_email` and `resend_verification_email` passed the
caller's value straight into the account lookup and the OTP identifier.

On a deployment that derives the tenant from the request — the documented use
case — an unauthenticated caller on one tenant can drive reset and verification
mail at accounts in a tenant they have no relationship with: a mail-bombing
vector and cross-tenant enumeration. It is also a functional break in the other
direction: a reset started under the resolved tenant could never be completed,
because the initiate step wrote its record under one tenant and the confirm step
derived its identifier from another. Completion itself was never at risk — the
stored reset context re-binds the tenant — so this is not account takeover.

**Breaking.** Those six methods now take `&RequestContext` as their final
argument, matching what `login` and `register` already take. The axum routes
supply it through the existing `RequestMeta` extractor, which the reset routes
were not using at all. The library is not published to production yet, which is
the cheap moment for this.

The new test is indirect but exact: the harness resolver refuses when no `host`
header is present, so a flow that consults it fails with `Forbidden` on an empty
context and a flow that ignores it does not. All six used to pass silently.

`nest-auth` takes the same change as the Express request.

Coverage stays at 100% lines and 100% functions.
Copilot AI review requested due to automatic review settings July 29, 2026 19:35

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 107 out of 108 changed files in this pull request and generated no new comments.

Files not reviewed (1)
  • packages/rust-auth/package-lock.json: Generated file
Comments suppressed due to low confidence (1)

packages/rust-auth/src/shared/error-codes.ts:8

  • AuthErrorCode now includes auth.password_compromised and auth.untrusted_origin, but the generated AUTH_ERROR_CODES const below does not export corresponding PASSWORD_COMPROMISED / UNTRUSTED_ORIGIN keys. This makes the file internally inconsistent and breaks consumers that rely on AUTH_ERROR_CODES.* rather than hard-coded strings. Regenerate this file (or otherwise ensure AUTH_ERROR_CODES includes the new entries) so both the type and constant stay in sync.

`POST /auth/logout` sat behind the `AuthUser` extractor. The common case — a
user comes back after their access token expired and signs out — therefore
answered 401, the engine never ran, and the refresh session stayed live for its
full lifetime on a device the user had just told the system to sign out. The
long-lived credential is exactly the one logout exists to kill, and it was the
one that survived.

The refresh token authorizes the operation now, and `AuthEngine::logout` reads
the session's owner from the stored record rather than taking it from the
caller: the route accepts an absent or forged access token, so a caller-supplied
id would let a revocation be aimed at someone else's session.

The access token is still verified — signature and pinned algorithm, retired
keys included — before its `jti` is blacklisted; only the expiry check is
waived, via a new `verify_access_ignoring_expiry`. The blacklist and epoch
checks are skipped with it: an already-revoked token is precisely the one whose
owner is trying to finish signing out. Reading the token unverified would have
been simpler and worse, since `jti` decides which token gets blacklisted.

**Breaking.** `logout` drops its `user_id` parameter. `nest-auth` takes the same
change.

Coverage stays at 100% lines and 100% functions.
Copilot AI review requested due to automatic review settings July 29, 2026 20:47

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 107 out of 108 changed files in this pull request and generated no new comments.

Files not reviewed (1)
  • packages/rust-auth/package-lock.json: Generated file
Comments suppressed due to low confidence (2)

packages/rust-auth/src/shared/error-codes.ts:8

  • AuthErrorCode union includes auth.password_compromised and auth.untrusted_origin, but AUTH_ERROR_CODES does not define corresponding keys. Any consumer using AUTH_ERROR_CODES.PASSWORD_COMPROMISED / .UNTRUSTED_ORIGIN will fail at compile time, and the file is internally inconsistent.

Regenerate this ts-rs output (preferred) or add the missing entries to AUTH_ERROR_CODES so the constant matches the union/wire contract.
crates/bymax-auth-redis/src/lua/refresh_rotate.lua:82

  • If the grace pointer value does not contain the expected successorHash:json separator (e.g. a legacy rp: value from a rolling deploy, or corruption), this branch deletes the pointer and then falls through to the consumed-family marker check, which will report REUSED: and trigger family revocation for what may have been a legitimate in-grace retry.

Consider treating a no-separator grace value as a legacy pointer and returning GRACE: (or otherwise short-circuiting) so the presence of KEYS[3] can never be reclassified as reuse.

`mfa_setup` was guarded by the access token alone. Enabling MFA changes how the
account authenticates, and a token is not proof of who is asking: one lifted by
XSS or from a shared machine could enrol an authenticator the attacker holds.
The enable then revokes every session and bumps the token epoch — so the real
owner is locked out of an account they still know the password to, and the
recovery codes were displayed only to the attacker. ASVS requires
re-authentication before an authentication factor changes; `disable` already
honoured that by demanding a TOTP code.

`setup` is gated rather than `verify_and_enable`, so the attacker cannot even
obtain a secret they control. An account provisioned purely through OAuth has no
local password and is exempt. A missing password still pays the KDF, so "no
password sent" and "wrong password" take the same time.

**Breaking.** `MfaService::setup` and `AuthEngine::mfa_setup` take
`Option<&str>` for the password; both setup routes accept a `password` body
field, optional on the wire because the engine is what knows whether this
account has one.

Found while chasing a coverage gap this change exposed: **the platform
recovery-code challenge never gated on winning the temp-token consume**, which
the dashboard path was fixed to do earlier. The two planes carry that logic
separately and only one had been closed — so one recovery code could still mint
two platform sessions. Gated here, with the test that reaches it.

Also flushed out by the same gap: several MFA tests seeded accounts with an
unparseable `"$scrypt$x"` hash, so enrolment refused and their `else { return }`
swallowed it — they passed while exercising nothing. They now seed a real hash
(platform admins) or no password at all (the OAuth-shaped unit tests), which is
what put the 34 lines those tests were supposed to cover back under test.

Coverage stays at 100% lines and 100% functions.
Copilot AI review requested due to automatic review settings July 29, 2026 21:23

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 107 out of 108 changed files in this pull request and generated 1 comment.

Files not reviewed (1)
  • packages/rust-auth/package-lock.json: Generated file
Comments suppressed due to low confidence (3)

scripts/check-invariants.sh:112

  • This comment says “Comment lines are stripped first”, but the filter only excludes //-style line comments. Matches inside /* ... */ block comments will still trip the invariant and can still “punish documentation”, contrary to what the comment claims.

Either broaden the filter to strip block-comment lines too, or adjust the wording to be precise about only stripping // comments.
crates/bymax-auth-axum/src/middleware.rs:7

  • The module-level layer-order doc doesn’t mention the new trusted-origin enforcement middleware that’s now applied to the router. Since this file explicitly documents the ordered stack, the omission makes the comment inaccurate and can mislead someone trying to reason about auth/CSRF behavior and where it runs relative to CORS/cookies/body limits.
//! Layers, outermost first: structured tracing spans, an optional consumer-supplied CORS
//! layer, the `Cache-Control: no-store` response stamp (RFC 6749 §5.1 — no auth response is
//! ever cacheable), sensitive-header redaction (so the credential-bearing headers never
//! reach trace output), a request-body size cap, and the cookie manager that makes the typed
//! `CookieJar` available to extractors and the delivery layer. Rate-limit layers are

.cargo/mutants.toml:118

  • .cargo/mutants.toml is still excluding mutants for is_legacy and decode_hex, but those symbols no longer exist anywhere in crates/ (so these exclusions are now dead config). Keeping stale exclusions around is risky because if similarly-named code returns later, it may get excluded without re-triage.

Remove these two exclude_re entries (and ideally the now-obsolete rationale comments above them).

    'replace \| with \^ in hotp',
    'replace is_legacy -> bool with false',
    'replace \| with \^ in decode_hex',

Comment on lines +105 to +112
/// ```
/// use bymax_auth_crypto::mac::sha1;
///
/// // Known-answer vector: SHA-1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d.
/// let digest = sha1(b"abc");
/// assert_eq!(digest[0], 0xa9);
/// assert_eq!(digest[19], 0x9d);
/// ```
…he flow

The `state` nonce was validated against the store alone, which proves only that
somebody started a flow — not that this browser did. An attacker could run
their own authorization, complete consent at the provider, capture the
resulting `?code=...&state=...` callback URL without visiting it, and lure the
victim there: the victim's browser then received the attacker's session, and
everything they did next landed in the attacker's account. PKCE does not cover
this, because the verifier is held server-side and replayed for whoever
presents the state.

`oauth_initiate` now returns `OAuthRedirect { authorize_url, state }` and the
Axum adapter plants the raw state as an HttpOnly `oauth_state` cookie; the
callback refuses any request that does not carry it back, as RFC 6749 section
10.12 requires. Two details are load-bearing:

- `SameSite` is `Lax`, not the value the refresh cookie uses. The provider's
  callback is a cross-site top-level GET, and `Strict` would withhold the
  cookie on exactly that hop, breaking every OAuth login on a deployment that
  hardened the setting everywhere else.
- The check runs before `take_state`, so a lured victim cannot burn a state the
  legitimate browser is still entitled to spend.

BREAKING CHANGE: `AuthEngine::oauth_initiate` returns `OAuthRedirect` instead
of `String`, and `AuthEngine::oauth_callback` takes the state cookie as its
fourth argument.
Copilot AI review requested due to automatic review settings July 29, 2026 21:53

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 109 out of 110 changed files in this pull request and generated no new comments.

Files not reviewed (1)
  • packages/rust-auth/package-lock.json: Generated file
Comments suppressed due to low confidence (1)

crates/bymax-auth-axum/src/routes/mod.rs:115

  • sanitize_headers() strips both the fixed SENSITIVE_HEADERS list and the suffix-based x-...-token/secret/... rule via is_sensitive_header(), but sensitive_header_names() only returns the fixed list. The doc comment currently claims the tracing redaction set “always matches what sanitize_headers strips”, which is no longer true and could mislead someone into logging request headers assuming suffix-matched secrets are redacted.
/// The sensitive headers as typed [`HeaderName`]s, for the `SetSensitiveRequestHeadersLayer`
/// that masks them in `tracing` spans/events. Derived from [`SENSITIVE_HEADERS`] so the
/// redaction set always matches what [`sanitize_headers`] strips. Any entry that is not a
/// valid header name is skipped (the const holds only valid lowercase names).
pub(crate) fn sensitive_header_names() -> Vec<HeaderName> {

The field was configurable and never read: a deployment that set it got
host-only cookies anyway, with nothing to say so. The adapter now asks the
resolver per request — handing it the request host with the port stripped,
since it names a domain and not an origin — and stamps the answer on all three
session cookies and on the logout clear, which must mirror the plant or the
browser keeps the cookie it was asked to delete.

Only the first domain is used. A browser rejects a `Set-Cookie` whose `Domain`
is not a suffix of the host that sent the response (RFC 6265 section 5.3.6), so
a second one on the same response is either the same scope written twice or a
value that gets dropped on the floor. The resolver is handed the host precisely
so it can answer with the scope that applies to it.

Unset — the default — still means no `Domain` attribute at all, which is what a
session cookie should be: `Domain=app.example.com` is sent to every subdomain of
that name, so a session scoped that way is readable by a marketing site, a
user-content host, or a stale DNS record someone else now answers for.
…ling

RFC 6749 section 4.1.2.1 defines a callback carrying `error` and no `code` —
the response a provider sends when the user declines consent.
`OAuthCallbackQuery` required `code`, so a user who simply clicked "Cancel" got
a validation envelope rather than the configured error redirect.

`code` is now optional, and the handler refuses a callback carrying neither it
nor `error` on the same path. The provider's value is logged and never echoed
back: it is provider-chosen text that would otherwise land in a URL the browser
follows, and `oauth_failed` already says everything the library is willing to
vouch for.

The refusal and the failed-exchange path now share one helper, so the status,
the code and the destination cannot drift apart. That exposed a branch no test
covered: an infrastructure failure must NOT become an error redirect — a store
that is down is not a refusal, and dressing it up as `?error=oauth_failed` would
tell the user to retry while hiding an outage from whatever watches 5xx. There
is now a harness for it.
Copilot AI review requested due to automatic review settings July 29, 2026 22:51

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review this pull request because it exceeds the maximum number of lines (20,000). Try reducing the number of changed lines and requesting a review from Copilot again.

The request side was already redacted from traces; the response side is where
the credential travels outward. Every successful login, refresh and OAuth
callback answers with `Set-Cookie: access_token=<a signed JWT>`, so a
deployment whose tracing records response headers — a reasonable thing to
switch on while debugging — was writing live session tokens into its logs,
where they outlive the session and are read by people it was never issued to.

Marking the header sensitive costs nothing and makes that mistake unavailable.
Copilot AI review requested due to automatic review settings July 29, 2026 23:01

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review this pull request because it exceeds the maximum number of lines (20,000). Try reducing the number of changed lines and requesting a review from Copilot again.

`initiate_reset` now claims the same cooldown `resend_reset_otp` does, under
the same key. The throttle on one door was decorative while the other was
free — and worse, every issuance rewrites the OTP record with `attempts: 0`,
so an untimed initiate turned the 5-attempt ceiling into 5 attempts per call.
An attacker who knew an address could loop "initiate, guess five times" at a
six-digit code indefinitely, mailing the victim once per lap.

The absolute session-lifetime cap is enforced on the grace-recovery path, on
both planes. The check ran against the seed, and there the seed is the
placeholder used when the live key is already gone: its `family_created_at` is
`None`, so the check returned early and applied nothing. A lineage that had
just passed its cap could still mint a fresh access token and a full-length
refresh session through its grace window — the cap ended normal rotation and
left the one remaining door open.

`GET /auth/me` is pinned in the wire contract and the TypeScript client reads
the bare user object the route actually returns. It was still unwrapping a
`{ user }` envelope, so `getMe()` resolved to `undefined` while every other
signal said authenticated. The test that should have caught it mocked the old
envelope; the contract had no `me` entry, which is why nothing else did.

`POST /auth/logout` and `POST /auth/ws-ticket` are rate-limited at 20/60s.
Logout is public by necessity and was unlimited; ws-ticket is authenticated but
writes a fresh single-use key per call.

The Next.js proxy strips the caller's `x-user-*` headers on a public path — that
arm forwarded them verbatim, so the advisory identity headers were forgeable
with no token at all — and `isPublicPath` matches at a segment boundary, so
`/login` no longer exempts `/loginhistory`.
Copilot AI review requested due to automatic review settings July 29, 2026 23:53

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review this pull request because it exceeds the maximum number of lines (20,000). Try reducing the number of changed lines and requesting a review from Copilot again.

…voke-all

Refresh re-reads the account and re-applies both gates login applies. Rotation
worked entirely from the store record, so nothing on that path ever looked at
the user again — and rotation is the door a signed-in caller actually uses. A
banned account renewed its access token for the refresh token's whole lifetime;
an address that was never verified held a session indefinitely, because
`register` issues one deliberately and only `login` ever checked. A blocked
account that touches the system now has every session revoked and its epoch
bumped in the same breath; an unverified one is refused without compensation,
because an unproven address is an unfinished onboarding and revoking would kill
the very token rendering the "check your inbox" screen.

`POST /auth/platform/logout` no longer requires a live access token. It required
`PlatformUser`, which refuses an expired one, so an operator who stepped away
for longer than the access lifetime could not sign out and the refresh session
of the highest-privilege identity in the system stayed live on a console they
believed they had left.

`DELETE /auth/sessions/all` accepts the refresh token from the body and refuses
when it cannot identify the caller's session. It read the cookie only, and a
bearer-mode deployment plants none — so it could never identify one, and the
engine treated that as "revoke nothing, successfully": a user with a compromised
second device clicked "sign out my other devices", got 204, and nothing
happened.

The in-memory store double now clears grace pointers on `revoke_all`, as the
real Lua does. Keeping them made the double weaker than production, so the
property those flows exist to guarantee was asserted against a fake that could
not break it.

BREAKING CHANGE: `AuthEngine::refresh` returns `RefreshedSession`, and
`AuthEngine::platform_logout` drops its `admin_id` parameter and returns the
revoked session's owner instead.
Copilot AI review requested due to automatic review settings July 30, 2026 01:19

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review this pull request because it exceeds the maximum number of lines (20,000). Try reducing the number of changed lines and requesting a review from Copilot again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants