| 1 | package connect |
| 2 | |
| 3 | import ( |
| 4 | "crypto/subtle" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "mime" |
| 8 | "net/http" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/home/connect/linkstore" |
| 12 | "amadan.net/oficina/home/handoff" |
| 13 | json "github.com/go-json-experiment/json" |
| 14 | ) |
| 15 | |
| 16 | // NativeExchangePath is where a native app trades a Home assertion for a |
| 17 | // session on this instance (Home spec 2026-11-14-oficina-id-native.md §7, |
| 18 | // step 2). Mount Bridge.NativeExchange at POST, outside the app's CSRF |
| 19 | // middleware (Routes.Middleware lets it through): it refuses any request a |
| 20 | // browser could make, and reads and sets no cookies. |
| 21 | const NativeExchangePath = "/native/oficina-id" |
| 22 | |
| 23 | // The answer states. Every answer is a JSON object with "state", served |
| 24 | // no-store with no cookies: |
| 25 | // |
| 26 | // 200 ok {"state":"ok","name":<cookie name>,"value":<session>,"expires_at":<unix>} |
| 27 | // (and "target" echoed when the request carried one) |
| 28 | // 400 invalid the request is malformed; do not retry it as is |
| 29 | // 401 failed the assertion was not accepted (bad, expired, wrong |
| 30 | // audience or verifier, or already used): fetch a fresh |
| 31 | // assertion and try once more |
| 32 | // 403 unknown no person here, and none may be made; identical for |
| 33 | // every such subject, and on an instance without the hooks |
| 34 | // 409 choose a roster Member with no person here: offer "Connect my |
| 35 | // existing account" and "I'm new here", and send |
| 36 | // choice:"new" only from the second |
| 37 | // 503 unavailable try again shortly |
| 38 | const ( |
| 39 | nativeOK = "ok" |
| 40 | nativeInvalid = "invalid" |
| 41 | nativeFailed = "failed" |
| 42 | nativeUnknown = "unknown" |
| 43 | nativeChoose = "choose" |
| 44 | nativeUnavailable = "unavailable" |
| 45 | ) |
| 46 | |
| 47 | var nativeStatus = map[string]int{ |
| 48 | nativeInvalid: http.StatusBadRequest, nativeFailed: http.StatusUnauthorized, |
| 49 | nativeUnknown: http.StatusForbidden, nativeChoose: http.StatusConflict, |
| 50 | nativeUnavailable: http.StatusServiceUnavailable, |
| 51 | } |
| 52 | |
| 53 | type nativeRequest struct { |
| 54 | Assertion string `json:"assertion"` |
| 55 | Verifier string `json:"verifier"` |
| 56 | Target string `json:"target,omitempty"` |
| 57 | Choice string `json:"choice,omitempty"` |
| 58 | } |
| 59 | |
| 60 | type nativeSession struct { |
| 61 | State string `json:"state"` |
| 62 | Name string `json:"name"` |
| 63 | Value string `json:"value"` |
| 64 | ExpiresAt int64 `json:"expires_at"` |
| 65 | Target string `json:"target,omitempty"` |
| 66 | } |
| 67 | |
| 68 | func nativeAnswer(w http.ResponseWriter, state string) { |
| 69 | w.Header().Set("Content-Type", "application/json") |
| 70 | w.WriteHeader(nativeStatus[state]) |
| 71 | w.Write([]byte(`{"state":"` + state + `"}`)) |
| 72 | } |
| 73 | |
| 74 | // NativeExchange is POST /native/oficina-id, {assertion, verifier, |
| 75 | // target?, choice?}. It runs the spec's five steps in order, and holds no |
| 76 | // transaction across any hook or the mint: |
| 77 | // |
| 78 | // 1. Verify the assertion (pinned keys, exact issuer and audience) and |
| 79 | // recompute the native nonce from the verifier. |
| 80 | // 2. Resolve the link, then the Home-only person, writing nothing. |
| 81 | // 3. With neither, ask Admit: a non-member is "unknown", an unavailable |
| 82 | // roster 503, a Member without choice:"new" 409 "choose". All three |
| 83 | // return before any jti is written. |
| 84 | // 4. A Member with choice:"new" is allocated through Unlinked, then |
| 85 | // resolved again; nobody found is "unknown" (or 503). |
| 86 | // 5. Reserve the jti in its own committed transaction, then resolve |
| 87 | // again, recheck a Home-only person's admission, and mint a |
| 88 | // NativeMethod session through MintNativeSession. |
| 89 | // |
| 90 | // A reserved jti that ends in no session costs the client one fresh |
| 91 | // assertion; a jti is never reserved twice. choice is ignored for a subject |
| 92 | // who already has a person here. Without MintNativeSession it is 404. |
| 93 | func (b *Bridge) NativeExchange(w http.ResponseWriter, r *http.Request) { |
| 94 | w.Header().Set("Cache-Control", "no-store") |
| 95 | if b.mintNative == nil || r.Host != b.host() || r.URL.Path != NativeExchangePath { |
| 96 | w.Header().Set("Content-Type", "application/json") |
| 97 | w.WriteHeader(http.StatusNotFound) |
| 98 | w.Write([]byte(`{"state":"not_found"}`)) |
| 99 | return |
| 100 | } |
| 101 | if r.Method != http.MethodPost { |
| 102 | w.Header().Set("Allow", http.MethodPost) |
| 103 | w.Header().Set("Content-Type", "application/json") |
| 104 | w.WriteHeader(http.StatusMethodNotAllowed) |
| 105 | w.Write([]byte(`{"state":"method_not_allowed"}`)) |
| 106 | return |
| 107 | } |
| 108 | // No browser makes this request: refuse anything carrying a browser's |
| 109 | // provenance, which also means no form or fetch from any page can. |
| 110 | if r.URL.RawQuery != "" || len(r.Header.Values("Origin")) != 0 || len(r.Header.Values("Sec-Fetch-Site")) != 0 { |
| 111 | nativeAnswer(w, nativeInvalid) |
| 112 | return |
| 113 | } |
| 114 | media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 115 | if err != nil || media != "application/json" { |
| 116 | nativeAnswer(w, nativeInvalid) |
| 117 | return |
| 118 | } |
| 119 | body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024)) |
| 120 | if err != nil { |
| 121 | nativeAnswer(w, nativeInvalid) |
| 122 | return |
| 123 | } |
| 124 | var in nativeRequest |
| 125 | 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)) { |
| 126 | nativeAnswer(w, nativeInvalid) |
| 127 | return |
| 128 | } |
| 129 | challenge, ok := handoff.NativeChallenge(in.Verifier) |
| 130 | if !ok { |
| 131 | nativeAnswer(w, nativeInvalid) |
| 132 | return |
| 133 | } |
| 134 | |
| 135 | // 1. Verify, and accept only the native nonce for this verifier. |
| 136 | claims, err := b.exchange.Verify(in.Assertion, b.now()) |
| 137 | if err != nil { |
| 138 | nativeAnswer(w, nativeFailed) |
| 139 | return |
| 140 | } |
| 141 | // Known and accepted (Fable, 2026-11-14 review; recorded in the spec): |
| 142 | // an instance cannot tell this assertion from a browser one that |
| 143 | // /authorize minted with a caller-chosen nonce equal to a native nonce. |
| 144 | // Only the subject's own browser can do that, for itself, so it grants |
| 145 | // nothing the person does not already have. |
| 146 | nonce, _ := handoff.NativeNonce(challenge) |
| 147 | if subtle.ConstantTimeCompare([]byte(nonce), []byte(claims.Nonce)) != 1 { |
| 148 | nativeAnswer(w, nativeFailed) |
| 149 | return |
| 150 | } |
| 151 | ctx := r.Context() |
| 152 | subject := claims.Subject |
| 153 | |
| 154 | // 2. Read the link, then the Home-only person. |
| 155 | _, err = b.Resolve(ctx, subject) |
| 156 | if errors.Is(err, linkstore.ErrRefused) { |
| 157 | // 3. Decide: the roster, with nothing allocated and no jti kept. |
| 158 | if b.admit == nil { |
| 159 | nativeAnswer(w, nativeUnknown) |
| 160 | return |
| 161 | } |
| 162 | switch decision := b.admit(ctx, b.issuer, subject); { |
| 163 | case errors.Is(decision, ErrNoPerson): |
| 164 | nativeAnswer(w, nativeUnknown) |
| 165 | return |
| 166 | case decision != nil: |
| 167 | nativeAnswer(w, nativeUnavailable) |
| 168 | return |
| 169 | case in.Choice != "new": |
| 170 | nativeAnswer(w, nativeChoose) |
| 171 | return |
| 172 | } |
| 173 | // 4. Allocate, on the Member's explicit choice. |
| 174 | _, err = b.allocate(ctx, subject) |
| 175 | } |
| 176 | switch { |
| 177 | case errors.Is(err, linkstore.ErrRefused): |
| 178 | nativeAnswer(w, nativeUnknown) |
| 179 | return |
| 180 | case err != nil: |
| 181 | nativeAnswer(w, nativeUnavailable) |
| 182 | return |
| 183 | } |
| 184 | |
| 185 | // 5. Reserve, then resolve again, recheck and mint. |
| 186 | if _, err := b.exchange.Reserve(ctx, in.Assertion, b.now()); err != nil { |
| 187 | if errors.Is(err, handoff.ErrRefused) { |
| 188 | nativeAnswer(w, nativeFailed) |
| 189 | } else { |
| 190 | nativeAnswer(w, nativeUnavailable) |
| 191 | } |
| 192 | return |
| 193 | } |
| 194 | person, err := b.Resolve(ctx, subject) |
| 195 | if err == nil && person.Label == "" && b.admit != nil { |
| 196 | // A Home-only person's standing is the roster's alone; a linked |
| 197 | // account's admission was rechecked by LookupPerson in Resolve. |
| 198 | switch decision := b.admit(ctx, b.issuer, subject); { |
| 199 | case errors.Is(decision, ErrNoPerson): |
| 200 | err = linkstore.ErrRefused |
| 201 | case decision != nil: |
| 202 | err = linkstore.ErrStorage |
| 203 | } |
| 204 | } |
| 205 | switch { |
| 206 | case errors.Is(err, linkstore.ErrRefused): |
| 207 | nativeAnswer(w, nativeUnknown) |
| 208 | return |
| 209 | case err != nil: |
| 210 | nativeAnswer(w, nativeUnavailable) |
| 211 | return |
| 212 | } |
| 213 | minted := b.now() |
| 214 | value, err := b.mintNative(ctx, Session{Subject: subject, Method: NativeMethod, AuthTime: time.Unix(claims.AuthTime, 0)}) |
| 215 | if err != nil || value == "" { |
| 216 | nativeAnswer(w, nativeUnavailable) |
| 217 | return |
| 218 | } |
| 219 | out, err := json.Marshal(nativeSession{State: nativeOK, Name: b.sessionCookie, Value: value, ExpiresAt: minted.Add(NativeLifetime).Unix(), Target: in.Target}) |
| 220 | if err != nil { |
| 221 | nativeAnswer(w, nativeUnavailable) |
| 222 | return |
| 223 | } |
| 224 | w.Header().Set("Content-Type", "application/json") |
| 225 | w.WriteHeader(http.StatusOK) |
| 226 | w.Write(out) |
| 227 | } |
| 228 | |