@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.
- package/README.md +12 -2
- package/dist/audit/actions.d.ts +21 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +22 -1
- package/dist/audit/emit.js +1 -1
- package/dist/caller/certificate.d.ts +83 -0
- package/dist/caller/certificate.d.ts.map +1 -0
- package/dist/caller/certificate.js +92 -0
- package/dist/caller/request.d.ts +66 -0
- package/dist/caller/request.d.ts.map +1 -0
- package/dist/caller/request.js +71 -0
- package/dist/caller/token.d.ts +130 -0
- package/dist/caller/token.d.ts.map +1 -0
- package/dist/caller/token.js +207 -0
- package/dist/capability.d.ts +70 -2
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +28 -7
- package/dist/client/lifecycle.d.ts +19 -0
- package/dist/client/lifecycle.d.ts.map +1 -0
- package/dist/client/lifecycle.js +25 -0
- package/dist/client/projection.d.ts +4 -0
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/data/betterAuth.d.ts +5 -1
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +7 -3
- package/dist/data/kitFields.d.ts +20 -25
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +28 -32
- package/dist/data/tables.d.ts +29 -3
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +61 -0
- package/dist/data/userLifecycle.d.ts.map +1 -0
- package/dist/data/userLifecycle.js +50 -0
- package/dist/http/credentialResign.d.ts +46 -0
- package/dist/http/credentialResign.d.ts.map +1 -0
- package/dist/http/credentialResign.js +203 -0
- package/dist/http/errorCallbackUrl.d.ts.map +1 -1
- package/dist/http/errorCallbackUrl.js +15 -9
- package/dist/http/guards.d.ts +23 -1
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +28 -3
- package/dist/http/lifecycleGate.d.ts +18 -0
- package/dist/http/lifecycleGate.d.ts.map +1 -0
- package/dist/http/lifecycleGate.js +75 -0
- package/dist/http/middleware.d.ts +5 -0
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +113 -21
- package/dist/http/providerRefusal.d.ts +8 -7
- package/dist/http/providerRefusal.d.ts.map +1 -1
- package/dist/http/providerRefusal.js +37 -32
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +23 -5
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +20 -1
- package/dist/instance/auth.d.ts +1280 -5
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +59 -4
- package/dist/instance/jwksReencryption.d.ts +75 -0
- package/dist/instance/jwksReencryption.d.ts.map +1 -0
- package/dist/instance/jwksReencryption.js +160 -0
- package/dist/instance/microsoftEmail.d.ts +70 -0
- package/dist/instance/microsoftEmail.d.ts.map +1 -0
- package/dist/instance/microsoftEmail.js +96 -0
- package/dist/instance/providerSignInGate.d.ts +14 -12
- package/dist/instance/providerSignInGate.d.ts.map +1 -1
- package/dist/instance/providerSignInGate.js +23 -20
- package/dist/instance/providers.d.ts +7 -5
- package/dist/instance/providers.d.ts.map +1 -1
- package/dist/instance/providers.js +5 -3
- package/dist/instance/secrets.d.ts +232 -4
- package/dist/instance/secrets.d.ts.map +1 -1
- package/dist/instance/secrets.js +129 -7
- package/dist/instance/sessionSecrets.d.ts +45 -0
- package/dist/instance/sessionSecrets.d.ts.map +1 -0
- package/dist/instance/sessionSecrets.js +29 -0
- package/dist/lifecycle/enforce.d.ts +40 -0
- package/dist/lifecycle/enforce.d.ts.map +1 -0
- package/dist/lifecycle/enforce.js +70 -0
- package/dist/lifecycle/hooks.d.ts +53 -0
- package/dist/lifecycle/hooks.d.ts.map +1 -0
- package/dist/lifecycle/hooks.js +2 -0
- package/dist/lifecycle/request.d.ts +15 -0
- package/dist/lifecycle/request.d.ts.map +1 -0
- package/dist/lifecycle/request.js +27 -0
- package/dist/lifecycle/state.d.ts +64 -0
- package/dist/lifecycle/state.d.ts.map +1 -0
- package/dist/lifecycle/state.js +90 -0
- package/dist/lifecycle/transitions.d.ts +132 -0
- package/dist/lifecycle/transitions.d.ts.map +1 -0
- package/dist/lifecycle/transitions.js +349 -0
- package/dist/migrations/0001_init.d.ts.map +1 -1
- package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
- package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
- package/dist/migrations/0003_account_issuer_nullable.js +131 -0
- package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
- package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
- package/dist/migrations/0004_user_lifecycle.js +47 -0
- package/dist/migrations/set.d.ts +3 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +6 -2
- package/dist/peer.d.ts +4 -0
- package/dist/peer.d.ts.map +1 -1
- package/dist/test-utils/liveApp.d.ts +26 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +1 -0
- package/dist/test-utils/schemaDrift.d.ts +49 -0
- package/dist/test-utils/schemaDrift.d.ts.map +1 -0
- package/dist/test-utils/schemaDrift.js +35 -0
- package/dist/test-utils/scopedBackend.d.ts +204 -0
- package/dist/test-utils/scopedBackend.d.ts.map +1 -0
- package/dist/test-utils/scopedBackend.js +166 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.d.ts.map +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +105 -0
- package/docs/apple-signin.md +7 -1
- package/docs/facebook-oauth.md +7 -1
- package/docs/github-oauth.md +7 -1
- package/docs/google-oauth.md +7 -1
- package/docs/microsoft-oauth.md +177 -0
- package/docs/server-authoritative.md +182 -0
- package/package.json +11 -8
- package/pithy.manifest.json +17 -3
- package/src/audit/actions.ts +23 -0
- package/src/audit/emit.ts +1 -1
- package/src/caller/certificate.ts +133 -0
- package/src/caller/request.ts +84 -0
- package/src/caller/token.ts +276 -0
- package/src/capability.ts +170 -38
- package/src/client/lifecycle.ts +27 -0
- package/src/client/projection.ts +4 -0
- package/src/data/betterAuth.ts +23 -2
- package/src/data/kitFields.ts +27 -0
- package/src/data/tables.ts +4 -2
- package/src/data/userLifecycle.ts +80 -0
- package/src/http/credentialResign.ts +268 -0
- package/src/http/errorCallbackUrl.ts +21 -13
- package/src/http/guards.ts +29 -1
- package/src/http/lifecycleGate.ts +78 -0
- package/src/http/middleware.ts +161 -37
- package/src/http/providerRefusal.ts +40 -32
- package/src/http/resolve.ts +34 -5
- package/src/http/routes.ts +39 -2
- package/src/instance/auth.ts +91 -6
- package/src/instance/jwksReencryption.ts +206 -0
- package/src/instance/microsoftEmail.ts +111 -0
- package/src/instance/providerSignInGate.ts +30 -27
- package/src/instance/providers.ts +8 -4
- package/src/instance/secrets.ts +153 -6
- package/src/instance/sessionSecrets.ts +64 -0
- package/src/lifecycle/enforce.ts +89 -0
- package/src/lifecycle/hooks.ts +54 -0
- package/src/lifecycle/request.ts +31 -0
- package/src/lifecycle/state.ts +101 -0
- package/src/lifecycle/transitions.ts +483 -0
- package/src/migrations/0001_init.ts +8 -10
- package/src/migrations/0003_account_issuer_nullable.ts +199 -0
- package/src/migrations/0004_user_lifecycle.ts +68 -0
- package/src/migrations/set.ts +5 -1
- package/src/test-utils/liveApp.ts +2 -1
- package/src/test-utils/schemaDrift.ts +82 -0
- package/src/test-utils/scopedBackend.ts +137 -0
- package/src/version.generated.ts +1 -1
package/dist/instance/secrets.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
import { defineSecretRegistry } from "@pithy-sh/secrets/src/registry";
|
|
5
6
|
import { sharedSecretsStore } from "@pithy-sh/secrets/src/sharedSecretsStore";
|
|
@@ -22,12 +23,47 @@ import { sharedSecretsStore } from "@pithy-sh/secrets/src/sharedSecretsStore";
|
|
|
22
23
|
* Read only when the provider is enabled; rotated in the Meta app dashboard, not on our schedule.
|
|
23
24
|
* - `auth-github-credentials` — the GitHub OAuth app client id and secret, as a typed JSON value.
|
|
24
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).
|
|
25
29
|
*/
|
|
26
30
|
const AUTH_SESSION_SECRET = "auth-session-secret";
|
|
27
31
|
const AUTH_GOOGLE_CREDENTIALS = "auth-google-credentials";
|
|
28
32
|
const AUTH_APPLE_CREDENTIALS = "auth-apple-credentials";
|
|
29
33
|
const AUTH_FACEBOOK_CREDENTIALS = "auth-facebook-credentials";
|
|
30
34
|
const AUTH_GITHUB_CREDENTIALS = "auth-github-credentials";
|
|
35
|
+
const AUTH_MICROSOFT_CREDENTIALS = "auth-microsoft-credentials";
|
|
36
|
+
/**
|
|
37
|
+
* The JWKS private keys, as `auth-session-secret`'s overlap names them (#602).
|
|
38
|
+
*
|
|
39
|
+
* Better Auth encrypts every key in `pithy_auth_jwks` under the session secret, and a key never expires —
|
|
40
|
+
* so retiring the version one is sealed under would leave a signing key nothing can open. The session
|
|
41
|
+
* secret's registry entry names this dependent, `instance/jwksReencryption.ts` moves the keys under the
|
|
42
|
+
* newest version and records it, and the secrets manager retires nothing until it has.
|
|
43
|
+
*/
|
|
44
|
+
const AUTH_JWKS_DEPENDENT = "auth-jwks";
|
|
45
|
+
/**
|
|
46
|
+
* The Better Auth plugins that seal rows of their own under the session secret, by id.
|
|
47
|
+
*
|
|
48
|
+
* `two-factor` seals every TOTP secret with `symmetricEncrypt({ key: ctx.context.secretConfig })`, and its
|
|
49
|
+
* backup codes the same way under `storeBackupCodes: "encrypted"` (`plugins/two-factor/index.mjs`,
|
|
50
|
+
* `backup-codes/index.mjs`). Neither expires. Nothing in the kit re-encrypts them, so an unattended rotation
|
|
51
|
+
* beside one is refused at `auth()` rather than allowed to retire the version they are sealed under.
|
|
52
|
+
*/
|
|
53
|
+
const SESSION_SECRET_SEALING_PLUGINS = ["two-factor"];
|
|
54
|
+
/** Seconds in a day. */
|
|
55
|
+
const DAY_SECONDS = 86400;
|
|
56
|
+
/**
|
|
57
|
+
* How many days a replaced session secret keeps verifying: the session's own lifetime, rounded up.
|
|
58
|
+
*
|
|
59
|
+
* **That is the whole of the overlap's argument.** A session in use is re-signed on its next request
|
|
60
|
+
* (`http/credentialResign.ts`), and its expiry slides forward on use — so a session that goes the whole
|
|
61
|
+
* overlap without one request has expired by the time the overlap ends. Any shorter, and a session used
|
|
62
|
+
* yesterday is signed out when the old version retires.
|
|
63
|
+
*/
|
|
64
|
+
function sessionSecretOverlapDays(sessionExpiresIn) {
|
|
65
|
+
return Math.max(1, Math.ceil(sessionExpiresIn / DAY_SECONDS));
|
|
66
|
+
}
|
|
31
67
|
/** The Google OAuth credential pair, stored as one typed JSON secret. */
|
|
32
68
|
const GoogleOAuthCredentials = z.object({
|
|
33
69
|
clientId: z.string().meta({ multiline: false }).describe("The Google OAuth client id for this environment. Not secret on its own, but stored with the secret so the pair is atomic."),
|
|
@@ -50,17 +86,30 @@ const GithubOAuthCredentials = z.object({
|
|
|
50
86
|
clientSecret: z.string().meta({ multiline: false }).describe("The GitHub OAuth app client secret for this environment. Never committed, never an env literal.")
|
|
51
87
|
}).describe("A GitHub OAuth credential pair (`clientId` + `clientSecret`) for one environment.");
|
|
52
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
|
+
/**
|
|
53
101
|
* Where a human goes for each OAuth credential pair, and where the same human rotates it.
|
|
54
102
|
*
|
|
55
103
|
* **The settings page, not the product homepage.** The point is to end a search, not to start one — and
|
|
56
|
-
* these
|
|
57
|
-
* can offer. Named constants because origin and rotation are the same page for all
|
|
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
|
|
58
106
|
* of a URL is one that goes stale.
|
|
59
107
|
*/
|
|
60
108
|
const GOOGLE_CREDENTIALS_PAGE = "https://console.cloud.google.com/apis/credentials";
|
|
61
109
|
const APPLE_KEYS_PAGE = "https://developer.apple.com/account/resources/authkeys/list";
|
|
62
110
|
const FACEBOOK_APPS_PAGE = "https://developers.facebook.com/apps/";
|
|
63
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";
|
|
64
113
|
const authSecretsRegistry = defineSecretRegistry({
|
|
65
114
|
[AUTH_SESSION_SECRET]: {
|
|
66
115
|
backend: "d1",
|
|
@@ -76,7 +125,12 @@ const authSecretsRegistry = defineSecretRegistry({
|
|
|
76
125
|
encoding: "base64url"
|
|
77
126
|
}
|
|
78
127
|
},
|
|
79
|
-
rotation: { kind: "local" }
|
|
128
|
+
rotation: { kind: "local" },
|
|
129
|
+
overlap: {
|
|
130
|
+
days: 7,
|
|
131
|
+
minimumDays: 7,
|
|
132
|
+
reencrypt: [AUTH_JWKS_DEPENDENT]
|
|
133
|
+
}
|
|
80
134
|
},
|
|
81
135
|
[AUTH_GOOGLE_CREDENTIALS]: {
|
|
82
136
|
backend: "d1",
|
|
@@ -145,9 +199,64 @@ const authSecretsRegistry = defineSecretRegistry({
|
|
|
145
199
|
issuer: "github",
|
|
146
200
|
documentation: GITHUB_OAUTH_APPS_PAGE
|
|
147
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
|
+
}
|
|
148
219
|
}
|
|
149
220
|
});
|
|
150
221
|
/**
|
|
222
|
+
* **The registry `auth()` contributes, from its own configuration (#602).**
|
|
223
|
+
*
|
|
224
|
+
* The session secret's overlap follows the configured session lifetime — {@link sessionSecretOverlapDays} —
|
|
225
|
+
* and it is both the overlap and its floor: an adopter who lengthens sessions lengthens the overlap with
|
|
226
|
+
* them, rather than holding a seven-day overlap against a thirty-day session. `rotateEveryDays` is
|
|
227
|
+
* `sessionSecretRotateEveryDays`, and only an adopter sets it: the kit turns no unattended rotation on.
|
|
228
|
+
*
|
|
229
|
+
* Checked by `defineSecretRegistry` like every registry, so a period no longer than the session lifetime is
|
|
230
|
+
* refused here, at `auth()`, naming the secret — rather than at a 03:00 cron that could only skip it.
|
|
231
|
+
*
|
|
232
|
+
* **A period is refused beside a plugin that seals rows under the session secret** —
|
|
233
|
+
* {@link SESSION_SECRET_SEALING_PLUGINS}. Only the JWKS keys are moved before a retirement; a plugin's own
|
|
234
|
+
* sealed rows would be left under the retired version, and nothing could open them again.
|
|
235
|
+
*/
|
|
236
|
+
function authSecretsRegistryFor(config) {
|
|
237
|
+
if (config.sessionSecretRotateEveryDays !== void 0) {
|
|
238
|
+
const sealing = (config.plugins ?? []).find((plugin) => SESSION_SECRET_SEALING_PLUGINS.includes(plugin.id));
|
|
239
|
+
if (sealing !== void 0) throw new ValidationError({
|
|
240
|
+
message: `${AUTH_SESSION_SECRET} cannot rotate unattended while the Better Auth "${sealing.id}" plugin is composed.`,
|
|
241
|
+
action: `Remove sessionSecretRotateEveryDays from auth({ ... }), or remove ${sealing.id}() from auth({ plugins: [...] }). ${sealing.id}() seals its secrets under ${AUTH_SESSION_SECRET}, and a rotation retires the version they are sealed under with nothing to move them first.`,
|
|
242
|
+
detail: `sessionSecretRotateEveryDays set with plugin "${sealing.id}", which seals rows under ${AUTH_SESSION_SECRET}`
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
const days = sessionSecretOverlapDays(config.sessionExpiresIn);
|
|
246
|
+
return defineSecretRegistry({
|
|
247
|
+
...authSecretsRegistry,
|
|
248
|
+
[AUTH_SESSION_SECRET]: {
|
|
249
|
+
...authSecretsRegistry[AUTH_SESSION_SECRET],
|
|
250
|
+
overlap: {
|
|
251
|
+
days,
|
|
252
|
+
minimumDays: days,
|
|
253
|
+
reencrypt: [AUTH_JWKS_DEPENDENT]
|
|
254
|
+
},
|
|
255
|
+
...config.sessionSecretRotateEveryDays === void 0 ? {} : { rotateEveryDays: config.sessionSecretRotateEveryDays }
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
151
260
|
* Which provider a credential belongs to — the join the CLI must never make by spelling (#541).
|
|
152
261
|
*
|
|
153
262
|
* `auth-apple-credentials` and the `apple` config key look like each other and that is a coincidence:
|
|
@@ -158,12 +267,13 @@ const PROVIDER_CREDENTIALS = [
|
|
|
158
267
|
["google", AUTH_GOOGLE_CREDENTIALS],
|
|
159
268
|
["apple", AUTH_APPLE_CREDENTIALS],
|
|
160
269
|
["facebook", AUTH_FACEBOOK_CREDENTIALS],
|
|
161
|
-
["github", AUTH_GITHUB_CREDENTIALS]
|
|
270
|
+
["github", AUTH_GITHUB_CREDENTIALS],
|
|
271
|
+
["microsoft", AUTH_MICROSOFT_CREDENTIALS]
|
|
162
272
|
];
|
|
163
273
|
/**
|
|
164
274
|
* **The provider credentials this composition cannot reach**, as the `inapplicableSecrets` contribution.
|
|
165
275
|
*
|
|
166
|
-
* Auth declares
|
|
276
|
+
* Auth declares five credentials whether or not a project runs five providers, so a project on Google
|
|
167
277
|
* and GitHub carries two secrets nothing will ever read. `pithy doctor` asked for them every run under
|
|
168
278
|
* *"fine to leave until you need it"* — softening, not silence, and "until you need it" is wrong about a
|
|
169
279
|
* provider the configuration has not enabled.
|
|
@@ -182,10 +292,18 @@ function inapplicableProviderSecrets(providers) {
|
|
|
182
292
|
}
|
|
183
293
|
return declared;
|
|
184
294
|
}
|
|
185
|
-
/** Resolve the Better Auth session secret for this invocation. */
|
|
295
|
+
/** Resolve the Better Auth session secret for this invocation — the current version alone. */
|
|
186
296
|
async function resolveSessionSecret(env) {
|
|
187
297
|
return (await sharedSecretsStore(env, authSecretsRegistry)).get(AUTH_SESSION_SECRET);
|
|
188
298
|
}
|
|
299
|
+
/**
|
|
300
|
+
* Resolve every retained version of the session secret (#602) — what an instance needs to open values sealed
|
|
301
|
+
* under the previous version, and what a credential signed under it is verified against. One read through
|
|
302
|
+
* the same cached accessor as {@link resolveSessionSecret}.
|
|
303
|
+
*/
|
|
304
|
+
async function resolveSessionSecrets(env) {
|
|
305
|
+
return (await sharedSecretsStore(env, authSecretsRegistry)).getVersions(AUTH_SESSION_SECRET);
|
|
306
|
+
}
|
|
189
307
|
/** Resolve the Google OAuth credential pair for this invocation (only call when Google is enabled). */
|
|
190
308
|
async function resolveGoogleCredentials(env) {
|
|
191
309
|
return (await sharedSecretsStore(env, authSecretsRegistry)).get(AUTH_GOOGLE_CREDENTIALS);
|
|
@@ -202,5 +320,9 @@ async function resolveFacebookCredentials(env) {
|
|
|
202
320
|
async function resolveGithubCredentials(env) {
|
|
203
321
|
return (await sharedSecretsStore(env, authSecretsRegistry)).get(AUTH_GITHUB_CREDENTIALS);
|
|
204
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
|
+
}
|
|
205
327
|
//#endregion
|
|
206
|
-
export { AUTH_APPLE_CREDENTIALS, AUTH_FACEBOOK_CREDENTIALS, AUTH_GITHUB_CREDENTIALS, AUTH_GOOGLE_CREDENTIALS, AUTH_SESSION_SECRET, AppleOAuthCredentials, FacebookOAuthCredentials, GithubOAuthCredentials, GoogleOAuthCredentials, authSecretsRegistry, inapplicableProviderSecrets, resolveAppleCredentials, resolveFacebookCredentials, resolveGithubCredentials, resolveGoogleCredentials, resolveSessionSecret };
|
|
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,45 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
/**
|
|
4
|
+
* **The session secret as Better Auth needs it across a rotation (#602): every retained version.**
|
|
5
|
+
*
|
|
6
|
+
* `auth-session-secret` is `rotatable: true`, and an unattended rotation appends a version and keeps the
|
|
7
|
+
* previous one for the overlap. The kit used to hand Better Auth one value — the current one — which made
|
|
8
|
+
* the overlap decorative: the moment the version changed, the JWKS private keys were sealed under a value
|
|
9
|
+
* the instance no longer held. Better Auth 1.7 takes a version set instead (`secrets: [{ version, value }]`,
|
|
10
|
+
* newest first): it encrypts under the first and decrypts under whichever version a ciphertext names
|
|
11
|
+
* (`$ba$<version>$…`, `better-auth/dist/crypto/index.mjs`).
|
|
12
|
+
*
|
|
13
|
+
* **It versions encryption and not signatures.** With `secrets` set, `ctx.secret` is the first entry alone
|
|
14
|
+
* (`context/create-context.mjs:75`), and the session cookie is signed and verified under `ctx.secret`
|
|
15
|
+
* (`cookies/index.mjs:172`). So a cookie signed under the previous version still fails after a rotation;
|
|
16
|
+
* `http/credentialResign.ts` is what verifies it under a retained version and re-signs it.
|
|
17
|
+
*
|
|
18
|
+
* **`secret` is the oldest retained version, and that is deliberate.** With a version set, Better Auth reads
|
|
19
|
+
* `secret` only as the *legacy* secret — the one it tries on a bare ciphertext with no `$ba$` envelope. Every
|
|
20
|
+
* JWKS key written before the kit passed a version set is one of those, sealed under the value that was
|
|
21
|
+
* current then, which is the oldest the envelope still holds. Re-encryption moves them into the envelope;
|
|
22
|
+
* until it has, this is what opens them.
|
|
23
|
+
*/
|
|
24
|
+
/** A secret's retained versions, as `secretsStore(…).getVersions` answers. */
|
|
25
|
+
export interface SessionSecretVersions {
|
|
26
|
+
/** The version key reads resolve to. */
|
|
27
|
+
currentVersion: string;
|
|
28
|
+
/** Every retained version: version key → value. */
|
|
29
|
+
versions: Readonly<Record<string, string>>;
|
|
30
|
+
}
|
|
31
|
+
/** What `betterAuth()` is handed: the version set, newest first, and the legacy secret. */
|
|
32
|
+
export interface BetterAuthSecretOptions {
|
|
33
|
+
/** Every retained version, current first, then the rest newest first. */
|
|
34
|
+
secrets: {
|
|
35
|
+
version: number;
|
|
36
|
+
value: string;
|
|
37
|
+
}[];
|
|
38
|
+
/** The oldest retained version — Better Auth's legacy secret, for a ciphertext sealed before versions existed. */
|
|
39
|
+
secret: string;
|
|
40
|
+
}
|
|
41
|
+
/** The version set and legacy secret for `betterAuth()`. */
|
|
42
|
+
export declare function betterAuthSecrets(versions: SessionSecretVersions): BetterAuthSecretOptions;
|
|
43
|
+
/** Every retained value but the current one, newest first — what a credential signed before a rotation is tried under. */
|
|
44
|
+
export declare function priorSessionSecrets(versions: SessionSecretVersions): string[];
|
|
45
|
+
//# sourceMappingURL=sessionSecrets.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sessionSecrets.d.ts","sourceRoot":"","sources":["../../src/instance/sessionSecrets.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,8EAA8E;AAC9E,MAAM,WAAW,qBAAqB;IACpC,wCAAwC;IACxC,cAAc,EAAE,MAAM,CAAC;IACvB,mDAAmD;IACnD,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CAC5C;AAED,2FAA2F;AAC3F,MAAM,WAAW,uBAAuB;IACtC,yEAAyE;IACzE,OAAO,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC9C,kHAAkH;IAClH,MAAM,EAAE,MAAM,CAAC;CAChB;AAYD,4DAA4D;AAC5D,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,qBAAqB,GAAG,uBAAuB,CAI1F;AAED,0HAA0H;AAC1H,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,qBAAqB,GAAG,MAAM,EAAE,CAI7E"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
//#region src/instance/sessionSecrets.ts
|
|
4
|
+
/** The retained versions, current first and the rest in descending numeric order. */
|
|
5
|
+
function ordered(versions) {
|
|
6
|
+
const prior = Object.entries(versions.versions).filter(([version]) => version !== versions.currentVersion).map(([version, value]) => ({
|
|
7
|
+
version: Number(version),
|
|
8
|
+
value
|
|
9
|
+
})).sort((left, right) => right.version - left.version);
|
|
10
|
+
const current = versions.versions[versions.currentVersion];
|
|
11
|
+
return current === void 0 ? prior : [{
|
|
12
|
+
version: Number(versions.currentVersion),
|
|
13
|
+
value: current
|
|
14
|
+
}, ...prior];
|
|
15
|
+
}
|
|
16
|
+
/** The version set and legacy secret for `betterAuth()`. */
|
|
17
|
+
function betterAuthSecrets(versions) {
|
|
18
|
+
const secrets = ordered(versions);
|
|
19
|
+
return {
|
|
20
|
+
secrets,
|
|
21
|
+
secret: [...secrets].sort((left, right) => left.version - right.version)[0]?.value ?? ""
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** Every retained value but the current one, newest first — what a credential signed before a rotation is tried under. */
|
|
25
|
+
function priorSessionSecrets(versions) {
|
|
26
|
+
return ordered(versions).filter((one) => String(one.version) !== versions.currentVersion).map((one) => one.value);
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
export { betterAuthSecrets, priorSessionSecrets };
|
|
@@ -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,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"}
|