id.oficina.works: the smart door, ruling 26 and its gates (smart-door step 5)
The door on id.* is rastrillo's one-way sign-in screen, drawn by its own
signin partial inside estilo's estilo-signin-screen. Home fills an
auth.SigninState itself (door.go) and builds none of auth's handlers.
- The jar: lastsignin.New at the credential origin, its instance key
derived from HOME_DEK under home/lastsignin/v1 (seal.Sealer.Derive,
handoff 3161be2). Remembered: a proven link or Keymail callback with
the address this browser proved; a finished passkey sign-in (the gate,
and the direct/conditional one) as passkey, keeping the address only
if its blind index resolves to the passkey owner's person ref, read in
the sign-in's own transaction. Every response that sets it is no-store.
- The doors: first visit (field, conditional UI), passkey, Continue as,
Continue to Keymail, the chooser and Back, ?way=, every problem
(Begin failures, ?err=, force=1 with force kept, prefilled only from
the cookie), Sent (address-free), the Keymail Continue step, and a
max_age step-up (reauth notice, every id.* way local). All no-store.
- Passkey glue: the partial's own module (passkey.JS() at
/static/signin.mjs) against the direct ceremony, whose finish already
answers {"ok":true,"to":...}; Home's passkey.js keeps enrolment, gate
and replacement and loses its dead direct button.
- Return memory: every chooser link, Back, Forget form and the passkey
finish carry return_to (the effective return, query or cookie).
- Forget: POST /signin/forget (csrf.Protect); GET/POST /forget?return=,
the chained "Forget me on Oficina ID too" confirm, returning only to a
registered consumer's /signed-out; id.*'s own signed-out page gains
Forget.
- Ruling 26 in the design spec's §1, with the §4 and gate 5 carve-out
under (a); AGENTS.md's gloss, Identity rule and v0.38.0 note; the
passkey.go comment; the smart-door spec's Signed-out paragraph now
describes the chain.
- Gates: gate 9 drives every credential route with a validly sealed
canary cookie plus the sign-ins that read and write it; gates 1 and 2
load the door after the sign-in (email and passkey) and re-scan DB,
WAL and SHM; gate 5 renders every credential route with the cookie
and refuses the canary off the door and any typed, query or unsealed
address anywhere; TestHomeNeverMountsFrameworkSignin narrowed to an
allowlist of the state's and jar's names in the door's two files.
- Makefile's printed ship line names oficina and oficina-id.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
31 files changed,
+1,739
−153
AGENTS.md+46 −11Makefile+7 −3docs/superpowers/specs/2026-08-30-home-design.md+15 −2docs/superpowers/specs/2026-11-19-smart-door.md+11 −3go.mod+1 −1go.sum+2 −0internal/guardstest/framework_signin_test.go+132 −17internal/home/app.go+19 −0internal/home/assertion_fresh_test.go+1 −3internal/home/calma.go+8 −9internal/home/door.go+354 −0internal/home/door_browser_test.go+86 −0internal/home/door_copy_test.go+19 −16internal/home/door_gates_test.go+202 −0internal/home/door_test.go+602 −0internal/home/id_browser_test.go+2 −2internal/home/id_passkey.go+11 −0internal/home/keymail_continue_test.go+51 −3internal/home/keymail_fresh_test.go+7 −5internal/home/keymailstub_test.go+1 −6internal/home/noscript_test.go+66 −0internal/home/passkey.go+15 −5internal/home/shared_chrome_test.go+10 −8internal/home/signin.go+34 −26internal/home/signin_test.go+15 −3internal/home/static/passkey.js+6 −4internal/home/templates/check_your_mail.html+0 −6internal/home/templates/door.html+2 −0internal/home/templates/id_forget.html+10 −0internal/home/templates/id_signed_out.html+4 −0internal/home/templates/signin.html+0 −20
diff --git a/AGENTS.md b/AGENTS.md| index 332a6bb..03b6162 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -38,6 +38,28 @@ of the membership roster: an owner row names a person ref from one team plus |
| a fact that is usually public, where the old wording needed several teams |
| and an outside fact. Spec §0 and §3.3 carry the full reasoning. |
| +**Ruling 26 (Paul, 2026-11-19, smart-door spec) is the one place a |
| +readable address may leave Home, and it never comes to rest here:** |
| + |
| +> Home may seal **the address this browser last proved** (an opened link, a |
| +> Keymail callback) into a cookie on **that person's own device**, and render |
| +> it back **only to the browser that presents it**, on a `no-store` page. It |
| +> is never written at rest by Home: not to the database, a log, an error, a |
| +> metric or a queue. It is not evidence of identity, and the page that shows |
| +> it consults no store. |
| + |
| +The falsifiable form above is unchanged by it. Under option (a) it also |
| +amends §4 and gate 5 (Identity, below) for exactly that one string: the |
| +door on id.* may render the address Home sealed itself (lastsignin's |
| +cookie, keyed from `HOME_DEK` under `home/lastsignin/v1`), shape-checked |
| +on read, escaped, as text and in a hidden `value`, and nothing else. It is |
| +not a licence to render a typed address, a query, a cookie Home did not |
| +seal, or any team, label or member name. A passkey sign-in keeps the |
| +remembered address only if its blind index resolves to the same person |
| +ref; otherwise it is blanked. Gates 1, 2, 5 and 9 are driven with a |
| +validly sealed canary cookie (`door_gates_test.go`). **Before shipping, |
| +confirm the carlos edge logs neither Cookie headers nor response bodies.** |
| + |
| *Two absolutes were argued and lost, and stay lost:* **"never stores your |
| address"** — a magic link's address is at rest between send and click, |
| sealed (§3.2), not absent — and **"some unidentified person"**: a team-set |
| @@ -161,9 +183,12 @@ quietly ignored). |
| **Identity** |
| - The **credential origin** serves sign-in, WebAuthn, recovery and assertion |
| - minting, and **never renders an account-authored string**. It is the |
| - relying party. This is a permanent constraint with its own test, not a |
| - naming choice. |
| + minting, and **never renders an account-authored string** but one: ruling |
| + 26's carve-out (above, under option (a)), the address Home sealed into |
| + this browser's own cookie, on the door only. It is the relying party. |
| + This is a permanent constraint with its own test (gate 5, amended for |
| + the carve-out and still refusing every other string), not a naming |
| + choice. |
| - **The RP ID is the full host — `id.oficina.works` — asserted by a test.** |
| Never widen it to a registrable suffix. WebAuthn *permits* an RP ID that |
| is a suffix of the origin's hostname, so `oficina.works` would be |
| @@ -369,15 +394,22 @@ quietly ignored). |
| `cmd/home` opens through `home.OpenDatabase`, which passes |
| `db.DurableCommits()` to keep `FULL` (`TestOpenDatabaseCommitsDurably` |
| reads `PRAGMA synchronous` = 2). |
| -- **What v0.38.0 changed under Home.** Home's own code imports neither |
| - `auth` nor `lastsignin`, whose structs and one-way door are the |
| - release's API changes. That is direct imports only: `passkey` (for |
| - its Schema and Config) links `lastsignin` and `secondfactor` itself. |
| - Home builds none of passkey's handlers (its ceremonies are its own; |
| +- **What v0.38.0 changed under Home.** `auth`'s and `lastsignin`'s |
| + structs and one-way door are the release's API changes. Since |
| + smart-door step 5 the door (`internal/home/door.go`, with `signin.go`) |
| + fills an `auth.SigninState` itself and renders rastrillo's `signin` |
| + partial in estilo's `estilo-signin-screen`, and remembers the way in |
| + with `lastsignin.New`'s jar; nothing else in Home imports either. |
| + `passkey` (for its Schema, Config and the door's module, `passkey.JS()`) |
| + links `lastsignin` and `secondfactor` itself. Home builds none of |
| + passkey's or auth's handlers (its ceremonies and sign-in are its own; |
| `passkeyCfg` is kept only as the record the RP-ID guard reads), and |
| `internal/guardstest`'s `TestHomeNeverMountsFrameworkSignin` fails on |
| - a direct import of `auth`, `lastsignin` or `secondfactor`, or a |
| - `passkey.New` / `passkey.Handlers`, in production code. `sessions`, `crypto`, `db`, `passkey` and |
| + a direct import of `secondfactor`; an import of `auth` or `lastsignin` |
| + outside the door's files, or any name of theirs beyond the state, its |
| + constants and the jar (`doorImports`: never `auth.New`, `auth.Config` |
| + or a handler); or a `passkey.New` / `passkey.Handlers`, in production |
| + code. `sessions`, `crypto`, `db`, `passkey` and |
| `webauthn`'s Go are byte-identical, `assertion` only moved its |
| validators into an internal package, `auth`'s migrations are |
| unchanged, and `keymaildev/signin` stays v0.1.1. `webauthn.JS()` |
| @@ -412,7 +444,10 @@ quietly ignored). |
| screens). Every screen works with scripts off — magic-link sign-in, |
| recovery codes, the springboard, sign-out — and a script may be added |
| to a page only to enhance it or to provide interaction HTML and CSS |
| - cannot: the passkey ceremonies (`webauthn.JS()` plus a little glue), |
| + cannot: the passkey ceremonies (`webauthn.JS()` plus a little glue, |
| + and on the door rastrillo's own module, `passkey.JS()` at |
| + `/static/signin.mjs`, which runs the passkey door and the email field's |
| + conditional UI against the direct ceremony's `{ok,to}` finish), |
| the assertion handoff's auto-submit (its Continue button stays for |
| script-off), and estilo's busy rule on every submit button (the |
| spinner, the double-submit guard). Reach for HTML and CSS first; a |
diff --git a/Makefile b/Makefile| index 1cf4200..30f46e6 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -53,9 +53,13 @@ release: |
| @echo "built $(RELEASE_BIN) reporting version $(VERSION)" |
| @echo "publish it with:" |
| @echo " amadan release create -repo oficina/$(APP) -notes-file NOTES.md $(VERSION) $(RELEASE_BIN)" |
| - @echo "ship it declaring CARLOS mail submission, then promote it (AGENTS.md, Deploys):" |
| - @echo " carlos ship -app $(APP) -mail submit -version $(VERSION) -target $(RELEASE_GOOS)-$(RELEASE_GOARCH) $(RELEASE_BIN)" |
| - @echo " carlos promote -app $(APP) $(VERSION)" |
| + @echo "ship it to BOTH production apps, oficina and oficina-id (neither is called home)," |
| + @echo "declaring CARLOS mail submission, then promote it (AGENTS.md, Deploys):" |
| + @echo " for app in oficina oficina-id; do" |
| + @echo " carlos ship --app \$$app --account oficina --mail submit --version $(VERSION) --target $(RELEASE_GOOS)-$(RELEASE_GOARCH) $(RELEASE_BIN)" |
| + @echo " carlos promote --app \$$app --account oficina $(VERSION)" |
| + @echo " done" |
| + @echo "(--app home is the preview/canary only; it leaves production as it was)" |
| # The gate, split into named targets so CI can report them individually |
| # (.amadan/ci.d calls these one at a time, each its own step). `make |
diff --git a/docs/superpowers/specs/2026-08-30-home-design.md b/docs/superpowers/specs/2026-08-30-home-design.md| index 167032e..9df6071 100644 |
| --- a/docs/superpowers/specs/2026-08-30-home-design.md |
| +++ b/docs/superpowers/specs/2026-08-30-home-design.md |
| @@ -137,6 +137,7 @@ blind, replaceable*. |
| | 22 | **The team selection is navigation state, not session state: `?team=<sqid>` on every team view, with `/` a generic entry that picks a team and `302`s to the explicit URL** — §11 | A session cookie (history does not restore one, so Back has no correct behaviour; and a shared cookie couples every same-origin team-dependent request across tabs, not just New); a URL fragment read by CSS `:target` (the server never learns the team, so nothing server-rendered can be team-scoped — not the grid, not the switcher's `aria-current`, not gate 4's 404); a `prefs` row (§14) | Paul, 2026-09-05, after a second opinion from **GPT-6 Astra via Codex** (its default; `gpt-5.3-codex` and `gpt-5.3-sol` were both refused by the account, so the model is named from Codex's own rollout record rather than from what was asked for) | |
| | 23 | **The suite sharing doctrine (`oficina/suite`) binds this spec, and membership becomes a record of the home's own.** The team is the boundary; the home owns identity, the team and the membership roster; it never owns a per-item grant. `(team, person, role)` is written only at the directory origin by an owner behind step-up, or seeded by the drain with the team's first owner. A directory row never grants team standing. Call 8, roster pull, is added to §9. | **The status quo this overturns: team standing living only in each instance's grants, with the home holding no roster at all** (§5.5, §7 as they stood). And the doctrine's own first revision, which derived the roster from call-2 directory rows: the row has no owner role (§6 — `kind` is member or guest), §7 says the home never learns who an owner is, the row is scoped per (team, app) where the roster is per team, and any instance can write one under its consumer token — so deriving from it routes around the step-up entirely | Paul, 2026-09-05 (suite ruling 12). Numbered 23 because the doctrine's appendix said "add ruling 22" and 22 was already taken; a review of the doctrine caught the collision | |
| | 24 | **Automatic app entry uses the shared P-256 assertion core, separate credential/directory processes, and a static auto-POST enhancement on the handoff screen.** Exact contract: implementation/team-entry.md at36f876c, with the reviewed consumer implementation at3c550c3. The Continue button works without script; no other credential screen gains script. | A second app-specific verifier; shared-domain cookies; an arbitrary return URL; requiring a manual handoff click when scripts are enabled | Codex implementation decision, 2026-09-08, under Paul's explicit approval in this session of Home sign-in and automatic return to the selected team app. Reviewed by Claude Fable 5.1; not attributed to the older ruling21. | |
| +| 26 | **Home may seal the address this browser last proved (an opened link, a Keymail callback) into a cookie on that person's own device, and render it back only to the browser that presents it, on a `no-store` page. It is never written at rest by Home: not to the database, a log, an error, a metric or a queue. It is not evidence of identity, and the page that shows it consults no store.** The falsifiable form is unchanged: publish Home's database in full, and nothing in it is a readable address. **§4 and gate 5 are amended by it, under option (a):** the credential origin may render exactly one person-supplied string, the address Home sealed itself, shape-checked again on read, escaped by html/template, as text and in a hidden `value`, on the door only. Any other account-authored string stays forbidden there — §4, smart-door spec | **(b)** keeping §4 absolute, with id.* remembering the method only and the browser's autofill supplying the address; rastrillo's blind mode, which turns address-remembering off; a parent-domain cookie shared across hosts | Paul, 2026-11-19 (smart-door spec, ruling 1 and option (a)); recorded with smart-door step 5 | |
| --- |
| @@ -461,7 +462,14 @@ is what `decisions.md` warns against. Tito's answer: *credentials only ever |
| on the root origin, account-authored content only on the account's own host.* |
| - **Credential origin** — sign-in, WebAuthn, recovery, assertion minting. |
| - **No account-authored string, ever.** This is the RP. |
| + **No account-authored string, ever** — with exactly one exception, ruling |
| + 26 (2026-11-19, option (a)): the sign-in door may show back the address |
| + Home itself sealed into this browser's own cookie (the address this |
| + browser last proved), re-checked on read, escaped, as text and in a |
| + hidden `value`, on a `no-store` page, and nowhere else on the origin. |
| + Nothing a request supplies — a typed address, a query, a cookie Home did |
| + not seal — and no team name, label or member name is ever rendered here. |
| + This is the RP. |
| - **Directory origin** — a different hostname. Renders team names, holds no |
| credentials. |
| @@ -1427,7 +1435,12 @@ No template gallery, no upsell chrome, no waffle. |
| to find — **a member of Acme with no grant in `acme.sheets` does see the |
| `acme.sheets` tile.** |
| 5. **Origin separation** — no account-authored string reachable on the |
| - credential origin. §4 made mechanical. |
| + credential origin. §4 made mechanical. **Amended by ruling 26:** the |
| + one exception is the address Home sealed into this browser's cookie, |
| + on the door alone; the gate drives every credential route with a |
| + validly sealed canary cookie and fails if the canary renders anywhere |
| + else, if any page renders a typed or query-supplied address, or if the |
| + door renders an address Home did not seal. |
| 6. **Scriptless-affordance diff** — every page, script-stripped. **For the |
| ruling-21 screens: every affordance except the passkey ceremony button |
| itself, and the allowlist is named explicitly in the test. The ruling24 handoff keeps its Continue button with scripts off.** Exempting |
diff --git a/docs/superpowers/specs/2026-11-19-smart-door.md b/docs/superpowers/specs/2026-11-19-smart-door.md| index 06bbde9..6a97345 100644 |
| --- a/docs/superpowers/specs/2026-11-19-smart-door.md |
| +++ b/docs/superpowers/specs/2026-11-19-smart-door.md |
| @@ -141,9 +141,17 @@ email way is always one tap away in the chooser. |
| **Signed out** (every app): "You're signed out", **Sign in again**, and a |
| quiet *new* **Forget me on this device**, which posts to `Forget` for a shared |
| computer. connect's signed-out `PageData` and estilo's `estilo-signed-out` |
| -each gain that second POST form. A Home-derived sign-out chains to id.*'s |
| -signed-out page, which offers its own Forget, because each host forgets |
| -separately. Forget's request-forgery protection is unchanged: |
| +each gain that second POST form. Each host forgets separately, so a |
| +Home-derived app chains to id.* after its own Forget: the app's signed-out |
| +page links to `https://id.oficina.works/forget?return=<its own signed-out |
| +URL>`, which shows one button, *new* **Forget me on Oficina ID too** (a |
| +same-origin POST), and a quiet *new* **Not now** link back. After |
| +forgetting, id.* returns **only** to a URL whose origin is a registered |
| +consumer (`HOME_CONSUMERS`) and whose path is exactly `/signed-out`; |
| +anything else lands on id.*'s own signed-out page, which offers its own |
| +Forget. (Sign-out itself never passes through id.*'s signed-out page: the |
| +consumer hop lands on the app's own, so the chain starts there.) Apps add |
| +the link in step 6. Forget's request-forgery protection is unchanged: |
| `csrf.SameOrigin` in apps and `csrf.Protect` on Home. The worst a forged |
| request can do is forget. |
diff --git a/go.mod b/go.mod| index 7094091..25ffcca 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -7,7 +7,7 @@ toolchain go1.26.5 |
| require ( |
| amadan.net/oficina/estilo.git v0.0.0-20261120104604-487cadb03b88 |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 |
| - amadan.net/oficina/home/handoff v0.0.0-20261114110939-e03a01a1881c |
| + amadan.net/oficina/home/handoff v0.0.0-20261120123136-3161be2a8b1a |
| amadan.net/oficina/home/roster v0.0.0-20261028165624-d942439ac4e4 |
| amadan.net/rastrillo/rastrillo v0.38.0 |
| filippo.io/age v1.3.2 |
diff --git a/go.sum b/go.sum| index dc86672..fa58e75 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -6,6 +6,8 @@ amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0 |
| amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0= |
| amadan.net/oficina/home/handoff v0.0.0-20261114110939-e03a01a1881c h1:KxjjyIlEu3hY1G6l26IrI2PRcogOscpTeydRgNzimbA= |
| amadan.net/oficina/home/handoff v0.0.0-20261114110939-e03a01a1881c/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k= |
| +amadan.net/oficina/home/handoff v0.0.0-20261120123136-3161be2a8b1a h1:rpycnGdTgl+N1BDSmQq7A9P58TfqYIcyinr/C5pMAL8= |
| +amadan.net/oficina/home/handoff v0.0.0-20261120123136-3161be2a8b1a/go.mod h1:Mn5Rsm7Vcd6VZArBKMawza2yO+Fjo8KB1Ii6UcjcJHQ= |
| amadan.net/oficina/home/roster v0.0.0-20261028165624-d942439ac4e4 h1:jg3sS7hy8Qaewrv/7CZ4kjIYE62FaIG4KMlfNs918dY= |
| amadan.net/oficina/home/roster v0.0.0-20261028165624-d942439ac4e4/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg= |
| amadan.net/rastrillo/fiesta v1.5.0 h1:wKfTsL5zRMofJBAqOxNlCY7aCtgHCtfwvTPBMA+ZA20= |
diff --git a/internal/guardstest/framework_signin_test.go b/internal/guardstest/framework_signin_test.go| index 38a4660..473f1f7 100644 |
| --- a/internal/guardstest/framework_signin_test.go |
| +++ b/internal/guardstest/framework_signin_test.go |
| @@ -4,25 +4,111 @@ import ( |
| "go/ast" |
| "go/parser" |
| "go/token" |
| + "os" |
| + "path" |
| + "path/filepath" |
| + "slices" |
| "strconv" |
| "strings" |
| "testing" |
| ) |
| -// frameworkSignin are rastrillo's sign-in packages Home must not import |
| -// directly. Home is blind: its link store is sealed and its session |
| -// subject is an opaque person ref, and auth's defaults would write a |
| -// readable auth_links.address (AGENTS.md, Data). lastsignin remembers an |
| -// address in a cookie; secondfactor's Schema copies the recovery codes |
| -// out and drops the table Home's codes live in. passkey links lastsignin |
| -// and secondfactor itself, which is allowed: what is held here is that |
| -// Home's own code never reaches for them. |
| +// frameworkSignin are rastrillo's sign-in packages Home must not reach for |
| +// beyond what it needs. Home is blind: its link store is sealed and its |
| +// session subject is an opaque person ref, and auth's defaults would write |
| +// a readable auth_links.address (AGENTS.md, Data). secondfactor's Schema |
| +// copies the recovery codes out and drops the table Home's codes live in, |
| +// so it is never imported. passkey links lastsignin and secondfactor |
| +// itself, which is allowed: what is held here is that Home's own code |
| +// never reaches for them. |
| var frameworkSignin = []string{ |
| "amadan.net/rastrillo/rastrillo/auth", |
| "amadan.net/rastrillo/rastrillo/lastsignin", |
| "amadan.net/rastrillo/rastrillo/secondfactor", |
| } |
| +// doorImports is the one carve-out (smart-door spec step 5, ruling 26): |
| +// the door on id.* fills rastrillo's SigninState itself, renders its |
| +// partial, and remembers the way in with lastsignin's jar. So auth and |
| +// lastsignin may be imported, only by the door's two files, and only for |
| +// these names: the state, its constants and the jar. Never auth.New, |
| +// auth.Config or any handler, which would be the framework's sign-in, and |
| +// never secondfactor. |
| +var doorImports = map[string]struct { |
| + files []string |
| + names map[string]bool |
| +}{ |
| + "amadan.net/rastrillo/rastrillo/auth": { |
| + files: []string{"internal/home/door.go", "internal/home/signin.go"}, |
| + names: setOf("SigninState", "SigninProblem", "Remembered", "PasskeyDoor", "ParseWay", "WayEmail", |
| + "StepAsk", "StepReturning", "StepSent", "StepContinue", |
| + "ProblemNone", "ProblemAddress", "ProblemRate", "ProblemGeneric", "ProblemExpired", "ProblemKeymail", "ProblemReauth"), |
| + }, |
| + "amadan.net/rastrillo/rastrillo/lastsignin": { |
| + files: []string{"internal/home/door.go"}, |
| + names: setOf("New", "Config", "Jar", "Record", "On", "Valid", "Invalid", |
| + "MethodMagicLink", "MethodKeymail", "MethodPasskey"), |
| + }, |
| +} |
| + |
| +func setOf(names ...string) map[string]bool { |
| + set := make(map[string]bool, len(names)) |
| + for _, n := range names { |
| + set[n] = true |
| + } |
| + return set |
| +} |
| + |
| +// frameworkSigninUses is every way the file at rel (relative to the repo |
| +// root, slash-separated) reaches past the carve-out: a banned import, an |
| +// allowed import from another file, or a name the carve-out does not |
| +// list. |
| +func frameworkSigninUses(t *testing.T, rel string, src []byte) []string { |
| + t.Helper() |
| + fset := token.NewFileSet() |
| + f, err := parser.ParseFile(fset, rel, src, parser.SkipObjectResolution) |
| + if err != nil { |
| + t.Fatalf("parse %s: %v", rel, err) |
| + } |
| + var out []string |
| + local := map[string]string{} // import name in this file -> package path |
| + for _, imp := range f.Imports { |
| + p, _ := strconv.Unquote(imp.Path.Value) |
| + if !slices.Contains(frameworkSignin, p) { |
| + continue |
| + } |
| + allowed, ok := doorImports[p] |
| + if !ok || !slices.Contains(allowed.files, rel) { |
| + out = append(out, "imports "+p) |
| + continue |
| + } |
| + name := path.Base(p) |
| + if imp.Name != nil { |
| + name = imp.Name.Name |
| + } |
| + if name == "_" || name == "." { |
| + out = append(out, "imports "+p+" as "+name) |
| + continue |
| + } |
| + local[name] = p |
| + } |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + sel, ok := n.(*ast.SelectorExpr) |
| + if !ok { |
| + return true |
| + } |
| + x, ok := sel.X.(*ast.Ident) |
| + if !ok { |
| + return true |
| + } |
| + if p, ok := local[x.Name]; ok && !doorImports[p].names[sel.Sel.Name] { |
| + out = append(out, "line "+strconv.Itoa(fset.Position(sel.Pos()).Line)+": "+x.Name+"."+sel.Sel.Name) |
| + } |
| + return true |
| + }) |
| + return out |
| +} |
| + |
| // passkeyPkg's New and Handlers build and hold passkey's HTTP handlers. |
| // Home runs its own ceremonies (internal/home/id_passkey.go) and keeps |
| // passkey.Config only as the record its RP-ID guard reads; passkey's |
| @@ -65,9 +151,11 @@ func passkeyHandlerUses(t *testing.T, path string) []string { |
| return uses |
| } |
| -// TestHomeNeverMountsFrameworkSignin fails on a direct import of auth, |
| -// lastsignin or secondfactor, or a passkey.New / passkey.Handlers, in |
| -// any of Home's production files (tests may build fixtures with them). |
| +// TestHomeNeverMountsFrameworkSignin fails on a direct import of |
| +// secondfactor; an import of auth or lastsignin outside the door's files, |
| +// or any of their names beyond the door's carve-out (doorImports); or a |
| +// passkey.New / passkey.Handlers, in any of Home's production files |
| +// (tests may build fixtures with them). |
| func TestHomeNeverMountsFrameworkSignin(t *testing.T) { |
| root := repoRoot(t) |
| for _, path := range goFiles(t, root) { |
| @@ -75,15 +163,42 @@ func TestHomeNeverMountsFrameworkSignin(t *testing.T) { |
| continue |
| } |
| rel := relPath(t, root, path) |
| - for _, imp := range fileImports(t, path) { |
| - for _, banned := range frameworkSignin { |
| - if imp == banned { |
| - t.Errorf("%s: imports %s; Home does its own sign-in (AGENTS.md, Data)", rel, imp) |
| - } |
| - } |
| + src, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, use := range frameworkSigninUses(t, filepath.ToSlash(rel), src) { |
| + t.Errorf("%s: %s; Home does its own sign-in, and the door may use only its state and jar (AGENTS.md, Data)", rel, use) |
| } |
| for _, use := range passkeyHandlerUses(t, path) { |
| t.Errorf("%s: %s; Home mounts none of passkey's handlers", rel, use) |
| } |
| } |
| } |
| + |
| +// The carve-out is narrow, and the guard says so on the shapes it must |
| +// refuse: the framework's constructor and handlers from the door's own |
| +// file, the jar from a file that is not the door's, and secondfactor |
| +// anywhere. |
| +func TestFrameworkSigninCarveOutRefuses(t *testing.T) { |
| + const head = "package home\n\nimport (\n\t\"amadan.net/rastrillo/rastrillo/auth\"\n\t\"amadan.net/rastrillo/rastrillo/lastsignin\"\n)\n\n" |
| + cases := []struct { |
| + rel, body string |
| + refused bool |
| + }{ |
| + {"internal/home/door.go", "var _ auth.SigninState\nvar _, _ = lastsignin.New(lastsignin.Config{})\n", false}, |
| + {"internal/home/door.go", "var _, _ = auth.New(auth.Config{})\nvar _ lastsignin.Jar\n", true}, |
| + {"internal/home/door.go", "var _ = auth.SigninState{}.Door\nvar _ = lastsignin.Forgetting\n", true}, |
| + {"internal/home/signin.go", "var _ auth.SigninState\nvar _ lastsignin.Jar\n", true}, |
| + {"internal/home/app.go", "var _ auth.SigninState\nvar _ lastsignin.Jar\n", true}, |
| + } |
| + for i, c := range cases { |
| + if got := frameworkSigninUses(t, c.rel, []byte(head+c.body)); (len(got) > 0) != c.refused { |
| + t.Errorf("case %d (%s): uses %q, refused want %v", i, c.rel, got, c.refused) |
| + } |
| + } |
| + src := "package home\n\nimport _ \"amadan.net/rastrillo/rastrillo/secondfactor\"\n" |
| + if got := frameworkSigninUses(t, "internal/home/door.go", []byte(src)); len(got) == 0 { |
| + t.Error("secondfactor imported by the door's file passed") |
| + } |
| +} |
diff --git a/internal/home/app.go b/internal/home/app.go| index 86b70ae..bc0d3a1 100644 |
| --- a/internal/home/app.go |
| +++ b/internal/home/app.go |
| @@ -57,6 +57,11 @@ type App struct { |
| flow *signin.Flow |
| sessions *sessions.Sessions |
| + // jar is the door's remembered way in (door.go, ruling 26): a sealed |
| + // cookie on the person's own browser, never anything at rest here. |
| + // Nil on the directory, which never serves the door. |
| + jar *lastsigninJar |
| + |
| // signinLimiter is signin.Flow's own limiter, held here so that /resolve |
| // spends the same per-IP budget sign-in does; resolveLimiter is |
| // /resolve's per-subject budget (credential). teamWrites is the Team |
| @@ -130,7 +135,13 @@ func NewWithOrigins(secrets Secrets, d *db.DB, logger *slog.Logger, origins Orig |
| return nil, err |
| } |
| + jar, err := newJar(secrets, origins.Credential) |
| + if err != nil { |
| + return nil, err |
| + } |
| + |
| a := &App{ |
| + jar: jar, |
| origins: origins, |
| credentialHost: strings.TrimPrefix(origins.Credential, "https://"), |
| directoryHost: strings.TrimPrefix(origins.Directory, "https://"), |
| @@ -243,6 +254,11 @@ func (a *App) Router() http.Handler { |
| r.Get("/signin", a.handleSigninForm) |
| r.Post("/signin", a.handleSigninBegin) |
| r.Get("/signin/sent", a.handleSigninSent) |
| + // Forget (door.go): "Use a different email", and the confirm page |
| + // an app's signed-out page chains to. POSTs behind csrf.Protect. |
| + r.Post(forgetPath, a.handleForget) |
| + r.Get(forgetChainPath, a.handleForgetChainPage) |
| + r.Post(forgetChainPath, a.handleForgetChain) |
| // GET renders, POST redeems. See handleVerifyForm for why. |
| r.Get(linkPath, a.handleVerifyForm) |
| r.Post(linkPath, a.handleVerify) |
| @@ -294,6 +310,9 @@ func (a *App) Router() http.Handler { |
| // rule. |
| r.Get("/static/webauthn.mjs", serveAsset(webauthnJS(), "text/javascript; charset=utf-8")) |
| r.Get("/static/passkey.js", serveAsset(staticAsset("passkey.js"), "text/javascript; charset=utf-8")) |
| + // The door's passkey module: rastrillo's (passkey.JS()), the one |
| + // the signin partial loads on its passkey door and email field. |
| + r.Get(signinModule, serveAsset(signinJS(), "text/javascript; charset=utf-8")) |
| }) |
| // Vendored from rastrillo's ui package, not linked from it: an app |
diff --git a/internal/home/assertion_fresh_test.go b/internal/home/assertion_fresh_test.go| index 2314b2a..779a72a 100644 |
| --- a/internal/home/assertion_fresh_test.go |
| +++ b/internal/home/assertion_fresh_test.go |
| @@ -128,11 +128,9 @@ func TestOrdinaryIntentKeepsKeymailAndInvalidIntentCannotRequestFreshness(t *tes |
| intent.Value = base64.RawURLEncoding.EncodeToString(sealed) |
| } |
| r := exchangeRequest(p.credential.App, "POST", Origin+"/signin", Origin, url.Values{"address": {sealtest.CanaryAddress}}, cookies...) |
| - _, links := continuationTargets(t, r.Body.String()) |
| - if len(links) != 1 || !strings.Contains(links[0], "/oauth/authorize?") { |
| + if to := doorContinuation(t, r); !strings.Contains(to, "/oauth/authorize?") { |
| t.Fatal("ordinary or invalid intent lost Keymail continuation", r.Code) |
| } |
| - assertContinuationPage(t, r, links[0]) |
| }) |
| } |
| } |
diff --git a/internal/home/calma.go b/internal/home/calma.go| index 57d97a5..7d77449 100644 |
| --- a/internal/home/calma.go |
| +++ b/internal/home/calma.go |
| @@ -35,15 +35,14 @@ var homeFuncs = map[string]any{ |
| "suiteSky": func() sky.View { return sky.For(sky.SuiteSeed) }, |
| // The door's words and tab titles are estilo's (chrome.English), the |
| // one copy set every app's door speaks, so the hub's door cannot |
| - // drift from theirs. Home draws its own templates, so it reads the |
| - // strings from estilo's types rather than rendering estilo-signin. |
| - "signinDoor": func() chrome.SignIn { return chrome.SignIn{App: suiteName} }, |
| - "sentDoor": func(again string) chrome.SignInNotice { |
| - return chrome.SignInNotice{App: suiteName}.Sent(again) |
| - }, |
| + // drift from theirs. The sign-in door itself is rastrillo's partial in |
| + // estilo's door (door.go); these are the pages around it. |
| "signedOutDoor": func() chrome.SignInNotice { |
| return chrome.SignInNotice{App: suiteName}.SignedOut("/auth/start") |
| }, |
| + // forgetLabel is estilo's "Forget me on this device" (SignInNotice. |
| + // Forgetting's label), on id.*'s own signed-out page. |
| + "forgetLabel": func() string { return chrome.English.Forget }, |
| "linkLifetime": func() int { return int(chrome.LinkLifetime.Minutes()) }, |
| // doorView is estilo-door-open's data: the suite's sky behind one |
| // card, the Oficina mark and name at its head. |
| @@ -80,10 +79,10 @@ const suiteName = "Oficina" |
| // The sky goes only where Calma puts it — the door, the team home's header |
| // and the front page's hero — so the team chooser, Open source and the |
| // error pages are plain pages under the bar. |
| -// Not assertion.html or docs_continue.html: they are hops (hopPages). |
| +// Not assertion.html or docs_continue.html: they are hops (hopPages). Not |
| +// door.html either: estilo-signin-screen draws the door itself. |
| var doorPages = map[string]bool{ |
| - "signin.html": true, |
| - "check_your_mail.html": true, |
| + "id_forget.html": true, |
| "signin_confirm.html": true, |
| "signin_failed.html": true, |
| "passkey_confirm.html": true, |
diff --git a/internal/home/door.go b/internal/home/door.go| new file mode 100644 |
| index 0000000..623f5f8 |
| --- /dev/null |
| +++ b/internal/home/door.go |
| @@ -0,0 +1,354 @@ |
| +package home |
| + |
| +import ( |
| + "database/sql" |
| + "encoding/hex" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/estilo.git/chrome" |
| + "amadan.net/oficina/estilo.git/sky" |
| + "amadan.net/rastrillo/rastrillo/auth" |
| + "amadan.net/rastrillo/rastrillo/lastsignin" |
| + "github.com/keymaildev/signin" |
| +) |
| + |
| +// The smart door on id.oficina.works (smart-door spec, step 5; |
| +// docs/superpowers/specs/2026-11-19-smart-door.md). The sign-in page is |
| +// rastrillo's one-way screen, drawn by its own "signin" partial inside |
| +// estilo's door (estilo-signin-screen): Home fills an auth.SigninState |
| +// itself, because Home is blind and runs its own sign-in, and never |
| +// builds auth's handlers. This file is the only one in Home that may |
| +// import auth or lastsignin, and only for the state, the jar and their |
| +// constants (internal/guardstest, TestHomeNeverMountsFrameworkSignin). |
| +// |
| +// What the door remembers is ruling 26 (design spec §1): the way in this |
| +// browser used last, and the address it last proved, sealed into a |
| +// cookie on the person's own device and rendered back only to the browser |
| +// that presents it, on a no-store page. Never at rest in Home, never in a |
| +// log, never evidence of anything: a one-tap posts the address to Begin, |
| +// which proves it afresh. |
| + |
| +// doorName is the brand on the door (the spec: id.oficina.works is "Oficina |
| +// ID"): the card's head, and the partial's "Sign in to Oficina ID". |
| +const doorName = "Oficina ID" |
| + |
| +// jarLabel is the label HOME_DEK's Sealer derives the jar's instance key |
| +// under (seal.Sealer.Derive). Changing it forgets every browser, which is |
| +// harmless: an old cookie reads as Invalid and is cleared. |
| +const jarLabel = "home/lastsignin/v1" |
| + |
| +// The door's paths. signinPath is the door itself; forgetPath is "Use a |
| +// different email" (rastrillo's Forget, POST); forgetChainPath is the |
| +// confirm page an app's signed-out page links to after its own Forget. |
| +const ( |
| + signinPath = "/signin" |
| + forgetPath = "/signin/forget" |
| + forgetChainPath = "/forget" |
| +) |
| + |
| +// The passkey door's endpoints and scripts. The begin/finish pair is the |
| +// discoverable ("direct") ceremony, whose finish answers {"ok":true,"to":…}, |
| +// the shape rastrillo's door module reads. signinModule is that module |
| +// (passkey.JS()), served by Home; webauthnModule is rastrillo's WebAuthn |
| +// helper, which the module imports. |
| +const ( |
| + directBegin = "/passkey/direct/begin" |
| + directFinish = "/passkey/direct/finish" |
| + signinModule = "/static/signin.mjs" |
| + webauthnModule = "/static/webauthn.mjs" |
| +) |
| + |
| +// newJar builds the id.* jar: lastsignin's cookie, its key derived from |
| +// HOME_DEK under jarLabel, bound to the credential origin. No attempt |
| +// cookie: Home keeps none. |
| +func newJar(secrets Secrets, origin string) (*lastsignin.Jar, error) { |
| + key, err := secrets.Sealer.Derive(jarLabel) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return lastsignin.New(lastsignin.Config{ |
| + Origin: origin, |
| + InstanceKey: hex.EncodeToString(key), |
| + Mode: lastsignin.On, |
| + }) |
| +} |
| + |
| +// lastsigninRecord is lastsignin's record, named here so the passkey |
| +// finish (id_passkey.go) need not import lastsignin itself. |
| +type lastsigninRecord = lastsignin.Record |
| + |
| +// lastsigninJar is the jar's type, named for App. |
| +type lastsigninJar = lastsignin.Jar |
| + |
| +// remember records how this browser just signed in. A no-op on an App with |
| +// no jar (the directory role, which never serves the door). The response |
| +// that carries the sealed cookie is no-store, so no cache keeps it. |
| +func (a *App) remember(w http.ResponseWriter, rec lastsignin.Record) { |
| + if a.jar != nil { |
| + w.Header().Set("Cache-Control", "no-store") |
| + a.jar.Remember(w, rec) |
| + } |
| +} |
| + |
| +// rememberEmail records a proven link or Keymail callback, with the |
| +// address this browser proved. |
| +func (a *App) rememberEmail(w http.ResponseWriter, id signin.Identity) { |
| + method := lastsignin.MethodMagicLink |
| + if id.Method == signin.MethodKeymail { |
| + method = lastsignin.MethodKeymail |
| + } |
| + a.remember(w, lastsignin.Record{Method: method, Address: id.Address}) |
| +} |
| + |
| +// passkeyRecord is what a finished passkey sign-in remembers: passkey, and |
| +// the address this browser had remembered only if its blind index resolves |
| +// to the same person ref as the passkey's owner, checked now, inside the |
| +// sign-in's own transaction. Anything else blanks it, so one person's |
| +// passkey sign-in is never labelled with another's address. The lookup |
| +// reads; it never mints a person. |
| +func (a *App) passkeyRecord(tx *sql.Tx, r *http.Request, owner string) lastsignin.Record { |
| + rec := lastsignin.Record{Method: lastsignin.MethodPasskey} |
| + if a.jar == nil { |
| + return rec |
| + } |
| + prev, res := a.jar.Read(r) |
| + if res != lastsignin.Valid || prev.Address == "" { |
| + return rec |
| + } |
| + var ref string |
| + err := tx.QueryRow("SELECT person_ref FROM people WHERE blind_index=?", blindIndex(a.secrets.Pepper, prev.Address)).Scan(&ref) |
| + if err == nil && ref == owner { |
| + rec.Address = prev.Address |
| + } |
| + return rec |
| +} |
| + |
| +// queryProblem maps ?err= as rastrillo's screen does, so its words are |
| +// rastrillo's approved copy. Home sends none of |
| +// these itself today; the door honours them so that every problem is drawn |
| +// the same way, on the email field. An err it does not know is the |
| +// generic problem (ChooseWay). |
| +func queryProblem(q url.Values) auth.SigninProblem { |
| + switch q.Get("err") { |
| + case "rate": |
| + return auth.ProblemRate |
| + case "address": |
| + return auth.ProblemAddress |
| + case "expired": |
| + return auth.ProblemExpired |
| + case "keymail": |
| + return auth.ProblemKeymail |
| + } |
| + return auth.ProblemNone |
| +} |
| + |
| +// doorState fills the one-way screen's state for r. It reads the query, |
| +// this browser's remembered cookie and its return and step-up cookies, |
| +// and consults no store, so the page is a function of what the browser |
| +// already holds and cannot reveal whether an address is known. A cookie |
| +// that cannot be believed is cleared on w. |
| +// |
| +// target is where the sign-in is going (a credentialReturn value): every |
| +// link, Back, the Forget forms and the passkey finish carry it as |
| +// return_to, so neither the chooser nor Forget loses the app's handoff. |
| +func (a *App) doorState(w http.ResponseWriter, r *http.Request, target string, problem auth.SigninProblem) auth.SigninState { |
| + q := r.URL.Query() |
| + st := auth.SigninState{ |
| + Step: auth.StepAsk, |
| + BeginPath: signinPath, |
| + ForgetPath: forgetPath, |
| + SigninPath: signinPath, |
| + OneWay: true, |
| + Force: q.Get("force") == "1", |
| + Passkey: &auth.PasskeyDoor{ |
| + BeginPath: directBegin, |
| + FinishPath: directFinish, |
| + ModuleURL: webauthnModule, |
| + ScriptURL: signinModule, |
| + LegacyRPID: a.passkeyCfg.LegacyRPID, |
| + }, |
| + } |
| + // The form's own action keeps force: a browser submits the action, not |
| + // the URL that drew the form, and a forced retry that lost it would go |
| + // straight back to Keymail. The partial also posts a hidden force=1. |
| + if st.Force { |
| + st.BeginPath = signinPath + "?force=1" |
| + } |
| + if target != "/" { |
| + st.ReturnTo = target |
| + } |
| + if a.jar != nil { |
| + switch rec, res := a.jar.Read(r); res { |
| + case lastsignin.Valid: |
| + st.Remembered = &auth.Remembered{Method: rec.Method, Address: rec.Address, Provider: rec.Provider} |
| + // The field's prefill is the remembered address, never the |
| + // query or a posted value: the one account-authored string |
| + // id.* may render is the one Home sealed itself (ruling 26). |
| + st.Address = rec.Address |
| + case lastsignin.Invalid: |
| + a.jar.Clear(w) |
| + } |
| + } |
| + if problem == auth.ProblemNone { |
| + problem = queryProblem(q) |
| + } |
| + switch { |
| + case problem != auth.ProblemNone: |
| + st.Problem = problem |
| + case q.Get("reauth") == "1" || a.freshStepUp(r): |
| + // A step-up (max_age): every way id.* offers is local, so the |
| + // door keeps them all and says why it is asking. |
| + st.Problem = auth.ProblemReauth |
| + } |
| + if st.Remembered != nil && (st.Problem == auth.ProblemNone || st.Problem == auth.ProblemReauth) { |
| + st.Step = auth.StepReturning |
| + } |
| + st.ChooseWay(q) |
| + return st |
| +} |
| + |
| +// freshStepUp reports whether this sign-in is a fresh step-up: a live |
| +// assertion intent with max_age (implementation/fresh-assertion.md). |
| +func (a *App) freshStepUp(r *http.Request) bool { |
| + intent, ok := a.readAssertionIntent(r, time.Now()) |
| + return ok && intent.MaxAge != 0 |
| +} |
| + |
| +// doorScreen is door.html's data: estilo's door around rastrillo's |
| +// partial, with the suite's sky and the Oficina mark. |
| +func doorScreen(st auth.SigninState) chrome.SignInScreen { |
| + return chrome.SignInScreen{ |
| + Icon: versioned("/static/brand/icon.svg"), |
| + App: doorName, |
| + Sky: sky.For(sky.SuiteSeed), |
| + State: st, |
| + } |
| +} |
| + |
| +// renderDoor draws one state of the door. Every door response is |
| +// no-store: it may carry the remembered address, and a shared cache or |
| +// the back-forward history keeps a page, not a cookie. |
| +func (a *App) renderDoor(w http.ResponseWriter, r *http.Request, status int, st auth.SigninState) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + if st.Step == auth.StepContinue { |
| + // The page navigates to a URL carrying state and the PKCE |
| + // challenge. |
| + w.Header().Set("Referrer-Policy", "no-referrer") |
| + } |
| + a.render(w, r, status, "door.html", doorScreen(st)) |
| +} |
| + |
| +// doorTarget is where a sign-in drawn for r is going, as rememberReturn |
| +// decides it for a GET of the door. |
| +func doorTarget(r *http.Request) string { |
| + q, err := url.ParseQuery(r.URL.RawQuery) |
| + if err != nil { |
| + return "/" |
| + } |
| + values, present := q["return_to"] |
| + if !present && q.Get("force") == "1" { |
| + return readReturn(r) |
| + } |
| + if len(values) == 1 { |
| + return credentialReturn(values[0]) |
| + } |
| + return "/" |
| +} |
| + |
| +// handleForget is POST /signin/forget, "Use a different email": it forgets |
| +// this browser's remembered way in and opens the email field, keeping |
| +// where the sign-in was going (the posted return_to, else the return |
| +// cookie) and a step-up. Behind csrf.Protect, as every form here is; the |
| +// worst a forged one can do is forget. |
| +func (a *App) handleForget(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + if err := r.ParseForm(); err != nil { |
| + a.errorPage(w, r, http.StatusBadRequest) |
| + return |
| + } |
| + a.forget(w) |
| + target := credentialReturn(r.PostFormValue("return_to")) |
| + if target == "/" { |
| + target = readReturn(r) |
| + } |
| + q := url.Values{} |
| + if auth.ParseWay(r.PostFormValue("way")) == auth.WayEmail { |
| + q.Set("way", string(auth.WayEmail)) |
| + } |
| + if target != "/" { |
| + q.Set("return_to", target) |
| + } |
| + if r.PostFormValue("reauth") == "1" { |
| + q.Set("reauth", "1") |
| + } |
| + to := signinPath |
| + if len(q) > 0 { |
| + to += "?" + q.Encode() |
| + } |
| + http.Redirect(w, r, to, http.StatusSeeOther) |
| +} |
| + |
| +func (a *App) forget(w http.ResponseWriter) { |
| + if a.jar != nil { |
| + a.jar.Clear(w) |
| + } |
| +} |
| + |
| +// forgetChainReturn is where the chained Forget may send the browser: an |
| +// app's own signed-out page, so exactly <registered consumer origin> |
| +// + "/signed-out", no query, no fragment, no userinfo. The URL is built |
| +// from the matched registration, never echoed. Anything else is refused, |
| +// and the caller lands on id.*'s own signed-out page. |
| +func (a *App) forgetChainReturn(raw string) (string, error) { |
| + u, err := url.Parse(raw) |
| + if err != nil || u.User != nil || u.Opaque != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.RawFragment != "" || |
| + u.Path != "/signed-out" || u.RawPath != "" || u.Scheme == "" || u.Host == "" { |
| + return "", errForgetReturn |
| + } |
| + matched, ok := a.consumerOrigin(u.Scheme + "://" + u.Host) |
| + if !ok { |
| + return "", errForgetReturn |
| + } |
| + return matched + "/signed-out", nil |
| +} |
| + |
| +var errForgetReturn = errors.New("home: forget return is not a consumer's signed-out page") |
| + |
| +// handleForgetChainPage is GET /forget?return=<an app's signed-out URL>, |
| +// the second half of a shared computer's sign-out: the app has forgotten |
| +// this browser on its own host, and links here so id.* can forget it too, |
| +// because each host remembers separately. One button, a same-origin POST, |
| +// and a quiet "Not now" back to the app. A GET changes nothing. |
| +func (a *App) handleForgetChainPage(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + back, err := a.forgetChainReturn(r.URL.Query().Get("return")) |
| + data := map[string]any{"Back": "/signed-out"} |
| + if err == nil { |
| + data["Return"], data["Back"] = back, back |
| + // form-action governs the POST's redirect too, so the page names |
| + // the one consumer it may land on (setConsumerPolicy only ever |
| + // adds a registered one). |
| + a.setConsumerPolicy(w, strings.TrimSuffix(back, "/signed-out")) |
| + } |
| + a.render(w, r, http.StatusOK, "id_forget.html", data) |
| +} |
| + |
| +// handleForgetChain is POST /forget: forget this browser on id.*, then |
| +// back to the app's signed-out page if return names one, else id.*'s own. |
| +func (a *App) handleForgetChain(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + if err := r.ParseForm(); err != nil { |
| + a.errorPage(w, r, http.StatusBadRequest) |
| + return |
| + } |
| + a.forget(w) |
| + to := "/signed-out" |
| + if back, err := a.forgetChainReturn(r.PostFormValue("return")); err == nil { |
| + to = back |
| + } |
| + http.Redirect(w, r, to, http.StatusSeeOther) |
| +} |
diff --git a/internal/home/door_browser_test.go b/internal/home/door_browser_test.go| new file mode 100644 |
| index 0000000..c76deff |
| --- /dev/null |
| +++ b/internal/home/door_browser_test.go |
| @@ -0,0 +1,86 @@ |
| +//go:build browser |
| + |
| +package home |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "amadan.net/rastrillo/rastrillo/lastsignin" |
| + "github.com/chromedp/cdproto/emulation" |
| + "github.com/chromedp/cdproto/network" |
| + "github.com/chromedp/chromedp" |
| +) |
| + |
| +// The door in a real Chrome with a virtual authenticator. The email |
| +// field's autofill (conditional UI) signs a passkey holder in by itself; |
| +// from the chooser, a passkey is signed in by rastrillo's own module |
| +// against Home's {ok,to} finish, landing where the sign-in was going. |
| +// The next visit offers the passkey first, and its button is enabled by |
| +// the module. With script off, that door says |
| +// passkeys need JavaScript and its Other ways still opens the email way. |
| +func TestDoorBrowserChooserPasskeyAndReturn(t *testing.T) { |
| + p, ctx, _ := idBrowser(t) |
| + s := signInFully(t, p.credential, sealtest.CanaryAddress) |
| + idBrowserRun(t, ctx, idBrowserCookie(s), chromedp.Navigate(browserIssuer+"/passkey/enrol"), chromedp.WaitVisible("#passkey-enrol"), chromedp.Click("#passkey-enrol"), chromedp.WaitVisible(`form[action="/passkey/codes"]`)) |
| + idBrowserRun(t, ctx, cdpStep(network.DeleteCookies, network.DeleteCookiesParams{Name: s.Name, URL: browserIssuer + "/"})) |
| + |
| + // First visit: the field, with passkeys offered in its autofill (the |
| + // door's markup is checked in TestDoorStates; it is the only way in on |
| + // this page that runs without a press). |
| + idBrowserRun(t, ctx, chromedp.Navigate(browserIssuer+"/signin?return_to=%2Fpasskey%2Fcodes")) |
| + // With one discoverable credential and presence simulated, the virtual |
| + // authenticator answers the field's conditional request by itself: the |
| + // module begins, gets, finishes against {ok,to} and navigates to where |
| + // the sign-in was going, with nobody pressing anything. |
| + idBrowserRun(t, ctx, chromedp.WaitVisible(`form[action="/passkey/codes"]`)) |
| + var conditional bool |
| + idBrowserRun(t, ctx, harness.Into(&conditional, chromedp.Evaluate[bool](`PublicKeyCredential.isConditionalMediationAvailable()`, chromedp.EvalAwaitPromise))) |
| + if !conditional { |
| + t.Fatal("this Chrome reports no conditional mediation") |
| + } |
| + var location string |
| + idBrowserRun(t, ctx, harness.Into(&location, chromedp.Location())) |
| + if !strings.HasPrefix(location, browserIssuer+"/passkey/codes") { |
| + t.Fatal("conditional UI did not sign in to where the sign-in was going", location) |
| + } |
| + idBrowserRun(t, ctx, cdpStep(network.DeleteCookies, network.DeleteCookiesParams{Name: s.Name, URL: browserIssuer + "/"}), |
| + cdpStep(network.DeleteCookies, network.DeleteCookiesParams{Name: jarCookie, URL: browserIssuer + "/"})) |
| + |
| + // This browser proved the address once (a sealed record, as a link |
| + // sign-in writes). Other ways, then a passkey, then the button the |
| + // module enables: the passkey's owner is the same person, so the |
| + // address is kept. |
| + remembered := sealedRecord(t, p.credential.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: sealtest.CanaryAddress}) |
| + idBrowserRun(t, ctx, idBrowserCookie(remembered), |
| + chromedp.Navigate(browserIssuer+"/signin?return_to=%2Fpasskey%2Fcodes&ways=1&way=email"), chromedp.WaitVisible(`a[href*="way=passkey"]`), |
| + chromedp.Click(`a[href*="way=passkey"]`), chromedp.WaitVisible(`button[data-rst-passkey]:enabled`), |
| + chromedp.Click(`button[data-rst-passkey]`), chromedp.WaitVisible(`form[action="/passkey/codes"]`)) |
| + idBrowserRun(t, ctx, harness.Into(&location, chromedp.Location())) |
| + if !strings.HasPrefix(location, browserIssuer+"/passkey/codes") { |
| + t.Fatal("the passkey sign-in lost where it was going", location) |
| + } |
| + |
| + // The next visit offers the passkey first, enabled by the module. |
| + idBrowserRun(t, ctx, cdpStep(network.DeleteCookies, network.DeleteCookiesParams{Name: s.Name, URL: browserIssuer + "/"}), |
| + chromedp.Navigate(browserIssuer+"/signin"), chromedp.WaitVisible(`button[data-rst-passkey]:enabled`)) |
| + var label string |
| + idBrowserRun(t, ctx, harness.Into(&label, chromedp.Text(`button[data-rst-passkey]`))) |
| + if !strings.Contains(label, "Sign in with your passkey") { |
| + t.Fatal("the next visit does not offer the passkey first", label) |
| + } |
| + |
| + // Script off: the noscript line, and Other ways opens the email way, |
| + // the address kept. |
| + idBrowserRun(t, ctx, cdpStep(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}), |
| + chromedp.Navigate(browserIssuer+"/signin"), chromedp.WaitVisible(`a[href*="ways=1"]`), |
| + chromedp.Click(`a[href*="ways=1"]`), chromedp.WaitVisible(`a[href*="way=email"]`), |
| + chromedp.Click(`a[href*="way=email"]`), chromedp.WaitVisible(`form[action="/signin"] button[type="submit"]`)) |
| + var html string |
| + idBrowserRun(t, ctx, harness.Into(&html, chromedp.OuterHTML("main"))) |
| + if !strings.Contains(html, sealtest.CanaryAddress) { |
| + t.Fatal("the email way lost the remembered address") |
| + } |
| +} |
diff --git a/internal/home/door_copy_test.go b/internal/home/door_copy_test.go| index 141a765..41e298a 100644 |
| --- a/internal/home/door_copy_test.go |
| +++ b/internal/home/door_copy_test.go |
| @@ -7,14 +7,16 @@ import ( |
| "testing" |
| ) |
| -// The door's words are estilo's chrome.English, the one copy set every |
| -// app's door renders (Paul, 2026-10-01: the submit reads "Sign in", never |
| -// "Continue" or "Email me a link"). They are pinned here as literals, not |
| -// read back from chrome.English, so a change upstream shows up as a red |
| -// test on the hub rather than as silently different copy. |
| +// The door's words. The sign-in door itself is rastrillo's one-way screen |
| +// (smart-door spec: "Unless marked new, all copy is rastrillo's approved |
| +// copy"; on id.* the field's submit is Continue, which the spec's door |
| +// table names and which supersedes, for this door, the 2026-10-01 "Sign |
| +// in" ruling for estilo's form). The pages around it keep estilo's |
| +// chrome.English. Both are pinned here as literals, not read back from |
| +// the libraries, so a change upstream shows up as a red test on the hub |
| +// rather than as silently different copy. |
| const ( |
| - doorHelp = "We’ll email you a link that signs you in. It works once and expires in 15 minutes." |
| - doorSentBody = "If that address can sign in here, we’ve sent it a link. It works once and expires in 15 minutes." |
| + doorSentBody = "We sent a link to your inbox. The link works once and expires soon." |
| ) |
| func getCredential(t *testing.T, app *testApp, path string) string { |
| @@ -52,19 +54,20 @@ func TestDoorSpeaksTheSuiteCopy(t *testing.T) { |
| form := getCredential(t, app, "/signin") |
| mustContain(t, "/signin", form, |
| - "<title>Sign in · Oficina</title>", |
| - "<h1>Sign in</h1>", |
| - ">Email address</label>", |
| - doorHelp, |
| - `<button type="submit" rst-btn="primary">Sign in</button>`) |
| - mustNotContain(t, "/signin", form, ">Continue<", "Email me a link", "Home") |
| + "<title>Sign in to Oficina ID</title>", |
| + `<h1 id="rst-signin-heading">Sign in to Oficina ID</h1>`, |
| + `>Email</label>`, |
| + `<button rst-btn="primary block" type="submit">Continue</button>`, |
| + "<span>Other ways to sign in</span>") |
| + mustNotContain(t, "/signin", form, "Email me a link", "Home") |
| sent := getCredential(t, app, "/signin/sent") |
| mustContain(t, "/signin/sent", sent, |
| - "<title>Check your email · Oficina</title>", |
| - "<h1>Check your email</h1>", |
| + "<title>Check your email to sign in to Oficina ID</title>", |
| + `<h1 id="rst-signin-heading">Check your email</h1>`, |
| doorSentBody, |
| - `<a href="/signin">Use a different address</a>`) |
| + `<form rst-signin-form method="post" action="/signin/forget">`, |
| + "<span>Use a different email</span>") |
| mustNotContain(t, "/signin/sent", sent, "fifteen", "Check your mail", "Home") |
| failed := redeem(t, app, "not-a-token").Body.String() |
diff --git a/internal/home/door_gates_test.go b/internal/home/door_gates_test.go| new file mode 100644 |
| index 0000000..5818b5e |
| --- /dev/null |
| +++ b/internal/home/door_gates_test.go |
| @@ -0,0 +1,202 @@ |
| +package home |
| + |
| +import ( |
| + "log" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/go-chi/chi/v5" |
| + |
| + "amadan.net/oficina/home/internal/home/logtest" |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/lastsignin" |
| +) |
| + |
| +// The privacy gates against the door's remembered address (ruling 26). |
| +// The cookie's name is not secret and its ciphertext differs on every |
| +// seal, so neither is a useful canary: each gate is driven with a VALIDLY |
| +// SEALED cookie whose address is a canary. |
| + |
| +// credentialRoutes walks a credential router: every declared (method, |
| +// path), with route parameters filled by a canary. |
| +func credentialRoutes(t *testing.T, h http.Handler) [][2]string { |
| + t.Helper() |
| + routes, ok := h.(chi.Routes) |
| + if !ok { |
| + t.Fatalf("router is %T, not chi.Routes", h) |
| + } |
| + var out [][2]string |
| + seen := map[[2]string]bool{} |
| + if err := chi.Walk(routes, func(method, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { |
| + path := fillParams(strings.ReplaceAll(route, "/*", "/x")) |
| + for _, m := range []string{method, http.MethodGet, http.MethodPost} { |
| + if k := [2]string{m, path}; !seen[k] { |
| + seen[k] = true |
| + out = append(out, k) |
| + } |
| + } |
| + return nil |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(out) < 20 { |
| + t.Fatalf("walked %d routes: the gate would pass by not looking", len(out)) |
| + } |
| + return out |
| +} |
| + |
| +// Gate 9 (§12) with the door's cookie: every route on the credential |
| +// origin, driven with a validly sealed cookie whose address is a canary |
| +// (as the cookie a person's browser actually carries), plus full sign-ins |
| +// that read and rewrite it, logs the address nowhere: neither the app's |
| +// logger nor the default. |
| +func TestNoContentInLogsWithTheDoorCookie(t *testing.T) { |
| + rec := logtest.NewRecorder() |
| + prevLogger, prevWriter, prevFlags := slog.Default(), log.Writer(), log.Flags() |
| + slog.SetDefault(slog.New(rec.Handler())) |
| + t.Cleanup(func() { |
| + slog.SetDefault(prevLogger) |
| + log.SetOutput(prevWriter) |
| + log.SetFlags(prevFlags) |
| + }) |
| + p := newExchangePair(t) |
| + app := p.credential |
| + app.logger = slog.New(rec.Handler()) |
| + canary := logtest.Canaries[0] |
| + for _, method := range []string{lastsignin.MethodMagicLink, lastsignin.MethodKeymail, lastsignin.MethodPasskey} { |
| + cookie := sealedRecord(t, app.App, lastsignin.Record{Method: method, Address: canary}) |
| + if !strings.Contains(doorGet(t, app, "/signin?way=email", cookie).Body.String(), canary) { |
| + t.Fatal("the canary cookie does not reach the door: the gate would scan nothing") |
| + } |
| + session := signInFully(t, app, "logs-session@example.invalid") |
| + for _, rt := range credentialRoutes(t, app.Router()) { |
| + for _, withSession := range []bool{false, true} { |
| + body := url.Values{"address": {canary}, "return_to": {"/authorize/resume"}, "way": {"email"}, "return": {"https://" + logtest.Canaries[1] + ".example/signed-out"}}.Encode() |
| + req := httptest.NewRequest(rt[0], Origin+rt[1]+"?ways=1&way=passkey&err=x&return="+url.QueryEscape(canary), strings.NewReader(body)) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Origin", Origin) |
| + req.Header.Set("Accept", "text/html") |
| + req.AddCookie(cookie) |
| + if withSession { |
| + req.AddCookie(session) |
| + } |
| + app.Router().ServeHTTP(httptest.NewRecorder(), req) |
| + } |
| + } |
| + // The CSRF refusal sees the cookie too. |
| + req := httptest.NewRequest("POST", Origin+forgetPath, strings.NewReader("way=email")) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Sec-Fetch-Site", "cross-site") |
| + req.AddCookie(cookie) |
| + app.Router().ServeHTTP(httptest.NewRecorder(), req) |
| + } |
| + // The sign-ins that write the cookie, with the canary address: a link, |
| + // a passkey that keeps it (same person), and one that blanks it. |
| + signIn(t, app, strings.ToLower(canary)) |
| + linked := redeem(t, app, capturedLink(t, app)) |
| + written, _ := jarSet(linked) |
| + if written == nil { |
| + t.Fatal("the canary sign-in remembered nothing") |
| + } |
| + key := enrol(t, app, sessionCookie(linked)) |
| + directPasskey(t, app, key, written) |
| + directPasskey(t, app, key, sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "other-" + strings.ToLower(canary)})) |
| + rec.AssertNoContent(t) |
| +} |
| + |
| +// Gate 5 (§12, amended by ruling 26): the credential origin renders no |
| +// account-authored string, except exactly one, the address Home sealed |
| +// into this browser's cookie, and only on the door. Every credential page |
| +// is drawn with the canary cookie present, signed out and signed in; only |
| +// the door's own sign-in states may show it, and none shows an address |
| +// that arrived any other way: typed into the form, put in the query, or |
| +// in a cookie Home did not seal. |
| +func TestDoorRendersOnlyTheAddressItSealed(t *testing.T) { |
| + p := newExchangePair(t) |
| + app := p.credential |
| + const canary = sealtest.CanaryAddress |
| + cookie := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: canary}) |
| + session := signInFully(t, app, "gate5-session@example.invalid") |
| + door := map[string]bool{"/signin": true} |
| + shown := 0 |
| + for _, rt := range credentialRoutes(t, app.Router()) { |
| + for _, withSession := range []bool{false, true} { |
| + cookies := []*http.Cookie{cookie} |
| + if withSession { |
| + cookies = append(cookies, session) |
| + } |
| + var form url.Values |
| + if rt[0] == http.MethodPost { |
| + form = url.Values{"address": {"typed-canary@example.invalid"}} |
| + } |
| + target := Origin + rt[1] |
| + if door[rt[1]] { |
| + // The door's own query: an address there is never shown. |
| + target += "?address=query-canary%40example.invalid" |
| + } |
| + r := exchangeRequest(app.App, rt[0], target, Origin, form, cookies...) |
| + body := strings.ToLower(r.Body.String()) |
| + for _, never := range []string{"typed-canary", "query-canary"} { |
| + if strings.Contains(body, never) { |
| + t.Errorf("%s %s rendered an address it did not seal (%s)", rt[0], rt[1], never) |
| + } |
| + } |
| + if strings.Contains(body, canary) { |
| + shown++ |
| + if !door[rt[1]] { |
| + t.Errorf("%s %s rendered the remembered address off the door", rt[0], rt[1]) |
| + } |
| + if r.Header().Get("Cache-Control") != "no-store" { |
| + t.Errorf("%s %s rendered the address on a cacheable page", rt[0], rt[1]) |
| + } |
| + } |
| + } |
| + } |
| + if shown == 0 { |
| + t.Fatal("the door never showed the sealed address: the gate checked nothing") |
| + } |
| + // The door draws it only as text and in a hidden value, escaped. |
| + hostile := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: `"><script>x</script>@example.invalid`}) |
| + body := doorGet(t, app, "/signin", hostile).Body.String() |
| + if strings.Contains(body, "<script>x</script>") || !strings.Contains(body, ""><script>x</script>@example.invalid") { |
| + t.Fatal("the remembered address was not escaped") |
| + } |
| + // A posted address is never echoed, even on the door, even valid. |
| + limited := returnRequest(app, "POST", "/signin", url.Values{"address": {"posted-canary"}}) |
| + if strings.Contains(limited.Body.String(), "posted-canary") { |
| + t.Fatal("a posted address was echoed") |
| + } |
| +} |
| + |
| +// Gates 1 and 2, the sign-in half, with the door after: a full email |
| +// sign-in and a passkey sign-in that keeps the address, each followed by |
| +// loading the door with the cookie they wrote (which shows the address), |
| +// leave no readable address in the database, its WAL or its SHM. The door |
| +// reads the cookie and consults no store; the same-person check reads the |
| +// blind index and writes nothing. |
| +func TestDoorLeavesNoReadableAddressAtRest(t *testing.T) { |
| + app := newTestApp(t) |
| + signIn(t, app, sealtest.CanaryAddress) |
| + linked := redeem(t, app, capturedLink(t, app)) |
| + written, _ := jarSet(linked) |
| + if written == nil || !strings.Contains(doorGet(t, app, "/signin", written).Body.String(), sealtest.CanaryAddress) { |
| + t.Fatal("the door does not show the address the sign-in remembered") |
| + } |
| + sealtest.AssertNoPlaintext(t, app.dbPath) |
| + key := enrol(t, app, sessionCookie(linked)) |
| + done := directPasskey(t, app, key, written) |
| + kept, _ := jarSet(done) |
| + if kept == nil || readJar(t, app.App, kept).Address != sealtest.CanaryAddress { |
| + t.Fatal("the same person's passkey sign-in did not keep the address") |
| + } |
| + for _, path := range []string{"/signin", "/signin?ways=1&way=passkey", "/signin?way=email", "/signin/sent"} { |
| + doorGet(t, app, path, kept) |
| + } |
| + returnRequest(app, "POST", "/signin", url.Values{"address": {"bad"}}, kept) |
| + returnRequest(app, "POST", forgetPath, url.Values{"way": {"email"}}, kept) |
| + sealtest.AssertNoPlaintext(t, app.dbPath) |
| +} |
diff --git a/internal/home/door_test.go b/internal/home/door_test.go| new file mode 100644 |
| index 0000000..91225f6 |
| --- /dev/null |
| +++ b/internal/home/door_test.go |
| @@ -0,0 +1,602 @@ |
| +package home |
| + |
| +import ( |
| + "encoding/hex" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/home/internal/home/seal" |
| + "amadan.net/oficina/home/internal/home/sealtest" |
| + "amadan.net/rastrillo/rastrillo/lastsignin" |
| + "amadan.net/rastrillo/rastrillo/webauthn/authtest" |
| +) |
| + |
| +// The smart door on id.* (door.go, smart-door spec step 5): every state |
| +// the door answers, what it remembers and when, the same-person check, |
| +// Forget, and the return memory across the chooser. |
| + |
| +const jarCookie = "__Host-rastrillo_last_signin" |
| + |
| +// sealedRecord is rec as this app's jar seals it: a validly sealed cookie. |
| +func sealedRecord(t *testing.T, app *App, rec lastsignin.Record) *http.Cookie { |
| + t.Helper() |
| + w := httptest.NewRecorder() |
| + app.jar.Remember(w, rec) |
| + for _, c := range w.Result().Cookies() { |
| + if c.Name == jarCookie && c.Value != "" { |
| + return c |
| + } |
| + } |
| + t.Fatalf("the jar sealed nothing for %+v", rec) |
| + return nil |
| +} |
| + |
| +// jarSet is the jar cookie a response set, or nil; cleared reports a |
| +// deletion. |
| +func jarSet(r *httptest.ResponseRecorder) (set *http.Cookie, cleared bool) { |
| + for _, c := range r.Result().Cookies() { |
| + if c.Name != jarCookie { |
| + continue |
| + } |
| + if c.MaxAge < 0 || c.Value == "" { |
| + cleared = true |
| + continue |
| + } |
| + set = c |
| + } |
| + return set, cleared |
| +} |
| + |
| +// readJar opens a jar cookie with the app's own jar. |
| +func readJar(t *testing.T, app *App, c *http.Cookie) lastsignin.Record { |
| + t.Helper() |
| + req := httptest.NewRequest("GET", Origin+"/signin", nil) |
| + req.AddCookie(c) |
| + rec, res := app.jar.Read(req) |
| + if res != lastsignin.Valid { |
| + t.Fatalf("jar cookie reads as %v", res) |
| + } |
| + return rec |
| +} |
| + |
| +func doorGet(t *testing.T, app *testApp, path string, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := returnRequest(app, "GET", path, nil, cookies...) |
| + if r.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("GET %s: door response is cacheable (%d)", path, r.Code) |
| + } |
| + return r |
| +} |
| + |
| +// The jar's key is HOME_DEK's, derived under home/lastsignin/v1, and its |
| +// origin is the credential origin: a cookie sealed under another label, |
| +// another DEK or another origin reads as Invalid, and the door clears it |
| +// and shows nothing of it. |
| +func TestDoorJarIsDerivedFromHomeDEKAndBoundToTheOrigin(t *testing.T) { |
| + app := newTestApp(t) |
| + if app.jar.CookieName() != jarCookie { |
| + t.Fatalf("cookie %q, want the __Host- one", app.jar.CookieName()) |
| + } |
| + good := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) |
| + if !good.Secure || !good.HttpOnly || good.Path != "/" || good.Domain != "" || good.SameSite != http.SameSiteLaxMode { |
| + t.Fatalf("jar cookie attributes: %+v", good) |
| + } |
| + if body := doorGet(t, app, "/signin", good).Body.String(); !strings.Contains(body, "Continue as <bdi>kept@example.invalid</bdi>") { |
| + t.Fatal("a validly sealed cookie was not shown back") |
| + } |
| + dek := make([]byte, 32) |
| + for i := range dek { |
| + dek[i] = byte(i) |
| + } |
| + other := func(label string, dek []byte, origin string) *http.Cookie { |
| + s, err := seal.New(dek) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + key, err := s.Derive(label) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + jar, err := lastsignin.New(lastsignin.Config{Origin: origin, InstanceKey: hex.EncodeToString(key), Mode: lastsignin.On}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + w := httptest.NewRecorder() |
| + jar.Remember(w, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "forged@example.invalid"}) |
| + return w.Result().Cookies()[0] |
| + } |
| + // The control: the same construction with Home's own inputs is read. |
| + if body := doorGet(t, app, "/signin", other(jarLabel, dek, Origin)).Body.String(); !strings.Contains(body, "forged@example.invalid") { |
| + t.Fatal("the jar is not HOME_DEK under home/lastsignin/v1 at the credential origin") |
| + } |
| + wrongDEK := append([]byte(nil), dek...) |
| + wrongDEK[0] ^= 1 |
| + for name, c := range map[string]*http.Cookie{ |
| + "label": other("home/lastsignin/v2", dek, Origin), |
| + "dek": other(jarLabel, wrongDEK, Origin), |
| + "origin": other(jarLabel, dek, directoryOrigin), |
| + "junk": {Name: jarCookie, Value: "not-a-sealed-value"}, |
| + } { |
| + r := doorGet(t, app, "/signin", c) |
| + if strings.Contains(r.Body.String(), "forged@example.invalid") { |
| + t.Fatalf("%s: a cookie the jar did not seal was shown", name) |
| + } |
| + if _, cleared := jarSet(r); !cleared { |
| + t.Fatalf("%s: an unbelievable cookie was not cleared", name) |
| + } |
| + } |
| +} |
| + |
| +// Every state of the door, drawn by rastrillo's partial: what the one |
| +// option is, what Other ways lists, and that the address appears only |
| +// where a sealed cookie put it. |
| +func TestDoorStates(t *testing.T) { |
| + app := newTestApp(t) |
| + const addr = "remembered@example.invalid" |
| + link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: addr}) |
| + keymail := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodKeymail, Address: addr}) |
| + passkey := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodPasskey, Address: addr}) |
| + bare := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodPasskey}) |
| + const rt = "return_to=%2Fauthorize%2Fresume" |
| + field := `<input rst-input type="email" id="rst-signin-email" name="address"` |
| + conditional := `data-rst-passkey-conditional data-rst-passkey-begin="/passkey/direct/begin" data-rst-passkey-finish="/passkey/direct/finish?return_to=%2Fauthorize%2Fresume" data-rst-passkey-module="/static/webauthn.mjs"` |
| + passkeyDoor := `<button rst-btn="primary block" type="button" disabled data-rst-passkey data-rst-passkey-begin="/passkey/direct/begin"` |
| + cases := []struct { |
| + name string |
| + path string |
| + cookie *http.Cookie |
| + want []string |
| + notWant []string |
| + }{ |
| + {"first visit: the field, passkeys in its autofill", "/signin?" + rt, nil, |
| + []string{field, `autocomplete="username webauthn"`, conditional, `<script type="module" src="/static/signin.mjs"></script>`, `<button rst-btn="primary block" type="submit">Continue</button>`, |
| + `href="/signin?return_to=%2Fauthorize%2Fresume&way=email&ways=1"><span>Other ways to sign in</span>`}, |
| + []string{"Continue as", "data-rst-passkey-fallback", "@example.invalid"}}, |
| + {"first visit's chooser: a passkey, and Back", "/signin?ways=1&way=email&" + rt, nil, |
| + []string{"<h1 id=\"rst-signin-heading\">Other ways to sign in</h1>", `href="/signin?return_to=%2Fauthorize%2Fresume&way=passkey"`, "<span>Sign in with a passkey</span>", |
| + `href="/signin?return_to=%2Fauthorize%2Fresume&way=email"><svg`, "<span>Back</span>"}, |
| + []string{"Use a different email", field}}, |
| + {"passkey remembered: the passkey, drawn visible and disabled", "/signin?" + rt, passkey, |
| + []string{passkeyDoor, "<span>Sign in with your passkey</span>", `data-rst-passkey-fallback="/signin?return_to=%2Fauthorize%2Fresume&way=email"`, |
| + "<noscript><p>To use a passkey, turn on JavaScript.</p></noscript>", `href="/signin?return_to=%2Fauthorize%2Fresume&way=passkey&ways=1"`}, |
| + []string{field, addr, " hidden data-rst-passkey"}}, |
| + {"passkey remembered, chooser: Email with the kept address, Use a different email", "/signin?ways=1&way=passkey&" + rt, passkey, |
| + []string{"<span>Email <bdi>" + addr + "</bdi></span>", `action="/signin/forget"><input type="hidden" name="return_to" value="/authorize/resume">`, "<span>Use a different email</span>", "<span>Back</span>"}, |
| + []string{"Sign in with a passkey"}}, |
| + {"passkey remembered without an address", "/signin?ways=1&way=passkey", bare, |
| + []string{"<span>Email</span>", "<span>Use a different email</span>"}, |
| + []string{"<bdi>"}}, |
| + {"link remembered: Continue as", "/signin?" + rt, link, |
| + []string{"Continue as <bdi>" + addr + "</bdi>", `<input type="hidden" name="address" value="` + addr + `">`, "<span>Other ways to sign in</span>"}, |
| + []string{field, passkeyDoor}}, |
| + {"link remembered, chooser: a passkey and Use a different email", "/signin?ways=1&way=email&" + rt, link, |
| + []string{"<span>Sign in with a passkey</span>", "<span>Use a different email</span>"}, |
| + []string{"Continue as"}}, |
| + {"keymail remembered: Continue to Keymail, as the address", "/signin", keymail, |
| + []string{">Continue to Keymail</button>", "as <bdi>" + addr + "</bdi>", `name="expect" value="keymail"`}, |
| + []string{field}}, |
| + {"way=email on a remembered passkey: the address's one-tap", "/signin?way=email", passkey, |
| + []string{"Continue as <bdi>" + addr + "</bdi>"}, []string{passkeyDoor}}, |
| + {"way=passkey on a remembered link: the passkey door", "/signin?way=passkey", link, |
| + []string{passkeyDoor, "<span>Sign in with a passkey</span>"}, []string{"Continue as"}}, |
| + {"a way picks a method, never an address", "/signin?way=email&address=typed%40example.invalid", nil, |
| + []string{field}, []string{"typed@example.invalid"}}, |
| + {"force=1 (a failed Keymail): the field, force kept, prefilled from the cookie", "/signin?force=1", keymail, |
| + []string{`action="/signin?force=1"`, `<input type="hidden" name="force" value="1">`, `value="` + addr + `"`, field}, |
| + []string{"Continue to Keymail"}}, |
| + {"err=keymail: the field and the problem", "/signin?err=keymail", link, |
| + []string{"Keymail couldn't confirm it's you.", field, ">Send me a link instead</button>"}, []string{"Continue as"}}, |
| + {"err=rate", "/signin?err=rate", nil, []string{"Too many tries. Try again in a few minutes.", field}, nil}, |
| + {"err=expired", "/signin?err=expired", nil, []string{"That link has expired or was already used. Send a new one.", field}, nil}, |
| + {"err=address", "/signin?err=address", nil, []string{"That doesn't look like an email address.", field}, nil}, |
| + {"an unknown err is the generic problem", "/signin?err=whatever&ways=1", passkey, |
| + []string{"Something went wrong. Try again.", field}, []string{"Other ways to sign in</h1>", passkeyDoor}}, |
| + {"reauth=1: a step-up keeps the ways and says why", "/signin?reauth=1", passkey, |
| + []string{"Sign in again to continue.", passkeyDoor, "reauth=1"}, nil}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + var cookies []*http.Cookie |
| + if c.cookie != nil { |
| + cookies = append(cookies, c.cookie) |
| + } |
| + r := doorGet(t, app, c.path, cookies...) |
| + if r.Code != 200 { |
| + t.Fatal(r.Code) |
| + } |
| + body := r.Body.String() |
| + for _, w := range c.want { |
| + if !strings.Contains(body, w) { |
| + t.Errorf("missing %q", w) |
| + } |
| + } |
| + for _, n := range c.notWant { |
| + if strings.Contains(body, n) { |
| + t.Errorf("unexpected %q", n) |
| + } |
| + } |
| + if strings.Contains(body, `data-rst-passkey-legacy-rpid`) { |
| + t.Error("a legacy RP ID on the door") |
| + } |
| + if t.Failed() { |
| + t.Log(body) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A fresh step-up (max_age) asks again on the same door: the reauth notice |
| +// over the way this browser used last, every way still offered (each of |
| +// id.*'s ways is local), and reauth carried on every link. |
| +func TestDoorStepUpOffersLocalWays(t *testing.T) { |
| + p := newExchangePair(t) |
| + intent, navigation := freshSignInForm(t, p, nil) |
| + remembered := sealedRecord(t, p.credential.App, lastsignin.Record{Method: lastsignin.MethodPasskey}) |
| + r := exchangeRequest(p.credential.App, "GET", Origin+"/signin?return_to=%2Fauthorize%2Fresume", "", nil, intent, navigation, remembered) |
| + body := r.Body.String() |
| + for _, want := range []string{"Sign in again to continue.", "<span>Sign in with your passkey</span>", "way=passkey&ways=1"} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("step-up door missing %q", want) |
| + } |
| + } |
| + chooser := exchangeRequest(p.credential.App, "GET", Origin+"/signin?return_to=%2Fauthorize%2Fresume&ways=1&way=passkey", "", nil, intent, navigation, remembered).Body.String() |
| + if !strings.Contains(chooser, "reauth=1") || !strings.Contains(chooser, `name="reauth" value="1"`) { |
| + t.Error("the chooser dropped the step-up") |
| + } |
| + if r.Header().Get("Cache-Control") != "no-store" { |
| + t.Error("cacheable step-up door") |
| + } |
| +} |
| + |
| +// A failed Begin redraws the field door with the problem and the right |
| +// status, prefilled from the cookie and never from what was posted. |
| +func TestDoorBeginFailures(t *testing.T) { |
| + app := newTestApp(t) |
| + keymail := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodKeymail, Address: "kept@example.invalid"}) |
| + bad := returnRequest(app, "POST", "/signin", url.Values{"address": {"typed-not-an-address"}}, keymail) |
| + body := bad.Body.String() |
| + if bad.Code != 400 || bad.Header().Get("Cache-Control") != "no-store" || |
| + !strings.Contains(body, "That doesn't look like an email address.") || !strings.Contains(body, `value="kept@example.invalid"`) || strings.Contains(body, "typed-not-an-address") { |
| + t.Fatalf("bad address: %d\n%s", bad.Code, body) |
| + } |
| + forced := returnRequest(app, "POST", "/signin?force=1", url.Values{"address": {"nope"}}) |
| + if !strings.Contains(forced.Body.String(), `action="/signin?force=1"`) { |
| + t.Fatal("a forced retry's error dropped force") |
| + } |
| + limited := app |
| + var last *httptest.ResponseRecorder |
| + for i := 0; i < 30; i++ { |
| + last = returnRequest(limited, "POST", "/signin", url.Values{"address": {"many@example.invalid"}}) |
| + if last.Code == http.StatusTooManyRequests { |
| + break |
| + } |
| + } |
| + if last.Code != http.StatusTooManyRequests || !strings.Contains(last.Body.String(), "Too many tries. Try again in a few minutes.") || last.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatal("rate limit", last.Code) |
| + } |
| +} |
| + |
| +// Sent stays address-free (Home's is by design), even with a remembered |
| +// address, and keeps "Use a different email". |
| +func TestDoorSentIsAddressFree(t *testing.T) { |
| + app := newTestApp(t) |
| + link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) |
| + r := doorGet(t, app, "/signin/sent?attempt=x&ways=1", link) |
| + body := r.Body.String() |
| + if !strings.Contains(body, "We sent a link to your inbox.") || strings.Contains(body, "kept@example.invalid") || !strings.Contains(body, "<span>Use a different email</span>") { |
| + t.Fatal(body) |
| + } |
| +} |
| + |
| +// What the door remembers, and when: a proven link, a Keymail callback, |
| +// and a passkey (direct, and a finished gate), with the address kept on a |
| +// passkey record only for the same person. |
| +func TestDoorRemembersProvenSignIns(t *testing.T) { |
| + t.Run("magic link", func(t *testing.T) { |
| + app := newTestApp(t) |
| + signIn(t, app, "linked@example.invalid") |
| + if c, _ := jarSet(redeem(t, app, "nope")); c != nil { |
| + t.Fatal("a failed redemption remembered something") |
| + } |
| + r := redeem(t, app, capturedLink(t, app)) |
| + c, _ := jarSet(r) |
| + if c == nil { |
| + t.Fatal("a proven link remembered nothing") |
| + } |
| + if got := readJar(t, app.App, c); got.Method != lastsignin.MethodMagicLink || got.Address != "linked@example.invalid" { |
| + t.Fatalf("remembered %+v", got) |
| + } |
| + if c, _ := jarSet(signIn(t, app, "unproven@example.invalid")); c != nil { |
| + t.Fatal("Begin remembered an address nobody has proved") |
| + } |
| + }) |
| + t.Run("keymail", func(t *testing.T) { |
| + app := newTestApp(t) |
| + const addr = "person@keymail.invalid" |
| + newKeymailStub(t, app, addr) |
| + pending, state := beginKeymail(t, app, addr) |
| + c, _ := jarSet(callback(t, app, "code-1", state, pending)) |
| + if c == nil { |
| + t.Fatal("a Keymail callback remembered nothing") |
| + } |
| + if got := readJar(t, app.App, c); got.Method != lastsignin.MethodKeymail || got.Address != addr { |
| + t.Fatalf("remembered %+v", got) |
| + } |
| + if c, _ := jarSet(callback(t, app, "code-2", "bad-state", pending)); c != nil { |
| + t.Fatal("a failed callback remembered something") |
| + } |
| + }) |
| + for _, kind := range []string{"same person", "another person", "nothing remembered", "unbelievable"} { |
| + t.Run("direct passkey, "+kind, func(t *testing.T) { |
| + app := newTestApp(t) |
| + owner := "owner@example.invalid" |
| + key := enrol(t, app, signInFully(t, app, owner)) |
| + signInFully(t, app, "someone-else@example.invalid") |
| + var prior *http.Cookie |
| + want := "" |
| + switch kind { |
| + case "same person": |
| + prior = sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "OWNER@example.invalid"}) |
| + want = "OWNER@example.invalid" |
| + case "another person": |
| + prior = sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "someone-else@example.invalid"}) |
| + case "unbelievable": |
| + prior = &http.Cookie{Name: jarCookie, Value: "junk"} |
| + } |
| + done := directPasskey(t, app, key, prior) |
| + c, _ := jarSet(done) |
| + if c == nil { |
| + t.Fatal("a passkey sign-in remembered nothing") |
| + } |
| + if got := readJar(t, app.App, c); got.Method != lastsignin.MethodPasskey || got.Address != want { |
| + t.Fatalf("remembered %+v, want passkey with %q", got, want) |
| + } |
| + }) |
| + } |
| + t.Run("a refused passkey remembers nothing", func(t *testing.T) { |
| + app := newTestApp(t) |
| + enrol(t, app, signInFully(t, app, "owner@example.invalid")) |
| + stranger, _ := authtest.New() |
| + if c, _ := jarSet(directPasskey(t, app, stranger, nil)); c != nil { |
| + t.Fatal("a refused finish remembered a passkey") |
| + } |
| + }) |
| + t.Run("gate", func(t *testing.T) { |
| + app := newTestApp(t) |
| + const addr = "gated@example.invalid" |
| + key := enrol(t, app, signInFully(t, app, addr)) |
| + signIn(t, app, addr) |
| + first := redeem(t, app, capturedLink(t, app)) |
| + emailed, _ := jarSet(first) |
| + if first.Header().Get("Location") != confirmPath || emailed == nil || readJar(t, app.App, emailed).Address != addr { |
| + t.Fatal("the first factor was not remembered before the gate", first.Header().Get("Location")) |
| + } |
| + gate := namedCookie(t, first, gateCookie) |
| + begin := idJSON(t, app, "/passkey/signin/begin", nil, gate) |
| + zero := uint32(0) |
| + done := idJSON(t, app, "/passkey/signin/finish", assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}), gate, emailed) |
| + c, _ := jarSet(done) |
| + if done.Code != 200 || c == nil { |
| + t.Fatal("a finished gate remembered nothing", done.Code) |
| + } |
| + if got := readJar(t, app.App, c); got.Method != lastsignin.MethodPasskey || got.Address != addr { |
| + t.Fatalf("remembered %+v", got) |
| + } |
| + if body := doorGet(t, app, "/signin", c).Body.String(); !strings.Contains(body, "<span>Sign in with your passkey</span>") { |
| + t.Fatal("the next visit does not offer the passkey") |
| + } |
| + }) |
| +} |
| + |
| +// directPasskey runs one discoverable sign-in with key, presenting prior |
| +// (a jar cookie) on the finish. |
| +func directPasskey(t *testing.T, app *testApp, key *authtest.Authenticator, prior *http.Cookie) *httptest.ResponseRecorder { |
| + t.Helper() |
| + begin := idJSON(t, app, directBegin, nil) |
| + zero := uint32(0) |
| + body := assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}) |
| + return idJSON(t, app, directFinish, body, namedCookie(t, begin, ceremonyCookie), prior) |
| +} |
| + |
| +// The passkey finish answers rastrillo's shape, which the door's module |
| +// reads: {"ok":true,"to":<a local path>} on success, a non-2xx on refusal |
| +// (so the conditional request re-begins once). |
| +func TestDoorPasskeyFinishAnswersRastrillosShape(t *testing.T) { |
| + app := newTestApp(t) |
| + key := enrol(t, app, signInFully(t, app, "shape@example.invalid")) |
| + if _, err := app.db.Writer().Exec("INSERT INTO passkey_recovery_codes(subject,code_hash,created_at) SELECT subject,'x','2026-01-01T00:00:00Z' FROM passkey_credentials"); err != nil { |
| + t.Fatal(err) |
| + } |
| + done := directPasskey(t, app, key, nil) |
| + if done.Code != 200 || strings.TrimSpace(done.Body.String()) != `{"ok":true,"to":"/"}` || done.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatal(done.Code, done.Body.String()) |
| + } |
| + stranger, _ := authtest.New() |
| + if refused := directPasskey(t, app, stranger, nil); refused.Code/100 == 2 { |
| + t.Fatal("a refused finish answered 2xx", refused.Code) |
| + } |
| +} |
| + |
| +// Forget: "Use a different email" forgets this browser's record, opens the |
| +// email field and keeps where the sign-in was going; it needs origin |
| +// evidence, as every form here does. |
| +func TestDoorForget(t *testing.T) { |
| + app := newTestApp(t) |
| + link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) |
| + r := returnRequest(app, "POST", forgetPath, url.Values{"return_to": {"/authorize/resume"}, "way": {"email"}}, link) |
| + if _, cleared := jarSet(r); !cleared || r.Code != 303 || r.Header().Get("Location") != "/signin?return_to=%2Fauthorize%2Fresume&way=email" || r.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatal(r.Code, r.Header()) |
| + } |
| + // No posted return_to: the return cookie's, and a step-up kept. |
| + keep := &http.Cookie{Name: returnCookie, Value: "/passkey/codes"} |
| + r = returnRequest(app, "POST", forgetPath, url.Values{"way": {"email"}, "reauth": {"1"}}, link, keep) |
| + if r.Header().Get("Location") != "/signin?reauth=1&return_to=%2Fpasskey%2Fcodes&way=email" { |
| + t.Fatal(r.Header().Get("Location")) |
| + } |
| + // A hostile return_to is no destination. |
| + r = returnRequest(app, "POST", forgetPath, url.Values{"return_to": {"https://evil.invalid/"}}, link) |
| + if r.Header().Get("Location") != "/signin" { |
| + t.Fatal(r.Header().Get("Location")) |
| + } |
| + req := httptest.NewRequest("POST", forgetPath, strings.NewReader("way=email")) |
| + req.Host = credentialHost |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Sec-Fetch-Site", "cross-site") |
| + req.AddCookie(link) |
| + w := httptest.NewRecorder() |
| + app.Router().ServeHTTP(w, req) |
| + if _, cleared := jarSet(w); cleared || w.Code != http.StatusForbidden { |
| + t.Fatal("a cross-site Forget went through", w.Code) |
| + } |
| + // Forget, then the door: nothing remembered, the field. |
| + after := doorGet(t, app, "/signin?way=email") |
| + if strings.Contains(after.Body.String(), "kept@example.invalid") { |
| + t.Fatal("still remembered") |
| + } |
| +} |
| + |
| +// The chained Forget: an app's signed-out page links to /forget?return=…; |
| +// id.* asks once, forgets on a same-origin POST, and returns only to a |
| +// registered consumer's /signed-out, else to its own signed-out page. |
| +func TestDoorForgetChain(t *testing.T) { |
| + p := newExchangePair(t) |
| + app := p.credential |
| + link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) |
| + const back = "https://blue.docs.oficina.works/signed-out" |
| + page := exchangeRequest(app.App, "GET", Origin+forgetChainPath+"?return="+url.QueryEscape(back), "", nil, link) |
| + body := page.Body.String() |
| + for _, want := range []string{`<form method="post" action="/forget"`, `<input type="hidden" name="return" value="` + back + `">`, ">Forget me on Oficina ID too</button>", `<a href="` + back + `">Not now</a>`} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("confirm page missing %q", want) |
| + } |
| + } |
| + if page.Code != 200 || page.Header().Get("Cache-Control") != "no-store" || !strings.Contains(page.Header().Get("Content-Security-Policy"), "https://blue.docs.oficina.works") { |
| + t.Fatal("confirm page", page.Code, page.Header()) |
| + } |
| + if _, cleared := jarSet(page); cleared || strings.Contains(body, "kept@example.invalid") { |
| + t.Fatal("the GET forgot, or showed the address") |
| + } |
| + done := exchangeRequest(app.App, "POST", Origin+forgetChainPath, Origin, url.Values{"return": {back}}, link) |
| + if _, cleared := jarSet(done); !cleared || done.Code != 303 || done.Header().Get("Location") != back { |
| + t.Fatal("forget", done.Code, done.Header()) |
| + } |
| + for _, bad := range []string{ |
| + "", "https://evil.invalid/signed-out", "https://blue.docs.oficina.works/", "https://blue.docs.oficina.works/signed-out?x=1", |
| + "https://blue.docs.oficina.works/signed-out#x", "https://u@blue.docs.oficina.works/signed-out", "http://blue.docs.oficina.works/signed-out", |
| + "https://blue.docs.oficina.works:443/signed-out", "https://blue.docs.oficina.works/signed-out/", "//blue.docs.oficina.works/signed-out", |
| + "https://blue.docs.oficina.works/%73igned-out", "/signed-out", "javascript:alert(1)", |
| + } { |
| + page := exchangeRequest(app.App, "GET", Origin+forgetChainPath+"?return="+url.QueryEscape(bad), "", nil) |
| + if !strings.Contains(page.Body.String(), `<a href="/signed-out">Not now</a>`) || strings.Contains(page.Body.String(), `name="return"`) || |
| + strings.Contains(page.Header().Get("Content-Security-Policy"), "blue.docs") { |
| + t.Errorf("GET %q was trusted", bad) |
| + } |
| + post := exchangeRequest(app.App, "POST", Origin+forgetChainPath, Origin, url.Values{"return": {bad}}, link) |
| + if post.Header().Get("Location") != "/signed-out" { |
| + t.Errorf("POST %q went to %q", bad, post.Header().Get("Location")) |
| + } |
| + } |
| + if cross := exchangeRequest(app.App, "POST", Origin+forgetChainPath, "https://blue.docs.oficina.works", url.Values{"return": {back}}, link); cross.Code != http.StatusForbidden { |
| + t.Fatal("a cross-origin chained Forget went through", cross.Code) |
| + } |
| + // The directory is a registered consumer too. |
| + if r := exchangeRequest(app.App, "POST", Origin+forgetChainPath, Origin, url.Values{"return": {directoryOrigin + "/signed-out"}}); r.Header().Get("Location") != directoryOrigin+"/signed-out" { |
| + t.Fatal("the directory's signed-out page refused", r.Header().Get("Location")) |
| + } |
| + // id.*'s own signed-out page offers its own Forget. |
| + own := exchangeRequest(app.App, "GET", Origin+"/signed-out", "", nil).Body.String() |
| + if !strings.Contains(own, `action="/signin/forget"`) || !strings.Contains(own, ">Forget me on this device</button>") { |
| + t.Fatal("id.* signed-out page has no Forget") |
| + } |
| +} |
| + |
| +// The return memory survives the door: an app sends a person to id.*; they |
| +// open Other ways, pick a passkey, sign in with it, and land back in the |
| +// app. Every chooser link and the passkey finish carry return_to, so |
| +// rememberReturn never forgets the handoff on the way. |
| +func TestDoorAppToChooserToPasskeyAndBack(t *testing.T) { |
| + p := newExchangePair(t) |
| + app := p.credential |
| + key := enrol(t, app, signInFully(t, app, sealtest.CanaryAddress)) |
| + if _, err := app.db.Writer().Exec("INSERT INTO passkey_recovery_codes(subject,code_hash,created_at) SELECT subject,'x','2026-01-01T00:00:00Z' FROM passkey_credentials"); err != nil { |
| + t.Fatal(err) |
| + } |
| + pending, intent := p.start(t) // the app (here, the directory) asks id.* for an assertion |
| + resume := exchangeRequest(app.App, "GET", Origin+"/authorize/resume", "", nil, intent) |
| + if resume.Code != 303 { |
| + t.Fatal("no sign-in asked for", resume.Code) |
| + } |
| + jar := &cookieJar{} |
| + jar.add(intent) |
| + follow := func(target string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := exchangeRequest(app.App, "GET", Origin+target, "", nil, jar.all()...) |
| + jar.take(r) |
| + if r.Code != 200 { |
| + t.Fatal("GET", target, r.Code) |
| + } |
| + return r |
| + } |
| + door := follow(resume.Header().Get("Location")) |
| + ways := follow(hrefOf(t, door.Body.String(), "Other ways to sign in")) |
| + passkeyDoor := follow(hrefOf(t, ways.Body.String(), "Sign in with a passkey")) |
| + if !strings.Contains(passkeyDoor.Body.String(), `data-rst-passkey-finish="/passkey/direct/finish?return_to=%2Fauthorize%2Fresume"`) { |
| + t.Fatal("the passkey door lost the return") |
| + } |
| + begin := exchangeRequest(app.App, "POST", Origin+directBegin, Origin, nil, jar.all()...) |
| + jar.take(begin) |
| + zero := uint32(0) |
| + finish := idJSON(t, app, directFinish+"?return_to=%2Fauthorize%2Fresume", assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}), jar.all()...) |
| + jar.take(finish) |
| + if finish.Code != 200 || strings.TrimSpace(finish.Body.String()) != `{"ok":true,"to":"/authorize/resume"}` { |
| + t.Fatal("finish", finish.Code, finish.Body.String()) |
| + } |
| + token, _ := p.mint(t, intent, sessionCookie(finish)) |
| + p.finish(t, token, pending) // back in the app, signed in |
| +} |
| + |
| +// hrefOf is the href of the link whose text contains label. |
| +func hrefOf(t *testing.T, body, label string) string { |
| + t.Helper() |
| + i := strings.Index(body, "<span>"+label+"</span>") |
| + if i < 0 { |
| + t.Fatalf("no link %q", label) |
| + } |
| + j := strings.LastIndex(body[:i], `href="`) |
| + if j < 0 { |
| + t.Fatalf("no href before %q", label) |
| + } |
| + rest := body[j+len(`href="`):] |
| + return strings.ReplaceAll(rest[:strings.Index(rest, `"`)], "&", "&") |
| +} |
| + |
| +// cookieJar is a browser's cookies for one origin, enough for a walk. |
| +type cookieJar struct{ m map[string]*http.Cookie } |
| + |
| +func (j *cookieJar) add(c *http.Cookie) { |
| + if j.m == nil { |
| + j.m = map[string]*http.Cookie{} |
| + } |
| + j.m[c.Name] = c |
| +} |
| + |
| +func (j *cookieJar) take(r *httptest.ResponseRecorder) { |
| + for _, c := range r.Result().Cookies() { |
| + if c.MaxAge < 0 || c.Value == "" { |
| + delete(j.m, c.Name) |
| + continue |
| + } |
| + j.add(c) |
| + } |
| +} |
| + |
| +func (j *cookieJar) all() []*http.Cookie { |
| + var out []*http.Cookie |
| + for _, c := range j.m { |
| + out = append(out, &http.Cookie{Name: c.Name, Value: c.Value}) |
| + } |
| + return out |
| +} |
diff --git a/internal/home/id_browser_test.go b/internal/home/id_browser_test.go| index 1e2afd8..d1692a3 100644 |
| --- a/internal/home/id_browser_test.go |
| +++ b/internal/home/id_browser_test.go |
| @@ -120,7 +120,7 @@ func TestIDBrowserDirectPasskeyAndGeneratedNames(t *testing.T) { |
| if len(credentials) != 1 || !credentials[0].IsResidentCredential || credentials[0].UserName != subject || credentials[0].UserDisplayName != subject { |
| t.Fatal("WebAuthn names were not generated opaque identifiers") |
| } |
| - idBrowserRun(t, ctx, cdpStep(network.DeleteCookies, network.DeleteCookiesParams{Name: s.Name, URL: browserIssuer + "/"}), chromedp.Navigate(browserIssuer+"/signin?return_to=%2Fpasskey%2Fcodes"), chromedp.WaitVisible("#passkey-direct"), chromedp.Click("#passkey-direct"), chromedp.WaitVisible(`form[action="/passkey/codes"]`)) |
| + idBrowserRun(t, ctx, cdpStep(network.DeleteCookies, network.DeleteCookiesParams{Name: s.Name, URL: browserIssuer + "/"}), chromedp.Navigate(browserIssuer+"/signin?return_to=%2Fpasskey%2Fcodes&way=passkey"), chromedp.WaitVisible(`button[data-rst-passkey]:enabled`), chromedp.Click(`button[data-rst-passkey]`), chromedp.WaitVisible(`form[action="/passkey/codes"]`)) |
| sealtest.AssertNoPlaintext(t, p.credential.dbPath) |
| } |
| @@ -169,7 +169,7 @@ func TestIDBrowserLegacyNonresidentGate(t *testing.T) { |
| } |
| func TestIDBrowserScriptlessCrossSiteReturn(t *testing.T) { |
| p, ctx, _ := idBrowser(t) |
| - idBrowserRun(t, ctx, cdpStep(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}), chromedp.Navigate(p.directory.origins.Directory+"/auth/start"), chromedp.WaitVisible("#address"), chromedp.SendKeys("#address", sealtest.CanaryAddress), chromedp.Click(`form[action="/signin"] button`), chromedp.WaitVisible(`a[href*="/signin"]`)) |
| + idBrowserRun(t, ctx, cdpStep(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}), chromedp.Navigate(p.directory.origins.Directory+"/auth/start"), chromedp.WaitVisible("#rst-signin-email"), chromedp.SendKeys("#rst-signin-email", sealtest.CanaryAddress), chromedp.Click(`form[action="/signin"] button`), chromedp.WaitVisible(`form[action="/signin/forget"] button`)) |
| token := capturedLink(t, p.credential) |
| idBrowserRun(t, ctx, chromedp.Navigate(browserIssuer+linkPath+"?token="+url.QueryEscape(token)), chromedp.WaitVisible(`form[action="/signin/verify"] button`), chromedp.Click(`form[action="/signin/verify"] button`), chromedp.WaitVisible(`form[action="/authorize/resume"] button`), chromedp.Click(`form[action="/authorize/resume"] button`), chromedp.WaitVisible(`form[data-assertion-handoff] button`), chromedp.Click(`form[data-assertion-handoff] button`), chromedp.WaitVisible(`[estilo-account]`)) |
| var location string |
diff --git a/internal/home/id_passkey.go b/internal/home/id_passkey.go| index 7ecdf6e..2597a77 100644 |
| --- a/internal/home/id_passkey.go |
| +++ b/internal/home/id_passkey.go |
| @@ -419,10 +419,21 @@ func (a *App) idFinish(purpose string) http.HandlerFunc { |
| idRefuse(w) |
| return |
| } |
| + // A passkey sign-in, gated or direct, is what the door offers |
| + // next time; the remembered address survives only for the same |
| + // person (door.go, passkeyRecord), read in this transaction. |
| + var remembered lastsigninRecord |
| + signedIn := purpose == "signin" || purpose == "direct" |
| + if signedIn { |
| + remembered = a.passkeyRecord(tx, r, owner) |
| + } |
| if e = tx.Commit(); e != nil { |
| idRefuse(w) |
| return |
| } |
| + if signedIn { |
| + a.remember(w, remembered) |
| + } |
| idCookie(w, a.sessions.CookieName(), token, 30*24*3600) |
| idCookie(w, ceremonyCookie, "", -1) |
| if purpose == "signin" { |
diff --git a/internal/home/keymail_continue_test.go b/internal/home/keymail_continue_test.go| index e4422e4..16cd27f 100644 |
| --- a/internal/home/keymail_continue_test.go |
| +++ b/internal/home/keymail_continue_test.go |
| @@ -1,7 +1,10 @@ |
| package home |
| import ( |
| + "encoding/xml" |
| + "io" |
| "net/http" |
| + "net/http/httptest" |
| "strings" |
| "testing" |
| ) |
| @@ -15,11 +18,9 @@ func TestKeymailSignInContinuesWithoutExternalPostRedirect(t *testing.T) { |
| if rec.Code != http.StatusOK { |
| t.Fatalf("POST sign-in must end before external navigation: %d", rec.Code) |
| } |
| - refresh, links := continuationTargets(t, rec.Body.String()) |
| - if len(links) != 1 || len(refresh) != 1 || !strings.HasPrefix(links[0], stub.srv.URL+"/") { |
| + if to := doorContinuation(t, rec); !strings.HasPrefix(to, stub.srv.URL+"/") { |
| t.Fatal("missing exact provider continuation") |
| } |
| - assertContinuationPage(t, rec, links[0]) |
| if app.SecurityPolicy() != policy || strings.Contains(policy, stub.host) { |
| t.Fatal("CSP broadened to provider") |
| } |
| @@ -36,3 +37,50 @@ func TestKeymailSignInContinuesWithoutExternalPostRedirect(t *testing.T) { |
| t.Fatal("pending cookie lost") |
| } |
| } |
| + |
| +// doorContinuation is the Keymail authorize URL the door's Continue step |
| +// (rastrillo's "Taking you to Keymail") hands the browser, checked: a 200 |
| +// that is not cacheable and sends no referrer from the page (the |
| +// header covers every link on it, as rastrillo's PrepareSigninResponse |
| +// does), exactly one meta refresh and exactly one primary link, both to |
| +// that URL, written through attribute escaping, and no script but |
| +// estilo's busy rule. |
| +func doorContinuation(t *testing.T, r *httptest.ResponseRecorder) string { |
| + t.Helper() |
| + h := r.Header() |
| + if r.Code != 200 || h.Get("Cache-Control") != "no-store" || h.Get("Referrer-Policy") != "no-referrer" || h.Get("Location") != "" || h.Get("Refresh") != "" { |
| + t.Fatal("continuation response", r.Code, h) |
| + } |
| + body := r.Body.String() |
| + var refresh, links []string |
| + d := xml.NewDecoder(strings.NewReader(body)) |
| + d.Strict, d.AutoClose, d.Entity = false, xml.HTMLAutoClose, xml.HTMLEntity |
| + for { |
| + token, err := d.Token() |
| + if err == io.EOF { |
| + break |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + el, ok := token.(xml.StartElement) |
| + if !ok { |
| + continue |
| + } |
| + a := map[string]string{} |
| + for _, v := range el.Attr { |
| + a[v.Name.Local] = v.Value |
| + } |
| + if el.Name.Local == "meta" && strings.EqualFold(a["http-equiv"], "refresh") { |
| + refresh = append(refresh, a["content"]) |
| + } |
| + if el.Name.Local == "a" && a["rst-btn"] == "primary block" { |
| + links = append(links, a["href"]) |
| + } |
| + } |
| + if len(links) != 1 || len(refresh) != 1 || refresh[0] != "0;url="+links[0] || strings.Contains(body, "ZgotmplZ") || hasOtherScript(body) || |
| + !strings.Contains(body, "Taking you to Keymail") { |
| + t.Fatal(refresh, links, body) |
| + } |
| + return links[0] |
| +} |
diff --git a/internal/home/keymail_fresh_test.go b/internal/home/keymail_fresh_test.go| index 8129cd9..35e0033 100644 |
| --- a/internal/home/keymail_fresh_test.go |
| +++ b/internal/home/keymail_fresh_test.go |
| @@ -52,15 +52,17 @@ func freshBegin(t *testing.T, p exchangePair, path, address string, cookies ...* |
| // if the begin did anything else, mail included. |
| func keymailContinuation(t *testing.T, p exchangePair, begin *httptest.ResponseRecorder) (*url.URL, *http.Cookie) { |
| t.Helper() |
| - _, links := continuationTargets(t, begin.Body.String()) |
| - if begin.Code != 200 || len(links) != 1 || !strings.Contains(links[0], "/oauth/authorize?") { |
| + if begin.Code != 200 { |
| t.Fatal("fresh Keymail begin did not continue to Keymail", begin.Code, begin.Header().Get("Location")) |
| } |
| - assertContinuationPage(t, begin, links[0]) |
| + to := doorContinuation(t, begin) |
| + if !strings.Contains(to, "/oauth/authorize?") { |
| + t.Fatal("fresh Keymail begin did not continue to Keymail", to) |
| + } |
| if _, sent := p.credential.mailer.last(); sent { |
| t.Fatal("fresh Keymail begin also sent mail") |
| } |
| - u, err := url.Parse(links[0]) |
| + u, err := url.Parse(to) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -170,7 +172,7 @@ func TestFreshKeymailWithoutAFreshGestureFallsBackToEmail(t *testing.T) { |
| // survived. |
| func formAction(t *testing.T, r *httptest.ResponseRecorder) string { |
| t.Helper() |
| - m := regexp.MustCompile(`<form method="post" action="([^"]*)"`).FindStringSubmatch(r.Body.String()) |
| + m := regexp.MustCompile(`<form rst-signin-form method="post" action="([^"]*)"`).FindStringSubmatch(r.Body.String()) |
| if len(m) != 2 { |
| t.Fatal("no sign-in form") |
| } |
diff --git a/internal/home/keymailstub_test.go b/internal/home/keymailstub_test.go| index 9bfec0a..3c7225d 100644 |
| --- a/internal/home/keymailstub_test.go |
| +++ b/internal/home/keymailstub_test.go |
| @@ -155,12 +155,7 @@ func writeJSON(t *testing.T, w http.ResponseWriter, v any) { |
| func beginKeymail(t *testing.T, app *testApp, address string) (*http.Cookie, string) { |
| t.Helper() |
| rec := signIn(t, app, address) |
| - _, links := continuationTargets(t, rec.Body.String()) |
| - if len(links) != 1 { |
| - t.Fatal("missing provider continuation") |
| - } |
| - loc := links[0] |
| - assertContinuationPage(t, rec, loc) |
| + loc := doorContinuation(t, rec) |
| if !strings.Contains(loc, "/oauth/authorize") { |
| t.Fatalf("sign-in went to %q, which is not the keymail authorize URL — "+ |
| "classification did not take the keymail branch", loc) |
diff --git a/internal/home/noscript_test.go b/internal/home/noscript_test.go| index ccfd76e..8edc387 100644 |
| --- a/internal/home/noscript_test.go |
| +++ b/internal/home/noscript_test.go |
| @@ -19,6 +19,8 @@ import ( |
| "amadan.net/oficina/estilo.git/theme" |
| "amadan.net/oficina/home/internal/home/sealtest" |
| "amadan.net/rastrillo/rastrillo" |
| + "amadan.net/rastrillo/rastrillo/lastsignin" |
| + "amadan.net/rastrillo/rastrillo/passkey" |
| "amadan.net/rastrillo/rastrillo/ui" |
| "github.com/go-chi/chi/v5" |
| ) |
| @@ -35,6 +37,7 @@ var homeScripts = []string{ |
| "/static/assertion.js", // the handoff's auto-submit; Continue stays for script-off |
| "/static/passkey.js", // the passkey ceremonies: webauthn cannot be done without script |
| "/static/busy.js", // estilo's busy rule: spinner and double-submit guard |
| + "/static/signin.mjs", // the door's passkey (rastrillo's passkey.JS()): its button, and the field's autofill |
| } |
| // templateSrc unwraps {{v "PATH"}} to PATH, so the sweep checks the file, |
| @@ -625,3 +628,66 @@ func TestOperatorPagesUnderTheScriptlessSweep(t *testing.T) { |
| t.Fatal("the sweep did not reach the confirm pages' success paths") |
| } |
| } |
| + |
| +// The door is rastrillo's partial, whose <script> the source sweep above |
| +// cannot see (it reads Home's templates), so its every state is swept |
| +// rendered: each script it loads is one of Home's, never inline, and with |
| +// every script stripped each state keeps a way in that works without |
| +// one. The passkey door's button is the one allowed affordance that needs |
| +// script (ruling 25), and it is drawn visible-but-disabled before |
| +// enhancement, with a <noscript> line and Other ways right below it. |
| +func TestDoorStatesUnderTheScriptRule(t *testing.T) { |
| + app := newTestApp(t) |
| + link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) |
| + keymail := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodKeymail, Address: "kept@example.invalid"}) |
| + remembered := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodPasskey}) |
| + type state struct { |
| + path string |
| + cookie *http.Cookie |
| + // what survives stripping: a form posting somewhere, or a link on |
| + works []string |
| + } |
| + states := []state{ |
| + {"/signin", nil, []string{`action="/signin"`, `name="address"`, `type="submit"`, "Other ways to sign in"}}, |
| + {"/signin?ways=1&way=email", nil, []string{`href="/signin?way=passkey"`, "<span>Back</span>"}}, |
| + {"/signin", link, []string{`action="/signin"`, `name="address" value="kept@example.invalid"`, `type="submit"`}}, |
| + {"/signin", keymail, []string{`action="/signin"`, `name="expect" value="keymail"`, `type="submit"`}}, |
| + {"/signin", remembered, []string{"<noscript><p>To use a passkey, turn on JavaScript.</p></noscript>", `href="/signin?way=passkey&ways=1"`}}, |
| + {"/signin?ways=1&way=passkey", remembered, []string{`href="/signin?way=email"`, `action="/signin/forget"`}}, |
| + {"/signin?force=1", keymail, []string{`action="/signin?force=1"`, `name="force" value="1"`}}, |
| + {"/signin?err=rate", nil, []string{`action="/signin"`, `name="address"`}}, |
| + {"/signin/sent", link, []string{`action="/signin/forget"`}}, |
| + } |
| + for _, s := range states { |
| + var cookies []*http.Cookie |
| + if s.cookie != nil { |
| + cookies = append(cookies, s.cookie) |
| + } |
| + body := doorGet(t, app, s.path, cookies...).Body.String() |
| + for _, src := range scriptSrcs([]byte(body)) { |
| + if i := strings.Index(src, "?v="); i >= 0 { |
| + src = src[:i] |
| + } |
| + if !slices.Contains(homeScripts, src) { |
| + t.Errorf("%s: loads %q, not one of Home's scripts", s.path, src) |
| + } |
| + } |
| + stripped := scriptTag.ReplaceAllString(body, "") |
| + for _, w := range s.works { |
| + if !strings.Contains(stripped, w) { |
| + t.Errorf("%s: without script, lost %q", s.path, w) |
| + } |
| + } |
| + if strings.Contains(stripped, "data-rst-passkey") && !strings.Contains(stripped, "<noscript>") && !strings.Contains(stripped, "data-rst-passkey-conditional") { |
| + t.Errorf("%s: a passkey control with no script-off way past it", s.path) |
| + } |
| + } |
| + // The module the door loads is rastrillo's, served at its stable path. |
| + r := httptest.NewRequest(http.MethodGet, signinModule, nil) |
| + r.Host = credentialHost |
| + w := httptest.NewRecorder() |
| + app.Router().ServeHTTP(w, r) |
| + if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), passkey.JS()) || w.Header().Get("Content-Type") != "text/javascript; charset=utf-8" { |
| + t.Fatal("the door's module is not rastrillo's passkey.JS()", w.Code) |
| + } |
| +} |
diff --git a/internal/home/passkey.go b/internal/home/passkey.go| index e8ac127..8d95742 100644 |
| --- a/internal/home/passkey.go |
| +++ b/internal/home/passkey.go |
| @@ -58,11 +58,16 @@ func passkeyConfig(a *App) passkey.Config { |
| // pageData is what every passkey page needs: the values the glue reads |
| // off <body> to run a ceremony. |
| // |
| -// UserName is the person ref, NOT the address. The credential origin |
| -// never renders an account-authored string (§4), and this app does not |
| -// hold the address anyway. A person ref reads poorly in a password |
| -// manager; that is the cost of §0, and it is accepted rather than worked |
| -// around. |
| +// UserName is the person ref, NOT the address. This app does not hold |
| +// the address, so it has none to give a passkey. And the credential |
| +// origin renders no account-authored string (§4) but one: since ruling |
| +// 26, the door (door.go) may show back the address Home sealed into this |
| +// browser's own cookie, as text and a hidden value on a no-store page. |
| +// That carve-out is the door's alone. A passkey page, and the user name |
| +// a ceremony writes into a password manager, still withhold the address: |
| +// the cookie is not evidence of who owns a passkey. A person ref reads |
| +// poorly in a password manager; that is the cost of §0, and it is |
| +// accepted rather than worked around. |
| func (a *App) passkeyPageData(subject string, extra map[string]any) map[string]any { |
| data := map[string]any{ |
| "RPID": a.credentialHost, |
| @@ -210,3 +215,8 @@ func staticAsset(name string) []byte { |
| } |
| func webauthnJS() []byte { return webauthn.JS() } |
| + |
| +// signinJS is the door's passkey module, rastrillo's own: it runs the |
| +// passkey door and the email field's autofill (conditional UI) against |
| +// the direct ceremony, whose finish answers {"ok":true,"to":…}. |
| +func signinJS() []byte { return passkey.JS() } |
diff --git a/internal/home/shared_chrome_test.go b/internal/home/shared_chrome_test.go| index 0d1373a..1731934 100644 |
| --- a/internal/home/shared_chrome_test.go |
| +++ b/internal/home/shared_chrome_test.go |
| @@ -77,8 +77,8 @@ func TestHomePagesWearTheSharedBar(t *testing.T) { |
| {"open source, signed in", directory, directoryOrigin + "/help/open-source", person, want{"Open source · Oficina", true, false, false, "/"}}, |
| {"open source, signed out", directory, directoryOrigin + "/help/open-source", nil, want{"Open source · Oficina", false, true, false, "/"}}, |
| {"signed out", directory, directoryOrigin + "/signed-out", nil, want{"Signed out · Oficina", false, false, true, "/"}}, |
| - {"id.* sign in", credential, Origin + "/signin", nil, want{"Sign in · Oficina", false, false, true, directoryOrigin + "/"}}, |
| - {"id.* check your email", credential, Origin + "/signin/sent", nil, want{"Check your email · Oficina", false, false, true, directoryOrigin + "/"}}, |
| + {"id.* sign in", credential, Origin + "/signin", nil, want{"Sign in to Oficina ID", false, false, true, directoryOrigin + "/"}}, |
| + {"id.* check your email", credential, Origin + "/signin/sent", nil, want{"Check your email to sign in to Oficina ID", false, false, true, directoryOrigin + "/"}}, |
| {"id.* recovery codes", credential, Origin + "/passkey/codes", idSession, want{"Recovery codes · Oficina", false, false, true, directoryOrigin + "/"}}, |
| {"id.* add a passkey", credential, Origin + "/passkey/enrol", idSession, want{"Add a passkey · Oficina", false, false, true, directoryOrigin + "/"}}, |
| {"id.* open source", credential, Origin + "/help/open-source", nil, want{"Open source · Oficina", false, false, false, directoryOrigin + "/"}}, |
| @@ -390,10 +390,11 @@ func TestErrorPagesSplitByAccept(t *testing.T) { |
| } |
| } |
| -// "Use a different address" and "Start again" keep where you were going |
| +// "Use a different email" and "Start again" keep where you were going |
| // (r3 C1). Both were a bare /signin, which forgets return_to: the magic |
| // link then ended at id.* "/", which sends you to the signed-out front |
| -// page, and a sign-in from an app lost the app. |
| +// page, and a sign-in from an app lost the app. On the door, "Use a |
| +// different email" is Forget, a POST that carries return_to. |
| func TestStartingAgainKeepsTheDestination(t *testing.T) { |
| app := newTestApp(t) |
| h := app.Router() |
| @@ -408,9 +409,10 @@ func TestStartingAgainKeepsTheDestination(t *testing.T) { |
| t.Fatal("the form did not remember return_to") |
| } |
| const again = `href="/signin?return_to=%2Fauthorize%2Fresume"` |
| + const forget = `<form rst-signin-form method="post" action="/signin/forget"><input type="hidden" name="return_to" value="/authorize/resume">` |
| sent := chromeGet(h, Origin+"/signin/sent", acceptHTML, keep).Body.String() |
| - if !strings.Contains(sent, again+">Use a different address") { |
| - t.Errorf("Use a different address forgets the destination:\n%s", sent) |
| + if !strings.Contains(sent, forget) || !strings.Contains(sent, "<span>Use a different email</span>") { |
| + t.Errorf("Use a different email forgets the destination:\n%s", sent) |
| } |
| r := httptest.NewRequest(http.MethodPost, Origin+linkPath, strings.NewReader("token=nope")) |
| r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| @@ -421,8 +423,8 @@ func TestStartingAgainKeepsTheDestination(t *testing.T) { |
| if !strings.Contains(rec.Body.String(), again+">Start again") { |
| t.Errorf("Start again forgets the destination:\n%s", rec.Body.String()) |
| } |
| - // With nowhere remembered, both stay a plain /signin. |
| - if body := chromeGet(h, Origin+"/signin/sent", acceptHTML).Body.String(); !strings.Contains(body, `href="/signin">Use a different address`) { |
| + // With nowhere remembered, Forget posts no destination. |
| + if body := chromeGet(h, Origin+"/signin/sent", acceptHTML).Body.String(); !strings.Contains(body, `action="/signin/forget"><input type="hidden" name="way"`) { |
| t.Errorf("with no destination: %s", body) |
| } |
| } |
diff --git a/internal/home/signin.go b/internal/home/signin.go| index a0ef3d2..b2c024f 100644 |
| --- a/internal/home/signin.go |
| +++ b/internal/home/signin.go |
| @@ -9,6 +9,7 @@ import ( |
| "time" |
| "amadan.net/oficina/estilo.git/chrome" |
| + "amadan.net/rastrillo/rastrillo/auth" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "github.com/keymaildev/signin" |
| ) |
| @@ -159,7 +160,8 @@ func clientIP(r *http.Request) string { |
| return "" |
| } |
| -// handleSigninForm renders the address form. |
| +// handleSigninForm draws the door (door.go): the way this browser used |
| +// last, Other ways to sign in, the chooser, or one way's own page. |
| // |
| // The email override (force=1) has to survive into the POST, because the |
| // browser submits the form's action and not the URL that rendered it. |
| @@ -170,35 +172,33 @@ func clientIP(r *http.Request) string { |
| // held to the same checks. |
| func (a *App) handleSigninForm(w http.ResponseWriter, r *http.Request) { |
| rememberReturn(w, r) |
| - a.renderSigninForm(w, r, http.StatusOK, "") |
| + a.renderDoor(w, r, http.StatusOK, a.doorState(w, r, doorTarget(r), "")) |
| } |
| -// renderSigninForm is the one way the address form is drawn: the first |
| -// GET and every error re-render alike. The person resubmits whatever |
| -// form is on screen, so an error page that dropped the override would |
| -// send a forced retry straight back to Keymail. |
| -func (a *App) renderSigninForm(w http.ResponseWriter, r *http.Request, status int, msg string) { |
| - data := a.passkeyPageData("", nil) |
| - if msg != "" { |
| - data["Error"] = msg |
| - } |
| - if r.URL.Query().Get("force") == "1" { |
| - data["Action"] = "/signin?force=1" |
| - } |
| - a.render(w, r, status, "signin.html", data) |
| +// renderSigninForm redraws the door after a failed Begin: the email field |
| +// with the problem, prefilled from this browser's remembered address and |
| +// never from what was posted (ruling 26: the one account-authored string |
| +// id.* renders is the one Home sealed). The return cookie is unchanged by |
| +// a POST, so it is where the sign-in is still going. |
| +func (a *App) renderSigninForm(w http.ResponseWriter, r *http.Request, status int, problem auth.SigninProblem) { |
| + a.renderDoor(w, r, status, a.doorState(w, r, readReturn(r), problem)) |
| } |
| // handleSigninSent is the check-your-mail page. It is reached by |
| // redirect and asserts nothing about the address, so it is the same page |
| -// whether or not anybody has an account here. |
| +// whether or not anybody has an account here: rastrillo's Sent, with no |
| +// address (SentTo stays empty), and "Use a different email" posting to |
| +// Forget with where the sign-in was going. |
| func (a *App) handleSigninSent(w http.ResponseWriter, r *http.Request) { |
| - a.render(w, r, http.StatusOK, "check_your_mail.html", map[string]any{"Again": againHref(r)}) |
| + st := a.doorState(w, r, readReturn(r), "") |
| + st.Step, st.Problem = auth.StepSent, auth.ProblemNone |
| + a.renderDoor(w, r, http.StatusOK, st) |
| } |
| // againHref is the way back to the form that keeps where the sign-in was |
| -// going: "Use a different address" and "Start again" (r3 C1). A bare |
| -// /signin forgets return_to (rememberReturn clears it), so the next link |
| -// ended at id.* "/" and the person on the signed-out front page. |
| +// going: "Start again" on the failed-link page (r3 C1). A bare /signin |
| +// forgets return_to (rememberReturn clears it), so the next link ended at |
| +// id.* "/" and the person on the signed-out front page. |
| func againHref(r *http.Request) string { |
| if target := readReturn(r); target != "/" { |
| return "/signin?return_to=" + url.QueryEscape(target) |
| @@ -215,7 +215,7 @@ func againHref(r *http.Request) string { |
| // neither discloses whether that person has an account here. |
| func (a *App) handleSigninBegin(w http.ResponseWriter, r *http.Request) { |
| if err := r.ParseForm(); err != nil { |
| - a.renderSigninForm(w, r, http.StatusBadRequest, "That did not look like a form.") |
| + a.renderSigninForm(w, r, http.StatusBadRequest, auth.ProblemGeneric) |
| return |
| } |
| address := strings.TrimSpace(r.PostFormValue("address")) |
| @@ -223,7 +223,7 @@ func (a *App) handleSigninBegin(w http.ResponseWriter, r *http.Request) { |
| // The force override carries a failed keymail round trip back to the |
| // magic link, so a failed approval is not a dead end. |
| var force signin.Method |
| - if r.URL.Query().Get("force") == "1" { |
| + if r.URL.Query().Get("force") == "1" || r.PostFormValue("force") == "1" { |
| force = signin.MethodMagicLink |
| } |
| next, err := a.flow.Begin(r.Context(), address, clientIP(r), force) |
| @@ -252,7 +252,9 @@ func (a *App) handleSigninBegin(w http.ResponseWriter, r *http.Request) { |
| if next.Kind == signin.NextKeymail { |
| a.setPending(w, next.Pending) |
| - a.renderContinuation(w, r, next.Redirect, "Continue to Keymail") |
| + // rastrillo's Continue step: "Taking you to Keymail", a refresh |
| + // and a link, both written through attribute escaping. |
| + a.renderDoor(w, r, http.StatusOK, auth.SigninState{Step: auth.StepContinue, ContinueURL: next.Redirect, OneWay: true}) |
| return |
| } |
| http.Redirect(w, r, "/signin/sent", http.StatusSeeOther) |
| @@ -264,14 +266,14 @@ func (a *App) beginFailed(w http.ResponseWriter, r *http.Request, err error) boo |
| case err == nil: |
| return false |
| case errors.Is(err, signin.ErrBadAddress): |
| - a.renderSigninForm(w, r, http.StatusBadRequest, "That does not look like an email address.") |
| + a.renderSigninForm(w, r, http.StatusBadRequest, auth.ProblemAddress) |
| case errors.Is(err, signin.ErrRateLimited): |
| // 429 without saying which budget: which one was hit is itself |
| // information about whether that address has been tried. |
| - a.renderSigninForm(w, r, http.StatusTooManyRequests, "Too many attempts. Try again shortly.") |
| + a.renderSigninForm(w, r, http.StatusTooManyRequests, auth.ProblemRate) |
| default: |
| a.logger.Error("signin begin failed") |
| - a.renderSigninForm(w, r, http.StatusInternalServerError, "Something went wrong. Try again.") |
| + a.renderSigninForm(w, r, http.StatusInternalServerError, auth.ProblemGeneric) |
| } |
| return true |
| } |
| @@ -403,6 +405,12 @@ func (a *App) completeSignIn(w http.ResponseWriter, r *http.Request, id signin.I |
| a.signinFailed(w, r) |
| return |
| } |
| + // The door remembers the way in and the address this browser just |
| + // proved (ruling 26), in a sealed cookie on this browser only. Here, |
| + // where the link or the Keymail return is proven, before the passkey |
| + // gate: the gate's own finish keeps the address only for the same |
| + // person (passkeyRecord). |
| + a.rememberEmail(w, id) |
| sess := sessions.Session{ |
| Subject: ref, |
| Method: string(id.Method), |
diff --git a/internal/home/signin_test.go b/internal/home/signin_test.go| index 3402a14..a04f7fa 100644 |
| --- a/internal/home/signin_test.go |
| +++ b/internal/home/signin_test.go |
| @@ -84,7 +84,9 @@ func sessionCookie(rec *httptest.ResponseRecorder) *http.Cookie { |
| } |
| // TestFullSigninLeavesNoReadableAddress is §12 gate 2: a full sign-in |
| -// leaves no readable address anywhere, WAL included. The directory and |
| +// leaves no readable address anywhere, WAL included, and neither does |
| +// loading the door afterwards with the cookie it wrote (gates 1 and 2's |
| +// sign-in half; TestDoorLeavesNoReadableAddressAtRest adds the passkey). The directory and |
| // owner seed now extends the completed sign-in into separate role databases. |
| // The rekey half remains for its implementation. |
| func TestFullSigninLeavesNoReadableAddress(t *testing.T) { |
| @@ -93,12 +95,22 @@ func TestFullSigninLeavesNoReadableAddress(t *testing.T) { |
| if rec := signIn(t, app, sealtest.CanaryAddress); rec.Code != http.StatusSeeOther { |
| t.Fatalf("POST /signin = %d, want 303", rec.Code) |
| } |
| - if rec := redeem(t, app, capturedLink(t, app)); rec.Code != http.StatusSeeOther { |
| - t.Fatalf("redeem = %d, want 303", rec.Code) |
| + redeemed := redeem(t, app, capturedLink(t, app)) |
| + if redeemed.Code != http.StatusSeeOther { |
| + t.Fatalf("redeem = %d, want 303", redeemed.Code) |
| } |
| exerciseOperatorSeedPrivacy(t, app) |
| sealtest.AssertNoPlaintext(t, app.dbPath) |
| + |
| + // Ruling 26: the sign-in remembered the address in this browser's |
| + // cookie. Loading the door with it shows the address back, and still |
| + // nothing at rest holds it. |
| + written, _ := jarSet(redeemed) |
| + if written == nil || !strings.Contains(doorGet(t, app, "/signin", written).Body.String(), sealtest.CanaryAddress) { |
| + t.Fatal("the door does not show back the address the sign-in remembered") |
| + } |
| + sealtest.AssertNoPlaintext(t, app.dbPath) |
| } |
| // A sign-in that completes must actually mint a session, or the gate |
diff --git a/internal/home/static/passkey.js b/internal/home/static/passkey.js| index c3dc999..2b2f0ff 100644 |
| --- a/internal/home/static/passkey.js |
| +++ b/internal/home/static/passkey.js |
| @@ -58,10 +58,14 @@ async function enrol(button, replacement = false) { |
| } |
| } |
| -async function confirm(button, direct = false) { |
| +// The door's own passkey (the discoverable "direct" ceremony and the email |
| +// field's autofill) is rastrillo's module, /static/signin.mjs, which the |
| +// signin partial loads; this file is the enrolment, gate and replacement |
| +// glue. |
| +async function confirm(button) { |
| button.disabled = true; |
| try { |
| - const path = direct ? "/passkey/direct" : "/passkey/signin"; |
| + const path = "/passkey/signin"; |
| const begin = await post(path + "/begin"); |
| const got = begin.credentials?.length ? await authenticateBound(begin) : await authenticate({ |
| challenge: begin.challenge, |
| @@ -84,8 +88,6 @@ reveal(); |
| document.getElementById("passkey-enrol")?.addEventListener("click", (e) => enrol(e.currentTarget)); |
| document.getElementById("passkey-confirm")?.addEventListener("click", (e) => confirm(e.currentTarget)); |
| -document.getElementById("passkey-direct")?.addEventListener("click", (e) => confirm(e.currentTarget, true)); |
| - |
| document.getElementById("passkey-replace")?.addEventListener("click", (e) => enrol(e.currentTarget, true)); |
| async function authenticateBound(begin) { |
diff --git a/internal/home/templates/check_your_mail.html b/internal/home/templates/check_your_mail.html| deleted file mode 100644 |
| index 740f16a..0000000 |
| --- a/internal/home/templates/check_your_mail.html |
| +++ /dev/null |
| @@ -1,6 +0,0 @@ |
| -{{define "title"}}{{(sentDoor .Data.Again).Title}}{{end}} |
| -{{define "content"}}{{with sentDoor .Data.Again}} |
| -<h1>{{.Heading}}</h1> |
| -<p estilo-signin-body role="status">{{.Body}}</p> |
| -{{with .Link}}<p><a href="{{.Href}}">{{.Label}}</a></p>{{end}} |
| -{{end}}{{end}} |
diff --git a/internal/home/templates/door.html b/internal/home/templates/door.html| new file mode 100644 |
| index 0000000..512e580 |
| --- /dev/null |
| +++ b/internal/home/templates/door.html |
| @@ -0,0 +1,2 @@ |
| +{{define "title"}}{{template "estilo-signin-screen-title" .Data}}{{end}} |
| +{{define "content"}}{{template "estilo-signin-screen" .Data}}{{end}} |
diff --git a/internal/home/templates/id_forget.html b/internal/home/templates/id_forget.html| new file mode 100644 |
| index 0000000..9ee4961 |
| --- /dev/null |
| +++ b/internal/home/templates/id_forget.html |
| @@ -0,0 +1,10 @@ |
| +{{define "title"}}Forget me · Oficina ID{{end}} |
| +{{define "content"}} |
| +<h1>Forget me on Oficina ID too?</h1> |
| +<p estilo-signin-body>Oficina ID remembers how you last signed in on this device. Forget it too, so the next person to use this device starts with a blank sign-in.</p> |
| +<form method="post" action="/forget" rst-form> |
| +{{with .Data.Return}}<input type="hidden" name="return" value="{{.}}">{{end}} |
| +<div rst-form-foot><button type="submit" rst-btn="primary">Forget me on Oficina ID too</button></div> |
| +</form> |
| +<p><a href="{{.Data.Back}}">Not now</a></p> |
| +{{end}} |
diff --git a/internal/home/templates/id_signed_out.html b/internal/home/templates/id_signed_out.html| index 508fa06..da2d0d6 100644 |
| --- a/internal/home/templates/id_signed_out.html |
| +++ b/internal/home/templates/id_signed_out.html |
| @@ -3,4 +3,8 @@ |
| <h1>You are signed out</h1> |
| <p>You are signed out of Oficina ID in this browser.</p> |
| <a href="/signin" rst-btn="primary">Sign in</a> |
| +<form method="post" action="/signin/forget" estilo-signin-forget> |
| +<input type="hidden" name="way" value="email"> |
| +<button rst-btn="ghost" type="submit">{{forgetLabel}}</button> |
| +</form> |
| {{end}} |
diff --git a/internal/home/templates/signin.html b/internal/home/templates/signin.html| deleted file mode 100644 |
| index 6a6ca3c..0000000 |
| --- a/internal/home/templates/signin.html |
| +++ /dev/null |
| @@ -1,20 +0,0 @@ |
| -{{define "title"}}{{signinDoor.Title}}{{end}} |
| -{{define "content"}}{{with signinDoor}} |
| -<h1>{{.Heading}}</h1> |
| -<button id="passkey-direct" type="button" rst-btn="primary" data-passkey hidden>Sign in with a passkey</button> |
| -<p id="passkey-status" role="status"></p> |
| -{{if $.Data.Error}}<p role="alert" rst-callout rst-tone="negative"><span rst-callout-body>{{$.Data.Error}}</span></p>{{end}} |
| -<form method="post" action="{{with $.Data.Action}}{{.}}{{else}}/signin{{end}}" rst-form estilo-signin-form> |
| - <div rst-field> |
| - <label rst-field-label for="address">{{.AddressLabel}}</label> |
| - <input id="address" name="address" type="email" autocomplete="email" required autofocus rst-input aria-describedby="address-help"> |
| - <p id="address-help" rst-field-help>{{.Help}}</p> |
| - </div> |
| - <div rst-form-foot> |
| - <button type="submit" rst-btn="primary">{{.Submit}}</button> |
| - </div> |
| -</form> |
| -{{end}}{{end}} |
| - |
| -{{define "bodyattrs"}} data-rpid="{{.Data.RPID}}" data-legacyrpid="{{.Data.LegacyRPID}}"{{end}} |
| -{{define "scripts"}}<script type="module" src="/static/passkey.js"></script>{{end}} |