Sign out all devices: marks, duplicate cookies, honest copy
Human
Prompt
Coordinator, 2026-11-14: Fable re-reviewed @6365328: APPROVE AFTER FIXES. F1: duplicated session cookie names slip past nativeSessionsStayNative; strip them and test it. F2: assertions minted before the press survive; store a per-subject "signed out all at" mark (receipt iat) at the directory and on id.*, refuse assertions with iat <= mark at the directory browser finish and native exchange; note connect does not see it yet (slice C follow-up). F3: honest copy about what ends. F4: the hop gets its own copy and failure copy with a retry; move the residual into the branch description. F5: clear this browser's directory cookie only if it is the receipt's subject.
From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.
Summary
F1: nativeSessionsStayNative looks up every cookie of the session name (up to eight; more are stripped outright) and strips them all if any is native, so a duplicate can't hide one; requests without a native one are untouched, so the dashboard's ambiguous-session refusals still apply. F2: the press writes a per-person mark on id.* (no grant created at or before it authenticates) and the directory's receiver writes the receipt's iat in the same transaction as the session delete (new directory migration set home_directory_id, ServingSchema only); the directory's browser finish and native exchange refuse assertions issued at or before it. Marks older than five minutes are pruned on the next write. F3/F4: the page, the hop ('Finishing signing out of oficina.works…') and a new failure page say exactly what ended and what may not have, with 'Sign in and try again'. F5: the directory clears this browser's cookie only if it is the receipt's person's.Agent notes
Team instances (connect) do not read the mark; recorded as a slice C follow-up in the branch description. Each new check was mutation-tested: disabling the browser-finish mark, the native-exchange mark or the duplicate strip fails its test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+316
−53
internal/home/calma.go+17 −15internal/home/directory.go+4 −0internal/home/directory_id/migrations/0001_signed_out_all.sql+11 −0internal/home/directory_native.go+26 −8internal/home/exchange_test.go+1 −1internal/home/identity/migrations/0004_native.sql+9 −0internal/home/models.go+14 −0internal/home/native.go+14 −2internal/home/native_review_test.go+96 −0internal/home/runtime.go+1 −1internal/home/signout_all.go+93 −23internal/home/templates/directory_signed_out.html+1 −1internal/home/templates/directory_signout_all_failed.html+7 −0internal/home/templates/id_signout_all.html+3 −2internal/home/templates/id_signout_all_hop.html+19 −0
CI passed — run details
diff --git a/internal/home/calma.go b/internal/home/calma.go| index 647b04a..36f2e48 100644 |
| --- a/internal/home/calma.go |
| +++ b/internal/home/calma.go |
| @@ -73,18 +73,19 @@ const suiteName = "Oficina" |
| // error pages are plain pages under the bar. |
| // Not assertion.html or docs_continue.html: they are hops (hopPages). |
| var doorPages = map[string]bool{ |
| - "signin.html": true, |
| - "check_your_mail.html": true, |
| - "signin_confirm.html": true, |
| - "signin_failed.html": true, |
| - "passkey_confirm.html": true, |
| - "passkey_enrol.html": true, |
| - "recovery_codes.html": true, |
| - "handoff_failed.html": true, |
| - "signout_confirm.html": true, |
| - "directory_signed_out.html": true, |
| - "operator_confirm_id.html": true, |
| - "resolve.html": true, |
| + "signin.html": true, |
| + "check_your_mail.html": true, |
| + "signin_confirm.html": true, |
| + "signin_failed.html": true, |
| + "passkey_confirm.html": true, |
| + "passkey_enrol.html": true, |
| + "recovery_codes.html": true, |
| + "handoff_failed.html": true, |
| + "signout_confirm.html": true, |
| + "directory_signed_out.html": true, |
| + "operator_confirm_id.html": true, |
| + "resolve.html": true, |
| + "directory_signout_all_failed.html": true, |
| } |
| // hopPages move on by themselves (an auto-submit, a 0 s refresh). They |
| @@ -92,9 +93,10 @@ var doorPages = map[string]bool{ |
| // door and the directory is not a blank page (r3 C2), but load no script, |
| // no sky layer and no card: the card shows only if the hop stalls. |
| var hopPages = map[string]bool{ |
| - "assertion.html": true, |
| - "docs_continue.html": true, |
| - "resolve_handoff.html": true, |
| + "assertion.html": true, |
| + "docs_continue.html": true, |
| + "resolve_handoff.html": true, |
| + "id_signout_all_hop.html": true, |
| } |
| // mountCalma serves the Calma pieces Home's pages link: the sky's layers |
diff --git a/internal/home/directory.go b/internal/home/directory.go| index 1c694d7..38edafb 100644 |
| --- a/internal/home/directory.go |
| +++ b/internal/home/directory.go |
| @@ -47,6 +47,10 @@ func newDirectory(cfg Runtime, d *db.DB, logger *slog.Logger) (*App, error) { |
| a := &App{handoffStore: store, runtime: &cfg, origins: cfg.origins, credentialHost: strings.TrimPrefix(cfg.origins.Credential, "https://"), directoryHost: strings.TrimPrefix(cfg.origins.Directory, "https://"), secrets: cfg.secrets, db: d, logger: logger, renderer: renderer, sessions: sess} |
| // One completion for both consumers: the directory's one session boundary. |
| complete := func(w http.ResponseWriter, r *http.Request, c assertion.Claims) error { |
| + // An assertion issued before "Sign out all devices" buys nothing. |
| + if err := a.directorySigninAllowed(r.Context(), c); err != nil { |
| + return err |
| + } |
| return a.sessions.SignIn(w, r, sessions.Session{Subject: c.Subject, Method: "assertion", AuthTime: time.Unix(c.AuthTime, 0)}) |
| } |
| a.consumer, err = handoff.NewConsumer(handoff.ConsumerConfig{Store: store, ConsumerID: "directory", CurrentSubject: func(r *http.Request) string { |
diff --git a/internal/home/directory_id/migrations/0001_signed_out_all.sql b/internal/home/directory_id/migrations/0001_signed_out_all.sql| new file mode 100644 |
| index 0000000..a933160 |
| --- /dev/null |
| +++ b/internal/home/directory_id/migrations/0001_signed_out_all.sql |
| @@ -0,0 +1,11 @@ |
| +-- "Sign out all devices" (Oficina ID native spec §10, Paul's ruling of |
| +-- 2026-11-14). The directory records when a person last pressed it, as the |
| +-- receipt's iat, and refuses any assertion for that person issued at or |
| +-- before it: one minted in the 120 seconds before the press could otherwise |
| +-- still buy a fresh directory session. A mark matters only while such an |
| +-- assertion could be live, so rows older than five minutes are pruned. |
| +CREATE TABLE home_directory_signed_out_all ( |
| + person_ref TEXT PRIMARY KEY, |
| + at INTEGER NOT NULL |
| +); |
| +CREATE INDEX home_directory_signed_out_all_at ON home_directory_signed_out_all(at); |
diff --git a/internal/home/directory_native.go b/internal/home/directory_native.go| index c0409da..e4dce6b 100644 |
| --- a/internal/home/directory_native.go |
| +++ b/internal/home/directory_native.go |
| @@ -88,6 +88,10 @@ func (a *App) directoryNativeExchange(w http.ResponseWriter, r *http.Request) { |
| answer(http.StatusUnauthorized, "failed") |
| return |
| } |
| + if a.directorySigninAllowed(r.Context(), claims) != nil { |
| + answer(http.StatusUnauthorized, "failed") |
| + return |
| + } |
| // The jti is reserved in handoff's own committed transaction, as |
| // connect's NativeExchange does; a reserved jti that then mints nothing |
| // costs the app one fresh assertion (spec §7, accepted non-atomicity). |
| @@ -219,18 +223,32 @@ func (a *App) handleNoTeamsHelp(w http.ResponseWriter, r *http.Request) { |
| func (a *App) nativeSessionsStayNative(next http.Handler) http.Handler { |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| name := a.sessions.CookieName() |
| - token := cookieValue(r, name) |
| - if token == "" || r.URL.Path == nativeTeamsPath || r.URL.Path == nativeDirectorySignout { |
| + var tokens []string |
| + for _, c := range r.Cookies() { |
| + if c.Name == name { |
| + tokens = append(tokens, c.Value) |
| + } |
| + } |
| + if len(tokens) == 0 || r.URL.Path == nativeTeamsPath || r.URL.Path == nativeDirectorySignout { |
| next.ServeHTTP(w, r) |
| return |
| } |
| - var method string |
| - err := a.db.Writer().QueryRowContext(r.Context(), "SELECT method FROM sessions WHERE token_hash=?", sessions.HashToken(token)).Scan(&method) |
| - if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| - http.Error(w, "Directory unavailable", http.StatusServiceUnavailable) |
| - return |
| + // Every cookie of the session name is looked up, not just a lone |
| + // one: the session middleware takes the first of several, so a |
| + // native token hidden among duplicates must not get through. If any |
| + // is native, all of that name go; otherwise the request is untouched |
| + // and the existing ambiguous-session refusals still see it. |
| + native := len(tokens) > 8 // more than that is not a browser; strip without looking |
| + for _, token := range tokens[:min(len(tokens), 8)] { |
| + var method string |
| + err := a.db.Writer().QueryRowContext(r.Context(), "SELECT method FROM sessions WHERE token_hash=?", sessions.HashToken(token)).Scan(&method) |
| + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + http.Error(w, "Directory unavailable", http.StatusServiceUnavailable) |
| + return |
| + } |
| + native = native || method == nativeSessionMethod |
| } |
| - if method != nativeSessionMethod { |
| + if !native { |
| next.ServeHTTP(w, r) |
| return |
| } |
diff --git a/internal/home/exchange_test.go b/internal/home/exchange_test.go| index fe1baf0..9dbbadd 100644 |
| --- a/internal/home/exchange_test.go |
| +++ b/internal/home/exchange_test.go |
| @@ -50,7 +50,7 @@ func newExchangePair(t *testing.T) exchangePair { |
| t.Fatal(err) |
| } |
| t.Cleanup(func() { d.Close() }) |
| - if _, err = migrate.Apply(context.Background(), d, (Runtime{role: "directory"}).Schema()); err != nil { |
| + if _, err = migrate.Apply(context.Background(), d, migrate.Merge((Runtime{role: "directory"}).Schema(), directoryIDSchema)); err != nil { |
| t.Fatal(err) |
| } |
| dek := make([]byte, 32) |
diff --git a/internal/home/identity/migrations/0004_native.sql b/internal/home/identity/migrations/0004_native.sql| index 3520e23..b6b266e 100644 |
| --- a/internal/home/identity/migrations/0004_native.sql |
| +++ b/internal/home/identity/migrations/0004_native.sql |
| @@ -90,3 +90,12 @@ CREATE TABLE home_id_native_ceremonies ( |
| pending TEXT NOT NULL, |
| expires_at INTEGER NOT NULL |
| ); |
| + |
| +-- The credential origin's copy of the "Sign out all devices" mark (§10): the |
| +-- press time, per person. No grant created at or before it authenticates, |
| +-- and rows older than five minutes are pruned. |
| +CREATE TABLE home_id_signed_out_all ( |
| + person_ref TEXT PRIMARY KEY, |
| + at INTEGER NOT NULL |
| +); |
| +CREATE INDEX home_id_signed_out_all_at ON home_id_signed_out_all(at); |
diff --git a/internal/home/models.go b/internal/home/models.go| index 23fa74d..4bf9f7b 100644 |
| --- a/internal/home/models.go |
| +++ b/internal/home/models.go |
| @@ -51,3 +51,17 @@ var identitySchema = func() *migrate.Set { |
| } |
| return migrate.MustFromFS(sub, "home_id") |
| }() |
| + |
| +// directoryIDSchema is the directory's Oficina ID additions: today only the |
| +// "Sign out all devices" mark. Applied by the directory's ServingSchema, so |
| +// the frozen role schema is unchanged. |
| +// |
| +//go:embed directory_id/migrations/*.sql |
| +var directoryIDFS embed.FS |
| +var directoryIDSchema = func() *migrate.Set { |
| + sub, err := fs.Sub(directoryIDFS, "directory_id") |
| + if err != nil { |
| + panic(err) |
| + } |
| + return migrate.MustFromFS(sub, "home_directory_id") |
| +}() |
diff --git a/internal/home/native.go b/internal/home/native.go| index 68abb17..9f6ae9a 100644 |
| --- a/internal/home/native.go |
| +++ b/internal/home/native.go |
| @@ -331,8 +331,9 @@ func (a *App) nativeAuthed(handle func(tx *sql.Tx, g nativeGrant, body []byte, n |
| var lastUsed string |
| var ended sql.NullInt64 |
| g.hash = nativeHash(token) |
| - err = tx.QueryRow("SELECT person_ref,identity_id,device_key,platform,method,auth_time,expires_at,last_used_day,ended_at FROM home_id_grants WHERE grant_hash=?", g.hash). |
| - Scan(&g.person, &g.identityID, &g.deviceKey, &g.platform, &g.method, &g.authTime, &expires, &lastUsed, &ended) |
| + var created int64 |
| + err = tx.QueryRow("SELECT person_ref,identity_id,device_key,platform,method,auth_time,expires_at,last_used_day,ended_at,created_at FROM home_id_grants WHERE grant_hash=?", g.hash). |
| + Scan(&g.person, &g.identityID, &g.deviceKey, &g.platform, &g.method, &g.authTime, &expires, &lastUsed, &ended, &created) |
| if errors.Is(err, sql.ErrNoRows) || (err == nil && ended.Valid) { |
| nativeUnauthorized(w, nativeGrantEnded) |
| return |
| @@ -341,6 +342,17 @@ func (a *App) nativeAuthed(handle func(tx *sql.Tx, g nativeGrant, body []byte, n |
| nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| return |
| } |
| + // Belt and braces: "Sign out all devices" ends every grant in the |
| + // same transaction as its mark, so none created at or before the |
| + // mark should be live; if one is, it is not honoured. |
| + if before, err := signedOutBefore(r.Context(), tx, "home_id_signed_out_all", g.person, created); err != nil || before { |
| + if err != nil { |
| + nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| + } else { |
| + nativeUnauthorized(w, nativeGrantEnded) |
| + } |
| + return |
| + } |
| if expires <= now || lastUsed <= idleCutoff(now) { |
| if _, err = tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='expiry' WHERE grant_hash=? AND ended_at IS NULL", now, g.hash); err != nil || tx.Commit() != nil { |
| nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
diff --git a/internal/home/native_review_test.go b/internal/home/native_review_test.go| index 6fe115b..bf62014 100644 |
| --- a/internal/home/native_review_test.go |
| +++ b/internal/home/native_review_test.go |
| @@ -4,10 +4,12 @@ import ( |
| "context" |
| "fmt" |
| "net/http" |
| + "regexp" |
| "strings" |
| "testing" |
| "time" |
| + "amadan.net/oficina/home/handoff" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| ) |
| @@ -44,6 +46,20 @@ func TestNativeDirectorySessionIsConfined(t *testing.T) { |
| if w := exchangeRequest(f.p.directory, "GET", directoryOrigin+teamPath+"?team=AAA111", "", nil, native); w.Code == 200 && strings.Contains(w.Body.String(), "Blue team") { |
| t.Fatal("a native session opened the Team page") |
| } |
| + // Fable's re-review F1: a duplicate cookie name hides nothing. The |
| + // session middleware takes the first of two; both are stripped. |
| + junk := &http.Cookie{Name: native.Name, Value: "junk"} |
| + dup := exchangeRequest(f.p.directory, "GET", directoryOrigin+"/", "", nil, native, junk) |
| + if strings.Contains(dup.Body.String(), "Sign out all devices") || dup.Body.String() == browser.Body.String() { |
| + t.Fatal("a duplicated native cookie opened the directory") |
| + } |
| + if w := exchangeRequest(f.p.directory, "POST", directoryOrigin+signoutPath, directoryOrigin, map[string][]string{}, native, junk); w.Code == 303 { |
| + var n int |
| + f.p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE method=?", nativeSessionMethod).Scan(&n) |
| + if n == 0 { |
| + t.Fatal("a duplicated native cookie used the browser sign-out") |
| + } |
| + } |
| // A forged same-origin roster write carries it in vain. |
| exchangeRequest(f.p.directory, "POST", directoryOrigin+teamNamePath, directoryOrigin, map[string][]string{"team": {"AAA111"}, "name": {"Renamed"}}, native) |
| if w := directoryCall(t, f, "GET", nativeTeamsPath, "", native, nil); !strings.Contains(w.Body.String(), `"name":"Blue team"`) { |
| @@ -196,3 +212,83 @@ func TestNativeNetworkBucketsAndBeginDedupe(t *testing.T) { |
| t.Fatal("the web's passkey ceremonies were locked out", w.Code) |
| } |
| } |
| + |
| +// Fable's re-review F2: an assertion minted before "Sign out all devices" |
| +// (up to 120 s earlier, by /authorize or native assert) buys no directory |
| +// session afterwards; one minted after does. |
| +func TestNativeSignOutAllRefusesEarlierAssertions(t *testing.T) { |
| + t.Parallel() |
| + f := newMountedChooser(t) |
| + cred := f.p.credential |
| + session := signInFully(t, cred, "early@example.invalid") |
| + person := subjectOf(t, cred, session) |
| + // Minted before the press: a browser handoff and a native assertion. |
| + pending, intent := f.p.start(t) |
| + browserToken, _ := f.p.mint(t, intent, session) |
| + d := newDevice(t) |
| + grant, _ := d.signInByCode(t, cred.restart(t), "early@example.invalid") |
| + verifier, challenge := verifierFor(60) |
| + nativeToken := decodeReply(t, d.assert(t, cred, grant, directoryOrigin, challenge))["assertion"].(string) |
| + |
| + // The press, one second later so the marks are strictly after. |
| + time.Sleep(1100 * time.Millisecond) |
| + press := exchangeRequest(cred.App, "POST", Origin+signoutAllPath, Origin, map[string][]string{}, session) |
| + hop := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(press.Body.String()) |
| + if press.Code != 200 || hop == nil || !strings.Contains(press.Body.String(), "Finishing signing out of oficina.works") { |
| + t.Fatal("press", press.Code) |
| + } |
| + if w := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, map[string][]string{"assertion": {hop[1]}}); w.Code != 303 { |
| + t.Fatal("hop", w.Code) |
| + } |
| + var n int |
| + cred.db.Writer().QueryRow("SELECT count(*) FROM home_id_signed_out_all WHERE person_ref=?", person).Scan(&n) |
| + if n != 1 { |
| + t.Fatal("no mark on id.*") |
| + } |
| + // The earlier browser assertion cannot finish a sign-in. |
| + callback := exchangeRequest(f.p.directory, "POST", directoryOrigin+handoff.CallbackPath, Origin, map[string][]string{"assertion": {browserToken}}) |
| + if inbox := namedCookieOrNil(callback, "__Host-oficina-assertion-inbox"); inbox != nil { |
| + if fin := exchangeRequest(f.p.directory, "GET", directoryOrigin+handoff.FinishPath, "", nil, pending, inbox); sessionCookie(fin) != nil { |
| + t.Fatal("an assertion from before the press signed the directory in") |
| + } |
| + } |
| + // Nor the earlier native one. |
| + if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(nativeToken, verifier), nil, nil); w.Code != 401 { |
| + t.Fatal("a native assertion from before the press exchanged", w.Code) |
| + } |
| + // After the press, signing in works again. |
| + time.Sleep(1100 * time.Millisecond) |
| + again := signInFully(t, cred.restart(t), "early@example.invalid") |
| + pending, intent = f.p.start(t) |
| + token, _ := f.p.mint(t, intent, again) |
| + f.p.finish(t, token, pending) |
| +} |
| + |
| +// F4 and F5: a refused receipt lands on the failure page, which says what |
| +// did and did not sign out; and a browser holding someone else's directory |
| +// session keeps it. |
| +func TestNativeSignOutAllHopFailureAndOtherCookie(t *testing.T) { |
| + t.Parallel() |
| + f := newMountedChooser(t) |
| + w := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, map[string][]string{"assertion": {"nonsense"}}) |
| + if w.Code != 403 || !strings.Contains(w.Body.String(), "id.oficina.works is signed out") || !strings.Contains(w.Body.String(), Origin+signoutAllPath) { |
| + t.Fatal("failure page", w.Code) |
| + } |
| + cred := f.p.credential |
| + session := signInFully(t, cred, "owner@example.invalid") |
| + press := exchangeRequest(cred.App, "POST", Origin+signoutAllPath, Origin, map[string][]string{}, session) |
| + hop := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(press.Body.String()) |
| + someoneElse := f.session(t, chooserOther) |
| + done := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, map[string][]string{"assertion": {hop[1]}}, someoneElse) |
| + if done.Code != 303 { |
| + t.Fatal("hop", done.Code) |
| + } |
| + if c := namedCookieOrNil(done, f.p.directory.sessions.CookieName()); c != nil { |
| + t.Fatal("cleared another person's directory cookie") |
| + } |
| + var n int |
| + f.p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE subject=?", chooserOther).Scan(&n) |
| + if n != 1 { |
| + t.Fatal("another person's directory session ended") |
| + } |
| +} |
diff --git a/internal/home/runtime.go b/internal/home/runtime.go| index bed7dee..b8737d8 100644 |
| --- a/internal/home/runtime.go |
| +++ b/internal/home/runtime.go |
| @@ -212,7 +212,7 @@ func (cfg Runtime) Schema() *migrate.Set { |
| func (cfg Runtime) ServingSchema() *migrate.Set { |
| switch cfg.role { |
| case "directory": |
| - return migrate.Merge(cfg.Schema(), operator.DirectoryHTTPSchema, directorydata.TeamSchema) |
| + return migrate.Merge(cfg.Schema(), operator.DirectoryHTTPSchema, directorydata.TeamSchema, directoryIDSchema) |
| case "credential": |
| return migrate.Merge(cfg.Schema(), operator.CredentialHTTPSchema, identitySchema) |
| case "": |
diff --git a/internal/home/signout_all.go b/internal/home/signout_all.go| index 54c649e..b149daf 100644 |
| --- a/internal/home/signout_all.go |
| +++ b/internal/home/signout_all.go |
| @@ -1,29 +1,29 @@ |
| package home |
| import ( |
| + "context" |
| "crypto/sha256" |
| "crypto/subtle" |
| + "database/sql" |
| "encoding/base64" |
| "encoding/hex" |
| + "errors" |
| "net/http" |
| "time" |
| "amadan.net/rastrillo/rastrillo/assertion" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| ) |
| // signoutAllPath is "Sign out all devices" (§10): the slice-A stand-in for |
| // A2's Devices page. Paul, 2026-11-14: it ends every native grant AND every |
| // Home browser session the person has, on id.* and on the directory, |
| -// including the browser pressing the button. |
| -// |
| -// id.* holds the grants and its own sessions in one database, so those end |
| -// in one transaction. The directory's sessions live in the directory's own |
| -// database, which id.* cannot write; they end in one transaction there, when |
| -// this browser carries a signed receipt across (signedOutAllPath). What |
| -// cannot be made atomic is the hop between the two stores: if the browser |
| -// never makes it, the person's directory sessions run to their own expiry. |
| -// They grant identity only (never an app's content), and the native ones |
| -// cannot be renewed once the grants are gone. |
| +// including the browser pressing the button. id.* ends its half in one |
| +// transaction; the directory ends its half in one transaction when this |
| +// browser carries the signed receipt across (signedOutAllPath). Both record |
| +// a per-person mark, and assertions issued at or before it are refused. The |
| +// residual (the hop between the two stores, and team instances that do not |
| +// read the mark yet) is in the branch description. |
| const signoutAllPath = "/devices/sign-out-all" |
| // signedOutAllPath is the directory's receiver for that receipt. |
| @@ -84,6 +84,10 @@ func (a *App) handleSignoutAll(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| } |
| + if err = markSignedOutAll(tx, "home_id_signed_out_all", live.Subject, now); err != nil { |
| + a.serverError(w, r) |
| + return |
| + } |
| id, err := assertion.RandomID() |
| if err != nil { |
| a.serverError(w, r) |
| @@ -106,7 +110,55 @@ func (a *App) handleSignoutAll(w http.ResponseWriter, r *http.Request) { |
| // The hop to the directory: the same self-submitting form, transport and |
| // referrer policy as the assertion handoff. |
| w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") |
| - a.render(w, r, http.StatusOK, "assertion.html", map[string]any{"Action": a.origins.Directory + signedOutAllPath, "Token": receipt}) |
| + a.render(w, r, http.StatusOK, "id_signout_all_hop.html", map[string]any{"Action": a.origins.Directory + signedOutAllPath, "Token": receipt}) |
| +} |
| + |
| +// markSignedOutAll records the press, keeping the later of two, and prunes |
| +// marks too old to matter: no assertion lives longer than 120 seconds. |
| +func markSignedOutAll(tx *sql.Tx, table, person string, at int64) error { |
| + if _, err := tx.Exec("DELETE FROM "+table+" WHERE at<?", at-signedOutAllKeep); err != nil { |
| + return errIDProof |
| + } |
| + if _, err := tx.Exec("INSERT INTO "+table+"(person_ref,at) VALUES(?,?) ON CONFLICT(person_ref) DO UPDATE SET at=MAX(at,excluded.at)", person, at); err != nil { |
| + return errIDProof |
| + } |
| + return nil |
| +} |
| + |
| +const signedOutAllKeep = 300 |
| + |
| +type rowQueryer interface { |
| + QueryRowContext(context.Context, string, ...any) *sql.Row |
| +} |
| + |
| +// signedOutBefore reports whether something issued at iat predates the |
| +// person's latest "Sign out all devices" (iat at or before the mark). |
| +func signedOutBefore(ctx context.Context, q rowQueryer, table, person string, iat int64) (bool, error) { |
| + var at int64 |
| + err := q.QueryRowContext(ctx, "SELECT at FROM "+table+" WHERE person_ref=?", person).Scan(&at) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + return iat <= at, nil |
| +} |
| + |
| +// errSignedOutAll refuses a directory sign-in from an assertion issued |
| +// before the person pressed "Sign out all devices". |
| +var errSignedOutAll = errors.New("home: assertion predates sign out all devices") |
| + |
| +// directorySigninAllowed is the directory's browser-finish check. |
| +func (a *App) directorySigninAllowed(ctx context.Context, c assertion.Claims) error { |
| + before, err := signedOutBefore(ctx, a.db.Writer(), "home_directory_signed_out_all", c.Subject, c.IssuedAt) |
| + if err != nil { |
| + return err |
| + } |
| + if before { |
| + return errSignedOutAll |
| + } |
| + return nil |
| } |
| // handleSignedOutAll is the directory's half: POST /auth/signed-out-all |
| @@ -115,45 +167,63 @@ func (a *App) handleSignoutAll(w http.ResponseWriter, r *http.Request) { |
| // the receipt's jti, then lands this browser on the signed-out page. |
| func (a *App) handleSignedOutAll(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
| + failed := func(status int) { |
| + a.render(w, r, status, "directory_signout_all_failed.html", map[string]any{"Again": a.origins.Credential + signoutAllPath}) |
| + } |
| if origins := r.Header.Values("Origin"); len(origins) != 1 || origins[0] != a.origins.Credential { |
| - a.failDirectoryHandoff(w, r, http.StatusForbidden) |
| + failed(http.StatusForbidden) |
| return |
| } |
| r.Body = http.MaxBytesReader(w, r.Body, 16<<10) |
| if r.ParseForm() != nil || len(r.PostForm["assertion"]) != 1 || len(r.PostForm) != 1 { |
| - a.failDirectoryHandoff(w, r, http.StatusBadRequest) |
| + failed(http.StatusBadRequest) |
| return |
| } |
| claims, err := a.handoffStore.Verify(r.PostForm.Get("assertion"), time.Now()) |
| if err != nil || subtle.ConstantTimeCompare([]byte(claims.Nonce), []byte(signoutAllNonce(claims.ID))) != 1 || !ValidPersonRef(claims.Subject) { |
| - a.failDirectoryHandoff(w, r, http.StatusForbidden) |
| + failed(http.StatusForbidden) |
| return |
| } |
| tx, err := a.db.Writer().BeginTx(r.Context(), nil) |
| if err != nil { |
| - a.failDirectoryHandoff(w, r, http.StatusServiceUnavailable) |
| + failed(http.StatusServiceUnavailable) |
| return |
| } |
| defer tx.Rollback() |
| // Reserved here rather than through handoff.Store.Reserve, on purpose: |
| - // the receipt is one-shot, so its jti and the sessions it ends commit |
| - // together. The key is handoff's jtiHash, SHA-256(iss ‖ 0 ‖ jti), so the |
| - // one ledger still refuses it at every other door. |
| + // the receipt is one-shot, so its jti, the sessions it ends and the mark |
| + // commit together. The key is handoff's jtiHash, SHA-256(iss ‖ 0 ‖ jti), |
| + // so the one ledger still refuses it at every other door. |
| jti := sha256.Sum256([]byte(claims.Issuer + "\x00" + claims.ID)) |
| res, err := tx.Exec("INSERT INTO oficina_handoff_replay(jti_hash,expires_at) VALUES(?,?) ON CONFLICT DO NOTHING", hex.EncodeToString(jti[:]), claims.ExpiresAt) |
| if err != nil { |
| - a.failDirectoryHandoff(w, r, http.StatusServiceUnavailable) |
| + failed(http.StatusServiceUnavailable) |
| return |
| } |
| if n, err := res.RowsAffected(); err != nil || n != 1 { |
| - a.failDirectoryHandoff(w, r, http.StatusForbidden) |
| + failed(http.StatusForbidden) |
| return |
| } |
| - if _, err = tx.Exec("DELETE FROM sessions WHERE subject=?", claims.Subject); err != nil || tx.Commit() != nil { |
| - a.failDirectoryHandoff(w, r, http.StatusServiceUnavailable) |
| + // Whose session does this browser hold? Its cookie is cleared only if it |
| + // is the receipt's person's, which the delete below ends anyway. |
| + mine := false |
| + if token := cookieValue(r, a.sessions.CookieName()); token != "" { |
| + var subject string |
| + if tx.QueryRow("SELECT subject FROM sessions WHERE token_hash=?", sessions.HashToken(token)).Scan(&subject) == nil { |
| + mine = subject == claims.Subject |
| + } |
| + } |
| + if _, err = tx.Exec("DELETE FROM sessions WHERE subject=?", claims.Subject); err != nil { |
| + failed(http.StatusServiceUnavailable) |
| return |
| } |
| - idCookie(w, a.sessions.CookieName(), "", -1) |
| + if markSignedOutAll(tx, "home_directory_signed_out_all", claims.Subject, claims.IssuedAt) != nil || tx.Commit() != nil { |
| + failed(http.StatusServiceUnavailable) |
| + return |
| + } |
| + if mine { |
| + idCookie(w, a.sessions.CookieName(), "", -1) |
| + } |
| idCookie(w, "__Host-oficina-signed-out-all", "1", 300) |
| http.Redirect(w, r, "/signed-out", http.StatusSeeOther) |
| } |
diff --git a/internal/home/templates/directory_signed_out.html b/internal/home/templates/directory_signed_out.html| index 35cb536..0f62138 100644 |
| --- a/internal/home/templates/directory_signed_out.html |
| +++ b/internal/home/templates/directory_signed_out.html |
| @@ -8,7 +8,7 @@ |
| </form> |
| {{else if .Data.AllDevices}}{{with signedOutDoor}} |
| <h1>All devices are signed out</h1> |
| -<p estilo-signin-body>Your Oficina ID is signed out in this browser, in every other browser, and in the Oficina apps on every device. Each one asks you to sign in again.</p> |
| +<p estilo-signin-body>Your Oficina ID is signed out on id.oficina.works and oficina.works in every browser. The Oficina apps sign out as each device next checks in. A team's app already open in a browser stays signed in until its own session ends.</p> |
| <p><a href="{{.Link.Href}}" rst-btn="primary">{{.Link.Label}}</a></p> |
| {{end}}{{else}}{{with signedOutDoor}} |
| <h1>{{.Heading}}</h1> |
diff --git a/internal/home/templates/directory_signout_all_failed.html b/internal/home/templates/directory_signout_all_failed.html| new file mode 100644 |
| index 0000000..5987651 |
| --- /dev/null |
| +++ b/internal/home/templates/directory_signout_all_failed.html |
| @@ -0,0 +1,7 @@ |
| +{{define "title"}}Not finished signing out · Oficina{{end}} |
| +{{define "content"}} |
| +<h1>oficina.works may still be signed in</h1> |
| +<p estilo-signin-body>id.oficina.works is signed out, and so are your Oficina apps as each device next checks in. Signing out of oficina.works didn’t finish, so it may still be signed in, in this browser and others.</p> |
| +<p estilo-signin-body>Sign in again and press Sign out all devices once more to finish.</p> |
| +<p><a href="{{.Data.Again}}" rst-btn="primary">Sign in and try again</a></p> |
| +{{end}} |
diff --git a/internal/home/templates/id_signout_all.html b/internal/home/templates/id_signout_all.html| index 55e8a6b..b95d0a5 100644 |
| --- a/internal/home/templates/id_signout_all.html |
| +++ b/internal/home/templates/id_signout_all.html |
| @@ -1,8 +1,9 @@ |
| {{define "title"}}Sign out all devices · Oficina{{end}} |
| {{define "content"}} |
| <h1>Sign out all devices</h1> |
| -<p>This signs your Oficina ID out everywhere: the Oficina apps on every Mac, iPhone and iPad, and every browser, this one included.</p> |
| -<p>Use it if you have lost a device, or if you signed in somewhere you shouldn't have. An app that is offline finds out when it next connects; until then it can keep what it already has open for up to seven days.</p> |
| +<p>This ends your Oficina ID sign-ins on id.oficina.works and oficina.works in every browser, this one included. The Oficina apps on every Mac, iPhone and iPad sign out as each device next checks in.</p> |
| +<p>A team's app already open in a browser, such as a Docs tab, stays signed in until its own session ends. An app on a device that stays offline can keep what it already has for up to seven days.</p> |
| +<p>If you have lost a device, this stops it signing in again with your Oficina ID. What it already has open can keep working for up to seven days.</p> |
| <form method="post" action="/devices/sign-out-all" rst-form> |
| <div rst-form-foot> |
| <button type="submit" rst-btn="danger">Sign out all devices</button> |
diff --git a/internal/home/templates/id_signout_all_hop.html b/internal/home/templates/id_signout_all_hop.html| new file mode 100644 |
| index 0000000..aa35980 |
| --- /dev/null |
| +++ b/internal/home/templates/id_signout_all_hop.html |
| @@ -0,0 +1,19 @@ |
| +{{define "title"}}Finishing signing out · Oficina{{end}} |
| +{{define "head"}} |
| +{{/* Like assertion.html: the form submits itself (static/assertion.js) and |
| + the card shows only if that stalls, or at once with scripts off. */}} |
| +<style> |
| +[estilo-handoff] { animation: estilo-reveal 0s 1.5s both; } |
| +@keyframes estilo-reveal { from { visibility: hidden } to { visibility: visible } } |
| +</style> |
| +<noscript><style>[estilo-handoff] { animation: none; }</style></noscript> |
| +{{end}} |
| +{{define "content"}} |
| +<h1>Finishing signing out of oficina.works…</h1> |
| +<p estilo-signin-body>id.oficina.works and your Oficina apps are signed out. Select Continue to sign out of oficina.works too, if this page doesn’t move on.</p> |
| +<form method="post" action="{{.Data.Action}}" rst-form data-assertion-handoff> |
| +<input type="hidden" name="assertion" value="{{.Data.Token}}"> |
| +<button type="submit" rst-btn="primary">Continue</button> |
| +</form> |
| +{{end}} |
| +{{define "scripts"}}<script src='{{v "/static/assertion.js"}}' async></script>{{end}} |