@pithy-sh/auth 0.9.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 (125) hide show
  1. package/README.md +8 -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/capability.d.ts +26 -1
  7. package/dist/capability.d.ts.map +1 -1
  8. package/dist/capability.js +23 -5
  9. package/dist/client/lifecycle.d.ts +19 -0
  10. package/dist/client/lifecycle.d.ts.map +1 -0
  11. package/dist/client/lifecycle.js +25 -0
  12. package/dist/client/projection.d.ts +4 -0
  13. package/dist/client/projection.d.ts.map +1 -1
  14. package/dist/data/betterAuth.d.ts +4 -0
  15. package/dist/data/betterAuth.d.ts.map +1 -1
  16. package/dist/data/betterAuth.js +6 -2
  17. package/dist/data/kitFields.d.ts +20 -25
  18. package/dist/data/kitFields.d.ts.map +1 -1
  19. package/dist/data/kitFields.js +28 -32
  20. package/dist/data/tables.d.ts +28 -2
  21. package/dist/data/tables.d.ts.map +1 -1
  22. package/dist/data/tables.js +5 -3
  23. package/dist/data/userLifecycle.d.ts +61 -0
  24. package/dist/data/userLifecycle.d.ts.map +1 -0
  25. package/dist/data/userLifecycle.js +50 -0
  26. package/dist/http/guards.d.ts +23 -1
  27. package/dist/http/guards.d.ts.map +1 -1
  28. package/dist/http/guards.js +28 -3
  29. package/dist/http/lifecycleGate.d.ts +18 -0
  30. package/dist/http/lifecycleGate.d.ts.map +1 -0
  31. package/dist/http/lifecycleGate.js +75 -0
  32. package/dist/http/middleware.d.ts +5 -0
  33. package/dist/http/middleware.d.ts.map +1 -1
  34. package/dist/http/middleware.js +47 -6
  35. package/dist/http/providerRefusal.d.ts.map +1 -1
  36. package/dist/http/providerRefusal.js +8 -0
  37. package/dist/http/resolve.d.ts.map +1 -1
  38. package/dist/http/resolve.js +7 -4
  39. package/dist/http/routes.d.ts.map +1 -1
  40. package/dist/http/routes.js +20 -1
  41. package/dist/instance/auth.d.ts +55 -3
  42. package/dist/instance/auth.d.ts.map +1 -1
  43. package/dist/instance/auth.js +53 -2
  44. package/dist/instance/microsoftEmail.d.ts +70 -0
  45. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  46. package/dist/instance/microsoftEmail.js +96 -0
  47. package/dist/instance/providerSignInGate.d.ts +7 -6
  48. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  49. package/dist/instance/providerSignInGate.js +7 -6
  50. package/dist/instance/providers.d.ts +7 -5
  51. package/dist/instance/providers.d.ts.map +1 -1
  52. package/dist/instance/providers.js +5 -3
  53. package/dist/instance/secrets.d.ts +64 -3
  54. package/dist/instance/secrets.d.ts.map +1 -1
  55. package/dist/instance/secrets.js +44 -5
  56. package/dist/lifecycle/enforce.d.ts +40 -0
  57. package/dist/lifecycle/enforce.d.ts.map +1 -0
  58. package/dist/lifecycle/enforce.js +70 -0
  59. package/dist/lifecycle/hooks.d.ts +53 -0
  60. package/dist/lifecycle/hooks.d.ts.map +1 -0
  61. package/dist/lifecycle/hooks.js +2 -0
  62. package/dist/lifecycle/request.d.ts +15 -0
  63. package/dist/lifecycle/request.d.ts.map +1 -0
  64. package/dist/lifecycle/request.js +27 -0
  65. package/dist/lifecycle/state.d.ts +64 -0
  66. package/dist/lifecycle/state.d.ts.map +1 -0
  67. package/dist/lifecycle/state.js +90 -0
  68. package/dist/lifecycle/transitions.d.ts +132 -0
  69. package/dist/lifecycle/transitions.d.ts.map +1 -0
  70. package/dist/lifecycle/transitions.js +349 -0
  71. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  72. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  73. package/dist/migrations/0004_user_lifecycle.js +47 -0
  74. package/dist/migrations/set.d.ts +2 -1
  75. package/dist/migrations/set.d.ts.map +1 -1
  76. package/dist/migrations/set.js +4 -2
  77. package/dist/peer.d.ts +4 -0
  78. package/dist/peer.d.ts.map +1 -1
  79. package/dist/test-utils/liveApp.d.ts +21 -0
  80. package/dist/test-utils/liveApp.d.ts.map +1 -1
  81. package/dist/test-utils/liveApp.js +1 -0
  82. package/dist/test-utils/scopedBackend.d.ts +21 -0
  83. package/dist/test-utils/scopedBackend.d.ts.map +1 -1
  84. package/dist/test-utils/scopedBackend.js +7 -1
  85. package/dist/version.generated.d.ts +1 -1
  86. package/dist/version.generated.d.ts.map +1 -1
  87. package/dist/version.generated.js +1 -1
  88. package/docs/account-lifecycle.md +105 -0
  89. package/docs/apple-signin.md +7 -1
  90. package/docs/facebook-oauth.md +7 -1
  91. package/docs/github-oauth.md +7 -1
  92. package/docs/google-oauth.md +7 -1
  93. package/docs/microsoft-oauth.md +177 -0
  94. package/package.json +5 -5
  95. package/pithy.manifest.json +17 -3
  96. package/src/audit/actions.ts +23 -0
  97. package/src/audit/emit.ts +1 -1
  98. package/src/capability.ts +125 -54
  99. package/src/client/lifecycle.ts +27 -0
  100. package/src/client/projection.ts +4 -0
  101. package/src/data/betterAuth.ts +21 -1
  102. package/src/data/kitFields.ts +27 -0
  103. package/src/data/tables.ts +4 -2
  104. package/src/data/userLifecycle.ts +80 -0
  105. package/src/http/guards.ts +29 -1
  106. package/src/http/lifecycleGate.ts +78 -0
  107. package/src/http/middleware.ts +61 -2
  108. package/src/http/providerRefusal.ts +10 -0
  109. package/src/http/resolve.ts +8 -3
  110. package/src/http/routes.ts +38 -1
  111. package/src/instance/auth.ts +69 -2
  112. package/src/instance/microsoftEmail.ts +111 -0
  113. package/src/instance/providerSignInGate.ts +7 -6
  114. package/src/instance/providers.ts +8 -4
  115. package/src/instance/secrets.ts +59 -5
  116. package/src/lifecycle/enforce.ts +89 -0
  117. package/src/lifecycle/hooks.ts +54 -0
  118. package/src/lifecycle/request.ts +31 -0
  119. package/src/lifecycle/state.ts +101 -0
  120. package/src/lifecycle/transitions.ts +483 -0
  121. package/src/migrations/0004_user_lifecycle.ts +68 -0
  122. package/src/migrations/set.ts +3 -1
  123. package/src/test-utils/liveApp.ts +2 -1
  124. package/src/test-utils/scopedBackend.ts +2 -1
  125. package/src/version.generated.ts +1 -1
