@fluixi/oauth2 1.0.0-alpha.10 → 1.0.0-alpha.100
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/LICENSE +1 -1
- package/dist/backchannel.cjs +462 -0
- package/dist/backchannel.d.ts +39 -0
- package/dist/backchannel.d.ts.map +1 -0
- package/dist/backchannel.js +97 -0
- package/dist/backchannel.mjs +307 -0
- package/dist/{browser-36FHB6KG.mjs → browser-TV25RBLT.mjs} +2 -2
- package/dist/browser.cjs +6 -1
- package/dist/browser.mjs +6 -1
- package/dist/callback.cjs +2 -2
- package/dist/callback.js +1 -1
- package/dist/callback.mjs +3 -3
- package/dist/{chunk-F52RUVDM.mjs → chunk-2B3I72DV.mjs} +1 -1
- package/dist/chunk-KOP5Z4LB.mjs +108 -0
- package/dist/{chunk-OGS6MQ3D.mjs → chunk-KTGVSZE6.mjs} +1 -1
- package/dist/discovery.cjs +6 -1
- package/dist/discovery.d.ts.map +1 -1
- package/dist/discovery.js +6 -1
- package/dist/discovery.mjs +6 -1
- package/dist/dpop-O3HWR7AH.mjs +22 -0
- package/dist/{dpop-GOWCCCFR.mjs → dpop-SGWG3K2I.mjs} +4 -4
- package/dist/index.cjs +108 -8
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.mjs +112 -12
- package/dist/module.cjs +1 -1
- package/dist/module.mjs +1 -1
- package/dist/server.cjs +705 -143
- package/dist/server.d.ts +71 -4
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +455 -64
- package/dist/server.mjs +588 -145
- package/dist/service-client.cjs +7 -2
- package/dist/service-client.mjs +9 -4
- package/dist/service.cjs +104 -5
- package/dist/service.d.ts.map +1 -1
- package/dist/service.js +38 -6
- package/dist/service.mjs +105 -6
- package/dist/session-monitor.cjs +98 -0
- package/dist/session-monitor.d.ts +32 -0
- package/dist/session-monitor.d.ts.map +1 -0
- package/dist/session-monitor.js +104 -0
- package/dist/session-monitor.mjs +77 -0
- package/dist/tokens.cjs +1 -1
- package/dist/tokens.d.ts +2 -2
- package/dist/tokens.d.ts.map +1 -1
- package/dist/tokens.js +1 -1
- package/dist/tokens.mjs +1 -1
- package/dist/tsconfig.lib.tsbuildinfo +1 -1
- package/dist/types.d.ts +8 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/verify.cjs +7 -2
- package/dist/verify.mjs +12 -7
- package/package.json +22 -16
package/LICENSE
CHANGED
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __esm = (fn, res) => function __init() {
|
|
9
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
10
|
+
};
|
|
11
|
+
var __export = (target, all) => {
|
|
12
|
+
for (var name in all)
|
|
13
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
14
|
+
};
|
|
15
|
+
var __copyProps = (to, from, except, desc) => {
|
|
16
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
17
|
+
for (let key of __getOwnPropNames(from))
|
|
18
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
19
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
20
|
+
}
|
|
21
|
+
return to;
|
|
22
|
+
};
|
|
23
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
24
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
25
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
26
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
27
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
28
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
29
|
+
mod
|
|
30
|
+
));
|
|
31
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
|
+
|
|
33
|
+
// src/types.ts
|
|
34
|
+
var OAuthError;
|
|
35
|
+
var init_types = __esm({
|
|
36
|
+
"src/types.ts"() {
|
|
37
|
+
"use strict";
|
|
38
|
+
OAuthError = class extends Error {
|
|
39
|
+
constructor(message, code, description) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.code = code;
|
|
42
|
+
this.description = description;
|
|
43
|
+
this.name = "OAuthError";
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
// src/dpop.ts
|
|
50
|
+
var dpop_exports = {};
|
|
51
|
+
__export(dpop_exports, {
|
|
52
|
+
boundKeyOf: () => boundKeyOf,
|
|
53
|
+
createDpopKey: () => createDpopKey,
|
|
54
|
+
exportDpopKey: () => exportDpopKey,
|
|
55
|
+
importDpopKey: () => importDpopKey,
|
|
56
|
+
nonceFrom: () => nonceFrom,
|
|
57
|
+
proofFor: () => proofFor,
|
|
58
|
+
thumbprintOf: () => thumbprintOf,
|
|
59
|
+
wantsNonce: () => wantsNonce
|
|
60
|
+
});
|
|
61
|
+
async function loadJose() {
|
|
62
|
+
try {
|
|
63
|
+
return await import("jose");
|
|
64
|
+
} catch {
|
|
65
|
+
throw new OAuthError(
|
|
66
|
+
"DPoP needs `jose`. Install it: npm i jose. It is an optional peer, so a client not using DPoP does not carry it.",
|
|
67
|
+
"jose_missing"
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
async function createDpopKey(alg = "ES256", options = {}) {
|
|
72
|
+
const jose = await loadJose();
|
|
73
|
+
const { privateKey, publicKey } = await jose.generateKeyPair(alg, {
|
|
74
|
+
extractable: options.extractable ?? false
|
|
75
|
+
});
|
|
76
|
+
const publicJwk = { ...await jose.exportJWK(publicKey) };
|
|
77
|
+
return {
|
|
78
|
+
privateKey,
|
|
79
|
+
publicJwk,
|
|
80
|
+
thumbprint: await jose.calculateJwkThumbprint(publicJwk, "sha256"),
|
|
81
|
+
alg
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
async function exportDpopKey(key) {
|
|
85
|
+
const jose = await loadJose();
|
|
86
|
+
return { jwk: { ...await jose.exportJWK(key.privateKey) }, alg: key.alg };
|
|
87
|
+
}
|
|
88
|
+
async function importDpopKey(stored) {
|
|
89
|
+
const jose = await loadJose();
|
|
90
|
+
const privateKey = await jose.importJWK(stored.jwk, stored.alg);
|
|
91
|
+
const publicJwk = Object.fromEntries(Object.entries(stored.jwk).filter(([k]) => !PRIVATE_MEMBERS.has(k)));
|
|
92
|
+
return {
|
|
93
|
+
privateKey,
|
|
94
|
+
publicJwk,
|
|
95
|
+
thumbprint: await jose.calculateJwkThumbprint(publicJwk, "sha256"),
|
|
96
|
+
alg: stored.alg
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
async function thumbprintOf(jwk) {
|
|
100
|
+
const jose = await loadJose();
|
|
101
|
+
return jose.calculateJwkThumbprint(jwk, "sha256");
|
|
102
|
+
}
|
|
103
|
+
async function proofFor(key, options) {
|
|
104
|
+
const jose = await loadJose();
|
|
105
|
+
const htu = (() => {
|
|
106
|
+
try {
|
|
107
|
+
const url = new URL(options.url);
|
|
108
|
+
url.search = "";
|
|
109
|
+
url.hash = "";
|
|
110
|
+
return url.toString();
|
|
111
|
+
} catch {
|
|
112
|
+
return options.url;
|
|
113
|
+
}
|
|
114
|
+
})();
|
|
115
|
+
const claims = {
|
|
116
|
+
htm: options.method.toUpperCase(),
|
|
117
|
+
htu,
|
|
118
|
+
jti: crypto.randomUUID()
|
|
119
|
+
};
|
|
120
|
+
if (options.accessToken) {
|
|
121
|
+
const digest = await crypto.subtle.digest(
|
|
122
|
+
"SHA-256",
|
|
123
|
+
new TextEncoder().encode(options.accessToken)
|
|
124
|
+
);
|
|
125
|
+
let binary = "";
|
|
126
|
+
for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
|
|
127
|
+
claims.ath = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
128
|
+
}
|
|
129
|
+
if (options.nonce) claims.nonce = options.nonce;
|
|
130
|
+
return new jose.SignJWT(claims).setProtectedHeader({ typ: "dpop+jwt", alg: key.alg, jwk: key.publicJwk }).setIssuedAt().sign(key.privateKey);
|
|
131
|
+
}
|
|
132
|
+
function nonceFrom(response) {
|
|
133
|
+
return response.headers.get("dpop-nonce");
|
|
134
|
+
}
|
|
135
|
+
function wantsNonce(error, response) {
|
|
136
|
+
const code = typeof error === "string" ? error : error?.error;
|
|
137
|
+
return code === "use_dpop_nonce" || !!response && !!nonceFrom(response);
|
|
138
|
+
}
|
|
139
|
+
function boundKeyOf(claims) {
|
|
140
|
+
const cnf = claims.cnf;
|
|
141
|
+
return typeof cnf?.jkt === "string" ? cnf.jkt : null;
|
|
142
|
+
}
|
|
143
|
+
var PRIVATE_MEMBERS;
|
|
144
|
+
var init_dpop = __esm({
|
|
145
|
+
"src/dpop.ts"() {
|
|
146
|
+
"use strict";
|
|
147
|
+
init_types();
|
|
148
|
+
PRIVATE_MEMBERS = /* @__PURE__ */ new Set(["d", "p", "q", "dp", "dq", "qi", "oth"]);
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
// src/backchannel.ts
|
|
153
|
+
var backchannel_exports = {};
|
|
154
|
+
__export(backchannel_exports, {
|
|
155
|
+
LOGOUT_EVENT: () => LOGOUT_EVENT,
|
|
156
|
+
idTokenClaims: () => idTokenClaims,
|
|
157
|
+
logoutTokenVerifier: () => logoutTokenVerifier,
|
|
158
|
+
memoryLogouts: () => memoryLogouts
|
|
159
|
+
});
|
|
160
|
+
module.exports = __toCommonJS(backchannel_exports);
|
|
161
|
+
|
|
162
|
+
// src/client-auth.ts
|
|
163
|
+
init_types();
|
|
164
|
+
|
|
165
|
+
// src/discovery.ts
|
|
166
|
+
init_types();
|
|
167
|
+
var cache = /* @__PURE__ */ new Map();
|
|
168
|
+
function documentUrl(issuer) {
|
|
169
|
+
return `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
170
|
+
}
|
|
171
|
+
async function discover(issuer, fetcher = fetch) {
|
|
172
|
+
const cached = cache.get(issuer);
|
|
173
|
+
if (cached) return cached;
|
|
174
|
+
const pending = (async () => {
|
|
175
|
+
let response;
|
|
176
|
+
try {
|
|
177
|
+
response = await fetcher(documentUrl(issuer));
|
|
178
|
+
} catch (cause) {
|
|
179
|
+
const why = cause instanceof Error ? cause.message : String(cause);
|
|
180
|
+
throw new OAuthError(
|
|
181
|
+
typeof window === "undefined" ? (
|
|
182
|
+
// On a server nothing blocks the read: the provider is down, or the address is wrong.
|
|
183
|
+
`Could not reach the provider at ${documentUrl(issuer)}: is it running, and is the issuer right? (${why})`
|
|
184
|
+
) : `Could not read the discovery document at ${documentUrl(issuer)}. In a browser this is usually the provider refusing a cross-origin read: give \`endpoints\` directly, or resolve them on a server. (${why})`,
|
|
185
|
+
"discovery_unreachable"
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
if (!response.ok) {
|
|
189
|
+
throw new OAuthError(
|
|
190
|
+
`Discovery failed for ${issuer}: ${response.status}`,
|
|
191
|
+
"discovery_failed"
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
const doc = await response.json();
|
|
195
|
+
if (!doc.authorization_endpoint || !doc.token_endpoint) {
|
|
196
|
+
throw new OAuthError(
|
|
197
|
+
`${issuer} published a discovery document with no authorization or token endpoint.`,
|
|
198
|
+
"discovery_incomplete"
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
authorization: doc.authorization_endpoint,
|
|
203
|
+
token: doc.token_endpoint,
|
|
204
|
+
userinfo: doc.userinfo_endpoint,
|
|
205
|
+
endSession: doc.end_session_endpoint,
|
|
206
|
+
jwks: doc.jwks_uri,
|
|
207
|
+
introspection: doc.introspection_endpoint,
|
|
208
|
+
revocation: doc.revocation_endpoint,
|
|
209
|
+
checkSession: doc.check_session_iframe,
|
|
210
|
+
issuer: doc.issuer ?? issuer
|
|
211
|
+
};
|
|
212
|
+
})();
|
|
213
|
+
cache.set(issuer, pending);
|
|
214
|
+
pending.catch(() => cache.delete(issuer));
|
|
215
|
+
return pending;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// src/verify.ts
|
|
219
|
+
init_types();
|
|
220
|
+
var TokenError = class extends OAuthError {
|
|
221
|
+
constructor(message, code = "invalid_token") {
|
|
222
|
+
super(message, code);
|
|
223
|
+
this.name = "TokenError";
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
function bearerOf(request) {
|
|
227
|
+
const header = request.headers.get("authorization");
|
|
228
|
+
if (!header) return null;
|
|
229
|
+
const match = header.match(/^(?:Bearer|DPoP)\s+(.+)$/i);
|
|
230
|
+
return match ? match[1].trim() : null;
|
|
231
|
+
}
|
|
232
|
+
async function loadJose2() {
|
|
233
|
+
try {
|
|
234
|
+
return await import("jose");
|
|
235
|
+
} catch {
|
|
236
|
+
throw new OAuthError(
|
|
237
|
+
"Token verification needs `jose`. Install it: npm i jose. It is an optional peer so an app that does not verify does not carry it.",
|
|
238
|
+
"jose_missing"
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
function createTokenVerifier(options) {
|
|
243
|
+
const issuers = (Array.isArray(options.issuer) ? options.issuer : [options.issuer]).filter(Boolean);
|
|
244
|
+
if (!issuers.length) {
|
|
245
|
+
throw new Error("[fluixi/oauth2] createTokenVerifier needs an issuer to accept tokens from.");
|
|
246
|
+
}
|
|
247
|
+
const discoveryIssuer = issuers[0];
|
|
248
|
+
if (options.audience === void 0) {
|
|
249
|
+
throw new Error(
|
|
250
|
+
"[fluixi/oauth2] createTokenVerifier needs an audience, or `audience: false` to say this service really does accept a token minted for any client of the issuer."
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
if (options.audience === false && options.authorizedParty === void 0) {
|
|
254
|
+
console.warn(
|
|
255
|
+
"[fluixi/oauth2] This verifier checks neither `aud` nor `azp`, so a token minted for any client of the issuer is accepted. Set `authorizedParty` if that is not what you meant."
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
const algorithms = options.algorithms ?? ["RS256"];
|
|
259
|
+
if (algorithms.some((alg) => !alg || alg.toLowerCase() === "none")) {
|
|
260
|
+
throw new Error("[fluixi/oauth2] `none` is not a signing algorithm and cannot be accepted.");
|
|
261
|
+
}
|
|
262
|
+
let keys = null;
|
|
263
|
+
async function keySet() {
|
|
264
|
+
if (keys) return keys;
|
|
265
|
+
const jose = await loadJose2();
|
|
266
|
+
if (options.jwks) {
|
|
267
|
+
keys = jose.createLocalJWKSet(options.jwks);
|
|
268
|
+
return keys;
|
|
269
|
+
}
|
|
270
|
+
let uri = options.jwksUri;
|
|
271
|
+
if (!uri) {
|
|
272
|
+
const endpoints = await discover(discoveryIssuer);
|
|
273
|
+
uri = endpoints.jwks;
|
|
274
|
+
}
|
|
275
|
+
if (!uri) {
|
|
276
|
+
throw new OAuthError(
|
|
277
|
+
`${discoveryIssuer} published no jwks_uri. Give the verifier one directly.`,
|
|
278
|
+
"no_jwks"
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
keys = jose.createRemoteJWKSet(new URL(uri));
|
|
282
|
+
return keys;
|
|
283
|
+
}
|
|
284
|
+
const checkProof = async (claims, token, request) => {
|
|
285
|
+
const jose = await loadJose2();
|
|
286
|
+
const { boundKeyOf: boundKeyOf2, thumbprintOf: thumbprintOf2 } = await Promise.resolve().then(() => (init_dpop(), dpop_exports));
|
|
287
|
+
const bound = boundKeyOf2(claims);
|
|
288
|
+
if (!bound) {
|
|
289
|
+
throw new TokenError(
|
|
290
|
+
"This token is not bound to a key, and this service requires binding.",
|
|
291
|
+
"token_not_bound"
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
const proof = request.headers.get("dpop");
|
|
295
|
+
if (!proof) throw new TokenError("The request carried no DPoP proof.", "missing_dpop_proof");
|
|
296
|
+
let payload;
|
|
297
|
+
let header;
|
|
298
|
+
try {
|
|
299
|
+
const result = await jose.jwtVerify(proof, jose.EmbeddedJWK, { typ: "dpop+jwt" });
|
|
300
|
+
payload = result.payload;
|
|
301
|
+
header = result.protectedHeader;
|
|
302
|
+
} catch (cause) {
|
|
303
|
+
throw new TokenError(
|
|
304
|
+
`The DPoP proof did not verify: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
305
|
+
"invalid_dpop_proof"
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
const presented = await thumbprintOf2(header.jwk);
|
|
309
|
+
if (presented !== bound) {
|
|
310
|
+
throw new TokenError(
|
|
311
|
+
"The DPoP proof was signed with a different key from the one this token is bound to.",
|
|
312
|
+
"dpop_key_mismatch"
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
const url = new URL(request.url);
|
|
316
|
+
url.search = "";
|
|
317
|
+
url.hash = "";
|
|
318
|
+
if (payload.htm !== request.method.toUpperCase()) {
|
|
319
|
+
throw new TokenError("The DPoP proof was made for a different method.", "invalid_dpop_proof");
|
|
320
|
+
}
|
|
321
|
+
if (payload.htu !== url.toString()) {
|
|
322
|
+
throw new TokenError("The DPoP proof was made for a different URL.", "invalid_dpop_proof");
|
|
323
|
+
}
|
|
324
|
+
if (typeof payload.ath === "string") {
|
|
325
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
|
|
326
|
+
let binary = "";
|
|
327
|
+
for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
|
|
328
|
+
const expected = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
329
|
+
if (payload.ath !== expected) {
|
|
330
|
+
throw new TokenError("The DPoP proof was made for a different token.", "invalid_dpop_proof");
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
const age = Math.abs(Date.now() / 1e3 - payload.iat);
|
|
334
|
+
if (!Number.isFinite(age) || age > (options.dpopProofAgeSec ?? 10)) {
|
|
335
|
+
throw new TokenError("The DPoP proof is too old to accept.", "invalid_dpop_proof");
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
const verify = async (token, request) => {
|
|
339
|
+
if (!token) throw new TokenError("No token to verify.", "no_token");
|
|
340
|
+
const jose = await loadJose2();
|
|
341
|
+
let payload;
|
|
342
|
+
try {
|
|
343
|
+
({ payload } = await jose.jwtVerify(token, await keySet(), {
|
|
344
|
+
// jose takes a list and accepts any of them, which is what a provider naming
|
|
345
|
+
// itself two ways needs.
|
|
346
|
+
issuer: issuers,
|
|
347
|
+
...options.audience === false ? {} : { audience: options.audience },
|
|
348
|
+
algorithms,
|
|
349
|
+
clockTolerance: options.clockToleranceSec ?? 5
|
|
350
|
+
}));
|
|
351
|
+
} catch (cause) {
|
|
352
|
+
throw new TokenError(
|
|
353
|
+
`The token was not accepted: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
if (options.authorizedParty !== void 0) {
|
|
357
|
+
const allowed = Array.isArray(options.authorizedParty) ? options.authorizedParty : [options.authorizedParty];
|
|
358
|
+
const issuedTo = payload.azp ?? payload.client_id;
|
|
359
|
+
if (typeof issuedTo !== "string" || !allowed.includes(issuedTo)) {
|
|
360
|
+
throw new TokenError("The token was issued to a different client.", "invalid_azp");
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (options.dpop) {
|
|
364
|
+
if (!request) {
|
|
365
|
+
throw new Error(
|
|
366
|
+
"[fluixi/oauth2] `dpop: true` needs the request to read its proof. Use `verify.fromRequest(request)` rather than verifying a bare token."
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
await checkProof(payload, token, request);
|
|
370
|
+
}
|
|
371
|
+
if (options.require) {
|
|
372
|
+
const verdict = options.require(payload);
|
|
373
|
+
if (verdict !== true) {
|
|
374
|
+
throw new TokenError(
|
|
375
|
+
typeof verdict === "string" ? verdict : "The token did not meet this service's requirements.",
|
|
376
|
+
"insufficient_claims"
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return payload;
|
|
381
|
+
};
|
|
382
|
+
const verifier = verify;
|
|
383
|
+
verifier.bearerOf = bearerOf;
|
|
384
|
+
verifier.fromRequest = async (request) => {
|
|
385
|
+
const token = verifier.bearerOf(request);
|
|
386
|
+
if (!token) {
|
|
387
|
+
throw new TokenError("The request carried no bearer token.", "no_token");
|
|
388
|
+
}
|
|
389
|
+
return verify(token, request);
|
|
390
|
+
};
|
|
391
|
+
return verifier;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// src/backchannel.ts
|
|
395
|
+
var LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
|
|
396
|
+
function memoryLogouts(ttlMs = 14 * 24 * 36e5) {
|
|
397
|
+
const sids = /* @__PURE__ */ new Map();
|
|
398
|
+
const subs = /* @__PURE__ */ new Map();
|
|
399
|
+
const prune = (now) => {
|
|
400
|
+
for (const map of [sids, subs]) for (const [key, at] of map) if (now - at > ttlMs) map.delete(key);
|
|
401
|
+
};
|
|
402
|
+
return {
|
|
403
|
+
add(entry) {
|
|
404
|
+
prune(Date.now());
|
|
405
|
+
if (entry.sid) sids.set(entry.sid, entry.at);
|
|
406
|
+
else if (entry.sub) subs.set(entry.sub, Math.max(entry.at, subs.get(entry.sub) ?? 0));
|
|
407
|
+
},
|
|
408
|
+
ended(session) {
|
|
409
|
+
if (session.sid && sids.has(session.sid)) return true;
|
|
410
|
+
const all = session.sub ? subs.get(session.sub) : void 0;
|
|
411
|
+
return all !== void 0 && session.since <= all;
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
function idTokenClaims(idToken) {
|
|
416
|
+
if (!idToken) return {};
|
|
417
|
+
try {
|
|
418
|
+
const part = idToken.split(".")[1] ?? "";
|
|
419
|
+
const json = atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "="));
|
|
420
|
+
const claims = JSON.parse(json);
|
|
421
|
+
return {
|
|
422
|
+
sid: typeof claims.sid === "string" ? claims.sid : void 0,
|
|
423
|
+
sub: typeof claims.sub === "string" ? claims.sub : void 0,
|
|
424
|
+
iat: typeof claims.iat === "number" ? claims.iat : void 0
|
|
425
|
+
};
|
|
426
|
+
} catch {
|
|
427
|
+
return {};
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
function headerOf(token) {
|
|
431
|
+
try {
|
|
432
|
+
const part = token.split(".")[0] ?? "";
|
|
433
|
+
return JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=")));
|
|
434
|
+
} catch {
|
|
435
|
+
return {};
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
function logoutTokenVerifier(options) {
|
|
439
|
+
const verify = createTokenVerifier({
|
|
440
|
+
issuer: options.issuer,
|
|
441
|
+
audience: options.clientId,
|
|
442
|
+
jwksUri: options.jwksUri,
|
|
443
|
+
jwks: options.jwks,
|
|
444
|
+
require: (claims) => {
|
|
445
|
+
const events = claims.events;
|
|
446
|
+
if (!events || typeof events !== "object" || !(LOGOUT_EVENT in events)) return "no logout event";
|
|
447
|
+
if ("nonce" in claims) return "a logout token has no nonce";
|
|
448
|
+
if (typeof claims.sid !== "string" && typeof claims.sub !== "string") return "names no session and no subject";
|
|
449
|
+
return true;
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
return async (token) => {
|
|
453
|
+
const typ = headerOf(token).typ;
|
|
454
|
+
if (typ !== void 0 && typ !== "logout+jwt") throw new Error("not a logout token");
|
|
455
|
+
const claims = await verify(token);
|
|
456
|
+
return {
|
|
457
|
+
sid: typeof claims.sid === "string" ? claims.sid : void 0,
|
|
458
|
+
sub: typeof claims.sub === "string" ? claims.sub : void 0,
|
|
459
|
+
at: (typeof claims.iat === "number" ? claims.iat : Math.floor(Date.now() / 1e3)) * 1e3
|
|
460
|
+
};
|
|
461
|
+
};
|
|
462
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export declare const LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
|
|
2
|
+
/** A logout the provider announced: a session (`sid`), or every session of `sub` begun before `at`. */
|
|
3
|
+
export interface LogoutEntry {
|
|
4
|
+
sid?: string;
|
|
5
|
+
sub?: string;
|
|
6
|
+
/** When the provider said so, in milliseconds. */
|
|
7
|
+
at: number;
|
|
8
|
+
}
|
|
9
|
+
export interface LogoutStore {
|
|
10
|
+
add(entry: LogoutEntry): void | Promise<void>;
|
|
11
|
+
/** Whether a session (its `sid`, its `sub`, and when it signed in) has been logged out since. */
|
|
12
|
+
ended(session: {
|
|
13
|
+
sid?: string;
|
|
14
|
+
sub?: string;
|
|
15
|
+
since: number;
|
|
16
|
+
}): boolean | Promise<boolean>;
|
|
17
|
+
}
|
|
18
|
+
/** Logouts in memory, forgotten after `ttlMs` (a session that old has expired anyway). */
|
|
19
|
+
export declare function memoryLogouts(ttlMs?: number): LogoutStore;
|
|
20
|
+
/** The claims of an ID token, unverified: it came from the token endpoint and sits in a sealed cookie. */
|
|
21
|
+
export declare function idTokenClaims(idToken: string | undefined): {
|
|
22
|
+
sid?: string;
|
|
23
|
+
sub?: string;
|
|
24
|
+
iat?: number;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Checks a logout token as the specification asks: signature, issuer, audience and age like
|
|
28
|
+
* any token, then the logout event, a `sid` or a `sub`, and no `nonce` (which only an ID token
|
|
29
|
+
* carries, so a token with one is an ID token being passed off as a logout).
|
|
30
|
+
*/
|
|
31
|
+
export declare function logoutTokenVerifier(options: {
|
|
32
|
+
issuer: string;
|
|
33
|
+
clientId: string;
|
|
34
|
+
jwksUri?: string;
|
|
35
|
+
jwks?: {
|
|
36
|
+
keys: unknown[];
|
|
37
|
+
};
|
|
38
|
+
}): (token: string) => Promise<LogoutEntry>;
|
|
39
|
+
//# sourceMappingURL=backchannel.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backchannel.d.ts","sourceRoot":"","sources":["../src/backchannel.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,YAAY,uDAAuD,CAAC;AAEjF,uGAAuG;AACvG,MAAM,WAAW,WAAW;IAC1B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,kDAAkD;IAClD,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,WAAW;IAC1B,GAAG,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,iGAAiG;IACjG,KAAK,CAAC,OAAO,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3F;AAED,0FAA0F;AAC1F,wBAAgB,aAAa,CAAC,KAAK,SAAqB,GAAG,WAAW,CAkBrE;AAED,0GAA0G;AAC1G,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,CAcvG;AAcD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE;QAAE,IAAI,EAAE,OAAO,EAAE,CAAA;KAAE,CAAA;CAAE,IAc/G,OAAO,MAAM,KAAG,OAAO,CAAC,WAAW,CAAC,CAUnD"}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenID Connect Back-Channel Logout, the app's half: the provider posts a logout token when a
|
|
3
|
+
* session this app took part in ends, and the app ends its own session for it.
|
|
4
|
+
*
|
|
5
|
+
* Logouts are kept in a `LogoutStore`. The default holds them in this process's memory, which
|
|
6
|
+
* is right for one instance; several instances behind a balancer each need to hear of every
|
|
7
|
+
* logout, so they share a store (Redis, a table) passed as `logouts`.
|
|
8
|
+
*/
|
|
9
|
+
import { createTokenVerifier } from './verify.js';
|
|
10
|
+
export const LOGOUT_EVENT = 'http://schemas.openid.net/event/backchannel-logout';
|
|
11
|
+
/** Logouts in memory, forgotten after `ttlMs` (a session that old has expired anyway). */
|
|
12
|
+
export function memoryLogouts(ttlMs = 14 * 24 * 3600_000) {
|
|
13
|
+
const sids = new Map();
|
|
14
|
+
const subs = new Map();
|
|
15
|
+
const prune = (now) => {
|
|
16
|
+
for (const map of [sids, subs])
|
|
17
|
+
for (const [key, at] of map)
|
|
18
|
+
if (now - at > ttlMs)
|
|
19
|
+
map.delete(key);
|
|
20
|
+
};
|
|
21
|
+
return {
|
|
22
|
+
add(entry) {
|
|
23
|
+
prune(Date.now());
|
|
24
|
+
if (entry.sid)
|
|
25
|
+
sids.set(entry.sid, entry.at);
|
|
26
|
+
else if (entry.sub)
|
|
27
|
+
subs.set(entry.sub, Math.max(entry.at, subs.get(entry.sub) ?? 0));
|
|
28
|
+
},
|
|
29
|
+
ended(session) {
|
|
30
|
+
if (session.sid && sids.has(session.sid))
|
|
31
|
+
return true;
|
|
32
|
+
const all = session.sub ? subs.get(session.sub) : undefined;
|
|
33
|
+
return all !== undefined && session.since <= all;
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** The claims of an ID token, unverified: it came from the token endpoint and sits in a sealed cookie. */
|
|
38
|
+
export function idTokenClaims(idToken) {
|
|
39
|
+
if (!idToken)
|
|
40
|
+
return {};
|
|
41
|
+
try {
|
|
42
|
+
const part = idToken.split('.')[1] ?? '';
|
|
43
|
+
const json = atob(part.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(part.length / 4) * 4, '='));
|
|
44
|
+
const claims = JSON.parse(json);
|
|
45
|
+
return {
|
|
46
|
+
sid: typeof claims.sid === 'string' ? claims.sid : undefined,
|
|
47
|
+
sub: typeof claims.sub === 'string' ? claims.sub : undefined,
|
|
48
|
+
iat: typeof claims.iat === 'number' ? claims.iat : undefined,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return {};
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function headerOf(token) {
|
|
56
|
+
try {
|
|
57
|
+
const part = token.split('.')[0] ?? '';
|
|
58
|
+
return JSON.parse(atob(part.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(part.length / 4) * 4, '=')));
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return {};
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Checks a logout token as the specification asks: signature, issuer, audience and age like
|
|
66
|
+
* any token, then the logout event, a `sid` or a `sub`, and no `nonce` (which only an ID token
|
|
67
|
+
* carries, so a token with one is an ID token being passed off as a logout).
|
|
68
|
+
*/
|
|
69
|
+
export function logoutTokenVerifier(options) {
|
|
70
|
+
const verify = createTokenVerifier({
|
|
71
|
+
issuer: options.issuer,
|
|
72
|
+
audience: options.clientId,
|
|
73
|
+
jwksUri: options.jwksUri,
|
|
74
|
+
jwks: options.jwks,
|
|
75
|
+
require: (claims) => {
|
|
76
|
+
const events = claims.events;
|
|
77
|
+
if (!events || typeof events !== 'object' || !(LOGOUT_EVENT in events))
|
|
78
|
+
return 'no logout event';
|
|
79
|
+
if ('nonce' in claims)
|
|
80
|
+
return 'a logout token has no nonce';
|
|
81
|
+
if (typeof claims.sid !== 'string' && typeof claims.sub !== 'string')
|
|
82
|
+
return 'names no session and no subject';
|
|
83
|
+
return true;
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
return async (token) => {
|
|
87
|
+
const typ = headerOf(token).typ;
|
|
88
|
+
if (typ !== undefined && typ !== 'logout+jwt')
|
|
89
|
+
throw new Error('not a logout token');
|
|
90
|
+
const claims = await verify(token);
|
|
91
|
+
return {
|
|
92
|
+
sid: typeof claims.sid === 'string' ? claims.sid : undefined,
|
|
93
|
+
sub: typeof claims.sub === 'string' ? claims.sub : undefined,
|
|
94
|
+
at: (typeof claims.iat === 'number' ? claims.iat : Math.floor(Date.now() / 1000)) * 1000,
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
}
|