@pithy-sh/auth 0.7.0 → 0.9.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 (108) hide show
  1. package/README.md +4 -0
  2. package/dist/caller/certificate.d.ts +83 -0
  3. package/dist/caller/certificate.d.ts.map +1 -0
  4. package/dist/caller/certificate.js +92 -0
  5. package/dist/caller/request.d.ts +66 -0
  6. package/dist/caller/request.d.ts.map +1 -0
  7. package/dist/caller/request.js +71 -0
  8. package/dist/caller/token.d.ts +130 -0
  9. package/dist/caller/token.d.ts.map +1 -0
  10. package/dist/caller/token.js +207 -0
  11. package/dist/capability.d.ts +44 -1
  12. package/dist/capability.d.ts.map +1 -1
  13. package/dist/capability.js +7 -4
  14. package/dist/data/betterAuth.d.ts +1 -1
  15. package/dist/data/betterAuth.d.ts.map +1 -1
  16. package/dist/data/betterAuth.js +1 -1
  17. package/dist/data/tables.d.ts +1 -1
  18. package/dist/http/adminRoutes.d.ts.map +1 -1
  19. package/dist/http/adminRoutes.js +39 -8
  20. package/dist/http/credentialResign.d.ts +46 -0
  21. package/dist/http/credentialResign.d.ts.map +1 -0
  22. package/dist/http/credentialResign.js +203 -0
  23. package/dist/http/devLoginRoute.d.ts.map +1 -1
  24. package/dist/http/devLoginRoute.js +12 -5
  25. package/dist/http/errorCallbackUrl.d.ts.map +1 -1
  26. package/dist/http/errorCallbackUrl.js +15 -9
  27. package/dist/http/middleware.d.ts.map +1 -1
  28. package/dist/http/middleware.js +66 -15
  29. package/dist/http/providerRefusal.d.ts +8 -7
  30. package/dist/http/providerRefusal.d.ts.map +1 -1
  31. package/dist/http/providerRefusal.js +29 -32
  32. package/dist/http/resolve.d.ts.map +1 -1
  33. package/dist/http/resolve.js +18 -3
  34. package/dist/http/responses.d.ts +52 -0
  35. package/dist/http/responses.d.ts.map +1 -1
  36. package/dist/http/responses.js +25 -1
  37. package/dist/http/routes.d.ts.map +1 -1
  38. package/dist/http/routes.js +60 -9
  39. package/dist/http/schemas.d.ts +1 -1
  40. package/dist/http/schemas.js +1 -1
  41. package/dist/instance/auth.d.ts +1225 -2
  42. package/dist/instance/auth.d.ts.map +1 -1
  43. package/dist/instance/auth.js +6 -2
  44. package/dist/instance/jwksReencryption.d.ts +75 -0
  45. package/dist/instance/jwksReencryption.d.ts.map +1 -0
  46. package/dist/instance/jwksReencryption.js +160 -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 +16 -14
  50. package/dist/instance/providers.d.ts.map +1 -1
  51. package/dist/instance/providers.js +2 -1
  52. package/dist/instance/secrets.d.ts +168 -1
  53. package/dist/instance/secrets.d.ts.map +1 -1
  54. package/dist/instance/secrets.js +86 -3
  55. package/dist/instance/sessionSecrets.d.ts +45 -0
  56. package/dist/instance/sessionSecrets.d.ts.map +1 -0
  57. package/dist/instance/sessionSecrets.js +29 -0
  58. package/dist/migrations/0001_init.d.ts.map +1 -1
  59. package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
  60. package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
  61. package/dist/migrations/0003_account_issuer_nullable.js +131 -0
  62. package/dist/migrations/set.d.ts +2 -1
  63. package/dist/migrations/set.d.ts.map +1 -1
  64. package/dist/migrations/set.js +4 -2
  65. package/dist/seeds/devSession.d.ts.map +1 -1
  66. package/dist/seeds/devSession.js +2 -1
  67. package/dist/test-utils/liveApp.d.ts +5 -0
  68. package/dist/test-utils/liveApp.d.ts.map +1 -1
  69. package/dist/test-utils/liveApp.js +3 -3
  70. package/dist/test-utils/schemaDrift.d.ts +49 -0
  71. package/dist/test-utils/schemaDrift.d.ts.map +1 -0
  72. package/dist/test-utils/schemaDrift.js +35 -0
  73. package/dist/test-utils/scopedBackend.d.ts +183 -0
  74. package/dist/test-utils/scopedBackend.d.ts.map +1 -0
  75. package/dist/test-utils/scopedBackend.js +160 -0
  76. package/dist/version.generated.d.ts +1 -1
  77. package/dist/version.generated.js +1 -1
  78. package/docs/server-authoritative.md +182 -0
  79. package/package.json +14 -11
  80. package/src/caller/certificate.ts +133 -0
  81. package/src/caller/request.ts +84 -0
  82. package/src/caller/token.ts +276 -0
  83. package/src/capability.ts +65 -4
  84. package/src/data/betterAuth.ts +2 -1
  85. package/src/http/adminRoutes.ts +46 -10
  86. package/src/http/credentialResign.ts +268 -0
  87. package/src/http/devLoginRoute.ts +19 -6
  88. package/src/http/errorCallbackUrl.ts +21 -13
  89. package/src/http/middleware.ts +100 -35
  90. package/src/http/providerRefusal.ts +30 -32
  91. package/src/http/resolve.ts +27 -3
  92. package/src/http/responses.ts +54 -0
  93. package/src/http/routes.ts +97 -11
  94. package/src/http/schemas.ts +1 -1
  95. package/src/instance/auth.ts +22 -4
  96. package/src/instance/jwksReencryption.ts +206 -0
  97. package/src/instance/providerSignInGate.ts +23 -21
  98. package/src/instance/providers.ts +2 -1
  99. package/src/instance/secrets.ts +94 -1
  100. package/src/instance/sessionSecrets.ts +64 -0
  101. package/src/migrations/0001_init.ts +8 -10
  102. package/src/migrations/0003_account_issuer_nullable.ts +199 -0
  103. package/src/migrations/set.ts +3 -1
  104. package/src/seeds/devSession.ts +2 -1
  105. package/src/test-utils/liveApp.ts +8 -6
  106. package/src/test-utils/schemaDrift.ts +82 -0
  107. package/src/test-utils/scopedBackend.ts +136 -0
  108. package/src/version.generated.ts +1 -1
