@pithy-sh/auth 0.11.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (246) hide show
  1. package/README.md +30 -2
  2. package/dist/audit/actions.d.ts +39 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +40 -1
  5. package/dist/audit/emit.d.ts +34 -0
  6. package/dist/audit/emit.d.ts.map +1 -1
  7. package/dist/audit/emit.js +47 -1
  8. package/dist/audit/evidence.d.ts +8 -2
  9. package/dist/audit/evidence.d.ts.map +1 -1
  10. package/dist/capability.d.ts +31 -11
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +38 -5
  13. package/dist/client/api.d.ts +55 -12
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +57 -18
  16. package/dist/client/bearer.d.ts +110 -0
  17. package/dist/client/bearer.d.ts.map +1 -0
  18. package/dist/client/bearer.js +265 -0
  19. package/dist/client/handoff.d.ts +77 -0
  20. package/dist/client/handoff.d.ts.map +1 -0
  21. package/dist/client/handoff.js +119 -0
  22. package/dist/client/mcp.d.ts +70 -0
  23. package/dist/client/mcp.d.ts.map +1 -0
  24. package/dist/client/mcp.js +65 -0
  25. package/dist/data/betterAuth.d.ts +3 -2
  26. package/dist/data/betterAuth.d.ts.map +1 -1
  27. package/dist/data/betterAuth.js +5 -3
  28. package/dist/data/kitFields.d.ts +5 -0
  29. package/dist/data/kitFields.d.ts.map +1 -1
  30. package/dist/data/kitFields.js +5 -0
  31. package/dist/data/tables.d.ts +25 -4
  32. package/dist/data/tables.d.ts.map +1 -1
  33. package/dist/data/tables.js +5 -3
  34. package/dist/data/userLifecycle.d.ts +9 -0
  35. package/dist/data/userLifecycle.d.ts.map +1 -1
  36. package/dist/data/userLifecycle.js +6 -2
  37. package/dist/data/verificationOutcome.d.ts +53 -0
  38. package/dist/data/verificationOutcome.d.ts.map +1 -0
  39. package/dist/data/verificationOutcome.js +50 -0
  40. package/dist/email/send.js +6 -2
  41. package/dist/http/adminRoutes.d.ts.map +1 -1
  42. package/dist/http/adminRoutes.js +56 -10
  43. package/dist/http/csrf.d.ts.map +1 -1
  44. package/dist/http/csrf.js +2 -1
  45. package/dist/http/guards.d.ts +15 -11
  46. package/dist/http/guards.d.ts.map +1 -1
  47. package/dist/http/guards.js +46 -11
  48. package/dist/http/handoff.d.ts +76 -0
  49. package/dist/http/handoff.d.ts.map +1 -0
  50. package/dist/http/handoff.js +316 -0
  51. package/dist/http/middleware.d.ts +12 -0
  52. package/dist/http/middleware.d.ts.map +1 -1
  53. package/dist/http/middleware.js +25 -4
  54. package/dist/http/resolve.d.ts.map +1 -1
  55. package/dist/http/resolve.js +9 -3
  56. package/dist/http/responses.d.ts +142 -0
  57. package/dist/http/responses.d.ts.map +1 -1
  58. package/dist/http/responses.js +66 -10
  59. package/dist/http/routes.d.ts +2 -0
  60. package/dist/http/routes.d.ts.map +1 -1
  61. package/dist/http/routes.js +35 -4
  62. package/dist/http/schemas.d.ts +57 -0
  63. package/dist/http/schemas.d.ts.map +1 -1
  64. package/dist/http/schemas.js +44 -1
  65. package/dist/http/views.d.ts +22 -2
  66. package/dist/http/views.d.ts.map +1 -1
  67. package/dist/http/views.js +40 -4
  68. package/dist/index.d.ts +2 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +4 -2
  71. package/dist/instance/auth.d.ts +148 -10
  72. package/dist/instance/auth.d.ts.map +1 -1
  73. package/dist/instance/auth.js +86 -41
  74. package/dist/instance/plugins.d.ts +6 -0
  75. package/dist/instance/plugins.d.ts.map +1 -1
  76. package/dist/instance/plugins.js +14 -1
  77. package/dist/ledger/read.d.ts +53 -0
  78. package/dist/ledger/read.d.ts.map +1 -0
  79. package/dist/ledger/read.js +85 -0
  80. package/dist/ledger/record.d.ts +35 -0
  81. package/dist/ledger/record.d.ts.map +1 -0
  82. package/dist/ledger/record.js +98 -0
  83. package/dist/lifecycle/erasure.d.ts +9 -0
  84. package/dist/lifecycle/erasure.d.ts.map +1 -0
  85. package/dist/lifecycle/erasure.js +96 -0
  86. package/dist/lifecycle/inactivity.d.ts +19 -0
  87. package/dist/lifecycle/inactivity.d.ts.map +1 -0
  88. package/dist/lifecycle/inactivity.js +28 -0
  89. package/dist/lifecycle/transitions.d.ts +22 -1
  90. package/dist/lifecycle/transitions.d.ts.map +1 -1
  91. package/dist/lifecycle/transitions.js +51 -4
  92. package/dist/mcp/argumentClass.d.ts +51 -0
  93. package/dist/mcp/argumentClass.d.ts.map +1 -0
  94. package/dist/mcp/argumentClass.js +69 -0
  95. package/dist/mcp/capability.d.ts +50 -0
  96. package/dist/mcp/capability.d.ts.map +1 -0
  97. package/dist/mcp/capability.js +140 -0
  98. package/dist/mcp/clientMetadata.d.ts +40 -0
  99. package/dist/mcp/clientMetadata.d.ts.map +1 -0
  100. package/dist/mcp/clientMetadata.js +68 -0
  101. package/dist/mcp/consent.d.ts +49 -0
  102. package/dist/mcp/consent.d.ts.map +1 -0
  103. package/dist/mcp/consent.js +69 -0
  104. package/dist/mcp/dispatch.d.ts +35 -0
  105. package/dist/mcp/dispatch.d.ts.map +1 -0
  106. package/dist/mcp/dispatch.js +135 -0
  107. package/dist/mcp/floor.d.ts +37 -0
  108. package/dist/mcp/floor.d.ts.map +1 -0
  109. package/dist/mcp/floor.js +41 -0
  110. package/dist/mcp/host.d.ts +34 -0
  111. package/dist/mcp/host.d.ts.map +1 -0
  112. package/dist/mcp/host.js +2 -0
  113. package/dist/mcp/http/redirectList.d.ts +9 -0
  114. package/dist/mcp/http/redirectList.d.ts.map +1 -0
  115. package/dist/mcp/http/redirectList.js +24 -0
  116. package/dist/mcp/http/responses.d.ts +143 -0
  117. package/dist/mcp/http/responses.d.ts.map +1 -0
  118. package/dist/mcp/http/responses.js +83 -0
  119. package/dist/mcp/http/routes.d.ts +28 -0
  120. package/dist/mcp/http/routes.d.ts.map +1 -0
  121. package/dist/mcp/http/routes.js +517 -0
  122. package/dist/mcp/http/schemas.d.ts +24 -0
  123. package/dist/mcp/http/schemas.d.ts.map +1 -0
  124. package/dist/mcp/http/schemas.js +18 -0
  125. package/dist/mcp/marker.d.ts +15 -0
  126. package/dist/mcp/marker.d.ts.map +1 -0
  127. package/dist/mcp/marker.js +15 -0
  128. package/dist/mcp/provider.d.ts +78 -0
  129. package/dist/mcp/provider.d.ts.map +1 -0
  130. package/dist/mcp/provider.js +108 -0
  131. package/dist/mcp/purge.d.ts +15 -0
  132. package/dist/mcp/purge.d.ts.map +1 -0
  133. package/dist/mcp/purge.js +31 -0
  134. package/dist/mcp/rpc.d.ts +79 -0
  135. package/dist/mcp/rpc.d.ts.map +1 -0
  136. package/dist/mcp/rpc.js +103 -0
  137. package/dist/mcp/toolAudit.d.ts +76 -0
  138. package/dist/mcp/toolAudit.d.ts.map +1 -0
  139. package/dist/mcp/toolAudit.js +86 -0
  140. package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
  141. package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
  142. package/dist/migrations/0006_verification_outcomes.js +35 -0
  143. package/dist/migrations/0007_erasure_record.d.ts +17 -0
  144. package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
  145. package/dist/migrations/0007_erasure_record.js +36 -0
  146. package/dist/migrations/0008_last_active.d.ts +15 -0
  147. package/dist/migrations/0008_last_active.d.ts.map +1 -0
  148. package/dist/migrations/0008_last_active.js +29 -0
  149. package/dist/migrations/set.d.ts +4 -1
  150. package/dist/migrations/set.d.ts.map +1 -1
  151. package/dist/migrations/set.js +8 -2
  152. package/dist/peer.d.ts +3 -2
  153. package/dist/peer.d.ts.map +1 -1
  154. package/dist/processing/activities.d.ts +6 -0
  155. package/dist/processing/activities.d.ts.map +1 -0
  156. package/dist/processing/activities.js +12 -0
  157. package/dist/purge/contribution.d.ts +20 -5
  158. package/dist/purge/contribution.d.ts.map +1 -1
  159. package/dist/purge/contribution.js +20 -6
  160. package/dist/purge/run.d.ts +75 -5
  161. package/dist/purge/run.d.ts.map +1 -1
  162. package/dist/purge/run.js +117 -14
  163. package/dist/purge/workflow.d.ts +15 -2
  164. package/dist/purge/workflow.d.ts.map +1 -1
  165. package/dist/purge/workflow.js +51 -7
  166. package/dist/test-utils/accountFootprint.d.ts +5 -2
  167. package/dist/test-utils/accountFootprint.d.ts.map +1 -1
  168. package/dist/test-utils/accountFootprint.js +7 -2
  169. package/dist/test-utils/liveApp.d.ts +6 -0
  170. package/dist/test-utils/liveApp.d.ts.map +1 -1
  171. package/dist/test-utils/liveApp.js +7 -2
  172. package/dist/token/handoff.d.ts +80 -0
  173. package/dist/token/handoff.d.ts.map +1 -0
  174. package/dist/token/handoff.js +136 -0
  175. package/dist/version.generated.d.ts +1 -1
  176. package/dist/version.generated.js +1 -1
  177. package/docs/account-lifecycle.md +59 -7
  178. package/docs/apple-signin.md +32 -4
  179. package/docs/facebook-oauth.md +2 -2
  180. package/docs/github-oauth.md +2 -2
  181. package/docs/google-oauth.md +9 -7
  182. package/docs/microsoft-oauth.md +2 -2
  183. package/package.json +11 -5
  184. package/pithy.manifest.json +2 -2
  185. package/pithy.mcp.manifest.json +36 -0
  186. package/src/audit/actions.ts +39 -0
  187. package/src/audit/emit.ts +63 -0
  188. package/src/audit/evidence.ts +8 -4
  189. package/src/capability.ts +80 -23
  190. package/src/client/api.ts +69 -19
  191. package/src/client/bearer.ts +388 -0
  192. package/src/client/handoff.ts +172 -0
  193. package/src/client/mcp.ts +140 -0
  194. package/src/data/betterAuth.ts +8 -4
  195. package/src/data/kitFields.ts +2 -0
  196. package/src/data/tables.ts +4 -2
  197. package/src/data/userLifecycle.ts +15 -3
  198. package/src/data/verificationOutcome.ts +86 -0
  199. package/src/email/send.ts +2 -2
  200. package/src/http/adminRoutes.ts +68 -3
  201. package/src/http/csrf.ts +4 -1
  202. package/src/http/guards.ts +48 -11
  203. package/src/http/handoff.ts +350 -0
  204. package/src/http/middleware.ts +29 -3
  205. package/src/http/resolve.ts +25 -25
  206. package/src/http/responses.ts +134 -8
  207. package/src/http/routes.ts +63 -4
  208. package/src/http/schemas.ts +85 -0
  209. package/src/http/views.ts +46 -2
  210. package/src/index.ts +2 -0
  211. package/src/instance/auth.ts +51 -1
  212. package/src/instance/plugins.ts +20 -2
  213. package/src/ledger/read.ts +133 -0
  214. package/src/ledger/record.ts +198 -0
  215. package/src/lifecycle/erasure.ts +118 -0
  216. package/src/lifecycle/inactivity.ts +56 -0
  217. package/src/lifecycle/transitions.ts +75 -5
  218. package/src/mcp/argumentClass.ts +112 -0
  219. package/src/mcp/capability.ts +194 -0
  220. package/src/mcp/clientMetadata.ts +81 -0
  221. package/src/mcp/consent.ts +95 -0
  222. package/src/mcp/dispatch.ts +154 -0
  223. package/src/mcp/floor.ts +62 -0
  224. package/src/mcp/host.ts +36 -0
  225. package/src/mcp/http/redirectList.ts +26 -0
  226. package/src/mcp/http/responses.ts +157 -0
  227. package/src/mcp/http/routes.ts +635 -0
  228. package/src/mcp/http/schemas.ts +37 -0
  229. package/src/mcp/marker.ts +18 -0
  230. package/src/mcp/provider.ts +151 -0
  231. package/src/mcp/purge.ts +39 -0
  232. package/src/mcp/rpc.ts +135 -0
  233. package/src/mcp/toolAudit.ts +132 -0
  234. package/src/migrations/0006_verification_outcomes.ts +51 -0
  235. package/src/migrations/0007_erasure_record.ts +43 -0
  236. package/src/migrations/0008_last_active.ts +30 -0
  237. package/src/migrations/set.ts +7 -1
  238. package/src/processing/activities.ts +14 -0
  239. package/src/purge/contribution.ts +37 -10
  240. package/src/purge/run.ts +179 -16
  241. package/src/purge/workflow.ts +65 -7
  242. package/src/seeds/example.ts +2 -2
  243. package/src/test-utils/accountFootprint.ts +10 -1
  244. package/src/test-utils/liveApp.ts +10 -1
  245. package/src/token/handoff.ts +180 -0
  246. package/src/version.generated.ts +1 -1
