@pithy-sh/auth 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/README.md +12 -2
  2. package/dist/audit/actions.d.ts +21 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +22 -1
  5. package/dist/audit/emit.js +1 -1
  6. package/dist/caller/certificate.d.ts +83 -0
  7. package/dist/caller/certificate.d.ts.map +1 -0
  8. package/dist/caller/certificate.js +92 -0
  9. package/dist/caller/request.d.ts +66 -0
  10. package/dist/caller/request.d.ts.map +1 -0
  11. package/dist/caller/request.js +71 -0
  12. package/dist/caller/token.d.ts +130 -0
  13. package/dist/caller/token.d.ts.map +1 -0
  14. package/dist/caller/token.js +207 -0
  15. package/dist/capability.d.ts +70 -2
  16. package/dist/capability.d.ts.map +1 -1
  17. package/dist/capability.js +28 -7
  18. package/dist/client/lifecycle.d.ts +19 -0
  19. package/dist/client/lifecycle.d.ts.map +1 -0
  20. package/dist/client/lifecycle.js +25 -0
  21. package/dist/client/projection.d.ts +4 -0
  22. package/dist/client/projection.d.ts.map +1 -1
  23. package/dist/data/betterAuth.d.ts +5 -1
  24. package/dist/data/betterAuth.d.ts.map +1 -1
  25. package/dist/data/betterAuth.js +7 -3
  26. package/dist/data/kitFields.d.ts +20 -25
  27. package/dist/data/kitFields.d.ts.map +1 -1
  28. package/dist/data/kitFields.js +28 -32
  29. package/dist/data/tables.d.ts +29 -3
  30. package/dist/data/tables.d.ts.map +1 -1
  31. package/dist/data/tables.js +5 -3
  32. package/dist/data/userLifecycle.d.ts +61 -0
  33. package/dist/data/userLifecycle.d.ts.map +1 -0
  34. package/dist/data/userLifecycle.js +50 -0
  35. package/dist/http/credentialResign.d.ts +46 -0
  36. package/dist/http/credentialResign.d.ts.map +1 -0
  37. package/dist/http/credentialResign.js +203 -0
  38. package/dist/http/errorCallbackUrl.d.ts.map +1 -1
  39. package/dist/http/errorCallbackUrl.js +15 -9
  40. package/dist/http/guards.d.ts +23 -1
  41. package/dist/http/guards.d.ts.map +1 -1
  42. package/dist/http/guards.js +28 -3
  43. package/dist/http/lifecycleGate.d.ts +18 -0
  44. package/dist/http/lifecycleGate.d.ts.map +1 -0
  45. package/dist/http/lifecycleGate.js +75 -0
  46. package/dist/http/middleware.d.ts +5 -0
  47. package/dist/http/middleware.d.ts.map +1 -1
  48. package/dist/http/middleware.js +113 -21
  49. package/dist/http/providerRefusal.d.ts +8 -7
  50. package/dist/http/providerRefusal.d.ts.map +1 -1
  51. package/dist/http/providerRefusal.js +37 -32
  52. package/dist/http/resolve.d.ts.map +1 -1
  53. package/dist/http/resolve.js +23 -5
  54. package/dist/http/routes.d.ts.map +1 -1
  55. package/dist/http/routes.js +20 -1
  56. package/dist/instance/auth.d.ts +1280 -5
  57. package/dist/instance/auth.d.ts.map +1 -1
  58. package/dist/instance/auth.js +59 -4
  59. package/dist/instance/jwksReencryption.d.ts +75 -0
  60. package/dist/instance/jwksReencryption.d.ts.map +1 -0
  61. package/dist/instance/jwksReencryption.js +160 -0
  62. package/dist/instance/microsoftEmail.d.ts +70 -0
  63. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  64. package/dist/instance/microsoftEmail.js +96 -0
  65. package/dist/instance/providerSignInGate.d.ts +14 -12
  66. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  67. package/dist/instance/providerSignInGate.js +23 -20
  68. package/dist/instance/providers.d.ts +7 -5
  69. package/dist/instance/providers.d.ts.map +1 -1
  70. package/dist/instance/providers.js +5 -3
  71. package/dist/instance/secrets.d.ts +232 -4
  72. package/dist/instance/secrets.d.ts.map +1 -1
  73. package/dist/instance/secrets.js +129 -7
  74. package/dist/instance/sessionSecrets.d.ts +45 -0
  75. package/dist/instance/sessionSecrets.d.ts.map +1 -0
  76. package/dist/instance/sessionSecrets.js +29 -0
  77. package/dist/lifecycle/enforce.d.ts +40 -0
  78. package/dist/lifecycle/enforce.d.ts.map +1 -0
  79. package/dist/lifecycle/enforce.js +70 -0
  80. package/dist/lifecycle/hooks.d.ts +53 -0
  81. package/dist/lifecycle/hooks.d.ts.map +1 -0
  82. package/dist/lifecycle/hooks.js +2 -0
  83. package/dist/lifecycle/request.d.ts +15 -0
  84. package/dist/lifecycle/request.d.ts.map +1 -0
  85. package/dist/lifecycle/request.js +27 -0
  86. package/dist/lifecycle/state.d.ts +64 -0
  87. package/dist/lifecycle/state.d.ts.map +1 -0
  88. package/dist/lifecycle/state.js +90 -0
  89. package/dist/lifecycle/transitions.d.ts +132 -0
  90. package/dist/lifecycle/transitions.d.ts.map +1 -0
  91. package/dist/lifecycle/transitions.js +349 -0
  92. package/dist/migrations/0001_init.d.ts.map +1 -1
  93. package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
  94. package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
  95. package/dist/migrations/0003_account_issuer_nullable.js +131 -0
  96. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  97. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  98. package/dist/migrations/0004_user_lifecycle.js +47 -0
  99. package/dist/migrations/set.d.ts +3 -1
  100. package/dist/migrations/set.d.ts.map +1 -1
  101. package/dist/migrations/set.js +6 -2
  102. package/dist/peer.d.ts +4 -0
  103. package/dist/peer.d.ts.map +1 -1
  104. package/dist/test-utils/liveApp.d.ts +26 -0
  105. package/dist/test-utils/liveApp.d.ts.map +1 -1
  106. package/dist/test-utils/liveApp.js +1 -0
  107. package/dist/test-utils/schemaDrift.d.ts +49 -0
  108. package/dist/test-utils/schemaDrift.d.ts.map +1 -0
  109. package/dist/test-utils/schemaDrift.js +35 -0
  110. package/dist/test-utils/scopedBackend.d.ts +204 -0
  111. package/dist/test-utils/scopedBackend.d.ts.map +1 -0
  112. package/dist/test-utils/scopedBackend.js +166 -0
  113. package/dist/version.generated.d.ts +1 -1
  114. package/dist/version.generated.d.ts.map +1 -1
  115. package/dist/version.generated.js +1 -1
  116. package/docs/account-lifecycle.md +105 -0
  117. package/docs/apple-signin.md +7 -1
  118. package/docs/facebook-oauth.md +7 -1
  119. package/docs/github-oauth.md +7 -1
  120. package/docs/google-oauth.md +7 -1
  121. package/docs/microsoft-oauth.md +177 -0
  122. package/docs/server-authoritative.md +182 -0
  123. package/package.json +11 -8
  124. package/pithy.manifest.json +17 -3
  125. package/src/audit/actions.ts +23 -0
  126. package/src/audit/emit.ts +1 -1
  127. package/src/caller/certificate.ts +133 -0
  128. package/src/caller/request.ts +84 -0
  129. package/src/caller/token.ts +276 -0
  130. package/src/capability.ts +170 -38
  131. package/src/client/lifecycle.ts +27 -0
  132. package/src/client/projection.ts +4 -0
  133. package/src/data/betterAuth.ts +23 -2
  134. package/src/data/kitFields.ts +27 -0
  135. package/src/data/tables.ts +4 -2
  136. package/src/data/userLifecycle.ts +80 -0
  137. package/src/http/credentialResign.ts +268 -0
  138. package/src/http/errorCallbackUrl.ts +21 -13
  139. package/src/http/guards.ts +29 -1
  140. package/src/http/lifecycleGate.ts +78 -0
  141. package/src/http/middleware.ts +161 -37
  142. package/src/http/providerRefusal.ts +40 -32
  143. package/src/http/resolve.ts +34 -5
  144. package/src/http/routes.ts +39 -2
  145. package/src/instance/auth.ts +91 -6
  146. package/src/instance/jwksReencryption.ts +206 -0
  147. package/src/instance/microsoftEmail.ts +111 -0
  148. package/src/instance/providerSignInGate.ts +30 -27
  149. package/src/instance/providers.ts +8 -4
  150. package/src/instance/secrets.ts +153 -6
  151. package/src/instance/sessionSecrets.ts +64 -0
  152. package/src/lifecycle/enforce.ts +89 -0
  153. package/src/lifecycle/hooks.ts +54 -0
  154. package/src/lifecycle/request.ts +31 -0
  155. package/src/lifecycle/state.ts +101 -0
  156. package/src/lifecycle/transitions.ts +483 -0
  157. package/src/migrations/0001_init.ts +8 -10
  158. package/src/migrations/0003_account_issuer_nullable.ts +199 -0
  159. package/src/migrations/0004_user_lifecycle.ts +68 -0
  160. package/src/migrations/set.ts +5 -1
  161. package/src/test-utils/liveApp.ts +2 -1
  162. package/src/test-utils/schemaDrift.ts +82 -0
  163. package/src/test-utils/scopedBackend.ts +137 -0
  164. package/src/version.generated.ts +1 -1
