package connect import ( "crypto/subtle" "errors" "io" "mime" "net/http" "time" "amadan.net/oficina/home/connect/linkstore" "amadan.net/oficina/home/handoff" json "github.com/go-json-experiment/json" ) // NativeExchangePath is where a native app trades a Home assertion for a // session on this instance (Home spec 2026-11-14-oficina-id-native.md ยง7, // step 2). Mount Bridge.NativeExchange at POST, outside the app's CSRF // middleware (Routes.Middleware lets it through): it refuses any request a // browser could make, and reads and sets no cookies. const NativeExchangePath = "/native/oficina-id" // The answer states. Every answer is a JSON object with "state", served // no-store with no cookies: // // 200 ok {"state":"ok","name":,"value":,"expires_at":} // (and "target" echoed when the request carried one) // 400 invalid the request is malformed; do not retry it as is // 401 failed the assertion was not accepted (bad, expired, wrong // audience or verifier, or already used): fetch a fresh // assertion and try once more // 403 unknown no person here, and none may be made; identical for // every such subject, and on an instance without the hooks // 409 choose a roster Member with no person here: offer "Connect my // existing account" and "I'm new here", and send // choice:"new" only from the second // 503 unavailable try again shortly const ( nativeOK = "ok" nativeInvalid = "invalid" nativeFailed = "failed" nativeUnknown = "unknown" nativeChoose = "choose" nativeUnavailable = "unavailable" ) var nativeStatus = map[string]int{ nativeInvalid: http.StatusBadRequest, nativeFailed: http.StatusUnauthorized, nativeUnknown: http.StatusForbidden, nativeChoose: http.StatusConflict, nativeUnavailable: http.StatusServiceUnavailable, } type nativeRequest struct { Assertion string `json:"assertion"` Verifier string `json:"verifier"` Target string `json:"target,omitempty"` Choice string `json:"choice,omitempty"` } type nativeSession struct { State string `json:"state"` Name string `json:"name"` Value string `json:"value"` ExpiresAt int64 `json:"expires_at"` Target string `json:"target,omitempty"` } func nativeAnswer(w http.ResponseWriter, state string) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(nativeStatus[state]) w.Write([]byte(`{"state":"` + state + `"}`)) } // NativeExchange is POST /native/oficina-id, {assertion, verifier, // target?, choice?}. It runs the spec's five steps in order, and holds no // transaction across any hook or the mint: // // 1. Verify the assertion (pinned keys, exact issuer and audience) and // recompute the native nonce from the verifier. // 2. Resolve the link, then the Home-only person, writing nothing. // 3. With neither, ask Admit: a non-member is "unknown", an unavailable // roster 503, a Member without choice:"new" 409 "choose". All three // return before any jti is written. // 4. A Member with choice:"new" is allocated through Unlinked, then // resolved again; nobody found is "unknown" (or 503). // 5. Reserve the jti in its own committed transaction, then resolve // again, recheck a Home-only person's admission, and mint a // NativeMethod session through MintNativeSession. // // A reserved jti that ends in no session costs the client one fresh // assertion; a jti is never reserved twice. choice is ignored for a subject // who already has a person here. Without MintNativeSession it is 404. func (b *Bridge) NativeExchange(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") if b.mintNative == nil || r.Host != b.host() || r.URL.Path != NativeExchangePath { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusNotFound) w.Write([]byte(`{"state":"not_found"}`)) return } if r.Method != http.MethodPost { w.Header().Set("Allow", http.MethodPost) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusMethodNotAllowed) w.Write([]byte(`{"state":"method_not_allowed"}`)) return } // No browser makes this request: refuse anything carrying a browser's // provenance, which also means no form or fetch from any page can. if r.URL.RawQuery != "" || len(r.Header.Values("Origin")) != 0 || len(r.Header.Values("Sec-Fetch-Site")) != 0 { nativeAnswer(w, nativeInvalid) return } media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil || media != "application/json" { nativeAnswer(w, nativeInvalid) return } body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024)) if err != nil { nativeAnswer(w, nativeInvalid) return } var in nativeRequest if json.Unmarshal(body, &in, json.RejectUnknownMembers(true)) != nil || in.Assertion == "" || len(in.Assertion) > 8192 || (in.Choice != "" && in.Choice != "new") || (in.Target != "" && !handoff.SafePath(in.Target)) { nativeAnswer(w, nativeInvalid) return } challenge, ok := handoff.NativeChallenge(in.Verifier) if !ok { nativeAnswer(w, nativeInvalid) return } // 1. Verify, and accept only the native nonce for this verifier. claims, err := b.exchange.Verify(in.Assertion, b.now()) if err != nil { nativeAnswer(w, nativeFailed) return } // Known and accepted (Fable, 2026-11-14 review; recorded in the spec): // an instance cannot tell this assertion from a browser one that // /authorize minted with a caller-chosen nonce equal to a native nonce. // Only the subject's own browser can do that, for itself, so it grants // nothing the person does not already have. nonce, _ := handoff.NativeNonce(challenge) if subtle.ConstantTimeCompare([]byte(nonce), []byte(claims.Nonce)) != 1 { nativeAnswer(w, nativeFailed) return } ctx := r.Context() subject := claims.Subject // 2. Read the link, then the Home-only person. _, err = b.Resolve(ctx, subject) if errors.Is(err, linkstore.ErrRefused) { // 3. Decide: the roster, with nothing allocated and no jti kept. if b.admit == nil { nativeAnswer(w, nativeUnknown) return } switch decision := b.admit(ctx, b.issuer, subject); { case errors.Is(decision, ErrNoPerson): nativeAnswer(w, nativeUnknown) return case decision != nil: nativeAnswer(w, nativeUnavailable) return case in.Choice != "new": nativeAnswer(w, nativeChoose) return } // 4. Allocate, on the Member's explicit choice. _, err = b.allocate(ctx, subject) } switch { case errors.Is(err, linkstore.ErrRefused): nativeAnswer(w, nativeUnknown) return case err != nil: nativeAnswer(w, nativeUnavailable) return } // 5. Reserve, then resolve again, recheck and mint. if _, err := b.exchange.Reserve(ctx, in.Assertion, b.now()); err != nil { if errors.Is(err, handoff.ErrRefused) { nativeAnswer(w, nativeFailed) } else { nativeAnswer(w, nativeUnavailable) } return } person, err := b.Resolve(ctx, subject) if err == nil && person.Label == "" && b.admit != nil { // A Home-only person's standing is the roster's alone; a linked // account's admission was rechecked by LookupPerson in Resolve. switch decision := b.admit(ctx, b.issuer, subject); { case errors.Is(decision, ErrNoPerson): err = linkstore.ErrRefused case decision != nil: err = linkstore.ErrStorage } } switch { case errors.Is(err, linkstore.ErrRefused): nativeAnswer(w, nativeUnknown) return case err != nil: nativeAnswer(w, nativeUnavailable) return } minted := b.now() value, err := b.mintNative(ctx, Session{Subject: subject, Method: NativeMethod, AuthTime: time.Unix(claims.AuthTime, 0)}) if err != nil || value == "" { nativeAnswer(w, nativeUnavailable) return } out, err := json.Marshal(nativeSession{State: nativeOK, Name: b.sessionCookie, Value: value, ExpiresAt: minted.Add(NativeLifetime).Unix(), Target: in.Target}) if err != nil { nativeAnswer(w, nativeUnavailable) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(out) }