@pithy-sh/auth 0.8.0 → 0.10.0

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 (164) hide show
  1. package/README.md +12 -2
  2. package/dist/audit/actions.d.ts +21 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +22 -1
  5. package/dist/audit/emit.js +1 -1
  6. package/dist/caller/certificate.d.ts +83 -0
  7. package/dist/caller/certificate.d.ts.map +1 -0
  8. package/dist/caller/certificate.js +92 -0
  9. package/dist/caller/request.d.ts +66 -0
  10. package/dist/caller/request.d.ts.map +1 -0
  11. package/dist/caller/request.js +71 -0
  12. package/dist/caller/token.d.ts +130 -0
  13. package/dist/caller/token.d.ts.map +1 -0
  14. package/dist/caller/token.js +207 -0
  15. package/dist/capability.d.ts +70 -2
  16. package/dist/capability.d.ts.map +1 -1
  17. package/dist/capability.js +28 -7
  18. package/dist/client/lifecycle.d.ts +19 -0
  19. package/dist/client/lifecycle.d.ts.map +1 -0
  20. package/dist/client/lifecycle.js +25 -0
  21. package/dist/client/projection.d.ts +4 -0
  22. package/dist/client/projection.d.ts.map +1 -1
  23. package/dist/data/betterAuth.d.ts +5 -1
  24. package/dist/data/betterAuth.d.ts.map +1 -1
  25. package/dist/data/betterAuth.js +7 -3
  26. package/dist/data/kitFields.d.ts +20 -25
  27. package/dist/data/kitFields.d.ts.map +1 -1
  28. package/dist/data/kitFields.js +28 -32
  29. package/dist/data/tables.d.ts +29 -3
  30. package/dist/data/tables.d.ts.map +1 -1
  31. package/dist/data/tables.js +5 -3
  32. package/dist/data/userLifecycle.d.ts +61 -0
  33. package/dist/data/userLifecycle.d.ts.map +1 -0
  34. package/dist/data/userLifecycle.js +50 -0
  35. package/dist/http/credentialResign.d.ts +46 -0
  36. package/dist/http/credentialResign.d.ts.map +1 -0
  37. package/dist/http/credentialResign.js +203 -0
  38. package/dist/http/errorCallbackUrl.d.ts.map +1 -1
  39. package/dist/http/errorCallbackUrl.js +15 -9
  40. package/dist/http/guards.d.ts +23 -1
  41. package/dist/http/guards.d.ts.map +1 -1
  42. package/dist/http/guards.js +28 -3
  43. package/dist/http/lifecycleGate.d.ts +18 -0
  44. package/dist/http/lifecycleGate.d.ts.map +1 -0
  45. package/dist/http/lifecycleGate.js +75 -0
  46. package/dist/http/middleware.d.ts +5 -0
  47. package/dist/http/middleware.d.ts.map +1 -1
  48. package/dist/http/middleware.js +113 -21
  49. package/dist/http/providerRefusal.d.ts +8 -7
  50. package/dist/http/providerRefusal.d.ts.map +1 -1
  51. package/dist/http/providerRefusal.js +37 -32
  52. package/dist/http/resolve.d.ts.map +1 -1
  53. package/dist/http/resolve.js +23 -5
  54. package/dist/http/routes.d.ts.map +1 -1
  55. package/dist/http/routes.js +20 -1
  56. package/dist/instance/auth.d.ts +1280 -5
  57. package/dist/instance/auth.d.ts.map +1 -1
  58. package/dist/instance/auth.js +59 -4
  59. package/dist/instance/jwksReencryption.d.ts +75 -0
  60. package/dist/instance/jwksReencryption.d.ts.map +1 -0
  61. package/dist/instance/jwksReencryption.js +160 -0
  62. package/dist/instance/microsoftEmail.d.ts +70 -0
  63. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  64. package/dist/instance/microsoftEmail.js +96 -0
  65. package/dist/instance/providerSignInGate.d.ts +14 -12
  66. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  67. package/dist/instance/providerSignInGate.js +23 -20
  68. package/dist/instance/providers.d.ts +7 -5
  69. package/dist/instance/providers.d.ts.map +1 -1
  70. package/dist/instance/providers.js +5 -3
  71. package/dist/instance/secrets.d.ts +232 -4
  72. package/dist/instance/secrets.d.ts.map +1 -1
  73. package/dist/instance/secrets.js +129 -7
  74. package/dist/instance/sessionSecrets.d.ts +45 -0
  75. package/dist/instance/sessionSecrets.d.ts.map +1 -0
  76. package/dist/instance/sessionSecrets.js +29 -0
  77. package/dist/lifecycle/enforce.d.ts +40 -0
  78. package/dist/lifecycle/enforce.d.ts.map +1 -0
  79. package/dist/lifecycle/enforce.js +70 -0
  80. package/dist/lifecycle/hooks.d.ts +53 -0
  81. package/dist/lifecycle/hooks.d.ts.map +1 -0
  82. package/dist/lifecycle/hooks.js +2 -0
  83. package/dist/lifecycle/request.d.ts +15 -0
  84. package/dist/lifecycle/request.d.ts.map +1 -0
  85. package/dist/lifecycle/request.js +27 -0
  86. package/dist/lifecycle/state.d.ts +64 -0
  87. package/dist/lifecycle/state.d.ts.map +1 -0
  88. package/dist/lifecycle/state.js +90 -0
  89. package/dist/lifecycle/transitions.d.ts +132 -0
  90. package/dist/lifecycle/transitions.d.ts.map +1 -0
  91. package/dist/lifecycle/transitions.js +349 -0
  92. package/dist/migrations/0001_init.d.ts.map +1 -1
  93. package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
  94. package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
  95. package/dist/migrations/0003_account_issuer_nullable.js +131 -0
  96. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  97. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  98. package/dist/migrations/0004_user_lifecycle.js +47 -0
  99. package/dist/migrations/set.d.ts +3 -1
  100. package/dist/migrations/set.d.ts.map +1 -1
  101. package/dist/migrations/set.js +6 -2
  102. package/dist/peer.d.ts +4 -0
  103. package/dist/peer.d.ts.map +1 -1
  104. package/dist/test-utils/liveApp.d.ts +26 -0
  105. package/dist/test-utils/liveApp.d.ts.map +1 -1
  106. package/dist/test-utils/liveApp.js +1 -0
  107. package/dist/test-utils/schemaDrift.d.ts +49 -0
  108. package/dist/test-utils/schemaDrift.d.ts.map +1 -0
  109. package/dist/test-utils/schemaDrift.js +35 -0
  110. package/dist/test-utils/scopedBackend.d.ts +204 -0
  111. package/dist/test-utils/scopedBackend.d.ts.map +1 -0
  112. package/dist/test-utils/scopedBackend.js +166 -0
  113. package/dist/version.generated.d.ts +1 -1
  114. package/dist/version.generated.d.ts.map +1 -1
  115. package/dist/version.generated.js +1 -1
  116. package/docs/account-lifecycle.md +105 -0
  117. package/docs/apple-signin.md +7 -1
  118. package/docs/facebook-oauth.md +7 -1
  119. package/docs/github-oauth.md +7 -1
  120. package/docs/google-oauth.md +7 -1
  121. package/docs/microsoft-oauth.md +177 -0
  122. package/docs/server-authoritative.md +182 -0
  123. package/package.json +11 -8
  124. package/pithy.manifest.json +17 -3
  125. package/src/audit/actions.ts +23 -0
  126. package/src/audit/emit.ts +1 -1
  127. package/src/caller/certificate.ts +133 -0
  128. package/src/caller/request.ts +84 -0
  129. package/src/caller/token.ts +276 -0
  130. package/src/capability.ts +170 -38
  131. package/src/client/lifecycle.ts +27 -0
  132. package/src/client/projection.ts +4 -0
  133. package/src/data/betterAuth.ts +23 -2
  134. package/src/data/kitFields.ts +27 -0
  135. package/src/data/tables.ts +4 -2
  136. package/src/data/userLifecycle.ts +80 -0
  137. package/src/http/credentialResign.ts +268 -0
  138. package/src/http/errorCallbackUrl.ts +21 -13
  139. package/src/http/guards.ts +29 -1
  140. package/src/http/lifecycleGate.ts +78 -0
  141. package/src/http/middleware.ts +161 -37
  142. package/src/http/providerRefusal.ts +40 -32
  143. package/src/http/resolve.ts +34 -5
  144. package/src/http/routes.ts +39 -2
  145. package/src/instance/auth.ts +91 -6
  146. package/src/instance/jwksReencryption.ts +206 -0
  147. package/src/instance/microsoftEmail.ts +111 -0
  148. package/src/instance/providerSignInGate.ts +30 -27
  149. package/src/instance/providers.ts +8 -4
  150. package/src/instance/secrets.ts +153 -6
  151. package/src/instance/sessionSecrets.ts +64 -0
  152. package/src/lifecycle/enforce.ts +89 -0
  153. package/src/lifecycle/hooks.ts +54 -0
  154. package/src/lifecycle/request.ts +31 -0
  155. package/src/lifecycle/state.ts +101 -0
  156. package/src/lifecycle/transitions.ts +483 -0
  157. package/src/migrations/0001_init.ts +8 -10
  158. package/src/migrations/0003_account_issuer_nullable.ts +199 -0
  159. package/src/migrations/0004_user_lifecycle.ts +68 -0
  160. package/src/migrations/set.ts +5 -1
  161. package/src/test-utils/liveApp.ts +2 -1
  162. package/src/test-utils/schemaDrift.ts +82 -0
  163. package/src/test-utils/scopedBackend.ts +137 -0
  164. package/src/version.generated.ts +1 -1