@@ -21,12 +21,16 @@ import type { SessionSecretVersions } from "./sessionSecrets";
21
21
  * Read only when the provider is enabled; rotated in the Meta app dashboard, not on our schedule.
22
22
  * - `auth-github-credentials` — the GitHub OAuth app client id and secret, as a typed JSON value.
23
23
  * Read only when the provider is enabled; rotated in GitHub Developer settings, not on our schedule.
24
+ * - `auth-microsoft-credentials` — the Microsoft Entra ID app registration's client id, client secret,
25
+ * and tenant, as a typed JSON value. The tenant rides inside because it means nothing apart from the
26
+ * registration it belongs to. Rotatable: an Entra client secret expires (24 months at most).
24
27
  */
25
28
  export declare const AUTH_SESSION_SECRET = "auth-session-secret";
26
29
  export declare const AUTH_GOOGLE_CREDENTIALS = "auth-google-credentials";
27
30
  export declare const AUTH_APPLE_CREDENTIALS = "auth-apple-credentials";
28
31
  export declare const AUTH_FACEBOOK_CREDENTIALS = "auth-facebook-credentials";
29
32
  export declare const AUTH_GITHUB_CREDENTIALS = "auth-github-credentials";
33
+ export declare const AUTH_MICROSOFT_CREDENTIALS = "auth-microsoft-credentials";
30
34
  /**
31
35
  * The JWKS private keys, as `auth-session-secret`'s overlap names them (#602).
32
36
  *
@@ -79,6 +83,19 @@ export declare const GithubOAuthCredentials: z.ZodObject<{
79
83
  clientSecret: z.ZodString;
80
84
  }, z.core.$strip>;
81
85
  export type GithubOAuthCredentials = z.infer<typeof GithubOAuthCredentials>;
86
+ /**
87
+ * The Microsoft Entra ID credentials, stored as one typed JSON secret.
88
+ *
89
+ * **`tenantId` is required and may not be empty.** Better Auth builds its endpoints from
90
+ * `options.tenantId || "common"`, so an empty string would not fail: it would quietly open a
91
+ * single-tenant app to every Entra tenant and every personal account.
92
+ */
93
+ export declare const MicrosoftOAuthCredentials: z.ZodObject<{
94
+ clientId: z.ZodString;
95
+ clientSecret: z.ZodString;
96
+ tenantId: z.ZodString;
97
+ }, z.core.$strip>;
98
+ export type MicrosoftOAuthCredentials = z.infer<typeof MicrosoftOAuthCredentials>;
82
99
  export declare const authSecretsRegistry: {
83
100
  readonly "auth-session-secret": {
84
101
  readonly backend: "d1";
@@ -184,6 +201,27 @@ export declare const authSecretsRegistry: {
184
201
  readonly documentation: "https://github.com/settings/developers";
185
202
  };
186
203
  };
204
+ readonly "auth-microsoft-credentials": {
205
+ readonly backend: "d1";
206
+ readonly scope: "environment";
207
+ readonly rotatable: true;
208
+ readonly valueType: "json";
209
+ readonly schema: z.ZodObject<{
210
+ clientId: z.ZodString;
211
+ clientSecret: z.ZodString;
212
+ tenantId: z.ZodString;
213
+ }, z.core.$strip>;
214
+ readonly origin: {
215
+ readonly kind: "obtained";
216
+ readonly issuer: "microsoft";
217
+ readonly documentation: "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade";
218
+ };
219
+ readonly rotation: {
220
+ readonly kind: "manual";
221
+ readonly issuer: "microsoft";
222
+ readonly documentation: "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade";
223
+ };
224
+ };
187
225
  };
188
226
  /**
189
227
  * **The registry `auth()` contributes, from its own configuration (#602).**
@@ -288,6 +326,27 @@ export declare function authSecretsRegistryFor(config: {
288
326
  readonly documentation: "https://github.com/settings/developers";
289
327
  };
290
328
  };
329
+ readonly "auth-microsoft-credentials": {
330
+ readonly backend: "d1";
331
+ readonly scope: "environment";
332
+ readonly rotatable: true;
333
+ readonly valueType: "json";
334
+ readonly schema: z.ZodObject<{
335
+ clientId: z.ZodString;
336
+ clientSecret: z.ZodString;
337
+ tenantId: z.ZodString;
338
+ }, z.core.$strip>;
339
+ readonly origin: {
340
+ readonly kind: "obtained";
341
+ readonly issuer: "microsoft";
342
+ readonly documentation: "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade";
343
+ };
344
+ readonly rotation: {
345
+ readonly kind: "manual";
346
+ readonly issuer: "microsoft";
347
+ readonly documentation: "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade";
348
+ };
349
+ };
291
350
  readonly "auth-session-secret": {
292
351
  readonly backend: "d1";
293
352
  readonly scope: "environment";
@@ -320,15 +379,15 @@ export declare function authSecretsRegistryFor(config: {
320
379
  * nothing makes a secret name and a config key the same thing, and a reporting command that matched
321
380
  * them by substring would be right by luck. Stated here, once, beside both.
322
381
  */