@@ -1,7 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import { JsonDate, SQLiteBoolean } from "@pithy-sh/core/src/data/codecs";
4
+ import { JsonDate, SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
5
  import { Locale } from "@pithy-sh/core/src/i18n/locale";
6
6
  import { z } from "zod";
7
7
 
@@ -52,6 +52,26 @@ export const User = z
52
52
  updatedAt: BetterAuthDate.describe(
53
53
  "When the user record was last updated. ISO-8601 text in SQLite; a `Date` in app code.",
54
54
  ),
55
+ // The four lifecycle columns (#620). **Ms-epoch through `SQLiteDate`, not ISO text like their
56
+ // neighbors**, and the difference is who writes them: Better Auth writes every other date on this
57
+ // table, and never these — they are `input: false` and only the kit's lifecycle transitions set
58
+ // them, through the kit's own Kysely. So they take the house convention, and `../data/kitFields.ts`
59
+ // declares them `type: "number"` so Better Auth hands back exactly what is stored.
60
+ //
61
+ // `nullish` rather than `nullable`: a row read before `0004_user_lifecycle` ran has no such key at
62
+ // all, and an absent state is the same fact as a null one — nothing has happened to this account.
63
+ suspendedAt: SQLiteDate.nullish().describe(
64
+ "When this account was suspended, or null when it is not. A suspended account cannot sign in, refresh a token, or act on any route. Ms-epoch in SQLite; a `Date` in app code.",
65
+ ),
66
+ suspendedUntil: SQLiteDate.nullish().describe(
67
+ "When the current suspension ends by itself, or null for one that lasts until an operator reinstates the account. A suspension past this instant is treated as absent, with no write needed to expire it. Ms-epoch in SQLite.",
68
+ ),
69
+ deletedAt: SQLiteDate.nullish().describe(
70
+ "When this account was deleted, or null when it is not. A deleted account cannot sign in or act, and can be restored until `purgeAfter`. Ms-epoch in SQLite.",
71
+ ),
72
+ purgeAfter: SQLiteDate.nullish().describe(
73
+ "When a deleted account's data may be erased — the deletion instant plus `retention.purgeAfterDays`. Null unless the account is deleted. Ms-epoch in SQLite.",
74
+ ),
55
75
  })