@@ -1,13 +1,13 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import { zValidator } from "@hono/zod-validator";
5
4
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
6
5
  import type { ControlPlaneContext } from "@pithy-sh/core/src/controlPlane/context";
7
6
  import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
8
7
  import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
9
8
  import { InternalError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
10
- import { validationHook } from "@pithy-sh/core/src/http/validation";
9
+ import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
10
+ import { validate } from "@pithy-sh/core/src/http/validation";
11
11
  import type { Context, Hono } from "hono";
12
12
  import {
13
13
  type AdminSubList,
@@ -33,7 +33,7 @@ import {
33
33
  AUTH_USERS_READ_SCOPE,
34
34
  } from "./guards";
35
35
  import { getAuthInstance, resolveDb } from "./resolve";
36
- import type {
36
+ import {
37
37
  AdminDeviceRevokeResponse,
38
38
  AdminDevicesResponse,
39
39
  AdminRevokeResponse,
@@ -179,8 +179,14 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
179
179
 
180
180
  app.get(
181
181
  `${base}/admin/users`,
182
+ describeRoute({
183
+ summary: "Page through the users, newest first, optionally searching by email or name.",
184
+ verification: "control-plane",
185
+ scopes: [AUTH_USERS_READ_SCOPE],
186
+ responses: { 200: AdminUsersResponse },
187
+ }),
182
188
  requireControlPlane(AUTH_USERS_READ_SCOPE),
183
- zValidator("query", ListUsersQuery, validationHook),
189
+ validate("query", ListUsersQuery),
184
190
  async (c) => {
185
191
  const query = c.req.valid("query");
186
192
  const caller = controlPlaneCaller(c);
@@ -204,8 +210,14 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
204
210
 
205
211
  app.get(
206
212
  `${base}/admin/users/:userId`,
213
+ describeRoute({
214
+ summary: "Read one user with their sessions, devices and linked providers.",
215
+ verification: "control-plane",
216
+ scopes: [AUTH_USERS_READ_SCOPE],
217
+ responses: { 200: AdminUserResponse },
218
+ }),
207
219
  requireControlPlane(AUTH_USERS_READ_SCOPE),
208
- zValidator("param", UserIdParam, validationHook),
220
+ validate("param", UserIdParam),
209
221
  async (c) => {
210
222
  const { userId } = c.req.valid("param");
211
223
  const caller = controlPlaneCaller(c);
@@ -254,8 +266,14 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
254
266
 
255
267
  app.get(
256
268
  `${base}/admin/devices`,
269
+ describeRoute({
270
+ summary: "Page through the device registry, most recently seen first.",
271
+ verification: "control-plane",
272
+ scopes: [AUTH_DEVICES_READ_SCOPE],
273
+ responses: { 200: AdminDevicesResponse },
274
+ }),
257
275
  requireControlPlane(AUTH_DEVICES_READ_SCOPE),
258
- zValidator("query", ListDevicesQuery, validationHook),
276
+ validate("query", ListDevicesQuery),
259
277
  async (c) => {
260
278
  const query = c.req.valid("query");
261
279
  const caller = controlPlaneCaller(c);
@@ -278,8 +296,14 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
278
296
 
279
297
  app.post(
280
298
  `${base}/admin/sessions/revoke`,
299
+ describeRoute({
300
+ summary: "Revoke one session by its id.",
301
+ verification: "control-plane",
302
+ scopes: [AUTH_SESSIONS_REVOKE_SCOPE],
303
+ responses: { 200: AdminRevokeResponse },
304
+ }),
281
305
  requireControlPlane(AUTH_SESSIONS_REVOKE_SCOPE),
282
- zValidator("json", RevokeSessionBody, validationHook),
306
+ validate("json", RevokeSessionBody),
283
307
  async (c) => {
284
308
  const { sessionId } = c.req.valid("json");
285
309
  const caller = controlPlaneCaller(c);
@@ -309,8 +333,14 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
309
333
 
310
334
  app.post(
311
335
  `${base}/admin/users/:userId/sessions/revoke`,
336
+ describeRoute({
337
+ summary: "Sign one user out everywhere.",
338
+ verification: "control-plane",
339
+ scopes: [AUTH_USERS_LOGOUT_SCOPE],
340
+ responses: { 200: AdminRevokeResponse },
341
+ }),
312
342
  requireControlPlane(AUTH_USERS_LOGOUT_SCOPE),
313
- zValidator("param", UserIdParam, validationHook),
343
+ validate("param", UserIdParam),
314
344
  async (c) => {
315
345
  const { userId } = c.req.valid("param");
316
346
  const caller = controlPlaneCaller(c);
@@ -335,9 +365,15 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
335
365
 
336
366
  app.post(
337
367
  `${base}/admin/users/:userId/devices/revoke`,
368
+ describeRoute({
369
+ summary: "Sign out one of a user's devices and remove it from the registry.",
370
+ verification: "control-plane",
371
+ scopes: [AUTH_DEVICES_REVOKE_SCOPE],
372
+ responses: { 200: AdminDeviceRevokeResponse },
373
+ }),
338
374
  requireControlPlane(AUTH_DEVICES_REVOKE_SCOPE),
339
- zValidator("param", UserIdParam, validationHook),
340
- zValidator("json", RevokeDeviceBody, validationHook),
375
+ validate("param", UserIdParam),
376
+ validate("json", RevokeDeviceBody),
341
377
  async (c) => {
342
378
  const { userId } = c.req.valid("param");
343
379
  const { deviceId } = c.req.valid("json");
@@ -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
+ }
@@ -1,12 +1,14 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import { zValidator } from "@hono/zod-validator";
5
4
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
+ import { commandName, pithyCommand } from "@pithy-sh/core/src/cli/command";
6
6
  import { type AmbientEnv, ambientEnv, compositionEnvironment } from "@pithy-sh/core/src/env/ambient";
7
7
  import { isContinuousIntegration } from "@pithy-sh/core/src/env/ci";
8
8
  import { NotFoundError } from "@pithy-sh/core/src/error/pithyError";
9
- import { validationHook } from "@pithy-sh/core/src/http/validation";
9
+ import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
10
+ import { validate } from "@pithy-sh/core/src/http/validation";
11
+ import { LOCAL_ENVIRONMENT } from "@pithy-sh/core/src/naming/environment";
10
12
  import { DEV_LOGIN_CLAIM_PARAM, DEV_LOGIN_ROUTE } from "@pithy-sh/core/src/seed/devLogin";
11
13
  import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
12
14
  import type { Context, Hono } from "hono";
@@ -65,8 +67,19 @@ export function registerDevLoginRoute(
65
67
  if (isContinuousIntegration(env)) return;
66
68
  // The claim is read here rather than inside the handler: `c.req.valid` is typed off the chain it was
67
69
  // declared on, and a handler taking a bare `Context` has no validator to read from.
68
- app.get(DEV_LOGIN_ROUTE, zValidator("query", DevLoginQuery, validationHook), (c) =>
69
- serveDevLogin(c, wiring, c.req.valid("query")[DEV_LOGIN_CLAIM_PARAM]),
70
+ app.get(
71
+ DEV_LOGIN_ROUTE,
72
+ describeRoute({
73
+ summary: "Sign the browser in as the seeded dev user.",
74
+ description:
75
+ "Mounted only in a `dev` composition outside CI. It takes no credential: the signed claim `pithy seed` wrote into the URL is the whole of what it checks.",
76
+ verification: "public",
77
+ responses: {
78
+ 302: { description: "Signed in: sets the session cookie and redirects to `/`." },
79
+ },
80
+ }),
81
+ validate("query", DevLoginQuery),
82
+ (c) => serveDevLogin(c, wiring, c.req.valid("query")[DEV_LOGIN_CLAIM_PARAM]),
70
83
  );
71
84
  };
72
85
  }
@@ -86,7 +99,7 @@ export function registerDevLoginRoute(
86
99
  */
87
100
  function noSeededSession(): NotFoundError {
88
101
  return new NotFoundError({
89
- message: "No dev login has been seeded for this environment. Run pithy seed, then open this URL again.",
102
+ message: `No dev login has been seeded for this environment. Run ${pithyCommand("seed", { flags: { "--env": LOCAL_ENVIRONMENT } })}, then open this URL again.`,
90
103
  });
91
104
  }
92
105
 
@@ -162,7 +175,7 @@ async function serveDevLogin(
162
175
  createdAt: now,
163
176
  updatedAt: now,
164
177
  ipAddress: "127.0.0.1",
165
- userAgent: "pithy dev login",
178
+ userAgent: `${commandName("dev")} login`,
166
179
  deviceId: null,
167
180
  familyId: null,
168
181
  // A dev login is a real sign-in, so it is authenticated now — what the live hook stamps.
@@ -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");