@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.
- package/README.md +4 -0
- package/dist/caller/certificate.d.ts +83 -0
- package/dist/caller/certificate.d.ts.map +1 -0
- package/dist/caller/certificate.js +92 -0
- package/dist/caller/request.d.ts +66 -0
- package/dist/caller/request.d.ts.map +1 -0
- package/dist/caller/request.js +71 -0
- package/dist/caller/token.d.ts +130 -0
- package/dist/caller/token.d.ts.map +1 -0
- package/dist/caller/token.js +207 -0
- package/dist/capability.d.ts +44 -1
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +7 -4
- package/dist/data/betterAuth.d.ts +1 -1
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +1 -1
- package/dist/data/tables.d.ts +1 -1
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +39 -8
- package/dist/http/credentialResign.d.ts +46 -0
- package/dist/http/credentialResign.d.ts.map +1 -0
- package/dist/http/credentialResign.js +203 -0
- package/dist/http/devLoginRoute.d.ts.map +1 -1
- package/dist/http/devLoginRoute.js +12 -5
- package/dist/http/errorCallbackUrl.d.ts.map +1 -1
- package/dist/http/errorCallbackUrl.js +15 -9
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +66 -15
- package/dist/http/providerRefusal.d.ts +8 -7
- package/dist/http/providerRefusal.d.ts.map +1 -1
- package/dist/http/providerRefusal.js +29 -32
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +18 -3
- package/dist/http/responses.d.ts +52 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +25 -1
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +60 -9
- package/dist/http/schemas.d.ts +1 -1
- package/dist/http/schemas.js +1 -1
- package/dist/instance/auth.d.ts +1225 -2
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +6 -2
- package/dist/instance/jwksReencryption.d.ts +75 -0
- package/dist/instance/jwksReencryption.d.ts.map +1 -0
- package/dist/instance/jwksReencryption.js +160 -0
- package/dist/instance/providerSignInGate.d.ts +7 -6
- package/dist/instance/providerSignInGate.d.ts.map +1 -1
- package/dist/instance/providerSignInGate.js +16 -14
- package/dist/instance/providers.d.ts.map +1 -1
- package/dist/instance/providers.js +2 -1
- package/dist/instance/secrets.d.ts +168 -1
- package/dist/instance/secrets.d.ts.map +1 -1
- package/dist/instance/secrets.js +86 -3
- package/dist/instance/sessionSecrets.d.ts +45 -0
- package/dist/instance/sessionSecrets.d.ts.map +1 -0
- package/dist/instance/sessionSecrets.js +29 -0
- package/dist/migrations/0001_init.d.ts.map +1 -1
- package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
- package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
- package/dist/migrations/0003_account_issuer_nullable.js +131 -0
- package/dist/migrations/set.d.ts +2 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +4 -2
- package/dist/seeds/devSession.d.ts.map +1 -1
- package/dist/seeds/devSession.js +2 -1
- package/dist/test-utils/liveApp.d.ts +5 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +3 -3
- package/dist/test-utils/schemaDrift.d.ts +49 -0
- package/dist/test-utils/schemaDrift.d.ts.map +1 -0
- package/dist/test-utils/schemaDrift.js +35 -0
- package/dist/test-utils/scopedBackend.d.ts +183 -0
- package/dist/test-utils/scopedBackend.d.ts.map +1 -0
- package/dist/test-utils/scopedBackend.js +160 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/server-authoritative.md +182 -0
- package/package.json +14 -11
- package/src/caller/certificate.ts +133 -0
- package/src/caller/request.ts +84 -0
- package/src/caller/token.ts +276 -0
- package/src/capability.ts +65 -4
- package/src/data/betterAuth.ts +2 -1
- package/src/http/adminRoutes.ts +46 -10
- package/src/http/credentialResign.ts +268 -0
- package/src/http/devLoginRoute.ts +19 -6
- package/src/http/errorCallbackUrl.ts +21 -13
- package/src/http/middleware.ts +100 -35
- package/src/http/providerRefusal.ts +30 -32
- package/src/http/resolve.ts +27 -3
- package/src/http/responses.ts +54 -0
- package/src/http/routes.ts +97 -11
- package/src/http/schemas.ts +1 -1
- package/src/instance/auth.ts +22 -4
- package/src/instance/jwksReencryption.ts +206 -0
- package/src/instance/providerSignInGate.ts +23 -21
- package/src/instance/providers.ts +2 -1
- package/src/instance/secrets.ts +94 -1
- package/src/instance/sessionSecrets.ts +64 -0
- package/src/migrations/0001_init.ts +8 -10
- package/src/migrations/0003_account_issuer_nullable.ts +199 -0
- package/src/migrations/set.ts +3 -1
- package/src/seeds/devSession.ts +2 -1
- package/src/test-utils/liveApp.ts +8 -6
- package/src/test-utils/schemaDrift.ts +82 -0
- package/src/test-utils/scopedBackend.ts +136 -0
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { resolveSessionSecrets } from "../instance/secrets.js";
|
|
4
|
+
import { priorSessionSecrets } from "../instance/sessionSecrets.js";
|
|
5
|
+
//#region src/http/credentialResign.ts
|
|
6
|
+
/**
|
|
7
|
+
* **A session signed before a rotation, carried across it (#602).**
|
|
8
|
+
*
|
|
9
|
+
* Better Auth signs the session cookie — and the signed token a bearer client holds — with one secret,
|
|
10
|
+
* `ctx.secret`, which is the first entry of the version set and nothing else (`cookies/index.mjs:172`,
|
|
11
|
+
* `plugins/bearer/index.mjs`). So the moment `auth-session-secret` rotates, every credential issued under
|
|
12
|
+
* the previous version fails verification, and everyone is signed out at once. The overlap the registry
|
|
13
|
+
* declares would protect nothing.
|
|
14
|
+
*
|
|
15
|
+
* This closes that gap in front of Better Auth: before a request reaches it, a credential that fails under
|
|
16
|
+
* the current version and verifies under a **retained** prior one is re-signed under the current version.
|
|
17
|
+
* Better Auth then sees a credential it accepts, and the response carries the re-signed one back — a
|
|
18
|
+
* `Set-Cookie` for a browser, `set-auth-token` for a bearer client — so the next request needs no help.
|
|
19
|
+
*
|
|
20
|
+
* **It extends no trust.** A credential is re-signed only when it verifies under a version this deployment
|
|
21
|
+
* still holds, which is exactly the set Better Auth would accept if it verified signatures by version. The
|
|
22
|
+
* session it names is still looked up, still expired, still revoked by Better Auth as before. And the
|
|
23
|
+
* window closes on its own: once the rotation retires the previous version, nothing verifies under it.
|
|
24
|
+
*
|
|
25
|
+
* **The session's lifetime is the overlap.** A session in use is re-signed on its next request, inside the
|
|
26
|
+
* overlap; one not used for the whole overlap has expired anyway, because `auth-session-secret`'s overlap
|
|
27
|
+
* is declared at least as long as `sessionExpiresIn`, which slides on use.
|
|
28
|
+
*/
|
|
29
|
+
/** HMAC-SHA256 under `secret`, in standard base64 — the 44 characters better-call writes and checks. */
|
|
30
|
+
async function signature(value, secret) {
|
|
31
|
+
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
|
|
32
|
+
name: "HMAC",
|
|
33
|
+
hash: "SHA-256"
|
|
34
|
+
}, false, ["sign"]);
|
|
35
|
+
const bytes = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(value)));
|
|
36
|
+
let binary = "";
|
|
37
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
38
|
+
return btoa(binary);
|
|
39
|
+
}
|
|
40
|
+
/** Constant-time comparison of two strings of equal length; unequal lengths are unequal. */
|
|
41
|
+
function sameSignature(left, right) {
|
|
42
|
+
if (left.length !== right.length) return false;
|
|
43
|
+
let difference = 0;
|
|
44
|
+
for (let index = 0; index < left.length; index++) difference |= left.charCodeAt(index) ^ right.charCodeAt(index);
|
|
45
|
+
return difference === 0;
|
|
46
|
+
}
|
|
47
|
+
/** Sign `value` the way better-call's `signCookieValue` does, before its URL encoding: `value.signature`. */
|
|
48
|
+
async function signCredential(value, secret) {
|
|
49
|
+
return `${value}.${await signature(value, secret)}`;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Which of `keys` a signed credential verifies under, by index, and the value it signs — or `null` when it
|
|
53
|
+
* is not a signed credential or verifies under none. Takes the decoded form, `value.signature`.
|
|
54
|
+
*/
|
|
55
|
+
async function verifyCredential(signed, keys) {
|
|
56
|
+
const dot = signed.lastIndexOf(".");
|
|
57
|
+
if (dot < 1) return null;
|
|
58
|
+
const value = signed.slice(0, dot);
|
|
59
|
+
const presented = signed.slice(dot + 1);
|
|
60
|
+
if (presented.length !== 44 || !presented.endsWith("=")) return null;
|
|
61
|
+
for (let index = 0; index < keys.length; index++) {
|
|
62
|
+
const key = keys[index];
|
|
63
|
+
if (sameSignature(await signature(value, key), presented)) return {
|
|
64
|
+
value,
|
|
65
|
+
key: index
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
/** `decodeURIComponent`, answering the input itself when it is not valid percent-encoding. */
|
|
71
|
+
function decoded(text) {
|
|
72
|
+
try {
|
|
73
|
+
return decodeURIComponent(text);
|
|
74
|
+
} catch {
|
|
75
|
+
return text;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Re-sign under `current` whichever of a credential's two forms was signed under a key in `prior`.
|
|
80
|
+
*
|
|
81
|
+
* Takes the decoded credential and answers the re-signed one, or `null` when it verifies under the current
|
|
82
|
+
* key already, under no key at all, or is not a signed credential.
|
|
83
|
+
*/
|
|
84
|
+
async function carried(signed, keys) {
|
|
85
|
+
const verified = await verifyCredential(signed, [keys.current, ...keys.prior]);
|
|
86
|
+
if (verified === null || verified.key === 0) return null;
|
|
87
|
+
return await signCredential(verified.value, keys.current);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Re-sign every credential in `headers` that verifies under a prior key: the cookies named in `names`, and
|
|
91
|
+
* a signed bearer token. Answers `null` when nothing needed it — including always when there is no prior
|
|
92
|
+
* key, so a deployment that has never rotated parses nothing.
|
|
93
|
+
*/
|
|
94
|
+
async function resignCredentials(headers, keys, names) {
|
|
95
|
+
if (keys.prior.length === 0) return null;
|
|
96
|
+
const cookies = [];
|
|
97
|
+
let bearer;
|
|
98
|
+
const header = headers.get("cookie");
|
|
99
|
+
let cookieHeader = header;
|
|
100
|
+
if (header !== null) {
|
|
101
|
+
const parts = header.split(";").map((part) => part.trim());
|
|
102
|
+
cookieHeader = (await Promise.all(parts.map(async (part) => {
|
|
103
|
+
const equals = part.indexOf("=");
|
|
104
|
+
if (equals < 1) return part;
|
|
105
|
+
const name = part.slice(0, equals);
|
|
106
|
+
if (!names.includes(name)) return part;
|
|
107
|
+
const fresh = await carried(decoded(part.slice(equals + 1)), keys);
|
|
108
|
+
if (fresh === null) return part;
|
|
109
|
+
cookies.push({
|
|
110
|
+
name,
|
|
111
|
+
value: fresh
|
|
112
|
+
});
|
|
113
|
+
return `${name}=${encodeURIComponent(fresh)}`;
|
|
114
|
+
}))).join("; ");
|
|
115
|
+
}
|
|
116
|
+
const authorization = headers.get("authorization");
|
|
117
|
+
let authorizationHeader = authorization;
|
|
118
|
+
if (authorization !== null && authorization.slice(0, 7).toLowerCase() === "bearer ") {
|
|
119
|
+
const token = decoded(authorization.slice(7).trim());
|
|
120
|
+
const fresh = token.includes(".") ? await carried(token, keys) : null;
|
|
121
|
+
if (fresh !== null) {
|
|
122
|
+
bearer = fresh;
|
|
123
|
+
authorizationHeader = `Bearer ${fresh}`;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (cookies.length === 0 && bearer === void 0) return null;
|
|
127
|
+
const next = new Headers(headers);
|
|
128
|
+
if (cookieHeader !== null) next.set("cookie", cookieHeader);
|
|
129
|
+
if (authorizationHeader !== null) next.set("authorization", authorizationHeader);
|
|
130
|
+
return {
|
|
131
|
+
headers: next,
|
|
132
|
+
cookies,
|
|
133
|
+
...bearer === void 0 ? {} : { bearer }
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/** One `Set-Cookie` value, with the attributes Better Auth itself would have written. */
|
|
137
|
+
function setCookie(name, value, attributes, maxAge) {
|
|
138
|
+
const parts = [`${name}=${encodeURIComponent(value)}`];
|
|
139
|
+
if (maxAge !== void 0) parts.push(`Max-Age=${Math.floor(maxAge)}`);
|
|
140
|
+
if (attributes.domain) parts.push(`Domain=${attributes.domain}`);
|
|
141
|
+
parts.push(`Path=${attributes.path ?? "/"}`);
|
|
142
|
+
if (attributes.httpOnly) parts.push("HttpOnly");
|
|
143
|
+
if (attributes.secure || attributes.partitioned) parts.push("Secure");
|
|
144
|
+
if (attributes.sameSite) parts.push(`SameSite=${attributes.sameSite.charAt(0).toUpperCase()}${attributes.sameSite.slice(1).toLowerCase()}`);
|
|
145
|
+
if (attributes.partitioned) parts.push("Partitioned");
|
|
146
|
+
return parts.join("; ");
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The credentials this request needs re-signed, with the instance context their cookies are written from —
|
|
150
|
+
* or `null` when there is no prior version, or nothing to re-sign.
|
|
151
|
+
*/
|
|
152
|
+
async function resignedFor(c, instance) {
|
|
153
|
+
const versions = await resolveSessionSecrets(c.env);
|
|
154
|
+
const current = versions.versions[versions.currentVersion];
|
|
155
|
+
const prior = priorSessionSecrets(versions);
|
|
156
|
+
if (current === void 0 || prior.length === 0) return null;
|
|
157
|
+
const context = await instance.$context;
|
|
158
|
+
const names = [context.authCookies.sessionToken.name, context.authCookies.dontRememberToken.name];
|
|
159
|
+
const resigned = await resignCredentials(c.req.raw.headers, {
|
|
160
|
+
current,
|
|
161
|
+
prior
|
|
162
|
+
}, names);
|
|
163
|
+
return resigned === null ? null : {
|
|
164
|
+
resigned,
|
|
165
|
+
context
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Carry this request's credentials across a rotation, then run the rest of the chain, then hand the
|
|
170
|
+
* re-signed credentials back on the response.
|
|
171
|
+
*
|
|
172
|
+
* Swaps `c.req.raw` for a request carrying the re-signed credentials, so the session middleware, the auth
|
|
173
|
+
* handler and every route that reads the request see one consistent set. A response that already sets the
|
|
174
|
+
* cookie — a sign-out, a refresh — keeps its own; this only fills the silence.
|
|
175
|
+
*/
|
|
176
|
+
async function withResignedCredentials(c, instance, next) {
|
|
177
|
+
const prepared = await resignedFor(c, instance).catch(() => null);
|
|
178
|
+
if (prepared === null) return await next();
|
|
179
|
+
const { resigned, context } = prepared;
|
|
180
|
+
const session = context.authCookies.sessionToken;
|
|
181
|
+
const dontRemember = context.authCookies.dontRememberToken;
|
|
182
|
+
c.req.raw = new Request(c.req.raw, { headers: resigned.headers });
|
|
183
|
+
await next();
|
|
184
|
+
const response = new Response(c.res.body, c.res);
|
|
185
|
+
const setting = response.headers.getSetCookie().map((line) => line.slice(0, line.indexOf("=")));
|
|
186
|
+
const remembered = !(resigned.headers.get("cookie") ?? "").split(";").some((part) => part.trim().startsWith(`${dontRemember.name}=`));
|
|
187
|
+
for (const cookie of resigned.cookies) {
|
|
188
|
+
if (setting.includes(cookie.name)) continue;
|
|
189
|
+
const isSession = cookie.name === session.name;
|
|
190
|
+
const attributes = isSession ? session.attributes : dontRemember.attributes;
|
|
191
|
+
response.headers.append("set-cookie", setCookie(cookie.name, cookie.value, attributes, isSession && remembered ? context.sessionConfig.expiresIn : void 0));
|
|
192
|
+
}
|
|
193
|
+
if (resigned.bearer !== void 0 && !response.headers.has("set-auth-token")) {
|
|
194
|
+
response.headers.set("set-auth-token", encodeURIComponent(resigned.bearer));
|
|
195
|
+
const exposed = new Set((response.headers.get("access-control-expose-headers") ?? "").split(",").map((header) => header.trim()).filter(Boolean));
|
|
196
|
+
exposed.add("set-auth-token");
|
|
197
|
+
response.headers.set("access-control-expose-headers", [...exposed].join(", "));
|
|
198
|
+
}
|
|
199
|
+
c.res = void 0;
|
|
200
|
+
c.res = response;
|
|
201
|
+
}
|
|
202
|
+
//#endregion
|
|
203
|
+
export { resignCredentials, signCredential, verifyCredential, withResignedCredentials };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"devLoginRoute.d.ts","sourceRoot":"","sources":["../../src/http/devLoginRoute.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"devLoginRoute.d.ts","sourceRoot":"","sources":["../../src/http/devLoginRoute.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAE7E,OAAO,EAAE,KAAK,UAAU,EAAsC,MAAM,gCAAgC,CAAC;AAQrG,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAOhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,UAAU,EAClB,GAAG,GAAE,UAAyB,GAC7B,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAuBnC"}
|
|
@@ -8,9 +8,11 @@ import { resolveDb } from "./resolve.js";
|
|
|
8
8
|
import { NotFoundError } from "@pithy-sh/core/src/error/pithyError";
|
|
9
9
|
import { z } from "zod";
|
|
10
10
|
import { ambientEnv, compositionEnvironment } from "@pithy-sh/core/src/env/ambient";
|
|
11
|
-
import {
|
|
11
|
+
import { commandName, pithyCommand } from "@pithy-sh/core/src/cli/command";
|
|
12
12
|
import { isContinuousIntegration } from "@pithy-sh/core/src/env/ci";
|
|
13
|
-
import {
|
|
13
|
+
import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
|
|
14
|
+
import { validate } from "@pithy-sh/core/src/http/validation";
|
|
15
|
+
import { LOCAL_ENVIRONMENT } from "@pithy-sh/core/src/naming/environment";
|
|
14
16
|
import { DEV_LOGIN_CLAIM_PARAM, DEV_LOGIN_ROUTE } from "@pithy-sh/core/src/seed/devLogin";
|
|
15
17
|
//#region src/http/devLoginRoute.ts
|
|
16
18
|
/**
|
|
@@ -53,7 +55,12 @@ function registerDevLoginRoute(wiring, env = ambientEnv()) {
|
|
|
53
55
|
return (app) => {
|
|
54
56
|
if (compositionEnvironment(env) !== "dev") return;
|
|
55
57
|
if (isContinuousIntegration(env)) return;
|
|
56
|
-
app.get(DEV_LOGIN_ROUTE,
|
|
58
|
+
app.get(DEV_LOGIN_ROUTE, describeRoute({
|
|
59
|
+
summary: "Sign the browser in as the seeded dev user.",
|
|
60
|
+
description: "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.",
|
|
61
|
+
verification: "public",
|
|
62
|
+
responses: { 302: { description: "Signed in: sets the session cookie and redirects to `/`." } }
|
|
63
|
+
}), validate("query", DevLoginQuery), (c) => serveDevLogin(c, wiring, c.req.valid("query")[DEV_LOGIN_CLAIM_PARAM]));
|
|
57
64
|
};
|
|
58
65
|
}
|
|
59
66
|
/**
|
|
@@ -70,7 +77,7 @@ function registerDevLoginRoute(wiring, env = ambientEnv()) {
|
|
|
70
77
|
* which is the opposite of a field nobody classified carrying it everywhere.
|
|
71
78
|
*/
|
|
72
79
|
function noSeededSession() {
|
|
73
|
-
return new NotFoundError({ message:
|
|
80
|
+
return new NotFoundError({ message: `No dev login has been seeded for this environment. Run ${pithyCommand("seed", { flags: { "--env": LOCAL_ENVIRONMENT } })}, then open this URL again.` });
|
|
74
81
|
}
|
|
75
82
|
/**
|
|
76
83
|
* What the route takes: the claim, in the query.
|
|
@@ -110,7 +117,7 @@ async function serveDevLogin(c, wiring, presented) {
|
|
|
110
117
|
createdAt: now,
|
|
111
118
|
updatedAt: now,
|
|
112
119
|
ipAddress: "127.0.0.1",
|
|
113
|
-
userAgent: "
|
|
120
|
+
userAgent: `${commandName("dev")} login`,
|
|
114
121
|
deviceId: null,
|
|
115
122
|
familyId: null,
|
|
116
123
|
authenticatedAt: now
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errorCallbackUrl.d.ts","sourceRoot":"","sources":["../../src/http/errorCallbackUrl.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"errorCallbackUrl.d.ts","sourceRoot":"","sources":["../../src/http/errorCallbackUrl.ts"],"names":[],"mappings":"AAuKA;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAgDnF;AA0ED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAkBlG"}
|
|
@@ -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`)
|
|
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
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
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`
|
|
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
|
|
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
|
|
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,
|
|
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"}
|
package/dist/http/middleware.js
CHANGED
|
@@ -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
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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:
|
|
43
|
-
* | `signup_disabled` | **no** row matched (`:
|
|
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:
|
|
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`
|
|
78
|
-
*
|
|
79
|
-
*
|
|
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`
|
|
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
|
|
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"}
|