@fluixi/oauth2 1.0.0-alpha.107 → 1.0.0-alpha.109

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.
Files changed (59) hide show
  1. package/dist/api-guard.cjs +7 -2
  2. package/dist/api-guard.mjs +9 -135
  3. package/dist/backchannel.cjs +7 -2
  4. package/dist/backchannel.mjs +11 -299
  5. package/dist/browser.mjs +10 -707
  6. package/dist/callback.mjs +16 -23
  7. package/dist/{dpop-YPGCGL7S.mjs → chunk-27BGFJIY.mjs} +6 -6
  8. package/dist/chunk-2GLWT7XH.mjs +143 -0
  9. package/dist/chunk-3EICMAF7.mjs +22 -0
  10. package/dist/chunk-4OHJTTX7.mjs +398 -0
  11. package/dist/chunk-4QRYJ4TN.mjs +86 -0
  12. package/dist/chunk-5WX3EV2W.mjs +78 -0
  13. package/dist/chunk-7AMC336S.mjs +52 -0
  14. package/dist/chunk-AAN3YN4S.mjs +63 -0
  15. package/dist/chunk-AWVECOG7.mjs +404 -0
  16. package/dist/chunk-GN5SERAQ.mjs +189 -0
  17. package/dist/chunk-KIXTZEEW.mjs +80 -0
  18. package/dist/chunk-KVW2S6VY.mjs +36 -0
  19. package/dist/chunk-MHWZTXZZ.mjs +9 -0
  20. package/dist/chunk-QC2FFASM.mjs +67 -0
  21. package/dist/chunk-SJOBQPG6.mjs +77 -0
  22. package/dist/chunk-VCNXQCIH.mjs +26 -0
  23. package/dist/chunk-XQJTQV3C.mjs +91 -0
  24. package/dist/client-auth.mjs +6 -78
  25. package/dist/discovery.mjs +6 -64
  26. package/dist/dpop-store.mjs +6 -118
  27. package/dist/dpop.mjs +11 -95
  28. package/dist/env-config.mjs +5 -214
  29. package/dist/env-credentials.mjs +5 -47
  30. package/dist/index.cjs +1 -1
  31. package/dist/index.mjs +48 -1010
  32. package/dist/module.mjs +5 -20
  33. package/dist/pkce.mjs +11 -56
  34. package/dist/presets.mjs +5 -214
  35. package/dist/return-to.mjs +4 -22
  36. package/dist/roles.mjs +4 -32
  37. package/dist/server-client.mjs +7 -107
  38. package/dist/server.cjs +61 -9
  39. package/dist/server.d.ts +8 -0
  40. package/dist/server.d.ts.map +1 -1
  41. package/dist/server.js +80 -5
  42. package/dist/server.mjs +94 -433
  43. package/dist/service-client.cjs +1 -1
  44. package/dist/service-client.mjs +16 -138
  45. package/dist/service.mjs +14 -978
  46. package/dist/session-monitor.mjs +4 -74
  47. package/dist/tokens.mjs +5 -4
  48. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  49. package/dist/types.mjs +4 -9
  50. package/dist/verify.cjs +8 -3
  51. package/dist/verify.mjs +17 -585
  52. package/package.json +21 -21
  53. package/dist/browser-RHLXMWQ2.mjs +0 -3545
  54. package/dist/chunk-NRB7JOZV.mjs +0 -15
  55. package/dist/chunk-WE2RTKJY.mjs +0 -10
  56. package/dist/chunk-ZIX4ITGP.mjs +0 -108
  57. package/dist/dpop-UCBLIUQC.mjs +0 -100
  58. package/dist/dpop-W2ACBDEM.mjs +0 -22
  59. /package/dist/{chunk-OGSFNTKA.mjs → chunk-AXPSPTNP.mjs} +0 -0
