@pithy-sh/auth 0.8.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 (85) 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/credentialResign.d.ts +46 -0
  19. package/dist/http/credentialResign.d.ts.map +1 -0
  20. package/dist/http/credentialResign.js +203 -0
  21. package/dist/http/errorCallbackUrl.d.ts.map +1 -1
  22. package/dist/http/errorCallbackUrl.js +15 -9
  23. package/dist/http/middleware.d.ts.map +1 -1
  24. package/dist/http/middleware.js +66 -15
  25. package/dist/http/providerRefusal.d.ts +8 -7
  26. package/dist/http/providerRefusal.d.ts.map +1 -1
  27. package/dist/http/providerRefusal.js +29 -32
  28. package/dist/http/resolve.d.ts.map +1 -1
  29. package/dist/http/resolve.js +18 -3
  30. package/dist/instance/auth.d.ts +1225 -2
  31. package/dist/instance/auth.d.ts.map +1 -1
  32. package/dist/instance/auth.js +6 -2
  33. package/dist/instance/jwksReencryption.d.ts +75 -0
  34. package/dist/instance/jwksReencryption.d.ts.map +1 -0
  35. package/dist/instance/jwksReencryption.js +160 -0
  36. package/dist/instance/providerSignInGate.d.ts +7 -6
  37. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  38. package/dist/instance/providerSignInGate.js +16 -14
  39. package/dist/instance/secrets.d.ts +168 -1
  40. package/dist/instance/secrets.d.ts.map +1 -1
  41. package/dist/instance/secrets.js +86 -3
  42. package/dist/instance/sessionSecrets.d.ts +45 -0
  43. package/dist/instance/sessionSecrets.d.ts.map +1 -0
  44. package/dist/instance/sessionSecrets.js +29 -0
  45. package/dist/migrations/0001_init.d.ts.map +1 -1
  46. package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
  47. package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
  48. package/dist/migrations/0003_account_issuer_nullable.js +131 -0
  49. package/dist/migrations/set.d.ts +2 -1
  50. package/dist/migrations/set.d.ts.map +1 -1
  51. package/dist/migrations/set.js +4 -2
  52. package/dist/test-utils/liveApp.d.ts +5 -0
  53. package/dist/test-utils/liveApp.d.ts.map +1 -1
  54. package/dist/test-utils/schemaDrift.d.ts +49 -0
  55. package/dist/test-utils/schemaDrift.d.ts.map +1 -0
  56. package/dist/test-utils/schemaDrift.js +35 -0
  57. package/dist/test-utils/scopedBackend.d.ts +183 -0
  58. package/dist/test-utils/scopedBackend.d.ts.map +1 -0
  59. package/dist/test-utils/scopedBackend.js +160 -0
  60. package/dist/version.generated.d.ts +1 -1
  61. package/dist/version.generated.js +1 -1
  62. package/docs/server-authoritative.md +182 -0
  63. package/package.json +11 -8
  64. package/src/caller/certificate.ts +133 -0
  65. package/src/caller/request.ts +84 -0
  66. package/src/caller/token.ts +276 -0
  67. package/src/capability.ts +65 -4
  68. package/src/data/betterAuth.ts +2 -1
  69. package/src/http/credentialResign.ts +268 -0
  70. package/src/http/errorCallbackUrl.ts +21 -13
  71. package/src/http/middleware.ts +100 -35
  72. package/src/http/providerRefusal.ts +30 -32
  73. package/src/http/resolve.ts +27 -3
  74. package/src/http/routes.ts +1 -1
  75. package/src/instance/auth.ts +22 -4
  76. package/src/instance/jwksReencryption.ts +206 -0
  77. package/src/instance/providerSignInGate.ts +23 -21
  78. package/src/instance/secrets.ts +94 -1
  79. package/src/instance/sessionSecrets.ts +64 -0
  80. package/src/migrations/0001_init.ts +8 -10
  81. package/src/migrations/0003_account_issuer_nullable.ts +199 -0
  82. package/src/migrations/set.ts +3 -1
  83. package/src/test-utils/schemaDrift.ts +82 -0
  84. package/src/test-utils/scopedBackend.ts +136 -0
  85. package/src/version.generated.ts +1 -1