56
76
  .describe("A user in `pithy_auth_users` — the canonical identity every session and account hangs off.");
57
77
  export type User = z.output<typeof User>;
@@ -103,8 +123,9 @@ export const Account = z
103
123
  id: z.string().describe("Primary key. A random/UUID text id."),
104
124
  issuer: z
105
125
  .string()
126
+ .nullable()
106
127
  .describe(
107
- "Who asserted this identity, as the identity provider names itself: an OIDC issuer URL (`https://accounts.google.com`), `local:oauth:<id>` for an OAuth provider that publishes none, or `local:credential` for a password. With `accountId` it is the account's identity and carries a unique index — a provider slug is a name this project chose, so two providers pointed at one directory could assert the same `accountId` and land on two rows.",
128
+ "A relic of Better Auth 1.7.0–1.7.2, which identified an account by `(issuer, accountId)` and wrote who asserted the identity here: an OIDC issuer URL, `local:oauth:<id>`, or `local:credential`. 1.7.3 went back to `(providerId, accountId)` and writes nothing here, so a row created since is null. Kept, with the values a Worker migrated under 1.7.1 holds, and read by nothing (#787).",
108
129
  ),
109
130
  accountId: z.string().describe("The provider's stable id for this user (e.g. the Google `sub` claim)."),
110
131
  providerId: z
@@ -29,6 +29,32 @@ import { Locale } from "@pithy-sh/core/src/i18n/locale";
29
29
  * because it has no transactional DDL.
30
30
  */
31
31
 
32
+ /**
33
+ * The account-lifecycle columns on `pithy_auth_users` (#620): whether this account is suspended or
34
+ * deleted, and until when.
35
+ *
36
+ * **Declared here so a session read already carries them.** Better Auth returns every declared field on
37
+ * the user it resolves for a session, so the middleware that fills `AuthContext` reads the account's state
38
+ * off the row it has already loaded — enforcement costs no query and no join. Left out of this object, the
39
+ * columns would exist and every session would read as unrestricted.
40
+ *
41
+ * **`input: false` on all four, and that is the security property.** An account's state is something done
42
+ * *to* it — by an operator, or by its owner through the kit's own deletion route — never a field its
43
+ * holder may write. With `input: true`, one `updateUser({ suspendedAt: null })` would lift a suspension.
44
+ *
45
+ * **`type: "number"`, not `"date"`.** Only the kit writes these, through its own Kysely, in the house
46
+ * ms-epoch convention (`../data/betterAuth.ts` says why they differ from their neighbors). `"date"` would
47
+ * have Better Auth convert what it hands back, and a `"date"` that the adapter believes is ISO text while
48
+ * the column holds an integer is a column that reads back as the wrong thing. As a number it arrives
49
+ * exactly as stored, and `SQLiteDate` decodes it.
50
+ */
51
+ const LIFECYCLE_FIELDS = {
52
+ suspendedAt: { type: "number", required: false, input: false },
53
+ suspendedUntil: { type: "number", required: false, input: false },
54
+ deletedAt: { type: "number", required: false, input: false },
55
+ purgeAfter: { type: "number", required: false, input: false },
56
+ } as const;
57
+
32
58
  /**
33
59
  * The extra `pithy_auth_users` columns.
34
60
  *
@@ -54,6 +80,7 @@ import { Locale } from "@pithy-sh/core/src/i18n/locale";
54
80
  */
55
81
  export const KIT_USER_FIELDS = {
56
82
  locale: { type: "string", required: false, input: true, validator: { input: Locale.nullable() } },
83
+ ...LIFECYCLE_FIELDS,
57
84
  } as const;
58
85
 
59
86
  /**
@@ -7,14 +7,15 @@ import type { Kysely } from "kysely";
7
7
  import { Account, Jwks, RateLimit, Session, User, Verification } from "./betterAuth";
8
8
  import { Device } from "./device";
9
9
  import { RotatedToken } from "./rotatedToken";
10
+ import { UserLifecycleEvent } from "./userLifecycle";
10
11
 
11
12
  /**
12
13
  * The auth capability's table map: camelCase keys, so `CamelCasePlugin` emits the snake_case
13
14
  * `pithy_auth_*` SQL. One source of truth shared by the capability wiring, the Better-Auth instance
14
15
  * (whose Kysely adapter wraps this same Kysely), the device registry, and the migration.
15
16
  *
16
- * The first six tables are Better-Auth-managed; `pithyAuthDevices` and `pithyAuthRotatedTokens` are
17
- * ours. Setting Better Auth's `modelName` to these exact camelCase keys lets the one `CamelCasePlugin`
17
+ * The first six tables are Better-Auth-managed; `pithyAuthDevices`, `pithyAuthRotatedTokens` and
18
+ * `pithyAuthUserLifecycle` are ours. Setting Better Auth's `modelName` to these exact camelCase keys lets the one `CamelCasePlugin`
18
19
  * own the camelCase ↔ snake_case boundary uniformly for both Better Auth's queries and our migration DDL.
19
20
  */