323
- declare const PROVIDER_CREDENTIALS: readonly [readonly ["google", "auth-google-credentials"], readonly ["apple", "auth-apple-credentials"], readonly ["facebook", "auth-facebook-credentials"], readonly ["github", "auth-github-credentials"]];
324
- /** The four toggles this reads off the resolved `AuthConfig` — nothing else about it is its business. */
382
+ declare const PROVIDER_CREDENTIALS: readonly [readonly ["google", "auth-google-credentials"], readonly ["apple", "auth-apple-credentials"], readonly ["facebook", "auth-facebook-credentials"], readonly ["github", "auth-github-credentials"], readonly ["microsoft", "auth-microsoft-credentials"]];
383
+ /** The five toggles this reads off the resolved `AuthConfig` — nothing else about it is its business. */
325
384
  export type AuthProviderToggles = Record<(typeof PROVIDER_CREDENTIALS)[number][0], {
326
385
  enabled: boolean;
327
386
  }>;
328
387
  /**
329
388
  * **The provider credentials this composition cannot reach**, as the `inapplicableSecrets` contribution.
330
389
  *
331
- * Auth declares four credentials whether or not a project runs four providers, so a project on Google
390
+ * Auth declares five credentials whether or not a project runs five providers, so a project on Google
332
391
  * and GitHub carries two secrets nothing will ever read. `pithy doctor` asked for them every run under
333
392
  * *"fine to leave until you need it"* — softening, not silence, and "until you need it" is wrong about a
334
393
  * provider the configuration has not enabled.
@@ -356,5 +415,7 @@ export declare function resolveAppleCredentials(env: SecretsStoreEnv): Promise<A
356
415
  export declare function resolveFacebookCredentials(env: SecretsStoreEnv): Promise<FacebookOAuthCredentials>;
357
416
  /** Resolve the GitHub OAuth credential pair for this invocation (only call when GitHub is enabled). */
358
417
  export declare function resolveGithubCredentials(env: SecretsStoreEnv): Promise<GithubOAuthCredentials>;
418
+ /** Resolve the Microsoft Entra ID credentials for this invocation (only call when Microsoft is enabled). */
419
+ export declare function resolveMicrosoftCredentials(env: SecretsStoreEnv): Promise<MicrosoftOAuthCredentials>;
359
420
  export {};
360
421
  //# sourceMappingURL=secrets.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"secrets.d.ts","sourceRoot":"","sources":["../../src/instance/secrets.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAG1E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAE9D;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,mBAAmB,wBAAwB,CAAC;AACzD,eAAO,MAAM,uBAAuB,4BAA4B,CAAC;AACjE,eAAO,MAAM,sBAAsB,2BAA2B,CAAC;AAC/D,eAAO,MAAM,yBAAyB,8BAA8B,CAAC;AACrE,eAAO,MAAM,uBAAuB,4BAA4B,CAAC;AAEjE;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,cAAc,CAAC;AAE/C;;;;;;;GAOG;AACH,eAAO,MAAM,8BAA8B,EAAE,SAAS,MAAM,EAAmB,CAAC;AAKhF;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CAAC,gBAAgB,EAAE,MAAM,GAAG,MAAM,CAEzE;AAED,yEAAyE;AACzE,eAAO,MAAM,sBAAsB;;;iBAaoE,CAAC;AACxG,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAE5E,sEAAsE;AACtE,eAAO,MAAM,qBAAqB;;;;iBAsB/B,CAAC;AACJ,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAE1E,2EAA2E;AAC3E,eAAO,MAAM,wBAAwB;;;iBAa6D,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-23,12 +23,16 @@ import { sharedSecretsStore } from "@pithy-sh/secrets/src/sharedSecretsStore";
23
23
  * Read only when the provider is enabled; rotated in the Meta app dashboard, not on our schedule.
24
24
  * - `auth-github-credentials` — the GitHub OAuth app client id and secret, as a typed JSON value.
25
25
  * Read only when the provider is enabled; rotated in GitHub Developer settings, not on our schedule.
26
+ * - `auth-microsoft-credentials` — the Microsoft Entra ID app registration's client id, client secret,
27
+ * and tenant, as a typed JSON value. The tenant rides inside because it means nothing apart from the
28
+ * registration it belongs to. Rotatable: an Entra client secret expires (24 months at most).
26
29
  */
27
30
  const AUTH_SESSION_SECRET = "auth-session-secret";
28
31
  const AUTH_GOOGLE_CREDENTIALS = "auth-google-credentials";
29
32
  const AUTH_APPLE_CREDENTIALS = "auth-apple-credentials";
30
33
  const AUTH_FACEBOOK_CREDENTIALS = "auth-facebook-credentials";
31
34
  const AUTH_GITHUB_CREDENTIALS = "auth-github-credentials";
