@stxapp/stx-typescript 0.7.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 +29 -0
- package/README.md +42 -0
- package/dist/{chunk-ASOLCDBG.cjs → chunk-33AQCUGM.cjs} +245 -6
- package/dist/chunk-33AQCUGM.cjs.map +1 -0
- package/dist/{chunk-CDXZOW53.js → chunk-4CSBA2YV.js} +244 -5
- package/dist/chunk-4CSBA2YV.js.map +1 -0
- package/dist/{client-CA1d-osT.d.cts → client-CNkaTuhG.d.cts} +665 -110
- package/dist/{client-CA1d-osT.d.ts → client-CNkaTuhG.d.ts} +665 -110
- package/dist/index.cjs +8 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +7 -1
- package/dist/oauth.cjs +378 -41
- package/dist/oauth.cjs.map +1 -1
- package/dist/oauth.d.cts +162 -13
- package/dist/oauth.d.ts +162 -13
- package/dist/oauth.js +353 -16
- package/dist/oauth.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-ASOLCDBG.cjs.map +0 -1
- package/dist/chunk-CDXZOW53.js.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;
|
|
@@ -168,8 +185,10 @@ var MemberScopes = {
|
|
|
168
185
|
var AppScopes = {
|
|
169
186
|
/** The market catalog (`GET /api/v1/markets`) and the market data channels. */
|
|
170
187
|
MARKET_DATA: "market_data",
|
|
171
|
-
/** The event catalog (`GET /api/v1/events
|
|
172
|
-
EVENTS: "events"
|
|
188
|
+
/** The event catalog (`GET /api/v1/events`, an event's players) and the `events` channel. */
|
|
189
|
+
EVENTS: "events",
|
|
190
|
+
/** Create markets (`POST /api/v1/markets`). Granted by STX only. */
|
|
191
|
+
MARKETS_WRITE: "markets.write"
|
|
173
192
|
};
|
|
174
193
|
var Scopes = { ...MemberScopes, ...AppScopes };
|
|
175
194
|
var ALL_MEMBER_SCOPES = Object.values(MemberScopes);
|
|
@@ -275,7 +294,11 @@ var OAuthClient = class _OAuthClient {
|
|
|
275
294
|
scope: params.scope,
|
|
276
295
|
prompt: params.prompt,
|
|
277
296
|
redirectUri: params.redirectUri,
|
|
278
|
-
extraParams:
|
|
297
|
+
extraParams: {
|
|
298
|
+
...params.connection ? { connection: params.connection } : {},
|
|
299
|
+
...params.loginHint ? { login_hint: params.loginHint } : {},
|
|
300
|
+
...params.extraParams ?? {}
|
|
301
|
+
}
|
|
279
302
|
});
|
|
280
303
|
return { url, state, codeVerifier: pkce.codeVerifier, codeChallenge: pkce.codeChallenge };
|
|
281
304
|
}
|
|
@@ -303,7 +326,7 @@ var OAuthClient = class _OAuthClient {
|
|
|
303
326
|
}
|
|
304
327
|
/**
|
|
305
328
|
* Finish a sign-in from the callback's query. Checks for an `error` from
|
|
306
|
-
* the exchange (
|
|
329
|
+
* the exchange (`access_denied`, `account_pending`), consumes the
|
|
307
330
|
* `state` (single use; unknown or expired throws `invalid_state`), exchanges
|
|
308
331
|
* the code with the stored PKCE verifier and, when `store` is given, saves
|
|
309
332
|
* the tokens under `memberKey` (a string, or a function of the `data` passed
|
|
@@ -428,7 +451,10 @@ var OAuthClient = class _OAuthClient {
|
|
|
428
451
|
return provider;
|
|
429
452
|
}
|
|
430
453
|
// ---- Revoke (RFC 7009) --------------------------------------------------
|
|
431
|
-
/**
|
|
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
|
+
*/
|
|
432
458
|
async revoke(token, tokenTypeHint) {
|
|
433
459
|
const body = new URLSearchParams({ token });
|
|
434
460
|
if (tokenTypeHint) body.set("token_type_hint", tokenTypeHint);
|
|
@@ -533,10 +559,13 @@ var OAuthClient = class _OAuthClient {
|
|
|
533
559
|
return map;
|
|
534
560
|
}
|
|
535
561
|
// ---- internals ----------------------------------------------------------
|
|
536
|
-
/**
|
|
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
|
+
*/
|
|
537
566
|
basicAuthHeader() {
|
|
538
567
|
if (this.clientSecret === void 0) return void 0;
|
|
539
|
-
const raw = `${this.clientId}:${this.clientSecret}`;
|
|
568
|
+
const raw = `${formEncode(this.clientId)}:${formEncode(this.clientSecret)}`;
|
|
540
569
|
return "Basic " + Buffer.from(raw).toString("base64");
|
|
541
570
|
}
|
|
542
571
|
formHeaders() {
|
|
@@ -561,6 +590,16 @@ var OAuthClient = class _OAuthClient {
|
|
|
561
590
|
const text = await res.text();
|
|
562
591
|
if (!res.ok) {
|
|
563
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
|
+
}
|
|
564
603
|
if (res.status === 400 && err?.error === "invalid_grant" && body.get("grant_type") === "refresh_token") {
|
|
565
604
|
throw new STXGrantRevokedException(
|
|
566
605
|
err.error_description ? `OAuth grant revoked: ${err.error_description}. The member must re-authorize.` : void 0
|
|
@@ -573,7 +612,7 @@ var OAuthClient = class _OAuthClient {
|
|
|
573
612
|
oauthError(status, text, endpoint) {
|
|
574
613
|
const err = rfcError(text);
|
|
575
614
|
const path = pathOf(endpoint);
|
|
576
|
-
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);
|
|
577
616
|
return new STXOAuthException("http_error", text.slice(0, 300) || void 0, status, path);
|
|
578
617
|
}
|
|
579
618
|
};
|
|
@@ -603,6 +642,7 @@ function parseTokenResponse(json) {
|
|
|
603
642
|
set.expiresAt = Date.now() + obj.expires_in * 1e3;
|
|
604
643
|
}
|
|
605
644
|
if (typeof obj.scope === "string") set.scope = obj.scope;
|
|
645
|
+
if (typeof obj.id_token === "string") set.idToken = obj.id_token;
|
|
606
646
|
return set;
|
|
607
647
|
}
|
|
608
648
|
function tokenSetToStored(set) {
|
|
@@ -732,7 +772,9 @@ var OAuthSessionAuth = class {
|
|
|
732
772
|
* Refresh with rotation, single-flight. Persists the new pair (keeping the
|
|
733
773
|
* returned refresh token; the old one only if the server omitted it). On a
|
|
734
774
|
* revoked grant, deletes the store entry and throws
|
|
735
|
-
* `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.
|
|
736
778
|
*/
|
|
737
779
|
refresh(refreshToken) {
|
|
738
780
|
const inflight = this.client._refreshesFor(this.store);
|
|
@@ -758,6 +800,7 @@ var OAuthSessionAuth = class {
|
|
|
758
800
|
await this.opts.onGrantRevoked?.(err);
|
|
759
801
|
throw err;
|
|
760
802
|
}
|
|
803
|
+
if (err instanceof STXAccountPendingException) throw err;
|
|
761
804
|
return null;
|
|
762
805
|
}
|
|
763
806
|
};
|
|
@@ -795,6 +838,9 @@ var OAuthAppAuth = class {
|
|
|
795
838
|
return { "x-stx-oauth-token": token };
|
|
796
839
|
}
|
|
797
840
|
};
|
|
841
|
+
function formEncode(value) {
|
|
842
|
+
return new URLSearchParams({ v: value }).toString().slice(2);
|
|
843
|
+
}
|
|
798
844
|
function normalizeScope(scope) {
|
|
799
845
|
if (scope === void 0) return void 0;
|
|
800
846
|
return typeof scope === "string" ? scope : formatScopes(scope);
|
|
@@ -803,13 +849,12 @@ async function readCallback(pending, callback, authorizeEndpoint = DEFAULT_ENDPO
|
|
|
803
849
|
const q = callbackParams(callback);
|
|
804
850
|
const where = pathOf(authorizeEndpoint);
|
|
805
851
|
const error = q.get("error");
|
|
806
|
-
if (error) throw new STXOAuthException(error, q.get("error_description") ?? void 0, 400, where);
|
|
807
852
|
const code = q.get("code");
|
|
808
853
|
const state = q.get("state");
|
|
809
|
-
if (!code || !state) {
|
|
854
|
+
if (!error && (!code || !state)) {
|
|
810
855
|
throw new STXOAuthException("invalid_request", "The callback carries no code or no state.", 400, where);
|
|
811
856
|
}
|
|
812
|
-
const entry = await pending.take(state);
|
|
857
|
+
const entry = state ? await pending.take(state) : null;
|
|
813
858
|
if (!entry) {
|
|
814
859
|
throw new STXOAuthException(
|
|
815
860
|
"invalid_state",
|
|
@@ -818,6 +863,7 @@ async function readCallback(pending, callback, authorizeEndpoint = DEFAULT_ENDPO
|
|
|
818
863
|
where
|
|
819
864
|
);
|
|
820
865
|
}
|
|
866
|
+
if (error) throw callbackError(error, q.get("error_description") ?? void 0, where);
|
|
821
867
|
return { code, pending: entry };
|
|
822
868
|
}
|
|
823
869
|
function callbackParams(input) {
|
|
@@ -839,6 +885,294 @@ function pathOf(endpoint) {
|
|
|
839
885
|
}
|
|
840
886
|
}
|
|
841
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
|
+
|
|
842
1176
|
// src/oauth/metadata.ts
|
|
843
1177
|
async function discoverMetadata(baseUrl, opts = {}) {
|
|
844
1178
|
const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.authorizationServer, opts);
|
|
@@ -937,6 +1271,8 @@ export {
|
|
|
937
1271
|
OAuthBearerAuth,
|
|
938
1272
|
OAuthClient,
|
|
939
1273
|
OAuthSessionAuth,
|
|
1274
|
+
STXAccessDeniedException,
|
|
1275
|
+
STXAccountPendingException,
|
|
940
1276
|
STXAuthenticationException,
|
|
941
1277
|
STXForbiddenException,
|
|
942
1278
|
STXGrantRevokedException,
|
|
@@ -948,6 +1284,7 @@ export {
|
|
|
948
1284
|
base64url,
|
|
949
1285
|
canonicalScope,
|
|
950
1286
|
codeChallengeS256,
|
|
1287
|
+
createConnect,
|
|
951
1288
|
createPkce,
|
|
952
1289
|
discoverMetadata,
|
|
953
1290
|
discoverProtectedResource,
|