@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
@@ -17,22 +17,28 @@ import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyEr
17
17
  * | 1 | `…?error=access_denied` | read the *first* `error`, which the caller had planted |
18
18
  * | 2 | `…/sign-in#x` | the appended `error=` landed inside the fragment; `searchParams` saw nothing |
19
19
  *
20
- * The third shape is the diagnosis rather than another entry. `better-auth`'s `redirectOnError`
21
- * (`dist/api/routes/callback.mjs:78`) is string concatenation that never parses:
20
+ * The third shape is the diagnosis rather than another entry. At 1.7.1, `better-auth`'s `redirectOnError`
21
+ * (`dist/api/routes/callback.mjs:78`) was string concatenation that never parsed:
22
22
  *
23
23
  * ```js
24
24
  * const url = `${baseURL}${baseURL.includes("?") ? "&" : "?"}${params.toString()}`;
25
25
  * ```
26
26
  *
27
27
  * and `baseURL` there is `errorURL`, which `oauth2/state.mjs:27` stored as the caller's raw string. So the
28
- * collapse parses the output of a concatenation performed without regard to URL structure, and **every
29
- * input shape where concatenation and parsing disagree is a new bypass.** `#x` was the third; a fourth
30
- * exists for as long as the caller chooses the string being concatenated. Patching the parser again finds
31
- * it later, from a report, rather than now.
28
+ * collapse parsed the output of a construction the caller steered, and **every input shape where that
29
+ * construction and parsing disagree is a new bypass.** `#x` was the third; a fourth exists for as long as
30
+ * the caller chooses the string being built on. Patching the parser again finds it later, from a report,
31
+ * rather than now.
32
+ *
33
+ * At 1.7.11 the line is `appendQueryParams(baseURL, params)`, from `@better-auth/core`'s
34
+ * `dist/utils/url.mjs:40`. It parses the input, sets the query before any fragment, and throws on a `//`
35
+ * or `/\` input. That closes the fragment shape inside the dependency and leaves the planted `error`
36
+ * open, since the existing query is kept as text. The guard does not lean on either fact. The argument
37
+ * above is about who chooses the string, and that has not changed.
32
38
  *
33
39
  * ## The invariant this module holds
34
40
  *
35
- * By the time `redirectOnError` concatenates, `errorURL` is **a URL the kit produced**:
41
+ * By the time `redirectOnError` appends to it, `errorURL` is **a URL the kit produced**:
36
42
  *
37
43
  * - no fragment — not a populated one, and not a bare trailing `#` either, which has an empty
38
44
  * `URL.hash` and still swallows everything appended after it;
@@ -40,7 +46,7 @@ import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyEr
40
46
  * - a `?` in it **iff** it carries a query, so appending `?k=v` or `&k=v` — whichever the dependency
41
47
  * picks — yields exactly one readable query either way.
42
48
  *
43
- * Then the concatenation is predictable by construction, and the collapse is reading a string this
49
+ * Then the append is predictable by construction, under raw concatenation or a parse, and the collapse is reading a string this
44
50
  * capability wrote rather than one an attacker composed.
45
51
  *
46
52
  * ## Refused, never quietly rewritten
@@ -63,7 +69,7 @@ import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyEr
63
69
  *
64
70
  * Every request through `handleBetterAuth` carrying an `errorCallbackURL` is guarded — `/sign-in/social`,
65
71
  * `/link-social`, `/sign-in/magic-link`. Deciding *per route* which of the dependency's code paths parse
