oficina / home Public

Oficina ID native: grants, device-key proof, email codes, assert

Human

Prompt

Implement the Home (id.oficina.works) half of slice A of the approved Oficina ID native spec. Paul approved the spec and building on 2026-11-14.

Read first: native-levelup/BRIEF.md (own worktree from fresh origin/main, repo AGENTS.md, amadan workflow, agent account, never -as-human, pinned-toolchain make gates, no deploys, do not merge). Then in the Home repo: docs/superpowers/specs/2026-11-14-oficina-id-native.md (binding; slice table §14), 2026-11-13-oficina-id-slice-1.md (binding base), Home AGENTS.md.

Scope — slice A, Home side only (another agent does connect/NativeExchange/choose page/IsHomeDerived in parallel on its own branch; a third does the Swift client; coordinate only through the spec's wire formats, and if the spec is ambiguous about a wire detail, pick the reading most consistent with it, write it into a short "wire notes" section of your branch description, and flag it):
- the native grant + device-key proof (§3), persistent replay table, per-grant rate limit, server Date for clock offset;
- email code start/resend/verify with every limit in §4 (per-(address, device key) caps, daily cap, returning-key exemption by end_reason, per-IP-bucket live starts, 503 when full, shared email budget with the web, sealed addresses, no codes/addresses in logs; Keymail addresses get the code in slice A);
- native passkey sign-in (§5): passkey/begin, passkey/finish against RP id.oficina.works, plus the static /.well-known/apple-app-site-association with webcredentials for the five App IDs 9U4A84C4WK.works.oficina.{calls,docs,sheets,calendar,memoria} (no applinks);
- assert with the shared mintPolicy (empty in slice A), native nonce derivation;
- signout, "Sign out all devices" on the web, replacement revoking every grant, first passkey enrolment (native or web) revoking passkey-less grants;
- directory teams listing + zero-teams help;
- every slice-A gate in §13 that belongs to Home, as tests.
Not in scope: A2 (multiple identities UI, Devices page, Keymail sheet), B (native recovery/enrolment), C–E.

Process: small reviewable commits; make ci green; push; describe the branch on the hub with tasks; stop for review. Report: branch, tip, what's done vs deferred, gate output, wire notes, open questions.

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

Adds home_id_grants and the native proof (Authorization: OficinaID + Oficina-Proof, persistent 61 s replay table, 120 calls/grant/minute, fails closed when full, Date on every answer and now on a 401), POST /native/v1/code/{start,resend,verify} with every §4 limit as persistent buckets, the returning-key exemption by end_reason and the shared web email budget, POST /native/v1/assert with the native nonce and the shared mintPolicy (also called by /authorize), and POST /native/v1/signout. Credential role only.
Agent notes
identity_id, code MACs and the native blinds are HKDF subkeys of HOME_PEPPER (crypto.Derive, 'oficina-id/<purpose>/v1'), so no new secret is needed at deploy. Classification is skipped at code/start: in slice A every address, Keymail included, gets a code, so the classifier's outbound calls would decide nothing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b001884cbd61ad1b1d708cc328397e40db53bd1d parent 979dac4
9 files changed, +2,263 −0
  • internal/home/app.go +3 −0
  • internal/home/exchange.go +5 −0
  • internal/home/identity/migrations/0004_native.sql +90 −0
  • internal/home/native.go +497 −0
  • internal/home/native_assert.go +84 −0
  • internal/home/native_code.go +602 −0
  • internal/home/native_code_test.go +470 −0
  • internal/home/native_grant_test.go +273 −0
  • internal/home/native_helpers_test.go +239 −0
diff --git a/internal/home/app.go b/internal/home/app.go
index bdb3e3d..b42ad75 100644
--- a/internal/home/app.go
+++ b/internal/home/app.go
@@ -205,6 +205,9 @@ func (a *App) Router() http.Handler {
r.With(a.credentialOnly).Post(signoutPath, a.handleCredentialSignout)
r.With(a.credentialOnly).Get(signoutPath, a.handleCredentialSignoutPage)
r.With(a.credentialOnly).Get("/signed-out", func(w http.ResponseWriter, r *http.Request) { a.render(w, r, 200, "id_signed_out.html", nil) })
+ // Oficina ID for the native apps (native.go): JSON only, outside
+ // csrf.Protect because each refuses any browser evidence header.
+ a.mountNative(r)
}
r.Group(func(r chi.Router) {
diff --git a/internal/home/exchange.go b/internal/home/exchange.go
index c2c9a39..e9023bd 100644
--- a/internal/home/exchange.go
+++ b/internal/home/exchange.go
@@ -116,6 +116,11 @@ func (a *App) handleAssertion(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/signin?return_to=%2Fauthorize%2Fresume", http.StatusSeeOther)
return
}
+ // The one mint rule, shared with the native assert (native_assert.go).
+ if mintPolicy(intent.Consumer, session.Method) != nil {
+ a.failAssertion(w, r, assertionConsumer)
+ return
+ }
if r.Method == http.MethodGet {
if tx.Commit() != nil {
a.failAssertion(w, r, assertionSession)
diff --git a/internal/home/identity/migrations/0004_native.sql b/internal/home/identity/migrations/0004_native.sql
new file mode 100644
index 0000000..d2d475d
--- /dev/null
+++ b/internal/home/identity/migrations/0004_native.sql
@@ -0,0 +1,90 @@
+-- Oficina ID, the native slice (docs/superpowers/specs/2026-11-14-oficina-id-native.md).
+--
+-- A grant is a device's long-lived Oficina ID credential (§3). Only the
+-- SHA-256 of its token is stored. identity_id is an HMAC of the person ref
+-- under a Home-only key, so a device can tell identities apart without
+-- holding the ref. Ended rows keep device_key for 365 days so that §4 can
+-- recognise a returning device; end_reason says how it ended.
+CREATE TABLE home_id_grants (
+ grant_hash TEXT PRIMARY KEY,
+ person_ref TEXT NOT NULL,
+ identity_id TEXT NOT NULL,
+ device_key TEXT NOT NULL,
+ platform TEXT NOT NULL,
+ method TEXT NOT NULL,
+ auth_time INTEGER NOT NULL,
+ created_at INTEGER NOT NULL,
+ last_used_day TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ ended_at INTEGER,
+ end_reason TEXT CHECK (end_reason IN ('expiry','lru','enrolment','signout','all_devices','revoke','replacement'))
+);
+CREATE INDEX home_id_grants_person ON home_id_grants(person_ref, ended_at);
+CREATE INDEX home_id_grants_device ON home_id_grants(device_key, person_ref);
+CREATE INDEX home_id_grants_ended ON home_id_grants(ended_at);
+
+-- The proof replay table (§3): one row per accepted jti, written only after
+-- the grant and the signature verify, kept 60 seconds. It is also the
+-- per-grant rate limit's counter.
+CREATE TABLE home_id_native_replay (
+ jti_hash TEXT PRIMARY KEY,
+ grant_hash TEXT NOT NULL,
+ expires_at INTEGER NOT NULL
+);
+CREATE INDEX home_id_native_replay_grant ON home_id_native_replay(grant_hash, expires_at);
+CREATE INDEX home_id_native_replay_expiry ON home_id_native_replay(expires_at);
+
+-- A live email code (§4). The address is sealed before it is written and the
+-- row is deleted at verify or expiry, under secure_delete.
+-- blind_index is a Home-keyed HMAC used only to keep one live code per (address, device key);
+-- ip_bucket is blinded the same way. code_mac is an HMAC of the code, never
+-- the code.
+CREATE TABLE home_id_native_starts (
+ start_hash TEXT PRIMARY KEY,
+ sealed_address BLOB NOT NULL,
+ blind_index TEXT NOT NULL,
+ device_key TEXT NOT NULL,
+ platform TEXT NOT NULL,
+ ip_bucket TEXT NOT NULL,
+ code_mac TEXT NOT NULL,
+ sends INTEGER NOT NULL,
+ last_send INTEGER NOT NULL,
+ attempts INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL,
+ UNIQUE (blind_index, device_key)
+);
+CREATE INDEX home_id_native_starts_ip ON home_id_native_starts(ip_bucket, expires_at);
+CREATE INDEX home_id_native_starts_expiry ON home_id_native_starts(expires_at);
+
+-- A code verified for an account that has a passkey (§4): the person must
+-- still assert one. Valid five minutes and bound to the start and its key.
+CREATE TABLE home_id_native_pending (
+ pending_hash TEXT PRIMARY KEY,
+ person_ref TEXT NOT NULL,
+ start_hash TEXT NOT NULL,
+ device_key TEXT NOT NULL,
+ platform TEXT NOT NULL,
+ method TEXT NOT NULL,
+ expires_at INTEGER NOT NULL
+);
+CREATE INDEX home_id_native_pending_expiry ON home_id_native_pending(expires_at);
+
+-- Persistent fixed-window counters for §4's limits. Keys are blinded; none
+-- shares a key with home_id_attempts, which recovery uses.
+CREATE TABLE home_id_native_buckets (
+ bucket TEXT PRIMARY KEY,
+ count INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL
+);
+CREATE INDEX home_id_native_buckets_expiry ON home_id_native_buckets(expires_at);
+
+-- Native passkey challenges count within home_id_ceremonies; this records
+-- the device key and platform a native challenge is bound to (§5), keyed by
+-- the same challenge and deleted with it.
+CREATE TABLE home_id_native_ceremonies (
+ challenge TEXT PRIMARY KEY,
+ device_key TEXT NOT NULL,
+ platform TEXT NOT NULL,
+ pending TEXT NOT NULL,
+ expires_at INTEGER NOT NULL
+);
diff --git a/internal/home/native.go b/internal/home/native.go
new file mode 100644
index 0000000..872061d
--- /dev/null
+++ b/internal/home/native.go
@@ -0,0 +1,497 @@
+package home
+
+import (
+ "crypto/elliptic"
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "strings"
+ "time"
+
+ assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
+ "github.com/go-chi/chi/v5"
+ strictjson "github.com/go-json-experiment/json"
+)
+
+// The native half of Oficina ID (docs/superpowers/specs/2026-11-14-oficina-id-native.md).
+//
+// Every endpoint here lives under nativePrefix on the credential origin. They
+// take JSON only, answer no-store, send no CORS headers, render nothing and
+// refuse any request carrying Origin or Sec-Fetch-Site: a browser has no
+// business here, and refusing its evidence headers keeps every one of these
+// endpoints out of reach of a page (§4).
+const nativePrefix = "/native/v1"
+
+const (
+ // nativeProofContext domain-separates the device-key proof (§3).
+ nativeProofContext = "oficina-id/native-proof/v1"
+ // nativeNonceContext derives a native assertion's nonce (§7).
+ nativeNonceContext = "oficina-id/native/v1"
+
+ nativeProofSkew = 30 // |iat − now| allowed, seconds
+ nativeReplayHold = 61 // seconds a jti stays in the replay table: see below
+ nativeReplayPerMin = 120 // accepted calls per grant per minute
+ nativeGrantIdleDays = 90 // a grant unused this long has expired
+ nativeGrantLife = 365 * day // absolute grant lifetime
+ nativeGrantKeep = 365 * day // how long an ended grant keeps its device key
+ nativeGrantsPerID = 20 // live grants per person; a 21st ends the LRU
+ nativeBodyLimit = 64 << 10
+ day = 24 * 3600
+)
+
+// nativeReplayCap is how many replay rows the table holds before it fails
+// closed. A variable only so a test can fill it without 100,000 inserts.
+var nativeReplayCap = 100000
+
+// nativePlatforms is the closed set a device may report. It is self-reported
+// and decides nothing; it exists so A2's Devices page can draw a fixed label.
+var nativePlatforms = map[string]bool{"macos": true, "ios": true, "ipados": true}
+
+// mountNative mounts the native endpoints on the credential role. They sit
+// outside csrf.Protect: they refuse every browser evidence header instead.
+func (a *App) mountNative(r chi.Router) {
+ r.Group(func(r chi.Router) {
+ r.Use(a.credentialOnly)
+ r.Post(nativePrefix+"/code/start", a.nativeCodeStart)
+ r.Post(nativePrefix+"/code/resend", a.nativeCodeResend)
+ r.Post(nativePrefix+"/code/verify", a.nativeCodeVerify)
+ r.Post(nativePrefix+"/assert", a.nativeAuthed(a.nativeAssert))
+ r.Post(nativePrefix+"/signout", a.nativeAuthed(a.nativeSignout))
+ })
+}
+
+// nativeReply is every native answer. Date is set explicitly because the
+// client corrects its clock from it (§3); net/http would add one, but a
+// header the protocol depends on should not rest on a server default.
+func nativeReply(w http.ResponseWriter, status int, v any) {
+ h := w.Header()
+ h.Set("Cache-Control", "no-store")
+ h.Set("Content-Type", "application/json")
+ h.Set("X-Content-Type-Options", "nosniff")
+ h.Set("Date", time.Now().UTC().Format(http.TimeFormat))
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+func nativeFail(w http.ResponseWriter, status int, code string) {
+ nativeReply(w, status, map[string]string{"error": code})
+}
+
+// nativeUnauthorized carries the server's clock, so a client whose proof
+// failed on iat can correct its offset and retry once (§3).
+func nativeUnauthorized(w http.ResponseWriter, code string) {
+ nativeReply(w, http.StatusUnauthorized, map[string]any{"error": code, "now": time.Now().Unix()})
+}
+
+// nativeIntake applies the transport rules every native endpoint shares and
+// returns the raw body, which the proof's bh covers byte for byte.
+func nativeIntake(w http.ResponseWriter, r *http.Request) ([]byte, bool) {
+ if _, ok := r.Header["Origin"]; ok {
+ nativeFail(w, http.StatusForbidden, "browser")
+ return nil, false
+ }
+ if _, ok := r.Header["Sec-Fetch-Site"]; ok {
+ nativeFail(w, http.StatusForbidden, "browser")
+ return nil, false
+ }
+ if r.URL.RawQuery != "" {
+ nativeFail(w, http.StatusBadRequest, "request")
+ return nil, false
+ }
+ media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if err != nil || media != "application/json" {
+ nativeFail(w, http.StatusUnsupportedMediaType, "json")
+ return nil, false
+ }
+ body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, nativeBodyLimit))
+ if err != nil {
+ nativeFail(w, http.StatusRequestEntityTooLarge, "request")
+ return nil, false
+ }
+ return body, true
+}
+
+// decodeNative is strict: unknown members, duplicates and trailing data are
+// all refusals, so two parsers can never read one body two ways.
+func decodeNative(body []byte, v any) bool {
+ return strictjson.Unmarshal(body, v, strictjson.RejectUnknownMembers(true)) == nil
+}
+
+// b64 is the one encoding on the native wire: base64url without padding.
+var nb64 = base64.RawURLEncoding
+
+func decodeB64(s string, n int) ([]byte, bool) {
+ b, err := nb64.Strict().DecodeString(s)
+ if err != nil || (n > 0 && len(b) != n) || nb64.EncodeToString(b) != s {
+ return nil, false
+ }
+ return b, true
+}
+
+// decodeDeviceKey accepts a 65-byte uncompressed P-256 point, base64url, and
+// nothing else — the shape rastrillo/crypto.Verify takes.
+func decodeDeviceKey(s string) ([]byte, bool) {
+ if len(s) != 87 {
+ return nil, false
+ }
+ b, ok := decodeB64(s, 65)
+ if !ok {
+ return nil, false
+ }
+ if x, _ := elliptic.Unmarshal(elliptic.P256(), b); x == nil {
+ return nil, false
+ }
+ return b, true
+}
+
+// nativeProof is the Oficina-Proof payload (§3). No JWT, no algorithm field.
+type nativeProof struct {
+ V int `json:"v"`
+ HTM string `json:"htm"`
+ HTU string `json:"htu"`
+ IAT int64 `json:"iat"`
+ JTI string `json:"jti"`
+ BH string `json:"bh"`
+}
+
+var errNativeProof = errors.New("home: native proof refused")
+
+// parseNativeProof reads the header without trusting any of it yet.
+func parseNativeProof(r *http.Request) (nativeProof, []byte, []byte, error) {
+ var p nativeProof
+ values := r.Header.Values("Oficina-Proof")
+ if len(values) != 1 || len(values[0]) > 2048 {
+ return p, nil, nil, errNativeProof
+ }
+ enc, sigEnc, ok := strings.Cut(values[0], ".")
+ if !ok || strings.Contains(sigEnc, ".") {
+ return p, nil, nil, errNativeProof
+ }
+ payload, ok := decodeB64(enc, 0)
+ if !ok {
+ return p, nil, nil, errNativeProof
+ }
+ sig, ok := decodeB64(sigEnc, 64)
+ if !ok {
+ return p, nil, nil, errNativeProof
+ }
+ if !decodeNative(payload, &p) {
+ return p, nil, nil, errNativeProof
+ }
+ if p.V != 1 || p.HTM == "" || p.HTU == "" || p.IAT <= 0 || !nativeJTI(p.JTI) || len(p.BH) != 43 {
+ return p, nil, nil, errNativeProof
+ }
+ return p, payload, sig, nil
+}
+
+func nativeJTI(s string) bool {
+ if len(s) < 16 || len(s) > 64 {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ if !alphaNumeric(s[i]) && s[i] != '-' && s[i] != '_' {
+ return false
+ }
+ }
+ return true
+}
+func alphaNumeric(b byte) bool {
+ return b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9'
+}
+
+// verifyNativeProof is the whole check except the jti, which the caller
+// records only after this passes (§3: no jti row before the grant and the
+// signature verify).
+func (a *App) verifyNativeProof(r *http.Request, body, key []byte, p nativeProof, payload, sig []byte, now int64) bool {
+ if !assertioncrypto.Verify(key, nativeProofContext, payload, sig) {
+ return false
+ }
+ bh := sha256.Sum256(body)
+ skew := p.IAT - now
+ return p.HTM == r.Method &&
+ p.HTU == a.origins.Credential+r.URL.Path &&
+ skew <= nativeProofSkew && skew >= -nativeProofSkew &&
+ hmac.Equal([]byte(p.BH), []byte(nb64.EncodeToString(bh[:])))
+}
+
+// nativeKey derives one purpose's Home-only key from the pepper. The pepper
+// never leaves Home, and each purpose gets its own HKDF output, so no two
+// uses of it share a key (§3: identity_id is an HMAC under a dedicated key).
+func (a *App) nativeKey(purpose string) []byte {
+ return assertioncrypto.Derive(a.secrets.Pepper, "oficina-id/"+purpose+"/v1")
+}
+
+func (a *App) nativeMAC(purpose string, parts ...string) string {
+ m := hmac.New(sha256.New, a.nativeKey(purpose))
+ for _, p := range parts {
+ m.Write([]byte(p))
+ m.Write([]byte{0})
+ }
+ return hex.EncodeToString(m.Sum(nil))
+}
+
+// identityID is what a device keys an identity by; it never holds the ref.
+func (a *App) identityID(person string) string {
+ m := hmac.New(sha256.New, a.nativeKey("identity-id"))
+ m.Write([]byte(person))
+ return nb64.EncodeToString(m.Sum(nil))
+}
+
+func nativeHash(s string) string { h := sha256.Sum256([]byte(s)); return hex.EncodeToString(h[:]) }
+
+func nativeToken() (string, error) {
+ b := make([]byte, 32)
+ if _, err := rand.Read(b); err != nil {
+ return "", err
+ }
+ return nb64.EncodeToString(b), nil
+}
+
+// nativeNonce is the only nonce a native assertion carries:
+// H("oficina-id/native/v1\0" ‖ challenge), cut to the 16 bytes the
+// assertion format requires. Home derives it; the caller never chooses it,
+// so a grant holder cannot obtain an assertion bearing a browser's nonce.
+func nativeNonce(challenge []byte) string {
+ h := sha256.New()
+ h.Write([]byte(nativeNonceContext))
+ h.Write([]byte{0})
+ h.Write(challenge)
+ return nb64.EncodeToString(h.Sum(nil)[:16])
+}
+
+// nativeGrant is a live grant as loaded for one authenticated call.
+type nativeGrant struct {
+ hash, person, identityID, deviceKey, platform, method string
+ authTime int64
+}
+
+func dayOf(unix int64) string { return time.Unix(unix, 0).UTC().Format(dayFormat) }
+
+// idleCutoff is the newest last_used_day that has already expired: a grant
+// last used on day D lapses at the start of D+91, whatever hour it was used.
+func idleCutoff(now int64) string { return dayOf(now - (nativeGrantIdleDays+1)*day) }
+
+// nativeAuthed authenticates a grant-holding call (§3) and hands the handler
+// an open writer transaction. The handler's answer is committed together
+// with the jti, so a refused handler still spends its jti.
+func (a *App) nativeAuthed(handle func(tx *sql.Tx, g nativeGrant, body []byte, now int64) (int, any)) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ body, ok := nativeIntake(w, r)
+ if !ok {
+ return
+ }
+ auth := r.Header.Values("Authorization")
+ token, found := "", false
+ if len(auth) == 1 {
+ token, found = strings.CutPrefix(auth[0], "OficinaID ")
+ }
+ if !found || len(token) != 43 {
+ nativeUnauthorized(w, "grant")
+ return
+ }
+ if _, ok := decodeB64(token, 32); !ok {
+ nativeUnauthorized(w, "grant")
+ return
+ }
+ p, payload, sig, err := parseNativeProof(r)
+ if err != nil {
+ nativeUnauthorized(w, "proof")
+ return
+ }
+ tx, now, err := a.idTransaction(r.Context())
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ defer tx.Rollback()
+ var g nativeGrant
+ var expires int64
+ 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)
+ if errors.Is(err, sql.ErrNoRows) || (err == nil && ended.Valid) {
+ nativeUnauthorized(w, "grant")
+ return
+ }
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ 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")
+ return
+ }
+ nativeUnauthorized(w, "grant")
+ return
+ }
+ key, ok := decodeDeviceKey(g.deviceKey)
+ if !ok || !a.verifyNativeProof(r, body, key, p, payload, sig, now) {
+ nativeUnauthorized(w, "proof")
+ return
+ }
+ // Only now, with the grant live and the signature good, does the jti
+ // touch the table. A row lives 61 seconds, not 60: iat may be 30
+ // seconds ahead of now and is accepted until 30 seconds behind, so
+ // the last second a replay could pass is now+60, and the row must
+ // still be there then.
+ if _, err = tx.Exec("DELETE FROM home_id_native_replay WHERE expires_at<=?", now); err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ var total, mine int
+ if tx.QueryRow("SELECT count(*) FROM home_id_native_replay").Scan(&total) != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if total >= nativeReplayCap {
+ // Fails closed: a full table refuses every proof rather than
+ // forgetting the oldest ones and readmitting their replays.
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if tx.QueryRow("SELECT count(*) FROM home_id_native_replay WHERE grant_hash=?", g.hash).Scan(&mine) != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if mine >= nativeReplayPerMin {
+ nativeFail(w, http.StatusTooManyRequests, "rate_limited")
+ return
+ }
+ res, err := tx.Exec("INSERT INTO home_id_native_replay VALUES(?,?,?) ON CONFLICT DO NOTHING", nativeHash(g.hash+"\x00"+p.JTI), g.hash, now+nativeReplayHold)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if n, err := res.RowsAffected(); err != nil || n != 1 {
+ nativeUnauthorized(w, "replay")
+ return
+ }
+ if today := dayOf(now); lastUsed != today {
+ if _, err = tx.Exec("UPDATE home_id_grants SET last_used_day=? WHERE grant_hash=?", today, g.hash); err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ }
+ status, reply := handle(tx, g, body, now)
+ if status == 0 || tx.Commit() != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ nativeReply(w, status, reply)
+ }
+}
+
+// nativePreGrant verifies a proof-only call (§3): one made before a grant
+// exists, signed by the key the call is bound to. These never touch the jti
+// table; their single-use start or challenge is their replay protection.
+func (a *App) nativePreGrant(r *http.Request, body []byte, deviceKey string, now int64) bool {
+ key, ok := decodeDeviceKey(deviceKey)
+ if !ok {
+ return false
+ }
+ p, payload, sig, err := parseNativeProof(r)
+ return err == nil && a.verifyNativeProof(r, body, key, p, payload, sig, now)
+}
+
+// mintGrant issues a grant to one device. It is called inside the writer
+// transaction that consumed the sign-in's proof, so a grant exists only if
+// that proof is gone.
+func (a *App) mintGrant(tx *sql.Tx, person, deviceKey, platform, method string, authTime, now int64) (map[string]any, error) {
+ if err := sweepGrants(tx, now); err != nil {
+ return nil, err
+ }
+ // A 21st live grant ends the least recently used one.
+ for {
+ var live int
+ if err := tx.QueryRow("SELECT count(*) FROM home_id_grants WHERE person_ref=? AND ended_at IS NULL", person).Scan(&live); err != nil {
+ return nil, errIDProof
+ }
+ if live < nativeGrantsPerID {
+ break
+ }
+ if _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='lru' WHERE grant_hash=(SELECT grant_hash FROM home_id_grants WHERE person_ref=? AND ended_at IS NULL ORDER BY last_used_day,created_at LIMIT 1)", now, person); err != nil {
+ return nil, errIDProof
+ }
+ }
+ token, err := nativeToken()
+ if err != nil {
+ return nil, errIDProof
+ }
+ id := a.identityID(person)
+ if _, err = tx.Exec("INSERT INTO home_id_grants(grant_hash,person_ref,identity_id,device_key,platform,method,auth_time,created_at,last_used_day,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?)",
+ nativeHash(token), person, id, deviceKey, platform, method, authTime, now, dayOf(now), now+nativeGrantLife); err != nil {
+ return nil, errIDProof
+ }
+ return map[string]any{"grant": token, "identity_id": id, "auth_time": authTime}, nil
+}
+
+// sweepGrants marks lapsed grants as expired and forgets ended ones once
+// their device key is no longer needed to recognise a returning device.
+func sweepGrants(tx *sql.Tx, now int64) error {
+ if _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='expiry' WHERE ended_at IS NULL AND (expires_at<=? OR last_used_day<=?)", now, now, idleCutoff(now)); err != nil {
+ return errIDProof
+ }
+ if _, err := tx.Exec("DELETE FROM home_id_grants WHERE ended_at IS NOT NULL AND ended_at<=?", now-nativeGrantKeep); err != nil {
+ return errIDProof
+ }
+ return nil
+}
+
+// endGrants ends every live grant a person holds, for one reason: "all_devices"
+// and "replacement" (§3, §10).
+func endGrants(tx *sql.Tx, person, reason string, now int64) error {
+ _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason=? WHERE person_ref=? AND ended_at IS NULL", now, reason, person)
+ if err != nil {
+ return errIDProof
+ }
+ return nil
+}
+
+// endPasskeylessGrants is a first passkey enrolment's revocation (§3): every
+// live grant whose method has no passkey ends, except the enrolling grant. A
+// web enrolment has none, so it passes "".
+func endPasskeylessGrants(tx *sql.Tx, person, except string, now int64) error {
+ _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='enrolment' WHERE person_ref=? AND ended_at IS NULL AND instr(method,'passkey')=0 AND grant_hash<>?", now, person, except)
+ if err != nil {
+ return errIDProof
+ }
+ return nil
+}
+
+// returningKey reports §4's exemption: the device key's most recent grant
+// for this person is live, or ended by expiry, lru or enrolment. A key last
+// cut off by "Sign out all devices", Revoke or recovery replacement is not
+// returning — those are how a lost device is cut off.
+func returningKey(tx *sql.Tx, person, deviceKey string) (bool, error) {
+ if person == "" {
+ return false, nil
+ }
+ var ended sql.NullInt64
+ var reason sql.NullString
+ err := tx.QueryRow("SELECT ended_at,end_reason FROM home_id_grants WHERE person_ref=? AND device_key=? ORDER BY created_at DESC LIMIT 1", person, deviceKey).Scan(&ended, &reason)
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ if err != nil {
+ return false, errIDProof
+ }
+ if !ended.Valid {
+ return true, nil // live, or lapsed and not yet swept: lapsing is expiry
+ }
+ switch reason.String {
+ case "expiry", "lru", "enrolment":
+ return true, nil
+ }
+ return false, nil
+}
diff --git a/internal/home/native_assert.go b/internal/home/native_assert.go
new file mode 100644
index 0000000..61e36ca
--- /dev/null
+++ b/internal/home/native_assert.go
@@ -0,0 +1,84 @@
+package home
+
+import (
+ "database/sql"
+ "errors"
+ "net/http"
+
+ "amadan.net/rastrillo/rastrillo/assertion"
+)
+
+var errMintPolicy = errors.New("home: mint refused by policy")
+
+// mintPolicy is the one rule for whether Home mints an assertion for a
+// consumer from a sign-in method. /authorize (handleAssertion) and the
+// native assert both call it, so a rule added here holds on both doors.
+// It is empty in slice A; Contra's passkey-only rule lands here later (§7).
+//
+// A variable rather than a function so a test can install a refusing
+// policy and watch both doors refuse.
+var mintPolicy = func(consumer, method string) error { return nil }
+
+// nativeAssert is POST assert {aud, challenge} → {assertion} (§7 step 1).
+// aud is an origin, matched exactly against the registered consumers. The
+// nonce is derived here from the caller's challenge, never taken from it.
+func (a *App) nativeAssert(tx *sql.Tx, g nativeGrant, body []byte, now int64) (int, any) {
+ var in struct {
+ Aud string `json:"aud"`
+ Challenge string `json:"challenge"`
+ }
+ if !decodeNative(body, &in) {
+ return http.StatusBadRequest, map[string]string{"error": "request"}
+ }
+ challenge, ok := decodeB64(in.Challenge, 32)
+ if !ok {
+ return http.StatusBadRequest, map[string]string{"error": "request"}
+ }
+ consumer := ""
+ for id, origin := range a.consumers() {
+ if origin == in.Aud {
+ consumer = id
+ break
+ }
+ }
+ if consumer == "" || consumer == operatorConfirmConsumer || a.runtime == nil || a.runtime.signer == nil {
+ return http.StatusBadRequest, map[string]string{"error": "audience"}
+ }
+ if mintPolicy(consumer, g.method) != nil {
+ return http.StatusForbidden, map[string]string{"error": "policy"}
+ }
+ id, err := assertion.RandomID()
+ if err != nil {
+ return 0, nil
+ }
+ token, err := assertion.Sign(a.runtime.signer, assertion.Claims{
+ Version: 1,
+ Issuer: a.origins.Credential,
+ Audience: in.Aud,
+ Subject: g.person,
+ KeyID: a.runtime.keyID,
+ ID: id,
+ Nonce: nativeNonce(challenge),
+ IssuedAt: now,
+ ExpiresAt: now + 120,
+ AuthTime: g.authTime,
+ })
+ if err != nil {
+ return 0, nil
+ }
+ return http.StatusOK, map[string]string{"assertion": token}
+}
+
+// nativeSignout is POST signout: the device's own grant ends (§10). The app
+// signed this request before deleting its key, so it arrives after the key
+// is gone; the proof's 30-second window bounds how late.
+func (a *App) nativeSignout(tx *sql.Tx, g nativeGrant, body []byte, now int64) (int, any) {
+ var in struct{}
+ if !decodeNative(body, &in) {
+ return http.StatusBadRequest, map[string]string{"error": "request"}
+ }
+ if _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='signout' WHERE grant_hash=? AND ended_at IS NULL", now, g.hash); err != nil {
+ return 0, nil
+ }
+ return http.StatusOK, map[string]string{}
+}
diff --git a/internal/home/native_code.go b/internal/home/native_code.go
new file mode 100644
index 0000000..0736436
--- /dev/null
+++ b/internal/home/native_code.go
@@ -0,0 +1,602 @@
+package home
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/rand"
+ "database/sql"
+ "errors"
+ "fmt"
+ "math/big"
+ "net"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/keymaildev/signin"
+)
+
+// The email code (§4), for a person with no passkey yet.
+const (
+ nativeCodeLife = 600 // a code lives ten minutes
+ nativeCodeTries = 5 // and dies after five wrong tries
+ nativeCodeSends = 3 // a start gets at most three sends
+ nativeResendAfter = 30 // thirty seconds apart
+ nativePendingLife = 300 // a passkey-required pending lives five minutes
+ nativeLivePerIP = 20
+ nativeBucketCap = 200000
+ nativeWindow = 900
+ nativeCodeSealScope = "native.code"
+)
+
+// nativeLiveStarts is the live-start table's size (§4). A variable only so a
+// test can fill it without 10,000 inserts.
+var nativeLiveStarts = 10000
+
+// The §4 limits, each its own persistent fixed-window counter. The prefix
+// names the bucket; the rest of the key is blinded.
+type nativeLimit struct {
+ prefix string
+ limit int
+ window int64
+}
+
+var (
+ startsPerAddress = nativeLimit{"start-addr-15m", 5, nativeWindow}
+ startsPerAddressDay = nativeLimit{"start-addr-day", 20, day}
+ startsPerIP = nativeLimit{"start-ip-15m", 20, nativeWindow}
+ startsPerIPDay = nativeLimit{"start-ip-day", 200, day}
+ startsPerAddressKey = nativeLimit{"start-key-15m", 5, nativeWindow}
+ wrongPerAddressKey = nativeLimit{"wrong-key-15m", 5, nativeWindow}
+ wrongNewKeysPerDay = nativeLimit{"wrong-new-day", 20, day}
+ passkeyBeginsPerIP = nativeLimit{"passkey-ip-15m", 60, nativeWindow}
+ errNativeLimited = errors.New("home: native limit reached")
+ errNativeLimitedToday = errors.New("home: native daily limit reached")
+)
+
+const codeMailSubject = "Your Oficina ID code"
+
+// codeMailBody has no link: a link would sign in a browser (§4).
+func codeMailBody(code string) string {
+ return "Your Oficina ID code is " + code + "\n\n" +
+ "It expires in 10 minutes and works once.\n\n" +
+ "If you didn't ask for it, ignore this email. Nobody can sign in without the code."
+}
+
+func (a *App) bucketKey(l nativeLimit, parts ...string) string {
+ return l.prefix + ":" + a.nativeMAC("native-bucket", append([]string{l.prefix}, parts...)...)
+}
+
+// bucketFull reports whether a bucket has reached its limit in its window.
+func bucketFull(tx *sql.Tx, key string, l nativeLimit, now int64) (bool, error) {
+ var n int
+ err := tx.QueryRow("SELECT count FROM home_id_native_buckets WHERE bucket=? AND expires_at>?", key, now).Scan(&n)
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ if err != nil {
+ return false, errIDProof
+ }
+ return n >= l.limit, nil
+}
+
+// bucketSpend counts one against a bucket, opening a new window when the
+// last one has closed.
+func bucketSpend(tx *sql.Tx, key string, l nativeLimit, now int64) error {
+ _, err := tx.Exec(`INSERT INTO home_id_native_buckets(bucket,count,expires_at) VALUES(?,1,?)
+ ON CONFLICT(bucket) DO UPDATE SET
+ count = CASE WHEN expires_at<=? THEN 1 ELSE count+1 END,
+ expires_at = CASE WHEN expires_at<=? THEN ? ELSE expires_at END`, key, now+l.window, now, now, now+l.window)
+ if err != nil {
+ return errIDProof
+ }
+ return nil
+}
+
+type nativeBucket struct {
+ key string
+ limit nativeLimit
+ err error
+}
+
+// checkThenSpend refuses if any bucket is full, and otherwise spends one
+// from each, in the caller's transaction: parallel requests serialise on the
+// writer, so none can see a count another has not yet written.
+func checkThenSpend(tx *sql.Tx, buckets []nativeBucket, now int64) error {
+ for _, b := range buckets {
+ full, err := bucketFull(tx, b.key, b.limit, now)
+ if err != nil {
+ return err
+ }
+ if full {
+ return b.err
+ }
+ }
+ var n int
+ if tx.QueryRow("SELECT count(*) FROM home_id_native_buckets").Scan(&n) != nil {
+ return errIDProof
+ }
+ if n+len(buckets) > nativeBucketCap {
+ return errIDProof
+ }
+ for _, b := range buckets {
+ if err := bucketSpend(tx, b.key, b.limit, now); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// nativeIPBucket is §4's ip_bucket: the IPv4 /32 or the IPv6 /64, from the
+// same edge-written address signin's limiter uses. "" when no IP is known,
+// which skips the per-IP limits rather than pooling everyone into one.
+func nativeIPBucket(r *http.Request) string {
+ ip := net.ParseIP(clientIP(r))
+ if ip == nil {
+ return ""
+ }
+ if v4 := ip.To4(); v4 != nil {
+ return v4.String()
+ }
+ return ip.Mask(net.CIDRMask(64, 128)).String() + "/64"
+}
+
+func newNativeCode() (string, error) {
+ n, err := rand.Int(rand.Reader, big.NewInt(1000000))
+ if err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("%06d", n.Int64()), nil
+}
+
+// codeMAC binds a code to its start, so a code is worth nothing elsewhere.
+func (a *App) codeMAC(startHash, code string) string {
+ return a.nativeMAC("native-code", startHash, code)
+}
+
+func validCode(s string) bool {
+ if len(s) != 6 {
+ return false
+ }
+ for i := 0; i < 6; i++ {
+ if s[i] < '0' || s[i] > '9' {
+ return false
+ }
+ }
+ return true
+}
+
+// nativeAddress is the address as /signin normalises it, and its native
+// blind: a Home-keyed HMAC distinct from the people table's index.
+func (a *App) nativeAddress(raw string) (address, blind string, err error) {
+ local, domain, err := signin.SplitAddress(raw)
+ if err != nil || len(raw) > 320 {
+ return "", "", signin.ErrBadAddress
+ }
+ address = local + "@" + domain
+ return address, a.nativeMAC("native-address", strings.ToLower(address)), nil
+}
+
+// personFor finds, never mints, the person behind an address.
+func (a *App) personFor(tx *sql.Tx, address string) (string, error) {
+ var person string
+ err := tx.QueryRow("SELECT person_ref FROM people WHERE blind_index=?", blindIndex(a.secrets.Pepper, address)).Scan(&person)
+ if errors.Is(err, sql.ErrNoRows) {
+ return "", nil
+ }
+ if err != nil {
+ return "", errIDProof
+ }
+ return person, nil
+}
+
+// spendWebBudget spends the address's share of the web door's email budget,
+// so an address has one allowance across both doors (§4).
+func (a *App) spendWebBudget(ctx context.Context, address string) bool {
+ budget := a.flow.AddressBudget
+ if budget == 0 {
+ budget = 5
+ }
+ ok, err := a.flow.Limiter.Allow(ctx, "addr:"+strings.ToLower(address), time.Now(), budget)
+ return err == nil && ok
+}
+
+func sweepCodes(tx *sql.Tx, now int64) error {
+ for _, q := range []string{
+ "DELETE FROM home_id_native_starts WHERE expires_at<=?",
+ "DELETE FROM home_id_native_pending WHERE expires_at<=?",
+ "DELETE FROM home_id_native_buckets WHERE expires_at<=?",
+ } {
+ if _, err := tx.Exec(q, now); err != nil {
+ return errIDProof
+ }
+ }
+ return nil
+}
+
+func nativeLimitFail(w http.ResponseWriter, err error) {
+ switch {
+ case errors.Is(err, errNativeLimitedToday):
+ nativeFail(w, http.StatusTooManyRequests, "too_many_today")
+ case errors.Is(err, errNativeLimited):
+ nativeFail(w, http.StatusTooManyRequests, "rate_limited")
+ default:
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ }
+}
+
+// nativeCodeStart is POST code/start {email, device_key, platform}. The
+// answer is the same for an address Home knows and one it has never seen.
+func (a *App) nativeCodeStart(w http.ResponseWriter, r *http.Request) {
+ body, ok := nativeIntake(w, r)
+ if !ok {
+ return
+ }
+ var in struct {
+ Email string `json:"email"`
+ DeviceKey string `json:"device_key"`
+ Platform string `json:"platform"`
+ }
+ if !decodeNative(body, &in) || !nativePlatforms[in.Platform] {
+ nativeFail(w, http.StatusBadRequest, "request")
+ return
+ }
+ if !a.nativePreGrant(r, body, in.DeviceKey, time.Now().Unix()) {
+ nativeUnauthorized(w, "proof")
+ return
+ }
+ address, blind, err := a.nativeAddress(in.Email)
+ if err != nil {
+ nativeFail(w, http.StatusBadRequest, "email")
+ return
+ }
+ ip := nativeIPBucket(r)
+ ipBlind := ""
+ if ip != "" {
+ ipBlind = a.nativeMAC("native-ip", ip)
+ }
+
+ tx, now, err := a.idTransaction(r.Context())
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ defer tx.Rollback()
+ if sweepCodes(tx, now) != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ // A second start for the same (address, key) replaces the first: one
+ // code is live per pair, and the old one stops counting as live.
+ if _, err = tx.Exec("DELETE FROM home_id_native_starts WHERE blind_index=? AND device_key=?", blind, in.DeviceKey); err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ var live, liveIP int
+ if tx.QueryRow("SELECT count(*) FROM home_id_native_starts").Scan(&live) != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if live >= nativeLiveStarts {
+ // Full: new starts wait, existing ones still verify, and the web's
+ // link sign-in is untouched (§4).
+ nativeFail(w, http.StatusServiceUnavailable, "full")
+ return
+ }
+ if ipBlind != "" {
+ if tx.QueryRow("SELECT count(*) FROM home_id_native_starts WHERE ip_bucket=?", ipBlind).Scan(&liveIP) != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if liveIP >= nativeLivePerIP {
+ nativeFail(w, http.StatusTooManyRequests, "rate_limited")
+ return
+ }
+ }
+ person, err := a.personFor(tx, address)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ returning, err := returningKey(tx, person, in.DeviceKey)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ buckets := []nativeBucket{{a.bucketKey(startsPerAddressKey, blind, in.DeviceKey), startsPerAddressKey, errNativeLimited}}
+ if ipBlind != "" {
+ buckets = append(buckets,
+ nativeBucket{a.bucketKey(startsPerIP, ipBlind), startsPerIP, errNativeLimited},
+ nativeBucket{a.bucketKey(startsPerIPDay, ipBlind), startsPerIPDay, errNativeLimited})
+ }
+ if !returning {
+ // A new device's start is pointless once the address's new-device
+ // guesses are spent for the day, so it is refused before any mail.
+ full, err := bucketFull(tx, a.bucketKey(wrongNewKeysPerDay, blind), wrongNewKeysPerDay, now)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if full {
+ nativeLimitFail(w, errNativeLimitedToday)
+ return
+ }
+ buckets = append(buckets,
+ nativeBucket{a.bucketKey(startsPerAddress, blind), startsPerAddress, errNativeLimited},
+ nativeBucket{a.bucketKey(startsPerAddressDay, blind), startsPerAddressDay, errNativeLimitedToday})
+ }
+ if err = checkThenSpend(tx, buckets, now); err != nil {
+ nativeLimitFail(w, err)
+ return
+ }
+ start, err := nativeToken()
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ code, err := newNativeCode()
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ startHash := nativeHash(start)
+ sealed, err := a.secrets.Sealer.Seal(nativeCodeSealScope, []byte(address))
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if _, err = tx.Exec("INSERT INTO home_id_native_starts(start_hash,sealed_address,blind_index,device_key,platform,ip_bucket,code_mac,sends,last_send,attempts,expires_at) VALUES(?,?,?,?,?,?,?,1,?,0,?)",
+ startHash, sealed, blind, in.DeviceKey, in.Platform, ipBlind, a.codeMAC(startHash, code), now, now+nativeCodeLife); err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ // Last before commit: the in-memory web budget cannot roll back, so it is
+ // spent only once every persistent check has passed.
+ if !a.spendWebBudget(r.Context(), address) {
+ nativeLimitFail(w, errNativeLimited)
+ return
+ }
+ if tx.Commit() != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if !a.sendCode(r.Context(), address, code) {
+ a.dropStart(r.Context(), startHash)
+ nativeFail(w, http.StatusServiceUnavailable, "mail")
+ return
+ }
+ nativeReply(w, http.StatusAccepted, map[string]any{"start": start, "resend_after": nativeResendAfter})
+}
+
+// sendCode mails the code. Neither the code nor the address reaches a log.
+func (a *App) sendCode(ctx context.Context, address, code string) bool {
+ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ if a.secrets.Mailer.Send(ctx, address, codeMailSubject, codeMailBody(code)) != nil {
+ a.logger.Warn("native code delivery failed")
+ return false
+ }
+ return true
+}
+
+// dropStart removes a start whose mail failed. Best effort: the row is
+// sealed and expires in ten minutes regardless.
+func (a *App) dropStart(ctx context.Context, startHash string) {
+ if _, err := a.db.Writer().ExecContext(ctx, "DELETE FROM home_id_native_starts WHERE start_hash=?", startHash); err != nil {
+ a.logger.Warn("dropping an undelivered native start failed")
+ }
+}
+
+type nativeStart struct {
+ hash, deviceKey, platform, blind, codeMAC string
+ sealed []byte
+ sends, attempts int
+ lastSend int64
+}
+
+func loadStart(tx *sql.Tx, start string, now int64) (nativeStart, bool) {
+ s := nativeStart{hash: nativeHash(start)}
+ if _, ok := decodeB64(start, 32); !ok {
+ return s, false
+ }
+ err := tx.QueryRow("SELECT device_key,platform,blind_index,code_mac,sealed_address,sends,attempts,last_send FROM home_id_native_starts WHERE start_hash=? AND expires_at>?", s.hash, now).
+ Scan(&s.deviceKey, &s.platform, &s.blind, &s.codeMAC, &s.sealed, &s.sends, &s.attempts, &s.lastSend)
+ return s, err == nil
+}
+
+// nativeCodeResend is POST code/resend {start}: a new code for the same
+// start, at most three sends, thirty seconds apart.
+func (a *App) nativeCodeResend(w http.ResponseWriter, r *http.Request) {
+ body, ok := nativeIntake(w, r)
+ if !ok {
+ return
+ }
+ var in struct {
+ Start string `json:"start"`
+ }
+ if !decodeNative(body, &in) {
+ nativeFail(w, http.StatusBadRequest, "request")
+ return
+ }
+ tx, now, err := a.idTransaction(r.Context())
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ defer tx.Rollback()
+ s, found := loadStart(tx, in.Start, now)
+ if !found {
+ nativeFail(w, http.StatusBadRequest, "start")
+ return
+ }
+ if !a.nativePreGrant(r, body, s.deviceKey, now) {
+ nativeUnauthorized(w, "proof")
+ return
+ }
+ if s.sends >= nativeCodeSends {
+ nativeFail(w, http.StatusTooManyRequests, "rate_limited")
+ return
+ }
+ if wait := s.lastSend + nativeResendAfter - now; wait > 0 {
+ nativeReply(w, http.StatusTooManyRequests, map[string]any{"error": "rate_limited", "resend_after": wait})
+ return
+ }
+ plain, err := a.secrets.Sealer.Open(nativeCodeSealScope, s.sealed)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ address := string(plain)
+ code, err := newNativeCode()
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ // A new code replaces the old one, with its own five tries; the
+ // persistent wrong-code buckets still bound guessing across codes.
+ if _, err = tx.Exec("UPDATE home_id_native_starts SET code_mac=?,sends=sends+1,last_send=?,attempts=0,expires_at=? WHERE start_hash=?", a.codeMAC(s.hash, code), now, now+nativeCodeLife, s.hash); err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if !a.spendWebBudget(r.Context(), address) {
+ nativeLimitFail(w, errNativeLimited)
+ return
+ }
+ if tx.Commit() != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if !a.sendCode(r.Context(), address, code) {
+ nativeFail(w, http.StatusServiceUnavailable, "mail")
+ return
+ }
+ nativeReply(w, http.StatusAccepted, map[string]any{"start": in.Start, "resend_after": nativeResendAfter})
+}
+
+// nativeCodeVerify is POST code/verify {start, code}. A right code finds or
+// mints the person and runs idGate's check: no passkey mints a grant; a
+// passkey returns a pending that must be finished with one.
+func (a *App) nativeCodeVerify(w http.ResponseWriter, r *http.Request) {
+ body, ok := nativeIntake(w, r)
+ if !ok {
+ return
+ }
+ var in struct {
+ Start string `json:"start"`
+ Code string `json:"code"`
+ }
+ if !decodeNative(body, &in) || !validCode(in.Code) {
+ nativeFail(w, http.StatusBadRequest, "request")
+ return
+ }
+ tx, now, err := a.idTransaction(r.Context())
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ defer tx.Rollback()
+ s, found := loadStart(tx, in.Start, now)
+ if !found {
+ nativeFail(w, http.StatusBadRequest, "code")
+ return
+ }
+ if !a.nativePreGrant(r, body, s.deviceKey, now) {
+ nativeUnauthorized(w, "proof")
+ return
+ }
+ plain, err := a.secrets.Sealer.Open(nativeCodeSealScope, s.sealed)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ address := string(plain)
+ person, err := a.personFor(tx, address)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ returning, err := returningKey(tx, person, s.deviceKey)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ wrongKey := nativeBucket{a.bucketKey(wrongPerAddressKey, s.blind, s.deviceKey), wrongPerAddressKey, errNativeLimited}
+ wrongNew := nativeBucket{a.bucketKey(wrongNewKeysPerDay, s.blind), wrongNewKeysPerDay, errNativeLimitedToday}
+ guard := []nativeBucket{wrongKey}
+ if !returning {
+ guard = append(guard, wrongNew)
+ }
+ for _, b := range guard {
+ full, err := bucketFull(tx, b.key, b.limit, now)
+ if err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if full {
+ nativeLimitFail(w, b.err)
+ return
+ }
+ }
+ if !hmac.Equal([]byte(a.codeMAC(s.hash, in.Code)), []byte(s.codeMAC)) {
+ for _, b := range guard {
+ if bucketSpend(tx, b.key, b.limit, now) != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ }
+ q := "UPDATE home_id_native_starts SET attempts=attempts+1 WHERE start_hash=?"
+ if s.attempts+1 >= nativeCodeTries {
+ q = "DELETE FROM home_id_native_starts WHERE start_hash=?"
+ }
+ if _, err = tx.Exec(q, s.hash); err != nil || tx.Commit() != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ nativeFail(w, http.StatusBadRequest, "code")
+ return
+ }
+ // Right: the start is used once, and its sealed address goes with it.
+ if _, err = tx.Exec("DELETE FROM home_id_native_starts WHERE start_hash=?", s.hash); err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ if person == "" {
+ if person, err = findOrMintPersonOn(r.Context(), tx, a.secrets.Pepper, address, time.Unix(now, 0)); err != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ }
+ var passkeys int
+ if tx.QueryRow("SELECT count(*) FROM passkey_credentials WHERE subject=?", person).Scan(&passkeys) != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ var reply map[string]any
+ if passkeys == 0 {
+ reply, err = a.mintGrant(tx, person, s.deviceKey, s.platform, "email", now, now)
+ } else {
+ reply, err = a.nativePending(tx, person, s, now)
+ }
+ if err != nil || tx.Commit() != nil {
+ nativeFail(w, http.StatusServiceUnavailable, "unavailable")
+ return
+ }
+ nativeReply(w, http.StatusOK, reply)
+}
+
+// nativePending is a code verified for an enrolled account: no grant, only a
+// five-minute handle bound to the start and its key, finished by a passkey.
+func (a *App) nativePending(tx *sql.Tx, person string, s nativeStart, now int64) (map[string]any, error) {
+ var n int
+ if tx.QueryRow("SELECT count(*) FROM home_id_native_pending").Scan(&n) != nil || n >= nativeLiveStarts {
+ return nil, errIDProof
+ }
+ pending, err := nativeToken()
+ if err != nil {
+ return nil, errIDProof
+ }
+ if _, err = tx.Exec("INSERT INTO home_id_native_pending VALUES(?,?,?,?,?,?,?)", nativeHash(pending), person, s.hash, s.deviceKey, s.platform, "email", now+nativePendingLife); err != nil {
+ return nil, errIDProof
+ }
+ return map[string]any{"factor": []string{"passkey"}, "pending": pending}, nil
+}
diff --git a/internal/home/native_code_test.go b/internal/home/native_code_test.go
new file mode 100644
index 0000000..c91d20b
--- /dev/null
+++ b/internal/home/native_code_test.go
@@ -0,0 +1,470 @@
+package home
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+
+ "amadan.net/oficina/home/internal/home/sealtest"
+)
+
+// §13 Codes: a full code sign-in, and the mail that carries the code.
+func TestNativeCodeSignIn(t *testing.T) {
+ app := newNativeApp(t)
+ d := newDevice(t)
+ start := d.start(t, app, sealtest.CanaryAddress)
+ mail, _ := app.mailer.last()
+ if mail.To != sealtest.CanaryAddress || mail.Subject != "Your Oficina ID code" || !strings.HasPrefix(mail.Body, "Your Oficina ID code is ") {
+ t.Fatalf("mail: %+v", mail)
+ }
+ if strings.Contains(mail.Body, "http") || strings.Contains(mail.Body, "oficina.works") {
+ t.Fatal("the code mail carries a link")
+ }
+ // No address at rest while the code is live: sealed, never readable.
+ sealtest.AssertNoPlaintext(t, app.dbPath)
+ w := d.verify(t, app, start, lastCode(t, app))
+ out := decodeReply(t, w)
+ if w.Code != 200 || len(out["grant"].(string)) != 43 || out["identity_id"] == "" || out["auth_time"] == nil {
+ t.Fatal("verify", w.Code, w.Body.String())
+ }
+ if n := count(t, app, "SELECT count(*) FROM home_id_native_starts"); n != 0 {
+ t.Fatal("a used start survived verify", n)
+ }
+ var method, platform string
+ if err := app.db.Writer().QueryRow("SELECT method,platform FROM home_id_grants").Scan(&method, &platform); err != nil || method != "email" || platform != "macos" {
+ t.Fatal("grant row", method, platform, err)
+ }
+ // The same person as the web door finds for that address.
+ session := signInFully(t, app, sealtest.CanaryAddress)
+ if out["identity_id"] != app.identityID(subjectOf(t, app, session)) {
+ t.Fatal("native code found a different person than /signin")
+ }
+ sealtest.AssertNoPlaintext(t, app.dbPath)
+}
+
+// §13 Codes: identical answers for known and unknown addresses.
+func TestNativeCodeStartIdenticalForKnownAndUnknown(t *testing.T) {
+ app := newNativeApp(t)
+ signInFully(t, app, "known@example.invalid")
+ shape := func(email string) (int, []string, []string) {
+ d := newDevice(t)
+ w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": d.public(), "platform": "ios"}, "")
+ var keys, headers []string
+ for k := range decodeReply(t, w) {
+ keys = append(keys, k)
+ }
+ for k := range w.Header() {
+ headers = append(headers, k)
+ }
+ sort.Strings(keys)
+ sort.Strings(headers)
+ return w.Code, keys, headers
+ }
+ c1, k1, h1 := shape("known@example.invalid")
+ c2, k2, h2 := shape("never-seen@example.invalid")
+ if c1 != 202 || c1 != c2 || fmt.Sprint(k1) != fmt.Sprint(k2) || fmt.Sprint(h1) != fmt.Sprint(h2) {
+ t.Fatal("known and unknown addresses differ", c1, c2, k1, k2, h1, h2)
+ }
+}
+
+// §13 Codes: entropy, expiry and single use.
+func TestNativeCodeEntropyExpiryAndSingleUse(t *testing.T) {
+ seen := map[string]bool{}
+ for range 200 {
+ c, err := newNativeCode()
+ if err != nil || !validCode(c) {
+ t.Fatal("bad code", c, err)
+ }
+ seen[c] = true
+ }
+ if len(seen) < 190 {
+ t.Fatal("codes repeat far too often", len(seen))
+ }
+ app := newNativeApp(t)
+ d := newDevice(t)
+ start := d.start(t, app, "a@example.invalid")
+ code := lastCode(t, app)
+ var mac string
+ app.db.Writer().QueryRow("SELECT code_mac FROM home_id_native_starts").Scan(&mac)
+ if strings.Contains(mac, code) {
+ t.Fatal("the code is at rest")
+ }
+ if w := d.verify(t, app, start, code); w.Code != 200 {
+ t.Fatal("first use", w.Code)
+ }
+ if w := d.verify(t, app, start, code); w.Code == 200 {
+ t.Fatal("a code worked twice")
+ }
+ // Expiry.
+ start = d.start(t, app, "a@example.invalid")
+ code = lastCode(t, app)
+ if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET expires_at=1"); err != nil {
+ t.Fatal(err)
+ }
+ if w := d.verify(t, app, start, code); w.Code == 200 {
+ t.Fatal("an expired code worked")
+ }
+ // A code is bound to its start.
+ other := newDevice(t)
+ d.start(t, app, "b@example.invalid")
+ c1 := lastCode(t, app)
+ s2 := other.start(t, app, "b@example.invalid")
+ if c2 := lastCode(t, app); c1 != c2 {
+ if w := other.verify(t, app, s2, c1); w.Code == 200 {
+ t.Fatal("one start's code opened another")
+ }
+ }
+}
+
+// §13 Codes: a code dies after five wrong tries.
+func TestNativeCodeDiesAfterFiveWrong(t *testing.T) {
+ app := newNativeApp(t)
+ d := newDevice(t)
+ start := d.start(t, app, "a@example.invalid")
+ code := lastCode(t, app)
+ wrong := "000000"
+ if code == wrong {
+ wrong = "111111"
+ }
+ for i := range 5 {
+ if w := d.verify(t, app, start, wrong); w.Code != 400 || decodeReply(t, w)["error"] != "code" {
+ t.Fatal("wrong try", i, w.Code, w.Body.String())
+ }
+ }
+ if w := d.verify(t, app, start, code); w.Code == 200 {
+ t.Fatal("the right code worked after five wrong tries")
+ }
+}
+
+// §13 Codes: persistent buckets survive a restart, and the per-(address,
+// key) wrong-code cap holds.
+func TestNativeCodeBucketsSurviveRestart(t *testing.T) {
+ app := newNativeApp(t)
+ for range 5 {
+ newDevice(t).start(t, app, "a@example.invalid")
+ }
+ // A restart forgets the web's in-memory budget; the native start cap
+ // is on disk and still refuses.
+ app = app.restart(t)
+ d := newDevice(t)
+ w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "a@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
+ if w.Code != 429 {
+ t.Fatal("per-address start cap forgot itself across a restart", w.Code)
+ }
+
+ // Wrong codes per (address, key): five per fifteen minutes, counted
+ // across codes (a resend gives a code fresh tries, never the address)
+ // and across a restart.
+ app = newNativeApp(t)
+ d = newDevice(t)
+ start := d.start(t, app, "b@example.invalid")
+ wrong := func() {
+ t.Helper()
+ if w := d.verify(t, app, start, "999999"); w.Code != 400 && lastCode(t, app) != "999999" {
+ t.Fatal("wrong code", w.Code)
+ }
+ }
+ for range 4 {
+ wrong()
+ }
+ if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil {
+ t.Fatal(err)
+ }
+ if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 202 {
+ t.Fatal("resend", w.Code)
+ }
+ app = app.restart(t)
+ wrong()
+ if w := d.verify(t, app, start, lastCode(t, app)); w.Code != 429 {
+ t.Fatal("a sixth guess in the window was judged", w.Code)
+ }
+}
+
+// §13 Codes: parallel starts cannot overspend a bucket.
+func TestNativeCodeParallelStartsHoldTheCap(t *testing.T) {
+ app := newNativeApp(t)
+ var wg sync.WaitGroup
+ var mu sync.Mutex
+ codes := map[int]int{}
+ devices := make([]*device, 12)
+ for i := range devices {
+ devices[i] = newDevice(t)
+ }
+ for _, d := range devices {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "p@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
+ mu.Lock()
+ codes[w.Code]++
+ mu.Unlock()
+ }()
+ }
+ wg.Wait()
+ if codes[202] != 5 || codes[429] != 7 {
+ t.Fatal("parallel starts overspent the address", codes)
+ }
+}
+
+// §13 Codes: the daily cap, the returning-key exemption, and its exclusions.
+func TestNativeCodeDailyCapAndReturningKeys(t *testing.T) {
+ for _, tc := range []struct {
+ reason string
+ returning bool
+ }{
+ {"", true}, {"expiry", true}, {"lru", true}, {"enrolment", true},
+ {"all_devices", false}, {"revoke", false}, {"replacement", false},
+ } {
+ t.Run("ended="+tc.reason, func(t *testing.T) {
+ app := newNativeApp(t)
+ const email = "victim@example.invalid"
+ mine := newDevice(t)
+ grant, _ := mine.signInByCode(t, app, email)
+ if tc.reason != "" {
+ if _, err := app.db.Writer().Exec("UPDATE home_id_grants SET ended_at=1,end_reason=? WHERE grant_hash=?", tc.reason, nativeHash(grant)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // An attacker spends the address's new-device guesses: four
+ // starts, five wrong codes each.
+ for range 4 {
+ a := newDevice(t)
+ start := a.start(t, app, email)
+ code := lastCode(t, app)
+ wrong := "000000"
+ if code == wrong {
+ wrong = "000001"
+ }
+ for range 5 {
+ a.verify(t, app, start, wrong)
+ }
+ }
+ stranger := newDevice(t)
+ w := stranger.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": stranger.public(), "platform": "macos"}, "")
+ if w.Code != 429 || decodeReply(t, w)["error"] != "too_many_today" {
+ t.Fatal("a new device started past the daily cap", w.Code, w.Body.String())
+ }
+ app = app.restart(t) // a fresh web budget: only the native caps speak
+ w = mine.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": mine.public(), "platform": "macos"}, "")
+ if tc.returning {
+ if w.Code != 202 {
+ t.Fatal("a returning device was blocked", w.Code, w.Body.String())
+ }
+ start := decodeReply(t, w)["start"].(string)
+ if v := mine.verify(t, app, start, lastCode(t, app)); v.Code != 200 {
+ t.Fatal("a returning device could not verify", v.Code, v.Body.String())
+ }
+ } else if w.Code != 429 {
+ t.Fatal("a cut-off device was treated as returning", w.Code)
+ }
+ })
+ }
+}
+
+// §13 Codes: an exempt key keeps its own limit.
+func TestNativeCodeExemptKeyKeepsItsOwnLimit(t *testing.T) {
+ app := newNativeApp(t)
+ d := newDevice(t)
+ d.signInByCode(t, app, "e@example.invalid")
+ for range 4 {
+ d.start(t, app, "e@example.invalid")
+ }
+ app = app.restart(t)
+ w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "e@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
+ if w.Code != 429 {
+ t.Fatal("a returning key started six times in fifteen minutes", w.Code)
+ }
+}
+
+// §13 Codes: one email allowance shared with the web, both ways.
+func TestNativeCodeSharesTheWebEmailBudget(t *testing.T) {
+ app := newNativeApp(t)
+ for range 5 {
+ signIn(t, app, "shared@example.invalid")
+ }
+ d := newDevice(t)
+ w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "shared@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
+ if w.Code != 429 {
+ t.Fatal("native start ignored the web's spent budget", w.Code)
+ }
+ app = newNativeApp(t)
+ for range 5 {
+ newDevice(t).start(t, app, "shared@example.invalid")
+ }
+ if rec := signIn(t, app, "shared@example.invalid"); rec.Code != http.StatusTooManyRequests {
+ t.Fatal("the web ignored native starts", rec.Code)
+ }
+}
+
+// §13 Codes: per-IP-bucket live starts, IPv6 by /64, and 503 when full.
+func TestNativeCodeLiveStartLimits(t *testing.T) {
+ app := newNativeApp(t)
+ for i := range 20 {
+ newDevice(t).start(t, app, fmt.Sprintf("ip%d@example.invalid", i))
+ }
+ if _, err := app.db.Writer().Exec("DELETE FROM home_id_native_buckets"); err != nil {
+ t.Fatal(err)
+ }
+ d := newDevice(t)
+ w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "ip-last@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
+ if w.Code != 429 {
+ t.Fatal("a 21st live start from one IP bucket", w.Code)
+ }
+ if w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "ip-last@example.invalid", "device_key": d.public(), "platform": "macos"}, "", proofOpts{ip: "198.51.100.7:1"}); w.Code != 202 {
+ t.Fatal("another IP was refused", w.Code)
+ }
+ a := httpRequestFrom("[2001:db8:1:2:aaaa::1]:1")
+ b := httpRequestFrom("[2001:db8:1:2:bbbb::9]:1")
+ c := httpRequestFrom("[2001:db8:1:3::1]:1")
+ if nativeIPBucket(a) != nativeIPBucket(b) || nativeIPBucket(a) == nativeIPBucket(c) || nativeIPBucket(httpRequestFrom("192.0.2.1:1")) != "192.0.2.1" {
+ t.Fatal("IP buckets", nativeIPBucket(a), nativeIPBucket(b), nativeIPBucket(c))
+ }
+
+ // Full: new starts get 503, an existing start still verifies.
+ app = newNativeApp(t)
+ keep := newDevice(t)
+ start := keep.start(t, app, "keep@example.invalid")
+ code := lastCode(t, app)
+ if nativeLiveStarts != 10000 {
+ t.Fatal("the live-start table's size moved", nativeLiveStarts)
+ }
+ prev := nativeLiveStarts
+ nativeLiveStarts = 100
+ t.Cleanup(func() { nativeLiveStarts = prev })
+ tx, err := app.db.Writer().Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := range nativeLiveStarts - 1 {
+ if _, err := tx.Exec("INSERT INTO home_id_native_starts VALUES(?,x'00',?,?,?,'',?,1,0,0,?)", fmt.Sprint("fill", i), fmt.Sprint("b", i), "k", "macos", "m", int64(1<<40)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ d = newDevice(t)
+ w = d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "late@example.invalid", "device_key": d.public(), "platform": "macos"}, "")
+ if w.Code != 503 || decodeReply(t, w)["error"] != "full" {
+ t.Fatal("a full table took a start", w.Code, w.Body.String())
+ }
+ if v := keep.verify(t, app, start, code); v.Code != 200 {
+ t.Fatal("a full table refused an existing start", v.Code)
+ }
+ // The web's link sign-in is unaffected.
+ if rec := signIn(t, app, "web@example.invalid"); rec.Code != http.StatusSeeOther {
+ t.Fatal("a full native table blocked the web", rec.Code)
+ }
+}
+
+func httpRequestFrom(addr string) *http.Request {
+ r, _ := http.NewRequest("POST", Origin, nil)
+ r.RemoteAddr = addr
+ return r
+}
+
+// §13 Codes: no grant from a code alone on an enrolled account.
+func TestNativeCodeOnEnrolledAccountNeedsPasskey(t *testing.T) {
+ app := newNativeApp(t)
+ session := signInFully(t, app, sealtest.CanaryAddress)
+ enrol(t, app, session)
+ d := newDevice(t)
+ start := d.start(t, app, sealtest.CanaryAddress)
+ w := d.verify(t, app, start, lastCode(t, app))
+ out := decodeReply(t, w)
+ if w.Code != 200 || out["grant"] != nil || out["pending"] == nil || fmt.Sprint(out["factor"]) != "[passkey]" {
+ t.Fatal("a code alone opened an enrolled account", w.Code, w.Body.String())
+ }
+ if n := count(t, app, "SELECT count(*) FROM home_id_grants"); n != 0 {
+ t.Fatal("a grant row exists", n)
+ }
+}
+
+// §13 Codes: no address and no code in any log line, the failure paths
+// included.
+func TestNativeCodeNothingInLogs(t *testing.T) {
+ app := newNativeApp(t)
+ var buf bytes.Buffer
+ app.logger = slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
+ d := newDevice(t)
+ start := d.start(t, app, sealtest.CanaryAddress)
+ code := lastCode(t, app)
+ d.verify(t, app, start, "123456")
+ d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, "")
+ d.verify(t, app, start, code)
+ app.secrets.Mailer = failingMailer{}
+ app.flow.Mailer = failingMailer{}
+ e := newDevice(t)
+ w := e.call(t, app, nativePrefix+"/code/start", map[string]string{"email": "other-" + sealtest.CanaryAddress, "device_key": e.public(), "platform": "macos"}, "")
+ if w.Code != 503 {
+ t.Fatal("failed mail answered", w.Code)
+ }
+ for _, needle := range []string{sealtest.CanaryAddress, url.QueryEscape(sealtest.CanaryAddress), code, start} {
+ if strings.Contains(buf.String(), needle) || strings.Contains(w.Body.String(), needle) {
+ t.Fatalf("%q reached a log line or an error", needle)
+ }
+ }
+ if !strings.Contains(buf.String(), "native code delivery failed") {
+ t.Fatal("the failure path did not run")
+ }
+ sealtest.AssertNoPlaintext(t, app.dbPath)
+}
+
+type failingMailer struct{}
+
+func (failingMailer) Send(context.Context, string, string, string) error {
+ return errors.New("smtp down")
+}
+
+// Resend replaces the code, three sends at most, thirty seconds apart.
+func TestNativeCodeResend(t *testing.T) {
+ app := newNativeApp(t)
+ d := newDevice(t)
+ start := d.start(t, app, "r@example.invalid")
+ first := lastCode(t, app)
+ if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 429 {
+ t.Fatal("resend inside thirty seconds", w.Code)
+ }
+ for i := range 2 {
+ if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil {
+ t.Fatal(err)
+ }
+ if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 202 {
+ t.Fatal("resend", i, w.Code, w.Body.String())
+ }
+ }
+ if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil {
+ t.Fatal(err)
+ }
+ if w := d.call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 429 {
+ t.Fatal("a fourth send", w.Code)
+ }
+ latest := lastCode(t, app)
+ if latest != first {
+ if w := d.verify(t, app, start, first); w.Code == 200 {
+ t.Fatal("a replaced code still worked")
+ }
+ }
+ if w := d.verify(t, app, start, latest); w.Code != 200 {
+ t.Fatal("the latest code failed", w.Code)
+ }
+ // A resend must be signed by the start's own key.
+ start = d.start(t, app, "s@example.invalid")
+ if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET last_send=last_send-31"); err != nil {
+ t.Fatal(err)
+ }
+ if w := newDevice(t).call(t, app, nativePrefix+"/code/resend", map[string]string{"start": start}, ""); w.Code != 401 {
+ t.Fatal("another key resent", w.Code)
+ }
+ if w := newDevice(t).verify(t, app, start, lastCode(t, app)); w.Code != 401 {
+ t.Fatal("another key verified", w.Code)
+ }
+}
diff --git a/internal/home/native_grant_test.go b/internal/home/native_grant_test.go
new file mode 100644
index 0000000..424d4b7
--- /dev/null
+++ b/internal/home/native_grant_test.go
@@ -0,0 +1,273 @@
+package home
+
+import (
+ "crypto/sha256"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/internal/home/sealtest"
+)
+
+const teamDocs = "https://blue.docs.oficina.works"
+
+// §13 Proof: every way a proof can be wrong is refused, and no jti is
+// recorded before the grant and the signature verify.
+func TestNativeProofRefusals(t *testing.T) {
+ app := newNativeApp(t)
+ d := newDevice(t)
+ grant, _ := d.signInByCode(t, app, "p@example.invalid")
+ _, challenge := verifierFor(1)
+ for name, o := range map[string]proofOpts{
+ "wrong key": {signer: newDevice(t)},
+ "skewed iat": {iat: time.Now().Unix() - 31},
+ "future iat": {iat: time.Now().Unix() + 31},
+ "wrong htu": {htu: Origin + nativePrefix + "/signout"},
+ "other host": {htu: "https://oficina.works" + nativePrefix + "/assert"},
+ "swapped body": {signedBody: []byte(`{"aud":"https://directory.example","challenge":"x"}`)},
+ "origin header": {headers: map[string]string{"Origin": Origin}},
+ "sec-fetch-site": {headers: map[string]string{"Sec-Fetch-Site": "none"}},
+ "malformed proof": {headers: map[string]string{"Oficina-Proof": "e30.AAAA"}},
+ } {
+ w := d.assert(t, app, grant, teamDocs, challenge, o)
+ if w.Code == 200 {
+ t.Fatalf("%s: accepted", name)
+ }
+ if n := count(t, app, "SELECT count(*) FROM home_id_native_replay"); n != 0 {
+ t.Fatalf("%s: a jti row before the proof verified", name)
+ }
+ }
+ // An unknown or ended grant writes no jti either.
+ if w := d.assert(t, app, strings.Repeat("A", 43), teamDocs, challenge); w.Code != 401 {
+ t.Fatal("unknown grant", w.Code)
+ }
+ if n := count(t, app, "SELECT count(*) FROM home_id_native_replay"); n != 0 {
+ t.Fatal("a jti row for an unknown grant")
+ }
+ // A 401 carries the server clock, and every answer a Date.
+ w := d.assert(t, app, grant, teamDocs, challenge, proofOpts{iat: time.Now().Unix() - 100})
+ if w.Code != 401 || decodeReply(t, w)["now"] == nil || w.Header().Get("Date") == "" || w.Header().Get("Cache-Control") != "no-store" {
+ t.Fatal("401 without now/Date", w.Code, w.Header())
+ }
+ if w.Header().Get("Access-Control-Allow-Origin") != "" {
+ t.Fatal("CORS on a native endpoint")
+ }
+}
+
+// §13 Proof: a replayed jti is refused, also across a restart.
+func TestNativeProofReplay(t *testing.T) {
+ app := newNativeApp(t)
+ d := newDevice(t)
+ grant, _ := d.signInByCode(t, app, "r@example.invalid")
+ _, challenge := verifierFor(2)
+ o := proofOpts{jti: "replay-me-0123456789", iat: time.Now().Unix()}
+ if w := d.assert(t, app, grant, teamDocs, challenge, o); w.Code != 200 {
+ t.Fatal("first", w.Code, w.Body.String())
+ }
+ if w := d.assert(t, app, grant, teamDocs, challenge, o); w.Code != 401 || decodeReply(t, w)["error"] != "replay" {
+ t.Fatal("replay accepted", w.Code)
+ }
+ app = app.restart(t)
+ if w := d.assert(t, app, grant, teamDocs, challenge, o); w.Code != 401 {
+ t.Fatal("replay accepted after a restart", w.Code)
+ }
+}
+
+// §13 Proof: the table fails closed when full, and each grant is limited to
+// 120 calls a minute.
+func TestNativeProofTableLimits(t *testing.T) {
+ app := newNativeApp(t)
+ d := newDevice(t)
+ grant, _ := d.signInByCode(t, app, "l@example.invalid")
+ _, challenge := verifierFor(3)
+ for i := range nativeReplayPerMin {
+ if w := d.assert(t, app, grant, teamDocs, challenge); w.Code != 200 {
+ t.Fatal("call", i, w.Code)
+ }
+ }
+ if w := d.assert(t, app, grant, teamDocs, challenge); w.Code != 429 {
+ t.Fatal("call 121 in a minute", w.Code)
+ }
+ other := newDevice(t)
+ grant2, _ := other.signInByCode(t, app, "m@example.invalid")
+ if nativeReplayCap != 100000 {
+ t.Fatal("the replay table's size moved", nativeReplayCap)
+ }
+ prev := nativeReplayCap
+ nativeReplayCap = 200
+ t.Cleanup(func() { nativeReplayCap = prev })
+ tx, err := app.db.Writer().Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := range nativeReplayCap {
+ if _, err := tx.Exec("INSERT INTO home_id_native_replay VALUES(?,?,?)", fmt.Sprint("fill", i), "x", int64(1<<40)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ if w := other.assert(t, app, grant2, teamDocs, challenge); w.Code != 503 {
+ t.Fatal("a full replay table admitted a proof", w.Code)
+ }
+}
+
+// §13 Assert: the assertion is slice 1's v1 for the registered audience,
+// with the grant's auth_time and a nonce Home derived from the challenge.
+func TestNativeAssert(t *testing.T) {
+ app := newNativeApp(t)
+ d := newDevice(t)
+ grant, _ := d.signInByCode(t, app, sealtest.CanaryAddress)
+ var authTime int64
+ app.db.Writer().QueryRow("SELECT auth_time FROM home_id_grants").Scan(&authTime)
+ _, challenge := verifierFor(4)
+ w := d.assert(t, app, grant, teamDocs, challenge)
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ token := decodeReply(t, w)["assertion"].(string)
+ c := verifyAssertion(t, app, token, teamDocs)
+ session := signInFully(t, app, sealtest.CanaryAddress)
+ if c.Subject != subjectOf(t, app, session) || c.AuthTime != authTime || c.ExpiresAt-c.IssuedAt != 120 || c.Nonce != nativeNonce(challenge) {
+ t.Fatalf("claims %+v", c)
+ }
+ // The nonce is derived, never the caller's: no challenge yields a nonce
+ // equal to its own encoding, so a web nonce cannot be requested.
+ if c.Nonce == base64.RawURLEncoding.EncodeToString(challenge[:16]) {
+ t.Fatal("nonce is the challenge")
+ }
+ sum := sha256.Sum256(append([]byte("oficina-id/native/v1\x00"), challenge...))
+ if c.Nonce != base64.RawURLEncoding.EncodeToString(sum[:16]) {
+ t.Fatal("nonce derivation drifted from the wire notes")
+ }
+ // Unregistered, near-miss and operator audiences are refused.
+ for _, aud := range []string{"https://evil.example", teamDocs + "/", "https://BLUE.docs.oficina.works", "https://green.docs.oficina.works", operatorConfirmConsumer} {
+ if w := d.assert(t, app, grant, aud, challenge); w.Code != 400 {
+ t.Fatal("unregistered audience", aud, w.Code)
+ }
+ }
+ if w := d.call(t, app, nativePrefix+"/assert", map[string]string{"aud": teamDocs, "challenge": "short"}, grant); w.Code != 400 {
+ t.Fatal("short challenge", w.Code)
+ }
+ if w := d.call(t, app, nativePrefix+"/assert", map[string]string{"aud": teamDocs, "challenge": base64.RawURLEncoding.EncodeToString(challenge), "nonce": "chosen"}, grant); w.Code != 400 {
+ t.Fatal("a caller-chosen nonce field was accepted", w.Code)
+ }
+ sealtest.AssertNoPlaintext(t, app.dbPath)
+}
+
+// §13 Assert: mintPolicy is one function shared with /authorize.
+func TestNativeMintPolicyShared(t *testing.T) {
+ refused := errors.New("refused")
+ prev := mintPolicy
+ var seen []string
+ mintPolicy = func(consumer, method string) error { seen = append(seen, consumer+"/"+method); return refused }
+ t.Cleanup(func() { mintPolicy = prev })
+
+ p := newExchangePair(t)
+ d := newDevice(t)
+ grant, _ := d.signInByCode(t, p.credential, "policy@example.invalid")
+ _, challenge := verifierFor(5)
+ if w := d.assert(t, p.credential, grant, directoryOrigin, challenge); w.Code != 403 {
+ t.Fatal("native assert ignored mintPolicy", w.Code)
+ }
+ session := signInFully(t, p.credential, "policy@example.invalid")
+ _, intent := p.start(t)
+ r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, session)
+ if strings.Contains(r.Body.String(), `name="assertion"`) {
+ t.Fatal("/authorize ignored mintPolicy")
+ }
+ if fmt.Sprint(seen) != "[directory/email directory/magiclink]" {
+ t.Fatal("policy inputs", seen)
+ }
+ // And both call sites name it: a second rule cannot appear beside it.
+ for _, f := range []string{"exchange.go", "native_assert.go"} {
+ found := false
+ for _, g := range grepPackage(t, "mintPolicy(") {
+ found = found || g == f
+ }
+ if !found {
+ t.Fatal("mintPolicy not called from", f)
+ }
+ }
+}
+
+// §3: a 21st grant ends the least recently used; lapsed grants expire.
+func TestNativeGrantLimitsAndExpiry(t *testing.T) {
+ app := newNativeApp(t)
+ var grants []string
+ for i := range nativeGrantsPerID + 1 {
+ app = app.restart(t) // a fresh web budget for each start
+ if _, err := app.db.Writer().Exec("DELETE FROM home_id_native_buckets"); err != nil {
+ t.Fatal(err)
+ }
+ g, _ := newDevice(t).signInByCode(t, app, "many@example.invalid")
+ if i == 0 {
+ if _, err := app.db.Writer().Exec("UPDATE home_id_grants SET last_used_day=? WHERE grant_hash=?", dayOf(time.Now().Unix()-2*day), nativeHash(g)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ grants = append(grants, g)
+ }
+ if ended, reason := grantState(t, app, grants[0]); !ended || reason != "lru" {
+ t.Fatal("21st grant did not end the LRU", ended, reason)
+ }
+ if n := count(t, app, "SELECT count(*) FROM home_id_grants WHERE ended_at IS NULL"); n != nativeGrantsPerID {
+ t.Fatal("live grants", n)
+ }
+ // Absolute and idle expiry.
+ app2 := newNativeApp(t)
+ for i, q := range []string{"UPDATE home_id_grants SET expires_at=1", "UPDATE home_id_grants SET last_used_day=?"} {
+ e := newDevice(t)
+ g, _ := e.signInByCode(t, app2, fmt.Sprintf("exp-%d@example.invalid", i))
+ args := []any{}
+ if strings.Contains(q, "last_used_day") {
+ args = append(args, idleCutoff(time.Now().Unix()))
+ }
+ if _, err := app2.db.Writer().Exec(q+" WHERE grant_hash='"+nativeHash(g)+"'", args...); err != nil {
+ t.Fatal(err)
+ }
+ _, challenge := verifierFor(6)
+ if w := e.assert(t, app2, g, teamDocs, challenge); w.Code != 401 {
+ t.Fatal("expired grant used", q, w.Code)
+ }
+ if ended, reason := grantState(t, app2, g); !ended || reason != "expiry" {
+ t.Fatal("expired grant not ended", reason)
+ }
+ }
+ // A grant used yesterday is still live.
+ e := newDevice(t)
+ g, _ := e.signInByCode(t, app2, "fresh@example.invalid")
+ if _, err := app2.db.Writer().Exec("UPDATE home_id_grants SET last_used_day=? WHERE grant_hash=?", dayOf(time.Now().Unix()-nativeGrantIdleDays*day), nativeHash(g)); err != nil {
+ t.Fatal(err)
+ }
+ _, challenge := verifierFor(7)
+ if w := e.assert(t, app2, g, teamDocs, challenge); w.Code != 200 {
+ t.Fatal("a grant inside its idle window was refused", w.Code)
+ }
+}
+
+// §10: the device's own sign-out ends its grant; a late, pre-signed one is
+// refused by the 30-second window.
+func TestNativeSignout(t *testing.T) {
+ app := newNativeApp(t)
+ d := newDevice(t)
+ grant, _ := d.signInByCode(t, app, "s@example.invalid")
+ late := d.call(t, app, nativePrefix+"/signout", map[string]string{}, grant, proofOpts{iat: time.Now().Unix() - 40})
+ if late.Code != 401 {
+ t.Fatal("late sign-out accepted", late.Code)
+ }
+ if w := d.call(t, app, nativePrefix+"/signout", map[string]string{}, grant); w.Code != 200 {
+ t.Fatal("signout", w.Code, w.Body.String())
+ }
+ if ended, reason := grantState(t, app, grant); !ended || reason != "signout" {
+ t.Fatal("grant", reason)
+ }
+ _, challenge := verifierFor(8)
+ if w := d.assert(t, app, grant, teamDocs, challenge); w.Code != 401 {
+ t.Fatal("a signed-out grant asserted", w.Code)
+ }
+}
diff --git a/internal/home/native_helpers_test.go b/internal/home/native_helpers_test.go
new file mode 100644
index 0000000..fab831f
--- /dev/null
+++ b/internal/home/native_helpers_test.go
@@ -0,0 +1,239 @@
+package home
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/assertion"
+ assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
+)
+
+// newNativeApp is a credential-role app: the native endpoints mount only
+// there. Its consumers are the directory and one team's Docs.
+func newNativeApp(t *testing.T) *testApp {
+ t.Helper()
+ app := newTestApp(t)
+ key, err := assertioncrypto.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(key.SignPub())
+ kid := hex.EncodeToString(sum[:])
+ app.runtime = &Runtime{role: "credential", origins: app.origins, secrets: app.secrets, signer: key, keyID: kid, keys: map[string][]byte{kid: key.SignPub()}, consumers: map[string]string{"directory": directoryOrigin, "team_docs": "https://blue.docs.oficina.works"}}
+ return app
+}
+
+// restart builds a fresh App on the same database and keys: every in-memory
+// budget is new, everything persistent is not.
+func (app *testApp) restart(t *testing.T) *testApp {
+ t.Helper()
+ next, err := NewWithOrigins(app.secrets, app.db, quietLogger(), app.origins)
+ if err != nil {
+ t.Fatal(err)
+ }
+ next.flow.Classifier.LookupTXT = app.flow.Classifier.LookupTXT
+ next.runtime = app.runtime
+ return &testApp{App: next, mailer: app.mailer, db: app.db, dbPath: app.dbPath}
+}
+
+// device is a native app's device key.
+type device struct {
+ key *assertioncrypto.Keypair
+ platform string
+}
+
+func newDevice(t *testing.T) *device {
+ t.Helper()
+ k, err := assertioncrypto.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return &device{key: k, platform: "macos"}
+}
+func (d *device) public() string { return base64.RawURLEncoding.EncodeToString(d.key.SignPub()) }
+
+// proofOpts tampers with one part of a proof.
+type proofOpts struct {
+ iat int64
+ htu, jti string
+ signedBody []byte // sign over this body instead of the one sent
+ signer *device
+ headers map[string]string
+ ip string
+}
+
+func (d *device) proof(t *testing.T, path string, body []byte, o proofOpts) string {
+ t.Helper()
+ signed := body
+ if o.signedBody != nil {
+ signed = o.signedBody
+ }
+ bh := sha256.Sum256(signed)
+ iat := time.Now().Unix()
+ if o.iat != 0 {
+ iat = o.iat
+ }
+ htu := Origin + path
+ if o.htu != "" {
+ htu = o.htu
+ }
+ jti := o.jti
+ if jti == "" {
+ r := make([]byte, 16)
+ if _, err := rand.Read(r); err != nil {
+ t.Fatal(err)
+ }
+ jti = base64.RawURLEncoding.EncodeToString(r)
+ }
+ payload, err := json.Marshal(map[string]any{"v": 1, "htm": "POST", "htu": htu, "iat": iat, "jti": jti, "bh": base64.RawURLEncoding.EncodeToString(bh[:])})
+ if err != nil {
+ t.Fatal(err)
+ }
+ signer := d
+ if o.signer != nil {
+ signer = o.signer
+ }
+ sig, err := assertioncrypto.Sign(signer.key, nativeProofContext, payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return base64.RawURLEncoding.EncodeToString(payload) + "." + base64.RawURLEncoding.EncodeToString(sig)
+}
+
+// call drives one native endpoint as the app would.
+func (d *device) call(t *testing.T, app *testApp, path string, body any, grant string, o ...proofOpts) *httptest.ResponseRecorder {
+ t.Helper()
+ var opts proofOpts
+ if len(o) > 0 {
+ opts = o[0]
+ }
+ b, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest("POST", Origin+path, strings.NewReader(string(b)))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Oficina-Proof", d.proof(t, path, b, opts))
+ if grant != "" {
+ req.Header.Set("Authorization", "OficinaID "+grant)
+ }
+ req.RemoteAddr = "192.0.2.10:4444"
+ if opts.ip != "" {
+ req.RemoteAddr = opts.ip
+ }
+ for k, v := range opts.headers {
+ req.Header.Set(k, v)
+ }
+ w := httptest.NewRecorder()
+ app.Router().ServeHTTP(w, req)
+ return w
+}
+
+func decodeReply(t *testing.T, w *httptest.ResponseRecorder) map[string]any {
+ t.Helper()
+ var out map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
+ t.Fatalf("not JSON (%d): %s", w.Code, w.Body.String())
+ }
+ return out
+}
+
+func (d *device) start(t *testing.T, app *testApp, email string) string {
+ t.Helper()
+ w := d.call(t, app, nativePrefix+"/code/start", map[string]string{"email": email, "device_key": d.public(), "platform": d.platform}, "")
+ if w.Code != http.StatusAccepted {
+ t.Fatalf("start: %d %s", w.Code, w.Body.String())
+ }
+ return decodeReply(t, w)["start"].(string)
+}
+
+var codeLine = regexp.MustCompile(`Your Oficina ID code is (\d{6})`)
+
+func lastCode(t *testing.T, app *testApp) string {
+ t.Helper()
+ m, ok := app.mailer.last()
+ if !ok {
+ t.Fatal("no mail")
+ }
+ got := codeLine.FindStringSubmatch(m.Body)
+ if got == nil {
+ t.Fatal("no code in mail")
+ }
+ return got[1]
+}
+
+func (d *device) verify(t *testing.T, app *testApp, start, code string) *httptest.ResponseRecorder {
+ t.Helper()
+ return d.call(t, app, nativePrefix+"/code/verify", map[string]string{"start": start, "code": code}, "")
+}
+
+// signInByCode runs the whole code sign-in and returns the grant token.
+func (d *device) signInByCode(t *testing.T, app *testApp, email string) (grant, identityID string) {
+ t.Helper()
+ start := d.start(t, app, email)
+ w := d.verify(t, app, start, lastCode(t, app))
+ out := decodeReply(t, w)
+ if w.Code != 200 || out["grant"] == nil {
+ t.Fatalf("verify: %d %s", w.Code, w.Body.String())
+ }
+ return out["grant"].(string), out["identity_id"].(string)
+}
+
+func (d *device) assert(t *testing.T, app *testApp, grant, aud string, challenge []byte, o ...proofOpts) *httptest.ResponseRecorder {
+ t.Helper()
+ return d.call(t, app, nativePrefix+"/assert", map[string]string{"aud": aud, "challenge": base64.RawURLEncoding.EncodeToString(challenge)}, grant, o...)
+}
+
+func grantState(t *testing.T, app *testApp, grant string) (ended bool, reason string) {
+ t.Helper()
+ var e *int64
+ var why *string
+ if err := app.db.Writer().QueryRow("SELECT ended_at,end_reason FROM home_id_grants WHERE grant_hash=?", nativeHash(grant)).Scan(&e, &why); err != nil {
+ t.Fatal(err)
+ }
+ if why != nil {
+ reason = *why
+ }
+ return e != nil, reason
+}
+
+func count(t *testing.T, app *testApp, query string, args ...any) int {
+ t.Helper()
+ var n int
+ if err := app.db.Writer().QueryRow(query, args...).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+// verifierFor is a native client's verifier and challenge.
+func verifierFor(seed byte) (verifier string, challenge []byte) {
+ raw := make([]byte, 32)
+ for i := range raw {
+ raw[i] = seed + byte(i)
+ }
+ sum := sha256.Sum256(raw)
+ return base64.RawURLEncoding.EncodeToString(raw), sum[:]
+}
+
+func verifyAssertion(t *testing.T, app *testApp, token, aud string) assertion.Claims {
+ t.Helper()
+ v, err := assertion.NewVerifier(Origin, aud, app.runtime.keys)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c, err := v.Verify(token, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return c
+}