@stxapp/stx-typescript 0.8.0 → 0.9.0-alpha.1
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/CHANGELOG.md +23 -0
- package/README.md +42 -0
- package/dist/{chunk-L2DEU7R6.cjs → chunk-33AQCUGM.cjs} +53 -27
- package/dist/chunk-33AQCUGM.cjs.map +1 -0
- package/dist/{chunk-H7XZDE2U.js → chunk-4CSBA2YV.js} +53 -27
- package/dist/chunk-4CSBA2YV.js.map +1 -0
- package/dist/{client-E5Lg6k8d.d.cts → client-CNkaTuhG.d.cts} +121 -40
- package/dist/{client-E5Lg6k8d.d.ts → client-CNkaTuhG.d.ts} +121 -40
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/oauth.cjs +374 -39
- package/dist/oauth.cjs.map +1 -1
- package/dist/oauth.d.cts +156 -11
- package/dist/oauth.d.ts +156 -11
- package/dist/oauth.js +349 -14
- package/dist/oauth.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-H7XZDE2U.js.map +0 -1
- package/dist/chunk-L2DEU7R6.cjs.map +0 -1
package/dist/oauth.js
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
STXInsufficientScopeException,
|
|
8
8
|
STXInvalidTokenException,
|
|
9
9
|
baseUrlFor
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-4CSBA2YV.js";
|
|
11
11
|
|
|
12
12
|
// src/oauth/endpoints.ts
|
|
13
13
|
var DEFAULT_ENDPOINTS = {
|
|
@@ -45,7 +45,13 @@ var STXOAuthException = class extends STXAuthenticationException {
|
|
|
45
45
|
endpoint;
|
|
46
46
|
/** Seconds to wait when the endpoint answered 429 with Retry-After. */
|
|
47
47
|
retryAfter;
|
|
48
|
-
|
|
48
|
+
/**
|
|
49
|
+
* STX's own, narrower reason, when the answer carries one. `account_pending`
|
|
50
|
+
* on an `invalid_grant` means the member's STX account is still being
|
|
51
|
+
* verified.
|
|
52
|
+
*/
|
|
53
|
+
errorReason;
|
|
54
|
+
constructor(error, errorDescription, status, endpoint, retryAfter, errorReason) {
|
|
49
55
|
super(`OAuth ${endpoint} ${status} ${error}${errorDescription ? `: ${errorDescription}` : ""}`, {
|
|
50
56
|
statusCode: status,
|
|
51
57
|
path: endpoint
|
|
@@ -54,8 +60,17 @@ var STXOAuthException = class extends STXAuthenticationException {
|
|
|
54
60
|
this.errorDescription = errorDescription;
|
|
55
61
|
this.endpoint = endpoint;
|
|
56
62
|
this.retryAfter = retryAfter;
|
|
63
|
+
this.errorReason = errorReason;
|
|
57
64
|
}
|
|
58
65
|
};
|
|
66
|
+
var STXAccessDeniedException = class extends STXOAuthException {
|
|
67
|
+
};
|
|
68
|
+
var STXAccountPendingException = class extends STXOAuthException {
|
|
69
|
+
};
|
|
70
|
+
function callbackError(error, errorDescription, endpoint) {
|
|
71
|
+
const Class = error === "account_pending" ? STXAccountPendingException : error === "access_denied" ? STXAccessDeniedException : STXOAuthException;
|
|
72
|
+
return new Class(error, errorDescription, 400, endpoint);
|
|
73
|
+
}
|
|
59
74
|
var STXGrantRevokedException = class extends STXAuthenticationException {
|
|
60
75
|
constructor(message = "OAuth grant revoked: the member must re-authorize.") {
|
|
61
76
|
super(message, { statusCode: 400 });
|
|
@@ -123,7 +138,8 @@ async function registerClient(request, opts = {}) {
|
|
|
123
138
|
err.error_description,
|
|
124
139
|
res.status,
|
|
125
140
|
path,
|
|
126
|
-
Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : void 0
|
|
141
|
+
Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : void 0,
|
|
142
|
+
err.error_reason
|
|
127
143
|
);
|
|
128
144
|
}
|
|
129
145
|
throw httpError(res.status, text, path);
|
|
@@ -134,7 +150,8 @@ function rfcError(text) {
|
|
|
134
150
|
if (typeof obj.error !== "string") return null;
|
|
135
151
|
return {
|
|
136
152
|
error: obj.error,
|
|
137
|
-
error_description: typeof obj.error_description === "string" ? obj.error_description : void 0
|
|
153
|
+
error_description: typeof obj.error_description === "string" ? obj.error_description : void 0,
|
|
154
|
+
error_reason: typeof obj.error_reason === "string" ? obj.error_reason : void 0
|
|
138
155
|
};
|
|
139
156
|
} catch {
|
|
140
157
|
return null;
|
|
@@ -277,7 +294,11 @@ var OAuthClient = class _OAuthClient {
|
|
|
277
294
|
scope: params.scope,
|
|
278
295
|
prompt: params.prompt,
|
|
279
296
|
redirectUri: params.redirectUri,
|
|
280
|
-
extraParams:
|
|
297
|
+
extraParams: {
|
|
298
|
+
...params.connection ? { connection: params.connection } : {},
|
|
299
|
+
...params.loginHint ? { login_hint: params.loginHint } : {},
|
|
300
|
+
...params.extraParams ?? {}
|
|
301
|
+
}
|
|
281
302
|
});
|
|
282
303
|
return { url, state, codeVerifier: pkce.codeVerifier, codeChallenge: pkce.codeChallenge };
|
|
283
304
|
}
|
|
@@ -305,7 +326,7 @@ var OAuthClient = class _OAuthClient {
|
|
|
305
326
|
}
|
|
306
327
|
/**
|
|
307
328
|
* Finish a sign-in from the callback's query. Checks for an `error` from
|
|
308
|
-
* the exchange (
|
|
329
|
+
* the exchange (`access_denied`, `account_pending`), consumes the
|
|
309
330
|
* `state` (single use; unknown or expired throws `invalid_state`), exchanges
|
|
310
331
|
* the code with the stored PKCE verifier and, when `store` is given, saves
|
|
311
332
|
* the tokens under `memberKey` (a string, or a function of the `data` passed
|
|
@@ -430,7 +451,10 @@ var OAuthClient = class _OAuthClient {
|
|
|
430
451
|
return provider;
|
|
431
452
|
}
|
|
432
453
|
// ---- Revoke (RFC 7009) --------------------------------------------------
|
|
433
|
-
/**
|
|
454
|
+
/**
|
|
455
|
+
* Revoke a token. A refresh token ends the member's grant (every token on it);
|
|
456
|
+
* an access token revokes only its pair. Always resolves on a 200.
|
|
457
|
+
*/
|
|
434
458
|
async revoke(token, tokenTypeHint) {
|
|
435
459
|
const body = new URLSearchParams({ token });
|
|
436
460
|
if (tokenTypeHint) body.set("token_type_hint", tokenTypeHint);
|
|
@@ -535,10 +559,13 @@ var OAuthClient = class _OAuthClient {
|
|
|
535
559
|
return map;
|
|
536
560
|
}
|
|
537
561
|
// ---- internals ----------------------------------------------------------
|
|
538
|
-
/**
|
|
562
|
+
/**
|
|
563
|
+
* `client_secret_basic` header, or undefined for a public client. Both parts
|
|
564
|
+
* are form-urlencoded before base64, as RFC 6749 section 2.3.1 requires.
|
|
565
|
+
*/
|
|
539
566
|
basicAuthHeader() {
|
|
540
567
|
if (this.clientSecret === void 0) return void 0;
|
|
541
|
-
const raw = `${this.clientId}:${this.clientSecret}`;
|
|
568
|
+
const raw = `${formEncode(this.clientId)}:${formEncode(this.clientSecret)}`;
|
|
542
569
|
return "Basic " + Buffer.from(raw).toString("base64");
|
|
543
570
|
}
|
|
544
571
|
formHeaders() {
|
|
@@ -563,6 +590,16 @@ var OAuthClient = class _OAuthClient {
|
|
|
563
590
|
const text = await res.text();
|
|
564
591
|
if (!res.ok) {
|
|
565
592
|
const err = rfcError(text);
|
|
593
|
+
if (err?.error === "invalid_grant" && err.error_reason === "account_pending") {
|
|
594
|
+
throw new STXAccountPendingException(
|
|
595
|
+
err.error,
|
|
596
|
+
err.error_description,
|
|
597
|
+
res.status,
|
|
598
|
+
pathOf(this.endpoints.token),
|
|
599
|
+
void 0,
|
|
600
|
+
err.error_reason
|
|
601
|
+
);
|
|
602
|
+
}
|
|
566
603
|
if (res.status === 400 && err?.error === "invalid_grant" && body.get("grant_type") === "refresh_token") {
|
|
567
604
|
throw new STXGrantRevokedException(
|
|
568
605
|
err.error_description ? `OAuth grant revoked: ${err.error_description}. The member must re-authorize.` : void 0
|
|
@@ -575,7 +612,7 @@ var OAuthClient = class _OAuthClient {
|
|
|
575
612
|
oauthError(status, text, endpoint) {
|
|
576
613
|
const err = rfcError(text);
|
|
577
614
|
const path = pathOf(endpoint);
|
|
578
|
-
if (err) return new STXOAuthException(err.error, err.error_description, status, path);
|
|
615
|
+
if (err) return new STXOAuthException(err.error, err.error_description, status, path, void 0, err.error_reason);
|
|
579
616
|
return new STXOAuthException("http_error", text.slice(0, 300) || void 0, status, path);
|
|
580
617
|
}
|
|
581
618
|
};
|
|
@@ -605,6 +642,7 @@ function parseTokenResponse(json) {
|
|
|
605
642
|
set.expiresAt = Date.now() + obj.expires_in * 1e3;
|
|
606
643
|
}
|
|
607
644
|
if (typeof obj.scope === "string") set.scope = obj.scope;
|
|
645
|
+
if (typeof obj.id_token === "string") set.idToken = obj.id_token;
|
|
608
646
|
return set;
|
|
609
647
|
}
|
|
610
648
|
function tokenSetToStored(set) {
|
|
@@ -734,7 +772,9 @@ var OAuthSessionAuth = class {
|
|
|
734
772
|
* Refresh with rotation, single-flight. Persists the new pair (keeping the
|
|
735
773
|
* returned refresh token; the old one only if the server omitted it). On a
|
|
736
774
|
* revoked grant, deletes the store entry and throws
|
|
737
|
-
* `STXGrantRevokedException`.
|
|
775
|
+
* `STXGrantRevokedException`. While the member's account is still being
|
|
776
|
+
* verified, keeps the store entry and throws `STXAccountPendingException`.
|
|
777
|
+
* A transient failure resolves null.
|
|
738
778
|
*/
|
|
739
779
|
refresh(refreshToken) {
|
|
740
780
|
const inflight = this.client._refreshesFor(this.store);
|
|
@@ -760,6 +800,7 @@ var OAuthSessionAuth = class {
|
|
|
760
800
|
await this.opts.onGrantRevoked?.(err);
|
|
761
801
|
throw err;
|
|
762
802
|
}
|
|
803
|
+
if (err instanceof STXAccountPendingException) throw err;
|
|
763
804
|
return null;
|
|
764
805
|
}
|
|
765
806
|
};
|
|
@@ -797,6 +838,9 @@ var OAuthAppAuth = class {
|
|
|
797
838
|
return { "x-stx-oauth-token": token };
|
|
798
839
|
}
|
|
799
840
|
};
|
|
841
|
+
function formEncode(value) {
|
|
842
|
+
return new URLSearchParams({ v: value }).toString().slice(2);
|
|
843
|
+
}
|
|
800
844
|
function normalizeScope(scope) {
|
|
801
845
|
if (scope === void 0) return void 0;
|
|
802
846
|
return typeof scope === "string" ? scope : formatScopes(scope);
|
|
@@ -805,13 +849,12 @@ async function readCallback(pending, callback, authorizeEndpoint = DEFAULT_ENDPO
|
|
|
805
849
|
const q = callbackParams(callback);
|
|
806
850
|
const where = pathOf(authorizeEndpoint);
|
|
807
851
|
const error = q.get("error");
|
|
808
|
-
if (error) throw new STXOAuthException(error, q.get("error_description") ?? void 0, 400, where);
|
|
809
852
|
const code = q.get("code");
|
|
810
853
|
const state = q.get("state");
|
|
811
|
-
if (!code || !state) {
|
|
854
|
+
if (!error && (!code || !state)) {
|
|
812
855
|
throw new STXOAuthException("invalid_request", "The callback carries no code or no state.", 400, where);
|
|
813
856
|
}
|
|
814
|
-
const entry = await pending.take(state);
|
|
857
|
+
const entry = state ? await pending.take(state) : null;
|
|
815
858
|
if (!entry) {
|
|
816
859
|
throw new STXOAuthException(
|
|
817
860
|
"invalid_state",
|
|
@@ -820,6 +863,7 @@ async function readCallback(pending, callback, authorizeEndpoint = DEFAULT_ENDPO
|
|
|
820
863
|
where
|
|
821
864
|
);
|
|
822
865
|
}
|
|
866
|
+
if (error) throw callbackError(error, q.get("error_description") ?? void 0, where);
|
|
823
867
|
return { code, pending: entry };
|
|
824
868
|
}
|
|
825
869
|
function callbackParams(input) {
|
|
@@ -841,6 +885,294 @@ function pathOf(endpoint) {
|
|
|
841
885
|
}
|
|
842
886
|
}
|
|
843
887
|
|
|
888
|
+
// src/oauth/connect.ts
|
|
889
|
+
function createConnect(opts) {
|
|
890
|
+
if (!opts.issuer) throw new STXConfigException("issuer is required.");
|
|
891
|
+
if (!opts.clientId || !opts.clientSecret) throw new STXConfigException("clientId and clientSecret are required.");
|
|
892
|
+
if (!opts.redirectUri) throw new STXConfigException("redirectUri is required.");
|
|
893
|
+
const issuer = opts.issuer.replace(/\/+$/, "");
|
|
894
|
+
const fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
895
|
+
if (typeof fetchImpl !== "function") {
|
|
896
|
+
throw new STXConfigException("No fetch implementation available. Use Node 18+, or pass { fetch }.");
|
|
897
|
+
}
|
|
898
|
+
const skew = opts.clockSkewSeconds ?? 60;
|
|
899
|
+
let config;
|
|
900
|
+
let client;
|
|
901
|
+
let keys;
|
|
902
|
+
const configuration = () => {
|
|
903
|
+
config ??= fetchJson(fetchImpl, joinUrl(issuer, "/.well-known/openid-configuration")).then((doc) => {
|
|
904
|
+
const c = doc;
|
|
905
|
+
if (typeof c.issuer !== "string" || typeof c.authorization_endpoint !== "string" || typeof c.token_endpoint !== "string" || typeof c.jwks_uri !== "string") {
|
|
906
|
+
throw new STXOAuthException(
|
|
907
|
+
"invalid_configuration",
|
|
908
|
+
"The discovery document is incomplete.",
|
|
909
|
+
0,
|
|
910
|
+
"/.well-known/openid-configuration"
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
if (c.issuer.replace(/\/+$/, "") !== issuer) {
|
|
914
|
+
throw new STXOAuthException(
|
|
915
|
+
"invalid_configuration",
|
|
916
|
+
`The discovery issuer ${c.issuer} does not match ${issuer}.`,
|
|
917
|
+
0,
|
|
918
|
+
"/.well-known/openid-configuration"
|
|
919
|
+
);
|
|
920
|
+
}
|
|
921
|
+
return c;
|
|
922
|
+
});
|
|
923
|
+
config.catch(() => {
|
|
924
|
+
config = void 0;
|
|
925
|
+
});
|
|
926
|
+
return config;
|
|
927
|
+
};
|
|
928
|
+
const oauth = () => {
|
|
929
|
+
client ??= configuration().then(
|
|
930
|
+
(c) => new OAuthClient({
|
|
931
|
+
baseUrl: issuer,
|
|
932
|
+
clientId: opts.clientId,
|
|
933
|
+
clientSecret: opts.clientSecret,
|
|
934
|
+
redirectUri: opts.redirectUri,
|
|
935
|
+
fetch: fetchImpl,
|
|
936
|
+
endpoints: {
|
|
937
|
+
authorize: c.authorization_endpoint,
|
|
938
|
+
token: c.token_endpoint,
|
|
939
|
+
...c.revocation_endpoint ? { revoke: c.revocation_endpoint } : {}
|
|
940
|
+
}
|
|
941
|
+
})
|
|
942
|
+
);
|
|
943
|
+
client.catch(() => {
|
|
944
|
+
client = void 0;
|
|
945
|
+
});
|
|
946
|
+
return client;
|
|
947
|
+
};
|
|
948
|
+
const jwks = async (refresh = false) => {
|
|
949
|
+
if (refresh) keys = void 0;
|
|
950
|
+
keys ??= configuration().then((c) => fetchJson(fetchImpl, c.jwks_uri)).then((doc) => {
|
|
951
|
+
const list = doc.keys;
|
|
952
|
+
if (!Array.isArray(list))
|
|
953
|
+
throw new STXOAuthException("invalid_configuration", "The key set has no keys.", 0, "jwks_uri");
|
|
954
|
+
return list;
|
|
955
|
+
});
|
|
956
|
+
keys.catch(() => {
|
|
957
|
+
keys = void 0;
|
|
958
|
+
});
|
|
959
|
+
return keys;
|
|
960
|
+
};
|
|
961
|
+
return {
|
|
962
|
+
configuration,
|
|
963
|
+
async start(params = {}) {
|
|
964
|
+
const c = await oauth();
|
|
965
|
+
const pkce = await createPkce();
|
|
966
|
+
const state = generateState();
|
|
967
|
+
const nonce = generateState();
|
|
968
|
+
const redirectUri = params.redirectUri ?? opts.redirectUri;
|
|
969
|
+
const extraParams = { nonce };
|
|
970
|
+
if (params.connection) extraParams.connection = params.connection;
|
|
971
|
+
if (params.loginHint) extraParams.login_hint = params.loginHint;
|
|
972
|
+
const url = c.buildAuthorizeUrl({
|
|
973
|
+
state,
|
|
974
|
+
codeChallenge: pkce.codeChallenge,
|
|
975
|
+
scope: withOpenId(params.scopes ?? opts.scopes),
|
|
976
|
+
prompt: params.prompt,
|
|
977
|
+
redirectUri,
|
|
978
|
+
extraParams
|
|
979
|
+
});
|
|
980
|
+
return { url, state, codeVerifier: pkce.codeVerifier, nonce, redirectUri };
|
|
981
|
+
},
|
|
982
|
+
async finish(callback, saved) {
|
|
983
|
+
const q = callbackParams(callback);
|
|
984
|
+
const where = pathOf2((await configuration()).authorization_endpoint);
|
|
985
|
+
const error = q.get("error");
|
|
986
|
+
const code = q.get("code");
|
|
987
|
+
const state = q.get("state");
|
|
988
|
+
if (!error && (!code || !state)) {
|
|
989
|
+
throw new STXOAuthException("invalid_request", "The callback carries no code or no state.", 400, where);
|
|
990
|
+
}
|
|
991
|
+
if (!state || !saved?.state || !constantTimeEqual(state, saved.state)) {
|
|
992
|
+
throw new STXOAuthException("invalid_state", "The state does not match this sign-in; start again.", 400, where);
|
|
993
|
+
}
|
|
994
|
+
if (error) throw callbackError(error, q.get("error_description") ?? void 0, where);
|
|
995
|
+
const c = await oauth();
|
|
996
|
+
const tokens = await c.exchangeCode({
|
|
997
|
+
code,
|
|
998
|
+
codeVerifier: saved.codeVerifier,
|
|
999
|
+
redirectUri: saved.redirectUri ?? opts.redirectUri
|
|
1000
|
+
});
|
|
1001
|
+
const idToken = tokens.idToken;
|
|
1002
|
+
if (!idToken) {
|
|
1003
|
+
throw new STXOAuthException(
|
|
1004
|
+
"invalid_id_token",
|
|
1005
|
+
"The token response has no id_token; request the openid scope.",
|
|
1006
|
+
0,
|
|
1007
|
+
"/oauth/token"
|
|
1008
|
+
);
|
|
1009
|
+
}
|
|
1010
|
+
const claims = await verifyIdToken(idToken, {
|
|
1011
|
+
issuer: (await configuration()).issuer,
|
|
1012
|
+
clientId: opts.clientId,
|
|
1013
|
+
nonce: saved.nonce,
|
|
1014
|
+
skew,
|
|
1015
|
+
keys: jwks
|
|
1016
|
+
});
|
|
1017
|
+
return { tokens: { ...tokens, idToken }, identity: identityFrom(claims) };
|
|
1018
|
+
},
|
|
1019
|
+
async userInfo(accessToken, expected = {}) {
|
|
1020
|
+
const endpoint = (await configuration()).userinfo_endpoint;
|
|
1021
|
+
if (!endpoint) {
|
|
1022
|
+
throw new STXOAuthException(
|
|
1023
|
+
"invalid_configuration",
|
|
1024
|
+
"The discovery document names no userinfo endpoint.",
|
|
1025
|
+
0,
|
|
1026
|
+
"/.well-known/openid-configuration"
|
|
1027
|
+
);
|
|
1028
|
+
}
|
|
1029
|
+
const where = pathOf2(endpoint);
|
|
1030
|
+
const res = await fetchImpl(endpoint, {
|
|
1031
|
+
method: "GET",
|
|
1032
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${accessToken}` }
|
|
1033
|
+
});
|
|
1034
|
+
const text = await res.text();
|
|
1035
|
+
let body;
|
|
1036
|
+
try {
|
|
1037
|
+
body = JSON.parse(text);
|
|
1038
|
+
} catch {
|
|
1039
|
+
body = void 0;
|
|
1040
|
+
}
|
|
1041
|
+
const claims = body && typeof body === "object" ? body : {};
|
|
1042
|
+
if (!res.ok) {
|
|
1043
|
+
const error = typeof claims.error === "string" ? claims.error : res.status === 401 ? "invalid_token" : "error";
|
|
1044
|
+
const description = typeof claims.error_description === "string" ? claims.error_description : void 0;
|
|
1045
|
+
const reason = typeof claims.error_reason === "string" ? claims.error_reason : void 0;
|
|
1046
|
+
throw new STXOAuthException(error, description, res.status, where, void 0, reason);
|
|
1047
|
+
}
|
|
1048
|
+
const fail = (why) => {
|
|
1049
|
+
throw new STXOAuthException("invalid_userinfo", why, 0, where);
|
|
1050
|
+
};
|
|
1051
|
+
if (typeof claims.sub !== "string" || claims.sub === "") fail("The userinfo answer has no subject.");
|
|
1052
|
+
if (expected.sub !== void 0 && claims.sub !== expected.sub) {
|
|
1053
|
+
fail("The userinfo answer is about a different member.");
|
|
1054
|
+
}
|
|
1055
|
+
return identityFrom(claims);
|
|
1056
|
+
},
|
|
1057
|
+
async refresh(refreshToken) {
|
|
1058
|
+
return (await oauth()).refreshToken(refreshToken);
|
|
1059
|
+
},
|
|
1060
|
+
async revoke(token, tokenTypeHint) {
|
|
1061
|
+
return (await oauth()).revoke(token, tokenTypeHint);
|
|
1062
|
+
},
|
|
1063
|
+
async disconnect(tokens) {
|
|
1064
|
+
const client2 = await oauth();
|
|
1065
|
+
if (tokens.refreshToken) return client2.revoke(tokens.refreshToken, "refresh_token");
|
|
1066
|
+
return client2.revoke(tokens.accessToken, "access_token");
|
|
1067
|
+
}
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
function pathOf2(url) {
|
|
1071
|
+
try {
|
|
1072
|
+
return new URL(url).pathname;
|
|
1073
|
+
} catch {
|
|
1074
|
+
return url;
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
function identityFrom(claims) {
|
|
1078
|
+
return {
|
|
1079
|
+
sub: claims.sub,
|
|
1080
|
+
...typeof claims.email === "string" ? { email: claims.email } : {},
|
|
1081
|
+
...claims.email_verified !== void 0 ? { emailVerified: claims.email_verified === true || claims.email_verified === "true" } : {},
|
|
1082
|
+
claims
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
function withOpenId(scopes) {
|
|
1086
|
+
const list = scopes === void 0 ? [] : typeof scopes === "string" ? scopes.split(/\s+/) : [...scopes];
|
|
1087
|
+
const set = new Set(list.filter(Boolean));
|
|
1088
|
+
set.delete("openid");
|
|
1089
|
+
return formatScopes(["openid", ...set]);
|
|
1090
|
+
}
|
|
1091
|
+
async function fetchJson(fetchImpl, url) {
|
|
1092
|
+
const res = await fetchImpl(url, { method: "GET", headers: { Accept: "application/json" } });
|
|
1093
|
+
const text = await res.text();
|
|
1094
|
+
if (!res.ok) {
|
|
1095
|
+
throw new STXOAuthException("invalid_configuration", `GET ${url} returned ${res.status}.`, res.status, url);
|
|
1096
|
+
}
|
|
1097
|
+
try {
|
|
1098
|
+
return JSON.parse(text);
|
|
1099
|
+
} catch {
|
|
1100
|
+
throw new STXOAuthException("invalid_configuration", `GET ${url} did not return JSON.`, res.status, url);
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
var ALGORITHMS = {
|
|
1104
|
+
RS256: {
|
|
1105
|
+
import: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
|
|
1106
|
+
verify: { name: "RSASSA-PKCS1-v1_5" }
|
|
1107
|
+
},
|
|
1108
|
+
ES256: {
|
|
1109
|
+
import: { name: "ECDSA", namedCurve: "P-256" },
|
|
1110
|
+
verify: { name: "ECDSA", hash: "SHA-256" }
|
|
1111
|
+
}
|
|
1112
|
+
};
|
|
1113
|
+
async function verifyIdToken(token, expected) {
|
|
1114
|
+
const fail = (why) => {
|
|
1115
|
+
throw new STXOAuthException("invalid_id_token", why, 0, "/oauth/token");
|
|
1116
|
+
};
|
|
1117
|
+
const parts = token.split(".");
|
|
1118
|
+
if (parts.length !== 3) fail("The ID token is not a JWT.");
|
|
1119
|
+
const [h, p, s] = parts;
|
|
1120
|
+
const header = decodeJson(h);
|
|
1121
|
+
const claims = decodeJson(p);
|
|
1122
|
+
if (!header || !claims) return fail("The ID token is malformed.");
|
|
1123
|
+
const alg = header.alg ?? "";
|
|
1124
|
+
const algorithm = ALGORITHMS[alg];
|
|
1125
|
+
if (!algorithm) return fail(`Unsupported ID token algorithm ${alg}.`);
|
|
1126
|
+
const pick = (list) => list.find((k) => (header.kid ? k.kid === header.kid : true) && (!k.alg || k.alg === alg) && k.use !== "enc");
|
|
1127
|
+
let jwk = pick(await expected.keys());
|
|
1128
|
+
if (!jwk && header.kid) jwk = pick(await expected.keys(true));
|
|
1129
|
+
if (!jwk) return fail("No published key matches the ID token.");
|
|
1130
|
+
const { kid: _kid, alg: _alg, use: _use, key_ops: _ops, ...material } = jwk;
|
|
1131
|
+
const key = await crypto.subtle.importKey("jwk", material, algorithm.import, false, [
|
|
1132
|
+
"verify"
|
|
1133
|
+
]);
|
|
1134
|
+
const ok = await crypto.subtle.verify(
|
|
1135
|
+
algorithm.verify,
|
|
1136
|
+
key,
|
|
1137
|
+
base64urlDecode(s),
|
|
1138
|
+
new TextEncoder().encode(`${h}.${p}`)
|
|
1139
|
+
);
|
|
1140
|
+
if (!ok) fail("The ID token signature does not verify.");
|
|
1141
|
+
if (claims.iss !== expected.issuer) fail("The ID token was issued by someone else.");
|
|
1142
|
+
const aud = claims.aud;
|
|
1143
|
+
const audiences = Array.isArray(aud) ? aud : [aud];
|
|
1144
|
+
if (!audiences.includes(expected.clientId)) fail("The ID token is for another app.");
|
|
1145
|
+
if (audiences.length > 1 && claims.azp !== expected.clientId) fail("The ID token is for another app.");
|
|
1146
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1147
|
+
if (typeof claims.exp !== "number" || claims.exp + expected.skew < now) fail("The ID token has expired.");
|
|
1148
|
+
if (typeof claims.iat === "number" && claims.iat - expected.skew > now) fail("The ID token is not valid yet.");
|
|
1149
|
+
if (typeof claims.nonce !== "string" || !constantTimeEqual(claims.nonce, expected.nonce)) {
|
|
1150
|
+
fail("The ID token nonce does not match this sign-in.");
|
|
1151
|
+
}
|
|
1152
|
+
if (typeof claims.sub !== "string" || claims.sub === "") fail("The ID token has no subject.");
|
|
1153
|
+
return claims;
|
|
1154
|
+
}
|
|
1155
|
+
function decodeJson(segment) {
|
|
1156
|
+
try {
|
|
1157
|
+
return JSON.parse(new TextDecoder().decode(base64urlDecode(segment)));
|
|
1158
|
+
} catch {
|
|
1159
|
+
return void 0;
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
function base64urlDecode(segment) {
|
|
1163
|
+
const b64 = segment.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((segment.length + 3) % 4);
|
|
1164
|
+
const bin = atob(b64);
|
|
1165
|
+
const out = new Uint8Array(bin.length);
|
|
1166
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
1167
|
+
return out;
|
|
1168
|
+
}
|
|
1169
|
+
function constantTimeEqual(a, b) {
|
|
1170
|
+
if (a.length !== b.length) return false;
|
|
1171
|
+
let diff = 0;
|
|
1172
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
1173
|
+
return diff === 0;
|
|
1174
|
+
}
|
|
1175
|
+
|
|
844
1176
|
// src/oauth/metadata.ts
|
|
845
1177
|
async function discoverMetadata(baseUrl, opts = {}) {
|
|
846
1178
|
const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.authorizationServer, opts);
|
|
@@ -939,6 +1271,8 @@ export {
|
|
|
939
1271
|
OAuthBearerAuth,
|
|
940
1272
|
OAuthClient,
|
|
941
1273
|
OAuthSessionAuth,
|
|
1274
|
+
STXAccessDeniedException,
|
|
1275
|
+
STXAccountPendingException,
|
|
942
1276
|
STXAuthenticationException,
|
|
943
1277
|
STXForbiddenException,
|
|
944
1278
|
STXGrantRevokedException,
|
|
@@ -950,6 +1284,7 @@ export {
|
|
|
950
1284
|
base64url,
|
|
951
1285
|
canonicalScope,
|
|
952
1286
|
codeChallengeS256,
|
|
1287
|
+
createConnect,
|
|
953
1288
|
createPkce,
|
|
954
1289
|
discoverMetadata,
|
|
955
1290
|
discoverProtectedResource,
|