@@ -1,67 +1,9 @@
1
- // src/types.ts
2
- var OAuthError = class extends Error {
3
- constructor(message, code, description) {
4
- super(message);
5
- this.code = code;
6
- this.description = description;
7
- this.name = "OAuthError";
8
- }
9
- };
10
-
11
- // src/discovery.ts
12
- var cache = /* @__PURE__ */ new Map();
13
- function documentUrl(issuer) {
14
- return `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
15
- }
16
- async function discover(issuer, fetcher = fetch) {
17
- const cached = cache.get(issuer);
18
- if (cached) return cached;
19
- const pending = (async () => {
20
- let response;
21
- try {
22
- response = await fetcher(documentUrl(issuer));
23
- } catch (cause) {
24
- const why = cause instanceof Error ? cause.message : String(cause);
25
- throw new OAuthError(
26
- typeof window === "undefined" ? (
27
- // On a server nothing blocks the read: the provider is down, or the address is wrong.
28
- `Could not reach the provider at ${documentUrl(issuer)}: is it running, and is the issuer right? (${why})`
29
- ) : `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})`,
30
- "discovery_unreachable"
31
- );
32
- }
33
- if (!response.ok) {
34
- throw new OAuthError(
35
- `Discovery failed for ${issuer}: ${response.status}`,
36
- "discovery_failed"
37
- );
38
- }
39
- const doc = await response.json();
40
- if (!doc.authorization_endpoint || !doc.token_endpoint) {
41
- throw new OAuthError(
42
- `${issuer} published a discovery document with no authorization or token endpoint.`,
43
- "discovery_incomplete"
44
- );
45
- }
46
- return {
47
- authorization: doc.authorization_endpoint,
48
- token: doc.token_endpoint,
49
- userinfo: doc.userinfo_endpoint,
50
- endSession: doc.end_session_endpoint,
51
- jwks: doc.jwks_uri,
52
- introspection: doc.introspection_endpoint,
53
- revocation: doc.revocation_endpoint,
54
- checkSession: doc.check_session_iframe,
55
- issuer: doc.issuer ?? issuer
56
- };
57
- })();
58
- cache.set(issuer, pending);
59
- pending.catch(() => cache.delete(issuer));
60
- return pending;
61
- }
62
- function clearDiscoveryCache() {
63
- cache.clear();
64
- }
1
+ import {
2
+ clearDiscoveryCache,
3
+ discover
4
+ } from "./chunk-AAN3YN4S.mjs";
5
+ import "./chunk-AXPSPTNP.mjs";
6
+ import "./chunk-7P6ASYW6.mjs";
65
7
  export {
66
8
  clearDiscoveryCache,
67
9
  discover
@@ -1,122 +1,10 @@
1
+ import {
2
+ forgetKey,
3
+ keyFor
4
+ } from "./chunk-XQJTQV3C.mjs";
5
+ import "./chunk-27BGFJIY.mjs";
6
+ import "./chunk-AXPSPTNP.mjs";
1
7
  import "./chunk-7P6ASYW6.mjs";
2
-
3
- // src/types.ts
4
- var OAuthError = class extends Error {
5
- constructor(message, code, description) {
6
- super(message);
7
- this.code = code;
8
- this.description = description;
9
- this.name = "OAuthError";
10
- }
11
- };
12
-
13
- // src/dpop.ts
14
- async function loadJose() {
15
- try {
16
- return await import("./browser-FDUOEUM2.mjs");
17
- } catch {
18
- throw new OAuthError(
19
- "DPoP needs `jose`. Install it: npm i jose. It is an optional peer, so a client not using DPoP does not carry it.",
20
- "jose_missing"
21
- );
22
- }
23
- }
24
- async function createDpopKey(alg = "ES256", options = {}) {
25
- const jose = await loadJose();
26
- const { privateKey, publicKey } = await jose.generateKeyPair(alg, {
27
- extractable: options.extractable ?? false
28
- });
29
- const publicJwk = { ...await jose.exportJWK(publicKey) };
30
- return {
31
- privateKey,
32
- publicJwk,
33
- thumbprint: await jose.calculateJwkThumbprint(publicJwk, "sha256"),
34
- alg
35
- };
36
- }
37
-
38
- // src/dpop-store.ts
39
- var DB = "fluixi-oauth2-dpop";
40
- var STORE = "keys";
41
- function available() {
42
- return typeof indexedDB !== "undefined";
43
- }
44
- function open() {
45
- return new Promise((resolve, reject) => {
46
- const request = indexedDB.open(DB, 1);
47
- request.onupgradeneeded = () => {
48
- const db = request.result;
49
- if (!db.objectStoreNames.contains(STORE)) db.createObjectStore(STORE);
50
- };
51
- request.onsuccess = () => resolve(request.result);
52
- request.onerror = () => reject(request.error ?? new Error("indexedDB.open failed"));
53
- });
54
- }
55
- function act(mode, run) {
56
- return open().then(
57
- (db) => new Promise((resolve, reject) => {
58
- const tx = db.transaction(STORE, mode);
59
- const request = run(tx.objectStore(STORE));
60
- request.onsuccess = () => resolve(request.result);
61
- request.onerror = () => reject(request.error ?? new Error("DPoP key request failed"));
62
- tx.oncomplete = () => db.close();
63
- })
64
- );
65
- }
66
- function usable(value) {
67
- const stored = value;
68
- return !!stored && typeof stored.thumbprint === "string" && typeof stored.alg === "string" && !!stored.publicJwk && // A CryptoKey survives the round trip as a CryptoKey. Anything else means the record was
69
- // written by something other than this, and binding to it would fail at the provider.
70
- typeof stored.privateKey?.type === "string";
71
- }
72
- async function keyFor(clientKey, alg = "ES256", onEphemeral) {
73
- if (!available()) {
74
- onEphemeral?.("This environment has no IndexedDB, so the key lasts only as long as this document.");
75
- return createDpopKey(alg);
76
- }
77
- try {
78
- const found = await act("readonly", (store) => store.get(clientKey));
79
- if (usable(found) && found.alg === alg) {
80
- return {
81
- privateKey: found.privateKey,
82
- publicJwk: found.publicJwk,
83
- thumbprint: found.thumbprint,
84
- alg: found.alg
85
- };
86
- }
87
- } catch (cause) {
88
- onEphemeral?.(
89
- `The stored DPoP key could not be read (${cause instanceof Error ? cause.message : String(cause)}), so a new one was made.`
90
- );
91
- }
92
- const key = await createDpopKey(alg);
93
- try {
94
- await act(
95
- "readwrite",
96
- (store) => store.put(
97
- {
98
- privateKey: key.privateKey,
99
- publicJwk: key.publicJwk,
100
- thumbprint: key.thumbprint,
101
- alg: key.alg
102
- },
103
- clientKey
104
- )
105
- );
106
- } catch (cause) {
107
- onEphemeral?.(
108
- `The DPoP key could not be stored (${cause instanceof Error ? cause.message : String(cause)}), so a refresh after the next navigation will be refused.`
109
- );
110
- }
111
- return key;
112
- }
113
- async function forgetKey(clientKey) {
114
- if (!available()) return;
115
- try {
116
- await act("readwrite", (store) => store.delete(clientKey));
117
- } catch {
118
- }
119
- }
120
8
  export {
121
9
  forgetKey,
122
10
  keyFor
package/dist/dpop.mjs CHANGED
@@ -1,99 +1,15 @@
1
+ import {
2
+ boundKeyOf,
3
+ createDpopKey,
4
+ exportDpopKey,
5
+ importDpopKey,
6
+ nonceFrom,
7
+ proofFor,
8
+ thumbprintOf,
9
+ wantsNonce
10
+ } from "./chunk-27BGFJIY.mjs";
11
+ import "./chunk-AXPSPTNP.mjs";
1
12
  import "./chunk-7P6ASYW6.mjs";
2
-
3
- // src/types.ts
4
- var OAuthError = class extends Error {
5
- constructor(message, code, description) {
6
- super(message);
7
- this.code = code;
8
- this.description = description;
9
- this.name = "OAuthError";
10
- }
11
- };
12
-
13
- // src/dpop.ts
14
- async function loadJose() {
15
- try {
16
- return await import("./browser-FDUOEUM2.mjs");
17
- } catch {
18
- throw new OAuthError(
19
- "DPoP needs `jose`. Install it: npm i jose. It is an optional peer, so a client not using DPoP does not carry it.",
20
- "jose_missing"
21
- );
22
- }
23
- }
24
- async function createDpopKey(alg = "ES256", options = {}) {
25
- const jose = await loadJose();
26
- const { privateKey, publicKey } = await jose.generateKeyPair(alg, {
27
- extractable: options.extractable ?? false
28
- });
29
- const publicJwk = { ...await jose.exportJWK(publicKey) };
30
- return {
31
- privateKey,
32
- publicJwk,
33
- thumbprint: await jose.calculateJwkThumbprint(publicJwk, "sha256"),
34
- alg
35
- };
36
- }
37
- async function exportDpopKey(key) {
38
- const jose = await loadJose();
39
- return { jwk: { ...await jose.exportJWK(key.privateKey) }, alg: key.alg };
40
- }
41
- var PRIVATE_MEMBERS = /* @__PURE__ */ new Set(["d", "p", "q", "dp", "dq", "qi", "oth"]);
42
- async function importDpopKey(stored) {
43
- const jose = await loadJose();
44
- const privateKey = await jose.importJWK(stored.jwk, stored.alg);
45
- const publicJwk = Object.fromEntries(Object.entries(stored.jwk).filter(([k]) => !PRIVATE_MEMBERS.has(k)));
46
- return {
47
- privateKey,
48
- publicJwk,
49
- thumbprint: await jose.calculateJwkThumbprint(publicJwk, "sha256"),
50
- alg: stored.alg
51
- };
52
- }
53
- async function thumbprintOf(jwk) {
54
- const jose = await loadJose();
55
- return jose.calculateJwkThumbprint(jwk, "sha256");
56
- }
57
- async function proofFor(key, options) {
58
- const jose = await loadJose();
59
- const htu = (() => {
60
- try {
61
- const url = new URL(options.url);
62
- url.search = "";
63
- url.hash = "";
64
- return url.toString();
65
- } catch {
66
- return options.url;
67
- }
68
- })();
69
- const claims = {
70
- htm: options.method.toUpperCase(),
71
- htu,
72
- jti: crypto.randomUUID()
73
- };
74
- if (options.accessToken) {
75
- const digest = await crypto.subtle.digest(
76
- "SHA-256",
77
- new TextEncoder().encode(options.accessToken)
78
- );
79
- let binary = "";
80
- for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
81
- claims.ath = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
82
- }
83
- if (options.nonce) claims.nonce = options.nonce;
84
- return new jose.SignJWT(claims).setProtectedHeader({ typ: "dpop+jwt", alg: key.alg, jwk: key.publicJwk }).setIssuedAt().sign(key.privateKey);
85
- }
86
- function nonceFrom(response) {
87
- return response.headers.get("dpop-nonce");
88
- }
89
- function wantsNonce(error, response) {
90
- const code = typeof error === "string" ? error : error?.error;
91
- return code === "use_dpop_nonce" || !!response && !!nonceFrom(response);
92
- }
93
- function boundKeyOf(claims) {
94
- const cnf = claims.cnf;
95
- return typeof cnf?.jkt === "string" ? cnf.jkt : null;
96
- }
97
13
  export {
98
14
  boundKeyOf,
99
15
  createDpopKey,
@@ -1,217 +1,8 @@
1
- // src/roles.ts
2
- var rolesFrom = {
3
- /** Keycloak, realm roles. Where it puts them unless a client mapper is configured. */
4
- keycloakRealm: (claims) => {
5
- const realm = claims.realm_access;
6
- return realm?.roles ?? [];
7
- },
8
- /** Keycloak, roles scoped to one client rather than the realm. */
9
- keycloakClient: (clientId) => (claims) => {
10
- const all = claims.resource_access;
11
- return all?.[clientId]?.roles ?? [];
12
- },
13
- /** Okta, and anything else using a groups claim. Needs a groups claim on the token. */
14
- groups: (claims) => Array.isArray(claims.groups) ? claims.groups : [],
15
- /** Cognito, which namespaces the claim. */
16
- cognito: (claims) => {
17
- const groups = claims["cognito:groups"];
18
- return Array.isArray(groups) ? groups : [];
19
- },
20
- /**
21
- * Auth0, which requires a namespaced custom claim added by an action.
22
- *
23
- * `rolesFrom.namespaced('https://acme.com/roles')`. Auth0 silently drops a custom claim
24
- * that is not a URI, so an empty list here usually means the namespace, not the action.
25
- */
26
- namespaced: (claim) => (claims) => {
27
- const value = claims[claim];
28
- return Array.isArray(value) ? value : [];
29
- },
30
- /** The `scope` claim read as a role list, for a provider issuing no roles at all. */
31
- scope: (claims) => typeof claims.scope === "string" ? claims.scope.split(" ") : []
32
- };
33
-
34
- // src/presets.ts
35
- var trim = (url) => url.replace(/\/+$/, "");
36
- var presets = {
37
- /**
38
- * Any OIDC provider publishing a discovery document.
39
- *
40
- * The agnostic path, and the one to reach for first. A provider not listed below almost
41
- * certainly works through this.
42
- */
43
- oidc(options) {
44
- return {
45
- label: options.issuer,
46
- client: { issuer: trim(options.issuer), scopes: options.scopes },
47
- roles: options.roles ?? rolesFrom.scope,
48
- verifier: (clientId) => ({
49
- issuer: trim(options.issuer),
50
- audience: options.audience ?? clientId,
51
- ...options.audience === false ? { authorizedParty: clientId } : {}
52
- }),
53
- constraints: []
54
- };
55
- },
56
- /**
57
- * A plain OAuth2 server with no discovery document.
58
- *
59
- * Every endpoint is given, because there is nothing to ask. Token verification needs an
60
- * issuer regardless, since a verifier will not accept a token without one.
61
- */
62
- oauth2(options) {
63
- return {
64
- label: options.issuer,
65
- client: { endpoints: options.endpoints, scopes: options.scopes },
66
- roles: options.roles ?? rolesFrom.scope,
67
- verifier: (clientId) => ({
68
- issuer: trim(options.issuer),
69
- audience: options.audience ?? clientId,
70
- ...options.audience === false ? { authorizedParty: clientId } : {}
71
- }),
72
- constraints: ["Publishes no discovery document, so every endpoint is configured by hand."]
73
- };
74
- },
75
- /** Keycloak. A realm is its own issuer. */
76
- keycloak(options) {
77
- const issuer = `${trim(options.baseUrl)}/realms/${options.realm}`;
78
- return {
79
- label: "Keycloak",
80
- client: {
81
- issuer,
82
- scopes: options.scopes ?? ["openid", "profile", "email"]
83
- },
84
- roles: rolesFrom.keycloakRealm,
85
- // No `aud` on an access token until an audience mapper is configured, and the client is
86
- // named in `azp` instead. So the check moves to `authorizedParty` rather than being
87
- // dropped: `audience: false` alone would accept a token minted for any client of the
88
- // realm, which is the check being skipped.
89
- verifier: (clientId) => ({ issuer, audience: false, authorizedParty: clientId }),
90
- constraints: [
91
- "Puts no `aud` on an access token until a dedicated audience mapper is configured. Configure one and switch the verifier to `audience: clientId`.",
92
- "Revokes the whole session when an authorization code is replayed, so a replay test has to run last."
93
- ]
94
- };
95
- },
96
- /**
97
- * Auth0.
98
- *
99
- * `audience` is the field that decides what kind of token comes back. Without it Auth0
100
- * issues an opaque token for its own userinfo endpoint and the JWT checks have nothing to
101
- * work with.
102
- */
103
- auth0(options) {
104
- const issuer = `https://${options.domain.replace(/^https?:\/\//, "").replace(/\/+$/, "")}/`;
105
- return {
106
- label: "Auth0",
107
- client: {
108
- issuer,
109
- scopes: options.scopes ?? ["openid", "profile", "email", "offline_access"],
110
- ...options.audience ? { extraParams: { audience: options.audience } } : {}
111
- },
112
- roles: options.rolesClaim ? rolesFrom.namespaced(options.rolesClaim) : rolesFrom.scope,
113
- verifier: (clientId) => ({
114
- issuer,
115
- // The API identifier is the audience of an access token. Without one the token is
116
- // opaque and there is nothing for a verifier to check.
117
- audience: options.audience ?? false,
118
- ...options.audience ? {} : { authorizedParty: clientId }
119
- }),
120
- constraints: [
121
- "Issues an opaque access token unless `audience` names an API, so token verification needs it.",
122
- "A refresh token needs three things together: `offline_access` in the scopes, an audience whose API has Allow Offline Access on, and Refresh Token Rotation enabled on the application. Any one missing and the scope is ignored silently.",
123
- "Has no roles claim of its own. An action must add a namespaced one, and Auth0 drops a custom claim that is not a URI.",
124
- "The issuer carries a trailing slash. A verifier pinned without it rejects every token."
125
- ]
126
- };
127
- },
128
- /**
129
- * Okta.
130
- *
131
- * Two authorization servers that are not interchangeable: a custom one per application,
132
- * and the org itself for Okta's own management API.
133
- */
134
- okta(options) {
135
- const host = `https://${options.domain.replace(/^https?:\/\//, "").replace(/\/+$/, "")}`;
136
- const server = options.authorizationServer === void 0 ? "default" : options.authorizationServer;
137
- const issuer = server === null ? host : `${host}/oauth2/${server}`;
138
- return {
139
- label: "Okta",
140
- client: {
141
- issuer,
142
- scopes: options.scopes ?? ["openid", "profile", "email", "offline_access"],
143
- dpop: options.dpop ?? true
144
- },
145
- roles: rolesFrom.groups,
146
- verifier: (clientId) => ({
147
- issuer,
148
- // An access token from a custom server is minted for that server's audience, named in
149
- // the console and `api://default` by default. It does not carry the client id.
150
- audience: false,
151
- authorizedParty: clientId
152
- }),
153
- constraints: [
154
- "Two authorization servers: /oauth2/<name> for an application, the bare domain for the management API. They are not interchangeable.",
155
- "Turns DPoP on by default for a new application, and an integrator org will not let you untick it.",
156
- "Binds the refresh token to the DPoP key as well as the access token, so a refresh must be proved with the key that obtained it.",
157
- "A public SPA cannot introspect at all. An API Services client with `private_key_jwt` has to ask instead.",
158
- "Client credentials against the org server must use `private_key_jwt`, whatever the application is set to."
159
- ]
160
- };
161
- },
162
- /**
163
- * Google.
164
- *
165
- * Refuses a public client outright, so server mode is the only option: the token endpoint
166
- * checks for a client secret before it looks at PKCE.
167
- */
168
- google(options = {}) {
169
- return {
170
- label: "Google",
171
- client: {
172
- issuer: "https://accounts.google.com",
173
- scopes: options.scopes ?? ["openid", "profile", "email"],
174
- ...options.hostedDomain ? { extraParams: { hd: options.hostedDomain } } : {}
175
- },
176
- roles: rolesFrom.scope,
177
- verifier: (clientId) => ({
178
- // Names itself two ways, and a service pinned to one rejects tokens carrying the
179
- // other. Discovery uses the first.
180
- issuer: ["https://accounts.google.com", "accounts.google.com"],
181
- audience: clientId
182
- }),
183
- constraints: [
184
- "Refuses a public client: the token endpoint reports `client_secret is missing` before checking PKCE, so browser mode cannot work.",
185
- "Publishes its issuer both with and without a scheme, so a verifier needs both spellings.",
186
- "Issues a refresh token only on the first consent unless `prompt=consent` and `access_type=offline` are sent."
187
- ]
188
- };
189
- },
190
- /**
191
- * Dex.
192
- *
193
- * Sends no CORS headers, on discovery or the token endpoint, so a browser cannot talk to it
194
- * at all. Server mode only, and giving endpoints explicitly does not help: the token request
195
- * is blocked too.
196
- */
197
- dex(options) {
198
- const issuer = trim(options.baseUrl);
199
- return {
200
- label: "Dex",
201
- client: {
202
- issuer,
203
- scopes: options.scopes ?? ["openid", "profile", "email", "offline_access"]
204
- },
205
- roles: rolesFrom.groups,
206
- verifier: (clientId) => ({ issuer, audience: clientId }),
207
- constraints: [
208
- "Sends no CORS headers on discovery or the token endpoint, so browser mode cannot work. Naming the endpoints explicitly only moves the failure to the token request.",
209
- "Has no admin interface. Users are static entries in its config file, and a password is a bcrypt hash.",
210
- "Publishes no revocation endpoint."
211
- ]
212
- };
213
- }
214
- };
1
+ import {
2
+ presets
3
+ } from "./chunk-GN5SERAQ.mjs";
4
+ import "./chunk-KVW2S6VY.mjs";
5
+ import "./chunk-7P6ASYW6.mjs";
215
6
 
216
7
  // src/env-config.ts
217
8
  var SECRETISH = /(SECRET|PASSWORD|PRIVATE_KEY|CREDENTIALS?)($|_)/;
@@ -1,50 +1,8 @@
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
- }
1
+ import {
2
+ credentialsFromEnv,
3
+ explainCredentials
4
+ } from "./chunk-7AMC336S.mjs";
5
+ import "./chunk-7P6ASYW6.mjs";
48
6
  export {
49
7
  credentialsFromEnv,
50
8
  explainCredentials
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /*! @fluixi/oauth2 v1.0.0-alpha.107 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
1
+ /*! @fluixi/oauth2 v1.0.0-alpha.109 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
2
2
  "use strict";
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;