66
- * the value and which concatenate it is exactly the out-guessing above, and it is a claim that goes stale
72
+ * the value and which build on it raw is exactly the out-guessing above, and it is a claim that goes stale
67
73
  * on the next bump. One field, one rule. (An adopter whose error screen is a hash route passes it as a
68
74
  * query parameter instead; the kit's own templates already do.)
69
75
  *
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/http/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAI9F,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAgBhD,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CAuC3E;AAED;;;GAGG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAU7D"}
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/http/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAI9F,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,KAAK,EAAE,UAAU,EAAuC,MAAM,eAAe,CAAC;AA0DrF,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CAqB3E;AA2CD;;;GAGG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAU7D"}
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { getAuthInstance } from "./resolve.js";
4
+ import { withResignedCredentials } from "./credentialResign.js";
4
5
  import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
5
6
  import { isLocale } from "@pithy-sh/core/src/i18n/locale";
6
7
  import { AuthContext } from "@pithy-sh/core/src/http/authContext";
@@ -17,27 +18,77 @@ function authenticatedDate(session) {
17
18
  const value = session.authenticatedAt;
18
19
  return value instanceof Date ? value : null;
19
20
  }
21
+ /**
22
+ * The scopes this request's caller resolves to — what the adopter's resolver answered, or `[]`.
23
+ *
24
+ * **Closed on every failure, and never fatal** (#560). A resolver that throws or rejects, and one that answers
25
+ * something other than a list of strings, both leave the request with no scopes and a warning: a gate then
26
+ * refuses it as it would any untrusted caller, rather than the request becoming a 500 or — worse — a
27
+ * malformed answer reaching a guard that would read `includes` off a string. Validated through
28
+ * `AuthContext`'s own field, so this and the context the middleware publishes cannot disagree on the shape.
29
+ *
30
+ * The warning names the session and never the answer: whatever the resolver handed back is the adopter's,
31
+ * and a log is not where to learn what a caller was trusted with.
32
+ */
33
+ async function resolvedScopes(c, resolve, session) {
34
+ if (resolve === void 0) return [];
35
+ let answer;
36
+ try {
37
+ answer = await resolve(c, session);
38
+ } catch (error) {
39
+ c.var.log.child("auth").warn("resolveScopes failed; this request carries no scopes", {
40
+ sessionId: session.sessionId,
41
+ reason: error instanceof Error ? error.message : String(error)
42
+ });
43
+ return [];
44
+ }
45
+ const parsed = AuthContext.shape.scopes.safeParse(answer);
46
+ if (!parsed.success || answer === void 0) {
47
+ c.var.log.child("auth").warn("resolveScopes answered something that is not a list of strings; this request carries no scopes", { sessionId: session.sessionId });
48
+ return [];
49
+ }
50
+ return parsed.data;
51
+ }
20
52
  function createSessionMiddleware(wiring) {
21
53
  return (app) => {
22
54
  app.use("*", async (c, next) => {
23
- const headers = c.req.raw.headers;
24
- if (headers.has("authorization") || headers.has("cookie")) try {
25
- const session = await (await getAuthInstance(c, wiring)).api.getSession({ headers });
26
- if (session) {
27
- const stored = session.user.locale;
28
- c.set("auth", AuthContext.parse({
29
- userId: session.user.id,
30
- sessionId: session.session.id,
31
- scopes: [],
32
- locale: typeof stored === "string" && isLocale(stored) ? stored : null,
33
- authenticatedAt: authenticatedDate(session.session)
34
- }));
35
- }
36
- } catch {}
37
- await next();
55
+ if (!c.req.raw.headers.has("authorization") && !c.req.raw.headers.has("cookie")) return await next();
56
+ let instance;
57
+ try {
58
+ instance = await getAuthInstance(c, wiring);
59
+ } catch {
60
+ instance = void 0;
61
+ }
62
+ if (instance === void 0) return await next();
63
+ const built = instance;
64
+ await withResignedCredentials(c, built, async () => {
65
+ await resolveSession(c, wiring, built);
66
+ await next();
67
+ });
38
68
  });
39
69
  };
40
70
  }
71
+ /** Fill `c.var.auth` from the request's credential, or leave it null. Never throws. */
72
+ async function resolveSession(c, wiring, instance) {
73
+ const headers = c.req.raw.headers;
74
+ try {
75
+ const session = await instance.api.getSession({ headers });
76
+ if (session) {
77
+ const scopes = await resolvedScopes(c, wiring.resolveScopes, {
78
+ userId: session.user.id,
79
+ sessionId: session.session.id
80
+ });
81
+ const stored = session.user.locale;
82
+ c.set("auth", AuthContext.parse({
83
+ userId: session.user.id,
84
+ sessionId: session.session.id,
85
+ scopes,
86
+ locale: typeof stored === "string" && isLocale(stored) ? stored : null,
87
+ authenticatedAt: authenticatedDate(session.session)
88
+ }));
89
+ }
90
+ } catch {}
91
+ }
41
92
  /**
42
93
  * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
43
94
  * not filled (no valid credential) with a `PithyError` `auth/invalid_token` (401).
@@ -39,11 +39,11 @@
39
39
  *
40
40
  * | Code | Emitted only when |
41
41
  * | --- | --- |
42
- * | `account_not_linked` | a user row **did** match (`better-auth/dist/oauth2/link-account.mjs:86`) |
43
- * | `signup_disabled` | **no** row matched (`:202`) |
42
+ * | `account_not_linked` | a user row **did** match (`better-auth/dist/oauth2/link-account.mjs:142`) |
43
+ * | `signup_disabled` | **no** row matched (`:257`) |
44
44
  *
45
45
  * Both leave through one line — `redirectOnError(result.error.split(" ").join("_"))`,
46
- * `dist/api/routes/callback.mjs:245` — so from outside the Worker they are one question with two
46
+ * `dist/api/routes/callback.mjs:197` — so from outside the Worker they are one question with two
47
47
  * answers. Press the provider button, read the `Location` header, repeat: an account-enumeration oracle
48
48
  * needing one GitHub account, no account on the target, and no page render. It works against the
49
49
  * configuration the kit's own security guidance recommends (`allowSignUp: false`, #554), so the
@@ -74,9 +74,10 @@
74
74
  * ## This module is the second line of defense, not the only one
75
75
  *
76
76
  * It reads the `Location` a refused callback answered with — which is the output of
77
- * `redirectOnError`'s raw string concatenation (`callback.mjs:78`), performed on a value the caller
78
- * supplied. It was walked around twice that way, and the second bypass was the diagnosis: **every input
79
- * shape where that concatenation and this parsing disagree is another one**, so patching the parsing
77
+ * `redirectOnError` (`callback.mjs:78`), built on a value the caller supplied. 1.7.1 concatenated it raw;
78
+ * 1.7.11 parses it with `new URL` in `@better-auth/core`'s `appendQueryParams`, which sets the query
79
+ * before any fragment and throws on a `//` or `/\` input. It was walked around twice on 1.7.1, and the second bypass
80
+ * was the diagnosis: **every input shape where that construction and this parsing disagree is another one**, so patching the parsing
80
81
  * again only moves the report later. `./errorCallbackUrl` therefore guards the value on the way *in*,
81
82
  * and by the time this module runs the string being parsed is one the kit produced.
82
83
  *
@@ -157,7 +158,7 @@ export interface CollapsedRefusal {
157
158
  *
158
159
  * - **It need not be absolute.** `api/middlewares/origin-check.mjs` passes `allowRelativePaths: true`,
159
160
  * `matchesOriginPattern` admits `/path?query`, `oauth2/state.mjs` stores the value as a bare
160
- * `z.string().optional()`, and `redirectOnError` concatenates it raw. So a relative `Location` is a
161
+ * `z.string().optional()`, and `redirectOnError` keeps it root-relative. So a relative `Location` is a
161
162
  * supported answer, and returning `undefined` to one sent the true code to the browser and wrote no
162
163
  * audit row.
163
164
  * - **`error` need not be the only one.** `redirectOnError` *appends* `&error=<code>`. An
@@ -1 +1 @@
1
- {"version":3,"file":"providerRefusal.d.ts","sourceRoot":"","sources":["../../src/http/providerRefusal.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4FG;AAEH;;;;;;;GAOG;AACH,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AAEnE,yFAAyF;AACzF,UAAU,cAAc;IACtB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,yFAAyF;IACzF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAoLD,qGAAqG;AACrG,eAAO,MAAM,sBAAsB,EAAE,SAAS,MAAM,EAE5B,CAAC;AAEzB,gFAAgF;AAChF,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAA6B,CAAC;AAE3G,yFAAyF;AACzF,MAAM,WAAW,gBAAgB;IAC/B,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,gBAAgB,GAAG,SAAS,CA0D5G"}
1
+ {"version":3,"file":"providerRefusal.d.ts","sourceRoot":"","sources":["../../src/http/providerRefusal.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6FG;AAEH;;;;;;;GAOG;AACH,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AAEnE,yFAAyF;AACzF,UAAU,cAAc;IACtB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,yFAAyF;IACzF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAiLD,qGAAqG;AACrG,eAAO,MAAM,sBAAsB,EAAE,SAAS,MAAM,EAE5B,CAAC;AAEzB,gFAAgF;AAChF,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAA6B,CAAC;AAE3G,yFAAyF;AACzF,MAAM,WAAW,gBAAgB;IAC/B,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,gBAAgB,GAAG,SAAS,CA0D5G"}
@@ -40,11 +40,11 @@
40
40
  *
41
41
  * | Code | Emitted only when |
42
42
  * | --- | --- |
43
- * | `account_not_linked` | a user row **did** match (`better-auth/dist/oauth2/link-account.mjs:86`) |
44
- * | `signup_disabled` | **no** row matched (`:202`) |
43
+ * | `account_not_linked` | a user row **did** match (`better-auth/dist/oauth2/link-account.mjs:142`) |
44
+ * | `signup_disabled` | **no** row matched (`:257`) |
45
45
  *
46
46
  * Both leave through one line — `redirectOnError(result.error.split(" ").join("_"))`,
47
- * `dist/api/routes/callback.mjs:245` — so from outside the Worker they are one question with two
47
+ * `dist/api/routes/callback.mjs:197` — so from outside the Worker they are one question with two
48
48
  * answers. Press the provider button, read the `Location` header, repeat: an account-enumeration oracle
49
49
  * needing one GitHub account, no account on the target, and no page render. It works against the
50
50
  * configuration the kit's own security guidance recommends (`allowSignUp: false`, #554), so the
@@ -75,9 +75,10 @@
75
75
  * ## This module is the second line of defense, not the only one
76
76
  *
77
77
  * It reads the `Location` a refused callback answered with — which is the output of
78
- * `redirectOnError`'s raw string concatenation (`callback.mjs:78`), performed on a value the caller
79
- * supplied. It was walked around twice that way, and the second bypass was the diagnosis: **every input
80
- * shape where that concatenation and this parsing disagree is another one**, so patching the parsing
78
+ * `redirectOnError` (`callback.mjs:78`), built on a value the caller supplied. 1.7.1 concatenated it raw;
79
+ * 1.7.11 parses it with `new URL` in `@better-auth/core`'s `appendQueryParams`, which sets the query
80
+ * before any fragment and throws on a `//` or `/\` input. It was walked around twice on 1.7.1, and the second bypass
81
+ * was the diagnosis: **every input shape where that construction and this parsing disagree is another one**, so patching the parsing
81
82
  * again only moves the report later. `./errorCallbackUrl` therefore guards the value on the way *in*,
82
83
  * and by the time this module runs the string being parsed is one the kit produced.
83
84
  *
@@ -110,7 +111,7 @@ const NEUTRAL_PROVIDER_REFUSAL = "provider_sign_in_refused";
110
111
  * `providerRefusal.test.ts` reads Better Auth's own `OAUTH_CALLBACK_ERROR_CODES`, scans the
111
112
  * `result.error` literals out of `link-account.mjs`, and scans the `new APIError(…, { code })` sites in
112
113
  * both codebases — `better-auth`'s on the callback's path and the kit's across this whole package,
113
- * because `callback.mjs:239` re-emits *anything* thrown inside `handleOAuthUserInfo` as `?error=`. Every
114
+ * because `callback.mjs:192` re-emits *anything* thrown inside `handleOAuthUserInfo` as `?error=`. Every
114
115
  * code any of them can produce must appear here. A dependency bump that adds one turns that red, and
115
116
  * somebody writes a verdict for it. So the roster records a *review*, and the review cannot silently fall
116
117
  * behind the thing it reviews.
@@ -126,11 +127,11 @@ const NEUTRAL_PROVIDER_REFUSAL = "provider_sign_in_refused";
126
127
  const PROVIDER_REFUSAL_VERDICTS = {
127
128
  account_not_linked: {
128
129
  collapse: true,
129
- why: "link-account.mjs:86 — returned only inside `if (dbUser)`, so it is literally the statement that a row matched."
130
+ why: "link-account.mjs:142 — returned only inside `if (dbUser)`, so it is literally the statement that a row matched."
130
131
  },
131
132
  signup_disabled: {
132
133
  collapse: true,
133
- why: "link-account.mjs:202 — the `else` of that same branch, so it is literally the statement that none did."
134
+ why: "link-account.mjs:257 — the `else` of that same branch, so it is literally the statement that none did."
134
135
  },
135
136
  EMAIL_NOT_VERIFIED: {
136
137
  collapse: true,
@@ -138,15 +139,19 @@ const PROVIDER_REFUSAL_VERDICTS = {
138
139
  },
139
140
  unable_to_create_user: {
140
141
  collapse: true,
141
- why: "link-account.mjs:254 — the create path only, so it sits on the no-row side exactly as `signup_disabled` does. A fault rather than a refusal, and still an answer to the question being asked."
142
+ why: "link-account.mjs:301/308 — the create path only, so it sits on the no-row side exactly as `signup_disabled` does. A fault rather than a refusal, and still an answer to the question being asked."
142
143
  },
143
144
  INVALID_PROFILE_FIELD: {
144
145
  collapse: true,
145
- why: "The kit's `user.update.before` hook, and **the branch it sits on was read wrong the first time.** `if (dbUser) {` opens at link-account.mjs:77 and the `if (!linkedAccount) {…} else {…}` pair sits *inside* it, so the ownership argument that carries `unable_to_update_account` does not reach here: the `updateUser` that can carry a provider's `name`/`image` is the `overrideUserInfo` write at :185, which runs after **either** sub-branch — including the one that has just linked an account that did not exist a line earlier. What every path to it does share is `if (dbUser)`: a matched row. The other side of that branch calls `createUser`, where the kit's `user.create.before` **sanitizes** the same two fields instead of refusing them. So a hostile provider display name answers `?error=INVALID_PROFILE_FIELD` against an address that has a row and a completed sign-in against one that does not, which is the oracle with a different name on it."
146
+ why: "The kit's `user.update.before` hook, and **the branch it sits on was read wrong the first time.** `if (dbUser) {` opens at link-account.mjs:133 and the `if (!linkedAccount) {…} else {…}` pair sits *inside* it, so the ownership argument that carries `unable_to_update_account` does not reach here: the `updateUser` writes that can carry a provider's `name`/`image` are the `overrideUserInfo` write at :238, which runs after **either** sub-branch, and since 1.7.3 the `updateUserInfoOnLink` write at :189 on the branch that has just linked an account that did not exist a line earlier. What every path to it does share is `if (dbUser)`: a matched row. The other side of that branch calls `createUser`, where the kit's `user.create.before` **sanitizes** the same two fields instead of refusing them. So a hostile provider display name answers `?error=INVALID_PROFILE_FIELD` against an address that has a row and a completed sign-in against one that does not, which is the oracle with a different name on it."
146
147
  },
147
148
  validation_context_missing: {
148
149
  collapse: true,
149
- why: "internal-adapter.mjs:160 — raised when `getCurrentAuthContext()` fails inside `createUser`, and `createUser` is the no-row side. `updateUser` runs no such check (internal-adapter.mjs:599), so this code cannot be observed against an address that has a row: it is `signup_disabled`'s shape reached through the adopter's `validateUserInfo` option rather than through the sign-up policy."
150
+ why: "internal-adapter.mjs:160 — raised when `getCurrentAuthContext()` fails inside `createUser`, and `createUser` is the no-row side. `updateUser` runs no such check (internal-adapter.mjs:616), so this code cannot be observed against an address that has a row: it is `signup_disabled`'s shape reached through the adopter's `validateUserInfo` option rather than through the sign-up policy."
151
+ },
152
+ unable_to_link_account: {
153
+ collapse: true,
154
+ why: "Two producers, and the verdict follows the one that reads our rows. `linkOAuthAccount` (link-account.mjs:45/68) answers it on `/link-social`, where the caller is signed in as the user being changed. But `handleOAuthUserInfo` answers it too, inside `if (dbUser)` when the account write fails (:171/:184), so on the social callback it says a row matched, and `unable_to_create_user` is its other half. Collapsing costs the signed-in linker a specific code for a fault. Letting it travel would cost the oracle. Corrected in #787; the earlier verdict read only the link flow."
150
155
  },
151
156
  no_code: {
152
157
  collapse: false,
@@ -158,7 +163,7 @@ const PROVIDER_REFUSAL_VERDICTS = {
158
163
  },
159
164
  invalid_callback_request: {
160
165
  collapse: false,
161
- why: "callback.mjs:55 — the callback's own query or body would not parse. Raised before `parseState`, so nothing had been read from anywhere yet."
166
+ why: "callback.mjs:54 — the callback's own query or body would not parse. Raised before `parseState`, so nothing had been read from anywhere yet."
162
167
  },
163
168
  oauth_provider_not_found: {
164
169
  collapse: false,
@@ -190,15 +195,15 @@ const PROVIDER_REFUSAL_VERDICTS = {
190
195
  },
191
196
  email_not_verified: {
192
197
  collapse: false,
193
- why: "Better Auth's lower-case code, from `requireEmailVerification` (link-account.mjs:263) — which the kit does not set. Reachable for a registering and a returning user alike, so it names no row either way. Not to be confused with the kit's upper-case `EMAIL_NOT_VERIFIED` above; the two are different strings from different places and only one of them is the oracle."
198
+ why: "Better Auth's lower-case code, from `requireEmailVerification` (link-account.mjs:317) — which the kit does not set. Reachable for a registering and a returning user alike, so it names no row either way. Not to be confused with the kit's upper-case `EMAIL_NOT_VERIFIED` above; the two are different strings from different places and only one of them is the oracle."
194
199
  },
195
200
  unable_to_create_session: {
196
201
  collapse: false,
197
- why: "link-account.mjs:269 — after the user is resolved, so it is reached from both sides of the branch equally."
202
+ why: "link-account.mjs:324 — after the user is resolved, so it is reached from both sides of the branch equally."
198
203
  },
199
204
  state_not_found: {
200
205
  collapse: false,
201
- why: "The request carried no state to parse. Raised at state.mjs:90, before any lookup."
206
+ why: "The request carried no state to parse. Raised at state.mjs:93, before any lookup."
202
207
  },
203
208
  state_mismatch: {
204
209
  collapse: false,
@@ -222,7 +227,7 @@ const PROVIDER_REFUSAL_VERDICTS = {
222
227
  },
223
228
  account_hook_binding_conflict: {
224
229
  collapse: false,
225
- why: "link-account.mjs:120/176/237 — a hook moved the account binding out from under the write that had just been made. Raised on the link path, the sign-in path *and* the create path, so it is reached from both sides of `if (dbUser)` equally and names neither."
230
+ why: "link-account.mjs:175/231/291 — a hook moved the account binding out from under the write that had just been made. Raised on the link path, the sign-in path *and* the create path, so it is reached from both sides of `if (dbUser)` equally and names neither."
226
231
  },
227
232
  validation_source_missing: {
228
233
  collapse: false,
@@ -230,11 +235,7 @@ const PROVIDER_REFUSAL_VERDICTS = {
230
235
  },
231
236
  validation_failed: {
232
237
  collapse: false,
233
- why: "validate-user-info.mjs:34 — the adopter's own `validateUserInfo` callback threw, and Better Auth fails closed. Called on the link path (link-account.mjs:92), the sign-in path (:137) and the create path (internal-adapter.mjs:164), so it is reachable whether or not a row matched. What that callback *returns* is the adopter's own code and travels off-roster, which is the same decision as for the provider's own `error` values."
234
- },
235
- unable_to_link_account: {
236
- collapse: false,
237
- why: "callback.mjs:173/198, inside `if (link)` — reachable only on `/link-social`, where the caller is signed in as the user being changed. Telling somebody about their own account is not enumeration."
238
+ why: "validate-user-info.mjs:34 — the adopter's own `validateUserInfo` callback threw, and Better Auth fails closed. Called on the link path (link-account.mjs:24 and :148), the sign-in path (:192) and the create path (internal-adapter.mjs:164), so it is reachable whether or not a row matched. What that callback *returns* is the adopter's own code and travels off-roster, which is the same decision as for the provider's own `error` values."
238
239
  },
239
240
  email_does_not_match: {
240
241
  collapse: false,
@@ -246,27 +247,23 @@ const PROVIDER_REFUSAL_VERDICTS = {
246
247
  },
247
248
  unable_to_update_account: {
248
249
  collapse: false,
249
- why: "link-account.mjs:172, inside `if (linkedAccount)` — reaching it requires an account row already binding this provider identity to this user, and the caller proved control of that identity at the provider to get here. Ownership, not a matched row. (This is the argument `INVALID_PROFILE_FIELD` was wrongly given: that code's write sits outside this branch.)"
250
+ why: "link-account.mjs:227, inside `if (linkedAccount)` — reaching it requires an account row already binding this provider identity to this user, and the caller proved control of that identity at the provider to get here. Ownership, not a matched row. (This is the argument `INVALID_PROFILE_FIELD` was wrongly given: that code's write sits outside this branch.)"
250
251
  },
251
252
  account_ownership_conflict: {
252
253
  collapse: false,
253
- why: "link-account.mjs:38, inside `if (opts.selectedUser && …)`. The lookup it reports on is keyed by the *provider* identity the caller has just proved control of, not by an address handed over — and the social callback passes no `selectedUser`, so this never reaches that redirect at all."
254
- },
255
- account_provider_conflict: {
256
- collapse: false,
257
- why: "link-account.mjs:42, guarded by `requireExactAccountBinding`, which is `opts.selectedUser || opts.requireExactAccountBinding` — neither of which `callback.mjs` passes. Keyed by the caller's own provider identity, as above."
254
+ why: "link-account.mjs:97, inside `if (opts.selectedUser && …)`. The lookup it reports on is keyed by the *provider* identity the caller has just proved control of, not by an address handed over — and the social callback passes no `selectedUser`, so this never reaches that redirect at all."
258
255
  },
259
256
  user_not_found: {
260
257
  collapse: false,
261
- why: "link-account.mjs:54 — `findUserById(opts.selectedUser.userId)`, so it answers about a user id the caller was already handed, on a flow the social callback does not enter. It reads a row by id, never by a provider-resolved address."
258
+ why: "link-account.mjs:109 — `findUserById(opts.selectedUser.userId)`, so it answers about a user id the caller was already handed, on a flow the social callback does not enter. It reads a row by id, never by a provider-resolved address."
262
259
  },
263
260
  user_hook_selection_conflict: {
264
261
  collapse: false,
265
- why: "link-account.mjs:195, inside `if (opts.selectedUser …)`. A hook returned a different user than the one the caller picked from a list they had already been shown, and the social callback never picks one."
262
+ why: "link-account.mjs:249, inside `if (opts.selectedUser …)`. A hook returned a different user than the one the caller picked from a list they had already been shown, and the social callback never picks one."
266
263
  },
267
264
  session_hook_user_conflict: {
268
265
  collapse: false,
269
- why: "link-account.mjs:275 — after the user is resolved and the session minted, under the same `requireExactAccountBinding` gate. Reached from both sides of `if (dbUser)` when it is reached at all, which on the social callback is never."
266
+ why: "link-account.mjs:328 — after the user is resolved and the session minted, under the same `requireExactAccountBinding` gate. Reached from both sides of `if (dbUser)` when it is reached at all, which on the social callback is never."
270
267
  }
271
268
  };
272
269
  /** The codes this module refuses to let out. Derived from the roster, so the two cannot disagree. */
@@ -301,7 +298,7 @@ const PROVIDER_REFUSAL_ROSTER = PROVIDER_REFUSAL_VERDICTS;
301
298
  *
302
299
  * - **It need not be absolute.** `api/middlewares/origin-check.mjs` passes `allowRelativePaths: true`,
303
300
  * `matchesOriginPattern` admits `/path?query`, `oauth2/state.mjs` stores the value as a bare
304
- * `z.string().optional()`, and `redirectOnError` concatenates it raw. So a relative `Location` is a
301
+ * `z.string().optional()`, and `redirectOnError` keeps it root-relative. So a relative `Location` is a
305
302
  * supported answer, and returning `undefined` to one sent the true code to the browser and wrote no
306
303
  * audit row.
307
304
  * - **`error` need not be the only one.** `redirectOnError` *appends* `&error=<code>`. An
@@ -1 +1 @@
1
- {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/http/resolve.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAI7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAAE,KAAK,YAAY,EAAY,MAAM,kBAAkB,CAAC;AAqB/D,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,UAAU,CASvF;AA0BD,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,CAMnG"}
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/http/resolve.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAK7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAAE,KAAK,YAAY,EAAY,MAAM,kBAAkB,CAAC;AAsB/D,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,UAAU,CASvF;AA0BD,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,CAMnG"}
@@ -2,11 +2,13 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { authDatabase } from "../data/tables.js";
4
4
  import { baseURLResolver } from "./baseUrl.js";
5
- import { resolveAppleCredentials, resolveFacebookCredentials, resolveGithubCredentials, resolveGoogleCredentials, resolveSessionSecret } from "../instance/secrets.js";
5
+ import { resolveAppleCredentials, resolveFacebookCredentials, resolveGithubCredentials, resolveGoogleCredentials, resolveSessionSecrets } from "../instance/secrets.js";
6
6
  import { makeSendAuthEmail } from "../email/send.js";
7
7
  import { resolveProvider } from "../instance/providers.js";
8
8
  import { makeAuth } from "../instance/auth.js";
9
+ import { ensureJwksSealedUnderCurrent } from "../instance/jwksReencryption.js";
9
10
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
11
+ import { createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
10
12
  //#region src/http/resolve.ts
11
13
  /**
12
14
  * Build the Better-Auth instance for one request, memoized on the request context so the
@@ -61,8 +63,8 @@ async function buildAuthInstance(c, wiring) {
61
63
  detail: "auth.compose did not resolve the email enqueue seam; ensure email() is composed."
62
64
  });
63
65
  const env = c.env;
64
- const [secret, google, apple, facebook, github] = await Promise.all([
65
- resolveSessionSecret(env),
66
+ const [sessionSecrets, google, apple, facebook, github] = await Promise.all([
67
+ resolveSessionSecrets(env),
66
68
  resolveProvider(cfg.google.enabled, () => resolveGoogleCredentials(env)),
67
69
  resolveProvider(cfg.apple.enabled, () => resolveAppleCredentials(env)),
68
70
  resolveProvider(cfg.facebook.enabled, () => resolveFacebookCredentials(env)),
@@ -70,11 +72,24 @@ async function buildAuthInstance(c, wiring) {
70
72
  ]);
71
73
  const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
72
74
  const d1 = resolveDb(c.env, cfg.database);
75
+ const secret = sessionSecrets.versions[sessionSecrets.currentVersion];
76
+ if (secret === void 0) throw new InternalError({
77
+ message: "Authentication is misconfigured.",
78
+ detail: "auth-session-secret resolved with no value at its current version"
79
+ });
80
+ await ensureJwksSealedUnderCurrent({
81
+ db: authDatabase(d1),
82
+ holder: cfg.database,
83
+ secrets: env.SECRETS,
84
+ versions: sessionSecrets,
85
+ log: (c.get("log") ?? createWorkerLogger({ name: "auth" })).child("auth")
86
+ });
73
87
  const listener = wiring.onSessionRevoked;
74
88
  return makeAuth({
75
89
  db: authDatabase(d1),
76
90
  ...listener ? { onSessionRevoked: (session) => listener(session, d1) } : {},
77
91
  secret,
92
+ sessionSecrets,
78
93
  baseURL: baseURLResolver(cfg.baseURL)(c.req.raw),
79
94
  locale: c.var.locale?.catalogLocale ?? null,
80
95
  basePath: cfg.basePath,