35
+ const AUTH_MICROSOFT_CREDENTIALS = "auth-microsoft-credentials";
32
36
  /**
33
37
  * The JWKS private keys, as `auth-session-secret`'s overlap names them (#602).
34
38
  *
@@ -82,17 +86,30 @@ const GithubOAuthCredentials = z.object({
82
86
  clientSecret: z.string().meta({ multiline: false }).describe("The GitHub OAuth app client secret for this environment. Never committed, never an env literal.")
83
87
  }).describe("A GitHub OAuth credential pair (`clientId` + `clientSecret`) for one environment.");
84
88
  /**
89
+ * The Microsoft Entra ID credentials, stored as one typed JSON secret.
90
+ *
91
+ * **`tenantId` is required and may not be empty.** Better Auth builds its endpoints from
92
+ * `options.tenantId || "common"`, so an empty string would not fail: it would quietly open a
93
+ * single-tenant app to every Entra tenant and every personal account.
94
+ */
95
+ const MicrosoftOAuthCredentials = z.object({
96
+ clientId: z.string().meta({ multiline: false }).describe("The Application (client) ID of the Entra ID app registration for this environment. Not secret on its own, but stored with the secret so the set is atomic."),
97
+ clientSecret: z.string().meta({ multiline: false }).describe("A client secret value from the same app registration. Expires (24 months at most), so rotate it on schedule. Never committed, never an env literal."),
98
+ tenantId: z.string().min(1).meta({ multiline: false }).describe("Who may sign in: a directory (tenant) ID for one organization, `organizations` for any work or school account, `consumers` for personal accounts only, or `common` for both.")
99
+ }).describe("A Microsoft Entra ID credential set (`clientId` + `clientSecret` + `tenantId`) for one environment.");
100
+ /**
85
101
  * Where a human goes for each OAuth credential pair, and where the same human rotates it.
86
102
  *
87
103
  * **The settings page, not the product homepage.** The point is to end a search, not to start one — and
88
- * these four are the case with no command and no possible one, so the link is the entire remedy the kit
89
- * can offer. Named constants because origin and rotation are the same page for all four, and two copies
104
+ * these five are the case with no command and no possible one, so the link is the entire remedy the kit
105
+ * can offer. Named constants because origin and rotation are the same page for all five, and two copies
90
106
  * of a URL is one that goes stale.
91
107
  */
92
108
  const GOOGLE_CREDENTIALS_PAGE = "https://console.cloud.google.com/apis/credentials";
93
109
  const APPLE_KEYS_PAGE = "https://developer.apple.com/account/resources/authkeys/list";
94
110
  const FACEBOOK_APPS_PAGE = "https://developers.facebook.com/apps/";
95
111
  const GITHUB_OAUTH_APPS_PAGE = "https://github.com/settings/developers";