@@ -0,0 +1,276 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
5
+ import { z } from "zod";
6
+
7
+ /**
8
+ * **A short-lived, audience-restricted caller token — the portable way to prove a request came from the
9
+ * adopter's own backend (#560).**
10
+ *
11
+ * `resolveScopes` asks one question: is this request's caller the adopter's trusted backend, or a device?
12
+ * Where that backend is a Worker, a service binding answers it with no credential at all, and where the
13
+ * zone can run mTLS a client certificate answers it at the edge. Neither works everywhere — a service
14
+ * binding needs both ends on Cloudflare, mTLS needs a proxied zone and an exact hostname, so not
15
+ * `workers.dev`. This is what works on day one anywhere, and it is shipped because the alternative every
16
+ * adopter otherwise reaches for is a long-lived shared secret compared in a header, which fails every
17
+ * control RFC 9700 names at once.
18
+ *
19
+ * So it holds to those controls, each on its own line below:
20
+ *
21
+ * - **Audience-restricted.** `aud` is the origin the token was minted for, and it verifies there and nowhere
22
+ * else — a staging token presented to production is refused, and so is one Worker's token replayed at
23
+ * another that happens to share the key.
24
+ * - **Short-lived.** Five minutes by default, and a ceiling of fifteen that no token and no configuration
25
+ * gets past. A token whose `exp` is a day after its `iat` is refused even when it is otherwise perfect,
26
+ * because honoring it would make it a shared secret with extra steps.
27
+ * - **Signed with a key the Worker reads from `@pithy-sh/secrets`.** The operator supplies it and the
28
+ * backend holds the same value. The `kid` names the stored version the token was signed with, and a kid
29
+ * the store does not hold is refused.
30
+ *
31
+ * What it is not is **sender-constrained**: a token lifted off the wire is usable by whoever lifted it, for
32
+ * the minutes it has left. RFC 9700 says a token SHOULD be bound to its sender, and the two answers are
33
+ * mTLS (`readClientCertificate`) and DPoP, which the kit does not ship yet. Short lifetime is what limits
34
+ * the damage here, which is why the ceiling is not negotiable.
35
+ *
36
+ * **HS256 and nothing else.** One algorithm, one key type, one token shape — the header is validated
37
+ * against a literal, so `alg: none` and an asymmetric algorithm are malformed rather than negotiated. No
38
+ * JWT library: the algorithm agility one brings is where the JWT vulnerabilities live.
39
+ */
40
+
41
+ /** The header a caller token travels on. Not `Authorization`, which carries the player's forwarded session. */
42
+ export const CALLER_TOKEN_HEADER = "pithy-caller";
43
+
44
+ /** How long a minted token lives unless the minter asks for less: five minutes. */
45
+ export const DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS = 5 * 60;
46
+
47
+ /**
48
+ * The longest a caller token may live, from its `iat` to its `exp` — fifteen minutes, minted or verified.
49
+ *
50
+ * A ceiling rather than a default, and it refuses above rather than clamping: a verifier configured past it
51
+ * is a configuration error, and a token claiming more is refused. Minutes because the token is a bearer
52
+ * credential with no sender binding, and its lifetime is the whole of what bounds a stolen one.
53
+ */
54
+ export const MAX_CALLER_TOKEN_LIFETIME_SECONDS = 15 * 60;
55
+
56
+ /** How far in the future an `iat` may sit before the token is refused — clocks disagree by seconds, not minutes. */
57
+ export const CALLER_TOKEN_CLOCK_SKEW_SECONDS = 30;
58
+
59
+ /** The protected header of a caller token. */
60
+ export const CallerTokenHeader = z
61
+ .object({
62
+ alg: z.literal("HS256").describe("The signature algorithm. HMAC-SHA-256, and nothing else is accepted."),
63
+ typ: z.literal("JWT").optional().describe("The media type, `JWT` when present."),
64
+ kid: z.string().min(1).describe("The version of the caller-token key this token was signed with."),
65
+ })
66
+ .describe("The protected header of a caller token: HS256, and which key version signed it.");
67
+ export type CallerTokenHeader = z.infer<typeof CallerTokenHeader>;
68
+
69
+ /** The claims a caller token carries. */
70
+ export const CallerTokenClaims = z
71
+ .object({
72
+ aud: z.string().describe("The origin this token was minted for. It verifies at that origin and nowhere else."),
73
+ iat: z.number().int().describe("When it was minted, in Unix seconds."),
74
+ exp: z.number().int().describe("When it stops verifying, in Unix seconds. At most fifteen minutes after `iat`."),
75
+ sub: z
76
+ .string()
77
+ .optional()
78
+ .describe("Which backend minted it, for the adopter's own logs. The verifier grants nothing on it."),
79
+ })
80
+ .describe("The claims of a caller token: where it is valid, and for how long.");
81
+ export type CallerTokenClaims = z.infer<typeof CallerTokenClaims>;
82
+
83
+ /**
84
+ * Why a caller token was not trusted. Distinct values so the adopter's own log can say which, never so a
85
+ * response can — a resolver answers `[]` for every one of them, and the gate's 403 is the same either way.
86
+ */
87
+ export type CallerTokenRefusal =
88
+ | "absent"
89
+ | "malformed"
90
+ | "unknown_key"
91
+ | "signature"
92
+ | "audience"
93
+ | "expired"
94
+ | "lifetime";
95
+
96
+ /** What {@link verifyCallerToken} decided. */
97
+ export type CallerTokenVerdict =
98
+ | { trusted: true; claims: CallerTokenClaims }
99
+ | { trusted: false; reason: CallerTokenRefusal };
100
+
101
+ /** A key set in the shape `secretsStore(...).getVersions(name)` answers: version → key. */
102
+ export interface CallerTokenKeys {
103
+ versions: Record<string, string>;
104
+ }
105
+
106
+ const encoder = new TextEncoder();
107
+ const decoder = new TextDecoder();
108
+
109
+ /** The url alphabet, unpadded. Padding and the standard alphabet are refused, so a token has one spelling. */
110
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
111
+
112
+ function encodeSegment(bytes: Uint8Array): string {
113
+ let binary = "";
114
+ for (const byte of bytes) binary += String.fromCharCode(byte);
115
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
116
+ }
117
+
118
+ /** Decode one unpadded base64url segment, or `null` — strict, because every segment is attacker-supplied. */
119
+ function decodeSegment(segment: string): Uint8Array | null {
120
+ if (!BASE64URL.test(segment) || segment.length % 4 === 1) return null;
121
+ try {
122
+ const binary = atob(segment.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (segment.length % 4)) % 4));
123
+ const bytes = new Uint8Array(binary.length);
124
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
125
+ return bytes;
126
+ } catch {
127
+ return null;
128
+ }
129
+ }
130
+
131
+ /** Decode a JSON segment through its schema, or `null` for any failure at all. */
132
+ function decodeJson<T>(segment: string, schema: z.ZodType<T>): T | null {
133
+ const bytes = decodeSegment(segment);
134
+ if (bytes === null) return null;
135
+ let json: unknown;
136
+ try {
137
+ json = JSON.parse(decoder.decode(bytes));
138
+ } catch {
139
+ return null;
140
+ }
141
+ const parsed = schema.safeParse(json);
142
+ return parsed.success ? parsed.data : null;
143
+ }
144
+
145
+ /** The origin a URL names, or the string unchanged when it is not one — so it can only fail to match. */
146
+ function originOf(audience: string): string {
147
+ try {
148
+ return new URL(audience).origin;
149
+ } catch {
150
+ return audience;
151
+ }
152
+ }
153
+
154
+ function hmacKey(key: string, usage: "sign" | "verify"): Promise<CryptoKey> {
155
+ return crypto.subtle.importKey("raw", encoder.encode(key), { name: "HMAC", hash: "SHA-256" }, false, [usage]);
156
+ }
157
+
158
+ /** Refuse a lifetime outside `(0, MAX]` — a configuration error, raised loudly rather than clamped. */
159
+ function assertLifetime(seconds: number, what: string): void {
160
+ if (!Number.isInteger(seconds) || seconds <= 0 || seconds > MAX_CALLER_TOKEN_LIFETIME_SECONDS) {
161
+ throw new InternalError({
162
+ message: `A caller token's ${what} must be a whole number of seconds from 1 to ${MAX_CALLER_TOKEN_LIFETIME_SECONDS}.`,
163
+ action: `Use a lifetime of minutes, not hours — at most ${MAX_CALLER_TOKEN_LIFETIME_SECONDS} seconds.`,
164
+ detail: `got ${String(seconds)}`,
165
+ });
166
+ }
167
+ }
168
+
169
+ /** What {@link mintCallerToken} takes. */
170
+ export interface MintCallerTokenOptions {
171
+ /** The caller-token key, the same value the Worker's store holds under `auth-caller-token-key`. */
172
+ key: string;
173
+ /** The version the Worker's store holds it as. `"1"` for any value `pithy secrets create` or `update` wrote. */
174
+ kid: string;
175
+ /** Any URL on the Worker the token will be presented to. Reduced to its origin. */
176
+ audience: string;
177
+ /** Which backend is minting, for the receiving Worker's logs. Optional; it grants nothing. */
178
+ subject?: string;
179
+ /** How long it lives. Defaults to {@link DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS}; never more than the ceiling. */
180
+ lifetimeSeconds?: number;
181
+ /** The clock. Defaults to now. */
182
+ now?: Date;
183
+ }
184
+
185
+ /**
186
+ * Mint a caller token — on the **trusted backend**, never on a device.
187
+ *
188
+ * Mint one per call, or per few minutes, and present it on {@link CALLER_TOKEN_HEADER}. A backend that is
189
+ * another Worker in this project reads the key the way the verifier does, through `@pithy-sh/secrets`.
190
+ */
191
+ export async function mintCallerToken(options: MintCallerTokenOptions): Promise<string> {
192
+ const lifetime = options.lifetimeSeconds ?? DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS;
193
+ assertLifetime(lifetime, "lifetime");
194
+ const iat = Math.floor((options.now ?? new Date()).getTime() / 1000);
195
+ const header: CallerTokenHeader = { alg: "HS256", typ: "JWT", kid: options.kid };
196
+ const claims: CallerTokenClaims = {
197
+ aud: originOf(options.audience),
198
+ iat,
199
+ exp: iat + lifetime,
200
+ ...(options.subject === undefined ? {} : { sub: options.subject }),
201
+ };
202
+ const input = `${encodeSegment(encoder.encode(JSON.stringify(header)))}.${encodeSegment(encoder.encode(JSON.stringify(claims)))}`;
203
+ const signature = new Uint8Array(
204
+ await crypto.subtle.sign("HMAC", await hmacKey(options.key, "sign"), encoder.encode(input)),
205
+ );
206
+ return `${input}.${encodeSegment(signature)}`;
207
+ }
208
+
209
+ /** What {@link verifyCallerToken} takes. */
210
+ export interface VerifyCallerTokenOptions {
211
+ /** Every still-valid key version, as `getVersions` answers them. */
212
+ keys: CallerTokenKeys;
213
+ /**
214
+ * This Worker's own public origin — the `baseURL` handed to `auth()`. **Never** a value read off the
215
+ * request or the token: a verifier handed the caller's idea of the audience accepts every audience.
216
+ */
217
+ audience: string;
218
+ /** The clock. Defaults to now. */
219
+ now?: Date;
220
+ /** A tighter ceiling than {@link MAX_CALLER_TOKEN_LIFETIME_SECONDS}, for a verifier that wants one. */
221
+ maxLifetimeSeconds?: number;
222
+ }
223
+
224
+ /**
225
+ * Decide whether a caller token is one to trust, and why not when it is not.
226
+ *
227
+ * **In this order, and the order is the security model:** structure, then the key, then the signature,
228
+ * then the audience, then the lifetime, then expiry. Nothing about the claims is read as a fact until the
229
+ * signature has verified, so a forgery learns nothing from the answer about how far it got.
230
+ *
231
+ * Returns a verdict rather than throwing, so a resolver can answer `[]` and log the reason. It throws only
232
+ * for its own misconfiguration — a ceiling past the maximum — which `resolveScopes` turns into no scopes.
233
+ */
234
+ export async function verifyCallerToken(token: string, options: VerifyCallerTokenOptions): Promise<CallerTokenVerdict> {
235
+ const ceiling = options.maxLifetimeSeconds ?? MAX_CALLER_TOKEN_LIFETIME_SECONDS;
236
+ assertLifetime(ceiling, "lifetime ceiling");
237
+
238
+ const segments = token.split(".");
239
+ const [encodedHeader, encodedClaims, encodedSignature] = segments;
240
+ if (segments.length !== 3 || !encodedHeader || !encodedClaims || !encodedSignature) {
241
+ return { trusted: false, reason: "malformed" };
242
+ }
243
+ const header = decodeJson(encodedHeader, CallerTokenHeader);
244
+ const claims = decodeJson(encodedClaims, CallerTokenClaims);
245
+ const signature = decodeSegment(encodedSignature);
246
+ if (header === null || claims === null || signature === null) return { trusted: false, reason: "malformed" };
247
+
248
+ // An own property and a string, or nothing. A bracket lookup with `kid: "__proto__"` would otherwise
249
+ // reach up the prototype chain, hand `importKey` an object it coerces to a fixed string, and sign for it.
250
+ const versions = options.keys.versions;
251
+ const key = Object.hasOwn(versions, header.kid) ? versions[header.kid] : undefined;
252
+ if (typeof key !== "string") return { trusted: false, reason: "unknown_key" };
253
+
254
+ let verified: boolean;
255
+ try {
256
+ verified = await crypto.subtle.verify(
257
+ "HMAC",
258
+ await hmacKey(key, "verify"),
259
+ new Uint8Array(signature),
260
+ encoder.encode(`${encodedHeader}.${encodedClaims}`),
261
+ );
262
+ } catch {
263
+ verified = false;
264
+ }
265
+ if (!verified) return { trusted: false, reason: "signature" };
266
+
267
+ if (claims.aud !== originOf(options.audience)) return { trusted: false, reason: "audience" };
268
+
269
+ const now = Math.floor((options.now ?? new Date()).getTime() / 1000);
270
+ if (claims.exp - claims.iat > ceiling || claims.iat > now + CALLER_TOKEN_CLOCK_SKEW_SECONDS) {
271
+ return { trusted: false, reason: "lifetime" };
272
+ }
273
+ if (claims.exp <= now) return { trusted: false, reason: "expired" };
274
+
275
+ return { trusted: true, claims };
276
+ }
package/src/capability.ts CHANGED
@@ -2,13 +2,14 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
- import type { Capability, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
5
+ import type { Capability, PithyHonoEnv, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
6
6
  import { defineCapability } from "@pithy-sh/core/src/capability/capability";
7
7
  import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
8
8
  import type { EmailCapability } from "@pithy-sh/email/src/capability";
9
9
  import { isEmailCapability } from "@pithy-sh/email/src/capability";
10
10
  import { isTurnstileCapability } from "@pithy-sh/turnstile/src/capability";
11
11
  import { TURNSTILE_LOGIN_ACTION, type TurnstileMode } from "@pithy-sh/turnstile/src/config/config";
12
+ import type { Context } from "hono";
12
13
  import { z } from "zod";
13
14
  import type { AuthClientProjection } from "./client/projection";
14
15
  import { authTables } from "./data/tables";
@@ -20,7 +21,8 @@ import { createRateLimitMiddleware } from "./http/rateLimit";
20
21
  import { createAuthRoutes } from "./http/routes";
21
22
  import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
22
23
  import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins";
23
- import { authSecretsRegistry, inapplicableProviderSecrets } from "./instance/secrets";
24
+ import { authSecretsRegistryFor, inapplicableProviderSecrets } from "./instance/secrets";
25
+ import type { UserLifecycleHooks } from "./lifecycle/hooks";
24
26
  import { AUTH_MIGRATION_ORDER } from "./migrations/0001_init";
25
27
  import { authPluginPlan } from "./migrations/pluginTables";
26
28
  import { AUTH_MIGRATIONS } from "./migrations/set";
@@ -96,6 +98,9 @@ export const AuthConfig = z
96
98
  github: ProviderToggle.prefault({}).describe(
97
99
  "GitHub OAuth. Enable it, then store credentials as the `auth-github-credentials` secret. See docs/github-oauth.md.",
98
100
  ),
101
+ microsoft: ProviderToggle.prefault({}).describe(
102
+ "Microsoft sign-in — work, school, or personal accounts through Entra ID. Enable it, then store credentials and the tenant as the `auth-microsoft-credentials` secret. Entra ID cannot vouch for an email it did not verify, so an unverified one is verified by magic link before it links. See docs/microsoft-oauth.md.",
103
+ ),
99
104
  sessionExpiresIn: z
100
105
  .number()
101
106
  .int()
@@ -106,6 +111,14 @@ export const AuthConfig = z
106
111
  .int()
107
112
  .default(60 * 60 * 24)
108
113
  .describe("How often (seconds) an active session's expiry slides forward. Defaults to 1 day."),
114
+ sessionSecretRotateEveryDays: z
115
+ .number()
116
+ .int()
117
+ .positive()
118
+ .optional()
119
+ .describe(
120
+ "How often, in days, the secrets manager rotates `auth-session-secret` by itself. Unset by default, so nothing rotates it unattended. The previous version keeps verifying for the session lifetime, so nobody is signed out, and is retired once the JWKS keys sealed under it are re-encrypted. Must be longer than `sessionExpiresIn`.",
121
+ ),
109
122
  verificationExpiresIn: z
110
123
  .number()
111
124
  .int()
@@ -118,6 +131,41 @@ export const AuthConfig = z
118
131
  .describe(
119
132
  "When true, sign-in never provisions a new user — existing accounts only. Unknown emails get no email (anti-enumeration).",
120
133
  ),
134
+ retention: z
135
+ .object({
136
+ purgeAfterDays: z
137
+ .number()
138
+ .int()
139
+ .positive()
140
+ .default(30)
141
+ .describe(
142
+ "How many days a deleted account waits before its data is erased. Inside the window it cannot sign in and can be restored; after it, the purge erases its rows from every capability that holds them. Defaults to 30.",
143
+ ),
144
+ })
145
+ .prefault({})
146
+ .describe(
147
+ "How long a deleted account is kept before it is purged. Self-service deletion and an operator's soft deletion both use this window.",
148
+ ),
149
+ lifecycleEmails: z
150
+ .object({
151
+ accountSuspended: z
152
+ .boolean()
153
+ .default(true)
154
+ .describe("Email the person when their account is suspended, with the reason and any end date."),
155
+ accountReinstated: z.boolean().default(true).describe("Email the person when a suspension is lifted."),
156
+ deletionScheduled: z
157
+ .boolean()
158
+ .default(true)
159
+ .describe("Email the person when their account is deleted, with the date its data will be erased."),
160
+ deletionComplete: z
161
+ .boolean()
162
+ .default(true)
163
+ .describe("Email the person once their data has been erased. Sent before the address is."),
164
+ })
165
+ .prefault({})
166
+ .describe(
167
+ "Which account-lifecycle emails are sent. All four send by default, through `@pithy-sh/email`; switch one off by setting it to false.",
168
+ ),
121
169
  plugins: z
122
170
  .array(AuthPlugin)
123
171
  .default([])
@@ -149,8 +197,41 @@ export interface AuthWiring {
149
197
  * is the ordinary case and every harness that builds this shape by hand would otherwise have to say so.
150
198
  */
151
199
  onSessionRevoked?: SessionRevokedListener | undefined;
200
+ /**
201
+ * The adopter's scope resolver, or absent. See {@link AuthOptions.resolveScopes}.
202
+ *
203
+ * Optional on the wiring for the reason `onSessionRevoked` is: no resolver is the ordinary composition.
204
+ */
205
+ resolveScopes?: ScopeResolver | undefined;
206
+ /**
207
+ * The adopter's lifecycle hooks, or absent. See {@link UserLifecycleHooks}.
208
+ *
209
+ * Optional on the wiring for the reason `onSessionRevoked` is: no hook is the ordinary composition.
210
+ */
211
+ lifecycleHooks?: UserLifecycleHooks | undefined;
212
+ }
213
+
214
+ /** The session a {@link ScopeResolver} is asked about — the one Better Auth just resolved for this request. */
215
+ export interface ScopeResolverSession {
216
+ /** The signed-in user the session belongs to. */
217
+ userId: string;
218
+ /** The session this request presented. */
219
+ sessionId: string;
152
220
  }
153
221
 
222
+ /**
223
+ * Decide what this request's caller is, and answer the scopes that attests to (#560).
224
+ *
225
+ * Called by the session middleware on every authenticated request, after Better Auth has resolved the
226
+ * session and before any route runs. What it returns becomes `AuthContext.scopes`. It reads the **request**,
227
+ * which is where the proof is — a service binding the call arrived over, `request.cf.tlsClientAuth`, a
228
+ * short-lived token on its own header — and never anything the request merely claims about itself.
229
+ */
230
+ export type ScopeResolver = (
231
+ c: Context<PithyHonoEnv>,
232
+ session: ScopeResolverSession,
233
+ ) => readonly string[] | Promise<readonly string[]>;
234
+
154
235
  /**
155
236
  * Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
156
237
  *
@@ -169,43 +250,68 @@ export type SessionRevokedListener = (session: { id: string; userId: string }, d
169
250
  * `PaymentsOptions`: everything describable stays in {@link AuthConfig}, and a resolver is a sibling key
170
251
  * destructured off before the parse.
171
252
  */
172
- export type AuthOptions = AuthConfigInput & {
173
- /**
174
- * Resolve a GitHub identity yourself, replacing the kit's primary-only rule.
175
- *
176
- * The kit's default is deliberately conservative: it links on the **primary** address and nothing else,
177
- * because GitHub never re-verifies and a verified secondary can only speak to the past. An adopter who
178
- * wants a richer ladder — match a verified secondary, present a chooser on multiple matches — builds it
179
- * here. `getUserInfo` is the only hook in this flow running before both fetches and before
180
- * `mapProfileToUser`, and the only one holding the OAuth token.
181
- *
182
- * **Better Auth trusts what you return, verbatim.** It performs no independent check, so an
183
- * `emailVerified: true` you did not read from GitHub is an account takeover: an attacker adds a
184
- * victim's address to their own GitHub *unverified* and links to the victim's user. Return GitHub's
185
- * real per-address flag, always.
186
- */
187
- resolveGithubUserInfo?: GithubUserInfoResolver;
188
- /**
189
- * Told when a session is revoked, so state another capability keyed on it can go with it.
190
- *
191
- * **On the row, not on the sign-out route.** A sign-out, a revoke and an admin ending somebody's
192
- * devices all delete the same row, so a listener hung off one endpoint would miss the others.
193
- *
194
- * The case this exists for is `@pithy-sh/organization`: its acting selection is keyed by session id
195
- * and its schema says signing out must take it with it. Tenancy depends on auth and not the reverse,
196
- * so the composition holding both is what joins them, and this is the join.
197
- *
198
- * **Non-fatal by contract.** The session is already gone when this runs; a failure here must not turn
199
- * a completed sign-out into an error the caller retries, so the instance swallows what it throws.
200
- *
201
- * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
202
- */
203
- onSessionRevoked?: SessionRevokedListener;
204
- };
253
+ export type AuthOptions = AuthConfigInput &
254
+ UserLifecycleHooks & {
255
+ /**
256
+ * Resolve a GitHub identity yourself, replacing the kit's primary-only rule.
257
+ *
258
+ * The kit's default is deliberately conservative: it links on the **primary** address and nothing else,
259
+ * because GitHub never re-verifies and a verified secondary can only speak to the past. An adopter who
260
+ * wants a richer ladder — match a verified secondary, present a chooser on multiple matches — builds it
261
+ * here. `getUserInfo` is the only hook in this flow running before both fetches and before
262
+ * `mapProfileToUser`, and the only one holding the OAuth token.
263
+ *
264
+ * **Better Auth trusts what you return, verbatim.** It performs no independent check, so an
265
+ * `emailVerified: true` you did not read from GitHub is an account takeover: an attacker adds a
266
+ * victim's address to their own GitHub *unverified* and links to the victim's user. Return GitHub's
267
+ * real per-address flag, always.
268
+ */
269
+ resolveGithubUserInfo?: GithubUserInfoResolver;
270
+ /**
271
+ * Told when a session is revoked, so state another capability keyed on it can go with it.
272
+ *
273
+ * **On the row, not on the sign-out route.** A sign-out, a revoke and an admin ending somebody's
274
+ * devices all delete the same row, so a listener hung off one endpoint would miss the others.
275
+ *
276
+ * The case this exists for is `@pithy-sh/organization`: its acting selection is keyed by session id
277
+ * and its schema says signing out must take it with it. Tenancy depends on auth and not the reverse,
278
+ * so the composition holding both is what joins them, and this is the join.
279
+ *
280
+ * **Non-fatal by contract.** The session is already gone when this runs; a failure here must not turn
281
+ * a completed sign-out into an error the caller retries, so the instance swallows what it throws.
282
+ *
283
+ * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
284
+ */
285
+ onSessionRevoked?: SessionRevokedListener;
286
+ /**
287
+ * Decide, per request, what this request's caller is — and so which scope gates it opens (#560).
288
+ *
289
+ * `leaderboard:submit`, `rating:record`, `leaderboard:admin` and `ledger:admin` are **attestations about
290
+ * the caller, not permissions granted to the user**: each says *this write came from the adopter's own
291
+ * trusted backend, not from a device*. This is where that is decided, and the seam does not dictate how.
292
+ * A backend calling over a service binding, one presenting a client certificate, and one presenting a
293
+ * short-lived token all answer the same question here. `verifyCallerToken` and `readClientCertificate`
294
+ * are the kit's helpers for the last two; `docs/server-authoritative.md` ranks the three.
295
+ *
296
+ * **Resolved per request, never cached** — a cached scope is a revocation that has not taken effect.
297
+ * **Failure is closed and never fatal**: a resolver that throws, or answers anything but a list of
298
+ * strings, leaves the request with no scopes and logs at warn, and the request goes on to whatever gate
299
+ * it was headed for. **No default**: without one the array is empty and nothing extra runs, so composing
300
+ * this changes nothing until an adopter opts in.
301
+ *
302
+ * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
303
+ */
304
+ resolveScopes?: ScopeResolver;
305
+ };
205
306
 
206
307
  /** The auth capability, with its resolved config attached for inspection. */
207
308
  export interface AuthCapability extends Capability {
208
309
  authConfig: AuthConfig;
310
+ /**
311
+ * The adopter's account-lifecycle hooks, as `auth()` was handed them. Read by whatever runs a transition
312
+ * outside a request this capability serves — the purge Workflow (#622) fires `onUserPurged` through it.
313
+ */
314
+ lifecycleHooks: UserLifecycleHooks;
209
315
  /**
210
316
  * What a capability composed beside this one reads an account through — `matchmaking`, `support`,
211
317
  * `testers`. Found in their `compose` hooks, so none of them imports this package and a project without
@@ -256,8 +362,25 @@ export function auth(options: AuthOptions): AuthCapability {
256
362
  // Zod 4 objects strip unknown keys silently, so a `resolveGithubUserInfo` handed to `AuthConfig.parse`
257
363
  // would vanish with no error and the adopter's override would simply never run. `payments()` splits
258
364
  // its `resolveSubject` out for the same reason.
259
- const { resolveGithubUserInfo, onSessionRevoked, ...config } = options;
365
+ const {
366
+ resolveGithubUserInfo,
367
+ onSessionRevoked,
368
+ resolveScopes,
369
+ onUserSuspended,
370
+ onUserReinstated,
371
+ onUserDeleted,
372
+ onUserPurged,
373
+ ...config
374
+ } = options;
260
375
  const resolved = AuthConfig.parse(config);
376
+ // The lifecycle hooks, kept only where one was given, so an absent hook is an absent key rather than an
377
+ // `undefined` every reader has to tell apart from a hook.
378
+ const lifecycleHooks: UserLifecycleHooks = {
379
+ ...(onUserSuspended ? { onUserSuspended } : {}),
380
+ ...(onUserReinstated ? { onUserReinstated } : {}),
381
+ ...(onUserDeleted ? { onUserDeleted } : {}),
382
+ ...(onUserPurged ? { onUserPurged } : {}),
383
+ };
261
384
  // What may be composed, before anything is built from the list. The four the kit composes are the
262
385
  // sign-in this product promises and what the control-plane seam verifies against, so a list naming one
263
386
  // of them is refused here by name rather than silently redefining a route at request time — and so is a
@@ -273,6 +396,8 @@ export function auth(options: AuthOptions): AuthCapability {
273
396
  enqueueEmail: undefined,
274
397
  turnstile: undefined,
275
398
  onSessionRevoked,
399
+ resolveScopes,
400
+ lifecycleHooks,
276
401
  };
277
402
 
278
403
  // Tier-1 edge rate limiter, contributed as middleware so it runs before session resolution.
@@ -290,7 +415,12 @@ export function auth(options: AuthOptions): AuthCapability {
290
415
  package: PACKAGE_NAME,
291
416
  config: AuthConfig,
292
417
  dependsOn: ["secrets", "email"],
293
- secretRegistry: authSecretsRegistry,
418
+ // Whether anything will ever put a string in `AuthContext.scopes` — only when the adopter supplied a
419
+ // resolver. `pithy doctor` reads it against every composed capability's `scopeGates` (#560).
420
+ providesScopes: resolveScopes !== undefined,
421
+ // Built from the config, so the session secret's overlap is this composition's session lifetime and its
422
+ // period is the one the adopter asked for, if any (#602).
423
+ secretRegistry: authSecretsRegistryFor(resolved),
294
424
  // And which of those four credentials this composition cannot reach (#541). A provider that is off
295
425
  // has no code path that reads its pair, so `pithy doctor` listing it as outstanding re-raised a
296
426
  // settled question on every run. Declared rather than inferred: the config key and the secret name
@@ -375,6 +505,7 @@ export function auth(options: AuthOptions): AuthCapability {
375
505
  apple: resolved.apple.enabled,
376
506
  facebook: resolved.facebook.enabled,
377
507
  github: resolved.github.enabled,
508
+ microsoft: resolved.microsoft.enabled,
378
509
  },
379
510
  // Per provider, beside the global one. A project may let email create accounts while a provider
380
511
  // may not, and a screen with only `signUpEnabled` promises what that provider will refuse (#559).
@@ -383,6 +514,7 @@ export function auth(options: AuthOptions): AuthCapability {
383
514
  apple: resolved.apple.allowSignUp,
384
515
  facebook: resolved.facebook.allowSignUp,
385
516
  github: resolved.github.allowSignUp,
517
+ microsoft: resolved.microsoft.allowSignUp,
386
518
  },
387
519
  otpLength: resolved.otpLength,
388
520
  signUpEnabled: !resolved.disableSignUp,
@@ -409,7 +541,7 @@ export function auth(options: AuthOptions): AuthCapability {
409
541
  seeds: [authExampleSeed, authDevSessionSeed],
410
542
  });
411
543
 
412
- return Object.assign(capability, { authConfig: resolved, authPeer });
544
+ return Object.assign(capability, { authConfig: resolved, authPeer, lifecycleHooks });
413
545
  }
414
546
 
415
547
  /** Type guard: is this capability the auth capability? */
@@ -0,0 +1,27 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { KitErrorCode } from "@pithy-sh/core/src/error/payload";
5
+
6
+ /**
7
+ * The two codes a refused account comes back with, for a screen to branch on (#620).
8
+ *
9
+ * **Imported rather than spelled**, for the reason the sign-in screen imports `NEUTRAL_PROVIDER_REFUSAL`: a
10
+ * literal in a copied screen and a literal in the Worker are a pair that can drift, and the drift shows as a
11
+ * locked-out person landing on a sign-in form that says nothing. The type ties each to the kit's taxonomy, so
12
+ * a rename there is a compile error here.
13
+ *
14
+ * Either arrives as a `PithyError` body's `code` from a JSON call, or as `?error=` on the screen a magic link
15
+ * or a social sign-in returned to.
16
+ */
17
+ export const ACCOUNT_SUSPENDED = "auth/account_suspended" satisfies KitErrorCode;
18
+
19
+ /** The code for an account inside its purge window. See {@link ACCOUNT_SUSPENDED}. */
20
+ export const ACCOUNT_DELETED = "auth/account_deleted" satisfies KitErrorCode;
21
+
22
+ /** Which of the two a code is, or `null` for anything else — a refusal a screen should not reroute. */
23
+ export function accountRefusal(code: string | null | undefined): "suspended" | "deleted" | null {
24
+ if (code === ACCOUNT_SUSPENDED) return "suspended";
25
+ if (code === ACCOUNT_DELETED) return "deleted";
26
+ return null;
27
+ }
@@ -47,6 +47,8 @@ export type AuthClientProjection =
47
47
  facebook: boolean;
48
48
  /** Whether Sign in with GitHub is offered. */
49
49
  github: boolean;
50
+ /** Whether Sign in with Microsoft is offered. */
51
+ microsoft: boolean;
50
52
  };
51
53
  /**
52
54
  * Whether each offered provider may create an account, from its `allowSignUp` toggle.
@@ -69,6 +71,8 @@ export type AuthClientProjection =
69
71
  facebook: boolean;
70
72
  /** Whether a GitHub sign-in may create an account. */
71
73
  github: boolean;
74
+ /** Whether a Microsoft sign-in may create an account. */
75
+ microsoft: boolean;
72
76
  };
73
77
  /** How many digits an email OTP carries. */
74
78
  otpLength: number;