20
21
  export const authTables = {
@@ -26,6 +27,7 @@ export const authTables = {
26
27
  pithyAuthRateLimit: RateLimit,
27
28
  pithyAuthDevices: Device,
28
29
  pithyAuthRotatedTokens: RotatedToken,
30
+ pithyAuthUserLifecycle: UserLifecycleEvent,
29
31
  };
30
32
  export type AuthTables = typeof authTables;
31
33
 
@@ -0,0 +1,80 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ import { z } from "zod";
6
+
7
+ /**
8
+ * `pithy_auth_user_lifecycle` — every transition an account went through, who made it, and why.
9
+ *
10
+ * **The columns on `pithy_auth_users` answer "what is true now"; this table answers "what happened, and who
11
+ * did it".** The two are written together by `../lifecycle/transitions.ts` and never apart. The columns are
12
+ * what enforcement reads on every request, so they hold only the current state; the reason an operator gave
13
+ * for a suspension, and the history of every reinstatement before it, live here.
14
+ *
15
+ * **No foreign key to the user, deliberately.** A purge erases the user row and every row hanging off it, and
16
+ * this table is the one record that must survive it: the trail that the account existed, was deleted, and
17
+ * was erased, by whom and when. A cascade would take the evidence with the subject. So the row names the user
18
+ * by id and holds nothing else about them — no address, no name — and is the only `pithy_auth_*` row a purge
19
+ * leaves behind.
20
+ *
21
+ * Written by the kit through its own Kysely, so its dates take the house ms-epoch `SQLiteDate`.
22
+ */
23
+
24
+ /** What happened to the account. */
25
+ export const UserLifecycleAction = z
26
+ .enum(["suspended", "reinstated", "deleted", "restored", "purge_step", "purged"])
27
+ .describe(
28
+ "The transition: `suspended` and `reinstated`; `deleted` (by an operator, or by the account's owner) and `restored` inside the purge window; `purge_step`, one capability's rows erased during a purge, named in `step`; and `purged`, the erasure finished.",
29
+ );
30
+ export type UserLifecycleAction = z.output<typeof UserLifecycleAction>;
31
+
32
+ /** Who made the transition. */
33
+ export const UserLifecycleActorType = z
34
+ .enum(["control-plane", "user", "system"])
35
+ .describe(
36
+ "Who made the transition: `control-plane` (a management client, under a scoped grant), `user` (the account's own holder, deleting their own account), or `system` (the scheduled purge, with nobody calling).",
37
+ );
38
+ export type UserLifecycleActorType = z.output<typeof UserLifecycleActorType>;
39
+
40
+ /** One transition, as stored. */
41
+ export const UserLifecycleEvent = z
42
+ .object({
43
+ id: z
44
+ .number()
45
+ .int()
46
+ .describe("Primary key. Auto-incrementing, so a user's history reads in the order it was written."),
47
+ userId: z
48
+ .string()
49
+ .describe(
50
+ "The account this happened to. Not a foreign key: the row outlives the user it names, because a purge must leave its own record behind. Indexed.",
51
+ ),
52
+ action: UserLifecycleAction.describe("What happened to the account."),
53
+ actorType: UserLifecycleActorType.describe("Who made the transition."),
54
+ actorId: z
55
+ .string()
56
+ .nullable()
57
+ .describe(
58
+ "The acting principal's id — the user's own id for a self-service deletion, the connection's for a management client. Null for `system`, and for a management client that named none.",
59
+ ),
60
+ reason: z
61
+ .string()
62
+ .nullable()
63
+ .describe(
64
+ "Why, in the words of whoever made the transition. For a suspension this is the sentence the locked-out person is shown, so it is written for them. Null for a transition nobody had to justify — a purge, a self-service deletion.",
65
+ ),
66
+ suspendedUntil: SQLiteDate.nullable().describe(
67
+ "For a `suspended` row, when that suspension ends by itself; null for one that lasts until a reinstatement, and for every other action. Ms-epoch in SQLite.",
68
+ ),
69
+ step: z
70
+ .string()
71
+ .nullable()
72
+ .describe(
73
+ "For a `purge_step` row, the capability whose rows that step erased — the purge's step name. Null for every other action.",
74
+ ),
75
+ createdAt: SQLiteDate.describe("When the transition happened. Ms-epoch in SQLite; a `Date` in app code."),
76
+ })
77
+ .describe(
78
+ "One transition in `pithy_auth_user_lifecycle`: an account suspended, reinstated, deleted, restored or purged, with who did it and why.",
79
+ );
80
+ export type UserLifecycleEvent = z.output<typeof UserLifecycleEvent>;
@@ -0,0 +1,268 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
+ import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
6
+ import type { Context } from "hono";
7
+ import type { AuthInstance } from "../instance/auth";
8
+ import { resolveSessionSecrets } from "../instance/secrets";
9
+ import { priorSessionSecrets } from "../instance/sessionSecrets";
10
+
11
+ /**
12
+ * **A session signed before a rotation, carried across it (#602).**
13
+ *
14
+ * Better Auth signs the session cookie — and the signed token a bearer client holds — with one secret,
15
+ * `ctx.secret`, which is the first entry of the version set and nothing else (`cookies/index.mjs:172`,
16
+ * `plugins/bearer/index.mjs`). So the moment `auth-session-secret` rotates, every credential issued under
17
+ * the previous version fails verification, and everyone is signed out at once. The overlap the registry
18
+ * declares would protect nothing.
19
+ *
20
+ * This closes that gap in front of Better Auth: before a request reaches it, a credential that fails under
21
+ * the current version and verifies under a **retained** prior one is re-signed under the current version.
22
+ * Better Auth then sees a credential it accepts, and the response carries the re-signed one back — a
23
+ * `Set-Cookie` for a browser, `set-auth-token` for a bearer client — so the next request needs no help.
24
+ *
25
+ * **It extends no trust.** A credential is re-signed only when it verifies under a version this deployment
26
+ * still holds, which is exactly the set Better Auth would accept if it verified signatures by version. The
27
+ * session it names is still looked up, still expired, still revoked by Better Auth as before. And the
28
+ * window closes on its own: once the rotation retires the previous version, nothing verifies under it.
29
+ *
30
+ * **The session's lifetime is the overlap.** A session in use is re-signed on its next request, inside the
31
+ * overlap; one not used for the whole overlap has expired anyway, because `auth-session-secret`'s overlap
32
+ * is declared at least as long as `sessionExpiresIn`, which slides on use.
33
+ */
34
+
35
+ /** HMAC-SHA256 under `secret`, in standard base64 — the 44 characters better-call writes and checks. */
36
+ async function signature(value: string, secret: string): Promise<string> {
37
+ const key = await crypto.subtle.importKey(
38
+ "raw",
39
+ new TextEncoder().encode(secret),
40
+ { name: "HMAC", hash: "SHA-256" },
41
+ false,
42
+ ["sign"],
43
+ );
44
+ const bytes = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(value)));
45
+ let binary = "";
46
+ for (const byte of bytes) binary += String.fromCharCode(byte);
47
+ return btoa(binary);
48
+ }
49
+
50
+ /** Constant-time comparison of two strings of equal length; unequal lengths are unequal. */
51
+ function sameSignature(left: string, right: string): boolean {
52
+ if (left.length !== right.length) return false;
53
+ let difference = 0;
54
+ for (let index = 0; index < left.length; index++) difference |= left.charCodeAt(index) ^ right.charCodeAt(index);
55
+ return difference === 0;
56
+ }
57
+
58
+ /** Sign `value` the way better-call's `signCookieValue` does, before its URL encoding: `value.signature`. */
59
+ export async function signCredential(value: string, secret: string): Promise<string> {
60
+ return `${value}.${await signature(value, secret)}`;
61
+ }
62
+
63
+ /**
64
+ * Which of `keys` a signed credential verifies under, by index, and the value it signs — or `null` when it
65
+ * is not a signed credential or verifies under none. Takes the decoded form, `value.signature`.
66
+ */
67
+ export async function verifyCredential(
68
+ signed: string,
69
+ keys: readonly string[],
70
+ ): Promise<{ value: string; key: number } | null> {
71
+ const dot = signed.lastIndexOf(".");
72
+ if (dot < 1) return null;
73
+ const value = signed.slice(0, dot);
74
+ const presented = signed.slice(dot + 1);
75
+ if (presented.length !== 44 || !presented.endsWith("=")) return null;
76
+ for (let index = 0; index < keys.length; index++) {
77
+ const key = keys[index] as string;
78
+ if (sameSignature(await signature(value, key), presented)) return { value, key: index };
79
+ }
80
+ return null;
81
+ }
82
+
83
+ /** `decodeURIComponent`, answering the input itself when it is not valid percent-encoding. */
84
+ function decoded(text: string): string {
85
+ try {
86
+ return decodeURIComponent(text);
87
+ } catch {
88
+ return text;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Re-sign under `current` whichever of a credential's two forms was signed under a key in `prior`.
94
+ *
95
+ * Takes the decoded credential and answers the re-signed one, or `null` when it verifies under the current
96
+ * key already, under no key at all, or is not a signed credential.
97
+ */
98
+ async function carried(signed: string, keys: { current: string; prior: readonly string[] }): Promise<string | null> {
99
+ const verified = await verifyCredential(signed, [keys.current, ...keys.prior]);
100
+ if (verified === null || verified.key === 0) return null;
101
+ return await signCredential(verified.value, keys.current);
102
+ }
103
+
104
+ /** What was re-signed: the request's new headers, each re-signed cookie, and the re-signed bearer credential. */
105
+ export interface ResignedCredentials {
106
+ /** The request headers with every re-signed credential in place of the one that arrived. */
107
+ headers: Headers;
108
+ /** Each cookie re-signed, by name, with its new value in decoded form. */
109
+ cookies: { name: string; value: string }[];
110
+ /** The bearer credential re-signed, in decoded form, when one was. */
111
+ bearer?: string;
112
+ }
113
+
114
+ /**
115
+ * Re-sign every credential in `headers` that verifies under a prior key: the cookies named in `names`, and
116
+ * a signed bearer token. Answers `null` when nothing needed it — including always when there is no prior
117
+ * key, so a deployment that has never rotated parses nothing.
118
+ */
119
+ export async function resignCredentials(
120
+ headers: Headers,
121
+ keys: { current: string; prior: readonly string[] },
122
+ names: readonly string[],
123
+ ): Promise<ResignedCredentials | null> {
124
+ if (keys.prior.length === 0) return null;
125
+ const cookies: { name: string; value: string }[] = [];
126
+ let bearer: string | undefined;
127
+
128
+ const header = headers.get("cookie");
129
+ let cookieHeader = header;
130
+ if (header !== null) {
131
+ const parts = header.split(";").map((part) => part.trim());
132
+ const rewritten = await Promise.all(
133
+ parts.map(async (part) => {
134
+ const equals = part.indexOf("=");
135
+ if (equals < 1) return part;
136
+ const name = part.slice(0, equals);
137
+ if (!names.includes(name)) return part;
138
+ const fresh = await carried(decoded(part.slice(equals + 1)), keys);
139
+ if (fresh === null) return part;
140
+ cookies.push({ name, value: fresh });
141
+ return `${name}=${encodeURIComponent(fresh)}`;
142
+ }),
143
+ );
144
+ cookieHeader = rewritten.join("; ");
145
+ }
146
+
147
+ const authorization = headers.get("authorization");
148
+ let authorizationHeader = authorization;
149
+ if (authorization !== null && authorization.slice(0, 7).toLowerCase() === "bearer ") {
150
+ const token = decoded(authorization.slice(7).trim());
151
+ // A raw token carries no signature to carry: Better Auth signs one itself, under the current version.
152
+ const fresh = token.includes(".") ? await carried(token, keys) : null;
153
+ if (fresh !== null) {
154
+ bearer = fresh;
155
+ authorizationHeader = `Bearer ${fresh}`;
156
+ }
157
+ }
158
+
159
+ if (cookies.length === 0 && bearer === undefined) return null;
160
+ const next = new Headers(headers);
161
+ if (cookieHeader !== null) next.set("cookie", cookieHeader);
162
+ if (authorizationHeader !== null) next.set("authorization", authorizationHeader);
163
+ return { headers: next, cookies, ...(bearer === undefined ? {} : { bearer }) };
164
+ }
165
+
166
+ /** A cookie's attributes as Better Auth states them on `authCookies.<name>.attributes`. */
167
+ interface CookieAttributes {
168
+ path?: string;
169
+ domain?: string;
170
+ secure?: boolean;
171
+ httpOnly?: boolean;
172
+ sameSite?: string;
173
+ partitioned?: boolean;
174
+ }
175
+
176
+ /** One `Set-Cookie` value, with the attributes Better Auth itself would have written. */
177
+ function setCookie(name: string, value: string, attributes: CookieAttributes, maxAge: number | undefined): string {
178
+ const parts = [`${name}=${encodeURIComponent(value)}`];
179
+ if (maxAge !== undefined) parts.push(`Max-Age=${Math.floor(maxAge)}`);
180
+ if (attributes.domain) parts.push(`Domain=${attributes.domain}`);
181
+ parts.push(`Path=${attributes.path ?? "/"}`);
182
+ if (attributes.httpOnly) parts.push("HttpOnly");
183
+ if (attributes.secure || attributes.partitioned) parts.push("Secure");
184
+ if (attributes.sameSite) {
185
+ parts.push(`SameSite=${attributes.sameSite.charAt(0).toUpperCase()}${attributes.sameSite.slice(1).toLowerCase()}`);
186
+ }
187
+ if (attributes.partitioned) parts.push("Partitioned");
188
+ return parts.join("; ");
189
+ }
190
+
191
+ /**
192
+ * The credentials this request needs re-signed, with the instance context their cookies are written from —
193
+ * or `null` when there is no prior version, or nothing to re-sign.
194
+ */
195
+ async function resignedFor(c: Context<PithyHonoEnv>, instance: AuthInstance) {
196
+ const versions = await resolveSessionSecrets(c.env as unknown as SecretsStoreEnv);
197
+ const current = versions.versions[versions.currentVersion];
198
+ const prior = priorSessionSecrets(versions);
199
+ if (current === undefined || prior.length === 0) return null;
200
+ const context = await instance.$context;
201
+ const names = [context.authCookies.sessionToken.name, context.authCookies.dontRememberToken.name];
202
+ const resigned = await resignCredentials(c.req.raw.headers, { current, prior }, names);
203
+ return resigned === null ? null : { resigned, context };
204
+ }
205
+
206
+ /**
207
+ * Carry this request's credentials across a rotation, then run the rest of the chain, then hand the
208
+ * re-signed credentials back on the response.
209
+ *
210
+ * Swaps `c.req.raw` for a request carrying the re-signed credentials, so the session middleware, the auth
211
+ * handler and every route that reads the request see one consistent set. A response that already sets the
212
+ * cookie — a sign-out, a refresh — keeps its own; this only fills the silence.
213
+ */
214
+ export async function withResignedCredentials(
215
+ c: Context<PithyHonoEnv>,
216
+ instance: AuthInstance,
217
+ next: () => Promise<void>,
218
+ ): Promise<void> {
219
+ // A failure to read the version set is not this function's to raise: the request goes on with the
220
+ // credential it arrived with, and Better Auth answers it exactly as it would have.
221
+ const prepared = await resignedFor(c, instance).catch(() => null);
222
+ if (prepared === null) return await next();
223
+ const { resigned, context } = prepared;
224
+ const session = context.authCookies.sessionToken;
225
+ const dontRemember = context.authCookies.dontRememberToken;
226
+
227
+ c.req.raw = new Request(c.req.raw, { headers: resigned.headers });
228
+ await next();
229
+
230
+ const response = new Response(c.res.body, c.res);
231
+ const setting = response.headers.getSetCookie().map((line) => line.slice(0, line.indexOf("=")));
232
+ // A remembered session's cookie lasts the session's lifetime; a "don't remember me" one ends with the
233
+ // browser, which is what the companion cookie's presence says. Either way it is what Better Auth writes.
234
+ const remembered = !(resigned.headers.get("cookie") ?? "")
235
+ .split(";")
236
+ .some((part) => part.trim().startsWith(`${dontRemember.name}=`));
237
+ for (const cookie of resigned.cookies) {
238
+ if (setting.includes(cookie.name)) continue;
239
+ const isSession = cookie.name === session.name;
240
+ const attributes = (isSession ? session.attributes : dontRemember.attributes) as CookieAttributes;
241
+ response.headers.append(
242
+ "set-cookie",
243
+ setCookie(
244
+ cookie.name,
245
+ cookie.value,
246
+ attributes,
247
+ isSession && remembered ? context.sessionConfig.expiresIn : undefined,
248
+ ),
249
+ );
250
+ }
251
+ if (resigned.bearer !== undefined && !response.headers.has("set-auth-token")) {
252
+ response.headers.set("set-auth-token", encodeURIComponent(resigned.bearer));
253
+ const exposed = new Set(
254
+ (response.headers.get("access-control-expose-headers") ?? "")
255
+ .split(",")
256
+ .map((header) => header.trim())
257
+ .filter(Boolean),
258
+ );
259
+ exposed.add("set-auth-token");
260
+ response.headers.set("access-control-expose-headers", [...exposed].join(", "));
261
+ }
262
+ // Cleared first, because Hono's `res` setter copies every header of the response it replaces onto the new
263
+ // one: `set-cookie` wholesale, which would drop each re-signed cookie whenever the route set any cookie of
264
+ // its own, and every other header by overwrite, which would put the route's expose list back over ours.
265
+ // `response` already carries all of them.
266
+ c.res = undefined;
267
+ c.res = response;
268
+ }
@@ -18,22 +18,28 @@ import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyEr
18
18
  * | 1 | `…?error=access_denied` | read the *first* `error`, which the caller had planted |
19
19
  * | 2 | `…/sign-in#x` | the appended `error=` landed inside the fragment; `searchParams` saw nothing |
20
20
  *
21
- * The third shape is the diagnosis rather than another entry. `better-auth`'s `redirectOnError`
22
- * (`dist/api/routes/callback.mjs:78`) is string concatenation that never parses:
21
+ * The third shape is the diagnosis rather than another entry. At 1.7.1, `better-auth`'s `redirectOnError`
22
+ * (`dist/api/routes/callback.mjs:78`) was string concatenation that never parsed:
23
23
  *
24
24
  * ```js
25
25
  * const url = `${baseURL}${baseURL.includes("?") ? "&" : "?"}${params.toString()}`;
26
26
  * ```
27
27
  *
28
28
  * and `baseURL` there is `errorURL`, which `oauth2/state.mjs:27` stored as the caller's raw string. So the
29
- * collapse parses the output of a concatenation performed without regard to URL structure, and **every
30
- * input shape where concatenation and parsing disagree is a new bypass.** `#x` was the third; a fourth
31
- * exists for as long as the caller chooses the string being concatenated. Patching the parser again finds
32
- * it later, from a report, rather than now.
29
+ * collapse parsed the output of a construction the caller steered, and **every input shape where that
30
+ * construction and parsing disagree is a new bypass.** `#x` was the third; a fourth exists for as long as
31
+ * the caller chooses the string being built on. Patching the parser again finds it later, from a report,
32
+ * rather than now.
33
+ *
34
+ * At 1.7.11 the line is `appendQueryParams(baseURL, params)`, from `@better-auth/core`'s
35
+ * `dist/utils/url.mjs:40`. It parses the input, sets the query before any fragment, and throws on a `//`
36
+ * or `/\` input. That closes the fragment shape inside the dependency and leaves the planted `error`
37
+ * open, since the existing query is kept as text. The guard does not lean on either fact. The argument
38
+ * above is about who chooses the string, and that has not changed.
33
39
  *
34
40
  * ## The invariant this module holds
35
41
  *
36
- * By the time `redirectOnError` concatenates, `errorURL` is **a URL the kit produced**:
42
+ * By the time `redirectOnError` appends to it, `errorURL` is **a URL the kit produced**:
37
43
  *
38
44
  * - no fragment — not a populated one, and not a bare trailing `#` either, which has an empty
39
45
  * `URL.hash` and still swallows everything appended after it;
@@ -41,7 +47,7 @@ import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyEr
41
47
  * - a `?` in it **iff** it carries a query, so appending `?k=v` or `&k=v` — whichever the dependency
42
48
  * picks — yields exactly one readable query either way.
43
49
  *
44
- * Then the concatenation is predictable by construction, and the collapse is reading a string this
50
+ * Then the append is predictable by construction, under raw concatenation or a parse, and the collapse is reading a string this
45
51
  * capability wrote rather than one an attacker composed.
46
52
  *
47
53
  * ## Refused, never quietly rewritten
@@ -64,7 +70,7 @@ import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyEr
64
70
  *
65
71
  * Every request through `handleBetterAuth` carrying an `errorCallbackURL` is guarded — `/sign-in/social`,
66
72
  * `/link-social`, `/sign-in/magic-link`. Deciding *per route* which of the dependency's code paths parse
67
- * the value and which concatenate it is exactly the out-guessing above, and it is a claim that goes stale
73
+ * the value and which build on it raw is exactly the out-guessing above, and it is a claim that goes stale
68
74
  * on the next bump. One field, one rule. (An adopter whose error screen is a hash route passes it as a
69
75
  * query parameter instead; the kit's own templates already do.)
70
76
  *
@@ -181,13 +187,15 @@ function refuse(value: string, why: string): never {
181
187
  export function normalizeErrorCallbackURL(value: string, requestUrl: string): string {
182
188
  if (value === "") {
183
189
  // Better Auth skips its own origin check on a falsy value (`errorCallbackURL && validateURL(…)`) and
184
- // then stores it with `??`, not `||` — so `""` survives as the error URL and the redirect becomes a
185
- // bare `?error=<code>` resolved against the callback's own path. There is no URL to produce from it.
190
+ // then stores it with `??`, not `||` — so `""` survives as the error URL. At 1.7.1 the redirect became
191
+ // a bare `?error=<code>` resolved against the callback's own path; at 1.7.11 the append's parse
192
+ // throws on it. There is no URL to produce from it either way.
186
193
  refuse(value, "it is empty");
187
194
  }
188
195
  // **The raw string, not `URL.hash`.** `http://host/sign-in#` parses with an empty hash and is still the
189
- // bypass: the dependency concatenates the string it was given, so `…#` + `?error=x` puts the code
190
- // inside a fragment that `URL` then reports as `#?error=x`. Any `#` at all disqualifies the value; one
196
+ // bypass under raw concatenation, which is what 1.7.1 did: `…#` + `?error=x` puts the code inside a
197
+ // fragment that `URL` then reports as `#?error=x`. 1.7.11 parses first, and this check does not
198
+ // rely on it. Any `#` at all disqualifies the value; one
191
199
  // that is meant literally survives as `%23`, which is not a fragment and is not this check's business.
192
200
  if (value.includes("#")) {
193
201
  refuse(value, "it carries a fragment, and an `error` appended after a `#` is never read as a query");
@@ -29,7 +29,7 @@ import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/sc
29
29
  * every legitimate management call, permanently, and **no credential could fix it** — there is no user
30
30
  * to sign in as. `controlPlaneIsolation.workers.test.ts` pins both directions of that separation.
31
31
  *
32
- * ## Five scopes, because these are five different blast radii
32
+ * ## Eight scopes, because these are eight different blast radii
33
33
  *
34
34
  * The temptation is one `auth:admin` flag, and on this capability it is the most dangerous version of
35
35
  * that mistake. **Reading a user is a privacy operation; revoking their sessions is an availability
@@ -92,9 +92,34 @@ export const AUTH_USERS_LOGOUT_SCOPE: ControlPlaneScope = "auth:users:logout";
92
92
  */
93
93
  export const AUTH_DEVICES_REVOKE_SCOPE: ControlPlaneScope = "auth:devices:revoke";
94
94
 
95
+ /**
96
+ * Suspend an account and reinstate it (#620, the routes in #621). Ending somebody's access is an availability
97
+ * operation on one person, and reversible — which is what separates it from deleting them, and why it is
98
+ * granted apart from both reading them and erasing them.
99
+ */
100
+ export const AUTH_USERS_SUSPEND_SCOPE: ControlPlaneScope = "auth:users:suspend";
101
+
102
+ /**
103
+ * Delete an account, restore one inside its purge window, and start a purge (#620, the routes in #622). The
104
+ * one scope on this surface whose worst case cannot be undone: once the window closes, the person's rows are
105
+ * gone from every capability that held them.
106
+ */
107
+ export const AUTH_USERS_DELETE_SCOPE: ControlPlaneScope = "auth:users:delete";
108
+
109
+ /**
110
+ * Export everything the kit holds about one account — the answer to an access request (#620, the route in
111
+ * #622). A disclosure, and a far larger one than reading the user: it carries every capability's rows about
112
+ * them, so it is granted on its own and audited as one.
113
+ */
114
+ export const AUTH_USERS_EXPORT_SCOPE: ControlPlaneScope = "auth:users:export";
115
+
95
116
  /**
96
117
  * Every control-plane scope auth defines — what `pithy dashboard connect` offers for this capability,
97
118
  * and the list a manifest or a doc quotes rather than re-typing.
119
+ *
120
+ * **The three lifecycle scopes are declared before the routes that require them.** The suspend, delete and
121
+ * export routes land in #621 and #622; declaring the vocabulary here, once, is what lets those issues build on
122
+ * one name each rather than three issues each choosing their own.
98
123
  */
99
124
  export const AUTH_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
100
125
  AUTH_USERS_READ_SCOPE,
@@ -102,6 +127,9 @@ export const AUTH_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
102
127
  AUTH_SESSIONS_REVOKE_SCOPE,
103
128
  AUTH_USERS_LOGOUT_SCOPE,
104
129
  AUTH_DEVICES_REVOKE_SCOPE,
130
+ AUTH_USERS_SUSPEND_SCOPE,
131
+ AUTH_USERS_DELETE_SCOPE,
132
+ AUTH_USERS_EXPORT_SCOPE,
105
133
  ];
106
134
 
107
135
  /**