oficina / home Public

smart door: Fable's fixes (jar confined to door.go, direct return, refused records, gate 5)

- The direct passkey finish takes the door's return_to from its own URL
  (credentialReturn), over the ten-minute return cookie, so a late
  autofill pick or another tab's cookie still lands in the app's handoff.
- The jar lives behind doorMemory in door.go; the record and jar aliases
  are gone, and every write is rememberEmail, passkeyRemembrance (decided
  in the sign-in transaction, written after commit) or forget. The guard
  refuses ".jar", any lastsignin name, and the SentTo, Federated, Confirm
  and Remembered fields of a composite literal outside door.go.
- A record the jar refuses (an address over 254 bytes) clears the cookie,
  so the previous person's record never survives a sign-in.
- Ruling 26 now reads "as text and as a form field's value" (the field
  door's prefill) in design §1, §4, gate 5 and AGENTS.md; gate 5 loops
  over every remembered method and checks the canary appears only in text
  nodes and value attributes.
- Comments: the directory has no door memory (newDirectory builds none;
  a test holds it); Home has no store objects beyond its SQLite database;
  the carlos edge-log pre-ship check is recorded on #138.

Copy unchanged, pending Paul.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d85daec8f00661e7cfd651ae23ab0abefa42f1ca parent e208e27
10 files changed, +330 −101
  • AGENTS.md +7 −3
  • docs/superpowers/specs/2026-08-30-home-design.md +9 −7
  • internal/guardstest/framework_signin_test.go +69 −0
  • internal/home/app.go +6 −5
  • internal/home/door.go +53 −40
  • internal/home/door_gates_test.go +100 −32
  • internal/home/door_test.go +66 −4
  • internal/home/id_passkey.go +17 −7
  • internal/home/passkey.go +2 −2
  • internal/home/signin.go +1 −1
diff --git a/AGENTS.md b/AGENTS.md
index 03b6162..a64eb80 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -52,13 +52,17 @@ 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
+on read, escaped, as text and as a form field's `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.**
+validly sealed canary cookie (`door_gates_test.go`). Only `door.go` holds
+the jar: every write goes through its narrow functions, and
+`internal/guardstest` refuses a `.jar` or a `lastsignin` name in any other
+production file. The pre-ship check that the carlos edge logs neither
+Cookie headers nor response bodies was done for this step (recorded on
+discussion #138); repeat it if the edge's logging changes.
*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,
diff --git a/docs/superpowers/specs/2026-08-30-home-design.md b/docs/superpowers/specs/2026-08-30-home-design.md
index 9df6071..318ebf6 100644
--- a/docs/superpowers/specs/2026-08-30-home-design.md
+++ b/docs/superpowers/specs/2026-08-30-home-design.md
@@ -137,7 +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 |
+| 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 as a form field's `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 |
---
@@ -465,8 +465,8 @@ on the root origin, account-authored content only on the account's own host.*
**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.
+ browser last proved), re-checked on read, escaped, as text and as a
+ form field's `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.
@@ -1437,10 +1437,12 @@ No template gallery, no upsell chrome, no waffle.
5. **Origin separation** — no account-authored string reachable on the
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.
+ on the door alone, as text and as a form field's `value`. The gate
+ drives every credential route with a validly sealed canary cookie, for
+ each remembered method, and fails if the canary renders off the door
+ or anywhere in the markup but a text node or a `value`, 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/internal/guardstest/framework_signin_test.go b/internal/guardstest/framework_signin_test.go
index 473f1f7..6583838 100644
--- a/internal/guardstest/framework_signin_test.go
+++ b/internal/guardstest/framework_signin_test.go
@@ -170,12 +170,81 @@ func TestHomeNeverMountsFrameworkSignin(t *testing.T) {
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 doorMemoryUses(t, filepath.ToSlash(rel), src) {
+ t.Errorf("%s: %s; only the door (internal/home/door.go) may reach the jar or fill these fields (ruling 26)", rel, use)
+ }
for _, use := range passkeyHandlerUses(t, path) {
t.Errorf("%s: %s; Home mounts none of passkey's handlers", rel, use)
}
}
}
+// doorFile is the one production file that holds the jar.
+const doorFile = "internal/home/door.go"
+
+// doorOnlyFields are SigninState fields that carry an address or a URL
+// the door must decide itself: only door.go may fill them in a composite
+// literal.
+var doorOnlyFields = map[string]bool{"SentTo": true, "Federated": true, "Confirm": true, "Remembered": true}
+
+// doorMemoryUses is every way a production file other than door.go
+// reaches the door's memory: the jar field (".jar", on whatever value),
+// any identifier named lastsignin, or a door-only SigninState field set
+// in a composite literal. The import allowlist above confines the
+// packages; this confines the jar, which an import rule cannot see: a
+// file that could reach the jar could seal any address it liked.
+func doorMemoryUses(t *testing.T, rel string, src []byte) []string {
+ t.Helper()
+ if rel == doorFile {
+ return nil
+ }
+ 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
+ at := func(n ast.Node) string { return "line " + strconv.Itoa(fset.Position(n.Pos()).Line) }
+ ast.Inspect(f, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.SelectorExpr:
+ if n.Sel.Name == "jar" {
+ out = append(out, at(n)+": .jar")
+ }
+ case *ast.Ident:
+ if n.Name == "lastsignin" {
+ out = append(out, at(n)+": lastsignin")
+ }
+ case *ast.KeyValueExpr:
+ if k, ok := n.Key.(*ast.Ident); ok && doorOnlyFields[k.Name] {
+ out = append(out, at(n)+": "+k.Name+":")
+ }
+ }
+ return true
+ })
+ return out
+}
+
+// The jar is the door's alone: a .jar, a lastsignin name or a door-only
+// field anywhere else is refused, and door.go itself passes.
+func TestDoorMemoryGuardRefuses(t *testing.T) {
+ cases := []struct {
+ rel, src string
+ refused bool
+ }{
+ {"internal/home/door.go", "package home\nfunc f(a *App) { a.door.jar.Clear(nil) }\n", false},
+ {"internal/home/signin.go", "package home\nfunc f(a *App) { a.door.jar.Clear(nil) }\n", true},
+ {"internal/home/app.go", "package home\nvar x = lastsignin.Record{}\n", true},
+ {"internal/home/signin.go", "package home\nvar x = auth.SigninState{SentTo: \"a@b\"}\n", true},
+ {"internal/home/signin.go", "package home\nvar x = auth.SigninState{Step: auth.StepSent}\n", false},
+ }
+ for i, c := range cases {
+ if got := doorMemoryUses(t, c.rel, []byte(c.src)); (len(got) > 0) != c.refused {
+ t.Errorf("case %d (%s): uses %q, refused want %v", i, c.rel, got, c.refused)
+ }
+ }
+}
+
// 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
diff --git a/internal/home/app.go b/internal/home/app.go
index bc0d3a1..48240c0 100644
--- a/internal/home/app.go
+++ b/internal/home/app.go
@@ -57,10 +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
+ // door 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
+ // Nil on the directory, which newDirectory builds without one and
+ // which never serves the door.
+ door *doorMemory
// signinLimiter is signin.Flow's own limiter, held here so that /resolve
// spends the same per-IP budget sign-in does; resolveLimiter is
@@ -135,13 +136,13 @@ func NewWithOrigins(secrets Secrets, d *db.DB, logger *slog.Logger, origins Orig
return nil, err
}
- jar, err := newJar(secrets, origins.Credential)
+ door, err := newDoorMemory(secrets, origins.Credential)
if err != nil {
return nil, err
}
a := &App{
- jar: jar,
+ door: door,
origins: origins,
credentialHost: strings.TrimPrefix(origins.Credential, "https://"),
directoryHost: strings.TrimPrefix(origins.Directory, "https://"),
diff --git a/internal/home/door.go b/internal/home/door.go
index 623f5f8..ecba8be 100644
--- a/internal/home/door.go
+++ b/internal/home/door.go
@@ -62,35 +62,50 @@ const (
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
+// doorMemory is the door's remembered way in: lastsignin's jar, which
+// seals an address into this browser's cookie (ruling 26). It is held
+// behind this type, and every write is one of the narrow functions below
+// (rememberEmail, passkeyRemembrance, forget), so nothing outside this
+// file can seal an arbitrary address: internal/guardstest refuses a
+// ".jar" or any lastsignin name in any other production file.
+type doorMemory struct {
+ jar *lastsignin.Jar
+}
+
+// newDoorMemory 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) {
+func newDoorMemory(secrets Secrets, origin string) (*doorMemory, error) {
key, err := secrets.Sealer.Derive(jarLabel)
if err != nil {
return nil, err
}
- return lastsignin.New(lastsignin.Config{
+ jar, err := lastsignin.New(lastsignin.Config{
Origin: origin,
InstanceKey: hex.EncodeToString(key),
Mode: lastsignin.On,
})
+ if err != nil {
+ return nil, err
+ }
+ return &doorMemory{jar: jar}, nil
}
-// 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.
+// no door (the directory: newDirectory builds it without one, and it never
+// serves the door). The response that carries the cookie is no-store, so no
+// cache keeps it. A record the jar refuses to write (an address it would
+// not read back, such as one over 254 bytes) clears the cookie instead:
+// otherwise the previous person's record would survive this sign-in.
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)
+ if a.door == nil {
+ return
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ before := len(w.Header().Values("Set-Cookie"))
+ a.door.jar.Remember(w, rec)
+ if len(w.Header().Values("Set-Cookie")) == before {
+ a.door.jar.Clear(w)
}
}
@@ -104,27 +119,25 @@ func (a *App) rememberEmail(w http.ResponseWriter, id signin.Identity) {
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 {
+// passkeyRemembrance is what a finished passkey sign-in will remember,
+// decided inside the sign-in's own transaction and written, by the
+// function it returns, only once that transaction has committed: passkey,
+// and the address this browser had remembered only if its blind index
+// resolves to the same person ref as the passkey's owner. 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) passkeyRemembrance(tx *sql.Tx, r *http.Request, owner string) func(http.ResponseWriter) {
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
+ if a.door != nil {
+ if prev, res := a.door.jar.Read(r); res == lastsignin.Valid && prev.Address != "" {
+ 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
+ return func(w http.ResponseWriter) { a.remember(w, rec) }
}
// queryProblem maps ?err= as rastrillo's screen does, so its words are
@@ -181,8 +194,8 @@ func (a *App) doorState(w http.ResponseWriter, r *http.Request, target string, p
if target != "/" {
st.ReturnTo = target
}
- if a.jar != nil {
- switch rec, res := a.jar.Read(r); res {
+ if a.door != nil {
+ switch rec, res := a.door.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
@@ -190,7 +203,7 @@ func (a *App) doorState(w http.ResponseWriter, r *http.Request, target string, p
// id.* may render is the one Home sealed itself (ruling 26).
st.Address = rec.Address
case lastsignin.Invalid:
- a.jar.Clear(w)
+ a.door.jar.Clear(w)
}
}
if problem == auth.ProblemNone {
@@ -293,8 +306,8 @@ func (a *App) handleForget(w http.ResponseWriter, r *http.Request) {
}
func (a *App) forget(w http.ResponseWriter) {
- if a.jar != nil {
- a.jar.Clear(w)
+ if a.door != nil {
+ a.door.jar.Clear(w)
}
}
diff --git a/internal/home/door_gates_test.go b/internal/home/door_gates_test.go
index 5818b5e..882f4c8 100644
--- a/internal/home/door_gates_test.go
+++ b/internal/home/door_gates_test.go
@@ -119,47 +119,63 @@ 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)
+ for _, method := range []string{lastsignin.MethodMagicLink, lastsignin.MethodKeymail, lastsignin.MethodPasskey} {
+ cookie := sealedRecord(t, app.App, lastsignin.Record{Method: method, Address: canary})
+ 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 %s rendered an address it did not seal (%s)", method, rt[0], rt[1], never)
+ }
+ }
+ if strings.Contains(body, canary) {
+ shown++
+ if !door[rt[1]] {
+ t.Errorf("%s %s %s rendered the remembered address off the door", method, rt[0], rt[1])
+ }
+ if r.Header().Get("Cache-Control") != "no-store" {
+ t.Errorf("%s %s %s rendered the address on a cacheable page", method, rt[0], rt[1])
+ }
+ if where := outsideTextAndValue(body, canary); where != "" {
+ t.Errorf("%s %s %s rendered the address outside text and value=: %s", method, rt[0], rt[1], where)
+ }
}
}
+ }
+ // Each method's door shows its address somewhere: the one-tap for
+ // a link or Keymail, the chooser's Email row for a passkey.
+ if method == lastsignin.MethodPasskey {
+ body := strings.ToLower(doorGet(t, app, "/signin?ways=1&way=passkey", cookie).Body.String())
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 where := outsideTextAndValue(body, canary); where != "" {
+ t.Errorf("passkey chooser rendered the address outside text and value=: %s", where)
}
}
}
+ if shown == 0 {
+ t.Fatalf("%s: the door never showed the sealed address: the gate checked nothing", method)
+ }
}
- 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.
+ // The door draws it only as text and as a form field's 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, "&#34;&gt;&lt;script&gt;x&lt;/script&gt;@example.invalid") {
@@ -172,12 +188,47 @@ func TestDoorRendersOnlyTheAddressItSealed(t *testing.T) {
}
}
+// outsideTextAndValue returns a description of the first place canary
+// occurs in body other than a text node or a value="…" attribute, or "".
+// Ruling 26 allows the address as text and as a form field's value, and
+// nowhere else: not in another attribute (an href, a data-*), not in a
+// tag name, comment or script.
+func outsideTextAndValue(body, canary string) string {
+ for from := 0; ; {
+ i := strings.Index(body[from:], canary)
+ if i < 0 {
+ return ""
+ }
+ i += from
+ from = i + len(canary)
+ open, close := strings.LastIndex(body[:i], "<"), strings.LastIndex(body[:i], ">")
+ if open <= close {
+ // Between tags: a text node, unless inside a script or comment.
+ if s := strings.LastIndex(body[:i], "<script"); s > strings.LastIndex(body[:i], "</script") {
+ return "inside a script"
+ }
+ if c := strings.LastIndex(body[:i], "<!--"); c > strings.LastIndex(body[:i], "-->") {
+ return "inside a comment"
+ }
+ continue
+ }
+ // Inside a tag: only as the whole of a value="…".
+ if !strings.HasSuffix(body[:i], ` value="`) || !strings.HasPrefix(body[from:], `"`) {
+ end := min(len(body), from+20)
+ return "in a tag: " + body[open:end]
+ }
+ }
+}
+
// 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.
+// blind index and writes nothing. Home has no store objects to scan (no
+// object storage, no blob store: its only persistent state is this SQLite
+// database, which Litestream ships with its WAL), so the database, WAL and
+// SHM are the whole of what is at rest.
func TestDoorLeavesNoReadableAddressAtRest(t *testing.T) {
app := newTestApp(t)
signIn(t, app, sealtest.CanaryAddress)
@@ -200,3 +251,20 @@ func TestDoorLeavesNoReadableAddressAtRest(t *testing.T) {
returnRequest(app, "POST", forgetPath, url.Values{"way": {"email"}}, kept)
sealtest.AssertNoPlaintext(t, app.dbPath)
}
+
+// outsideTextAndValue must see the places gate 5 refuses, or the gate's
+// text-and-value check is a check over nothing.
+func TestOutsideTextAndValueSeesTheRefusedPlaces(t *testing.T) {
+ for body, refused := range map[string]bool{
+ `<p>as <bdi>x@y</bdi></p><input value="x@y">`: false,
+ `<a href="/?a=x@y">`: true,
+ `<input data-v="x@y">`: true,
+ `<script>var a="x@y"</script>`: true,
+ `<!-- x@y -->`: true,
+ `<input value="x@y and">`: true,
+ } {
+ if got := outsideTextAndValue(body, "x@y") != ""; got != refused {
+ t.Errorf("%q: refused %v, want %v", body, got, refused)
+ }
+ }
+}
diff --git a/internal/home/door_test.go b/internal/home/door_test.go
index 91225f6..e97efac 100644
--- a/internal/home/door_test.go
+++ b/internal/home/door_test.go
@@ -12,6 +12,7 @@ import (
"amadan.net/oficina/home/internal/home/sealtest"
"amadan.net/rastrillo/rastrillo/lastsignin"
"amadan.net/rastrillo/rastrillo/webauthn/authtest"
+ "github.com/keymaildev/signin"
)
// The smart door on id.* (door.go, smart-door spec step 5): every state
@@ -24,7 +25,7 @@ const jarCookie = "__Host-rastrillo_last_signin"
func sealedRecord(t *testing.T, app *App, rec lastsignin.Record) *http.Cookie {
t.Helper()
w := httptest.NewRecorder()
- app.jar.Remember(w, rec)
+ app.door.jar.Remember(w, rec)
for _, c := range w.Result().Cookies() {
if c.Name == jarCookie && c.Value != "" {
return c
@@ -55,7 +56,7 @@ 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)
+ rec, res := app.door.jar.Read(req)
if res != lastsignin.Valid {
t.Fatalf("jar cookie reads as %v", res)
}
@@ -77,8 +78,8 @@ func doorGet(t *testing.T, app *testApp, path string, cookies ...*http.Cookie) *
// 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())
+ if app.door.jar.CookieName() != jarCookie {
+ t.Fatalf("cookie %q, want the __Host- one", app.door.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 {
@@ -356,6 +357,19 @@ func TestDoorRemembersProvenSignIns(t *testing.T) {
}
})
}
+ t.Run("a record the jar refuses clears the old one", func(t *testing.T) {
+ app := newTestApp(t)
+ prior := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "previous@example.invalid"})
+ long := strings.Repeat("a", 250) + "@example.invalid" // over lastsignin's 254 bytes
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", Origin+"/signin/verify", nil)
+ req.AddCookie(prior)
+ app.rememberEmail(w, signin.Identity{Method: signin.MethodMagicLink, Address: long})
+ set, cleared := jarSet(w)
+ if set != nil || !cleared || w.Header().Get("Cache-Control") != "no-store" {
+ t.Fatal("a refused record left the previous person's record in place", set, cleared)
+ }
+ })
t.Run("a refused passkey remembers nothing", func(t *testing.T) {
app := newTestApp(t)
enrol(t, app, signInFully(t, app, "owner@example.invalid"))
@@ -420,6 +434,54 @@ func TestDoorPasskeyFinishAnswersRastrillosShape(t *testing.T) {
}
}
+// The direct finish takes the door's return_to from its own URL (the
+// module puts the page's return_to there), so a late autofill pick, with
+// the ten-minute return cookie gone or replaced by another tab, still
+// lands in the app's handoff. A hostile one is no destination, and it
+// beats the cookie only when it names one.
+func TestDoorDirectFinishKeepsTheDoorsReturn(t *testing.T) {
+ app := newTestApp(t)
+ key := enrol(t, app, signInFully(t, app, "late@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)
+ }
+ finish := func(query string, cookies ...*http.Cookie) string {
+ 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})
+ done := idJSON(t, app, directFinish+query, body, append(cookies, namedCookie(t, begin, ceremonyCookie))...)
+ if done.Code != 200 {
+ t.Fatal("finish", done.Code)
+ }
+ return strings.TrimSpace(done.Body.String())
+ }
+ if got := finish("?return_to=%2Fauthorize%2Fresume"); got != `{"ok":true,"to":"/authorize/resume"}` {
+ t.Fatal("no cookie: lost the door's return", got)
+ }
+ other := &http.Cookie{Name: returnCookie, Value: "/passkey/codes"}
+ if got := finish("?return_to=%2Fauthorize%2Fresume", other); got != `{"ok":true,"to":"/authorize/resume"}` {
+ t.Fatal("another tab's cookie won over the door's return", got)
+ }
+ if got := finish("?return_to=https%3A%2F%2Fevil.invalid%2F", other); got != `{"ok":true,"to":"/passkey/codes"}` {
+ t.Fatal("a hostile return_to displaced the cookie", got)
+ }
+ if got := finish("?return_to=https%3A%2F%2Fevil.invalid%2F"); got != `{"ok":true,"to":"/"}` {
+ t.Fatal("a hostile return_to was followed", got)
+ }
+}
+
+// The directory never holds the door's memory: it never serves the door.
+func TestDirectoryHasNoDoorMemory(t *testing.T) {
+ p := newExchangePair(t)
+ if p.directory.door != nil {
+ t.Fatal("the directory built a jar")
+ }
+ if p.credential.door == nil {
+ t.Fatal("the credential origin has no jar")
+ }
+}
+
// 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.
diff --git a/internal/home/id_passkey.go b/internal/home/id_passkey.go
index 2597a77..018f9ec 100644
--- a/internal/home/id_passkey.go
+++ b/internal/home/id_passkey.go
@@ -395,6 +395,16 @@ func (a *App) idFinish(purpose string) http.HandlerFunc {
return
}
method, to := "passkey", readReturn(r)
+ if purpose == "direct" {
+ // The door's module puts the page's return_to on the finish
+ // URL (SigninState.PasskeyFinish). It wins over the return
+ // cookie, which lasts ten minutes and which another tab can
+ // replace, so a late autofill pick still lands in the app's
+ // handoff. credentialReturn keeps it to the closed list.
+ if q := credentialReturn(r.URL.Query().Get("return_to")); q != "/" {
+ to = q
+ }
+ }
if purpose == "signin" {
if e = tx.QueryRow("DELETE FROM passkey_pending WHERE token_hash=? RETURNING method,return_to", binding).Scan(&method, &to); e != nil {
idRefuse(w)
@@ -421,18 +431,18 @@ func (a *App) idFinish(purpose string) http.HandlerFunc {
}
// 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)
+ // person (door.go, passkeyRemembrance), read in this transaction
+ // and written only after it commits.
+ var remember func(http.ResponseWriter)
+ if purpose == "signin" || purpose == "direct" {
+ remember = a.passkeyRemembrance(tx, r, owner)
}
if e = tx.Commit(); e != nil {
idRefuse(w)
return
}
- if signedIn {
- a.remember(w, remembered)
+ if remember != nil {
+ remember(w)
}
idCookie(w, a.sessions.CookieName(), token, 30*24*3600)
idCookie(w, ceremonyCookie, "", -1)
diff --git a/internal/home/passkey.go b/internal/home/passkey.go
index 8d95742..01b0c9d 100644
--- a/internal/home/passkey.go
+++ b/internal/home/passkey.go
@@ -62,8 +62,8 @@ func passkeyConfig(a *App) passkey.Config {
// 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
+// browser's own cookie, as text and as a form field's 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
diff --git a/internal/home/signin.go b/internal/home/signin.go
index b2c024f..d34b034 100644
--- a/internal/home/signin.go
+++ b/internal/home/signin.go
@@ -409,7 +409,7 @@ func (a *App) completeSignIn(w http.ResponseWriter, r *http.Request, id signin.I
// 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).
+ // person (passkeyRemembrance).
a.rememberEmail(w, id)
sess := sessions.Session{
Subject: ref,