@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
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
import {
|
|
2
|
+
applyClientAuth,
|
|
3
|
+
assertUsable,
|
|
4
|
+
resolveMethod
|
|
5
|
+
} from "./chunk-SJOBQPG6.mjs";
|
|
6
|
+
import {
|
|
7
|
+
discover
|
|
8
|
+
} from "./chunk-AAN3YN4S.mjs";
|
|
9
|
+
import {
|
|
10
|
+
OAuthError
|
|
11
|
+
} from "./chunk-AXPSPTNP.mjs";
|
|
12
|
+
|
|
13
|
+
// src/api-guard.ts
|
|
14
|
+
var asList = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
|
|
15
|
+
function refuse(refusal) {
|
|
16
|
+
const body = { error: refusal.code };
|
|
17
|
+
if (refusal.detail) body.detail = refusal.detail;
|
|
18
|
+
return new Response(JSON.stringify(body), {
|
|
19
|
+
status: refusal.status,
|
|
20
|
+
headers: { "content-type": "application/json" }
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
function createApiGuard(options) {
|
|
24
|
+
const answer = (refusal, request) => {
|
|
25
|
+
const response = options.onRefused ? options.onRefused(refusal, request) : refuse(refusal);
|
|
26
|
+
if (refusal.status === 401 && !response.headers.has("www-authenticate")) {
|
|
27
|
+
response.headers.set("www-authenticate", `Bearer error="${refusal.code}"`);
|
|
28
|
+
}
|
|
29
|
+
return response;
|
|
30
|
+
};
|
|
31
|
+
const rolesOf = (claims, what) => {
|
|
32
|
+
if (!options.roles) {
|
|
33
|
+
throw new Error(
|
|
34
|
+
`[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.`
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
return options.roles(claims);
|
|
38
|
+
};
|
|
39
|
+
return (handler, requirements = {}) => async (request) => {
|
|
40
|
+
let claims;
|
|
41
|
+
try {
|
|
42
|
+
claims = await options.verify.fromRequest(request);
|
|
43
|
+
} catch (cause) {
|
|
44
|
+
const code = cause instanceof TokenError ? cause.code : "invalid_token";
|
|
45
|
+
return answer({ status: 401, code }, request);
|
|
46
|
+
}
|
|
47
|
+
const wanted = asList(requirements.role);
|
|
48
|
+
if (wanted.length) {
|
|
49
|
+
const held = rolesOf(claims, "a role");
|
|
50
|
+
if (!wanted.some((role) => held.includes(role))) {
|
|
51
|
+
return answer(
|
|
52
|
+
{
|
|
53
|
+
status: 403,
|
|
54
|
+
code: "insufficient_role",
|
|
55
|
+
detail: `needs ${wanted.length > 1 ? "one of " : ""}${wanted.join(", ")}`,
|
|
56
|
+
claims
|
|
57
|
+
},
|
|
58
|
+
request
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (requirements.allRoles?.length) {
|
|
63
|
+
const held = rolesOf(claims, "roles");
|
|
64
|
+
const missing = requirements.allRoles.filter((role) => !held.includes(role));
|
|
65
|
+
if (missing.length) {
|
|
66
|
+
return answer(
|
|
67
|
+
{ status: 403, code: "insufficient_role", detail: `needs ${missing.join(", ")}`, claims },
|
|
68
|
+
request
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const scopes = asList(requirements.scope);
|
|
73
|
+
if (scopes.length) {
|
|
74
|
+
const held = typeof claims.scope === "string" ? claims.scope.split(" ") : [];
|
|
75
|
+
if (!scopes.some((scope) => held.includes(scope))) {
|
|
76
|
+
return answer(
|
|
77
|
+
{
|
|
78
|
+
status: 403,
|
|
79
|
+
code: "insufficient_scope",
|
|
80
|
+
detail: `needs ${scopes.length > 1 ? "one of " : ""}${scopes.join(", ")}`,
|
|
81
|
+
claims
|
|
82
|
+
},
|
|
83
|
+
request
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (requirements.require) {
|
|
88
|
+
const verdict = requirements.require(claims, request);
|
|
89
|
+
if (verdict !== true) {
|
|
90
|
+
return answer(
|
|
91
|
+
{
|
|
92
|
+
status: 403,
|
|
93
|
+
code: "forbidden",
|
|
94
|
+
detail: typeof verdict === "string" ? verdict : void 0,
|
|
95
|
+
claims
|
|
96
|
+
},
|
|
97
|
+
request
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return handler(request, claims);
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// src/verify.ts
|
|
106
|
+
var TokenError = class extends OAuthError {
|
|
107
|
+
constructor(message, code = "invalid_token") {
|
|
108
|
+
super(message, code);
|
|
109
|
+
this.name = "TokenError";
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
function bearerOf(request) {
|
|
113
|
+
const header = request.headers.get("authorization");
|
|
114
|
+
if (!header) return null;
|
|
115
|
+
const match = header.match(/^(?:Bearer|DPoP)\s+(.+)$/i);
|
|
116
|
+
return match ? match[1].trim() : null;
|
|
117
|
+
}
|
|
118
|
+
async function loadJose() {
|
|
119
|
+
try {
|
|
120
|
+
return await import("./browser-FDUOEUM2.mjs");
|
|
121
|
+
} catch {
|
|
122
|
+
throw new OAuthError(
|
|
123
|
+
"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.",
|
|
124
|
+
"jose_missing"
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function createTokenVerifier(options) {
|
|
129
|
+
const issuers = (Array.isArray(options.issuer) ? options.issuer : [options.issuer]).filter(Boolean);
|
|
130
|
+
if (!issuers.length) {
|
|
131
|
+
throw new Error("[fluixi/oauth2] createTokenVerifier needs an issuer to accept tokens from.");
|
|
132
|
+
}
|
|
133
|
+
const discoveryIssuer = issuers[0];
|
|
134
|
+
if (options.audience === void 0) {
|
|
135
|
+
throw new Error(
|
|
136
|
+
"[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."
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
if (options.audience === false && options.authorizedParty === void 0) {
|
|
140
|
+
console.warn(
|
|
141
|
+
"[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."
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
const algorithms = options.algorithms ?? ["RS256"];
|
|
145
|
+
if (algorithms.some((alg) => !alg || alg.toLowerCase() === "none")) {
|
|
146
|
+
throw new Error("[fluixi/oauth2] `none` is not a signing algorithm and cannot be accepted.");
|
|
147
|
+
}
|
|
148
|
+
let keys = null;
|
|
149
|
+
async function keySet() {
|
|
150
|
+
if (keys) return keys;
|
|
151
|
+
const jose = await loadJose();
|
|
152
|
+
if (options.jwks) {
|
|
153
|
+
keys = jose.createLocalJWKSet(options.jwks);
|
|
154
|
+
return keys;
|
|
155
|
+
}
|
|
156
|
+
let uri = options.jwksUri;
|
|
157
|
+
if (!uri) {
|
|
158
|
+
const endpoints = await discover(discoveryIssuer);
|
|
159
|
+
uri = endpoints.jwks;
|
|
160
|
+
}
|
|
161
|
+
if (!uri) {
|
|
162
|
+
throw new OAuthError(
|
|
163
|
+
`${discoveryIssuer} published no jwks_uri. Give the verifier one directly.`,
|
|
164
|
+
"no_jwks"
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
keys = jose.createRemoteJWKSet(new URL(uri));
|
|
168
|
+
return keys;
|
|
169
|
+
}
|
|
170
|
+
const checkProof = async (claims, token, request) => {
|
|
171
|
+
const jose = await loadJose();
|
|
172
|
+
const { boundKeyOf, thumbprintOf } = await import("./dpop.mjs");
|
|
173
|
+
const bound = boundKeyOf(claims);
|
|
174
|
+
if (!bound) {
|
|
175
|
+
throw new TokenError(
|
|
176
|
+
"This token is not bound to a key, and this service requires binding.",
|
|
177
|
+
"token_not_bound"
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
const proof = request.headers.get("dpop");
|
|
181
|
+
if (!proof) throw new TokenError("The request carried no DPoP proof.", "missing_dpop_proof");
|
|
182
|
+
let payload;
|
|
183
|
+
let header;
|
|
184
|
+
try {
|
|
185
|
+
const result = await jose.jwtVerify(proof, jose.EmbeddedJWK, { typ: "dpop+jwt" });
|
|
186
|
+
payload = result.payload;
|
|
187
|
+
header = result.protectedHeader;
|
|
188
|
+
} catch (cause) {
|
|
189
|
+
throw new TokenError(
|
|
190
|
+
`The DPoP proof did not verify: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
191
|
+
"invalid_dpop_proof"
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
const presented = await thumbprintOf(header.jwk);
|
|
195
|
+
if (presented !== bound) {
|
|
196
|
+
throw new TokenError(
|
|
197
|
+
"The DPoP proof was signed with a different key from the one this token is bound to.",
|
|
198
|
+
"dpop_key_mismatch"
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
const url = new URL(request.url);
|
|
202
|
+
url.search = "";
|
|
203
|
+
url.hash = "";
|
|
204
|
+
if (payload.htm !== request.method.toUpperCase()) {
|
|
205
|
+
throw new TokenError("The DPoP proof was made for a different method.", "invalid_dpop_proof");
|
|
206
|
+
}
|
|
207
|
+
if (payload.htu !== url.toString()) {
|
|
208
|
+
throw new TokenError("The DPoP proof was made for a different URL.", "invalid_dpop_proof");
|
|
209
|
+
}
|
|
210
|
+
if (typeof payload.ath === "string") {
|
|
211
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
|
|
212
|
+
let binary = "";
|
|
213
|
+
for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
|
|
214
|
+
const expected = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
215
|
+
if (payload.ath !== expected) {
|
|
216
|
+
throw new TokenError("The DPoP proof was made for a different token.", "invalid_dpop_proof");
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const age = Math.abs(Date.now() / 1e3 - payload.iat);
|
|
220
|
+
if (!Number.isFinite(age) || age > (options.dpopProofAgeSec ?? 10)) {
|
|
221
|
+
throw new TokenError("The DPoP proof is too old to accept.", "invalid_dpop_proof");
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
const verify = async (token, request) => {
|
|
225
|
+
if (!token) throw new TokenError("No token to verify.", "no_token");
|
|
226
|
+
const jose = await loadJose();
|
|
227
|
+
let payload;
|
|
228
|
+
try {
|
|
229
|
+
({ payload } = await jose.jwtVerify(token, await keySet(), {
|
|
230
|
+
// jose takes a list and accepts any of them, which is what a provider naming
|
|
231
|
+
// itself two ways needs.
|
|
232
|
+
issuer: issuers,
|
|
233
|
+
...options.audience === false ? {} : { audience: options.audience },
|
|
234
|
+
algorithms,
|
|
235
|
+
clockTolerance: options.clockToleranceSec ?? 5
|
|
236
|
+
}));
|
|
237
|
+
} catch (cause) {
|
|
238
|
+
throw new TokenError(
|
|
239
|
+
`The token was not accepted: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
if (options.authorizedParty !== void 0) {
|
|
243
|
+
const allowed = Array.isArray(options.authorizedParty) ? options.authorizedParty : [options.authorizedParty];
|
|
244
|
+
const issuedTo = payload.azp ?? payload.client_id;
|
|
245
|
+
if (typeof issuedTo !== "string" || !allowed.includes(issuedTo)) {
|
|
246
|
+
throw new TokenError("The token was issued to a different client.", "invalid_azp");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (options.dpop) {
|
|
250
|
+
if (!request) {
|
|
251
|
+
throw new Error(
|
|
252
|
+
"[fluixi/oauth2] `dpop: true` needs the request to read its proof. Use `verify.fromRequest(request)` rather than verifying a bare token."
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
await checkProof(payload, token, request);
|
|
256
|
+
}
|
|
257
|
+
if (options.require) {
|
|
258
|
+
const verdict = options.require(payload);
|
|
259
|
+
if (verdict !== true) {
|
|
260
|
+
throw new TokenError(
|
|
261
|
+
typeof verdict === "string" ? verdict : "The token did not meet this service's requirements.",
|
|
262
|
+
"insufficient_claims"
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return payload;
|
|
267
|
+
};
|
|
268
|
+
const verifier = verify;
|
|
269
|
+
verifier.bearerOf = bearerOf;
|
|
270
|
+
verifier.fromRequest = async (request) => {
|
|
271
|
+
const token = verifier.bearerOf(request);
|
|
272
|
+
if (!token) {
|
|
273
|
+
throw new TokenError("The request carried no bearer token.", "no_token");
|
|
274
|
+
}
|
|
275
|
+
return verify(token, request);
|
|
276
|
+
};
|
|
277
|
+
return verifier;
|
|
278
|
+
}
|
|
279
|
+
function createTokenIntrospector(options) {
|
|
280
|
+
const issuers = (Array.isArray(options.issuer) ? options.issuer : [options.issuer]).filter(Boolean);
|
|
281
|
+
if (!issuers.length) {
|
|
282
|
+
throw new Error("[fluixi/oauth2] createTokenIntrospector needs an issuer.");
|
|
283
|
+
}
|
|
284
|
+
const discoveryIssuer = issuers[0];
|
|
285
|
+
const auth = {
|
|
286
|
+
clientId: options.clientId,
|
|
287
|
+
method: options.clientAuthMethod,
|
|
288
|
+
clientSecret: options.clientSecret,
|
|
289
|
+
privateKey: options.privateKey,
|
|
290
|
+
keyId: options.keyId,
|
|
291
|
+
assertionAlgorithm: options.assertionAlgorithm
|
|
292
|
+
};
|
|
293
|
+
if (resolveMethod(auth) === "none") {
|
|
294
|
+
throw new Error(
|
|
295
|
+
"[fluixi/oauth2] createTokenIntrospector needs credentials: a secret, or private_key_jwt with a key."
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
assertUsable(auth, "createTokenIntrospector");
|
|
299
|
+
if (options.audience === void 0) {
|
|
300
|
+
throw new Error(
|
|
301
|
+
"[fluixi/oauth2] createTokenIntrospector needs an audience, or `audience: false` to say this service accepts a token minted for any client of the issuer."
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
const ttl = options.cacheMs ?? 0;
|
|
305
|
+
const cache = /* @__PURE__ */ new Map();
|
|
306
|
+
let endpoint = options.introspectionEndpoint ?? null;
|
|
307
|
+
async function resolveEndpoint() {
|
|
308
|
+
if (endpoint) return endpoint;
|
|
309
|
+
const endpoints = await discover(discoveryIssuer);
|
|
310
|
+
if (!endpoints.introspection) {
|
|
311
|
+
throw new OAuthError(
|
|
312
|
+
`${discoveryIssuer} published no introspection_endpoint. Give the introspector one directly, or verify JWTs with createTokenVerifier.`,
|
|
313
|
+
"no_introspection"
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
endpoint = endpoints.introspection;
|
|
317
|
+
return endpoint;
|
|
318
|
+
}
|
|
319
|
+
const introspect = async (token) => {
|
|
320
|
+
if (!token) throw new TokenError("No token to verify.", "no_token");
|
|
321
|
+
const cached = cache.get(token);
|
|
322
|
+
if (cached && cached.until > Date.now()) return cached.claims;
|
|
323
|
+
const url = await resolveEndpoint();
|
|
324
|
+
const headers = {
|
|
325
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
326
|
+
accept: "application/json"
|
|
327
|
+
};
|
|
328
|
+
const form = new URLSearchParams({ token, token_type_hint: "access_token" });
|
|
329
|
+
await applyClientAuth(auth, url, headers, form);
|
|
330
|
+
const response = await fetch(url, { method: "POST", headers, body: form.toString() });
|
|
331
|
+
if (!response.ok) {
|
|
332
|
+
const method = resolveMethod(auth);
|
|
333
|
+
const check = method === "private_key_jwt" ? `Check clientId, and that the provider holds the public half of this key${auth.keyId ? ` under kid ${auth.keyId}` : ""}. A key registered to a different client than clientId is refused this way.` : "Check clientId and clientSecret.";
|
|
334
|
+
const said = await response.text().catch(() => "");
|
|
335
|
+
throw new OAuthError(
|
|
336
|
+
`The introspection endpoint refused this service: ${response.status}. ${check}${said ? ` It said: ${said}` : ""}`,
|
|
337
|
+
"introspection_failed"
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
const body = await response.json();
|
|
341
|
+
if (body.active !== true) {
|
|
342
|
+
throw new TokenError(
|
|
343
|
+
"The provider reports this token is not active. If it was just issued, check that this client is in the token audience: some providers refuse to introspect a token minted for someone else and say only this.",
|
|
344
|
+
"inactive_token"
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
if (typeof body.iss === "string" && !issuers.includes(body.iss)) {
|
|
348
|
+
throw new TokenError("The token was issued by a different issuer.", "invalid_issuer");
|
|
349
|
+
}
|
|
350
|
+
if (options.audience !== false && body.aud !== void 0) {
|
|
351
|
+
const wanted = Array.isArray(options.audience) ? options.audience : [options.audience];
|
|
352
|
+
const got = Array.isArray(body.aud) ? body.aud : [body.aud];
|
|
353
|
+
if (!got.some((a) => wanted.includes(a))) {
|
|
354
|
+
throw new TokenError("The token was minted for a different audience.", "invalid_audience");
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
if (options.authorizedParty !== void 0) {
|
|
358
|
+
const allowed = Array.isArray(options.authorizedParty) ? options.authorizedParty : [options.authorizedParty];
|
|
359
|
+
const issuedTo = body.client_id ?? body.azp;
|
|
360
|
+
if (!issuedTo || !allowed.includes(issuedTo)) {
|
|
361
|
+
throw new TokenError("The token was issued to a different client.", "invalid_azp");
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
if (options.require) {
|
|
365
|
+
const verdict = options.require(body);
|
|
366
|
+
if (verdict !== true) {
|
|
367
|
+
throw new TokenError(
|
|
368
|
+
typeof verdict === "string" ? verdict : "The token did not meet this service's requirements.",
|
|
369
|
+
"insufficient_claims"
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (ttl > 0) {
|
|
374
|
+
if (cache.size > 500) {
|
|
375
|
+
const now = Date.now();
|
|
376
|
+
for (const [key, entry] of cache) if (entry.until <= now) cache.delete(key);
|
|
377
|
+
if (cache.size > 500) cache.delete(cache.keys().next().value);
|
|
378
|
+
}
|
|
379
|
+
cache.set(token, { claims: body, until: Date.now() + ttl });
|
|
380
|
+
}
|
|
381
|
+
return body;
|
|
382
|
+
};
|
|
383
|
+
const verifier = introspect;
|
|
384
|
+
verifier.bearerOf = bearerOf;
|
|
385
|
+
verifier.fromRequest = async (request) => {
|
|
386
|
+
const token = bearerOf(request);
|
|
387
|
+
if (!token) throw new TokenError("The request carried no bearer token.", "no_token");
|
|
388
|
+
return introspect(token);
|
|
389
|
+
};
|
|
390
|
+
return verifier;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export {
|
|
394
|
+
TokenError,
|
|
395
|
+
createTokenVerifier,
|
|
396
|
+
createTokenIntrospector,
|
|
397
|
+
createApiGuard
|
|
398
|
+
};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import {
|
|
2
|
+
safeReturnTo
|
|
3
|
+
} from "./chunk-VCNXQCIH.mjs";
|
|
4
|
+
import {
|
|
5
|
+
OAuthError
|
|
6
|
+
} from "./chunk-AXPSPTNP.mjs";
|
|
7
|
+
|
|
8
|
+
// src/server-client.ts
|
|
9
|
+
var COOKIE_SESSION = "cookie";
|
|
10
|
+
function createServerClient(config, fetcher = fetch) {
|
|
11
|
+
const base = (config.basePath ?? "/auth").replace(/\/$/, "");
|
|
12
|
+
const url = (path) => `${base}${path}`;
|
|
13
|
+
const call = (path, init = {}) => fetcher(url(path), { credentials: "same-origin", ...init });
|
|
14
|
+
return {
|
|
15
|
+
async login(options = {}) {
|
|
16
|
+
const target = new URL(url("/login"), location.origin);
|
|
17
|
+
if (options.returnTo) target.searchParams.set("returnTo", options.returnTo);
|
|
18
|
+
for (const [key, value] of Object.entries(options.params ?? {})) {
|
|
19
|
+
target.searchParams.set(key, value);
|
|
20
|
+
}
|
|
21
|
+
location.assign(target.toString());
|
|
22
|
+
},
|
|
23
|
+
async handleCallback(params) {
|
|
24
|
+
const response = await call("/callback", {
|
|
25
|
+
method: "POST",
|
|
26
|
+
headers: { "content-type": "application/json" },
|
|
27
|
+
body: JSON.stringify(params)
|
|
28
|
+
});
|
|
29
|
+
if (!response.ok) {
|
|
30
|
+
const body = await response.json().catch(() => ({}));
|
|
31
|
+
throw new OAuthError(
|
|
32
|
+
String(body.error ?? `Callback failed: ${response.status}`),
|
|
33
|
+
String(body.error ?? "callback_failed")
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
return { accessToken: COOKIE_SESSION };
|
|
37
|
+
},
|
|
38
|
+
async refresh() {
|
|
39
|
+
const response = await call("/refresh", { method: "POST" });
|
|
40
|
+
if (!response.ok) {
|
|
41
|
+
throw new OAuthError("The server could not extend the session.", "refresh_failed");
|
|
42
|
+
}
|
|
43
|
+
return { accessToken: COOKIE_SESSION };
|
|
44
|
+
},
|
|
45
|
+
async fetchUser() {
|
|
46
|
+
const custom = config.userInfo;
|
|
47
|
+
const response = custom?.url ? await fetcher(custom.url, {
|
|
48
|
+
method: custom.method ?? "GET",
|
|
49
|
+
credentials: custom.credentials ?? "same-origin",
|
|
50
|
+
headers: { accept: "application/json", ...custom.headers }
|
|
51
|
+
}) : await call("/me");
|
|
52
|
+
if (!response.ok) {
|
|
53
|
+
throw new OAuthError(`The server refused the user request: ${response.status}`, "me_failed");
|
|
54
|
+
}
|
|
55
|
+
const raw = await response.json();
|
|
56
|
+
return custom?.map ? await custom.map(raw, COOKIE_SESSION) : raw;
|
|
57
|
+
},
|
|
58
|
+
/**
|
|
59
|
+
* Retire the session's tokens, which only the server can do here.
|
|
60
|
+
*
|
|
61
|
+
* The browser holds a cookie and no token, so it has nothing to send to a revocation
|
|
62
|
+
* endpoint. This asks the server's own route, which opens the cookie and revokes what
|
|
63
|
+
* is inside.
|
|
64
|
+
*/
|
|
65
|
+
async revoke(_token, hint = "refresh_token") {
|
|
66
|
+
await call(`/revoke?hint=${hint}`, { method: "POST" }).catch(() => void 0);
|
|
67
|
+
},
|
|
68
|
+
async logout(options = {}) {
|
|
69
|
+
await call("/logout", { method: "POST" }).catch(() => void 0);
|
|
70
|
+
const target = options.returnTo ? safeReturnTo(options.returnTo, {
|
|
71
|
+
fallback: config.postLogoutRedirectUri ?? "/",
|
|
72
|
+
allowedOrigins: config.allowedReturnOrigins
|
|
73
|
+
}) : config.postLogoutRedirectUri ?? "/";
|
|
74
|
+
if (typeof location !== "undefined") location.assign(target);
|
|
75
|
+
},
|
|
76
|
+
async restore() {
|
|
77
|
+
const response = await call("/me");
|
|
78
|
+
return response.ok ? { accessToken: COOKIE_SESSION } : null;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export {
|
|
84
|
+
COOKIE_SESSION,
|
|
85
|
+
createServerClient
|
|
86
|
+
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// src/session-monitor.ts
|
|
2
|
+
var SETTLE_MS = 15e3;
|
|
3
|
+
var GUARD_KEY = "fx-session-check";
|
|
4
|
+
function recentlyActed() {
|
|
5
|
+
try {
|
|
6
|
+
return Date.now() - Number(sessionStorage.getItem(GUARD_KEY) ?? 0) < SETTLE_MS;
|
|
7
|
+
} catch {
|
|
8
|
+
return false;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function markActed() {
|
|
12
|
+
try {
|
|
13
|
+
sessionStorage.setItem(GUARD_KEY, String(Date.now()));
|
|
14
|
+
} catch {
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function watchProviderSession(options = {}) {
|
|
18
|
+
if (typeof window === "undefined" || typeof document === "undefined") return () => {
|
|
19
|
+
};
|
|
20
|
+
const base = (options.basePath ?? "/auth").replace(/\/$/, "");
|
|
21
|
+
const fetcher = options.fetcher ?? fetch;
|
|
22
|
+
const onChange = options.onChange ?? (() => {
|
|
23
|
+
const login = new URLSearchParams({ prompt: "none", returnTo: location.pathname + location.search });
|
|
24
|
+
location.assign(`${base}/login?${login}`);
|
|
25
|
+
});
|
|
26
|
+
let stopped = false;
|
|
27
|
+
const cleanups = [];
|
|
28
|
+
const stop = () => {
|
|
29
|
+
stopped = true;
|
|
30
|
+
for (const cleanup of cleanups.splice(0)) cleanup();
|
|
31
|
+
};
|
|
32
|
+
void (async () => {
|
|
33
|
+
const check = await fetcher(`${base}/session-check`, { credentials: "same-origin" }).then((response) => response.ok ? response.json() : null).catch(() => null);
|
|
34
|
+
if (stopped || !check?.frame || !check.state) return;
|
|
35
|
+
const origin = new URL(check.frame).origin;
|
|
36
|
+
const frame = document.createElement("iframe");
|
|
37
|
+
frame.src = check.frame;
|
|
38
|
+
frame.title = "session check";
|
|
39
|
+
frame.setAttribute("aria-hidden", "true");
|
|
40
|
+
frame.tabIndex = -1;
|
|
41
|
+
frame.style.cssText = "position:absolute;width:0;height:0;border:0;visibility:hidden";
|
|
42
|
+
const message = `${check.clientId} ${check.state}`;
|
|
43
|
+
const ask = () => {
|
|
44
|
+
if (!stopped && document.visibilityState === "visible") frame.contentWindow?.postMessage(message, origin);
|
|
45
|
+
};
|
|
46
|
+
let confirmed = false;
|
|
47
|
+
const answer = (event) => {
|
|
48
|
+
if (event.origin !== origin || event.source !== frame.contentWindow) return;
|
|
49
|
+
if (event.data === "unchanged") confirmed = true;
|
|
50
|
+
else if (event.data === "changed") {
|
|
51
|
+
stop();
|
|
52
|
+
if (!confirmed && recentlyActed()) return;
|
|
53
|
+
markActed();
|
|
54
|
+
onChange();
|
|
55
|
+
} else if (event.data === "error") {
|
|
56
|
+
stop();
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
window.addEventListener("message", answer);
|
|
60
|
+
frame.addEventListener("load", ask);
|
|
61
|
+
document.addEventListener("visibilitychange", ask);
|
|
62
|
+
window.addEventListener("focus", ask);
|
|
63
|
+
const timer = setInterval(ask, options.intervalMs ?? 3e3);
|
|
64
|
+
document.body.appendChild(frame);
|
|
65
|
+
cleanups.push(() => {
|
|
66
|
+
window.removeEventListener("message", answer);
|
|
67
|
+
document.removeEventListener("visibilitychange", ask);
|
|
68
|
+
window.removeEventListener("focus", ask);
|
|
69
|
+
clearInterval(timer);
|
|
70
|
+
frame.remove();
|
|
71
|
+
});
|
|
72
|
+
})();
|
|
73
|
+
return stop;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export {
|
|
77
|
+
watchProviderSession
|
|
78
|
+
};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// src/env-credentials.ts
|
|
2
|
+
async function jwkAt(path) {
|
|
3
|
+
const [{ readFileSync }, { homedir }] = await Promise.all([
|
|
4
|
+
import("node:fs"),
|
|
5
|
+
import("node:os")
|
|
6
|
+
]);
|
|
7
|
+
const file = path.replace(/^~(?=$|\/)/, homedir());
|
|
8
|
+
let text;
|
|
9
|
+
try {
|
|
10
|
+
text = readFileSync(file, "utf8");
|
|
11
|
+
} catch {
|
|
12
|
+
throw new Error(
|
|
13
|
+
`[fluixi/oauth2] the key file ${file} cannot be read. A signing key is named by path so it can stay outside the repository.`
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(text);
|
|
18
|
+
} catch {
|
|
19
|
+
throw new Error(`[fluixi/oauth2] ${file} is not JSON, and a private key is expected as a JWK.`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
async function credentialsFromEnv(options) {
|
|
23
|
+
const source = options.env ?? (typeof process === "undefined" ? {} : process.env);
|
|
24
|
+
const upper = options.prefix.toUpperCase();
|
|
25
|
+
const prefer = (options.preferPrefix ?? `${upper}_INTROSPECT`).toUpperCase();
|
|
26
|
+
const read = (suffix) => source[`${prefer}_${suffix}`] ?? source[`${upper}_${suffix}`];
|
|
27
|
+
const clientId = read("CLIENT_ID") ?? options.clientId;
|
|
28
|
+
if (!clientId) return null;
|
|
29
|
+
const keyPath = read("PRIVATE_KEY");
|
|
30
|
+
if (keyPath) {
|
|
31
|
+
return {
|
|
32
|
+
clientId,
|
|
33
|
+
privateKey: await jwkAt(keyPath),
|
|
34
|
+
keyId: read("KEY_ID"),
|
|
35
|
+
clientAuthMethod: "private_key_jwt",
|
|
36
|
+
assertionAlgorithm: read("ASSERTION_ALG")
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const clientSecret = read("SECRET") ?? read("CLIENT_SECRET");
|
|
40
|
+
if (clientSecret) return { clientId, clientSecret };
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
function explainCredentials(options) {
|
|
44
|
+
const upper = options.prefix.toUpperCase();
|
|
45
|
+
const who = options.label ?? options.prefix;
|
|
46
|
+
return `This call authenticates its caller, so ${who} needs credentials. For a client with a shared secret, set ${upper}_CLIENT_SECRET. For one registered with a public key (Okta calls this "Public key / Private key"), set ${upper}_PRIVATE_KEY to the path of its private JWK and ${upper}_KEY_ID to the kid the provider lists. Prefix either with ${upper}_INTROSPECT_ to have a different client ask, which Okta requires: a public SPA cannot introspect at all.`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export {
|
|
50
|
+
credentialsFromEnv,
|
|
51
|
+
explainCredentials
|
|
52
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import {
|
|
2
|
+
OAuthError
|
|
3
|
+
} from "./chunk-AXPSPTNP.mjs";
|
|
4
|
+
|
|
5
|
+
// src/discovery.ts
|
|
6
|
+
var cache = /* @__PURE__ */ new Map();
|
|
7
|
+
function documentUrl(issuer) {
|
|
8
|
+
return `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
9
|
+
}
|
|
10
|
+
async function discover(issuer, fetcher = fetch) {
|
|
11
|
+
const cached = cache.get(issuer);
|
|
12
|
+
if (cached) return cached;
|
|
13
|
+
const pending = (async () => {
|
|
14
|
+
let response;
|
|
15
|
+
try {
|
|
16
|
+
response = await fetcher(documentUrl(issuer));
|
|
17
|
+
} catch (cause) {
|
|
18
|
+
const why = cause instanceof Error ? cause.message : String(cause);
|
|
19
|
+
throw new OAuthError(
|
|
20
|
+
typeof window === "undefined" ? (
|
|
21
|
+
// On a server nothing blocks the read: the provider is down, or the address is wrong.
|
|
22
|
+
`Could not reach the provider at ${documentUrl(issuer)}: is it running, and is the issuer right? (${why})`
|
|
23
|
+
) : `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})`,
|
|
24
|
+
"discovery_unreachable"
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
if (!response.ok) {
|
|
28
|
+
throw new OAuthError(
|
|
29
|
+
`Discovery failed for ${issuer}: ${response.status}`,
|
|
30
|
+
"discovery_failed"
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
const doc = await response.json();
|
|
34
|
+
if (!doc.authorization_endpoint || !doc.token_endpoint) {
|
|
35
|
+
throw new OAuthError(
|
|
36
|
+
`${issuer} published a discovery document with no authorization or token endpoint.`,
|
|
37
|
+
"discovery_incomplete"
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
authorization: doc.authorization_endpoint,
|
|
42
|
+
token: doc.token_endpoint,
|
|
43
|
+
userinfo: doc.userinfo_endpoint,
|
|
44
|
+
endSession: doc.end_session_endpoint,
|
|
45
|
+
jwks: doc.jwks_uri,
|
|
46
|
+
introspection: doc.introspection_endpoint,
|
|
47
|
+
revocation: doc.revocation_endpoint,
|
|
48
|
+
checkSession: doc.check_session_iframe,
|
|
49
|
+
issuer: doc.issuer ?? issuer
|
|
50
|
+
};
|
|
51
|
+
})();
|
|
52
|
+
cache.set(issuer, pending);
|
|
53
|
+
pending.catch(() => cache.delete(issuer));
|
|
54
|
+
return pending;
|
|
55
|
+
}
|
|
56
|
+
function clearDiscoveryCache() {
|
|
57
|
+
cache.clear();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export {
|
|
61
|
+
discover,
|
|
62
|
+
clearDiscoveryCache
|
|
63
|
+
};
|