112
+ const MICROSOFT_APP_REGISTRATIONS_PAGE = "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade";
96
113
  const authSecretsRegistry = defineSecretRegistry({
97
114
  [AUTH_SESSION_SECRET]: {
98
115
  backend: "d1",
@@ -182,6 +199,23 @@ const authSecretsRegistry = defineSecretRegistry({
182
199
  issuer: "github",
183
200
  documentation: GITHUB_OAUTH_APPS_PAGE
184
201
  }
202
+ },
203
+ [AUTH_MICROSOFT_CREDENTIALS]: {
204
+ backend: "d1",
205
+ scope: "environment",
206
+ rotatable: true,
207
+ valueType: "json",
208
+ schema: MicrosoftOAuthCredentials,
209
+ origin: {
210
+ kind: "obtained",
211
+ issuer: "microsoft",
212
+ documentation: MICROSOFT_APP_REGISTRATIONS_PAGE
213
+ },
214
+ rotation: {
215
+ kind: "manual",
216
+ issuer: "microsoft",
217
+ documentation: MICROSOFT_APP_REGISTRATIONS_PAGE
218
+ }
185
219
  }
186
220
  });
187
221
  /**
@@ -233,12 +267,13 @@ const PROVIDER_CREDENTIALS = [
233
267
  ["google", AUTH_GOOGLE_CREDENTIALS],
234
268
  ["apple", AUTH_APPLE_CREDENTIALS],
235
269
  ["facebook", AUTH_FACEBOOK_CREDENTIALS],
236
- ["github", AUTH_GITHUB_CREDENTIALS]
270
+ ["github", AUTH_GITHUB_CREDENTIALS],
271
+ ["microsoft", AUTH_MICROSOFT_CREDENTIALS]
237
272
  ];
238
273
  /**
239
274
  * **The provider credentials this composition cannot reach**, as the `inapplicableSecrets` contribution.
240
275
  *
241
- * Auth declares four credentials whether or not a project runs four providers, so a project on Google
276
+ * Auth declares five credentials whether or not a project runs five providers, so a project on Google
242
277
  * and GitHub carries two secrets nothing will ever read. `pithy doctor` asked for them every run under
243
278
  * *"fine to leave until you need it"* — softening, not silence, and "until you need it" is wrong about a
244
279
  * provider the configuration has not enabled.
@@ -285,5 +320,9 @@ async function resolveFacebookCredentials(env) {
285
320
  async function resolveGithubCredentials(env) {
286
321
  return (await sharedSecretsStore(env, authSecretsRegistry)).get(AUTH_GITHUB_CREDENTIALS);
287
322
  }
323
+ /** Resolve the Microsoft Entra ID credentials for this invocation (only call when Microsoft is enabled). */
324
+ async function resolveMicrosoftCredentials(env) {
325
+ return (await sharedSecretsStore(env, authSecretsRegistry)).get(AUTH_MICROSOFT_CREDENTIALS);
326
+ }
288
327
  //#endregion
289
- export { AUTH_APPLE_CREDENTIALS, AUTH_FACEBOOK_CREDENTIALS, AUTH_GITHUB_CREDENTIALS, AUTH_GOOGLE_CREDENTIALS, AUTH_JWKS_DEPENDENT, AUTH_SESSION_SECRET, AppleOAuthCredentials, FacebookOAuthCredentials, GithubOAuthCredentials, GoogleOAuthCredentials, SESSION_SECRET_SEALING_PLUGINS, authSecretsRegistry, authSecretsRegistryFor, inapplicableProviderSecrets, resolveAppleCredentials, resolveFacebookCredentials, resolveGithubCredentials, resolveGoogleCredentials, resolveSessionSecret, resolveSessionSecrets, sessionSecretOverlapDays };
328
+ export { AUTH_APPLE_CREDENTIALS, AUTH_FACEBOOK_CREDENTIALS, AUTH_GITHUB_CREDENTIALS, AUTH_GOOGLE_CREDENTIALS, AUTH_JWKS_DEPENDENT, AUTH_MICROSOFT_CREDENTIALS, AUTH_SESSION_SECRET, AppleOAuthCredentials, FacebookOAuthCredentials, GithubOAuthCredentials, GoogleOAuthCredentials, MicrosoftOAuthCredentials, SESSION_SECRET_SEALING_PLUGINS, authSecretsRegistry, authSecretsRegistryFor, inapplicableProviderSecrets, resolveAppleCredentials, resolveFacebookCredentials, resolveGithubCredentials, resolveGoogleCredentials, resolveMicrosoftCredentials, resolveSessionSecret, resolveSessionSecrets, sessionSecretOverlapDays };
@@ -0,0 +1,40 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyError } from "@pithy-sh/core/src/error/pithyError";
4
+ import type { AuthDatabase } from "../data/tables";
5
+ import { LifecycleColumns } from "./state";
6
+ /**
7
+ * The reads enforcement needs, and the one place a refusal is remembered for the rest of a request.
8
+ *
9
+ * ## Where an account is refused
10
+ *
11
+ * - **Every request** — the session middleware reads the state off the user Better Auth resolved for the
12
+ * session, which carries the columns, so the check costs no query. A refused account gets no
13
+ * `AuthContext`, so every `requireAuth()` in the kit refuses it whoever wrote the guard; this capability's
14
+ * own `requireAuth()` raises the refusal itself, with its code, rather than a 401.
15
+ * - **Every sign-in and every token refresh** — `session.create.before` in `../instance/auth.ts`. Every way
16
+ * a session comes into being goes through `createSession`, so one hook covers magic link, OTP, every
17
+ * social callback and `/token/rotate` alike.
18
+ * - **Better Auth's own endpoints that act as the session's holder** — `/token`, `/get-session`,
19
+ * `/update-user` and the rest — refused in `handleBetterAuth` from the middleware's verdict, because
20
+ * Better Auth resolves its own session there and never asks this capability.
21
+ *
22
+ * The reason for a suspension is the one read only a refused request pays for: it lives in
23
+ * `pithy_auth_user_lifecycle`, not on the user row, so an account in good standing never costs a lookup.
24
+ */
25
+ /** The reason given for the suspension in force — the newest `suspended` row — or null when none was written. */
26
+ export declare function suspensionReason(db: AuthDatabase, userId: string): Promise<string | null>;
27
+ /** An account's lifecycle columns, read from its row, or `null` when there is no such account. */
28
+ export declare function readLifecycleColumns(db: AuthDatabase, userId: string): Promise<LifecycleColumns | null>;
29
+ /**
30
+ * The refusal for this account at `now`, or `null` when it may act.
31
+ *
32
+ * `columns` is what the caller already holds — the session's user object, a row it read. Absent, the row is
33
+ * read here, which is the sign-in path: a session about to be created has no user object yet.
34
+ */
35
+ export declare function lifecycleRefusalFor(db: AuthDatabase, userId: string, columns: Partial<LifecycleColumns> | null | undefined, now: Date): Promise<PithyError | null>;
36
+ /** Remember that this request's credential belongs to an account that may not act. */
37
+ export declare function noteRefusal(context: object, refusal: PithyError): void;
38
+ /** The refusal the session middleware reached for this request, if it reached one. */
39
+ export declare function noticedRefusal(context: object): PithyError | undefined;
40
+ //# sourceMappingURL=enforce.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enforce.d.ts","sourceRoot":"","sources":["../../src/lifecycle/enforce.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AACtE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAmB,gBAAgB,EAAoB,MAAM,SAAS,CAAC;AAE9E;;;;;;;;;;;;;;;;;;GAkBG;AAEH,iHAAiH;AACjH,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAW/F;AAED,kGAAkG;AAClG,wBAAsB,oBAAoB,CAAC,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAO7G;AAED;;;;;GAKG;AACH,wBAAsB,mBAAmB,CACvC,EAAE,EAAE,YAAY,EAChB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,IAAI,GAAG,SAAS,EACrD,GAAG,EAAE,IAAI,GACR,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAM5B;AAYD,sFAAsF;AACtF,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,GAAG,IAAI,CAEtE;AAED,sFAAsF;AACtF,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAEtE"}
@@ -0,0 +1,70 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { LifecycleColumns, accountStanding, lifecycleRefusal } from "./state.js";
4
+ //#region src/lifecycle/enforce.ts
5
+ /**
6
+ * The reads enforcement needs, and the one place a refusal is remembered for the rest of a request.
7
+ *
8
+ * ## Where an account is refused
9
+ *
10
+ * - **Every request** — the session middleware reads the state off the user Better Auth resolved for the
11
+ * session, which carries the columns, so the check costs no query. A refused account gets no
12
+ * `AuthContext`, so every `requireAuth()` in the kit refuses it whoever wrote the guard; this capability's
13
+ * own `requireAuth()` raises the refusal itself, with its code, rather than a 401.
14
+ * - **Every sign-in and every token refresh** — `session.create.before` in `../instance/auth.ts`. Every way
15
+ * a session comes into being goes through `createSession`, so one hook covers magic link, OTP, every
16
+ * social callback and `/token/rotate` alike.
17
+ * - **Better Auth's own endpoints that act as the session's holder** — `/token`, `/get-session`,
18
+ * `/update-user` and the rest — refused in `handleBetterAuth` from the middleware's verdict, because
19
+ * Better Auth resolves its own session there and never asks this capability.
20
+ *
21
+ * The reason for a suspension is the one read only a refused request pays for: it lives in
22
+ * `pithy_auth_user_lifecycle`, not on the user row, so an account in good standing never costs a lookup.
23
+ */
24
+ /** The reason given for the suspension in force — the newest `suspended` row — or null when none was written. */
25
+ async function suspensionReason(db, userId) {
26
+ const reason = (await db.selectFrom("pithyAuthUserLifecycle").select("reason").where("userId", "=", userId).where("action", "=", "suspended").orderBy("id", "desc").limit(1).executeTakeFirst())?.reason?.trim();
27
+ return reason ? reason : null;
28
+ }
29
+ /** An account's lifecycle columns, read from its row, or `null` when there is no such account. */
30
+ async function readLifecycleColumns(db, userId) {
31
+ const row = await db.selectFrom("pithyAuthUsers").select([
32
+ "suspendedAt",
33
+ "suspendedUntil",
34
+ "deletedAt",
35
+ "purgeAfter"
36
+ ]).where("id", "=", userId).executeTakeFirst();
37
+ return row ? LifecycleColumns.parse(row) : null;
38
+ }
39
+ /**
40
+ * The refusal for this account at `now`, or `null` when it may act.
41
+ *
42
+ * `columns` is what the caller already holds — the session's user object, a row it read. Absent, the row is
43
+ * read here, which is the sign-in path: a session about to be created has no user object yet.
44
+ */
45
+ async function lifecycleRefusalFor(db, userId, columns, now) {
46
+ const held = columns ?? await readLifecycleColumns(db, userId) ?? {};
47
+ const standing = accountStanding(held, now);
48
+ if (standing.state === "active") return null;
49
+ const reason = standing.state === "suspended" ? await suspensionReason(db, userId) : null;
50
+ return lifecycleRefusal(userId, standing, reason);
51
+ }
52
+ /**
53
+ * The refusal the session middleware reached for this request, keyed by the request's context.
54
+ *
55
+ * A WeakMap rather than a request variable because `PithyVars` is core's, and this is a fact only this
56
+ * capability's own guards read — a refused account already has no `AuthContext`, which is the part every
57
+ * other capability's guard needs. Keyed by the context the way `../http/resolve.ts` caches the instance, so
58
+ * it dies with the request.
59
+ */
60
+ const refusals = /* @__PURE__ */ new WeakMap();
61
+ /** Remember that this request's credential belongs to an account that may not act. */
62
+ function noteRefusal(context, refusal) {
63
+ refusals.set(context, refusal);
64
+ }
65
+ /** The refusal the session middleware reached for this request, if it reached one. */
66
+ function noticedRefusal(context) {
67
+ return refusals.get(context);
68
+ }
69
+ //#endregion
70
+ export { lifecycleRefusalFor, noteRefusal, noticedRefusal, readLifecycleColumns, suspensionReason };
@@ -0,0 +1,53 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { D1Database } from "@cloudflare/workers-types";
4
+ import type { UserLifecycleActorType } from "../data/userLifecycle";
5
+ /**
6
+ * The four seams an adopter's own code follows the account lifecycle through, without polling (#620).
7
+ *
8
+ * **On the transition, not on a route.** An account is suspended from the management surface today and may be
9
+ * from somewhere else tomorrow; a listener hung off one route would miss the others, which is the argument
10
+ * `onSessionRevoked` already makes for the session row. `./transitions.ts` is the only place a transition is
11
+ * written, so it is the only place these fire — once per transition that actually happened, never for a
12
+ * request that found the account already in the state it asked for.
13
+ *
14
+ * **Non-fatal by contract.** By the time a hook runs the transition is written and recorded. A hook that throws
15
+ * is logged and swallowed, so it can neither undo the transition nor turn it into an error the caller retries
16
+ * — a retry would find the account already moved and fire nothing, and the adopter's side effect would be
17
+ * lost either way.
18
+ */
19
+ /** What happened, handed to every hook. */
20
+ export interface UserLifecycleHookEvent {
21
+ /** The account it happened to. */
22
+ readonly userId: string;
23
+ /** Who made the transition: the kind, and the principal's id where there is one. */
24
+ readonly actor: {
25
+ readonly type: UserLifecycleActorType;
26
+ readonly id: string | null;
27
+ };
28
+ /** The reason given, or null when the transition needed none. */
29
+ readonly reason: string | null;
30
+ /** When the transition was written. */
31
+ readonly at: Date;
32
+ /** For a suspension, when it ends by itself; null for one that lasts until a reinstatement. */
33
+ readonly suspendedUntil?: Date | null;
34
+ /** For a deletion, when the account's data may be erased. */
35
+ readonly purgeAfter?: Date | null;
36
+ }
37
+ /**
38
+ * One hook. Handed the request's D1 binding, for the reason `SessionRevokedListener` is: the listener almost
39
+ * certainly writes to the same database under a different capability's view of it.
40
+ */
41
+ export type UserLifecycleListener = (event: UserLifecycleHookEvent, d1: D1Database) => void | Promise<void>;
42
+ /** The four hooks, each optional. Passed to `auth()` beside the config. */
43
+ export interface UserLifecycleHooks {
44
+ /** An account was suspended. */
45
+ readonly onUserSuspended?: UserLifecycleListener;
46
+ /** A suspended account was reinstated. */
47
+ readonly onUserReinstated?: UserLifecycleListener;
48
+ /** An account was deleted — by an operator or by its owner — and its purge window began. */
49
+ readonly onUserDeleted?: UserLifecycleListener;
50
+ /** A deleted account's data was erased. The last thing that happens to it. */
51
+ readonly onUserPurged?: UserLifecycleListener;
52
+ }
53
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../../src/lifecycle/hooks.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAEpE;;;;;;;;;;;;;GAaG;AAEH,2CAA2C;AAC3C,MAAM,WAAW,sBAAsB;IACrC,kCAAkC;IAClC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,oFAAoF;IACpF,QAAQ,CAAC,KAAK,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,sBAAsB,CAAC;QAAC,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;IACtF,iEAAiE;IACjE,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,uCAAuC;IACvC,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAClB,+FAA+F;IAC/F,QAAQ,CAAC,cAAc,CAAC,EAAE,IAAI,GAAG,IAAI,CAAC;IACtC,6DAA6D;IAC7D,QAAQ,CAAC,UAAU,CAAC,EAAE,IAAI,GAAG,IAAI,CAAC;CACnC;AAED;;;GAGG;AACH,MAAM,MAAM,qBAAqB,GAAG,CAAC,KAAK,EAAE,sBAAsB,EAAE,EAAE,EAAE,UAAU,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE5G,2EAA2E;AAC3E,MAAM,WAAW,kBAAkB;IACjC,gCAAgC;IAChC,QAAQ,CAAC,eAAe,CAAC,EAAE,qBAAqB,CAAC;IACjD,0CAA0C;IAC1C,QAAQ,CAAC,gBAAgB,CAAC,EAAE,qBAAqB,CAAC;IAClD,4FAA4F;IAC5F,QAAQ,CAAC,aAAa,CAAC,EAAE,qBAAqB,CAAC;IAC/C,8EAA8E;IAC9E,QAAQ,CAAC,YAAY,CAAC,EAAE,qBAAqB,CAAC;CAC/C"}
@@ -0,0 +1,2 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
@@ -0,0 +1,15 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
4
+ import type { Context } from "hono";
5
+ import type { AuthWiring } from "../capability";
6
+ import type { LifecycleDeps } from "./transitions";
7
+ /**
8
+ * The transitions' dependencies, resolved from one request — what a lifecycle route hands `./transitions.ts`.
9
+ *
10
+ * One function so every route resolves them the same way: this request's database, its audit seam and logger,
11
+ * the composed email capability's enqueue bound to this request's env, and the adopter's hooks as `auth()` was
12
+ * handed them. A route that assembled its own would be the second place a hook could be forgotten.
13
+ */
14
+ export declare function lifecycleDeps(c: Context<PithyHonoEnv>, wiring: AuthWiring): LifecycleDeps;
15
+ //# sourceMappingURL=request.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../../src/lifecycle/request.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAE7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,UAAU,GAAG,aAAa,CAYzF"}
@@ -0,0 +1,27 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { authDatabase } from "../data/tables.js";
4
+ import { resolveDb } from "../http/resolve.js";
5
+ //#region src/lifecycle/request.ts
6
+ /**
7
+ * The transitions' dependencies, resolved from one request — what a lifecycle route hands `./transitions.ts`.
8
+ *
9
+ * One function so every route resolves them the same way: this request's database, its audit seam and logger,
10
+ * the composed email capability's enqueue bound to this request's env, and the adopter's hooks as `auth()` was
11
+ * handed them. A route that assembled its own would be the second place a hook could be forgotten.
12
+ */
13
+ function lifecycleDeps(c, wiring) {
14
+ const d1 = resolveDb(c.env, wiring.config.database);
15
+ const enqueue = wiring.enqueueEmail;
16
+ return {
17
+ db: authDatabase(d1),
18
+ d1,
19
+ emit: c.var.emit,
20
+ config: wiring.config,
21
+ hooks: wiring.lifecycleHooks ?? {},
22
+ enqueueEmail: enqueue ? (input) => enqueue(c.env, input) : void 0,
23
+ log: c.var.log?.child("auth")
24
+ };
25
+ }
26
+ //#endregion
27
+ export { lifecycleDeps };
@@ -0,0 +1,64 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
4
+ import type { z } from "zod";
5
+ /**
6
+ * What an account's four lifecycle columns mean, decided once.
7
+ *
8
+ * Every enforcement point — the session middleware, sign-in, token refresh — reads the state through
9
+ * {@link accountStanding} and refuses through {@link lifecycleRefusal}. Enforcement written twice is
10
+ * enforcement that disagrees, and the first disagreement would be a suspension one door honors and another
11
+ * does not.
12
+ */
13
+ /**
14
+ * The four columns, decoded off whatever carries them: a `pithy_auth_users` row, or the user object Better
15
+ * Auth resolved for a session, which carries them because `../data/kitFields.ts` declares them. Unknown keys
16
+ * are dropped, and a key that is absent — a row read before `0004_user_lifecycle` — reads as null.
17
+ */
18
+ export declare const LifecycleColumns: z.ZodObject<{
19
+ suspendedAt: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
20
+ suspendedUntil: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
21
+ deletedAt: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
22
+ purgeAfter: z.ZodOptional<z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>>>;
23
+ }, z.core.$strip>;
24
+ export type LifecycleColumns = z.output<typeof LifecycleColumns>;
25
+ /** Where an account stands, at one instant. */
26
+ export type AccountStanding = {
27
+ readonly state: "active";
28
+ } | {
29
+ readonly state: "suspended";
30
+ readonly until: Date | null;
31
+ } | {
32
+ readonly state: "deleted";
33
+ readonly purgeAfter: Date | null;
34
+ };
35
+ /**
36
+ * Where an account stands at `now`.
37
+ *
38
+ * **Deleted outranks suspended.** An account deleted while it was suspended is deleted: the suspension's end
39
+ * passing must not reopen it.
40
+ *
41
+ * **A suspension past its `suspendedUntil` is not a suspension**, and no write expires it. The end is
42
+ * exclusive — at the instant it names, the account is active again. A column nobody has cleared is a
43
+ * fact about the past, not about now, and reading it that way is what lets a timed suspension end on time
44
+ * with nothing scheduled to end it.
45
+ *
46
+ * **A deletion past its `purgeAfter` is still a deletion.** Only the purge ends that state, by erasing the
47
+ * account, and until it has run the account must stay shut.
48
+ */
49
+ export declare function accountStanding(columns: Partial<LifecycleColumns>, now: Date): AccountStanding;
50
+ /**
51
+ * The refusal for an account that may not act, or `null` for one that may.
52
+ *
53
+ * **The reason an operator gave is the public `message`**, because it is written for the person who is locked
54
+ * out and it is the one thing their screen cannot invent. `params` carries the end of a suspension, or the
55
+ * last day a deletion can be undone, as ISO-8601, for a client that renders the date in its reader's own
56
+ * words. Neither the account id nor who acted crosses: `detail` holds the id for the log, and `clientError`
57
+ * strips it with `action`.
58
+ *
59
+ * 403 for both, never 401: the credential is genuine, and signing in again cannot help.
60
+ */
61
+ export declare function lifecycleRefusal(userId: string, standing: AccountStanding, reason: string | null): PithyError | null;
62
+ /** Whether a caught error is one of the two lifecycle refusals. */
63
+ export declare function isLifecycleRefusal(error: unknown): error is PithyError;
64
+ //# sourceMappingURL=state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../src/lifecycle/state.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AACjE,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAG7B;;;;;;;GAOG;AAEH;;;;GAIG;AACH,eAAO,MAAM,gBAAgB;;;;;iBAKoD,CAAC;AAClF,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEjE,+CAA+C;AAC/C,MAAM,MAAM,eAAe,GACvB;IAAE,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAA;CAAE,GAC5B;IAAE,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,GAAG,IAAI,CAAA;CAAE,GAC5D;IAAE,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,UAAU,EAAE,IAAI,GAAG,IAAI,CAAA;CAAE,CAAC;AAEpE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,OAAO,CAAC,gBAAgB,CAAC,EAAE,GAAG,EAAE,IAAI,GAAG,eAAe,CAO9F;AAKD;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,UAAU,GAAG,IAAI,CAoBpH;AAED,mEAAmE;AACnE,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,UAAU,CAKtE"}
@@ -0,0 +1,90 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { User } from "../data/betterAuth.js";
4
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
5
+ //#region src/lifecycle/state.ts
6
+ /**
7
+ * What an account's four lifecycle columns mean, decided once.
8
+ *
9
+ * Every enforcement point — the session middleware, sign-in, token refresh — reads the state through
10
+ * {@link accountStanding} and refuses through {@link lifecycleRefusal}. Enforcement written twice is
11
+ * enforcement that disagrees, and the first disagreement would be a suspension one door honors and another
12
+ * does not.
13
+ */
14
+ /**
15
+ * The four columns, decoded off whatever carries them: a `pithy_auth_users` row, or the user object Better
16
+ * Auth resolved for a session, which carries them because `../data/kitFields.ts` declares them. Unknown keys
17
+ * are dropped, and a key that is absent — a row read before `0004_user_lifecycle` — reads as null.
18
+ */
19
+ const LifecycleColumns = User.pick({
20
+ suspendedAt: true,
21
+ suspendedUntil: true,
22
+ deletedAt: true,
23
+ purgeAfter: true
24
+ }).describe("An account's lifecycle columns, as `pithy_auth_users` stores them.");
25
+ /**
26
+ * Where an account stands at `now`.
27
+ *
28
+ * **Deleted outranks suspended.** An account deleted while it was suspended is deleted: the suspension's end
29
+ * passing must not reopen it.
30
+ *
31
+ * **A suspension past its `suspendedUntil` is not a suspension**, and no write expires it. The end is
32
+ * exclusive — at the instant it names, the account is active again. A column nobody has cleared is a
33
+ * fact about the past, not about now, and reading it that way is what lets a timed suspension end on time
34
+ * with nothing scheduled to end it.
35
+ *
36
+ * **A deletion past its `purgeAfter` is still a deletion.** Only the purge ends that state, by erasing the
37
+ * account, and until it has run the account must stay shut.
38
+ */
39
+ function accountStanding(columns, now) {
40
+ if (columns.deletedAt) return {
41
+ state: "deleted",
42
+ purgeAfter: columns.purgeAfter ?? null
43
+ };
44
+ if (columns.suspendedAt) {
45
+ const until = columns.suspendedUntil ?? null;
46
+ if (until === null || until.getTime() > now.getTime()) return {
47
+ state: "suspended",
48
+ until
49
+ };
50
+ }
51
+ return { state: "active" };
52
+ }
53
+ /** What a suspended account is told when nobody wrote a reason. */
54
+ const UNEXPLAINED_SUSPENSION = "This account is suspended.";
55
+ /**
56
+ * The refusal for an account that may not act, or `null` for one that may.
57
+ *
58
+ * **The reason an operator gave is the public `message`**, because it is written for the person who is locked
59
+ * out and it is the one thing their screen cannot invent. `params` carries the end of a suspension, or the
60
+ * last day a deletion can be undone, as ISO-8601, for a client that renders the date in its reader's own
61
+ * words. Neither the account id nor who acted crosses: `detail` holds the id for the log, and `clientError`
62
+ * strips it with `action`.
63
+ *
64
+ * 403 for both, never 401: the credential is genuine, and signing in again cannot help.
65
+ */
66
+ function lifecycleRefusal(userId, standing, reason) {
67
+ if (standing.state === "active") return null;
68
+ if (standing.state === "suspended") return new PithyError({
69
+ code: "auth/account_suspended",
70
+ status: 403,
71
+ message: reason ?? UNEXPLAINED_SUSPENSION,
72
+ ...standing.until ? { params: { suspendedUntil: standing.until.toISOString() } } : {},
73
+ action: "An operator suspended this account. Reinstate it from the management surface, or let it run out.",
74
+ detail: `user ${userId} is suspended${standing.until ? ` until ${standing.until.toISOString()}` : ""}`
75
+ });
76
+ return new PithyError({
77
+ code: "auth/account_deleted",
78
+ status: 403,
79
+ message: "This account is deleted.",
80
+ ...standing.purgeAfter ? { params: { purgeAfter: standing.purgeAfter.toISOString() } } : {},
81
+ action: "The account is inside its purge window. Restore it from the management surface before the purge runs.",
82
+ detail: `user ${userId} is deleted${standing.purgeAfter ? `, purge after ${standing.purgeAfter.toISOString()}` : ""}`
83
+ });
84
+ }
85
+ /** Whether a caught error is one of the two lifecycle refusals. */
86
+ function isLifecycleRefusal(error) {
87
+ return error instanceof PithyError && (error.payload.code === "auth/account_suspended" || error.payload.code === "auth/account_deleted");
88
+ }
89
+ //#endregion
90
+ export { LifecycleColumns, accountStanding, isLifecycleRefusal, lifecycleRefusal };