@stxapp/stx-typescript 0.6.0

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/dist/oauth.js ADDED
@@ -0,0 +1,967 @@
1
+ import {
2
+ STX,
3
+ STXAPIException,
4
+ STXAuthenticationException,
5
+ STXConfigException,
6
+ STXForbiddenException,
7
+ STXInsufficientScopeException,
8
+ STXInvalidTokenException,
9
+ baseUrlFor
10
+ } from "./chunk-U3KT3I43.js";
11
+
12
+ // src/oauth/endpoints.ts
13
+ var DEFAULT_ENDPOINTS = {
14
+ authorize: "/oauth/authorize",
15
+ token: "/oauth/token",
16
+ revoke: "/oauth/revoke",
17
+ introspect: "/oauth/introspect",
18
+ register: "/oauth/register"
19
+ };
20
+ var WELL_KNOWN = {
21
+ authorizationServer: "/.well-known/oauth-authorization-server",
22
+ protectedResource: "/.well-known/oauth-protected-resource"
23
+ };
24
+ function resolveOAuthConfig(input) {
25
+ const env = globalThis.process?.env ?? {};
26
+ const host = input.baseUrl ?? env.STX_HOST ?? env.STX_BASE_URL;
27
+ if (!host) throw new STXConfigException("An OAuth base URL is required. Pass { baseUrl } or set STX_HOST.");
28
+ const fetchImpl = input.fetch ?? globalThis.fetch;
29
+ if (typeof fetchImpl !== "function") {
30
+ throw new STXConfigException("No fetch implementation available. Use Node 18+, or pass { fetch }.");
31
+ }
32
+ return { baseUrl: baseUrlFor(null, null, host), fetch: fetchImpl };
33
+ }
34
+ function joinUrl(baseUrl, path) {
35
+ if (/^https?:\/\//i.test(path)) return path;
36
+ return baseUrl + (path.startsWith("/") ? path : "/" + path);
37
+ }
38
+
39
+ // src/oauth/errors.ts
40
+ var STXOAuthException = class extends STXAuthenticationException {
41
+ /** The RFC error code: `invalid_client`, `invalid_grant`, `invalid_scope`, ... */
42
+ error;
43
+ errorDescription;
44
+ /** The endpoint path that answered. */
45
+ endpoint;
46
+ /** Seconds to wait when the endpoint answered 429 with Retry-After. */
47
+ retryAfter;
48
+ constructor(error, errorDescription, status, endpoint, retryAfter) {
49
+ super(`OAuth ${endpoint} ${status} ${error}${errorDescription ? `: ${errorDescription}` : ""}`, {
50
+ statusCode: status,
51
+ path: endpoint
52
+ });
53
+ this.error = error;
54
+ this.errorDescription = errorDescription;
55
+ this.endpoint = endpoint;
56
+ this.retryAfter = retryAfter;
57
+ }
58
+ };
59
+ var STXGrantRevokedException = class extends STXAuthenticationException {
60
+ constructor(message = "OAuth grant revoked: the member must re-authorize.") {
61
+ super(message, { statusCode: 400 });
62
+ }
63
+ };
64
+
65
+ // src/oauth/pkce.ts
66
+ function base64url(bytes) {
67
+ let bin = "";
68
+ for (const b of bytes) bin += String.fromCharCode(b);
69
+ const b64 = btoa(bin);
70
+ return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
71
+ }
72
+ function randomBytes(n) {
73
+ const buf = new Uint8Array(n);
74
+ crypto.getRandomValues(buf);
75
+ return buf;
76
+ }
77
+ function generateCodeVerifier() {
78
+ return base64url(randomBytes(32));
79
+ }
80
+ async function codeChallengeS256(verifier) {
81
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
82
+ return base64url(new Uint8Array(digest));
83
+ }
84
+ function generateState() {
85
+ return base64url(randomBytes(24));
86
+ }
87
+ async function createPkce() {
88
+ const codeVerifier = generateCodeVerifier();
89
+ const codeChallenge = await codeChallengeS256(codeVerifier);
90
+ return { codeVerifier, codeChallenge };
91
+ }
92
+
93
+ // src/oauth/register.ts
94
+ async function registerClient(request, opts = {}) {
95
+ const cfg = resolveOAuthConfig({ baseUrl: opts.baseUrl, fetch: opts.fetch });
96
+ const endpoint = opts.registrationEndpoint ?? DEFAULT_ENDPOINTS.register;
97
+ const url = joinUrl(cfg.baseUrl, endpoint);
98
+ const path = new URL(url).pathname;
99
+ const res = await cfg.fetch(url, {
100
+ method: "POST",
101
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
102
+ body: JSON.stringify(request)
103
+ });
104
+ const text = await res.text();
105
+ if (res.status === 201 || res.status === 200) {
106
+ let doc;
107
+ try {
108
+ doc = JSON.parse(text);
109
+ } catch {
110
+ throw httpError(res.status, text, path);
111
+ }
112
+ const reg = doc;
113
+ if (typeof reg.client_id !== "string" || reg.client_id === "") {
114
+ throw httpError(res.status, text, path + " (missing client_id)");
115
+ }
116
+ return reg;
117
+ }
118
+ const err = rfcError(text);
119
+ if (err) {
120
+ const retryAfter = Number(res.headers.get("retry-after"));
121
+ throw new STXOAuthException(
122
+ err.error,
123
+ err.error_description,
124
+ res.status,
125
+ path,
126
+ Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : void 0
127
+ );
128
+ }
129
+ throw httpError(res.status, text, path);
130
+ }
131
+ function rfcError(text) {
132
+ try {
133
+ const obj = JSON.parse(text);
134
+ if (typeof obj.error !== "string") return null;
135
+ return {
136
+ error: obj.error,
137
+ error_description: typeof obj.error_description === "string" ? obj.error_description : void 0
138
+ };
139
+ } catch {
140
+ return null;
141
+ }
142
+ }
143
+ function httpError(status, text, path) {
144
+ return new STXAPIException(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {
145
+ statusCode: status,
146
+ body: text,
147
+ path
148
+ });
149
+ }
150
+
151
+ // src/oauth/scopes.ts
152
+ var MemberScopes = {
153
+ /** Who the member is: `me`, `GET /api/v1/me`. */
154
+ PROFILE_READ: "profile.read",
155
+ /** Cash balance: `account`, `GET /api/v1/account/balance`, `balances:` channel. */
156
+ BALANCE_READ: "balance.read",
157
+ /** Positions, settlements, loyalty/fee/adjustment ledgers, `positions:`/`settlements:`. */
158
+ PORTFOLIO_READ: "portfolio.read",
159
+ /** Order and fill history, `orders:`/`fills:` channels. */
160
+ ORDERS_READ: "orders.read",
161
+ /** Deposit and withdrawal history (read only). */
162
+ TRANSFERS_READ: "transfers.read",
163
+ /** Place and cancel orders; arm `cancel_on_disconnect`. */
164
+ ORDERS_WRITE: "orders.write",
165
+ /** Accept the terms and conditions. */
166
+ TERMS_WRITE: "terms.write"
167
+ };
168
+ var AppScopes = {
169
+ /** Public market catalog (`GET /api/v1/markets`) and the public market feeds. */
170
+ MARKET_DATA: "market_data",
171
+ /** Public event catalog (`GET /api/v1/events`) and the `events` feed. */
172
+ EVENTS: "events"
173
+ };
174
+ var Scopes = { ...MemberScopes, ...AppScopes };
175
+ var ALL_MEMBER_SCOPES = Object.values(MemberScopes);
176
+ var ALL_APP_SCOPES = Object.values(AppScopes);
177
+ var LEGACY_SCOPES = {
178
+ identity: MemberScopes.PROFILE_READ,
179
+ balance: MemberScopes.BALANCE_READ,
180
+ portfolio: MemberScopes.PORTFOLIO_READ,
181
+ history: MemberScopes.ORDERS_READ,
182
+ transfers: MemberScopes.TRANSFERS_READ,
183
+ trade: MemberScopes.ORDERS_WRITE,
184
+ onboarding: MemberScopes.TERMS_WRITE
185
+ };
186
+ function canonicalScope(scope) {
187
+ return LEGACY_SCOPES[scope] ?? scope;
188
+ }
189
+ function parseScopes(scope) {
190
+ if (!scope) return [];
191
+ const out = [];
192
+ for (const raw of scope.split(/\s+/)) {
193
+ if (!raw) continue;
194
+ const s = canonicalScope(raw);
195
+ if (!out.includes(s)) out.push(s);
196
+ }
197
+ return out;
198
+ }
199
+ function formatScopes(scopes) {
200
+ return scopes.join(" ");
201
+ }
202
+ function isMemberScope(scope) {
203
+ return ALL_MEMBER_SCOPES.includes(scope);
204
+ }
205
+ function isAppScope(scope) {
206
+ return ALL_APP_SCOPES.includes(scope);
207
+ }
208
+
209
+ // src/oauth/client.ts
210
+ var OAuthClient = class _OAuthClient {
211
+ baseUrl;
212
+ clientId;
213
+ clientSecret;
214
+ redirectUri;
215
+ scope;
216
+ endpoints;
217
+ fetch;
218
+ /**
219
+ * In-flight refreshes per token store and member, shared by every session
220
+ * adapter this client makes, so a burst of 401s across requests refreshes
221
+ * once. Two refreshes of one rotating token would trip reuse detection and
222
+ * revoke the grant.
223
+ */
224
+ refreshes = /* @__PURE__ */ new WeakMap();
225
+ /** One cached app token per requested scope. */
226
+ appTokens = /* @__PURE__ */ new Map();
227
+ constructor(opts) {
228
+ const cfg = resolveOAuthConfig({ baseUrl: opts.baseUrl, fetch: opts.fetch });
229
+ this.baseUrl = cfg.baseUrl;
230
+ this.fetch = cfg.fetch;
231
+ this.clientId = opts.clientId;
232
+ this.clientSecret = opts.clientSecret || void 0;
233
+ this.redirectUri = opts.redirectUri;
234
+ this.scope = normalizeScope(opts.scope);
235
+ this.endpoints = {
236
+ authorize: opts.endpoints?.authorize ?? DEFAULT_ENDPOINTS.authorize,
237
+ token: opts.endpoints?.token ?? DEFAULT_ENDPOINTS.token,
238
+ revoke: opts.endpoints?.revoke ?? DEFAULT_ENDPOINTS.revoke,
239
+ introspect: opts.endpoints?.introspect ?? DEFAULT_ENDPOINTS.introspect
240
+ };
241
+ }
242
+ /**
243
+ * Build a client from a discovered RFC 8414 document, so every endpoint is the
244
+ * one the exchange advertised on the host you asked. The base URL is the
245
+ * issuer unless overridden.
246
+ */
247
+ static fromMetadata(metadata, opts) {
248
+ return new _OAuthClient({
249
+ ...opts,
250
+ baseUrl: opts.baseUrl ?? metadata.issuer,
251
+ endpoints: {
252
+ authorize: metadata.authorization_endpoint,
253
+ token: metadata.token_endpoint,
254
+ ...metadata.revocation_endpoint ? { revoke: metadata.revocation_endpoint } : {},
255
+ ...metadata.introspection_endpoint ? { introspect: metadata.introspection_endpoint } : {}
256
+ }
257
+ });
258
+ }
259
+ /** True for a public client (no secret): PKCE-only, no app tokens. */
260
+ get isPublic() {
261
+ return this.clientSecret === void 0;
262
+ }
263
+ // ---- Step 1+2: prepare the authorize redirect ---------------------------
264
+ /**
265
+ * Create a fresh PKCE pair (S256) + `state` and build the authorize URL in
266
+ * one call. Persist `state` and `codeVerifier` against the member's pending
267
+ * sign-in and verify `state` on the callback.
268
+ */
269
+ async authorizationUrl(params = {}) {
270
+ const pkce = await createPkce();
271
+ const state = params.state ?? generateState();
272
+ const url = this.buildAuthorizeUrl({
273
+ state,
274
+ codeChallenge: pkce.codeChallenge,
275
+ scope: params.scope,
276
+ prompt: params.prompt,
277
+ redirectUri: params.redirectUri,
278
+ extraParams: params.extraParams
279
+ });
280
+ return { url, state, codeVerifier: pkce.codeVerifier, codeChallenge: pkce.codeChallenge };
281
+ }
282
+ /** Alias of `authorizationUrl()` kept from 0.1. */
283
+ createAuthorization(params = {}) {
284
+ return this.authorizationUrl(params);
285
+ }
286
+ /**
287
+ * Start a sign-in: create PKCE + state, remember them (and `data`) in
288
+ * `pending` under the state, and return the authorize URL to redirect to.
289
+ * Finish with `completeAuthorization()` on the callback.
290
+ */
291
+ async beginAuthorization(pending, params = {}) {
292
+ const redirectUri = params.redirectUri ?? this.redirectUri;
293
+ if (!redirectUri) throw new STXConfigException("redirectUri is required to build an authorize URL.");
294
+ const auth = await this.authorizationUrl({ ...params, redirectUri });
295
+ await pending.put(auth.state, {
296
+ codeVerifier: auth.codeVerifier,
297
+ redirectUri,
298
+ scope: normalizeScope(params.scope) ?? this.scope,
299
+ expiresAt: Date.now() + (params.ttlMs ?? 10 * 6e4),
300
+ data: params.data
301
+ });
302
+ return auth;
303
+ }
304
+ /**
305
+ * Finish a sign-in from the callback's query. Checks for an `error` from
306
+ * the exchange (the member denied consent: `access_denied`), consumes the
307
+ * `state` (single use; unknown or expired throws `invalid_state`), exchanges
308
+ * the code with the stored PKCE verifier and, when `store` is given, saves
309
+ * the tokens under `memberKey` (a string, or a function of the `data` passed
310
+ * to `beginAuthorization()`).
311
+ *
312
+ * Every failure is an `STXOAuthException` whose `error` says which:
313
+ * `access_denied` and friends from the redirect, `invalid_request` (no code
314
+ * or state), `invalid_state`, or the token endpoint's own (`invalid_grant`
315
+ * for a used, expired or mismatched code).
316
+ */
317
+ async completeAuthorization(pending, callback, opts = {}) {
318
+ return this.redeemAuthorization(await readCallback(pending, callback, this.endpoints.authorize), opts);
319
+ }
320
+ /**
321
+ * The second half of `completeAuthorization()`: exchange a callback already
322
+ * read with `readCallback()`. Use the pair when one callback URL serves
323
+ * several apps and the app is only known from the pending entry's `data`.
324
+ */
325
+ async redeemAuthorization(callback, opts = {}) {
326
+ const entry = callback.pending;
327
+ const tokens = await this.exchangeCode({
328
+ code: callback.code,
329
+ codeVerifier: entry.codeVerifier,
330
+ redirectUri: entry.redirectUri
331
+ });
332
+ let memberKey;
333
+ if (opts.store) {
334
+ memberKey = typeof opts.memberKey === "function" ? opts.memberKey(entry.data) : opts.memberKey;
335
+ if (!memberKey) throw new STXConfigException("Pass memberKey along with store.");
336
+ await opts.store.set(memberKey, tokenSetToStored(tokens));
337
+ }
338
+ return { tokens, scopes: parseScopes(tokens.scope), data: entry.data, memberKey };
339
+ }
340
+ /** Build the authorize URL from a challenge you already have. */
341
+ buildAuthorizeUrl(params) {
342
+ const redirectUri = params.redirectUri ?? this.redirectUri;
343
+ if (!redirectUri) {
344
+ throw new STXConfigException("redirectUri is required to build an authorize URL.");
345
+ }
346
+ const url = new URL(joinUrl(this.baseUrl, this.endpoints.authorize));
347
+ const search = {
348
+ response_type: "code",
349
+ client_id: this.clientId,
350
+ redirect_uri: redirectUri,
351
+ scope: normalizeScope(params.scope) ?? this.scope ?? "",
352
+ code_challenge: params.codeChallenge,
353
+ code_challenge_method: "S256",
354
+ state: params.state,
355
+ ...params.prompt ? { prompt: params.prompt } : {},
356
+ ...params.extraParams ?? {}
357
+ };
358
+ url.search = new URLSearchParams(search).toString();
359
+ return url.toString();
360
+ }
361
+ // ---- Step 4: exchange the code ------------------------------------------
362
+ /** Exchange an authorization code for tokens, proving PKCE with the verifier. */
363
+ exchangeCode(args) {
364
+ const redirectUri = args.redirectUri ?? this.redirectUri;
365
+ if (!redirectUri) {
366
+ throw new STXConfigException("redirectUri is required to exchange a code.");
367
+ }
368
+ return this.postToken(
369
+ new URLSearchParams({
370
+ grant_type: "authorization_code",
371
+ code: args.code,
372
+ redirect_uri: redirectUri,
373
+ code_verifier: args.codeVerifier
374
+ })
375
+ );
376
+ }
377
+ // ---- Refresh (with rotation) --------------------------------------------
378
+ /**
379
+ * Trade a refresh token for a fresh access/refresh pair. STX ROTATES the
380
+ * refresh token, so the caller MUST persist whatever comes back. A rejected
381
+ * refresh (`invalid_grant`) means the grant was revoked, including STX's
382
+ * reuse detection tripping on a replayed/retired token, and surfaces as
383
+ * `STXGrantRevokedException`.
384
+ */
385
+ refreshToken(refreshToken) {
386
+ return this.postToken(
387
+ new URLSearchParams({
388
+ grant_type: "refresh_token",
389
+ refresh_token: refreshToken
390
+ })
391
+ );
392
+ }
393
+ /** Alias of `refreshToken()` kept from 0.1. */
394
+ refresh(refreshToken) {
395
+ return this.refreshToken(refreshToken);
396
+ }
397
+ // ---- client_credentials (app tokens) ------------------------------------
398
+ /**
399
+ * Mint an APP token (RFC 6749 section 4.4): the client acting as itself, no
400
+ * member, no consent, no refresh token. Scoped to app scopes only
401
+ * (`market_data`, `events`); omit `scope` for every app scope the client is
402
+ * allowed. Requires a confidential client. For a cached, self-renewing
403
+ * token use `appToken()`.
404
+ */
405
+ clientCredentials(scope) {
406
+ if (this.isPublic) {
407
+ throw new STXConfigException(
408
+ "client_credentials needs a client secret; a public client cannot mint an app token."
409
+ );
410
+ }
411
+ const body = new URLSearchParams({ grant_type: "client_credentials" });
412
+ const s = normalizeScope(scope);
413
+ if (s) body.set("scope", s);
414
+ return this.postToken(body);
415
+ }
416
+ /**
417
+ * A cached `client_credentials` token that re-mints itself before expiry.
418
+ * The same scope returns the same provider, so every REST client and socket
419
+ * built from this OAuth client shares one token.
420
+ */
421
+ appToken(scope) {
422
+ const key = normalizeScope(scope) ?? "";
423
+ let provider = this.appTokens.get(key);
424
+ if (!provider) {
425
+ provider = new AppTokenProvider(this, scope);
426
+ this.appTokens.set(key, provider);
427
+ }
428
+ return provider;
429
+ }
430
+ // ---- Revoke (RFC 7009) --------------------------------------------------
431
+ /** Revoke a token (either kind kills the pair). Always resolves on a 200. */
432
+ async revoke(token, tokenTypeHint) {
433
+ const body = new URLSearchParams({ token });
434
+ if (tokenTypeHint) body.set("token_type_hint", tokenTypeHint);
435
+ const res = await this.fetch(joinUrl(this.baseUrl, this.endpoints.revoke), {
436
+ method: "POST",
437
+ headers: this.formHeaders(),
438
+ body: this.withClientId(body).toString()
439
+ });
440
+ if (!res.ok) {
441
+ const text = await res.text().catch(() => "");
442
+ throw this.oauthError(res.status, text, this.endpoints.revoke);
443
+ }
444
+ }
445
+ /**
446
+ * Unlink a member: revoke their grant at the exchange (best effort) and
447
+ * delete their tokens from `store`. Resolves true if the exchange confirmed
448
+ * the revoke, false if it could not be reached or refused; the local tokens
449
+ * are deleted either way.
450
+ */
451
+ async unlink(store, memberKey) {
452
+ const tokens = await store.get(memberKey);
453
+ let revoked = false;
454
+ try {
455
+ if (tokens?.refreshToken) {
456
+ await this.revoke(tokens.refreshToken, "refresh_token");
457
+ revoked = true;
458
+ } else if (tokens?.accessToken) {
459
+ await this.revoke(tokens.accessToken, "access_token");
460
+ revoked = true;
461
+ }
462
+ } catch {
463
+ revoked = false;
464
+ } finally {
465
+ await store.delete(memberKey);
466
+ }
467
+ return revoked;
468
+ }
469
+ // ---- Introspect (RFC 7662) ----------------------------------------------
470
+ /** Report a token's active state + scope. Confidential clients only. */
471
+ async introspect(token) {
472
+ const res = await this.fetch(joinUrl(this.baseUrl, this.endpoints.introspect), {
473
+ method: "POST",
474
+ headers: this.formHeaders(),
475
+ body: new URLSearchParams({ token }).toString()
476
+ });
477
+ const text = await res.text();
478
+ if (!res.ok) throw this.oauthError(res.status, text, this.endpoints.introspect);
479
+ return parseJsonBody(text, res.status, this.endpoints.introspect);
480
+ }
481
+ // ---- Adapter factories --------------------------------------------------
482
+ /** A simple Bearer adapter around a known access token (no refresh). */
483
+ bearer(accessToken) {
484
+ return new OAuthBearerAuth(accessToken);
485
+ }
486
+ /**
487
+ * A store-backed adapter that reads the member's tokens, attaches the Bearer
488
+ * header, refreshes proactively / on 401 with rotation, and clears the store
489
+ * (throwing `STXGrantRevokedException`) if the grant was revoked.
490
+ */
491
+ session(store, memberKey, opts = {}) {
492
+ return new OAuthSessionAuth(this, store, memberKey, opts);
493
+ }
494
+ /**
495
+ * An adapter authenticated as the APP (client_credentials): the public
496
+ * catalog over REST and the public market feeds over the socket. Re-mints
497
+ * before expiry, once on a 401, and fresh on every socket (re)connect.
498
+ */
499
+ app(scope) {
500
+ return new OAuthAppAuth(this.appToken(scope));
501
+ }
502
+ /**
503
+ * An `STX` REST client acting for one member, over `session(store,
504
+ * memberKey)`: every `/api/v1` method (balance, positions, fills, orders,
505
+ * place and cancel) with the Bearer token attached, refreshed before expiry
506
+ * and on a 401, and `client.websocket()` for the member's channels over the
507
+ * `x-stx-oauth-token` handshake.
508
+ */
509
+ memberClient(store, memberKey, opts = {}) {
510
+ const { session, ...rest } = opts;
511
+ return new STX({
512
+ ...rest,
513
+ host: this.baseUrl,
514
+ fetch: rest.fetch ?? this.fetch,
515
+ auth: this.session(store, memberKey, session)
516
+ });
517
+ }
518
+ /**
519
+ * An `STX` REST client acting as the app (client_credentials): the public
520
+ * catalog (`markets()`, `events()`) and, through `websocket()`, the public
521
+ * market channels. Scope defaults to every app scope the client may hold.
522
+ */
523
+ appClient(scope, opts = {}) {
524
+ return new STX({ ...opts, host: this.baseUrl, fetch: opts.fetch ?? this.fetch, auth: this.app(scope) });
525
+ }
526
+ /** @internal The in-flight refresh map for one store; see `OAuthSessionAuth`. */
527
+ _refreshesFor(store) {
528
+ let map = this.refreshes.get(store);
529
+ if (!map) {
530
+ map = /* @__PURE__ */ new Map();
531
+ this.refreshes.set(store, map);
532
+ }
533
+ return map;
534
+ }
535
+ // ---- internals ----------------------------------------------------------
536
+ /** `client_secret_basic` header, or undefined for a public client. */
537
+ basicAuthHeader() {
538
+ if (this.clientSecret === void 0) return void 0;
539
+ const raw = `${this.clientId}:${this.clientSecret}`;
540
+ return "Basic " + Buffer.from(raw).toString("base64");
541
+ }
542
+ formHeaders() {
543
+ const basic = this.basicAuthHeader();
544
+ return {
545
+ "Content-Type": "application/x-www-form-urlencoded",
546
+ Accept: "application/json",
547
+ ...basic ? { Authorization: basic } : {}
548
+ };
549
+ }
550
+ /** A public client identifies with `client_id` in the form (RFC 6749 section 4.1.3). */
551
+ withClientId(body) {
552
+ if (this.isPublic) body.set("client_id", this.clientId);
553
+ return body;
554
+ }
555
+ async postToken(body) {
556
+ const res = await this.fetch(joinUrl(this.baseUrl, this.endpoints.token), {
557
+ method: "POST",
558
+ headers: this.formHeaders(),
559
+ body: this.withClientId(body).toString()
560
+ });
561
+ const text = await res.text();
562
+ if (!res.ok) {
563
+ const err = rfcError(text);
564
+ if (res.status === 400 && err?.error === "invalid_grant" && body.get("grant_type") === "refresh_token") {
565
+ throw new STXGrantRevokedException(
566
+ err.error_description ? `OAuth grant revoked: ${err.error_description}. The member must re-authorize.` : void 0
567
+ );
568
+ }
569
+ throw this.oauthError(res.status, text, this.endpoints.token);
570
+ }
571
+ return parseTokenResponse(text);
572
+ }
573
+ oauthError(status, text, endpoint) {
574
+ const err = rfcError(text);
575
+ const path = pathOf(endpoint);
576
+ if (err) return new STXOAuthException(err.error, err.error_description, status, path);
577
+ return new STXOAuthException("http_error", text.slice(0, 300) || void 0, status, path);
578
+ }
579
+ };
580
+ function parseJsonBody(text, status, endpoint) {
581
+ try {
582
+ return JSON.parse(text);
583
+ } catch {
584
+ throw new STXOAuthException("invalid_response", "Response body is not JSON.", status, pathOf(endpoint));
585
+ }
586
+ }
587
+ function parseTokenResponse(json) {
588
+ const parsed = typeof json === "string" ? parseJsonBody(json, 200, DEFAULT_ENDPOINTS.token) : json;
589
+ const obj = parsed;
590
+ if (!obj || typeof obj.access_token !== "string" || obj.access_token === "") {
591
+ throw new STXOAuthException(
592
+ "invalid_response",
593
+ "Token response missing access_token.",
594
+ 200,
595
+ DEFAULT_ENDPOINTS.token
596
+ );
597
+ }
598
+ const set = { accessToken: obj.access_token };
599
+ if (typeof obj.refresh_token === "string") set.refreshToken = obj.refresh_token;
600
+ if (typeof obj.token_type === "string") set.tokenType = obj.token_type;
601
+ if (typeof obj.expires_in === "number") {
602
+ set.expiresIn = obj.expires_in;
603
+ set.expiresAt = Date.now() + obj.expires_in * 1e3;
604
+ }
605
+ if (typeof obj.scope === "string") set.scope = obj.scope;
606
+ return set;
607
+ }
608
+ function tokenSetToStored(set) {
609
+ return {
610
+ accessToken: set.accessToken,
611
+ refreshToken: set.refreshToken,
612
+ expiresAt: set.expiresAt,
613
+ scope: set.scope
614
+ };
615
+ }
616
+ var AppTokenProvider = class {
617
+ constructor(client, scope, opts = {}) {
618
+ this.client = client;
619
+ this.scope = scope;
620
+ this.skewMs = opts.skewMs ?? 6e4;
621
+ }
622
+ client;
623
+ scope;
624
+ cached = null;
625
+ inflight = null;
626
+ skewMs;
627
+ /** A valid access token, minting if missing or near expiry. */
628
+ async get() {
629
+ const c = this.cached;
630
+ if (c && Date.now() < c.expiresAt - this.skewMs) return c.accessToken;
631
+ if (this.inflight) return this.inflight;
632
+ this.inflight = this.mint().finally(() => {
633
+ this.inflight = null;
634
+ });
635
+ return this.inflight;
636
+ }
637
+ /** Drop the cache so the next `get()` mints. Call after a 401. */
638
+ invalidate() {
639
+ this.cached = null;
640
+ }
641
+ /** Invalidate and mint now. Use before a socket reconnect. */
642
+ fresh() {
643
+ this.invalidate();
644
+ return this.get();
645
+ }
646
+ /** The effective scope the exchange granted the current token, if minted. */
647
+ get grantedScope() {
648
+ return this.cached?.scope;
649
+ }
650
+ async mint() {
651
+ const set = await this.client.clientCredentials(this.scope);
652
+ this.cached = {
653
+ accessToken: set.accessToken,
654
+ expiresAt: set.expiresAt ?? Number.POSITIVE_INFINITY,
655
+ scope: set.scope
656
+ };
657
+ return set.accessToken;
658
+ }
659
+ };
660
+ var OAuthBearerAuth = class {
661
+ constructor(accessToken) {
662
+ this.accessToken = accessToken;
663
+ }
664
+ accessToken;
665
+ kind = "oauth";
666
+ setAccessToken(token) {
667
+ this.accessToken = token;
668
+ }
669
+ async authHeaders() {
670
+ return { Authorization: `Bearer ${this.accessToken}` };
671
+ }
672
+ async websocketHeaders() {
673
+ return { "x-stx-oauth-token": this.accessToken };
674
+ }
675
+ };
676
+ var OAuthSessionAuth = class {
677
+ constructor(client, store, memberKey, opts = {}) {
678
+ this.client = client;
679
+ this.store = store;
680
+ this.memberKey = memberKey;
681
+ this.opts = opts;
682
+ this.skewMs = opts.skewMs ?? 3e4;
683
+ }
684
+ client;
685
+ store;
686
+ memberKey;
687
+ opts;
688
+ kind = "oauth";
689
+ /** Ms of slack before expiry at which to refresh proactively. */
690
+ skewMs;
691
+ /** The access token last put on the wire, to tell a stale 401 from a dead token. */
692
+ lastSent;
693
+ async load() {
694
+ return await this.store.get(this.memberKey) ?? null;
695
+ }
696
+ /** The member's current tokens, refreshed first if at or near expiry. */
697
+ async tokens() {
698
+ let tokens = await this.load();
699
+ if (!tokens) {
700
+ throw new STXConfigException(`No tokens stored for member "${this.memberKey}". Complete the OAuth flow first.`);
701
+ }
702
+ if (tokens.refreshToken && tokens.expiresAt !== void 0 && tokens.expiresAt - Date.now() <= this.skewMs) {
703
+ const refreshed = await this.refresh(tokens.refreshToken);
704
+ if (refreshed) tokens = refreshed;
705
+ }
706
+ return tokens;
707
+ }
708
+ /** The granted scopes of the stored tokens, canonical names. */
709
+ async scopes() {
710
+ return parseScopes((await this.load())?.scope);
711
+ }
712
+ async authHeaders(_request) {
713
+ const tokens = await this.tokens();
714
+ this.lastSent = tokens.accessToken;
715
+ return { Authorization: `Bearer ${tokens.accessToken}` };
716
+ }
717
+ async onUnauthorized() {
718
+ const tokens = await this.load();
719
+ if (!tokens) return false;
720
+ if (this.lastSent !== void 0 && tokens.accessToken !== this.lastSent) return true;
721
+ if (!tokens.refreshToken) return false;
722
+ const refreshed = await this.refresh(tokens.refreshToken);
723
+ return refreshed !== null;
724
+ }
725
+ /** Called on every (re)connect, so a reconnect after expiry gets a fresh token. */
726
+ async websocketHeaders(_context) {
727
+ const tokens = await this.tokens();
728
+ this.lastSent = tokens.accessToken;
729
+ return { "x-stx-oauth-token": tokens.accessToken };
730
+ }
731
+ /**
732
+ * Refresh with rotation, single-flight. Persists the new pair (keeping the
733
+ * returned refresh token; the old one only if the server omitted it). On a
734
+ * revoked grant, deletes the store entry and throws
735
+ * `STXGrantRevokedException`. A transient failure resolves null.
736
+ */
737
+ refresh(refreshToken) {
738
+ const inflight = this.client._refreshesFor(this.store);
739
+ const existing = inflight.get(this.memberKey);
740
+ if (existing) return existing;
741
+ const run = async () => {
742
+ const current = await this.load();
743
+ if (current?.refreshToken && current.refreshToken !== refreshToken) return current;
744
+ try {
745
+ const set = await this.client.refreshToken(refreshToken);
746
+ const stored = {
747
+ accessToken: set.accessToken,
748
+ refreshToken: set.refreshToken ?? refreshToken,
749
+ expiresAt: set.expiresAt,
750
+ scope: set.scope ?? current?.scope
751
+ };
752
+ await this.store.set(this.memberKey, stored);
753
+ await this.opts.onRefresh?.(stored);
754
+ return stored;
755
+ } catch (err) {
756
+ if (err instanceof STXGrantRevokedException) {
757
+ await this.store.delete(this.memberKey);
758
+ await this.opts.onGrantRevoked?.(err);
759
+ throw err;
760
+ }
761
+ return null;
762
+ }
763
+ };
764
+ const promise = (async () => {
765
+ try {
766
+ return this.store.withLock ? await this.store.withLock(this.memberKey, run) : await run();
767
+ } finally {
768
+ inflight.delete(this.memberKey);
769
+ }
770
+ })();
771
+ inflight.set(this.memberKey, promise);
772
+ return promise;
773
+ }
774
+ };
775
+ var OAuthAppAuth = class {
776
+ constructor(tokens) {
777
+ this.tokens = tokens;
778
+ }
779
+ tokens;
780
+ kind = "oauth_app";
781
+ async authHeaders(_request) {
782
+ return { Authorization: `Bearer ${await this.tokens.get()}` };
783
+ }
784
+ async onUnauthorized() {
785
+ await this.tokens.fresh();
786
+ return true;
787
+ }
788
+ /**
789
+ * The first connect uses the cached token; a reconnect (or a caller that
790
+ * does not say) mints fresh, never reusing the token from a connection that
791
+ * just dropped.
792
+ */
793
+ async websocketHeaders(context) {
794
+ const token = context?.reconnect === false ? await this.tokens.get() : await this.tokens.fresh();
795
+ return { "x-stx-oauth-token": token };
796
+ }
797
+ };
798
+ function normalizeScope(scope) {
799
+ if (scope === void 0) return void 0;
800
+ return typeof scope === "string" ? scope : formatScopes(scope);
801
+ }
802
+ async function readCallback(pending, callback, authorizeEndpoint = DEFAULT_ENDPOINTS.authorize) {
803
+ const q = callbackParams(callback);
804
+ const where = pathOf(authorizeEndpoint);
805
+ const error = q.get("error");
806
+ if (error) throw new STXOAuthException(error, q.get("error_description") ?? void 0, 400, where);
807
+ const code = q.get("code");
808
+ const state = q.get("state");
809
+ if (!code || !state) {
810
+ throw new STXOAuthException("invalid_request", "The callback carries no code or no state.", 400, where);
811
+ }
812
+ const entry = await pending.take(state);
813
+ if (!entry) {
814
+ throw new STXOAuthException(
815
+ "invalid_state",
816
+ "Unknown, used or expired state; start the sign-in again.",
817
+ 400,
818
+ where
819
+ );
820
+ }
821
+ return { code, pending: entry };
822
+ }
823
+ function callbackParams(input) {
824
+ if (input instanceof URLSearchParams) return input;
825
+ if (input instanceof URL) return input.searchParams;
826
+ if (typeof input === "string") {
827
+ const q = input.includes("?") ? input.slice(input.indexOf("?") + 1) : input;
828
+ return new URLSearchParams(q.split("#", 1)[0]);
829
+ }
830
+ const out = new URLSearchParams();
831
+ for (const [k, v] of Object.entries(input)) if (typeof v === "string") out.set(k, v);
832
+ return out;
833
+ }
834
+ function pathOf(endpoint) {
835
+ try {
836
+ return /^https?:\/\//i.test(endpoint) ? new URL(endpoint).pathname : endpoint;
837
+ } catch {
838
+ return endpoint;
839
+ }
840
+ }
841
+
842
+ // src/oauth/metadata.ts
843
+ async function discoverMetadata(baseUrl, opts = {}) {
844
+ const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.authorizationServer, opts);
845
+ const meta = doc;
846
+ if (typeof meta.issuer !== "string" || typeof meta.authorization_endpoint !== "string" || typeof meta.token_endpoint !== "string") {
847
+ throw httpError2(
848
+ 200,
849
+ JSON.stringify(doc),
850
+ WELL_KNOWN.authorizationServer + " (missing issuer/authorization_endpoint/token_endpoint)"
851
+ );
852
+ }
853
+ return meta;
854
+ }
855
+ async function discoverProtectedResource(baseUrl, opts = {}) {
856
+ const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.protectedResource, opts);
857
+ const meta = doc;
858
+ if (typeof meta.resource !== "string" || !Array.isArray(meta.authorization_servers)) {
859
+ throw httpError2(
860
+ 200,
861
+ JSON.stringify(doc),
862
+ WELL_KNOWN.protectedResource + " (missing resource/authorization_servers)"
863
+ );
864
+ }
865
+ return meta;
866
+ }
867
+ async function fetchWellKnown(baseUrl, path, opts) {
868
+ const cfg = resolveOAuthConfig({ baseUrl, fetch: opts.fetch });
869
+ const res = await cfg.fetch(joinUrl(cfg.baseUrl, path), {
870
+ method: "GET",
871
+ headers: { Accept: "application/json" }
872
+ });
873
+ const text = await res.text();
874
+ if (!res.ok) throw httpError2(res.status, text, path);
875
+ try {
876
+ return JSON.parse(text);
877
+ } catch {
878
+ throw httpError2(res.status, text, path);
879
+ }
880
+ }
881
+ function httpError2(status, text, path) {
882
+ return new STXAPIException(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {
883
+ statusCode: status,
884
+ body: text,
885
+ path
886
+ });
887
+ }
888
+
889
+ // src/oauth/tokenStore.ts
890
+ var MemoryTokenStore = class {
891
+ map = /* @__PURE__ */ new Map();
892
+ get(memberKey) {
893
+ return this.map.get(memberKey) ?? null;
894
+ }
895
+ set(memberKey, tokens) {
896
+ this.map.set(memberKey, tokens);
897
+ }
898
+ delete(memberKey) {
899
+ this.map.delete(memberKey);
900
+ }
901
+ };
902
+
903
+ // src/oauth/pending.ts
904
+ var MemoryPendingAuthorizationStore = class {
905
+ map = /* @__PURE__ */ new Map();
906
+ put(state, pending) {
907
+ this.sweep();
908
+ this.map.set(state, pending);
909
+ }
910
+ take(state) {
911
+ const entry = this.map.get(state) ?? null;
912
+ this.map.delete(state);
913
+ if (!entry || entry.expiresAt <= Date.now()) return null;
914
+ return entry;
915
+ }
916
+ /** Entries not yet taken or expired. */
917
+ get size() {
918
+ this.sweep();
919
+ return this.map.size;
920
+ }
921
+ sweep() {
922
+ const now = Date.now();
923
+ for (const [k, v] of this.map) if (v.expiresAt <= now) this.map.delete(k);
924
+ }
925
+ };
926
+ export {
927
+ ALL_APP_SCOPES,
928
+ ALL_MEMBER_SCOPES,
929
+ AppScopes,
930
+ AppTokenProvider,
931
+ DEFAULT_ENDPOINTS,
932
+ LEGACY_SCOPES,
933
+ MemberScopes,
934
+ MemoryPendingAuthorizationStore,
935
+ MemoryTokenStore,
936
+ OAuthAppAuth,
937
+ OAuthBearerAuth,
938
+ OAuthClient,
939
+ OAuthSessionAuth,
940
+ STXAuthenticationException,
941
+ STXForbiddenException,
942
+ STXGrantRevokedException,
943
+ STXInsufficientScopeException,
944
+ STXInvalidTokenException,
945
+ STXOAuthException,
946
+ Scopes,
947
+ WELL_KNOWN,
948
+ base64url,
949
+ canonicalScope,
950
+ codeChallengeS256,
951
+ createPkce,
952
+ discoverMetadata,
953
+ discoverProtectedResource,
954
+ formatScopes,
955
+ generateCodeVerifier,
956
+ generateState,
957
+ isAppScope,
958
+ isMemberScope,
959
+ joinUrl,
960
+ parseScopes,
961
+ parseTokenResponse,
962
+ readCallback,
963
+ registerClient,
964
+ rfcError,
965
+ tokenSetToStored
966
+ };
967
+ //# sourceMappingURL=oauth.js.map