@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,207 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
4
+ import { z } from "zod";
5
+ //#region src/caller/token.ts
6
+ /**
7
+ * **A short-lived, audience-restricted caller token — the portable way to prove a request came from the
8
+ * adopter's own backend (#560).**
9
+ *
10
+ * `resolveScopes` asks one question: is this request's caller the adopter's trusted backend, or a device?
11
+ * Where that backend is a Worker, a service binding answers it with no credential at all, and where the
12
+ * zone can run mTLS a client certificate answers it at the edge. Neither works everywhere — a service
13
+ * binding needs both ends on Cloudflare, mTLS needs a proxied zone and an exact hostname, so not
14
+ * `workers.dev`. This is what works on day one anywhere, and it is shipped because the alternative every
15
+ * adopter otherwise reaches for is a long-lived shared secret compared in a header, which fails every
16
+ * control RFC 9700 names at once.
17
+ *
18
+ * So it holds to those controls, each on its own line below:
19
+ *
20
+ * - **Audience-restricted.** `aud` is the origin the token was minted for, and it verifies there and nowhere
21
+ * else — a staging token presented to production is refused, and so is one Worker's token replayed at
22
+ * another that happens to share the key.
23
+ * - **Short-lived.** Five minutes by default, and a ceiling of fifteen that no token and no configuration
24
+ * gets past. A token whose `exp` is a day after its `iat` is refused even when it is otherwise perfect,
25
+ * because honoring it would make it a shared secret with extra steps.
26
+ * - **Signed with a key the Worker reads from `@pithy-sh/secrets`.** The operator supplies it and the
27
+ * backend holds the same value. The `kid` names the stored version the token was signed with, and a kid
28
+ * the store does not hold is refused.
29
+ *
30
+ * What it is not is **sender-constrained**: a token lifted off the wire is usable by whoever lifted it, for
31
+ * the minutes it has left. RFC 9700 says a token SHOULD be bound to its sender, and the two answers are
32
+ * mTLS (`readClientCertificate`) and DPoP, which the kit does not ship yet. Short lifetime is what limits
33
+ * the damage here, which is why the ceiling is not negotiable.
34
+ *
35
+ * **HS256 and nothing else.** One algorithm, one key type, one token shape — the header is validated
36
+ * against a literal, so `alg: none` and an asymmetric algorithm are malformed rather than negotiated. No
37
+ * JWT library: the algorithm agility one brings is where the JWT vulnerabilities live.
38
+ */
39
+ /** The header a caller token travels on. Not `Authorization`, which carries the player's forwarded session. */
40
+ const CALLER_TOKEN_HEADER = "pithy-caller";
41
+ /** How long a minted token lives unless the minter asks for less: five minutes. */
42
+ const DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS = 300;
43
+ /**
44
+ * The longest a caller token may live, from its `iat` to its `exp` — fifteen minutes, minted or verified.
45
+ *
46
+ * A ceiling rather than a default, and it refuses above rather than clamping: a verifier configured past it
47
+ * is a configuration error, and a token claiming more is refused. Minutes because the token is a bearer
48
+ * credential with no sender binding, and its lifetime is the whole of what bounds a stolen one.
49
+ */
50
+ const MAX_CALLER_TOKEN_LIFETIME_SECONDS = 900;
51
+ /** How far in the future an `iat` may sit before the token is refused — clocks disagree by seconds, not minutes. */
52
+ const CALLER_TOKEN_CLOCK_SKEW_SECONDS = 30;
53
+ /** The protected header of a caller token. */
54
+ const CallerTokenHeader = z.object({
55
+ alg: z.literal("HS256").describe("The signature algorithm. HMAC-SHA-256, and nothing else is accepted."),
56
+ typ: z.literal("JWT").optional().describe("The media type, `JWT` when present."),
57
+ kid: z.string().min(1).describe("The version of the caller-token key this token was signed with.")
58
+ }).describe("The protected header of a caller token: HS256, and which key version signed it.");
59
+ /** The claims a caller token carries. */
60
+ const CallerTokenClaims = z.object({
61
+ aud: z.string().describe("The origin this token was minted for. It verifies at that origin and nowhere else."),
62
+ iat: z.number().int().describe("When it was minted, in Unix seconds."),
63
+ exp: z.number().int().describe("When it stops verifying, in Unix seconds. At most fifteen minutes after `iat`."),
64
+ sub: z.string().optional().describe("Which backend minted it, for the adopter's own logs. The verifier grants nothing on it.")
65
+ }).describe("The claims of a caller token: where it is valid, and for how long.");
66
+ const encoder = new TextEncoder();
67
+ const decoder = new TextDecoder();
68
+ /** The url alphabet, unpadded. Padding and the standard alphabet are refused, so a token has one spelling. */
69
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
70
+ function encodeSegment(bytes) {
71
+ let binary = "";
72
+ for (const byte of bytes) binary += String.fromCharCode(byte);
73
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
74
+ }
75
+ /** Decode one unpadded base64url segment, or `null` — strict, because every segment is attacker-supplied. */
76
+ function decodeSegment(segment) {
77
+ if (!BASE64URL.test(segment) || segment.length % 4 === 1) return null;
78
+ try {
79
+ const binary = atob(segment.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - segment.length % 4) % 4));
80
+ const bytes = new Uint8Array(binary.length);
81
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
82
+ return bytes;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+ /** Decode a JSON segment through its schema, or `null` for any failure at all. */
88
+ function decodeJson(segment, schema) {
89
+ const bytes = decodeSegment(segment);
90
+ if (bytes === null) return null;
91
+ let json;
92
+ try {
93
+ json = JSON.parse(decoder.decode(bytes));
94
+ } catch {
95
+ return null;
96
+ }
97
+ const parsed = schema.safeParse(json);
98
+ return parsed.success ? parsed.data : null;
99
+ }
100
+ /** The origin a URL names, or the string unchanged when it is not one — so it can only fail to match. */
101
+ function originOf(audience) {
102
+ try {
103
+ return new URL(audience).origin;
104
+ } catch {
105
+ return audience;
106
+ }
107
+ }
108
+ function hmacKey(key, usage) {
109
+ return crypto.subtle.importKey("raw", encoder.encode(key), {
110
+ name: "HMAC",
111
+ hash: "SHA-256"
112
+ }, false, [usage]);
113
+ }
114
+ /** Refuse a lifetime outside `(0, MAX]` — a configuration error, raised loudly rather than clamped. */
115
+ function assertLifetime(seconds, what) {
116
+ if (!Number.isInteger(seconds) || seconds <= 0 || seconds > 900) throw new InternalError({
117
+ message: `A caller token's ${what} must be a whole number of seconds from 1 to 900.`,
118
+ action: `Use a lifetime of minutes, not hours — at most 900 seconds.`,
119
+ detail: `got ${String(seconds)}`
120
+ });
121
+ }
122
+ /**
123
+ * Mint a caller token — on the **trusted backend**, never on a device.
124
+ *
125
+ * Mint one per call, or per few minutes, and present it on {@link CALLER_TOKEN_HEADER}. A backend that is
126
+ * another Worker in this project reads the key the way the verifier does, through `@pithy-sh/secrets`.
127
+ */
128
+ async function mintCallerToken(options) {
129
+ const lifetime = options.lifetimeSeconds ?? 300;
130
+ assertLifetime(lifetime, "lifetime");
131
+ const iat = Math.floor((options.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
132
+ const header = {
133
+ alg: "HS256",
134
+ typ: "JWT",
135
+ kid: options.kid
136
+ };
137
+ const claims = {
138
+ aud: originOf(options.audience),
139
+ iat,
140
+ exp: iat + lifetime,
141
+ ...options.subject === void 0 ? {} : { sub: options.subject }
142
+ };
143
+ const input = `${encodeSegment(encoder.encode(JSON.stringify(header)))}.${encodeSegment(encoder.encode(JSON.stringify(claims)))}`;
144
+ return `${input}.${encodeSegment(new Uint8Array(await crypto.subtle.sign("HMAC", await hmacKey(options.key, "sign"), encoder.encode(input))))}`;
145
+ }
146
+ /**
147
+ * Decide whether a caller token is one to trust, and why not when it is not.
148
+ *
149
+ * **In this order, and the order is the security model:** structure, then the key, then the signature,
150
+ * then the audience, then the lifetime, then expiry. Nothing about the claims is read as a fact until the
151
+ * signature has verified, so a forgery learns nothing from the answer about how far it got.
152
+ *
153
+ * Returns a verdict rather than throwing, so a resolver can answer `[]` and log the reason. It throws only
154
+ * for its own misconfiguration — a ceiling past the maximum — which `resolveScopes` turns into no scopes.
155
+ */
156
+ async function verifyCallerToken(token, options) {
157
+ const ceiling = options.maxLifetimeSeconds ?? 900;
158
+ assertLifetime(ceiling, "lifetime ceiling");
159
+ const segments = token.split(".");
160
+ const [encodedHeader, encodedClaims, encodedSignature] = segments;
161
+ if (segments.length !== 3 || !encodedHeader || !encodedClaims || !encodedSignature) return {
162
+ trusted: false,
163
+ reason: "malformed"
164
+ };
165
+ const header = decodeJson(encodedHeader, CallerTokenHeader);
166
+ const claims = decodeJson(encodedClaims, CallerTokenClaims);
167
+ const signature = decodeSegment(encodedSignature);
168
+ if (header === null || claims === null || signature === null) return {
169
+ trusted: false,
170
+ reason: "malformed"
171
+ };
172
+ const versions = options.keys.versions;
173
+ const key = Object.hasOwn(versions, header.kid) ? versions[header.kid] : void 0;
174
+ if (typeof key !== "string") return {
175
+ trusted: false,
176
+ reason: "unknown_key"
177
+ };
178
+ let verified;
179
+ try {
180
+ verified = await crypto.subtle.verify("HMAC", await hmacKey(key, "verify"), new Uint8Array(signature), encoder.encode(`${encodedHeader}.${encodedClaims}`));
181
+ } catch {
182
+ verified = false;
183
+ }
184
+ if (!verified) return {
185
+ trusted: false,
186
+ reason: "signature"
187
+ };
188
+ if (claims.aud !== originOf(options.audience)) return {
189
+ trusted: false,
190
+ reason: "audience"
191
+ };
192
+ const now = Math.floor((options.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
193
+ if (claims.exp - claims.iat > ceiling || claims.iat > now + 30) return {
194
+ trusted: false,
195
+ reason: "lifetime"
196
+ };
197
+ if (claims.exp <= now) return {
198
+ trusted: false,
199
+ reason: "expired"
200
+ };
201
+ return {
202
+ trusted: true,
203
+ claims
204
+ };
205
+ }
206
+ //#endregion
207
+ export { CALLER_TOKEN_CLOCK_SKEW_SECONDS, CALLER_TOKEN_HEADER, CallerTokenClaims, CallerTokenHeader, DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS, MAX_CALLER_TOKEN_LIFETIME_SECONDS, mintCallerToken, verifyCallerToken };
@@ -1,11 +1,13 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import type { D1Database } from "@cloudflare/workers-types";
4
- import type { Capability } from "@pithy-sh/core/src/capability/capability";
4
+ import type { Capability, PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
5
  import type { EmailCapability } from "@pithy-sh/email/src/capability";
6
6
  import { type TurnstileMode } from "@pithy-sh/turnstile/src/config/config";
7
+ import type { Context } from "hono";
7
8
  import { z } from "zod";
8
9
  import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
10
+ import type { UserLifecycleHooks } from "./lifecycle/hooks";
9
11
  import { type AuthPeer } from "./peer";
10
12
  /** The auth capability's configuration — the thin surface an adopter owns in `pithy.config.ts`. */
11
13
  export declare const AuthConfig: z.ZodObject<{
@@ -30,11 +32,25 @@ export declare const AuthConfig: z.ZodObject<{
30
32
  enabled: z.ZodDefault<z.ZodBoolean>;
31
33
  allowSignUp: z.ZodDefault<z.ZodBoolean>;
32
34
  }, z.core.$strip>>;
35
+ microsoft: z.ZodPrefault<z.ZodObject<{
36
+ enabled: z.ZodDefault<z.ZodBoolean>;
37
+ allowSignUp: z.ZodDefault<z.ZodBoolean>;
38
+ }, z.core.$strip>>;
33
39
  sessionExpiresIn: z.ZodDefault<z.ZodNumber>;
34
40
  sessionUpdateAge: z.ZodDefault<z.ZodNumber>;
41
+ sessionSecretRotateEveryDays: z.ZodOptional<z.ZodNumber>;
35
42
  verificationExpiresIn: z.ZodDefault<z.ZodNumber>;
36
43
  otpLength: z.ZodDefault<z.ZodNumber>;
37
44
  disableSignUp: z.ZodDefault<z.ZodBoolean>;
45
+ retention: z.ZodPrefault<z.ZodObject<{
46
+ purgeAfterDays: z.ZodDefault<z.ZodNumber>;
47
+ }, z.core.$strip>>;
48
+ lifecycleEmails: z.ZodPrefault<z.ZodObject<{
49
+ accountSuspended: z.ZodDefault<z.ZodBoolean>;
50
+ accountReinstated: z.ZodDefault<z.ZodBoolean>;
51
+ deletionScheduled: z.ZodDefault<z.ZodBoolean>;
52
+ deletionComplete: z.ZodDefault<z.ZodBoolean>;
53
+ }, z.core.$strip>>;
38
54
  plugins: z.ZodDefault<z.ZodArray<z.ZodCustom<import("better-auth").BetterAuthPlugin, import("better-auth").BetterAuthPlugin>>>;
39
55
  }, z.core.$strip>;
40
56
  export type AuthConfig = z.output<typeof AuthConfig>;
@@ -61,7 +77,35 @@ export interface AuthWiring {
61
77
  * is the ordinary case and every harness that builds this shape by hand would otherwise have to say so.
62
78
  */
63
79
  onSessionRevoked?: SessionRevokedListener | undefined;
80
+ /**
81
+ * The adopter's scope resolver, or absent. See {@link AuthOptions.resolveScopes}.
82
+ *
83
+ * Optional on the wiring for the reason `onSessionRevoked` is: no resolver is the ordinary composition.
84
+ */
85
+ resolveScopes?: ScopeResolver | undefined;
86
+ /**
87
+ * The adopter's lifecycle hooks, or absent. See {@link UserLifecycleHooks}.
88
+ *
89
+ * Optional on the wiring for the reason `onSessionRevoked` is: no hook is the ordinary composition.
90
+ */
91
+ lifecycleHooks?: UserLifecycleHooks | undefined;
92
+ }
93
+ /** The session a {@link ScopeResolver} is asked about — the one Better Auth just resolved for this request. */
94
+ export interface ScopeResolverSession {
95
+ /** The signed-in user the session belongs to. */
96
+ userId: string;
97
+ /** The session this request presented. */
98
+ sessionId: string;
64
99
  }
100
+ /**
101
+ * Decide what this request's caller is, and answer the scopes that attests to (#560).
102
+ *
103
+ * Called by the session middleware on every authenticated request, after Better Auth has resolved the
104
+ * session and before any route runs. What it returns becomes `AuthContext.scopes`. It reads the **request**,
105
+ * which is where the proof is — a service binding the call arrived over, `request.cf.tlsClientAuth`, a
106
+ * short-lived token on its own header — and never anything the request merely claims about itself.
107
+ */
108
+ export type ScopeResolver = (c: Context<PithyHonoEnv>, session: ScopeResolverSession) => readonly string[] | Promise<readonly string[]>;
65
109
  /**
66
110
  * Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
67
111
  *
@@ -82,7 +126,7 @@ export type SessionRevokedListener = (session: {
82
126
  * `PaymentsOptions`: everything describable stays in {@link AuthConfig}, and a resolver is a sibling key
83
127
  * destructured off before the parse.
84
128
  */
85
- export type AuthOptions = AuthConfigInput & {
129
+ export type AuthOptions = AuthConfigInput & UserLifecycleHooks & {
86
130
  /**
87
131
  * Resolve a GitHub identity yourself, replacing the kit's primary-only rule.
88
132
  *
@@ -114,10 +158,34 @@ export type AuthOptions = AuthConfigInput & {
114
158
  * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
115
159
  */
116
160
  onSessionRevoked?: SessionRevokedListener;
161
+ /**
162
+ * Decide, per request, what this request's caller is — and so which scope gates it opens (#560).
163
+ *
164
+ * `leaderboard:submit`, `rating:record`, `leaderboard:admin` and `ledger:admin` are **attestations about
165
+ * the caller, not permissions granted to the user**: each says *this write came from the adopter's own
166
+ * trusted backend, not from a device*. This is where that is decided, and the seam does not dictate how.
167
+ * A backend calling over a service binding, one presenting a client certificate, and one presenting a
168
+ * short-lived token all answer the same question here. `verifyCallerToken` and `readClientCertificate`
169
+ * are the kit's helpers for the last two; `docs/server-authoritative.md` ranks the three.
170
+ *
171
+ * **Resolved per request, never cached** — a cached scope is a revocation that has not taken effect.
172
+ * **Failure is closed and never fatal**: a resolver that throws, or answers anything but a list of
173
+ * strings, leaves the request with no scopes and logs at warn, and the request goes on to whatever gate
174
+ * it was headed for. **No default**: without one the array is empty and nothing extra runs, so composing
175
+ * this changes nothing until an adopter opts in.
176
+ *
177
+ * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
178
+ */
179
+ resolveScopes?: ScopeResolver;
117
180
  };
118
181
  /** The auth capability, with its resolved config attached for inspection. */
119
182
  export interface AuthCapability extends Capability {
120
183
  authConfig: AuthConfig;
184
+ /**
185
+ * The adopter's account-lifecycle hooks, as `auth()` was handed them. Read by whatever runs a transition
186
+ * outside a request this capability serves — the purge Workflow (#622) fires `onUserPurged` through it.
187
+ */
188
+ lifecycleHooks: UserLifecycleHooks;
121
189
  /**
122
190
  * What a capability composed beside this one reads an account through — `matchmaking`, `support`,
123
191
  * `testers`. Found in their `compose` hooks, so none of them imports this package and a project without
@@ -1 +1 @@
1
- {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2B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,CAAC;IAC/C;;;;;;;;;;;;;;OAcG;IACH,gBAAgB,CAAC,EAAE,sBAAsB,CAAC;IAC1C;;;;;;;;;;;;;;;;;OAiBG;IACH,aAAa,CAAC,EAAE,aAAa,CAAC;CAC/B,CAAC;AAEJ,6EAA6E;AAC7E,MAAM,WAAW,cAAe,SAAQ,UAAU;IAChD,UAAU,EAAE,UAAU,CAAC;IACvB;;;OAGG;IACH,cAAc,EAAE,kBAAkB,CAAC;IACnC;;;;OAIG;IACH,QAAQ,EAAE,QAAQ,CAAC;CACpB;AAiCD;;;;;GAKG;AACH,wBAAgB,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG,cAAc,CAyLzD;AAED,0DAA0D;AAC1D,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,IAAI,cAAc,CAErF"}
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { authTables } from "./data/tables.js";
4
4
  import { publishSameOrigin } from "./http/csrf.js";
5
- import { authSecretsRegistry, inapplicableProviderSecrets } from "./instance/secrets.js";
5
+ import { authSecretsRegistryFor, inapplicableProviderSecrets } from "./instance/secrets.js";
6
6
  import { authDevSessionSeed } from "./seeds/devSession.js";
7
7
  import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins.js";
8
8
  import { registerDevLoginRoute } from "./http/devLoginRoute.js";
@@ -48,11 +48,20 @@ const AuthConfig = z.object({
48
48
  apple: ProviderToggle.prefault({}).describe("Apple Sign-In. Enable it, then store credentials as the `auth-apple-credentials` secret. See docs/apple-signin.md."),
49
49
  facebook: ProviderToggle.prefault({}).describe("Facebook Login. Enable it, then store credentials as the `auth-facebook-credentials` secret. See docs/facebook-oauth.md."),
50
50
  github: ProviderToggle.prefault({}).describe("GitHub OAuth. Enable it, then store credentials as the `auth-github-credentials` secret. See docs/github-oauth.md."),
51
+ microsoft: ProviderToggle.prefault({}).describe("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."),
51
52
  sessionExpiresIn: z.number().int().default(604800).describe("Session (refresh credential) lifetime in seconds. Defaults to 7 days. Expiry slides forward on use."),
52
53
  sessionUpdateAge: z.number().int().default(86400).describe("How often (seconds) an active session's expiry slides forward. Defaults to 1 day."),
54
+ sessionSecretRotateEveryDays: z.number().int().positive().optional().describe("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`."),
53
55
  verificationExpiresIn: z.number().int().default(300).describe("Magic-link and OTP lifetime in seconds. Defaults to 5 minutes. Single-use regardless."),
54
56
  otpLength: z.number().int().default(6).describe("The number of digits in an email OTP. Defaults to 6."),
55
57
  disableSignUp: z.boolean().default(false).describe("When true, sign-in never provisions a new user — existing accounts only. Unknown emails get no email (anti-enumeration)."),
58
+ retention: z.object({ purgeAfterDays: z.number().int().positive().default(30).describe("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.") }).prefault({}).describe("How long a deleted account is kept before it is purged. Self-service deletion and an operator's soft deletion both use this window."),
59
+ lifecycleEmails: z.object({
60
+ accountSuspended: z.boolean().default(true).describe("Email the person when their account is suspended, with the reason and any end date."),
61
+ accountReinstated: z.boolean().default(true).describe("Email the person when a suspension is lifted."),
62
+ deletionScheduled: z.boolean().default(true).describe("Email the person when their account is deleted, with the date its data will be erased."),
63
+ deletionComplete: z.boolean().default(true).describe("Email the person once their data has been erased. Sent before the address is.")
64
+ }).prefault({}).describe("Which account-lifecycle emails are sent. All four send by default, through `@pithy-sh/email`; switch one off by setting it to false."),
56
65
  plugins: z.array(AuthPlugin).default([]).describe("Additional Better Auth plugins to compose — `organization()`, `passkey()`, `twoFactor()`, `apiKey()`, a generic OAuth provider. Additive: they join the set the kit composes (i18n, bearer, jwt, magic-link, email-otp) and cannot replace one. Tables a plugin declares are created by `pithy migrate`; add the matching client plugin to `createAuthClient` for its typed client surface.")
57
66
  }).describe("Configuration for the auth capability.");
58
67
  /**
@@ -86,8 +95,14 @@ function assertPluginTablesUnclaimed(capabilities, binding, extensions) {
86
95
  * and emits `auth/*` through `audit` when those are composed.
87
96
  */
88
97
  function auth(options) {
89
- const { resolveGithubUserInfo, onSessionRevoked, ...config } = options;
98
+ const { resolveGithubUserInfo, onSessionRevoked, resolveScopes, onUserSuspended, onUserReinstated, onUserDeleted, onUserPurged, ...config } = options;
90
99
  const resolved = AuthConfig.parse(config);
100
+ const lifecycleHooks = {
101
+ ...onUserSuspended ? { onUserSuspended } : {},
102
+ ...onUserReinstated ? { onUserReinstated } : {},
103
+ ...onUserDeleted ? { onUserDeleted } : {},
104
+ ...onUserPurged ? { onUserPurged } : {}
105
+ };
91
106
  assertAdditivePlugins(resolved.plugins);
92
107
  const pluginPlan = authPluginPlan(resolved.plugins);
93
108
  const wiring = {
@@ -95,7 +110,9 @@ function auth(options) {
95
110
  resolveGithubUserInfo,
96
111
  enqueueEmail: void 0,
97
112
  turnstile: void 0,
98
- onSessionRevoked
113
+ onSessionRevoked,
114
+ resolveScopes,
115
+ lifecycleHooks
99
116
  };
100
117
  const rateLimitMiddleware = (app) => {
101
118
  app.use(`${resolved.basePath}/*`, createRateLimitMiddleware(resolved.rateLimiterBinding));
@@ -106,7 +123,8 @@ function auth(options) {
106
123
  package: PACKAGE_NAME,
107
124
  config: AuthConfig,
108
125
  dependsOn: ["secrets", "email"],
109
- secretRegistry: authSecretsRegistry,
126
+ providesScopes: resolveScopes !== void 0,
127
+ secretRegistry: authSecretsRegistryFor(resolved),
110
128
  inapplicableSecrets: inapplicableProviderSecrets(resolved),
111
129
  requiredBindings: [{
112
130
  type: "d1",
@@ -163,13 +181,15 @@ function auth(options) {
163
181
  google: resolved.google.enabled,
164
182
  apple: resolved.apple.enabled,
165
183
  facebook: resolved.facebook.enabled,
166
- github: resolved.github.enabled
184
+ github: resolved.github.enabled,
185
+ microsoft: resolved.microsoft.enabled
167
186
  },
168
187
  providerSignUp: {
169
188
  google: resolved.google.allowSignUp,
170
189
  apple: resolved.apple.allowSignUp,
171
190
  facebook: resolved.facebook.allowSignUp,
172
- github: resolved.github.allowSignUp
191
+ github: resolved.github.allowSignUp,
192
+ microsoft: resolved.microsoft.allowSignUp
173
193
  },
174
194
  otpLength: resolved.otpLength,
175
195
  signUpEnabled: !resolved.disableSignUp
@@ -188,7 +208,8 @@ function auth(options) {
188
208
  });
189
209
  return Object.assign(capability, {
190
210
  authConfig: resolved,
191
- authPeer
211
+ authPeer,
212
+ lifecycleHooks
192
213
  });
193
214
  }
194
215
  /** Type guard: is this capability the auth capability? */
@@ -0,0 +1,19 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * The two codes a refused account comes back with, for a screen to branch on (#620).
5
+ *
6
+ * **Imported rather than spelled**, for the reason the sign-in screen imports `NEUTRAL_PROVIDER_REFUSAL`: a
7
+ * literal in a copied screen and a literal in the Worker are a pair that can drift, and the drift shows as a
8
+ * locked-out person landing on a sign-in form that says nothing. The type ties each to the kit's taxonomy, so
9
+ * a rename there is a compile error here.
10
+ *
11
+ * Either arrives as a `PithyError` body's `code` from a JSON call, or as `?error=` on the screen a magic link
12
+ * or a social sign-in returned to.
13
+ */
14
+ export declare const ACCOUNT_SUSPENDED = "auth/account_suspended";
15
+ /** The code for an account inside its purge window. See {@link ACCOUNT_SUSPENDED}. */
16
+ export declare const ACCOUNT_DELETED = "auth/account_deleted";
17
+ /** Which of the two a code is, or `null` for anything else — a refusal a screen should not reroute. */
18
+ export declare function accountRefusal(code: string | null | undefined): "suspended" | "deleted" | null;
19
+ //# sourceMappingURL=lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle.d.ts","sourceRoot":"","sources":["../../src/client/lifecycle.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,2BAAkD,CAAC;AAEjF,sFAAsF;AACtF,eAAO,MAAM,eAAe,yBAAgD,CAAC;AAE7E,uGAAuG;AACvG,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,WAAW,GAAG,SAAS,GAAG,IAAI,CAI9F"}
@@ -0,0 +1,25 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/client/lifecycle.ts
4
+ /**
5
+ * The two codes a refused account comes back with, for a screen to branch on (#620).
6
+ *
7
+ * **Imported rather than spelled**, for the reason the sign-in screen imports `NEUTRAL_PROVIDER_REFUSAL`: a
8
+ * literal in a copied screen and a literal in the Worker are a pair that can drift, and the drift shows as a
9
+ * locked-out person landing on a sign-in form that says nothing. The type ties each to the kit's taxonomy, so
10
+ * a rename there is a compile error here.
11
+ *
12
+ * Either arrives as a `PithyError` body's `code` from a JSON call, or as `?error=` on the screen a magic link
13
+ * or a social sign-in returned to.
14
+ */
15
+ const ACCOUNT_SUSPENDED = "auth/account_suspended";
16
+ /** The code for an account inside its purge window. See {@link ACCOUNT_SUSPENDED}. */
17
+ const ACCOUNT_DELETED = "auth/account_deleted";
18
+ /** Which of the two a code is, or `null` for anything else — a refusal a screen should not reroute. */
19
+ function accountRefusal(code) {
20
+ if (code === "auth/account_suspended") return "suspended";
21
+ if (code === "auth/account_deleted") return "deleted";
22
+ return null;
23
+ }
24
+ //#endregion
25
+ export { ACCOUNT_DELETED, ACCOUNT_SUSPENDED, accountRefusal };
@@ -44,6 +44,8 @@ export type AuthClientProjection = {
44
44
  facebook: boolean;
45
45
  /** Whether Sign in with GitHub is offered. */
46
46
  github: boolean;
47
+ /** Whether Sign in with Microsoft is offered. */
48
+ microsoft: boolean;
47
49
  };
48
50
  /**
49
51
  * Whether each offered provider may create an account, from its `allowSignUp` toggle.
@@ -66,6 +68,8 @@ export type AuthClientProjection = {
66
68
  facebook: boolean;
67
69
  /** Whether a GitHub sign-in may create an account. */
68
70
  github: boolean;
71
+ /** Whether a Microsoft sign-in may create an account. */
72
+ microsoft: boolean;
69
73
  };
70
74
  /** How many digits an email OTP carries. */
71
75
  otpLength: number;
@@ -1 +1 @@
1
- {"version":3,"file":"projection.d.ts","sourceRoot":"","sources":["../../src/client/projection.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,oBAAoB,GAC5B;IACE,mGAAmG;IACnG,OAAO,EAAE,KAAK,CAAC;CAChB,GACD;IACE,uCAAuC;IACvC,OAAO,EAAE,IAAI,CAAC;IACd,4DAA4D;IAC5D,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;;;;OAOG;IACH,SAAS,EAAE;QACT,8CAA8C;QAC9C,MAAM,EAAE,OAAO,CAAC;QAChB,6CAA6C;QAC7C,KAAK,EAAE,OAAO,CAAC;QACf,gDAAgD;QAChD,QAAQ,EAAE,OAAO,CAAC;QAClB,8CAA8C;QAC9C,MAAM,EAAE,OAAO,CAAC;KACjB,CAAC;IACF;;;;;;;;;;;OAWG;IACH,cAAc,CAAC,EAAE;QACf,sDAAsD;QACtD,MAAM,EAAE,OAAO,CAAC;QAChB,sDAAsD;QACtD,KAAK,EAAE,OAAO,CAAC;QACf,wDAAwD;QACxD,QAAQ,EAAE,OAAO,CAAC;QAClB,sDAAsD;QACtD,MAAM,EAAE,OAAO,CAAC;KACjB,CAAC;IACF,4CAA4C;IAC5C,SAAS,EAAE,MAAM,CAAC;IAClB,4EAA4E;IAC5E,aAAa,EAAE,OAAO,CAAC;CACxB,CAAC"}
1
+ {"version":3,"file":"projection.d.ts","sourceRoot":"","sources":["../../src/client/projection.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,oBAAoB,GAC5B;IACE,mGAAmG;IACnG,OAAO,EAAE,KAAK,CAAC;CAChB,GACD;IACE,uCAAuC;IACvC,OAAO,EAAE,IAAI,CAAC;IACd,4DAA4D;IAC5D,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;;;;OAOG;IACH,SAAS,EAAE;QACT,8CAA8C;QAC9C,MAAM,EAAE,OAAO,CAAC;QAChB,6CAA6C;QAC7C,KAAK,EAAE,OAAO,CAAC;QACf,gDAAgD;QAChD,QAAQ,EAAE,OAAO,CAAC;QAClB,8CAA8C;QAC9C,MAAM,EAAE,OAAO,CAAC;QAChB,iDAAiD;QACjD,SAAS,EAAE,OAAO,CAAC;KACpB,CAAC;IACF;;;;;;;;;;;OAWG;IACH,cAAc,CAAC,EAAE;QACf,sDAAsD;QACtD,MAAM,EAAE,OAAO,CAAC;QAChB,sDAAsD;QACtD,KAAK,EAAE,OAAO,CAAC;QACf,wDAAwD;QACxD,QAAQ,EAAE,OAAO,CAAC;QAClB,sDAAsD;QACtD,MAAM,EAAE,OAAO,CAAC;QAChB,yDAAyD;QACzD,SAAS,EAAE,OAAO,CAAC;KACpB,CAAC;IACF,4CAA4C;IAC5C,SAAS,EAAE,MAAM,CAAC;IAClB,4EAA4E;IAC5E,aAAa,EAAE,OAAO,CAAC;CACxB,CAAC"}
@@ -11,6 +11,10 @@ export declare const User: z.ZodObject<{
11
11
  locale: z.ZodNullable<z.ZodString>;
12
12
  createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
13
13
  updatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
14
+ suspendedAt: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
15
+ suspendedUntil: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
16
+ deletedAt: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
17
+ purgeAfter: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
14
18
  }, z.core.$strip>;
15
19
  export type User = z.output<typeof User>;
16
20
  /** `pithy_auth_sessions` — one active session (the long-lived, bearer/cookie credential). */
@@ -31,7 +35,7 @@ export type Session = z.output<typeof Session>;
31
35
  /** `pithy_auth_accounts` — a credential/identity link for a user (one row per social provider). */
32
36
  export declare const Account: z.ZodObject<{
33
37
  id: z.ZodString;
34
- issuer: z.ZodString;
38
+ issuer: z.ZodNullable<z.ZodString>;
35
39
  accountId: z.ZodString;
36
40
  providerId: z.ZodString;
37
41
  userId: z.ZodString;
@@ -1 +1 @@
1
- {"version":3,"file":"betterAuth.d.ts","sourceRoot":"","sources":["../../src/data/betterAuth.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAuBxB,2FAA2F;AAC3F,eAAO,MAAM,IAAI;;;;;;;;;iBA0BwF,CAAC;AAC1G,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;AAEzC,6FAA6F;AAC7F,eAAO,MAAM,OAAO;;;;;;;;;;;;iBAqCqF,CAAC;AAC1G,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,OAAO,CAAC,CAAC;AAE/C,mGAAmG;AACnG,eAAO,MAAM,OAAO;;;;;;;;;;;;;;;iBAyCqF,CAAC;AAC1G,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,OAAO,CAAC,CAAC;AAE/C,8FAA8F;AAC9F,eAAO,MAAM,YAAY;;;;;;;iBAmBtB,CAAC;AACJ,MAAM,MAAM,YAAY,GAAG,CA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;;iBAcnB,CAAC;AACJ,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC"}
@@ -1,7 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { z } from "zod";
4
- import { JsonDate, SQLiteBoolean } from "@pithy-sh/core/src/data/codecs";
4
+ import { JsonDate, SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
5
  import { Locale } from "@pithy-sh/core/src/i18n/locale";
6
6
  //#region src/data/betterAuth.ts
7
7
  /**
@@ -32,7 +32,11 @@ const User = z.object({
32
32
  image: z.string().nullable().describe("The user's picture: a URL on the provider that signed them in, or bytes this application stores as a bounded `data:` URL — see `../profile/profile.ts` for why the column takes two shapes. Null when nobody has set one, and then a caller draws initials, which is a real answer and not a placeholder.\n\n**Permissive here and strict on the write, exactly as `name` is, and the asymmetry is the point.** `UserImage` runs at the database hook, so nothing this kit writes can put an unacceptable value in the column. What this schema decodes is what is *already there* — a row a provider wrote before the rule existed, a repair script, a restored backup. A strict column turns one such row into a `ZodError` on every read that touches it, and `getUsers` parses a page of rows at once: one poisoned row would take down the whole roster for every operator rather than drawing one gap. That is the failure mode `./kitFields.ts` records for `locale`, and it is worse here, because a roster is read by people who did not write the row.\n\nThe value is made safe on the way **out** instead. `userImageSource` answers null for anything the rule does not recognize, so an unrecognized value renders as initials; and the serving route refuses to hand out bytes it cannot type."),
33
33
  locale: Locale.nullable().describe("The reader's chosen language as a BCP-47 tag, or null when they have never chosen. Null is not the default locale: it means negotiate from `Accept-Language`, so an unchosen reader follows their device. A stored tag outranks the header."),
34
34
  createdAt: BetterAuthDate.describe("When the user record was created. ISO-8601 text in SQLite; a `Date` in app code."),
35
- updatedAt: BetterAuthDate.describe("When the user record was last updated. ISO-8601 text in SQLite; a `Date` in app code.")
35
+ updatedAt: BetterAuthDate.describe("When the user record was last updated. ISO-8601 text in SQLite; a `Date` in app code."),
36
+ suspendedAt: SQLiteDate.nullish().describe("When this account was suspended, or null when it is not. A suspended account cannot sign in, refresh a token, or act on any route. Ms-epoch in SQLite; a `Date` in app code."),
37
+ suspendedUntil: SQLiteDate.nullish().describe("When the current suspension ends by itself, or null for one that lasts until an operator reinstates the account. A suspension past this instant is treated as absent, with no write needed to expire it. Ms-epoch in SQLite."),
38
+ deletedAt: SQLiteDate.nullish().describe("When this account was deleted, or null when it is not. A deleted account cannot sign in or act, and can be restored until `purgeAfter`. Ms-epoch in SQLite."),
39
+ purgeAfter: SQLiteDate.nullish().describe("When a deleted account's data may be erased — the deletion instant plus `retention.purgeAfterDays`. Null unless the account is deleted. Ms-epoch in SQLite.")
36
40
  }).describe("A user in `pithy_auth_users` — the canonical identity every session and account hangs off.");
37
41
  /** `pithy_auth_sessions` — one active session (the long-lived, bearer/cookie credential). */
38
42
  const Session = z.object({
@@ -51,7 +55,7 @@ const Session = z.object({
51
55
  /** `pithy_auth_accounts` — a credential/identity link for a user (one row per social provider). */
52
56
  const Account = z.object({
53
57
  id: z.string().describe("Primary key. A random/UUID text id."),
54
- issuer: z.string().describe("Who asserted this identity, as the identity provider names itself: an OIDC issuer URL (`https://accounts.google.com`), `local:oauth:<id>` for an OAuth provider that publishes none, or `local:credential` for a password. With `accountId` it is the account's identity and carries a unique index — a provider slug is a name this project chose, so two providers pointed at one directory could assert the same `accountId` and land on two rows."),
58
+ issuer: z.string().nullable().describe("A relic of Better Auth 1.7.0–1.7.2, which identified an account by `(issuer, accountId)` and wrote who asserted the identity here: an OIDC issuer URL, `local:oauth:<id>`, or `local:credential`. 1.7.3 went back to `(providerId, accountId)` and writes nothing here, so a row created since is null. Kept, with the values a Worker migrated under 1.7.1 holds, and read by nothing (#787)."),
55
59
  accountId: z.string().describe("The provider's stable id for this user (e.g. the Google `sub` claim)."),
56
60
  providerId: z.string().describe("The provider slug, e.g. `google`. Identifies which OAuth/credential provider this row links."),
57
61
  userId: z.string().describe("The owning user's id. Foreign key to `pithy_auth_users(id)`, ON DELETE CASCADE."),
@@ -1,30 +1,5 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- /**
4
- * The columns Pithy adds to Better Auth's own tables, declared **once**.
5
- *
6
- * Better Auth owns every read and write to `pithy_auth_users` and `pithy_auth_sessions` through its
7
- * Kysely adapter, and it writes only the fields its options declare. So a column that exists in the
8
- * migration and in the `User` Zod object and *not* here is null forever and absent from every user
9
- * object the instance returns — a migration and a schema field that silently did nothing.
10
- *
11
- * ## Why one module rather than two agreeing declarations
12
- *
13
- * These have to appear in two places: `makeAuth`'s live options (`../instance/auth.ts`) and the
14
- * schema baseline `pluginSchemaDelta` subtracts each adopter plugin's schema from
15
- * (`../migrations/pluginTables.ts`). Both were written out by hand, with a comment in each saying it
16
- * "must match" the other and a test claiming to hold them together. The test did not: it compared the
17
- * baseline against the `User` schema and never imported `makeAuth` at all, so reverting the live
18
- * declaration left the whole suite green while Better Auth silently stopped writing the column (#441).
19
- *
20
- * `docs/CONVENTIONS.md` is explicit that removing an invariant beats watching it. There is one object
21
- * now, imported by both, and the two cannot disagree because there is no second thing to disagree
22
- * with. That is also why the consequence is worth restating rather than diluting: leave a kit column
23
- * out of the baseline and `pluginSchemaDelta` reports it as something an adopter's plugin brought, so
24
- * a plugin that also declares a user `locale` emits `ALTER TABLE … ADD COLUMN locale` against a table
25
- * that already has one — a duplicate-column failure part-way through a migration D1 cannot roll back,
26
- * because it has no transactional DDL.
27
- */
28
3
  /**
29
4
  * The extra `pithy_auth_users` columns.
30
5
  *
@@ -49,6 +24,26 @@
49
24
  * `updateUser({ locale: null })` answering 400 for the one state the schema calls ordinary.
50
25
  */
51
26
  export declare const KIT_USER_FIELDS: {
27
+ readonly suspendedAt: {
28
+ readonly type: "number";
29
+ readonly required: false;
30
+ readonly input: false;
31
+ };
32
+ readonly suspendedUntil: {
33
+ readonly type: "number";
34
+ readonly required: false;
35
+ readonly input: false;
36
+ };
37
+ readonly deletedAt: {
38
+ readonly type: "number";
39
+ readonly required: false;
40
+ readonly input: false;
41
+ };
42
+ readonly purgeAfter: {
43
+ readonly type: "number";
44
+ readonly required: false;
45
+ readonly input: false;
46
+ };
52
47
  readonly locale: {
53
48
  readonly type: "string";
54
49
  readonly required: false;
@@ -1 +1 @@
1
- {"version":3,"file":"kitFields.d.ts","sourceRoot":"","sources":["../../src/data/kitFields.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,eAAe;aAC1B,MAAM;iBAAI,IAAI,EAAE,QAAQ;iBAAE,QAAQ;iBAAS,KAAK;iBAAQ,SAAS;qBAAI,KAAK;;;CAClE,CAAC;AAEX;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,kBAAkB;aAC7B,QAAQ;iBAAI,IAAI,EAAE,QAAQ;iBAAE,QAAQ;iBAAS,KAAK;;aAClD,QAAQ;iBAAI,IAAI,EAAE,QAAQ;iBAAE,QAAQ;iBAAS,KAAK;;aAClD,eAAe;iBAAI,IAAI,EAAE,MAAM;iBAAE,QAAQ;iBAAS,KAAK;;CAC/C,CAAC"}
1
+ {"version":3,"file":"kitFields.d.ts","sourceRoot":"","sources":["../../src/data/kitFields.ts"],"names":[],"mappings":"AAyDA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,eAAe;;iBA7BX,IAAI,EAAE,QAAQ;iBAAE,QAAQ;iBAAS,KAAK;;;iBACnC,IAAI,EAAE,QAAQ;iBAAE,QAAQ;iBAAS,KAAK;;;iBAC3C,IAAI,EAAE,QAAQ;iBAAE,QAAQ;iBAAS,KAAK;;;iBACrC,IAAI,EAAE,QAAQ;iBAAE,QAAQ;iBAAS,KAAK;;;iBA2B1C,IAAI,EAAE,QAAQ;iBAAE,QAAQ;iBAAS,KAAK;iBAAQ,SAAS;qBAAI,KAAK;;;CAElE,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