@fluixi/oauth2 1.0.0-alpha.11 → 1.0.0-alpha.111
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/dist/api-guard.cjs +8 -3
- package/dist/api-guard.mjs +9 -135
- package/dist/backchannel.cjs +467 -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 +19 -0
- package/dist/browser.cjs +6 -1
- package/dist/browser.mjs +10 -702
- package/dist/callback.cjs +2 -2
- package/dist/callback.d.ts +2 -2
- package/dist/callback.js +3 -3
- package/dist/callback.mjs +17 -24
- package/dist/{dpop-YPGCGL7S.mjs → chunk-27BGFJIY.mjs} +6 -6
- package/dist/chunk-2GLWT7XH.mjs +143 -0
- package/dist/chunk-3EICMAF7.mjs +22 -0
- package/dist/chunk-4OHJTTX7.mjs +398 -0
- package/dist/chunk-4QRYJ4TN.mjs +86 -0
- package/dist/chunk-5WX3EV2W.mjs +78 -0
- package/dist/chunk-7AMC336S.mjs +52 -0
- package/dist/chunk-AAN3YN4S.mjs +63 -0
- package/dist/chunk-AWVECOG7.mjs +404 -0
- package/dist/chunk-GN5SERAQ.mjs +189 -0
- package/dist/chunk-KIXTZEEW.mjs +80 -0
- package/dist/chunk-KVW2S6VY.mjs +36 -0
- package/dist/chunk-MHWZTXZZ.mjs +9 -0
- package/dist/chunk-QC2FFASM.mjs +67 -0
- package/dist/chunk-SJOBQPG6.mjs +77 -0
- package/dist/chunk-VCNXQCIH.mjs +26 -0
- package/dist/chunk-XQJTQV3C.mjs +91 -0
- package/dist/client-auth.mjs +6 -78
- 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 -59
- package/dist/dpop-store.mjs +6 -118
- package/dist/dpop.mjs +11 -95
- package/dist/env-config.cjs +1 -1
- package/dist/env-config.mjs +5 -214
- package/dist/env-credentials.mjs +5 -47
- 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 +50 -912
- package/dist/module.cjs +1 -1
- package/dist/module.mjs +5 -20
- package/dist/pkce.mjs +11 -56
- package/dist/presets.cjs +1 -1
- package/dist/presets.mjs +5 -214
- package/dist/return-to.mjs +4 -22
- package/dist/roles.cjs +1 -1
- package/dist/roles.d.ts +1 -1
- package/dist/roles.js +1 -1
- package/dist/roles.mjs +4 -32
- package/dist/server-client.mjs +7 -107
- package/dist/server.cjs +795 -153
- package/dist/server.d.ts +85 -4
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +577 -75
- package/dist/server.mjs +442 -310
- package/dist/service-client.cjs +7 -2
- package/dist/service-client.mjs +16 -133
- package/dist/service.cjs +104 -5
- package/dist/service.d.ts +1 -1
- package/dist/service.d.ts.map +1 -1
- package/dist/service.js +38 -6
- package/dist/service.mjs +14 -879
- 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 +7 -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 +5 -4
- package/dist/tsconfig.lib.tsbuildinfo +1 -1
- package/dist/types.d.ts +8 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.mjs +4 -9
- package/dist/verify.cjs +15 -5
- package/dist/verify.d.ts +2 -2
- package/dist/verify.js +2 -2
- package/dist/verify.mjs +17 -580
- package/package.json +23 -17
- package/dist/browser-N432SMC3.mjs +0 -3545
- package/dist/chunk-4TPZVJSR.mjs +0 -10
- package/dist/chunk-ZVDC3JW7.mjs +0 -15
- package/dist/dpop-DYUR2CH2.mjs +0 -100
- /package/dist/{chunk-OGSFNTKA.mjs → chunk-AXPSPTNP.mjs} +0 -0
package/dist/api-guard.cjs
CHANGED
|
@@ -3,8 +3,13 @@ var __defProp = Object.defineProperty;
|
|
|
3
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __esm = (fn, res) => function __init() {
|
|
7
|
-
|
|
6
|
+
var __esm = (fn, res, err) => function __init() {
|
|
7
|
+
if (err) throw err[0];
|
|
8
|
+
try {
|
|
9
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
10
|
+
} catch (e) {
|
|
11
|
+
throw err = [e], e;
|
|
12
|
+
}
|
|
8
13
|
};
|
|
9
14
|
var __export = (target, all) => {
|
|
10
15
|
for (var name in all)
|
|
@@ -81,7 +86,7 @@ var rolesFrom = {
|
|
|
81
86
|
/**
|
|
82
87
|
* Auth0, which requires a namespaced custom claim added by an action.
|
|
83
88
|
*
|
|
84
|
-
* `rolesFrom.namespaced('https://
|
|
89
|
+
* `rolesFrom.namespaced('https://acme.com/roles')`. Auth0 silently drops a custom claim
|
|
85
90
|
* that is not a URI, so an empty list here usually means the namespace, not the action.
|
|
86
91
|
*/
|
|
87
92
|
namespaced: (claim) => (claims) => {
|
package/dist/api-guard.mjs
CHANGED
|
@@ -1,140 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
} from "./chunk-
|
|
2
|
+
createApiGuard
|
|
3
|
+
} from "./chunk-4OHJTTX7.mjs";
|
|
4
|
+
import "./chunk-7AMC336S.mjs";
|
|
5
|
+
import {
|
|
6
|
+
rolesFrom
|
|
7
|
+
} from "./chunk-KVW2S6VY.mjs";
|
|
8
|
+
import "./chunk-SJOBQPG6.mjs";
|
|
9
|
+
import "./chunk-AAN3YN4S.mjs";
|
|
10
|
+
import "./chunk-AXPSPTNP.mjs";
|
|
4
11
|
import "./chunk-7P6ASYW6.mjs";
|
|
5
|
-
|
|
6
|
-
// src/verify.ts
|
|
7
|
-
var TokenError = class extends OAuthError {
|
|
8
|
-
constructor(message, code = "invalid_token") {
|
|
9
|
-
super(message, code);
|
|
10
|
-
this.name = "TokenError";
|
|
11
|
-
}
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
// src/roles.ts
|
|
15
|
-
var rolesFrom = {
|
|
16
|
-
/** Keycloak, realm roles. Where it puts them unless a client mapper is configured. */
|
|
17
|
-
keycloakRealm: (claims) => {
|
|
18
|
-
const realm = claims.realm_access;
|
|
19
|
-
return realm?.roles ?? [];
|
|
20
|
-
},
|
|
21
|
-
/** Keycloak, roles scoped to one client rather than the realm. */
|
|
22
|
-
keycloakClient: (clientId) => (claims) => {
|
|
23
|
-
const all = claims.resource_access;
|
|
24
|
-
return all?.[clientId]?.roles ?? [];
|
|
25
|
-
},
|
|
26
|
-
/** Okta, and anything else using a groups claim. Needs a groups claim on the token. */
|
|
27
|
-
groups: (claims) => Array.isArray(claims.groups) ? claims.groups : [],
|
|
28
|
-
/** Cognito, which namespaces the claim. */
|
|
29
|
-
cognito: (claims) => {
|
|
30
|
-
const groups = claims["cognito:groups"];
|
|
31
|
-
return Array.isArray(groups) ? groups : [];
|
|
32
|
-
},
|
|
33
|
-
/**
|
|
34
|
-
* Auth0, which requires a namespaced custom claim added by an action.
|
|
35
|
-
*
|
|
36
|
-
* `rolesFrom.namespaced('https://adafri.com/roles')`. Auth0 silently drops a custom claim
|
|
37
|
-
* that is not a URI, so an empty list here usually means the namespace, not the action.
|
|
38
|
-
*/
|
|
39
|
-
namespaced: (claim) => (claims) => {
|
|
40
|
-
const value = claims[claim];
|
|
41
|
-
return Array.isArray(value) ? value : [];
|
|
42
|
-
},
|
|
43
|
-
/** The `scope` claim read as a role list, for a provider issuing no roles at all. */
|
|
44
|
-
scope: (claims) => typeof claims.scope === "string" ? claims.scope.split(" ") : []
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
// src/api-guard.ts
|
|
48
|
-
var asList = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
|
|
49
|
-
function refuse(refusal) {
|
|
50
|
-
const body = { error: refusal.code };
|
|
51
|
-
if (refusal.detail) body.detail = refusal.detail;
|
|
52
|
-
return new Response(JSON.stringify(body), {
|
|
53
|
-
status: refusal.status,
|
|
54
|
-
headers: { "content-type": "application/json" }
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
function createApiGuard(options) {
|
|
58
|
-
const answer = (refusal, request) => {
|
|
59
|
-
const response = options.onRefused ? options.onRefused(refusal, request) : refuse(refusal);
|
|
60
|
-
if (refusal.status === 401 && !response.headers.has("www-authenticate")) {
|
|
61
|
-
response.headers.set("www-authenticate", `Bearer error="${refusal.code}"`);
|
|
62
|
-
}
|
|
63
|
-
return response;
|
|
64
|
-
};
|
|
65
|
-
const rolesOf = (claims, what) => {
|
|
66
|
-
if (!options.roles) {
|
|
67
|
-
throw new Error(
|
|
68
|
-
`[fluixi/oauth2] this route requires ${what}, but createApiGuard was given no \`roles\`. Providers disagree on where roles live, so there is no default: pass one of \`rolesFrom\`, or a function reading the claim your provider uses.`
|
|
69
|
-
);
|
|
70
|
-
}
|
|
71
|
-
return options.roles(claims);
|
|
72
|
-
};
|
|
73
|
-
return (handler, requirements = {}) => async (request) => {
|
|
74
|
-
let claims;
|
|
75
|
-
try {
|
|
76
|
-
claims = await options.verify.fromRequest(request);
|
|
77
|
-
} catch (cause) {
|
|
78
|
-
const code = cause instanceof TokenError ? cause.code : "invalid_token";
|
|
79
|
-
return answer({ status: 401, code }, request);
|
|
80
|
-
}
|
|
81
|
-
const wanted = asList(requirements.role);
|
|
82
|
-
if (wanted.length) {
|
|
83
|
-
const held = rolesOf(claims, "a role");
|
|
84
|
-
if (!wanted.some((role) => held.includes(role))) {
|
|
85
|
-
return answer(
|
|
86
|
-
{
|
|
87
|
-
status: 403,
|
|
88
|
-
code: "insufficient_role",
|
|
89
|
-
detail: `needs ${wanted.length > 1 ? "one of " : ""}${wanted.join(", ")}`,
|
|
90
|
-
claims
|
|
91
|
-
},
|
|
92
|
-
request
|
|
93
|
-
);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
if (requirements.allRoles?.length) {
|
|
97
|
-
const held = rolesOf(claims, "roles");
|
|
98
|
-
const missing = requirements.allRoles.filter((role) => !held.includes(role));
|
|
99
|
-
if (missing.length) {
|
|
100
|
-
return answer(
|
|
101
|
-
{ status: 403, code: "insufficient_role", detail: `needs ${missing.join(", ")}`, claims },
|
|
102
|
-
request
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
const scopes = asList(requirements.scope);
|
|
107
|
-
if (scopes.length) {
|
|
108
|
-
const held = typeof claims.scope === "string" ? claims.scope.split(" ") : [];
|
|
109
|
-
if (!scopes.some((scope) => held.includes(scope))) {
|
|
110
|
-
return answer(
|
|
111
|
-
{
|
|
112
|
-
status: 403,
|
|
113
|
-
code: "insufficient_scope",
|
|
114
|
-
detail: `needs ${scopes.length > 1 ? "one of " : ""}${scopes.join(", ")}`,
|
|
115
|
-
claims
|
|
116
|
-
},
|
|
117
|
-
request
|
|
118
|
-
);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
if (requirements.require) {
|
|
122
|
-
const verdict = requirements.require(claims, request);
|
|
123
|
-
if (verdict !== true) {
|
|
124
|
-
return answer(
|
|
125
|
-
{
|
|
126
|
-
status: 403,
|
|
127
|
-
code: "forbidden",
|
|
128
|
-
detail: typeof verdict === "string" ? verdict : void 0,
|
|
129
|
-
claims
|
|
130
|
-
},
|
|
131
|
-
request
|
|
132
|
-
);
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
return handler(request, claims);
|
|
136
|
-
};
|
|
137
|
-
}
|
|
138
12
|
export {
|
|
139
13
|
createApiGuard,
|
|
140
14
|
rolesFrom
|
|
@@ -0,0 +1,467 @@
|
|
|
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, err) => function __init() {
|
|
9
|
+
if (err) throw err[0];
|
|
10
|
+
try {
|
|
11
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
12
|
+
} catch (e) {
|
|
13
|
+
throw err = [e], e;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
var __export = (target, all) => {
|
|
17
|
+
for (var name in all)
|
|
18
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
19
|
+
};
|
|
20
|
+
var __copyProps = (to, from, except, desc) => {
|
|
21
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
22
|
+
for (let key of __getOwnPropNames(from))
|
|
23
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
24
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
25
|
+
}
|
|
26
|
+
return to;
|
|
27
|
+
};
|
|
28
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
29
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
30
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
31
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
32
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
33
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
34
|
+
mod
|
|
35
|
+
));
|
|
36
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
37
|
+
|
|
38
|
+
// src/types.ts
|
|
39
|
+
var OAuthError;
|
|
40
|
+
var init_types = __esm({
|
|
41
|
+
"src/types.ts"() {
|
|
42
|
+
"use strict";
|
|
43
|
+
OAuthError = class extends Error {
|
|
44
|
+
constructor(message, code, description) {
|
|
45
|
+
super(message);
|
|
46
|
+
this.code = code;
|
|
47
|
+
this.description = description;
|
|
48
|
+
this.name = "OAuthError";
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
// src/dpop.ts
|
|
55
|
+
var dpop_exports = {};
|
|
56
|
+
__export(dpop_exports, {
|
|
57
|
+
boundKeyOf: () => boundKeyOf,
|
|
58
|
+
createDpopKey: () => createDpopKey,
|
|
59
|
+
exportDpopKey: () => exportDpopKey,
|
|
60
|
+
importDpopKey: () => importDpopKey,
|
|
61
|
+
nonceFrom: () => nonceFrom,
|
|
62
|
+
proofFor: () => proofFor,
|
|
63
|
+
thumbprintOf: () => thumbprintOf,
|
|
64
|
+
wantsNonce: () => wantsNonce
|
|
65
|
+
});
|
|
66
|
+
async function loadJose() {
|
|
67
|
+
try {
|
|
68
|
+
return await import("jose");
|
|
69
|
+
} catch {
|
|
70
|
+
throw new OAuthError(
|
|
71
|
+
"DPoP needs `jose`. Install it: npm i jose. It is an optional peer, so a client not using DPoP does not carry it.",
|
|
72
|
+
"jose_missing"
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async function createDpopKey(alg = "ES256", options = {}) {
|
|
77
|
+
const jose = await loadJose();
|
|
78
|
+
const { privateKey, publicKey } = await jose.generateKeyPair(alg, {
|
|
79
|
+
extractable: options.extractable ?? false
|
|
80
|
+
});
|
|
81
|
+
const publicJwk = { ...await jose.exportJWK(publicKey) };
|
|
82
|
+
return {
|
|
83
|
+
privateKey,
|
|
84
|
+
publicJwk,
|
|
85
|
+
thumbprint: await jose.calculateJwkThumbprint(publicJwk, "sha256"),
|
|
86
|
+
alg
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
async function exportDpopKey(key) {
|
|
90
|
+
const jose = await loadJose();
|
|
91
|
+
return { jwk: { ...await jose.exportJWK(key.privateKey) }, alg: key.alg };
|
|
92
|
+
}
|
|
93
|
+
async function importDpopKey(stored) {
|
|
94
|
+
const jose = await loadJose();
|
|
95
|
+
const privateKey = await jose.importJWK(stored.jwk, stored.alg);
|
|
96
|
+
const publicJwk = Object.fromEntries(Object.entries(stored.jwk).filter(([k]) => !PRIVATE_MEMBERS.has(k)));
|
|
97
|
+
return {
|
|
98
|
+
privateKey,
|
|
99
|
+
publicJwk,
|
|
100
|
+
thumbprint: await jose.calculateJwkThumbprint(publicJwk, "sha256"),
|
|
101
|
+
alg: stored.alg
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
async function thumbprintOf(jwk) {
|
|
105
|
+
const jose = await loadJose();
|
|
106
|
+
return jose.calculateJwkThumbprint(jwk, "sha256");
|
|
107
|
+
}
|
|
108
|
+
async function proofFor(key, options) {
|
|
109
|
+
const jose = await loadJose();
|
|
110
|
+
const htu = (() => {
|
|
111
|
+
try {
|
|
112
|
+
const url = new URL(options.url);
|
|
113
|
+
url.search = "";
|
|
114
|
+
url.hash = "";
|
|
115
|
+
return url.toString();
|
|
116
|
+
} catch {
|
|
117
|
+
return options.url;
|
|
118
|
+
}
|
|
119
|
+
})();
|
|
120
|
+
const claims = {
|
|
121
|
+
htm: options.method.toUpperCase(),
|
|
122
|
+
htu,
|
|
123
|
+
jti: crypto.randomUUID()
|
|
124
|
+
};
|
|
125
|
+
if (options.accessToken) {
|
|
126
|
+
const digest = await crypto.subtle.digest(
|
|
127
|
+
"SHA-256",
|
|
128
|
+
new TextEncoder().encode(options.accessToken)
|
|
129
|
+
);
|
|
130
|
+
let binary = "";
|
|
131
|
+
for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
|
|
132
|
+
claims.ath = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
133
|
+
}
|
|
134
|
+
if (options.nonce) claims.nonce = options.nonce;
|
|
135
|
+
return new jose.SignJWT(claims).setProtectedHeader({ typ: "dpop+jwt", alg: key.alg, jwk: key.publicJwk }).setIssuedAt().sign(key.privateKey);
|
|
136
|
+
}
|
|
137
|
+
function nonceFrom(response) {
|
|
138
|
+
return response.headers.get("dpop-nonce");
|
|
139
|
+
}
|
|
140
|
+
function wantsNonce(error, response) {
|
|
141
|
+
const code = typeof error === "string" ? error : error?.error;
|
|
142
|
+
return code === "use_dpop_nonce" || !!response && !!nonceFrom(response);
|
|
143
|
+
}
|
|
144
|
+
function boundKeyOf(claims) {
|
|
145
|
+
const cnf = claims.cnf;
|
|
146
|
+
return typeof cnf?.jkt === "string" ? cnf.jkt : null;
|
|
147
|
+
}
|
|
148
|
+
var PRIVATE_MEMBERS;
|
|
149
|
+
var init_dpop = __esm({
|
|
150
|
+
"src/dpop.ts"() {
|
|
151
|
+
"use strict";
|
|
152
|
+
init_types();
|
|
153
|
+
PRIVATE_MEMBERS = /* @__PURE__ */ new Set(["d", "p", "q", "dp", "dq", "qi", "oth"]);
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// src/backchannel.ts
|
|
158
|
+
var backchannel_exports = {};
|
|
159
|
+
__export(backchannel_exports, {
|
|
160
|
+
LOGOUT_EVENT: () => LOGOUT_EVENT,
|
|
161
|
+
idTokenClaims: () => idTokenClaims,
|
|
162
|
+
logoutTokenVerifier: () => logoutTokenVerifier,
|
|
163
|
+
memoryLogouts: () => memoryLogouts
|
|
164
|
+
});
|
|
165
|
+
module.exports = __toCommonJS(backchannel_exports);
|
|
166
|
+
|
|
167
|
+
// src/client-auth.ts
|
|
168
|
+
init_types();
|
|
169
|
+
|
|
170
|
+
// src/discovery.ts
|
|
171
|
+
init_types();
|
|
172
|
+
var cache = /* @__PURE__ */ new Map();
|
|
173
|
+
function documentUrl(issuer) {
|
|
174
|
+
return `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
175
|
+
}
|
|
176
|
+
async function discover(issuer, fetcher = fetch) {
|
|
177
|
+
const cached = cache.get(issuer);
|
|
178
|
+
if (cached) return cached;
|
|
179
|
+
const pending = (async () => {
|
|
180
|
+
let response;
|
|
181
|
+
try {
|
|
182
|
+
response = await fetcher(documentUrl(issuer));
|
|
183
|
+
} catch (cause) {
|
|
184
|
+
const why = cause instanceof Error ? cause.message : String(cause);
|
|
185
|
+
throw new OAuthError(
|
|
186
|
+
typeof window === "undefined" ? (
|
|
187
|
+
// On a server nothing blocks the read: the provider is down, or the address is wrong.
|
|
188
|
+
`Could not reach the provider at ${documentUrl(issuer)}: is it running, and is the issuer right? (${why})`
|
|
189
|
+
) : `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})`,
|
|
190
|
+
"discovery_unreachable"
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
if (!response.ok) {
|
|
194
|
+
throw new OAuthError(
|
|
195
|
+
`Discovery failed for ${issuer}: ${response.status}`,
|
|
196
|
+
"discovery_failed"
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
const doc = await response.json();
|
|
200
|
+
if (!doc.authorization_endpoint || !doc.token_endpoint) {
|
|
201
|
+
throw new OAuthError(
|
|
202
|
+
`${issuer} published a discovery document with no authorization or token endpoint.`,
|
|
203
|
+
"discovery_incomplete"
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
authorization: doc.authorization_endpoint,
|
|
208
|
+
token: doc.token_endpoint,
|
|
209
|
+
userinfo: doc.userinfo_endpoint,
|
|
210
|
+
endSession: doc.end_session_endpoint,
|
|
211
|
+
jwks: doc.jwks_uri,
|
|
212
|
+
introspection: doc.introspection_endpoint,
|
|
213
|
+
revocation: doc.revocation_endpoint,
|
|
214
|
+
checkSession: doc.check_session_iframe,
|
|
215
|
+
issuer: doc.issuer ?? issuer
|
|
216
|
+
};
|
|
217
|
+
})();
|
|
218
|
+
cache.set(issuer, pending);
|
|
219
|
+
pending.catch(() => cache.delete(issuer));
|
|
220
|
+
return pending;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// src/verify.ts
|
|
224
|
+
init_types();
|
|
225
|
+
var TokenError = class extends OAuthError {
|
|
226
|
+
constructor(message, code = "invalid_token") {
|
|
227
|
+
super(message, code);
|
|
228
|
+
this.name = "TokenError";
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
function bearerOf(request) {
|
|
232
|
+
const header = request.headers.get("authorization");
|
|
233
|
+
if (!header) return null;
|
|
234
|
+
const match = header.match(/^(?:Bearer|DPoP)\s+(.+)$/i);
|
|
235
|
+
return match ? match[1].trim() : null;
|
|
236
|
+
}
|
|
237
|
+
async function loadJose2() {
|
|
238
|
+
try {
|
|
239
|
+
return await import("jose");
|
|
240
|
+
} catch {
|
|
241
|
+
throw new OAuthError(
|
|
242
|
+
"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.",
|
|
243
|
+
"jose_missing"
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
function createTokenVerifier(options) {
|
|
248
|
+
const issuers = (Array.isArray(options.issuer) ? options.issuer : [options.issuer]).filter(Boolean);
|
|
249
|
+
if (!issuers.length) {
|
|
250
|
+
throw new Error("[fluixi/oauth2] createTokenVerifier needs an issuer to accept tokens from.");
|
|
251
|
+
}
|
|
252
|
+
const discoveryIssuer = issuers[0];
|
|
253
|
+
if (options.audience === void 0) {
|
|
254
|
+
throw new Error(
|
|
255
|
+
"[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."
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
if (options.audience === false && options.authorizedParty === void 0) {
|
|
259
|
+
console.warn(
|
|
260
|
+
"[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."
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
const algorithms = options.algorithms ?? ["RS256"];
|
|
264
|
+
if (algorithms.some((alg) => !alg || alg.toLowerCase() === "none")) {
|
|
265
|
+
throw new Error("[fluixi/oauth2] `none` is not a signing algorithm and cannot be accepted.");
|
|
266
|
+
}
|
|
267
|
+
let keys = null;
|
|
268
|
+
async function keySet() {
|
|
269
|
+
if (keys) return keys;
|
|
270
|
+
const jose = await loadJose2();
|
|
271
|
+
if (options.jwks) {
|
|
272
|
+
keys = jose.createLocalJWKSet(options.jwks);
|
|
273
|
+
return keys;
|
|
274
|
+
}
|
|
275
|
+
let uri = options.jwksUri;
|
|
276
|
+
if (!uri) {
|
|
277
|
+
const endpoints = await discover(discoveryIssuer);
|
|
278
|
+
uri = endpoints.jwks;
|
|
279
|
+
}
|
|
280
|
+
if (!uri) {
|
|
281
|
+
throw new OAuthError(
|
|
282
|
+
`${discoveryIssuer} published no jwks_uri. Give the verifier one directly.`,
|
|
283
|
+
"no_jwks"
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
keys = jose.createRemoteJWKSet(new URL(uri));
|
|
287
|
+
return keys;
|
|
288
|
+
}
|
|
289
|
+
const checkProof = async (claims, token, request) => {
|
|
290
|
+
const jose = await loadJose2();
|
|
291
|
+
const { boundKeyOf: boundKeyOf2, thumbprintOf: thumbprintOf2 } = await Promise.resolve().then(() => (init_dpop(), dpop_exports));
|
|
292
|
+
const bound = boundKeyOf2(claims);
|
|
293
|
+
if (!bound) {
|
|
294
|
+
throw new TokenError(
|
|
295
|
+
"This token is not bound to a key, and this service requires binding.",
|
|
296
|
+
"token_not_bound"
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
const proof = request.headers.get("dpop");
|
|
300
|
+
if (!proof) throw new TokenError("The request carried no DPoP proof.", "missing_dpop_proof");
|
|
301
|
+
let payload;
|
|
302
|
+
let header;
|
|
303
|
+
try {
|
|
304
|
+
const result = await jose.jwtVerify(proof, jose.EmbeddedJWK, { typ: "dpop+jwt" });
|
|
305
|
+
payload = result.payload;
|
|
306
|
+
header = result.protectedHeader;
|
|
307
|
+
} catch (cause) {
|
|
308
|
+
throw new TokenError(
|
|
309
|
+
`The DPoP proof did not verify: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
310
|
+
"invalid_dpop_proof"
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
const presented = await thumbprintOf2(header.jwk);
|
|
314
|
+
if (presented !== bound) {
|
|
315
|
+
throw new TokenError(
|
|
316
|
+
"The DPoP proof was signed with a different key from the one this token is bound to.",
|
|
317
|
+
"dpop_key_mismatch"
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
const url = new URL(request.url);
|
|
321
|
+
url.search = "";
|
|
322
|
+
url.hash = "";
|
|
323
|
+
if (payload.htm !== request.method.toUpperCase()) {
|
|
324
|
+
throw new TokenError("The DPoP proof was made for a different method.", "invalid_dpop_proof");
|
|
325
|
+
}
|
|
326
|
+
if (payload.htu !== url.toString()) {
|
|
327
|
+
throw new TokenError("The DPoP proof was made for a different URL.", "invalid_dpop_proof");
|
|
328
|
+
}
|
|
329
|
+
if (typeof payload.ath === "string") {
|
|
330
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
|
|
331
|
+
let binary = "";
|
|
332
|
+
for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
|
|
333
|
+
const expected = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
334
|
+
if (payload.ath !== expected) {
|
|
335
|
+
throw new TokenError("The DPoP proof was made for a different token.", "invalid_dpop_proof");
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
const age = Math.abs(Date.now() / 1e3 - payload.iat);
|
|
339
|
+
if (!Number.isFinite(age) || age > (options.dpopProofAgeSec ?? 10)) {
|
|
340
|
+
throw new TokenError("The DPoP proof is too old to accept.", "invalid_dpop_proof");
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
const verify = async (token, request) => {
|
|
344
|
+
if (!token) throw new TokenError("No token to verify.", "no_token");
|
|
345
|
+
const jose = await loadJose2();
|
|
346
|
+
let payload;
|
|
347
|
+
try {
|
|
348
|
+
({ payload } = await jose.jwtVerify(token, await keySet(), {
|
|
349
|
+
// jose takes a list and accepts any of them, which is what a provider naming
|
|
350
|
+
// itself two ways needs.
|
|
351
|
+
issuer: issuers,
|
|
352
|
+
...options.audience === false ? {} : { audience: options.audience },
|
|
353
|
+
algorithms,
|
|
354
|
+
clockTolerance: options.clockToleranceSec ?? 5
|
|
355
|
+
}));
|
|
356
|
+
} catch (cause) {
|
|
357
|
+
throw new TokenError(
|
|
358
|
+
`The token was not accepted: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
if (options.authorizedParty !== void 0) {
|
|
362
|
+
const allowed = Array.isArray(options.authorizedParty) ? options.authorizedParty : [options.authorizedParty];
|
|
363
|
+
const issuedTo = payload.azp ?? payload.client_id;
|
|
364
|
+
if (typeof issuedTo !== "string" || !allowed.includes(issuedTo)) {
|
|
365
|
+
throw new TokenError("The token was issued to a different client.", "invalid_azp");
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
if (options.dpop) {
|
|
369
|
+
if (!request) {
|
|
370
|
+
throw new Error(
|
|
371
|
+
"[fluixi/oauth2] `dpop: true` needs the request to read its proof. Use `verify.fromRequest(request)` rather than verifying a bare token."
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
await checkProof(payload, token, request);
|
|
375
|
+
}
|
|
376
|
+
if (options.require) {
|
|
377
|
+
const verdict = options.require(payload);
|
|
378
|
+
if (verdict !== true) {
|
|
379
|
+
throw new TokenError(
|
|
380
|
+
typeof verdict === "string" ? verdict : "The token did not meet this service's requirements.",
|
|
381
|
+
"insufficient_claims"
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
return payload;
|
|
386
|
+
};
|
|
387
|
+
const verifier = verify;
|
|
388
|
+
verifier.bearerOf = bearerOf;
|
|
389
|
+
verifier.fromRequest = async (request) => {
|
|
390
|
+
const token = verifier.bearerOf(request);
|
|
391
|
+
if (!token) {
|
|
392
|
+
throw new TokenError("The request carried no bearer token.", "no_token");
|
|
393
|
+
}
|
|
394
|
+
return verify(token, request);
|
|
395
|
+
};
|
|
396
|
+
return verifier;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// src/backchannel.ts
|
|
400
|
+
var LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
|
|
401
|
+
function memoryLogouts(ttlMs = 14 * 24 * 36e5) {
|
|
402
|
+
const sids = /* @__PURE__ */ new Map();
|
|
403
|
+
const subs = /* @__PURE__ */ new Map();
|
|
404
|
+
const prune = (now) => {
|
|
405
|
+
for (const map of [sids, subs]) for (const [key, at] of map) if (now - at > ttlMs) map.delete(key);
|
|
406
|
+
};
|
|
407
|
+
return {
|
|
408
|
+
add(entry) {
|
|
409
|
+
prune(Date.now());
|
|
410
|
+
if (entry.sid) sids.set(entry.sid, entry.at);
|
|
411
|
+
else if (entry.sub) subs.set(entry.sub, Math.max(entry.at, subs.get(entry.sub) ?? 0));
|
|
412
|
+
},
|
|
413
|
+
ended(session) {
|
|
414
|
+
if (session.sid && sids.has(session.sid)) return true;
|
|
415
|
+
const all = session.sub ? subs.get(session.sub) : void 0;
|
|
416
|
+
return all !== void 0 && session.since <= all;
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
function idTokenClaims(idToken) {
|
|
421
|
+
if (!idToken) return {};
|
|
422
|
+
try {
|
|
423
|
+
const part = idToken.split(".")[1] ?? "";
|
|
424
|
+
const json = atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "="));
|
|
425
|
+
const claims = JSON.parse(json);
|
|
426
|
+
return {
|
|
427
|
+
sid: typeof claims.sid === "string" ? claims.sid : void 0,
|
|
428
|
+
sub: typeof claims.sub === "string" ? claims.sub : void 0,
|
|
429
|
+
iat: typeof claims.iat === "number" ? claims.iat : void 0
|
|
430
|
+
};
|
|
431
|
+
} catch {
|
|
432
|
+
return {};
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
function headerOf(token) {
|
|
436
|
+
try {
|
|
437
|
+
const part = token.split(".")[0] ?? "";
|
|
438
|
+
return JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=")));
|
|
439
|
+
} catch {
|
|
440
|
+
return {};
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
function logoutTokenVerifier(options) {
|
|
444
|
+
const verify = createTokenVerifier({
|
|
445
|
+
issuer: options.issuer,
|
|
446
|
+
audience: options.clientId,
|
|
447
|
+
jwksUri: options.jwksUri,
|
|
448
|
+
jwks: options.jwks,
|
|
449
|
+
require: (claims) => {
|
|
450
|
+
const events = claims.events;
|
|
451
|
+
if (!events || typeof events !== "object" || !(LOGOUT_EVENT in events)) return "no logout event";
|
|
452
|
+
if ("nonce" in claims) return "a logout token has no nonce";
|
|
453
|
+
if (typeof claims.sid !== "string" && typeof claims.sub !== "string") return "names no session and no subject";
|
|
454
|
+
return true;
|
|
455
|
+
}
|
|
456
|
+
});
|
|
457
|
+
return async (token) => {
|
|
458
|
+
const typ = headerOf(token).typ;
|
|
459
|
+
if (typ !== void 0 && typ !== "logout+jwt") throw new Error("not a logout token");
|
|
460
|
+
const claims = await verify(token);
|
|
461
|
+
return {
|
|
462
|
+
sid: typeof claims.sid === "string" ? claims.sid : void 0,
|
|
463
|
+
sub: typeof claims.sub === "string" ? claims.sub : void 0,
|
|
464
|
+
at: (typeof claims.iat === "number" ? claims.iat : Math.floor(Date.now() / 1e3)) * 1e3
|
|
465
|
+
};
|
|
466
|
+
};
|
|
467
|
+
}
|
|
@@ -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"}
|