@passflow/node 0.1.3 → 0.3.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 +106 -3
- package/dist/adapter-Du22h3Lk.mjs +57 -0
- package/dist/adapter-DyCsMsEq.cjs +62 -0
- package/dist/evaluate-BAJUQu_Z.d.cts +141 -0
- package/dist/evaluate-BAJUQu_Z.d.mts +141 -0
- package/dist/{evaluate-BTuol-Oa.mjs → evaluate-CHts4VKy.mjs} +77 -18
- package/dist/{evaluate-C20MecTf.cjs → evaluate-Yv4mWPRI.cjs} +88 -17
- package/dist/express.cjs +22 -8
- package/dist/express.d.cts +15 -6
- package/dist/express.d.mts +15 -6
- package/dist/express.mjs +22 -8
- package/dist/fastify.cjs +22 -8
- package/dist/fastify.d.cts +17 -8
- package/dist/fastify.d.mts +17 -8
- package/dist/fastify.mjs +22 -8
- package/dist/hono.cjs +22 -8
- package/dist/hono.d.cts +16 -7
- package/dist/hono.d.mts +16 -7
- package/dist/hono.mjs +22 -8
- package/dist/index.cjs +85 -18
- package/dist/index.d.cts +34 -41
- package/dist/index.d.mts +34 -41
- package/dist/index.mjs +83 -18
- package/dist/loopback-ADMM_GlW.cjs +22 -0
- package/dist/loopback-CDiL_KzV.mjs +17 -0
- package/dist/manager-Bm3vM2Aw.d.cts +93 -0
- package/dist/manager-Bm3vM2Aw.d.mts +93 -0
- package/dist/session-browser.cjs +17 -0
- package/dist/session-browser.d.cts +5 -0
- package/dist/session-browser.d.mts +5 -0
- package/dist/session-browser.mjs +14 -0
- package/dist/session.cjs +923 -0
- package/dist/session.d.cts +7 -0
- package/dist/session.d.mts +7 -0
- package/dist/session.mjs +898 -0
- package/package.json +30 -3
- package/dist/claims-BHJhnzch.d.cts +0 -51
- package/dist/claims-BHJhnzch.d.mts +0 -51
package/dist/session.cjs
ADDED
|
@@ -0,0 +1,923 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
// \0rolldown/runtime.js
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
13
|
+
get: ((k) => from[k]).bind(null, key),
|
|
14
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
|
+
value: mod,
|
|
21
|
+
enumerable: true
|
|
22
|
+
}) : target, mod));
|
|
23
|
+
const require_loopback = require("./loopback-ADMM_GlW.cjs");
|
|
24
|
+
let jose = require("jose");
|
|
25
|
+
let oauth4webapi = require("oauth4webapi");
|
|
26
|
+
oauth4webapi = __toESM(oauth4webapi, 1);
|
|
27
|
+
// src/session/config.ts
|
|
28
|
+
const DEFAULT_SCOPES = [
|
|
29
|
+
"openid",
|
|
30
|
+
"profile",
|
|
31
|
+
"email",
|
|
32
|
+
"offline_access"
|
|
33
|
+
];
|
|
34
|
+
const DEFAULT_ROUTES = {
|
|
35
|
+
login: "/auth/login",
|
|
36
|
+
callback: "/auth/callback",
|
|
37
|
+
logout: "/auth/logout"
|
|
38
|
+
};
|
|
39
|
+
const MIN_SECRET_LENGTH = 32;
|
|
40
|
+
/** A route is a plain absolute path: it becomes a cookie `Path`, so it may hold nothing that ends the attribute. */
|
|
41
|
+
const ROUTE = /^\/[A-Za-z0-9\-._~/%]*$/;
|
|
42
|
+
function processEnv() {
|
|
43
|
+
return globalThis.process?.env ?? {};
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The session settings from environment variables: `PASSFLOW_ISSUER`, `PASSFLOW_CLIENT_ID`,
|
|
47
|
+
* `PASSFLOW_CLIENT_SECRET`, `PASSFLOW_SECRET` and `APP_BASE_URL`. A variable that is unset or empty is left
|
|
48
|
+
* out, so an explicit value spread after this one wins. Reads `process.env` when `env` is not given.
|
|
49
|
+
*/
|
|
50
|
+
function configFromEnv(env) {
|
|
51
|
+
const source = env ?? processEnv();
|
|
52
|
+
const read = (name) => {
|
|
53
|
+
const value = source[name];
|
|
54
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
55
|
+
};
|
|
56
|
+
const config = {};
|
|
57
|
+
const issuer = read("PASSFLOW_ISSUER");
|
|
58
|
+
const clientId = read("PASSFLOW_CLIENT_ID");
|
|
59
|
+
const clientSecret = read("PASSFLOW_CLIENT_SECRET");
|
|
60
|
+
const secret = read("PASSFLOW_SECRET");
|
|
61
|
+
const baseUrl = read("APP_BASE_URL");
|
|
62
|
+
if (issuer !== void 0) config.issuer = issuer;
|
|
63
|
+
if (clientId !== void 0) config.clientId = clientId;
|
|
64
|
+
if (clientSecret !== void 0) config.clientSecret = clientSecret;
|
|
65
|
+
if (secret !== void 0) config.secret = secret;
|
|
66
|
+
if (baseUrl !== void 0) config.baseUrl = baseUrl;
|
|
67
|
+
return config;
|
|
68
|
+
}
|
|
69
|
+
function requireString(value, envName, option) {
|
|
70
|
+
if (typeof value !== "string" || value === "") throw new TypeError(`[passflow] ${envName} is not set (config.${option})`);
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
/** https, or http on a loopback host. The error names the variable, never the value. */
|
|
74
|
+
function requireUrl(value, envName, option) {
|
|
75
|
+
const raw = requireString(value, envName, option);
|
|
76
|
+
let url;
|
|
77
|
+
try {
|
|
78
|
+
url = new URL(raw);
|
|
79
|
+
} catch {
|
|
80
|
+
throw new TypeError(`[passflow] ${envName} must be a valid URL (config.${option})`);
|
|
81
|
+
}
|
|
82
|
+
if (url.protocol === "https:") return {
|
|
83
|
+
url,
|
|
84
|
+
loopback: false
|
|
85
|
+
};
|
|
86
|
+
if (url.protocol === "http:" && require_loopback.isLoopbackHost(raw, url)) return {
|
|
87
|
+
url,
|
|
88
|
+
loopback: true
|
|
89
|
+
};
|
|
90
|
+
throw new TypeError(`[passflow] ${envName} must use https unless the host is loopback (config.${option})`);
|
|
91
|
+
}
|
|
92
|
+
function requireRoutes(routes) {
|
|
93
|
+
if (routes === void 0) return { ...DEFAULT_ROUTES };
|
|
94
|
+
if (typeof routes !== "object" || routes === null) throw new TypeError("[passflow] config.routes must be an object");
|
|
95
|
+
const given = routes;
|
|
96
|
+
const resolved = { ...DEFAULT_ROUTES };
|
|
97
|
+
for (const key of [
|
|
98
|
+
"login",
|
|
99
|
+
"callback",
|
|
100
|
+
"logout"
|
|
101
|
+
]) {
|
|
102
|
+
const value = given[key];
|
|
103
|
+
if (value === void 0) continue;
|
|
104
|
+
if (typeof value !== "string" || !ROUTE.test(value)) throw new TypeError(`[passflow] config.routes.${key} must be an absolute path such as ${DEFAULT_ROUTES[key]}`);
|
|
105
|
+
if (value.endsWith("/")) throw new TypeError(`[passflow] config.routes.${key} must not end in "/" (use ${value.replace(/\/+$/, "") || DEFAULT_ROUTES[key]})`);
|
|
106
|
+
resolved[key] = value;
|
|
107
|
+
}
|
|
108
|
+
if (new Set(Object.values(resolved)).size !== 3) throw new TypeError("[passflow] config.routes must name three different paths");
|
|
109
|
+
return resolved;
|
|
110
|
+
}
|
|
111
|
+
function requireScopes(scopes) {
|
|
112
|
+
if (scopes === void 0) return [...DEFAULT_SCOPES];
|
|
113
|
+
if (!Array.isArray(scopes) || scopes.length === 0 || !scopes.every((scope) => typeof scope === "string" && /^[\x21\x23-\x5b\x5d-\x7e]+$/.test(scope))) throw new TypeError("[passflow] config.scopes must name one or more scopes");
|
|
114
|
+
return [...scopes];
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Checks every value. Called on first use, never at import, so a build without the environment passes.
|
|
118
|
+
* Throws `TypeError` naming the environment variable or option that is missing or wrong.
|
|
119
|
+
*/
|
|
120
|
+
function resolveConfig(config) {
|
|
121
|
+
if (typeof config !== "object" || config === null) throw new TypeError("[passflow] the session config must be an object");
|
|
122
|
+
const issuer = requireUrl(config.issuer, "PASSFLOW_ISSUER", "issuer");
|
|
123
|
+
const clientId = requireString(config.clientId, "PASSFLOW_CLIENT_ID", "clientId");
|
|
124
|
+
const clientSecret = requireString(config.clientSecret, "PASSFLOW_CLIENT_SECRET", "clientSecret");
|
|
125
|
+
const secret = requireString(config.secret, "PASSFLOW_SECRET", "secret");
|
|
126
|
+
if (secret.length < MIN_SECRET_LENGTH) throw new TypeError(`[passflow] PASSFLOW_SECRET must be at least ${String(MIN_SECRET_LENGTH)} characters (config.secret)`);
|
|
127
|
+
const base = requireUrl(config.baseUrl, "APP_BASE_URL", "baseUrl");
|
|
128
|
+
if (base.url.pathname !== "/" || base.url.search !== "" || base.url.hash !== "") throw new TypeError("[passflow] APP_BASE_URL must be the app's origin, with no path (config.baseUrl)");
|
|
129
|
+
if (config.fetch !== void 0 && typeof config.fetch !== "function") throw new TypeError("[passflow] config.fetch must be a function");
|
|
130
|
+
if (config.now !== void 0 && typeof config.now !== "function") throw new TypeError("[passflow] config.now must be a function");
|
|
131
|
+
return {
|
|
132
|
+
issuer: issuer.url,
|
|
133
|
+
issuerIsLoopback: issuer.loopback,
|
|
134
|
+
clientId,
|
|
135
|
+
clientSecret,
|
|
136
|
+
secret,
|
|
137
|
+
baseUrl: base.url.origin,
|
|
138
|
+
secure: base.url.protocol === "https:",
|
|
139
|
+
scopes: requireScopes(config.scopes),
|
|
140
|
+
routes: requireRoutes(config.routes),
|
|
141
|
+
fetch: config.fetch,
|
|
142
|
+
now: config.now ?? (() => /* @__PURE__ */ new Date())
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
// src/session/cookies.ts
|
|
146
|
+
/** The session cookie's name over http loopback, where a browser refuses `Secure` and so the `__Host-` prefix. */
|
|
147
|
+
const SESSION_COOKIE = "passflow_session";
|
|
148
|
+
/** The transaction cookie's name over http loopback. */
|
|
149
|
+
const TRANSACTION_COOKIE = "passflow_txn";
|
|
150
|
+
/**
|
|
151
|
+
* Over https both names carry `__Host-`: the browser then takes the cookie only with `Secure`, `Path=/` and no
|
|
152
|
+
* `Domain`, so a sibling subdomain cannot plant one under a parent domain.
|
|
153
|
+
*/
|
|
154
|
+
const HOST_PREFIX = "__Host-";
|
|
155
|
+
/** A sealed value longer than this is split into `<name>.0`, `<name>.1`, … */
|
|
156
|
+
const CHUNK_SIZE = 3500;
|
|
157
|
+
/** Browsers keep a cookie for at most 400 days, whatever `Max-Age` says. */
|
|
158
|
+
const MAX_COOKIE_AGE = 3456e4;
|
|
159
|
+
const DIGITS = /^\d+$/;
|
|
160
|
+
/** The session cookie's name: `__Host-passflow_session` over https, `passflow_session` over http loopback. */
|
|
161
|
+
function sessionCookieName(secure) {
|
|
162
|
+
return secure ? `${HOST_PREFIX}${SESSION_COOKIE}` : SESSION_COOKIE;
|
|
163
|
+
}
|
|
164
|
+
/** The transaction cookie's name: `__Host-passflow_txn` over https, `passflow_txn` over http loopback. */
|
|
165
|
+
function transactionCookieName(secure) {
|
|
166
|
+
return secure ? `${HOST_PREFIX}${TRANSACTION_COOKIE}` : TRANSACTION_COOKIE;
|
|
167
|
+
}
|
|
168
|
+
/** The name–value pairs of a `Cookie` header, in order. A part with no `=` is skipped. */
|
|
169
|
+
function parseCookies(cookieHeader) {
|
|
170
|
+
if (typeof cookieHeader !== "string" || cookieHeader === "") return [];
|
|
171
|
+
const pairs = [];
|
|
172
|
+
for (const part of cookieHeader.split(";")) {
|
|
173
|
+
const eq = part.indexOf("=");
|
|
174
|
+
if (eq < 0) continue;
|
|
175
|
+
const name = part.slice(0, eq).trim();
|
|
176
|
+
if (name !== "") pairs.push([name, part.slice(eq + 1).trim()]);
|
|
177
|
+
}
|
|
178
|
+
return pairs;
|
|
179
|
+
}
|
|
180
|
+
/** The chunk index of `name` under `base` (`<base>.<digits>`), or `undefined`. */
|
|
181
|
+
function chunkIndex(name, base) {
|
|
182
|
+
if (!name.startsWith(`${base}.`)) return;
|
|
183
|
+
const digits = name.slice(base.length + 1);
|
|
184
|
+
return DIGITS.test(digits) ? Number(digits) : void 0;
|
|
185
|
+
}
|
|
186
|
+
/** True for the session cookie of one scheme (see `sessionCookieName`) and for its chunks, `<name>.<digits>`. */
|
|
187
|
+
function isSessionCookieName(name, secure) {
|
|
188
|
+
const base = sessionCookieName(secure);
|
|
189
|
+
return name === base || chunkIndex(name, base) !== void 0;
|
|
190
|
+
}
|
|
191
|
+
/** True for a session cookie name of either scheme. */
|
|
192
|
+
function isAnySessionCookieName(name) {
|
|
193
|
+
return isSessionCookieName(name, true) || isSessionCookieName(name, false);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* True when the `Cookie` header carries a session cookie of either scheme: the base name or any chunk. It is
|
|
197
|
+
* broader than the reader, so a request the reader can treat as signed in is always one this reports.
|
|
198
|
+
*/
|
|
199
|
+
function hasSessionCookie(cookieHeader) {
|
|
200
|
+
return parseCookies(cookieHeader).some(([name]) => isAnySessionCookieName(name));
|
|
201
|
+
}
|
|
202
|
+
/** The value of the first cookie named `name`, or `undefined`. */
|
|
203
|
+
function readCookie(cookieHeader, name) {
|
|
204
|
+
return parseCookies(cookieHeader).find(([n]) => n === name)?.[1];
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* The sealed session from the `Cookie` header, read only under the name `secure` selects: the other scheme's
|
|
208
|
+
* name is ignored. The base cookie wins when present. Otherwise the chunks `.0` to `.n-1` are joined in order;
|
|
209
|
+
* a gap, or more than `MAX_CHUNKS`, reads as no session.
|
|
210
|
+
*/
|
|
211
|
+
function readSessionValue(cookieHeader, secure) {
|
|
212
|
+
const pairs = parseCookies(cookieHeader);
|
|
213
|
+
const baseName = sessionCookieName(secure);
|
|
214
|
+
const base = pairs.find(([name]) => name === baseName);
|
|
215
|
+
if (base !== void 0) return base[1] === "" ? void 0 : base[1];
|
|
216
|
+
const chunks = /* @__PURE__ */ new Map();
|
|
217
|
+
for (const [name, value] of pairs) {
|
|
218
|
+
const index = chunkIndex(name, baseName);
|
|
219
|
+
if (index !== void 0 && !chunks.has(index)) chunks.set(index, value);
|
|
220
|
+
}
|
|
221
|
+
if (chunks.size === 0 || chunks.size > 3) return;
|
|
222
|
+
let value = "";
|
|
223
|
+
for (let i = 0; i < chunks.size; i++) {
|
|
224
|
+
const chunk = chunks.get(i);
|
|
225
|
+
if (chunk === void 0 || chunk === "") return;
|
|
226
|
+
value += chunk;
|
|
227
|
+
}
|
|
228
|
+
return value;
|
|
229
|
+
}
|
|
230
|
+
/** A `Set-Cookie` value: always HttpOnly and SameSite=Lax; `Secure` when the app is served over https. */
|
|
231
|
+
function serializeCookie(name, value, { path, maxAge, secure }) {
|
|
232
|
+
const attributes = [
|
|
233
|
+
`${name}=${value}`,
|
|
234
|
+
`Path=${path}`,
|
|
235
|
+
`Max-Age=${String(Math.max(0, Math.floor(maxAge)))}`,
|
|
236
|
+
"HttpOnly",
|
|
237
|
+
"SameSite=Lax"
|
|
238
|
+
];
|
|
239
|
+
if (secure) attributes.push("Secure");
|
|
240
|
+
return attributes.join("; ");
|
|
241
|
+
}
|
|
242
|
+
/** A `Set-Cookie` value that expires the cookie. */
|
|
243
|
+
function expireCookie(name, path, secure) {
|
|
244
|
+
return serializeCookie(name, "", {
|
|
245
|
+
path,
|
|
246
|
+
maxAge: 0,
|
|
247
|
+
secure
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
var SessionTooLargeError = class extends Error {
|
|
251
|
+
bytes;
|
|
252
|
+
constructor(bytes) {
|
|
253
|
+
super(`[passflow] the sealed session is ${String(bytes)} bytes, over the ${String(CHUNK_SIZE * 3)}-byte limit`);
|
|
254
|
+
this.name = "SessionTooLargeError";
|
|
255
|
+
this.bytes = bytes;
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
/**
|
|
259
|
+
* The `Set-Cookie` values that store `value` as the session, and the pairs a replaced `Cookie` header carries.
|
|
260
|
+
* Every session cookie of this scheme in the incoming request that is not written now is expired, however many
|
|
261
|
+
* there are. Throws `SessionTooLargeError` when the value needs more than `MAX_CHUNKS` chunks.
|
|
262
|
+
*/
|
|
263
|
+
function writeSessionCookies(value, cookieHeader, options) {
|
|
264
|
+
const pairs = [];
|
|
265
|
+
const baseName = sessionCookieName(options.secure);
|
|
266
|
+
if (value.length <= 3500) pairs.push([baseName, value]);
|
|
267
|
+
else {
|
|
268
|
+
const count = Math.ceil(value.length / CHUNK_SIZE);
|
|
269
|
+
if (count > 3) throw new SessionTooLargeError(value.length);
|
|
270
|
+
for (let i = 0; i < count; i++) pairs.push([`${baseName}.${String(i)}`, value.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE)]);
|
|
271
|
+
}
|
|
272
|
+
const cookie = {
|
|
273
|
+
path: "/",
|
|
274
|
+
maxAge: options.maxAge,
|
|
275
|
+
secure: options.secure
|
|
276
|
+
};
|
|
277
|
+
const setCookies = pairs.map(([name, chunk]) => serializeCookie(name, chunk, cookie));
|
|
278
|
+
const written = new Set(pairs.map(([name]) => name));
|
|
279
|
+
setCookies.push(...expireSessionCookies(cookieHeader, options.secure, written));
|
|
280
|
+
return {
|
|
281
|
+
setCookies,
|
|
282
|
+
pairs
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* `Set-Cookie` values that expire every session cookie of this scheme in the request, except the names in
|
|
287
|
+
* `keep`. The other scheme's names are left alone: they are never read under this scheme.
|
|
288
|
+
*/
|
|
289
|
+
function expireSessionCookies(cookieHeader, secure, keep = /* @__PURE__ */ new Set()) {
|
|
290
|
+
const names = /* @__PURE__ */ new Set();
|
|
291
|
+
for (const [name] of parseCookies(cookieHeader)) if (isSessionCookieName(name, secure) && !keep.has(name)) names.add(name);
|
|
292
|
+
return [...names].map((name) => expireCookie(name, "/", secure));
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* The `Cookie` header with every session cookie, of either scheme, replaced by `pairs`. Other cookies keep
|
|
296
|
+
* their order.
|
|
297
|
+
*/
|
|
298
|
+
function replaceSessionCookies(cookieHeader, pairs) {
|
|
299
|
+
return [...parseCookies(cookieHeader).filter(([name]) => !isAnySessionCookieName(name)), ...pairs].map(([name, value]) => `${name}=${value}`).join("; ");
|
|
300
|
+
}
|
|
301
|
+
// src/session/oidc.ts
|
|
302
|
+
const SESSION_ENDING_ERRORS = /* @__PURE__ */ new Set(["invalid_grant", "invalid_client"]);
|
|
303
|
+
/**
|
|
304
|
+
* Errors a call to `fetch` rejected with. `fetch` rejects only when no answer came back, whatever the runtime
|
|
305
|
+
* names the error, so each of these counts as an unavailable issuer.
|
|
306
|
+
*/
|
|
307
|
+
const fetchRejections = /* @__PURE__ */ new WeakSet();
|
|
308
|
+
/** `fetch` (the configured one, else the global one), with its rejections recorded in `fetchRejections`. */
|
|
309
|
+
function recordingFetch(custom) {
|
|
310
|
+
return async (input, init) => {
|
|
311
|
+
try {
|
|
312
|
+
return await (custom ?? fetch)(input, init);
|
|
313
|
+
} catch (error) {
|
|
314
|
+
if (typeof error === "object" && error !== null) fetchRejections.add(error);
|
|
315
|
+
throw error;
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
/** How long one call to the issuer may take before it is abandoned. */
|
|
320
|
+
const ISSUER_TIMEOUT_MS = 1e4;
|
|
321
|
+
/**
|
|
322
|
+
* True when the issuer could not serve a call: no answer came back (the host is unreachable, its name doesn't
|
|
323
|
+
* resolve, the connection is refused or dropped, or the call timed out), or the answer was a 5xx. Any error
|
|
324
|
+
* `fetch` rejected with counts, whatever its name or message. Outside `fetch`, the runtime reports a stalled body
|
|
325
|
+
* as a `TypeError` (undici's "terminated", a browser runtime's "NetworkError") or as a `TimeoutError` or
|
|
326
|
+
* `AbortError`. oauth4webapi wraps some of these: a body that stalls after the headers arrived becomes an
|
|
327
|
+
* `OperationProcessingError` whose `cause` is the timeout, and a 5xx comes as an error with a `status`
|
|
328
|
+
* (`ResponseBodyError`, `WWWAuthenticateChallengeError`) or with the `Response` as its `cause`. So the error and
|
|
329
|
+
* its causes are checked, a few levels deep. Malformed JSON and an OAuth error answer below 500 are neither.
|
|
330
|
+
*/
|
|
331
|
+
function isIssuerUnavailable(error, depth = 0) {
|
|
332
|
+
if (typeof error !== "object" || error === null || depth > 3) return false;
|
|
333
|
+
if (fetchRejections.has(error)) return true;
|
|
334
|
+
const { name, message, status, cause } = error;
|
|
335
|
+
if (name === "TimeoutError" || name === "AbortError") return true;
|
|
336
|
+
if (error instanceof TypeError && typeof message === "string") {
|
|
337
|
+
if (/fetch failed|failed to fetch|networkerror|network error|^terminated$/i.test(message)) return true;
|
|
338
|
+
}
|
|
339
|
+
if (typeof status === "number" && status >= 500) return true;
|
|
340
|
+
return isIssuerUnavailable(cause, depth + 1);
|
|
341
|
+
}
|
|
342
|
+
/** The `exp` of a JWT, read without verifying it, or `undefined`. Only used to time the session. */
|
|
343
|
+
function unverifiedExp(token) {
|
|
344
|
+
if (typeof token !== "string") return;
|
|
345
|
+
try {
|
|
346
|
+
const { exp } = (0, jose.decodeJwt)(token);
|
|
347
|
+
return typeof exp === "number" && Number.isFinite(exp) ? exp : void 0;
|
|
348
|
+
} catch {
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* True when a token endpoint error says the session is over, and not that the call merely failed. An unavailable
|
|
354
|
+
* issuer (a 5xx, a timeout, no answer) never ends it, whatever OAuth error the answer carries.
|
|
355
|
+
*/
|
|
356
|
+
function endsSession(error) {
|
|
357
|
+
if (isIssuerUnavailable(error)) return false;
|
|
358
|
+
if (error instanceof oauth4webapi.ResponseBodyError) return SESSION_ENDING_ERRORS.has(error.error);
|
|
359
|
+
if (error instanceof oauth4webapi.WWWAuthenticateChallengeError) return error.cause.some((challenge) => SESSION_ENDING_ERRORS.has(String(challenge.parameters.error)));
|
|
360
|
+
return false;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* The OpenID Connect calls the session makes, through oauth4webapi: discovery, the authorization request, the
|
|
364
|
+
* code grant with the client secret and PKCE, refresh, revocation and UserInfo. `http://` is allowed only when
|
|
365
|
+
* the issuer's host is loopback.
|
|
366
|
+
*/
|
|
367
|
+
function createOidcClient(config, nowSeconds) {
|
|
368
|
+
const requestOptions = {
|
|
369
|
+
[oauth4webapi.customFetch]: recordingFetch(config.fetch),
|
|
370
|
+
signal: () => AbortSignal.timeout(ISSUER_TIMEOUT_MS)
|
|
371
|
+
};
|
|
372
|
+
if (config.issuerIsLoopback) requestOptions[oauth4webapi.allowInsecureRequests] = true;
|
|
373
|
+
const clientAuth = oauth4webapi.ClientSecretPost(config.clientSecret);
|
|
374
|
+
const redirectUri = `${config.baseUrl}${config.routes.callback}`;
|
|
375
|
+
let discovery;
|
|
376
|
+
/** Built per call, so that oauth4webapi's clock follows the configured one. */
|
|
377
|
+
const client = () => ({
|
|
378
|
+
client_id: config.clientId,
|
|
379
|
+
[oauth4webapi.clockSkew]: nowSeconds() - Math.floor(Date.now() / 1e3)
|
|
380
|
+
});
|
|
381
|
+
/** Discovery runs once; a failed attempt is forgotten, so the next request tries again. */
|
|
382
|
+
const server = () => {
|
|
383
|
+
if (discovery === void 0) {
|
|
384
|
+
const pending = oauth4webapi.discoveryRequest(config.issuer, {
|
|
385
|
+
...requestOptions,
|
|
386
|
+
algorithm: "oidc"
|
|
387
|
+
}).then((response) => oauth4webapi.processDiscoveryResponse(config.issuer, response));
|
|
388
|
+
discovery = pending;
|
|
389
|
+
pending.catch(() => {
|
|
390
|
+
if (discovery === pending) discovery = void 0;
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
return discovery;
|
|
394
|
+
};
|
|
395
|
+
/** The access token's expiry: `expires_in` when given, else the token's own `exp`. */
|
|
396
|
+
const accessTokenExpiry = (response) => {
|
|
397
|
+
if (typeof response.expires_in === "number" && Number.isFinite(response.expires_in)) return nowSeconds() + Math.floor(response.expires_in);
|
|
398
|
+
return unverifiedExp(response.access_token);
|
|
399
|
+
};
|
|
400
|
+
return {
|
|
401
|
+
redirectUri,
|
|
402
|
+
async authorizationRequest() {
|
|
403
|
+
const as = await server();
|
|
404
|
+
if (as.authorization_endpoint === void 0) throw new Error("[passflow] the issuer has no authorization endpoint");
|
|
405
|
+
const codeVerifier = oauth4webapi.generateRandomCodeVerifier();
|
|
406
|
+
const state = oauth4webapi.generateRandomState();
|
|
407
|
+
const nonce = oauth4webapi.generateRandomNonce();
|
|
408
|
+
const url = new URL(as.authorization_endpoint);
|
|
409
|
+
url.search = new URLSearchParams({
|
|
410
|
+
client_id: config.clientId,
|
|
411
|
+
redirect_uri: redirectUri,
|
|
412
|
+
response_type: "code",
|
|
413
|
+
scope: config.scopes.join(" "),
|
|
414
|
+
state,
|
|
415
|
+
nonce,
|
|
416
|
+
code_challenge: await oauth4webapi.calculatePKCECodeChallenge(codeVerifier),
|
|
417
|
+
code_challenge_method: "S256"
|
|
418
|
+
}).toString();
|
|
419
|
+
return {
|
|
420
|
+
url: url.href,
|
|
421
|
+
state,
|
|
422
|
+
nonce,
|
|
423
|
+
codeVerifier
|
|
424
|
+
};
|
|
425
|
+
},
|
|
426
|
+
/**
|
|
427
|
+
* Checks `state`, redeems the code, validates the ID token (iss, aud, exp, nonce) and reads UserInfo, whose
|
|
428
|
+
* `sub` must equal the ID token's. Throws on any failure, a refresh token without a numeric `exp` included.
|
|
429
|
+
* The ID token is returned too, for sign-out's `id_token_hint`.
|
|
430
|
+
*/
|
|
431
|
+
async signIn(callbackUrl, transaction) {
|
|
432
|
+
const as = await server();
|
|
433
|
+
const params = oauth4webapi.validateAuthResponse(as, client(), callbackUrl, transaction.state);
|
|
434
|
+
const response = await oauth4webapi.authorizationCodeGrantRequest(as, client(), clientAuth, params, redirectUri, transaction.codeVerifier, requestOptions);
|
|
435
|
+
const result = await oauth4webapi.processAuthorizationCodeResponse(as, client(), response, {
|
|
436
|
+
expectedNonce: transaction.nonce,
|
|
437
|
+
requireIdToken: true
|
|
438
|
+
});
|
|
439
|
+
const claims = oauth4webapi.getValidatedIdTokenClaims(result);
|
|
440
|
+
if (claims === void 0 || result.id_token === void 0) throw new Error("[passflow] the token response has no ID token");
|
|
441
|
+
const accessTokenExpiresAt = accessTokenExpiry(result);
|
|
442
|
+
const refreshTokenExpiresAt = unverifiedExp(result.refresh_token);
|
|
443
|
+
if (accessTokenExpiresAt === void 0 || result.refresh_token === void 0 || refreshTokenExpiresAt === void 0) throw new Error("[passflow] the token response needs an access token expiry and a refresh token with exp");
|
|
444
|
+
const userInfo = await oauth4webapi.processUserInfoResponse(as, client(), claims.sub, await oauth4webapi.userInfoRequest(as, client(), result.access_token, requestOptions));
|
|
445
|
+
return {
|
|
446
|
+
accessToken: result.access_token,
|
|
447
|
+
accessTokenExpiresAt,
|
|
448
|
+
refreshToken: result.refresh_token,
|
|
449
|
+
refreshTokenExpiresAt,
|
|
450
|
+
idToken: result.id_token,
|
|
451
|
+
userInfo
|
|
452
|
+
};
|
|
453
|
+
},
|
|
454
|
+
/**
|
|
455
|
+
* Redeems the refresh token. A response with no new refresh token keeps the old one and its `exp`; a new
|
|
456
|
+
* one without a numeric `exp` counts as `failed`. An ID token in the response is returned to replace the kept one.
|
|
457
|
+
*/
|
|
458
|
+
async refresh(refreshToken, refreshTokenExpiresAt) {
|
|
459
|
+
try {
|
|
460
|
+
const as = await server();
|
|
461
|
+
const response = await oauth4webapi.refreshTokenGrantRequest(as, client(), clientAuth, refreshToken, requestOptions);
|
|
462
|
+
const result = await oauth4webapi.processRefreshTokenResponse(as, client(), response);
|
|
463
|
+
const accessTokenExpiresAt = accessTokenExpiry(result);
|
|
464
|
+
const nextRefreshToken = result.refresh_token ?? refreshToken;
|
|
465
|
+
const nextExpiresAt = result.refresh_token === void 0 ? refreshTokenExpiresAt : unverifiedExp(result.refresh_token);
|
|
466
|
+
if (accessTokenExpiresAt === void 0 || nextExpiresAt === void 0) return { kind: "failed" };
|
|
467
|
+
const tokens = {
|
|
468
|
+
accessToken: result.access_token,
|
|
469
|
+
accessTokenExpiresAt,
|
|
470
|
+
refreshToken: nextRefreshToken,
|
|
471
|
+
refreshTokenExpiresAt: nextExpiresAt
|
|
472
|
+
};
|
|
473
|
+
if (result.id_token !== void 0) tokens.idToken = result.id_token;
|
|
474
|
+
return {
|
|
475
|
+
kind: "refreshed",
|
|
476
|
+
tokens
|
|
477
|
+
};
|
|
478
|
+
} catch (error) {
|
|
479
|
+
return endsSession(error) ? { kind: "ended" } : { kind: "failed" };
|
|
480
|
+
}
|
|
481
|
+
},
|
|
482
|
+
/** Revokes the refresh token. The result is ignored: sign-out goes on either way. */
|
|
483
|
+
async revoke(refreshToken) {
|
|
484
|
+
try {
|
|
485
|
+
const as = await server();
|
|
486
|
+
await oauth4webapi.revocationRequest(as, client(), clientAuth, refreshToken, requestOptions);
|
|
487
|
+
} catch {}
|
|
488
|
+
},
|
|
489
|
+
/**
|
|
490
|
+
* Passflow's end-session URL with `client_id`, the app's home page as the return address and, when the
|
|
491
|
+
* session holds one, the ID token as `id_token_hint`: Passflow then ends its session with no confirmation
|
|
492
|
+
* page. Without a hint, Passflow asks the user to confirm. `undefined` when discovery fails or names no
|
|
493
|
+
* end-session endpoint.
|
|
494
|
+
*/
|
|
495
|
+
async endSessionUrl(idTokenHint) {
|
|
496
|
+
try {
|
|
497
|
+
const as = await server();
|
|
498
|
+
if (as.end_session_endpoint === void 0) return;
|
|
499
|
+
const url = new URL(as.end_session_endpoint);
|
|
500
|
+
const params = new URLSearchParams();
|
|
501
|
+
if (idTokenHint !== void 0) params.set("id_token_hint", idTokenHint);
|
|
502
|
+
params.set("client_id", config.clientId);
|
|
503
|
+
params.set("post_logout_redirect_uri", `${config.baseUrl}/`);
|
|
504
|
+
url.search = params.toString();
|
|
505
|
+
return url.href;
|
|
506
|
+
} catch {
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
// src/session/seal.ts
|
|
513
|
+
/** HKDF `info` for the session cookie's key. */
|
|
514
|
+
const SESSION_KEY_INFO = "passflow/session/v1";
|
|
515
|
+
/** HKDF `info` for the transaction cookie's key. A sealed transaction never opens as a session, or back. */
|
|
516
|
+
const TRANSACTION_KEY_INFO = "passflow/txn/v1";
|
|
517
|
+
const encoder = new TextEncoder();
|
|
518
|
+
/** A 256-bit key derived from the app's secret with HKDF-SHA256, empty salt, and `info`. WebCrypto only. */
|
|
519
|
+
async function deriveKey(secret, info) {
|
|
520
|
+
const base = await crypto.subtle.importKey("raw", encoder.encode(secret), "HKDF", false, ["deriveBits"]);
|
|
521
|
+
const bits = await crypto.subtle.deriveBits({
|
|
522
|
+
name: "HKDF",
|
|
523
|
+
hash: "SHA-256",
|
|
524
|
+
salt: /* @__PURE__ */ new Uint8Array(),
|
|
525
|
+
info: encoder.encode(info)
|
|
526
|
+
}, base, 256);
|
|
527
|
+
return new Uint8Array(bits);
|
|
528
|
+
}
|
|
529
|
+
/** A compact JWE, `dir` with `A256GCM`: encrypted and authenticated with `key`. */
|
|
530
|
+
function seal(payload, key) {
|
|
531
|
+
return new jose.EncryptJWT(payload).setProtectedHeader({
|
|
532
|
+
alg: "dir",
|
|
533
|
+
enc: "A256GCM"
|
|
534
|
+
}).encrypt(key);
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* The payload of a value `seal` made with `key`, or `null` for anything else: a tampered value, another key,
|
|
538
|
+
* another algorithm, or an `exp` that has passed at `now` (in seconds).
|
|
539
|
+
*/
|
|
540
|
+
async function open(value, key, now) {
|
|
541
|
+
try {
|
|
542
|
+
const { payload } = await (0, jose.jwtDecrypt)(value, key, {
|
|
543
|
+
keyManagementAlgorithms: ["dir"],
|
|
544
|
+
contentEncryptionAlgorithms: ["A256GCM"],
|
|
545
|
+
currentDate: /* @__PURE__ */ new Date(now * 1e3),
|
|
546
|
+
requiredClaims: ["exp"],
|
|
547
|
+
clockTolerance: 0
|
|
548
|
+
});
|
|
549
|
+
return typeof payload.exp === "number" && payload.exp > now ? payload : null;
|
|
550
|
+
} catch {
|
|
551
|
+
return null;
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
// src/session/manager.ts
|
|
555
|
+
/**
|
|
556
|
+
* A refresh starts once the access token has this many seconds left, or fewer, and at most half its lifetime:
|
|
557
|
+
* a one-minute token is then used for 30 s instead of refreshing on every request.
|
|
558
|
+
*/
|
|
559
|
+
const REFRESH_MARGIN = 60;
|
|
560
|
+
/** How long a sign-in may take, from `/auth/login` to the callback. */
|
|
561
|
+
const TRANSACTION_LIFETIME = 600;
|
|
562
|
+
const NO_STORE = "no-store";
|
|
563
|
+
const RETURN_TO_BASE = "https://return-to.invalid";
|
|
564
|
+
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
565
|
+
/** A path that starts with exactly one `/` and holds no `\` or control character. */
|
|
566
|
+
function isPlainPath(path) {
|
|
567
|
+
return path.startsWith("/") && !path.startsWith("//") && !path.includes("\\") && !CONTROL.test(path);
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* `returnTo` when it is a relative path on the app's own origin, else `/`. The path is normalised first (dot
|
|
571
|
+
* segments removed, as the browser would), and the result is checked again, so `/..//evil.com`, which normalises
|
|
572
|
+
* to `//evil.com`, is refused. Checked without the config, so a page can build a sign-in link before the
|
|
573
|
+
* environment is read.
|
|
574
|
+
*/
|
|
575
|
+
function safeReturnTo(returnTo) {
|
|
576
|
+
if (typeof returnTo !== "string" || !isPlainPath(returnTo)) return "/";
|
|
577
|
+
let url;
|
|
578
|
+
try {
|
|
579
|
+
url = new URL(returnTo, RETURN_TO_BASE);
|
|
580
|
+
} catch {
|
|
581
|
+
return "/";
|
|
582
|
+
}
|
|
583
|
+
if (url.origin !== RETURN_TO_BASE) return "/";
|
|
584
|
+
const normalised = `${url.pathname}${url.search}${url.hash}`;
|
|
585
|
+
if (!isPlainPath(normalised)) return "/";
|
|
586
|
+
try {
|
|
587
|
+
return new URL(normalised, RETURN_TO_BASE).origin === RETURN_TO_BASE ? normalised : "/";
|
|
588
|
+
} catch {
|
|
589
|
+
return "/";
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
function isRecord(value) {
|
|
593
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
594
|
+
}
|
|
595
|
+
function isTime(value) {
|
|
596
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
597
|
+
}
|
|
598
|
+
/** True when a sealed value was made for this issuer and client: one sealed for another reads as absent. */
|
|
599
|
+
function isBound(payload, binding) {
|
|
600
|
+
return payload.iss === binding.iss && payload.cid === binding.cid;
|
|
601
|
+
}
|
|
602
|
+
function asSessionPayload(payload, binding) {
|
|
603
|
+
if (payload === null || !isBound(payload, binding) || payload.v !== 1 || !isRecord(payload.user) || typeof payload.user.sub !== "string" || typeof payload.at !== "string" || !isTime(payload.atExp) || !isTime(payload.atIat) || typeof payload.rt !== "string" || payload.it !== void 0 && typeof payload.it !== "string" || !isTime(payload.iat) || !isTime(payload.exp)) return null;
|
|
604
|
+
return payload;
|
|
605
|
+
}
|
|
606
|
+
function asTransactionPayload(payload, binding) {
|
|
607
|
+
if (payload === null || !isBound(payload, binding) || typeof payload.state !== "string" || typeof payload.nonce !== "string" || typeof payload.codeVerifier !== "string" || typeof payload.returnTo !== "string" || !isTime(payload.exp)) return null;
|
|
608
|
+
return payload;
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* The user from UserInfo: `email_verified` becomes `emailVerified`; a claim of the wrong type is dropped, and so
|
|
612
|
+
* is every claim `PassflowUser` doesn't name.
|
|
613
|
+
*/
|
|
614
|
+
function toUser(info) {
|
|
615
|
+
const { sub, email, email_verified, name, picture } = info;
|
|
616
|
+
const user = { sub };
|
|
617
|
+
if (typeof email === "string") user.email = email;
|
|
618
|
+
if (typeof email_verified === "boolean") user.emailVerified = email_verified;
|
|
619
|
+
if (typeof name === "string") user.name = name;
|
|
620
|
+
if (typeof picture === "string") user.picture = picture;
|
|
621
|
+
return user;
|
|
622
|
+
}
|
|
623
|
+
const toSession = (payload) => ({
|
|
624
|
+
user: payload.user,
|
|
625
|
+
expiresAt: payload.exp
|
|
626
|
+
});
|
|
627
|
+
const escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => `&#${String(c.charCodeAt(0))};`);
|
|
628
|
+
/**
|
|
629
|
+
* 503 for a sign-in the issuer could not serve: no answer (a network error or a timeout), or a 5xx. No retry:
|
|
630
|
+
* the user tries again later.
|
|
631
|
+
*/
|
|
632
|
+
function issuerUnreachable(setCookies) {
|
|
633
|
+
const headers = new Headers({
|
|
634
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
635
|
+
"Cache-Control": NO_STORE
|
|
636
|
+
});
|
|
637
|
+
for (const cookie of setCookies) headers.append("Set-Cookie", cookie);
|
|
638
|
+
return new Response("Sign-in is unavailable: the Passflow issuer could not be reached. Try again later.", {
|
|
639
|
+
status: 503,
|
|
640
|
+
headers
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* False for a prefetch the request declares (`Sec-Purpose`, `Purpose`, or `Next-Router-Prefetch` where the
|
|
645
|
+
* framework passes it on; the Next.js proxy may strip it, so sign-out links must be plain anchors) and for a
|
|
646
|
+
* request another site started (`Sec-Fetch-Site` other than `same-origin` or `none`). A browser that sends no
|
|
647
|
+
* `Sec-Fetch-Site` counts as deliberate.
|
|
648
|
+
*/
|
|
649
|
+
function isDeliberateNavigation(request) {
|
|
650
|
+
const purpose = `${request.headers.get("sec-purpose") ?? ""} ${request.headers.get("purpose") ?? ""}`;
|
|
651
|
+
if (/prefetch/i.test(purpose) || request.headers.has("next-router-prefetch")) return false;
|
|
652
|
+
const site = request.headers.get("sec-fetch-site");
|
|
653
|
+
return site === null || site === "same-origin" || site === "none";
|
|
654
|
+
}
|
|
655
|
+
function redirect(location, setCookies) {
|
|
656
|
+
const headers = new Headers({
|
|
657
|
+
Location: location,
|
|
658
|
+
"Cache-Control": NO_STORE
|
|
659
|
+
});
|
|
660
|
+
for (const cookie of setCookies) headers.append("Set-Cookie", cookie);
|
|
661
|
+
return new Response(null, {
|
|
662
|
+
status: 302,
|
|
663
|
+
headers
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* The server-side sign-in session for a web app: the auth routes, an encrypted and chunked session cookie,
|
|
668
|
+
* and refresh when the access token is due. Framework-neutral: it reads web `Request`s and returns web
|
|
669
|
+
* `Response`s. The config is checked on first use and throws `TypeError` naming what is missing.
|
|
670
|
+
*/
|
|
671
|
+
function createSessionManager(config) {
|
|
672
|
+
let resolved;
|
|
673
|
+
const ready = () => {
|
|
674
|
+
if (resolved === void 0) {
|
|
675
|
+
const checked = resolveConfig(config);
|
|
676
|
+
const nowSeconds = () => Math.floor(checked.now().getTime() / 1e3);
|
|
677
|
+
resolved = {
|
|
678
|
+
config: checked,
|
|
679
|
+
binding: {
|
|
680
|
+
iss: checked.issuer.href,
|
|
681
|
+
cid: checked.clientId
|
|
682
|
+
},
|
|
683
|
+
oidc: createOidcClient(checked, nowSeconds),
|
|
684
|
+
sessionKey: deriveKey(checked.secret, SESSION_KEY_INFO),
|
|
685
|
+
transactionKey: deriveKey(checked.secret, TRANSACTION_KEY_INFO)
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
return resolved;
|
|
689
|
+
};
|
|
690
|
+
const now = () => Math.floor(ready().config.now().getTime() / 1e3);
|
|
691
|
+
/**
|
|
692
|
+
* A same-origin path as an absolute URL on `baseUrl`. Redirects are absolute because some frameworks (the
|
|
693
|
+
* Next.js proxy) refuse a relative `Location`. `path` has passed `safeReturnTo`, so it stays on the app.
|
|
694
|
+
*/
|
|
695
|
+
const appUrl = (path) => new URL(path, ready().config.baseUrl).href;
|
|
696
|
+
async function readSession(cookieHeader) {
|
|
697
|
+
const value = readSessionValue(cookieHeader, ready().config.secure);
|
|
698
|
+
if (value === void 0) return null;
|
|
699
|
+
const { sessionKey, binding } = ready();
|
|
700
|
+
return asSessionPayload(await open(value, await sessionKey, now()), binding);
|
|
701
|
+
}
|
|
702
|
+
/** Seals `payload` into session cookies. Throws `SessionTooLargeError` over the chunk limit. */
|
|
703
|
+
async function writeSession(payload, cookieHeader) {
|
|
704
|
+
const { config: c, sessionKey } = ready();
|
|
705
|
+
return writeSessionCookies(await seal(payload, await sessionKey), cookieHeader, {
|
|
706
|
+
maxAge: Math.min(payload.exp - now(), MAX_COOKIE_AGE),
|
|
707
|
+
secure: c.secure
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
function signInFailed(setCookies) {
|
|
711
|
+
const href = escapeHtml(ready().config.routes.login);
|
|
712
|
+
const headers = new Headers({
|
|
713
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
714
|
+
"Cache-Control": NO_STORE
|
|
715
|
+
});
|
|
716
|
+
for (const cookie of setCookies) headers.append("Set-Cookie", cookie);
|
|
717
|
+
const body = `<!doctype html><title>Sign-in failed</title><p>Sign-in failed. Try again.</p><p><a href="${href}">Sign in</a></p>`;
|
|
718
|
+
return new Response(body, {
|
|
719
|
+
status: 400,
|
|
720
|
+
headers
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
async function login(url) {
|
|
724
|
+
const { config: c, binding, oidc, transactionKey } = ready();
|
|
725
|
+
let request;
|
|
726
|
+
try {
|
|
727
|
+
request = await oidc.authorizationRequest();
|
|
728
|
+
} catch (error) {
|
|
729
|
+
if (isIssuerUnavailable(error)) return issuerUnreachable([]);
|
|
730
|
+
throw error;
|
|
731
|
+
}
|
|
732
|
+
const sealed = await seal({
|
|
733
|
+
...binding,
|
|
734
|
+
state: request.state,
|
|
735
|
+
nonce: request.nonce,
|
|
736
|
+
codeVerifier: request.codeVerifier,
|
|
737
|
+
returnTo: safeReturnTo(url.searchParams.get("returnTo")),
|
|
738
|
+
exp: now() + TRANSACTION_LIFETIME
|
|
739
|
+
}, await transactionKey);
|
|
740
|
+
const cookie = serializeCookie(transactionCookieName(c.secure), sealed, {
|
|
741
|
+
path: "/",
|
|
742
|
+
maxAge: TRANSACTION_LIFETIME,
|
|
743
|
+
secure: c.secure
|
|
744
|
+
});
|
|
745
|
+
return redirect(request.url, [cookie]);
|
|
746
|
+
}
|
|
747
|
+
async function callback(url, cookieHeader) {
|
|
748
|
+
const { config: c, binding, oidc, transactionKey } = ready();
|
|
749
|
+
const transactionName = transactionCookieName(c.secure);
|
|
750
|
+
const clearTransaction = [expireCookie(transactionName, "/", c.secure)];
|
|
751
|
+
if (!c.secure) clearTransaction.push(expireCookie(transactionName, c.routes.callback, false));
|
|
752
|
+
try {
|
|
753
|
+
const sealed = readCookie(cookieHeader, transactionName);
|
|
754
|
+
const transaction = sealed === void 0 ? null : asTransactionPayload(await open(sealed, await transactionKey, now()), binding);
|
|
755
|
+
if (transaction === null) return signInFailed(clearTransaction);
|
|
756
|
+
const result = await oidc.signIn(url, transaction);
|
|
757
|
+
const payload = {
|
|
758
|
+
...binding,
|
|
759
|
+
v: 1,
|
|
760
|
+
user: toUser(result.userInfo),
|
|
761
|
+
at: result.accessToken,
|
|
762
|
+
atExp: result.accessTokenExpiresAt,
|
|
763
|
+
atIat: now(),
|
|
764
|
+
rt: result.refreshToken,
|
|
765
|
+
it: result.idToken,
|
|
766
|
+
iat: now(),
|
|
767
|
+
exp: result.refreshTokenExpiresAt
|
|
768
|
+
};
|
|
769
|
+
if (payload.exp <= payload.iat) return signInFailed(clearTransaction);
|
|
770
|
+
const { setCookies } = await writeSession(payload, cookieHeader);
|
|
771
|
+
return redirect(appUrl(safeReturnTo(transaction.returnTo)), [...setCookies, ...clearTransaction]);
|
|
772
|
+
} catch (error) {
|
|
773
|
+
if (isIssuerUnavailable(error)) return issuerUnreachable(clearTransaction);
|
|
774
|
+
if (error instanceof SessionTooLargeError) console.error(`[passflow] sign-in failed: ${error.message}`);
|
|
775
|
+
return signInFailed(clearTransaction);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
async function logout(cookieHeader) {
|
|
779
|
+
const { config: c, oidc } = ready();
|
|
780
|
+
const payload = await readSession(cookieHeader);
|
|
781
|
+
if (payload !== null) await oidc.revoke(payload.rt);
|
|
782
|
+
return redirect(await oidc.endSessionUrl(payload?.it) ?? appUrl("/"), [...expireSessionCookies(cookieHeader, c.secure), expireCookie(transactionCookieName(c.secure), "/", c.secure)]);
|
|
783
|
+
}
|
|
784
|
+
/** Any other path: continues, refreshing first when the access token is due. */
|
|
785
|
+
async function proceed(cookieHeader) {
|
|
786
|
+
const payload = await readSession(cookieHeader);
|
|
787
|
+
if (payload === null) return {
|
|
788
|
+
kind: "continue",
|
|
789
|
+
session: null,
|
|
790
|
+
setCookies: []
|
|
791
|
+
};
|
|
792
|
+
const margin = Math.min(REFRESH_MARGIN, Math.max(0, Math.floor((payload.atExp - payload.atIat) / 2)));
|
|
793
|
+
if (payload.atExp - margin > now()) return {
|
|
794
|
+
kind: "continue",
|
|
795
|
+
session: toSession(payload),
|
|
796
|
+
setCookies: []
|
|
797
|
+
};
|
|
798
|
+
const { config: c, oidc } = ready();
|
|
799
|
+
const signedOut = replaceSessionCookies(cookieHeader, []);
|
|
800
|
+
const result = await oidc.refresh(payload.rt, payload.exp);
|
|
801
|
+
if (result.kind === "ended") return {
|
|
802
|
+
kind: "continue",
|
|
803
|
+
session: null,
|
|
804
|
+
setCookies: expireSessionCookies(cookieHeader, c.secure),
|
|
805
|
+
cookieHeader: signedOut
|
|
806
|
+
};
|
|
807
|
+
if (result.kind === "failed") {
|
|
808
|
+
const at = now();
|
|
809
|
+
if (payload.exp > at && payload.atExp > at) return {
|
|
810
|
+
kind: "continue",
|
|
811
|
+
session: toSession(payload),
|
|
812
|
+
setCookies: []
|
|
813
|
+
};
|
|
814
|
+
return {
|
|
815
|
+
kind: "continue",
|
|
816
|
+
session: null,
|
|
817
|
+
setCookies: [],
|
|
818
|
+
cookieHeader: signedOut
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
const next = {
|
|
822
|
+
...payload,
|
|
823
|
+
at: result.tokens.accessToken,
|
|
824
|
+
atExp: result.tokens.accessTokenExpiresAt,
|
|
825
|
+
atIat: now(),
|
|
826
|
+
rt: result.tokens.refreshToken,
|
|
827
|
+
exp: result.tokens.refreshTokenExpiresAt
|
|
828
|
+
};
|
|
829
|
+
if (result.tokens.idToken !== void 0) next.it = result.tokens.idToken;
|
|
830
|
+
if (next.exp <= now()) return {
|
|
831
|
+
kind: "continue",
|
|
832
|
+
session: null,
|
|
833
|
+
setCookies: [],
|
|
834
|
+
cookieHeader: signedOut
|
|
835
|
+
};
|
|
836
|
+
try {
|
|
837
|
+
const { setCookies, pairs } = await writeSession(next, cookieHeader);
|
|
838
|
+
return {
|
|
839
|
+
kind: "continue",
|
|
840
|
+
session: toSession(next),
|
|
841
|
+
setCookies,
|
|
842
|
+
cookieHeader: replaceSessionCookies(cookieHeader, pairs)
|
|
843
|
+
};
|
|
844
|
+
} catch (error) {
|
|
845
|
+
if (error instanceof SessionTooLargeError) console.error(`[passflow] refresh could not store the session: ${error.message}`);
|
|
846
|
+
return {
|
|
847
|
+
kind: "continue",
|
|
848
|
+
session: null,
|
|
849
|
+
setCookies: [],
|
|
850
|
+
cookieHeader: signedOut
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
return {
|
|
855
|
+
async handle(request) {
|
|
856
|
+
const url = new URL(request.url);
|
|
857
|
+
const cookieHeader = request.headers.get("cookie");
|
|
858
|
+
const { routes } = ready().config;
|
|
859
|
+
const route = [
|
|
860
|
+
routes.login,
|
|
861
|
+
routes.callback,
|
|
862
|
+
routes.logout
|
|
863
|
+
].find((path) => url.pathname === path || url.pathname === `${path}/`);
|
|
864
|
+
if (route === void 0) return proceed(cookieHeader);
|
|
865
|
+
if (request.method !== "GET") return {
|
|
866
|
+
kind: "response",
|
|
867
|
+
response: new Response(null, {
|
|
868
|
+
status: 405,
|
|
869
|
+
headers: {
|
|
870
|
+
Allow: "GET",
|
|
871
|
+
"Cache-Control": NO_STORE
|
|
872
|
+
}
|
|
873
|
+
})
|
|
874
|
+
};
|
|
875
|
+
if (route === routes.login) return {
|
|
876
|
+
kind: "response",
|
|
877
|
+
response: await login(url)
|
|
878
|
+
};
|
|
879
|
+
if (route === routes.callback) return {
|
|
880
|
+
kind: "response",
|
|
881
|
+
response: await callback(url, cookieHeader)
|
|
882
|
+
};
|
|
883
|
+
if (!isDeliberateNavigation(request)) return {
|
|
884
|
+
kind: "response",
|
|
885
|
+
response: new Response(null, {
|
|
886
|
+
status: 204,
|
|
887
|
+
headers: { "Cache-Control": NO_STORE }
|
|
888
|
+
})
|
|
889
|
+
};
|
|
890
|
+
return {
|
|
891
|
+
kind: "response",
|
|
892
|
+
response: await logout(cookieHeader)
|
|
893
|
+
};
|
|
894
|
+
},
|
|
895
|
+
async getSession(cookieHeader) {
|
|
896
|
+
const payload = await readSession(cookieHeader);
|
|
897
|
+
return payload !== null && payload.atExp > now() ? toSession(payload) : null;
|
|
898
|
+
},
|
|
899
|
+
async getAccessToken(cookieHeader) {
|
|
900
|
+
const payload = await readSession(cookieHeader);
|
|
901
|
+
return payload !== null && payload.atExp > now() ? payload.at : null;
|
|
902
|
+
},
|
|
903
|
+
loginPath(returnTo) {
|
|
904
|
+
return `${config.routes?.login ?? DEFAULT_ROUTES.login}?returnTo=${encodeURIComponent(safeReturnTo(returnTo))}`;
|
|
905
|
+
},
|
|
906
|
+
isSameOrigin(request) {
|
|
907
|
+
const origin = request.headers.get("origin");
|
|
908
|
+
if (origin !== null) return origin === ready().config.baseUrl;
|
|
909
|
+
const site = request.headers.get("sec-fetch-site");
|
|
910
|
+
return site === "same-origin" || site === "none";
|
|
911
|
+
},
|
|
912
|
+
hasSessionCookie,
|
|
913
|
+
unauthorized() {
|
|
914
|
+
return new Response(null, {
|
|
915
|
+
status: 401,
|
|
916
|
+
headers: { "Cache-Control": NO_STORE }
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
exports.configFromEnv = configFromEnv;
|
|
922
|
+
exports.createSessionManager = createSessionManager;
|
|
923
|
+
exports.hasSessionCookie = hasSessionCookie;
|