@@ -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");
@@ -5,8 +5,10 @@ import type { PithyHonoEnv, PithyMiddleware } from "@pithy-sh/core/src/capabilit
5
5
  import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
6
6
  import { AuthContext } from "@pithy-sh/core/src/http/authContext";
7
7
  import { isLocale } from "@pithy-sh/core/src/i18n/locale";
8
- import type { MiddlewareHandler } from "hono";
9
- import type { AuthWiring } from "../capability";
8
+ import type { Context, MiddlewareHandler } from "hono";
9
+ import type { AuthWiring, ScopeResolver, ScopeResolverSession } from "../capability";
10
+ import type { AuthInstance } from "../instance/auth";
11
+ import { withResignedCredentials } from "./credentialResign";
10
12
  import { getAuthInstance } from "./resolve";
11
13
 
12
14
  /**
@@ -22,47 +24,110 @@ function authenticatedDate(session: unknown): Date | null {
22
24
  return value instanceof Date ? value : null;
23
25
  }
24
26
 
27
+ /**
28
+ * The scopes this request's caller resolves to — what the adopter's resolver answered, or `[]`.
29
+ *
30
+ * **Closed on every failure, and never fatal** (#560). A resolver that throws or rejects, and one that answers
31
+ * something other than a list of strings, both leave the request with no scopes and a warning: a gate then
32
+ * refuses it as it would any untrusted caller, rather than the request becoming a 500 or — worse — a
33
+ * malformed answer reaching a guard that would read `includes` off a string. Validated through
34
+ * `AuthContext`'s own field, so this and the context the middleware publishes cannot disagree on the shape.
35
+ *
36
+ * The warning names the session and never the answer: whatever the resolver handed back is the adopter's,
37
+ * and a log is not where to learn what a caller was trusted with.
38
+ */
39
+ async function resolvedScopes(
40
+ c: Context<PithyHonoEnv>,
41
+ resolve: ScopeResolver | undefined,
42
+ session: ScopeResolverSession,
43
+ ): Promise<string[]> {
44
+ if (resolve === undefined) return [];
45
+ let answer: unknown;
46
+ try {
47
+ answer = await resolve(c, session);
48
+ } catch (error) {
49
+ c.var.log.child("auth").warn("resolveScopes failed; this request carries no scopes", {
50
+ sessionId: session.sessionId,
51
+ reason: error instanceof Error ? error.message : String(error),
52
+ });
53
+ return [];
54
+ }
55
+ const parsed = AuthContext.shape.scopes.safeParse(answer);
56
+ if (!parsed.success || answer === undefined) {
57
+ c.var.log
58
+ .child("auth")
59
+ .warn("resolveScopes answered something that is not a list of strings; this request carries no scopes", {
60
+ sessionId: session.sessionId,
61
+ });
62
+ return [];
63
+ }
64
+ return parsed.data;
65
+ }
66
+
25
67
  export function createSessionMiddleware(wiring: AuthWiring): PithyMiddleware {
26
68
  return (app) => {
27
69
  app.use("*", async (c, next) => {
28
- const headers = c.req.raw.headers;
29
- if (headers.has("authorization") || headers.has("cookie")) {
30
- try {
31
- const instance = await getAuthInstance(c, wiring);
32
- const session = await instance.api.getSession({ headers });
33
- if (session) {
34
- // `locale` comes off the user row the session lookup already loaded, so publishing it
35
- // costs nothing — and it is the `user` link of `@pithy-sh/i18n`'s server chain, the one
36
- // that makes a reader's stored choice outrank their device's `Accept-Language`. Read
37
- // through `AuthContext.parse`, so a column holding something that is not a tag lands as
38
- // `undefined` rather than reaching `Intl`.
39
- const stored = (session.user as { locale?: unknown }).locale;
40
- c.set(
41
- "auth",
42
- AuthContext.parse({
43
- userId: session.user.id,
44
- sessionId: session.session.id,
45
- scopes: [],
46
- locale: typeof stored === "string" && isLocale(stored) ? stored : null,
47
- // Published for the same reason `locale` is: the session lookup has already loaded the
48
- // row, so a gate that needs it should not pay for a second read. The adapter hands back
49
- // a `Date`; a session predating the column hands back null, which reads as "cannot say".
50
- // Guarded like `locale` beside it, and for a worse failure: `z.date()` throws on a
51
- // string, the catch below swallows it, and every authenticated request in the Worker
52
- // becomes anonymous — a total outage presenting as "everyone is logged out".
53
- authenticatedAt: authenticatedDate(session.session),
54
- }),
55
- );
56
- }
57
- } catch {
58
- // Leave `auth` null; the credential was missing/invalid.
59
- }
70
+ if (!c.req.raw.headers.has("authorization") && !c.req.raw.headers.has("cookie")) return await next();
71
+ // A credential signed under a session secret this deployment has since rotated is re-signed under the
72
+ // current one before anything reads it (#602), and the re-signed one rides back on the response. A
73
+ // failure building the instance is not this middleware's to raise, so it is left to the routes.
74
+ let instance: AuthInstance | undefined;
75
+ try {
76
+ instance = await getAuthInstance(c, wiring);
77
+ } catch {
78
+ instance = undefined;
60
79
  }
61
- await next();
80
+ if (instance === undefined) return await next();
81
+ const built = instance;
82
+ await withResignedCredentials(c, built, async () => {
83
+ await resolveSession(c, wiring, built);
84
+ await next();
85
+ });
62
86
  });
63
87
  };
64
88
  }
65
89
 
90
+ /** Fill `c.var.auth` from the request's credential, or leave it null. Never throws. */
91
+ async function resolveSession(c: Context<PithyHonoEnv>, wiring: AuthWiring, instance: AuthInstance): Promise<void> {
92
+ const headers = c.req.raw.headers;
93
+ try {
94
+ const session = await instance.api.getSession({ headers });
95
+ if (session) {
96
+ // Before the context is built, so a resolver sees the request exactly as it arrived and the
97
+ // context is published once, whole. Per request and never cached: the answer is about this
98
+ // request's caller, and a cached one is a revocation that has not taken effect (#560).
99
+ const scopes = await resolvedScopes(c, wiring.resolveScopes, {
100
+ userId: session.user.id,
101
+ sessionId: session.session.id,
102
+ });
103
+ // `locale` comes off the user row the session lookup already loaded, so publishing it
104
+ // costs nothing — and it is the `user` link of `@pithy-sh/i18n`'s server chain, the one
105
+ // that makes a reader's stored choice outrank their device's `Accept-Language`. Read
106
+ // through `AuthContext.parse`, so a column holding something that is not a tag lands as
107
+ // `undefined` rather than reaching `Intl`.
108
+ const stored = (session.user as { locale?: unknown }).locale;
109
+ c.set(
110
+ "auth",
111
+ AuthContext.parse({
112
+ userId: session.user.id,
113
+ sessionId: session.session.id,
114
+ scopes,
115
+ locale: typeof stored === "string" && isLocale(stored) ? stored : null,
116
+ // Published for the same reason `locale` is: the session lookup has already loaded the
117
+ // row, so a gate that needs it should not pay for a second read. The adapter hands back
118
+ // a `Date`; a session predating the column hands back null, which reads as "cannot say".
119
+ // Guarded like `locale` beside it, and for a worse failure: `z.date()` throws on a
120
+ // string, the catch below swallows it, and every authenticated request in the Worker
121
+ // becomes anonymous — a total outage presenting as "everyone is logged out".
122
+ authenticatedAt: authenticatedDate(session.session),
123
+ }),
124
+ );
125
+ }
126
+ } catch {
127
+ // Leave `auth` null; the credential was missing/invalid.
128
+ }
129
+ }
130
+
66
131
  /**
67
132
  * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
68
133
  * not filled (no valid credential) with a `PithyError` `auth/invalid_token` (401).