@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.cjs
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
var
|
|
10
|
+
var _chunk33AQCUGMcjs = require('./chunk-33AQCUGM.cjs');
|
|
11
11
|
|
|
12
12
|
// src/oauth/endpoints.ts
|
|
13
13
|
var DEFAULT_ENDPOINTS = {
|
|
@@ -24,12 +24,12 @@ var WELL_KNOWN = {
|
|
|
24
24
|
function resolveOAuthConfig(input) {
|
|
25
25
|
const env = _nullishCoalesce(_optionalChain([globalThis, 'access', _ => _.process, 'optionalAccess', _2 => _2.env]), () => ( {}));
|
|
26
26
|
const host = _nullishCoalesce(_nullishCoalesce(input.baseUrl, () => ( env.STX_HOST)), () => ( env.STX_BASE_URL));
|
|
27
|
-
if (!host) throw new (0,
|
|
27
|
+
if (!host) throw new (0, _chunk33AQCUGMcjs.STXConfigException)("An OAuth base URL is required. Pass { baseUrl } or set STX_HOST.");
|
|
28
28
|
const fetchImpl = _nullishCoalesce(input.fetch, () => ( globalThis.fetch));
|
|
29
29
|
if (typeof fetchImpl !== "function") {
|
|
30
|
-
throw new (0,
|
|
30
|
+
throw new (0, _chunk33AQCUGMcjs.STXConfigException)("No fetch implementation available. Use Node 18+, or pass { fetch }.");
|
|
31
31
|
}
|
|
32
|
-
return { baseUrl:
|
|
32
|
+
return { baseUrl: _chunk33AQCUGMcjs.baseUrlFor.call(void 0, null, null, host), fetch: fetchImpl };
|
|
33
33
|
}
|
|
34
34
|
function joinUrl(baseUrl, path) {
|
|
35
35
|
if (/^https?:\/\//i.test(path)) return path;
|
|
@@ -37,7 +37,7 @@ function joinUrl(baseUrl, path) {
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
// src/oauth/errors.ts
|
|
40
|
-
var STXOAuthException = class extends
|
|
40
|
+
var STXOAuthException = class extends _chunk33AQCUGMcjs.STXAuthenticationException {
|
|
41
41
|
/** The RFC error code: `invalid_client`, `invalid_grant`, `invalid_scope`, ... */
|
|
42
42
|
|
|
43
43
|
|
|
@@ -45,7 +45,13 @@ var STXOAuthException = class extends _chunkASOLCDBGcjs.STXAuthenticationExcepti
|
|
|
45
45
|
|
|
46
46
|
/** Seconds to wait when the endpoint answered 429 with Retry-After. */
|
|
47
47
|
|
|
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
|
+
|
|
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,9 +60,18 @@ var STXOAuthException = class extends _chunkASOLCDBGcjs.STXAuthenticationExcepti
|
|
|
54
60
|
this.errorDescription = errorDescription;
|
|
55
61
|
this.endpoint = endpoint;
|
|
56
62
|
this.retryAfter = retryAfter;
|
|
63
|
+
this.errorReason = errorReason;
|
|
57
64
|
}
|
|
58
65
|
};
|
|
59
|
-
var
|
|
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
|
+
}
|
|
74
|
+
var STXGrantRevokedException = class extends _chunk33AQCUGMcjs.STXAuthenticationException {
|
|
60
75
|
constructor(message = "OAuth grant revoked: the member must re-authorize.") {
|
|
61
76
|
super(message, { statusCode: 400 });
|
|
62
77
|
}
|
|
@@ -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,14 +150,15 @@ 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 (e2) {
|
|
140
157
|
return null;
|
|
141
158
|
}
|
|
142
159
|
}
|
|
143
160
|
function httpError(status, text, path) {
|
|
144
|
-
return new (0,
|
|
161
|
+
return new (0, _chunk33AQCUGMcjs.STXAPIException)(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {
|
|
145
162
|
statusCode: status,
|
|
146
163
|
body: text,
|
|
147
164
|
path
|
|
@@ -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 = 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
|
+
..._nullishCoalesce(params.extraParams, () => ( {}))
|
|
301
|
+
}
|
|
279
302
|
});
|
|
280
303
|
return { url, state, codeVerifier: pkce.codeVerifier, codeChallenge: pkce.codeChallenge };
|
|
281
304
|
}
|
|
@@ -290,7 +313,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
290
313
|
*/
|
|
291
314
|
async beginAuthorization(pending, params = {}) {
|
|
292
315
|
const redirectUri = _nullishCoalesce(params.redirectUri, () => ( this.redirectUri));
|
|
293
|
-
if (!redirectUri) throw new (0,
|
|
316
|
+
if (!redirectUri) throw new (0, _chunk33AQCUGMcjs.STXConfigException)("redirectUri is required to build an authorize URL.");
|
|
294
317
|
const auth = await this.authorizationUrl({ ...params, redirectUri });
|
|
295
318
|
await pending.put(auth.state, {
|
|
296
319
|
codeVerifier: auth.codeVerifier,
|
|
@@ -303,7 +326,7 @@ var OAuthClient = (_class = 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
|
|
@@ -332,7 +355,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
332
355
|
let memberKey;
|
|
333
356
|
if (opts.store) {
|
|
334
357
|
memberKey = typeof opts.memberKey === "function" ? opts.memberKey(entry.data) : opts.memberKey;
|
|
335
|
-
if (!memberKey) throw new (0,
|
|
358
|
+
if (!memberKey) throw new (0, _chunk33AQCUGMcjs.STXConfigException)("Pass memberKey along with store.");
|
|
336
359
|
await opts.store.set(memberKey, tokenSetToStored(tokens));
|
|
337
360
|
}
|
|
338
361
|
return { tokens, scopes: parseScopes(tokens.scope), data: entry.data, memberKey };
|
|
@@ -341,7 +364,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
341
364
|
buildAuthorizeUrl(params) {
|
|
342
365
|
const redirectUri = _nullishCoalesce(params.redirectUri, () => ( this.redirectUri));
|
|
343
366
|
if (!redirectUri) {
|
|
344
|
-
throw new (0,
|
|
367
|
+
throw new (0, _chunk33AQCUGMcjs.STXConfigException)("redirectUri is required to build an authorize URL.");
|
|
345
368
|
}
|
|
346
369
|
const url = new URL(joinUrl(this.baseUrl, this.endpoints.authorize));
|
|
347
370
|
const search = {
|
|
@@ -363,7 +386,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
363
386
|
exchangeCode(args) {
|
|
364
387
|
const redirectUri = _nullishCoalesce(args.redirectUri, () => ( this.redirectUri));
|
|
365
388
|
if (!redirectUri) {
|
|
366
|
-
throw new (0,
|
|
389
|
+
throw new (0, _chunk33AQCUGMcjs.STXConfigException)("redirectUri is required to exchange a code.");
|
|
367
390
|
}
|
|
368
391
|
return this.postToken(
|
|
369
392
|
new URLSearchParams({
|
|
@@ -404,7 +427,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
404
427
|
*/
|
|
405
428
|
clientCredentials(scope) {
|
|
406
429
|
if (this.isPublic) {
|
|
407
|
-
throw new (0,
|
|
430
|
+
throw new (0, _chunk33AQCUGMcjs.STXConfigException)(
|
|
408
431
|
"client_credentials needs a client secret; a public client cannot mint an app token."
|
|
409
432
|
);
|
|
410
433
|
}
|
|
@@ -428,7 +451,10 @@ var OAuthClient = (_class = 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);
|
|
@@ -508,7 +534,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
508
534
|
*/
|
|
509
535
|
memberClient(store, memberKey, opts = {}) {
|
|
510
536
|
const { session, ...rest } = opts;
|
|
511
|
-
return new (0,
|
|
537
|
+
return new (0, _chunk33AQCUGMcjs.STX)({
|
|
512
538
|
...rest,
|
|
513
539
|
host: this.baseUrl,
|
|
514
540
|
fetch: _nullishCoalesce(rest.fetch, () => ( this.fetch)),
|
|
@@ -521,7 +547,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
521
547
|
* market channels. Scope defaults to every app scope the client may hold.
|
|
522
548
|
*/
|
|
523
549
|
appClient(scope, opts = {}) {
|
|
524
|
-
return new (0,
|
|
550
|
+
return new (0, _chunk33AQCUGMcjs.STX)({ ...opts, host: this.baseUrl, fetch: _nullishCoalesce(opts.fetch, () => ( this.fetch)), auth: this.app(scope) });
|
|
525
551
|
}
|
|
526
552
|
/** @internal The in-flight refresh map for one store; see `OAuthSessionAuth`. */
|
|
527
553
|
_refreshesFor(store) {
|
|
@@ -533,10 +559,13 @@ var OAuthClient = (_class = 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,7 +590,17 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
561
590
|
const text = await res.text();
|
|
562
591
|
if (!res.ok) {
|
|
563
592
|
const err = rfcError(text);
|
|
564
|
-
if (
|
|
593
|
+
if (_optionalChain([err, 'optionalAccess', _13 => _13.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
|
+
}
|
|
603
|
+
if (res.status === 400 && _optionalChain([err, 'optionalAccess', _14 => _14.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
|
|
567
606
|
);
|
|
@@ -573,7 +612,7 @@ var OAuthClient = (_class = 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
|
}, _class);
|
|
@@ -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) {
|
|
@@ -645,7 +685,7 @@ var AppTokenProvider = (_class2 = class {
|
|
|
645
685
|
}
|
|
646
686
|
/** The effective scope the exchange granted the current token, if minted. */
|
|
647
687
|
get grantedScope() {
|
|
648
|
-
return _optionalChain([this, 'access',
|
|
688
|
+
return _optionalChain([this, 'access', _15 => _15.cached, 'optionalAccess', _16 => _16.scope]);
|
|
649
689
|
}
|
|
650
690
|
async mint() {
|
|
651
691
|
const set = await this.client.clientCredentials(this.scope);
|
|
@@ -697,7 +737,7 @@ var OAuthSessionAuth = (_class4 = class {
|
|
|
697
737
|
async tokens() {
|
|
698
738
|
let tokens = await this.load();
|
|
699
739
|
if (!tokens) {
|
|
700
|
-
throw new (0,
|
|
740
|
+
throw new (0, _chunk33AQCUGMcjs.STXConfigException)(`No tokens stored for member "${this.memberKey}". Complete the OAuth flow first.`);
|
|
701
741
|
}
|
|
702
742
|
if (tokens.refreshToken && tokens.expiresAt !== void 0 && tokens.expiresAt - Date.now() <= this.skewMs) {
|
|
703
743
|
const refreshed = await this.refresh(tokens.refreshToken);
|
|
@@ -707,7 +747,7 @@ var OAuthSessionAuth = (_class4 = class {
|
|
|
707
747
|
}
|
|
708
748
|
/** The granted scopes of the stored tokens, canonical names. */
|
|
709
749
|
async scopes() {
|
|
710
|
-
return parseScopes(await _asyncOptionalChain([(await this.load()), 'optionalAccess', async
|
|
750
|
+
return parseScopes(await _asyncOptionalChain([(await this.load()), 'optionalAccess', async _17 => _17.scope]));
|
|
711
751
|
}
|
|
712
752
|
async authHeaders(_request) {
|
|
713
753
|
const tokens = await this.tokens();
|
|
@@ -732,7 +772,9 @@ var OAuthSessionAuth = (_class4 = 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);
|
|
@@ -740,24 +782,25 @@ var OAuthSessionAuth = (_class4 = class {
|
|
|
740
782
|
if (existing) return existing;
|
|
741
783
|
const run = async () => {
|
|
742
784
|
const current = await this.load();
|
|
743
|
-
if (_optionalChain([current, 'optionalAccess',
|
|
785
|
+
if (_optionalChain([current, 'optionalAccess', _18 => _18.refreshToken]) && current.refreshToken !== refreshToken) return current;
|
|
744
786
|
try {
|
|
745
787
|
const set = await this.client.refreshToken(refreshToken);
|
|
746
788
|
const stored = {
|
|
747
789
|
accessToken: set.accessToken,
|
|
748
790
|
refreshToken: _nullishCoalesce(set.refreshToken, () => ( refreshToken)),
|
|
749
791
|
expiresAt: set.expiresAt,
|
|
750
|
-
scope: _nullishCoalesce(set.scope, () => ( _optionalChain([current, 'optionalAccess',
|
|
792
|
+
scope: _nullishCoalesce(set.scope, () => ( _optionalChain([current, 'optionalAccess', _19 => _19.scope])))
|
|
751
793
|
};
|
|
752
794
|
await this.store.set(this.memberKey, stored);
|
|
753
|
-
await _optionalChain([this, 'access',
|
|
795
|
+
await _optionalChain([this, 'access', _20 => _20.opts, 'access', _21 => _21.onRefresh, 'optionalCall', _22 => _22(stored)]);
|
|
754
796
|
return stored;
|
|
755
797
|
} catch (err) {
|
|
756
798
|
if (err instanceof STXGrantRevokedException) {
|
|
757
799
|
await this.store.delete(this.memberKey);
|
|
758
|
-
await _optionalChain([this, 'access',
|
|
800
|
+
await _optionalChain([this, 'access', _23 => _23.opts, 'access', _24 => _24.onGrantRevoked, 'optionalCall', _25 => _25(err)]);
|
|
759
801
|
throw err;
|
|
760
802
|
}
|
|
803
|
+
if (err instanceof STXAccountPendingException) throw err;
|
|
761
804
|
return null;
|
|
762
805
|
}
|
|
763
806
|
};
|
|
@@ -791,10 +834,13 @@ var OAuthAppAuth = (_class5 = class {
|
|
|
791
834
|
* just dropped.
|
|
792
835
|
*/
|
|
793
836
|
async websocketHeaders(context) {
|
|
794
|
-
const token = _optionalChain([context, 'optionalAccess',
|
|
837
|
+
const token = _optionalChain([context, 'optionalAccess', _26 => _26.reconnect]) === false ? await this.tokens.get() : await this.tokens.fresh();
|
|
795
838
|
return { "x-stx-oauth-token": token };
|
|
796
839
|
}
|
|
797
840
|
}, _class5);
|
|
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, _nullishCoalesce(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, _nullishCoalesce(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 (0, _chunk33AQCUGMcjs.STXConfigException)("issuer is required.");
|
|
891
|
+
if (!opts.clientId || !opts.clientSecret) throw new (0, _chunk33AQCUGMcjs.STXConfigException)("clientId and clientSecret are required.");
|
|
892
|
+
if (!opts.redirectUri) throw new (0, _chunk33AQCUGMcjs.STXConfigException)("redirectUri is required.");
|
|
893
|
+
const issuer = opts.issuer.replace(/\/+$/, "");
|
|
894
|
+
const fetchImpl = _nullishCoalesce(opts.fetch, () => ( globalThis.fetch));
|
|
895
|
+
if (typeof fetchImpl !== "function") {
|
|
896
|
+
throw new (0, _chunk33AQCUGMcjs.STXConfigException)("No fetch implementation available. Use Node 18+, or pass { fetch }.");
|
|
897
|
+
}
|
|
898
|
+
const skew = _nullishCoalesce(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 = _nullishCoalesce(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(_nullishCoalesce(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 || !_optionalChain([saved, 'optionalAccess', _27 => _27.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, _nullishCoalesce(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: _nullishCoalesce(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 (e6) {
|
|
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 (e7) {
|
|
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 (e8) {
|
|
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 = _nullishCoalesce(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 (e9) {
|
|
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);
|
|
@@ -874,12 +1208,12 @@ async function fetchWellKnown(baseUrl, path, opts) {
|
|
|
874
1208
|
if (!res.ok) throw httpError2(res.status, text, path);
|
|
875
1209
|
try {
|
|
876
1210
|
return JSON.parse(text);
|
|
877
|
-
} catch (
|
|
1211
|
+
} catch (e10) {
|
|
878
1212
|
throw httpError2(res.status, text, path);
|
|
879
1213
|
}
|
|
880
1214
|
}
|
|
881
1215
|
function httpError2(status, text, path) {
|
|
882
|
-
return new (0,
|
|
1216
|
+
return new (0, _chunk33AQCUGMcjs.STXAPIException)(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {
|
|
883
1217
|
statusCode: status,
|
|
884
1218
|
body: text,
|
|
885
1219
|
path
|
|
@@ -963,5 +1297,8 @@ var MemoryPendingAuthorizationStore = (_class7 = class {constructor() { _class7.
|
|
|
963
1297
|
|
|
964
1298
|
|
|
965
1299
|
|
|
966
|
-
|
|
1300
|
+
|
|
1301
|
+
|
|
1302
|
+
|
|
1303
|
+
exports.ALL_APP_SCOPES = ALL_APP_SCOPES; exports.ALL_MEMBER_SCOPES = ALL_MEMBER_SCOPES; exports.AppScopes = AppScopes; exports.AppTokenProvider = AppTokenProvider; exports.DEFAULT_ENDPOINTS = DEFAULT_ENDPOINTS; exports.LEGACY_SCOPES = LEGACY_SCOPES; exports.MemberScopes = MemberScopes; exports.MemoryPendingAuthorizationStore = MemoryPendingAuthorizationStore; exports.MemoryTokenStore = MemoryTokenStore; exports.OAuthAppAuth = OAuthAppAuth; exports.OAuthBearerAuth = OAuthBearerAuth; exports.OAuthClient = OAuthClient; exports.OAuthSessionAuth = OAuthSessionAuth; exports.STXAccessDeniedException = STXAccessDeniedException; exports.STXAccountPendingException = STXAccountPendingException; exports.STXAuthenticationException = _chunk33AQCUGMcjs.STXAuthenticationException; exports.STXForbiddenException = _chunk33AQCUGMcjs.STXForbiddenException; exports.STXGrantRevokedException = STXGrantRevokedException; exports.STXInsufficientScopeException = _chunk33AQCUGMcjs.STXInsufficientScopeException; exports.STXInvalidTokenException = _chunk33AQCUGMcjs.STXInvalidTokenException; exports.STXOAuthException = STXOAuthException; exports.Scopes = Scopes; exports.WELL_KNOWN = WELL_KNOWN; exports.base64url = base64url; exports.canonicalScope = canonicalScope; exports.codeChallengeS256 = codeChallengeS256; exports.createConnect = createConnect; exports.createPkce = createPkce; exports.discoverMetadata = discoverMetadata; exports.discoverProtectedResource = discoverProtectedResource; exports.formatScopes = formatScopes; exports.generateCodeVerifier = generateCodeVerifier; exports.generateState = generateState; exports.isAppScope = isAppScope; exports.isMemberScope = isMemberScope; exports.joinUrl = joinUrl; exports.parseScopes = parseScopes; exports.parseTokenResponse = parseTokenResponse; exports.readCallback = readCallback; exports.registerClient = registerClient; exports.rfcError = rfcError; exports.tokenSetToStored = tokenSetToStored;
|
|
967
1304
|
//# sourceMappingURL=oauth.cjs.map
|