@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.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 _chunkL2DEU7R6cjs.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 _chunkL2DEU7R6cjs.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
|
|
@@ -277,7 +294,11 @@ var OAuthClient = (_class = 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
|
+
..._nullishCoalesce(params.extraParams, () => ( {}))
|
|
301
|
+
}
|
|
281
302
|
});
|
|
282
303
|
return { url, state, codeVerifier: pkce.codeVerifier, codeChallenge: pkce.codeChallenge };
|
|
283
304
|
}
|
|
@@ -292,7 +313,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
292
313
|
*/
|
|
293
314
|
async beginAuthorization(pending, params = {}) {
|
|
294
315
|
const redirectUri = _nullishCoalesce(params.redirectUri, () => ( this.redirectUri));
|
|
295
|
-
if (!redirectUri) throw new (0,
|
|
316
|
+
if (!redirectUri) throw new (0, _chunk33AQCUGMcjs.STXConfigException)("redirectUri is required to build an authorize URL.");
|
|
296
317
|
const auth = await this.authorizationUrl({ ...params, redirectUri });
|
|
297
318
|
await pending.put(auth.state, {
|
|
298
319
|
codeVerifier: auth.codeVerifier,
|
|
@@ -305,7 +326,7 @@ var OAuthClient = (_class = 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
|
|
@@ -334,7 +355,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
334
355
|
let memberKey;
|
|
335
356
|
if (opts.store) {
|
|
336
357
|
memberKey = typeof opts.memberKey === "function" ? opts.memberKey(entry.data) : opts.memberKey;
|
|
337
|
-
if (!memberKey) throw new (0,
|
|
358
|
+
if (!memberKey) throw new (0, _chunk33AQCUGMcjs.STXConfigException)("Pass memberKey along with store.");
|
|
338
359
|
await opts.store.set(memberKey, tokenSetToStored(tokens));
|
|
339
360
|
}
|
|
340
361
|
return { tokens, scopes: parseScopes(tokens.scope), data: entry.data, memberKey };
|
|
@@ -343,7 +364,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
343
364
|
buildAuthorizeUrl(params) {
|
|
344
365
|
const redirectUri = _nullishCoalesce(params.redirectUri, () => ( this.redirectUri));
|
|
345
366
|
if (!redirectUri) {
|
|
346
|
-
throw new (0,
|
|
367
|
+
throw new (0, _chunk33AQCUGMcjs.STXConfigException)("redirectUri is required to build an authorize URL.");
|
|
347
368
|
}
|
|
348
369
|
const url = new URL(joinUrl(this.baseUrl, this.endpoints.authorize));
|
|
349
370
|
const search = {
|
|
@@ -365,7 +386,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
365
386
|
exchangeCode(args) {
|
|
366
387
|
const redirectUri = _nullishCoalesce(args.redirectUri, () => ( this.redirectUri));
|
|
367
388
|
if (!redirectUri) {
|
|
368
|
-
throw new (0,
|
|
389
|
+
throw new (0, _chunk33AQCUGMcjs.STXConfigException)("redirectUri is required to exchange a code.");
|
|
369
390
|
}
|
|
370
391
|
return this.postToken(
|
|
371
392
|
new URLSearchParams({
|
|
@@ -406,7 +427,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
406
427
|
*/
|
|
407
428
|
clientCredentials(scope) {
|
|
408
429
|
if (this.isPublic) {
|
|
409
|
-
throw new (0,
|
|
430
|
+
throw new (0, _chunk33AQCUGMcjs.STXConfigException)(
|
|
410
431
|
"client_credentials needs a client secret; a public client cannot mint an app token."
|
|
411
432
|
);
|
|
412
433
|
}
|
|
@@ -430,7 +451,10 @@ var OAuthClient = (_class = 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);
|
|
@@ -510,7 +534,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
510
534
|
*/
|
|
511
535
|
memberClient(store, memberKey, opts = {}) {
|
|
512
536
|
const { session, ...rest } = opts;
|
|
513
|
-
return new (0,
|
|
537
|
+
return new (0, _chunk33AQCUGMcjs.STX)({
|
|
514
538
|
...rest,
|
|
515
539
|
host: this.baseUrl,
|
|
516
540
|
fetch: _nullishCoalesce(rest.fetch, () => ( this.fetch)),
|
|
@@ -523,7 +547,7 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
523
547
|
* market channels. Scope defaults to every app scope the client may hold.
|
|
524
548
|
*/
|
|
525
549
|
appClient(scope, opts = {}) {
|
|
526
|
-
return new (0,
|
|
550
|
+
return new (0, _chunk33AQCUGMcjs.STX)({ ...opts, host: this.baseUrl, fetch: _nullishCoalesce(opts.fetch, () => ( this.fetch)), auth: this.app(scope) });
|
|
527
551
|
}
|
|
528
552
|
/** @internal The in-flight refresh map for one store; see `OAuthSessionAuth`. */
|
|
529
553
|
_refreshesFor(store) {
|
|
@@ -535,10 +559,13 @@ var OAuthClient = (_class = 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,7 +590,17 @@ var OAuthClient = (_class = class _OAuthClient {
|
|
|
563
590
|
const text = await res.text();
|
|
564
591
|
if (!res.ok) {
|
|
565
592
|
const err = rfcError(text);
|
|
566
|
-
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") {
|
|
567
604
|
throw new STXGrantRevokedException(
|
|
568
605
|
err.error_description ? `OAuth grant revoked: ${err.error_description}. The member must re-authorize.` : void 0
|
|
569
606
|
);
|
|
@@ -575,7 +612,7 @@ var OAuthClient = (_class = 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
|
}, _class);
|
|
@@ -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) {
|
|
@@ -647,7 +685,7 @@ var AppTokenProvider = (_class2 = class {
|
|
|
647
685
|
}
|
|
648
686
|
/** The effective scope the exchange granted the current token, if minted. */
|
|
649
687
|
get grantedScope() {
|
|
650
|
-
return _optionalChain([this, 'access',
|
|
688
|
+
return _optionalChain([this, 'access', _15 => _15.cached, 'optionalAccess', _16 => _16.scope]);
|
|
651
689
|
}
|
|
652
690
|
async mint() {
|
|
653
691
|
const set = await this.client.clientCredentials(this.scope);
|
|
@@ -699,7 +737,7 @@ var OAuthSessionAuth = (_class4 = class {
|
|
|
699
737
|
async tokens() {
|
|
700
738
|
let tokens = await this.load();
|
|
701
739
|
if (!tokens) {
|
|
702
|
-
throw new (0,
|
|
740
|
+
throw new (0, _chunk33AQCUGMcjs.STXConfigException)(`No tokens stored for member "${this.memberKey}". Complete the OAuth flow first.`);
|
|
703
741
|
}
|
|
704
742
|
if (tokens.refreshToken && tokens.expiresAt !== void 0 && tokens.expiresAt - Date.now() <= this.skewMs) {
|
|
705
743
|
const refreshed = await this.refresh(tokens.refreshToken);
|
|
@@ -709,7 +747,7 @@ var OAuthSessionAuth = (_class4 = class {
|
|
|
709
747
|
}
|
|
710
748
|
/** The granted scopes of the stored tokens, canonical names. */
|
|
711
749
|
async scopes() {
|
|
712
|
-
return parseScopes(await _asyncOptionalChain([(await this.load()), 'optionalAccess', async
|
|
750
|
+
return parseScopes(await _asyncOptionalChain([(await this.load()), 'optionalAccess', async _17 => _17.scope]));
|
|
713
751
|
}
|
|
714
752
|
async authHeaders(_request) {
|
|
715
753
|
const tokens = await this.tokens();
|
|
@@ -734,7 +772,9 @@ var OAuthSessionAuth = (_class4 = 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);
|
|
@@ -742,24 +782,25 @@ var OAuthSessionAuth = (_class4 = class {
|
|
|
742
782
|
if (existing) return existing;
|
|
743
783
|
const run = async () => {
|
|
744
784
|
const current = await this.load();
|
|
745
|
-
if (_optionalChain([current, 'optionalAccess',
|
|
785
|
+
if (_optionalChain([current, 'optionalAccess', _18 => _18.refreshToken]) && current.refreshToken !== refreshToken) return current;
|
|
746
786
|
try {
|
|
747
787
|
const set = await this.client.refreshToken(refreshToken);
|
|
748
788
|
const stored = {
|
|
749
789
|
accessToken: set.accessToken,
|
|
750
790
|
refreshToken: _nullishCoalesce(set.refreshToken, () => ( refreshToken)),
|
|
751
791
|
expiresAt: set.expiresAt,
|
|
752
|
-
scope: _nullishCoalesce(set.scope, () => ( _optionalChain([current, 'optionalAccess',
|
|
792
|
+
scope: _nullishCoalesce(set.scope, () => ( _optionalChain([current, 'optionalAccess', _19 => _19.scope])))
|
|
753
793
|
};
|
|
754
794
|
await this.store.set(this.memberKey, stored);
|
|
755
|
-
await _optionalChain([this, 'access',
|
|
795
|
+
await _optionalChain([this, 'access', _20 => _20.opts, 'access', _21 => _21.onRefresh, 'optionalCall', _22 => _22(stored)]);
|
|
756
796
|
return stored;
|
|
757
797
|
} catch (err) {
|
|
758
798
|
if (err instanceof STXGrantRevokedException) {
|
|
759
799
|
await this.store.delete(this.memberKey);
|
|
760
|
-
await _optionalChain([this, 'access',
|
|
800
|
+
await _optionalChain([this, 'access', _23 => _23.opts, 'access', _24 => _24.onGrantRevoked, 'optionalCall', _25 => _25(err)]);
|
|
761
801
|
throw err;
|
|
762
802
|
}
|
|
803
|
+
if (err instanceof STXAccountPendingException) throw err;
|
|
763
804
|
return null;
|
|
764
805
|
}
|
|
765
806
|
};
|
|
@@ -793,10 +834,13 @@ var OAuthAppAuth = (_class5 = class {
|
|
|
793
834
|
* just dropped.
|
|
794
835
|
*/
|
|
795
836
|
async websocketHeaders(context) {
|
|
796
|
-
const token = _optionalChain([context, 'optionalAccess',
|
|
837
|
+
const token = _optionalChain([context, 'optionalAccess', _26 => _26.reconnect]) === false ? await this.tokens.get() : await this.tokens.fresh();
|
|
797
838
|
return { "x-stx-oauth-token": token };
|
|
798
839
|
}
|
|
799
840
|
}, _class5);
|
|
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, _nullishCoalesce(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, _nullishCoalesce(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 (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
|
+
|
|
844
1176
|
// src/oauth/metadata.ts
|
|
845
1177
|
async function discoverMetadata(baseUrl, opts = {}) {
|
|
846
1178
|
const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.authorizationServer, opts);
|
|
@@ -876,12 +1208,12 @@ async function fetchWellKnown(baseUrl, path, opts) {
|
|
|
876
1208
|
if (!res.ok) throw httpError2(res.status, text, path);
|
|
877
1209
|
try {
|
|
878
1210
|
return JSON.parse(text);
|
|
879
|
-
} catch (
|
|
1211
|
+
} catch (e10) {
|
|
880
1212
|
throw httpError2(res.status, text, path);
|
|
881
1213
|
}
|
|
882
1214
|
}
|
|
883
1215
|
function httpError2(status, text, path) {
|
|
884
|
-
return new (0,
|
|
1216
|
+
return new (0, _chunk33AQCUGMcjs.STXAPIException)(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {
|
|
885
1217
|
statusCode: status,
|
|
886
1218
|
body: text,
|
|
887
1219
|
path
|
|
@@ -965,5 +1297,8 @@ var MemoryPendingAuthorizationStore = (_class7 = class {constructor() { _class7.
|
|
|
965
1297
|
|
|
966
1298
|
|
|
967
1299
|
|
|
968
|
-
|
|
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;
|
|
969
1304
|
//# sourceMappingURL=oauth.cjs.map
|