@@ -0,0 +1,388 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import {
5
+ AUTH_BASE_PATH,
6
+ type AuthClientOptions,
7
+ type AuthFetch,
8
+ type AuthRequestInit,
9
+ type AuthResponse,
10
+ type AuthResult,
11
+ callAuth,
12
+ isBareOrigin,
13
+ resolveFetch,
14
+ withoutCookies,
15
+ } from "./api";
16
+
17
+ /**
18
+ * The bearer half of `@pithy-sh/auth`'s client: how a program this Worker does not serve — a native app —
19
+ * holds a session and presents it.
20
+ *
21
+ * **The credential is the raw session token**, the `token` a sign-in answers with and the `refreshToken`
22
+ * `/token/rotate` answers with. Never the JWT `accessToken` beside it, which the kit's own routes do not
23
+ * accept, and never the signed `set-auth-token` header, which the Worker cannot match against a spent
24
+ * credential. Only the raw token lets a replay be recognized as one.
25
+ *
26
+ * **It lives in memory and persists through a {@link SecureStore}**, the Keychain or the Keystore on a
27
+ * phone (`expo-secure-store`). Nothing here writes to `AsyncStorage` or `localStorage`.
28
+ *
29
+ * **Rotation is single-flight, and the successor is stored before anything uses it.** `/token/rotate`
30
+ * spends the credential it is shown. A second rotation of the same credential is refused, and one more
31
+ * than thirty seconds late is read as theft: every session descended from that sign-in is revoked. So
32
+ * one rotation is ever in flight, every request that arrives during it waits for it, and none proceeds
33
+ * until the successor is in the store — a launch that read the spent one back would present it.
34
+ *
35
+ * Nothing here throws. A store that fails costs persistence, never a crash, and every failure on the
36
+ * wire is an {@link AuthResult}.
37
+ */
38
+
39
+ /** Where a credential is persisted between launches. `expo-secure-store`'s three calls have this shape. */
40
+ export interface SecureStore {
41
+ /** The value stored under `key`, or `null`. */
42
+ getItem(key: string): Promise<string | null>;
43
+ /** Store `value` under `key`. */
44
+ setItem(key: string, value: string): Promise<void>;
45
+ /** Remove whatever is stored under `key`. */
46
+ deleteItem(key: string): Promise<void>;
47
+ }
48
+
49
+ /** The device a sign-in registers. The Worker lists it, and revoking it signs out its sessions. */
50
+ export interface DeviceInfo {
51
+ /** A stable id the app mints once per install, at most 128 characters. */
52
+ id: string;
53
+ /** The platform the app runs on. */
54
+ platform: "ios" | "android" | "web";
55
+ /** A human label for the device, when the platform gives one. */
56
+ name?: string;
57
+ /** The hardware model, when the platform gives one. */
58
+ model?: string;
59
+ }
60
+
61
+ /** A bearer session: the transport every client call takes, and the credential behind it. */
62
+ export interface BearerSession {
63
+ /** `{ origin, basePath, fetch }`. Pass it to every auth call. */
64
+ readonly options: AuthClientOptions;
65
+ /**
66
+ * A fetch that adds `Authorization` when a credential is held, sends no cookie, and rotates first when
67
+ * the credential is due. Another capability's client takes it as its own `fetch`.
68
+ */
69
+ readonly fetch: AuthFetch;
70
+ /** Load the credential an earlier launch stored. `true` when one was found. */
71
+ restore(): Promise<boolean>;
72
+ /** Hold the raw session token a sign-in answered with. Resolves once it is stored. */
73
+ adopt(token: string): Promise<void>;
74
+ /** Trade the credential for its successor. Concurrent calls share one request. */
75
+ rotate(): Promise<AuthResult<{ expiresAt: string }>>;
76
+ /** Forget the credential here and in the store. Sign-out calls this after the server call. */
77
+ clear(): Promise<void>;
78
+ /** Whether a credential is held. */
79
+ signedIn(): boolean;
80
+ /**
81
+ * The `Authorization` value a request to `url` would carry now, rotating first when due, for a request the
82
+ * platform sends itself rather than through {@link BearerSession.fetch}: an image the app draws. `null` when
83
+ * nothing is held, and for any URL off the Worker's origin, so the credential is still only ever presented there.
84
+ */
85
+ authorization(url: string): Promise<string | null>;
86
+ }
87
+
88
+ /** The key a credential is stored under by default. */
89
+ export const BEARER_STORAGE_KEY = "pithy.auth.session";
90
+
91
+ /**
92
+ * How long before its expiry a credential is rotated.
93
+ *
94
+ * Wide enough to absorb a phone's clock running a few minutes off the Worker's, narrow enough that a
95
+ * short configured session lifetime does not rotate on every request.
96
+ */
97
+ export const ROTATION_MARGIN_MS = 10 * 60_000;
98
+
99
+ /** The request headers the Worker reads a device from at sign-in. */
100
+ export const BEARER_DEVICE_HEADERS = {
101
+ id: "x-pithy-device-id",
102
+ platform: "x-pithy-platform",
103
+ name: "x-pithy-device-name",
104
+ model: "x-pithy-device-model",
105
+ } as const;
106
+
107
+ /** The longest device id the Worker stores. A longer one would fail the sign-in, so none is sent. */
108
+ const MAX_DEVICE_ID = 128;
109
+
110
+ /** The credential, and when it stops working if that is known. */
111
+ interface Held {
112
+ token: string;
113
+ expiresAt: number | null;
114
+ }
115
+
116
+ /** Whether a value is a plain record. */
117
+ function isRecord(value: unknown): value is Record<string, unknown> {
118
+ return typeof value === "object" && value !== null && !Array.isArray(value);
119
+ }
120
+
121
+ /** What `/token/rotate` answers with, as far as this client reads it. */
122
+ function isRotation(value: unknown): value is { refreshToken: string; expiresAt: string } {
123
+ return (
124
+ isRecord(value) &&
125
+ typeof value.refreshToken === "string" &&
126
+ value.refreshToken !== "" &&
127
+ typeof value.expiresAt === "string"
128
+ );
129
+ }
130
+
131
+ /** An ISO instant as epoch milliseconds, or `null` when it is not one. */
132
+ function instant(value: unknown): number | null {
133
+ if (typeof value !== "string") return null;
134
+ const parsed = Date.parse(value);
135
+ return Number.isNaN(parsed) ? null : parsed;
136
+ }
137
+
138
+ /** A stored credential read back, or `null` when the value is not one this module wrote. */
139
+ function readHeld(raw: string | null): Held | null {
140
+ if (raw === null) return null;
141
+ let parsed: unknown;
142
+ try {
143
+ parsed = JSON.parse(raw);
144
+ } catch {
145
+ return null;
146
+ }
147
+ if (!isRecord(parsed) || typeof parsed.token !== "string" || parsed.token === "") return null;
148
+ const expiresAt = typeof parsed.expiresAt === "number" && Number.isFinite(parsed.expiresAt) ? parsed.expiresAt : null;
149
+ return { token: parsed.token, expiresAt };
150
+ }
151
+
152
+ /**
153
+ * A header value `fetch` will send: printable ASCII only, trimmed, or nothing.
154
+ *
155
+ * `fetch` rejects a header value outside Latin-1, so a phone named with a curly apostrophe or an emoji
156
+ * would otherwise turn every sign-in from it into an unreachable Worker.
157
+ */
158
+ function headerValue(value: string | undefined): string | null {
159
+ if (value === undefined) return null;
160
+ const cleaned = value.replace(/[^\x20-\x7e]/g, "").trim();
161
+ return cleaned === "" ? null : cleaned;
162
+ }
163
+
164
+ /** The device headers a sign-in carries, or none when the id is one the Worker would refuse. */
165
+ function deviceHeaders(device: DeviceInfo): Record<string, string> {
166
+ const id = headerValue(device.id);
167
+ if (id === null || id.length > MAX_DEVICE_ID) return {};
168
+ const headers: Record<string, string> = {
169
+ [BEARER_DEVICE_HEADERS.id]: id,
170
+ [BEARER_DEVICE_HEADERS.platform]: device.platform,
171
+ };
172
+ const name = headerValue(device.name);
173
+ if (name !== null) headers[BEARER_DEVICE_HEADERS.name] = name;
174
+ const model = headerValue(device.model);
175
+ if (model !== null) headers[BEARER_DEVICE_HEADERS.model] = model;
176
+ return headers;
177
+ }
178
+
179
+ /**
180
+ * Start a bearer session against the Worker at `origin`.
181
+ *
182
+ * Nothing is held until {@link BearerSession.restore} or {@link BearerSession.adopt}. Device headers
183
+ * ride on every request to the auth routes, so whichever route creates the session registers the
184
+ * device; requests to another capability's routes carry the credential alone.
185
+ * A URL off `origin` is refused before it is sent, so the credential is only ever presented to this Worker.
186
+ *
187
+ * The expiry is learnt from what the Worker says: each rotation's `expiresAt`, and the session a
188
+ * `get-session` describes. Until one of those has been seen, nothing rotates on its own. A `get-session`
189
+ * that answers nobody means the credential is dead, and it is forgotten.
190
+ */
191
+ export function createBearerSession(input: {
192
+ origin: string;
193
+ basePath?: string;
194
+ store: SecureStore;
195
+ device: DeviceInfo;
196
+ fetch?: AuthFetch;
197
+ now?: () => number;
198
+ storageKey?: string;
199
+ }): BearerSession {
200
+ const { origin, store } = input;
201
+ const basePath = input.basePath ?? AUTH_BASE_PATH;
202
+ const key = input.storageKey ?? BEARER_STORAGE_KEY;
203
+ const now = input.now ?? Date.now;
204
+ const device = deviceHeaders(input.device);
205
+ const authPrefix = `${origin}${basePath}/`;
206
+ const sessionUrl = `${origin}${basePath}/get-session`;
207
+
208
+ let held: Held | null = null;
209
+ // Bumped by every adopt and clear, so a rotation or a restore that started under an older credential
210
+ // never writes over a newer one.
211
+ let generation = 0;
212
+ let inflight: Promise<AuthResult<{ expiresAt: string }>> | null = null;
213
+
214
+ async function persist(next: Held): Promise<void> {
215
+ try {
216
+ await store.setItem(key, JSON.stringify(next));
217
+ } catch {
218
+ // A stored credential that is not the live one is worse than none: after a rotation it is spent,
219
+ // and presenting it later revokes the family. Remove it, and hold the live one in memory.
220
+ await forget();
221
+ }
222
+ }
223
+
224
+ async function forget(): Promise<void> {
225
+ try {
226
+ await store.deleteItem(key);
227
+ } catch {
228
+ // Nothing left to try. The next launch reads whatever the store kept, and the Worker decides.
229
+ }
230
+ }
231
+
232
+ /** Whether the credential may be presented to `url`: the Worker's own origin, and nowhere else. */
233
+ function ownOrigin(url: string): boolean {
234
+ return isBareOrigin(origin) && url.startsWith(`${origin}/`);
235
+ }
236
+
237
+ function send(url: string, init: AuthRequestInit | undefined, token: string | null): Promise<AuthResponse> {
238
+ // The credential is for this Worker alone. A URL anywhere else — another host, a host that merely
239
+ // starts with this one, a relative path the platform would resolve somewhere unknown — is refused
240
+ // the way `fetch` refuses, so the caller's client reports it unreachable and nothing is presented.
241
+ // The origin itself is held to the shape `callAuth` holds it to: one with userinfo or a path in it would make
242
+ // the prefix test below name another host.
243
+ if (!ownOrigin(url)) {
244
+ return Promise.reject(new TypeError("A bearer session only sends to its own Worker's origin."));
245
+ }
246
+ const headers: Record<string, string> = {};
247
+ for (const [name, value] of Object.entries(init?.headers ?? {})) {
248
+ if (name.toLowerCase() !== "authorization") headers[name] = value;
249
+ }
250
+ if (url.startsWith(authPrefix)) Object.assign(headers, device);
251
+ if (token !== null) headers.authorization = `Bearer ${token}`;
252
+ const underlying = resolveFetch({ fetch: input.fetch });
253
+ if (!underlying) return Promise.reject(new TypeError("No fetch is available to send this request."));
254
+ return underlying(url, withoutCookies({ ...init, headers }));
255
+ }
256
+
257
+ function due(): boolean {
258
+ return held !== null && held.expiresAt !== null && now() >= held.expiresAt - ROTATION_MARGIN_MS;
259
+ }
260
+
261
+ async function runRotation(): Promise<AuthResult<{ expiresAt: string }>> {
262
+ const started = generation;
263
+ const token = held?.token ?? null;
264
+ let status = 0;
265
+ const recording: AuthFetch = async (url, init) => {
266
+ const response = await send(url, init, token);
267
+ status = response.status;
268
+ return response;
269
+ };
270
+ const result = await callAuth(
271
+ "/token/rotate",
272
+ { method: "POST" },
273
+ { origin, basePath, fetch: recording },
274
+ isRotation,
275
+ );
276
+ const current = started === generation;
277
+ if (!result.ok) {
278
+ if (current && status === 401) await clear();
279
+ return result;
280
+ }
281
+ if (current) {
282
+ const next = { token: result.value.refreshToken, expiresAt: instant(result.value.expiresAt) };
283
+ held = next;
284
+ await persist(next);
285
+ }
286
+ return { ok: true, value: { expiresAt: result.value.expiresAt } };
287
+ }
288
+
289
+ function rotate(): Promise<AuthResult<{ expiresAt: string }>> {
290
+ if (inflight) return inflight;
291
+ const running = runRotation().finally(() => {
292
+ if (inflight === running) inflight = null;
293
+ });
294
+ inflight = running;
295
+ return running;
296
+ }
297
+
298
+ function observeSession(body: unknown, presented: string): void {
299
+ // A rotation since the request left replaced the credential it describes, and an adopt or a clear
300
+ // replaced or dropped it: either way the answer is about a credential this session no longer holds.
301
+ if (held === null || held.token !== presented) return;
302
+ if (body === null) {
303
+ // A rotation in flight may have spent the presented credential, so the null can be about a
304
+ // credential whose successor is on its way. Decide once the rotation settles.
305
+ if (inflight) {
306
+ const settle = () => {
307
+ if (held !== null && held.token === presented) void clear();
308
+ };
309
+ void inflight.then(settle, settle);
310
+ return;
311
+ }
312
+ void clear();
313
+ return;
314
+ }
315
+ if (!isRecord(body) || !isRecord(body.session)) return;
316
+ const expiresAt = instant(body.session.expiresAt);
317
+ if (expiresAt === null || expiresAt === held.expiresAt) return;
318
+ held = { token: held.token, expiresAt };
319
+ void persist(held);
320
+ }
321
+
322
+ /** Wait out a rotation in flight, or start one when the credential is due. */
323
+ async function current(): Promise<void> {
324
+ if (inflight) await inflight;
325
+ else if (due()) await rotate();
326
+ }
327
+
328
+ const sessionFetch: AuthFetch = async (url, init) => {
329
+ await current();
330
+ const token = held?.token ?? null;
331
+ const response = await send(url, init, token);
332
+ if (token === null || url !== sessionUrl || !response.ok) return response;
333
+ return {
334
+ ok: response.ok,
335
+ status: response.status,
336
+ json: async () => {
337
+ const body = await response.json();
338
+ observeSession(body, token);
339
+ return body;
340
+ },
341
+ };
342
+ };
343
+
344
+ async function clear(): Promise<void> {
345
+ generation += 1;
346
+ held = null;
347
+ await forget();
348
+ }
349
+
350
+ return {
351
+ options: { origin, basePath, fetch: sessionFetch },
352
+ fetch: sessionFetch,
353
+ async restore() {
354
+ // An adopt, a clear or a rotation while the store is read makes what it reads stale: after a rotation it
355
+ // is the spent credential, and presenting that to a later rotation revokes the family.
356
+ const started = generation;
357
+ const before = held;
358
+ let raw: string | null;
359
+ try {
360
+ raw = await store.getItem(key);
361
+ } catch {
362
+ return false;
363
+ }
364
+ if (started !== generation || held !== before) return held !== null;
365
+ const restored = readHeld(raw);
366
+ if (restored === null) {
367
+ if (raw !== null) await forget();
368
+ return false;
369
+ }
370
+ held = restored;
371
+ return true;
372
+ },
373
+ async adopt(token) {
374
+ generation += 1;
375
+ const next = { token, expiresAt: null };
376
+ held = next;
377
+ await persist(next);
378
+ },
379
+ rotate,
380
+ clear,
381
+ signedIn: () => held !== null,
382
+ async authorization(url) {
383
+ if (!ownOrigin(url)) return null;
384
+ await current();
385
+ return held === null ? null : `Bearer ${held.token}`;
386
+ },
387
+ };
388
+ }
@@ -0,0 +1,172 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import {
5
+ AUTH_BASE_PATH,
6
+ type AuthClientOptions,
7
+ type AuthResult,
8
+ callAuth,
9
+ isBareOrigin,
10
+ isSameOriginPath,
11
+ } from "./api";
12
+
13
+ /**
14
+ * The native end of a redirect sign-in. Before it starts, the app makes a verifier with
15
+ * {@link createHandoffVerifier} and keeps it in memory, and opens {@link nativeSignInStartURL} in the system
16
+ * browser's sign-in sheet with {@link handoffCallbackURL} as `callbackURL`: its own link carrying the verifier's
17
+ * S256 challenge. That link is best an https universal link (iOS) or app link (Android), which the system opens only
18
+ * in the app that proves it owns the domain; a custom scheme works too for a social sign-in, and any app can claim
19
+ * one. A magic link is handed off only to an https link, because whoever asks for it chooses the challenge and
20
+ * somebody else opens it; without a universal link, sign in by email with a one-time code. The sign-in
21
+ * returns to that link with a one-time `code`, never the session; the app trades the code and the verifier once,
22
+ * within a minute, for the raw session token, and hands that to its bearer session's `adopt`. Another app that
23
+ * catches the link has the code and not the verifier, so it has nothing it can trade.
24
+ */
25
+
26
+ /** The app-link query parameter the Worker puts the one-time code in. */
27
+ export const HANDOFF_CODE_PARAM = "code";
28
+
29
+ /** The `callbackURL` query parameter the S256 challenge travels in. */
30
+ export const HANDOFF_CHALLENGE_PARAM = "handoff_challenge";
31
+
32
+ /**
33
+ * The two primitives a verifier needs, injected so this module reaches for no platform: on React Native,
34
+ * expo-crypto's `getRandomBytes` and `digest`; on the web, `crypto.getRandomValues` and `crypto.subtle.digest`.
35
+ */
36
+ export interface HandoffCrypto {
37
+ /** `length` cryptographically random bytes. */
38
+ randomBytes(length: number): Uint8Array;
39
+ /** The SHA-256 digest of `data`. */
40
+ sha256(data: Uint8Array): Promise<ArrayBuffer>;
41
+ }
42
+
43
+ /** A verifier the app keeps to itself and the challenge it sends with the sign-in. */
44
+ export interface HandoffVerifier {
45
+ verifier: string;
46
+ challenge: string;
47
+ }
48
+
49
+ const BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
50
+
51
+ /** Unpadded base64url, written out so it needs neither `btoa` nor `Buffer`. */
52
+ function base64Url(bytes: Uint8Array): string {
53
+ let out = "";
54
+ for (let i = 0; i < bytes.length; i += 3) {
55
+ const a = bytes[i] ?? 0;
56
+ const b = bytes[i + 1];
57
+ const c = bytes[i + 2];
58
+ out += BASE64URL[a >> 2];
59
+ out += BASE64URL[((a & 3) << 4) | ((b ?? 0) >> 4)];
60
+ if (b !== undefined) out += BASE64URL[((b & 15) << 2) | ((c ?? 0) >> 6)];
61
+ if (c !== undefined) out += BASE64URL[c & 63];
62
+ }
63
+ return out;
64
+ }
65
+
66
+ /**
67
+ * Make a fresh verifier and its S256 challenge, as RFC 7636 does: 32 random octets, base64url-encoded, is the
68
+ * verifier; the base64url SHA-256 of the verifier's ASCII is the challenge. Make one per sign-in.
69
+ */
70
+ export async function createHandoffVerifier(source: HandoffCrypto): Promise<HandoffVerifier> {
71
+ const verifier = base64Url(source.randomBytes(32));
72
+ const ascii = Uint8Array.from(verifier, (char) => char.charCodeAt(0));
73
+ const challenge = base64Url(new Uint8Array(await source.sha256(ascii)));
74
+ return { verifier, challenge };
75
+ }
76
+
77
+ /** The app's link with the challenge on it: what a native sign-in passes as `callbackURL`. */
78
+ export function handoffCallbackURL(deepLink: string, challenge: string): string {
79
+ const separator = deepLink.includes("?") ? "&" : "?";
80
+ return `${deepLink}${separator}${HANDOFF_CHALLENGE_PARAM}=${encodeURIComponent(challenge)}`;
81
+ }
82
+
83
+ /**
84
+ * The address a native app opens in the system browser's sign-in sheet to start a redirect sign-in: the Worker's
85
+ * `GET {basePath}/sign-in/social/start`. Open it with `WebBrowser.openAuthSessionAsync` rather than posting
86
+ * `/sign-in/social` from the app: the provider's state cookie is set on this answer, so it lands in the sheet's jar,
87
+ * and the sheet is what comes back through the provider's callback. `callbackURL` is {@link handoffCallbackURL}'s.
88
+ * Null for an origin that is not a bare http(s) origin, or a `basePath` that would leave it. Built without `URL`,
89
+ * which React Native does not fully implement.
90
+ */
91
+ export function nativeSignInStartURL(input: {
92
+ origin: string;
93
+ basePath?: string;
94
+ provider: string;
95
+ callbackURL: string;
96
+ errorCallbackURL?: string;
97
+ }): string | null {
98
+ const rooted = `${input.basePath ?? AUTH_BASE_PATH}/sign-in/social/start`;
99
+ if (!isBareOrigin(input.origin) || !isSameOriginPath(rooted)) return null;
100
+ const query = [
101
+ ["provider", input.provider],
102
+ ["callbackURL", input.callbackURL],
103
+ ["errorCallbackURL", input.errorCallbackURL],
104
+ ]
105
+ .filter((pair): pair is [string, string] => pair[1] !== undefined)
106
+ .map(([name, value]) => `${name}=${encodeURIComponent(value)}`)
107
+ .join("&");
108
+ return `${input.origin}${rooted}?${query}`;
109
+ }
110
+
111
+ /** What a trade answers: the raw session token and when the session lapses unless rotated first. */
112
+ export interface HandoffSession {
113
+ token: string;
114
+ expiresAt: string;
115
+ }
116
+
117
+ /** One query-string component, decoded as `application/x-www-form-urlencoded` does, or null when it is not valid. */
118
+ function decodeQueryComponent(raw: string): string | null {
119
+ try {
120
+ return decodeURIComponent(raw.replaceAll("+", " "));
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * The one-time code on the link the sign-in returned to, a custom-scheme deep link or an https universal link, or
128
+ * null when it carries none. Read from the query string by hand, since React Native's `URL` lacks `searchParams` on
129
+ * some runtimes.
130
+ */
131
+ export function handoffCode(link: string): string | null {
132
+ const fragmentStart = link.indexOf("#");
133
+ const beforeFragment = fragmentStart === -1 ? link : link.slice(0, fragmentStart);
134
+ const queryStart = beforeFragment.indexOf("?");
135
+ if (queryStart === -1) return null;
136
+ const query = beforeFragment.slice(queryStart + 1);
137
+ for (const pair of query.split("&")) {
138
+ const equals = pair.indexOf("=");
139
+ if (equals === -1) continue;
140
+ if (decodeQueryComponent(pair.slice(0, equals)) !== HANDOFF_CODE_PARAM) continue;
141
+ const code = decodeQueryComponent(pair.slice(equals + 1));
142
+ return code ? code : null;
143
+ }
144
+ return null;
145
+ }
146
+
147
+ function isHandoffSession(value: unknown): value is HandoffSession {
148
+ if (typeof value !== "object" || value === null) return false;
149
+ const record = value as Record<string, unknown>;
150
+ return typeof record.token === "string" && record.token.length > 0 && typeof record.expiresAt === "string";
151
+ }
152
+
153
+ /**
154
+ * Trade the code, with the verifier whose challenge started the sign-in, for the session. A spent, expired or
155
+ * unknown code, or a wrong verifier, is refused as `auth/handoff_invalid`, and the remedy is to sign in again.
156
+ * Pass a bearer session's `options`, so the device headers ride along.
157
+ */
158
+ export function exchangeHandoff(
159
+ input: { code: string; verifier: string },
160
+ options?: AuthClientOptions,
161
+ ): Promise<AuthResult<HandoffSession>> {
162
+ return callAuth(
163
+ "/handoff",
164
+ {
165
+ method: "POST",
166
+ headers: { "content-type": "application/json" },
167
+ body: JSON.stringify({ code: input.code, verifier: input.verifier }),
168
+ },
169
+ options,
170
+ isHandoffSession,
171
+ );
172
+ }