@stxapp/stx-typescript 0.6.3 → 0.7.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/CHANGELOG.md +4 -0
- package/dist/{chunk-CSHPFQ2V.cjs → chunk-ASOLCDBG.cjs} +26 -212
- package/dist/chunk-ASOLCDBG.cjs.map +1 -0
- package/dist/{chunk-PZUVKPHZ.js → chunk-CDXZOW53.js} +8 -194
- package/dist/chunk-CDXZOW53.js.map +1 -0
- package/dist/{client-Dkd5vesS.d.cts → client-CA1d-osT.d.cts} +4 -9
- package/dist/{client-Dkd5vesS.d.ts → client-CA1d-osT.d.ts} +4 -9
- 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 +21 -21
- package/dist/oauth.cjs.map +1 -1
- package/dist/oauth.d.cts +8 -8
- package/dist/oauth.d.ts +8 -8
- package/dist/oauth.js +5 -5
- package/dist/oauth.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-CSHPFQ2V.cjs.map +0 -1
- package/dist/chunk-PZUVKPHZ.js.map +0 -1
package/dist/oauth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/oauth/endpoints.ts","../src/oauth/errors.ts","../src/oauth/pkce.ts","../src/oauth/register.ts","../src/oauth/scopes.ts","../src/oauth/client.ts","../src/oauth/metadata.ts","../src/oauth/tokenStore.ts","../src/oauth/pending.ts"],"sourcesContent":["// OAuth endpoint paths and URL helpers. Every path is overridable, and\n// discovery (metadata.ts) supplies absolute URLs that win over these.\n\nimport { baseUrlFor } from \"../config.js\";\nimport { STXConfigException } from \"../exceptions.js\";\n\nexport interface OAuthEndpoints {\n /** Default `/oauth/authorize`. */\n authorize: string;\n /** Default `/oauth/token`. */\n token: string;\n /** Default `/oauth/revoke` (RFC 7009). */\n revoke: string;\n /** Default `/oauth/introspect` (RFC 7662). */\n introspect: string;\n /** Default `/oauth/register` (RFC 7591). */\n register: string;\n}\n\nexport const DEFAULT_ENDPOINTS: Readonly<OAuthEndpoints> = {\n authorize: \"/oauth/authorize\",\n token: \"/oauth/token\",\n revoke: \"/oauth/revoke\",\n introspect: \"/oauth/introspect\",\n register: \"/oauth/register\",\n};\n\n/** RFC 8414 / RFC 9728 discovery documents, relative to the base URL. */\nexport const WELL_KNOWN = {\n authorizationServer: \"/.well-known/oauth-authorization-server\",\n protectedResource: \"/.well-known/oauth-protected-resource\",\n} as const;\n\n/** A `fetch`-compatible function. Defaults to the global `fetch`. */\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\n/**\n * The base URL and fetch for an OAuth call. `baseUrl` is a host or URL (as\n * `STX`'s `host`); it falls back to STX_HOST / STX_BASE_URL.\n */\nexport function resolveOAuthConfig(input: { baseUrl?: string; fetch?: FetchLike }): {\n baseUrl: string;\n fetch: FetchLike;\n} {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n const host = input.baseUrl ?? env.STX_HOST ?? env.STX_BASE_URL;\n if (!host) throw new STXConfigException(\"An OAuth base URL is required. Pass { baseUrl } or set STX_HOST.\");\n const fetchImpl = input.fetch ?? (globalThis.fetch as FetchLike | undefined);\n if (typeof fetchImpl !== \"function\") {\n throw new STXConfigException(\"No fetch implementation available. Use Node 18+, or pass { fetch }.\");\n }\n return { baseUrl: baseUrlFor(null, null, host), fetch: fetchImpl };\n}\n\n/** Build an absolute URL from the base and a path (absolute URLs pass through). */\nexport function joinUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return baseUrl + (path.startsWith(\"/\") ? path : \"/\" + path);\n}\n","// OAuth errors. Both are STXAuthenticationException subclasses, so a caller\n// catching authentication failures from the REST client sees them too.\n\nimport { STXAuthenticationException } from \"../exceptions.js\";\n\n/**\n * An RFC 6749 section 5.2 (or RFC 7591 section 3.2.2) error body from an\n * OAuth protocol endpoint: `{\"error\": \"...\", \"error_description\": \"...\"}`.\n */\nexport class STXOAuthException extends STXAuthenticationException {\n /** The RFC error code: `invalid_client`, `invalid_grant`, `invalid_scope`, ... */\n readonly error: string;\n readonly errorDescription: string | undefined;\n /** The endpoint path that answered. */\n readonly endpoint: string;\n /** Seconds to wait when the endpoint answered 429 with Retry-After. */\n readonly retryAfter: number | undefined;\n\n constructor(\n error: string,\n errorDescription: string | undefined,\n status: number,\n endpoint: string,\n retryAfter?: number,\n ) {\n super(`OAuth ${endpoint} ${status} ${error}${errorDescription ? `: ${errorDescription}` : \"\"}`, {\n statusCode: status,\n path: endpoint,\n });\n this.error = error;\n this.errorDescription = errorDescription;\n this.endpoint = endpoint;\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * The OAuth grant is no longer valid: a refresh was rejected with\n * `invalid_grant` (the member revoked the app, or a retired or reused refresh\n * token tripped reuse detection and the whole grant was revoked). Send the\n * member back through consent.\n */\nexport class STXGrantRevokedException extends STXAuthenticationException {\n constructor(message = \"OAuth grant revoked: the member must re-authorize.\") {\n super(message, { statusCode: 400 });\n }\n}\n","// PKCE (RFC 7636) + state helpers for the OAuth authorization-code flow.\n//\n// Uses the global WebCrypto (`crypto.getRandomValues` / `crypto.subtle`),\n// available on Node 18+, Bun and Deno: no Node-specific imports here.\n\n/** Standard base64url (no padding), the encoding PKCE requires. */\nexport function base64url(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n const b64 = btoa(bin);\n return b64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction randomBytes(n: number): Uint8Array {\n const buf = new Uint8Array(n);\n crypto.getRandomValues(buf);\n return buf;\n}\n\n/**\n * A high-entropy `code_verifier`: 32 random bytes → 43-char base64url string,\n * within the RFC 7636 43–128 character range.\n */\nexport function generateCodeVerifier(): string {\n return base64url(randomBytes(32));\n}\n\n/** The S256 challenge is `base64url(SHA-256(verifier))`. STX rejects `plain`. */\nexport async function codeChallengeS256(verifier: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n return base64url(new Uint8Array(digest));\n}\n\n/** An opaque, unguessable CSRF `state` to tie /authorize to /callback. */\nexport function generateState(): string {\n return base64url(randomBytes(24));\n}\n\nexport interface Pkce {\n codeVerifier: string;\n codeChallenge: string;\n}\n\n/** Generate a verifier + its S256 challenge in one call. */\nexport async function createPkce(): Promise<Pkce> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await codeChallengeS256(codeVerifier);\n return { codeVerifier, codeChallenge };\n}\n","// RFC 7591 dynamic client registration: `POST /oauth/register`.\n//\n// Unauthenticated by design, so an MCP host or a first-time integrator can\n// obtain a client on the spot. A registration is inert until a member consents\n// on `/oauth/authorize`. Rules the exchange enforces (400 on violation):\n// - redirect URIs are absolute `https`, or `http` loopback (localhost,\n// 127.0.0.1, [::1]); no fragment\n// - `token_endpoint_auth_method` is `client_secret_basic` (default, returns a\n// one-time `client_secret`) or `none` (public client: no secret, PKCE only)\n// - `none` cannot be combined with `grant_types: [\"client_credentials\"]`\n// - `grant_types` is a subset of authorization_code / refresh_token /\n// client_credentials; `refresh_token` needs `authorization_code`\n// - `scope` may name member and app scopes; omitted means the exchange's\n// default member list\n\nimport { STXAPIException } from \"../exceptions.js\";\nimport { DEFAULT_ENDPOINTS, joinUrl, resolveOAuthConfig, type FetchLike } from \"./endpoints.js\";\nimport { STXOAuthException } from \"./errors.js\";\n\nexport type TokenEndpointAuthMethod = \"client_secret_basic\" | \"none\";\nexport type GrantType = \"authorization_code\" | \"refresh_token\" | \"client_credentials\";\n\n/** RFC 7591 section 2 client metadata accepted by the exchange. */\nexport interface ClientRegistrationRequest {\n client_name: string;\n redirect_uris: string[];\n /** Space-delimited. Defaults to the exchange's configured member scope list. */\n scope?: string;\n /** Default `client_secret_basic`. `none` registers a public (PKCE-only) client. */\n token_endpoint_auth_method?: TokenEndpointAuthMethod;\n /** Default `[\"authorization_code\", \"refresh_token\"]`. */\n grant_types?: GrantType[];\n /** Only `[\"code\"]` is supported. */\n response_types?: [\"code\"];\n client_uri?: string;\n logo_uri?: string;\n software_id?: string;\n software_version?: string;\n}\n\n/** RFC 7591 section 3.2.1 client information response. */\nexport interface ClientRegistration {\n client_id: string;\n /** Unix seconds. */\n client_id_issued_at: number;\n /** Present for a confidential client only; shown once, never recoverable. */\n client_secret?: string;\n /** `0` means never. Present with `client_secret`. */\n client_secret_expires_at?: number;\n client_name: string;\n redirect_uris: string[];\n /** The stored scopes, space-delimited, defaults applied. */\n scope: string;\n grant_types: GrantType[];\n response_types: string[];\n token_endpoint_auth_method: TokenEndpointAuthMethod;\n client_uri?: string;\n logo_uri?: string;\n software_id?: string;\n software_version?: string;\n}\n\nexport interface RegisterClientOptions {\n baseUrl?: string;\n /** Absolute `registration_endpoint` from discovery, or a path. Default `/oauth/register`. */\n registrationEndpoint?: string;\n fetch?: FetchLike;\n}\n\n/**\n * Register an OAuth client. Resolves with the client information on `201`.\n * Throws `STXOAuthException` with the RFC error code on `400`\n * (`invalid_redirect_uri`, `invalid_client_metadata`) and `429`\n * (`rate_limited`, with `retryAfter` seconds); `STXAPIException` on `404`\n * (registration disabled) and anything else.\n */\nexport async function registerClient(\n request: ClientRegistrationRequest,\n opts: RegisterClientOptions = {},\n): Promise<ClientRegistration> {\n const cfg = resolveOAuthConfig({ baseUrl: opts.baseUrl, fetch: opts.fetch });\n const endpoint = opts.registrationEndpoint ?? DEFAULT_ENDPOINTS.register;\n const url = joinUrl(cfg.baseUrl, endpoint);\n const path = new URL(url).pathname;\n\n const res = await cfg.fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Accept: \"application/json\" },\n body: JSON.stringify(request),\n });\n const text = await res.text();\n\n if (res.status === 201 || res.status === 200) {\n let doc: unknown;\n try {\n doc = JSON.parse(text);\n } catch {\n throw httpError(res.status, text, path);\n }\n const reg = doc as Partial<ClientRegistration>;\n if (typeof reg.client_id !== \"string\" || reg.client_id === \"\") {\n throw httpError(res.status, text, path + \" (missing client_id)\");\n }\n return reg as ClientRegistration;\n }\n\n const err = rfcError(text);\n if (err) {\n const retryAfter = Number(res.headers.get(\"retry-after\"));\n throw new STXOAuthException(\n err.error,\n err.error_description,\n res.status,\n path,\n Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : undefined,\n );\n }\n throw httpError(res.status, text, path);\n}\n\n/** Parse an RFC 6749 section 5.2 error body, or null if the body is not one. */\nexport function rfcError(text: string): { error: string; error_description?: string } | null {\n try {\n const obj = JSON.parse(text) as Record<string, unknown>;\n if (typeof obj.error !== \"string\") return null;\n return {\n error: obj.error,\n error_description: typeof obj.error_description === \"string\" ? obj.error_description : undefined,\n };\n } catch {\n return null;\n }\n}\n\nfunction httpError(status: number, text: string, path: string): STXAPIException {\n return new STXAPIException(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {\n statusCode: status,\n body: text,\n path,\n });\n}\n","// The STX OAuth scope vocabulary, as the exchange defines it (the exchange is\n// the source of truth): two disjoint vocabularies, member\n// scopes (`resource.action`, granted to a user token through consent) and app\n// scopes (carried by a `client_credentials` app token, no user, no consent).\n//\n// No scope moves money. `transfers.read` is a read of deposit/withdrawal\n// history; there is no scope that initiates, approves or cancels a transfer.\n\n/** Member scopes, in the exchange's canonical order. */\nexport const MemberScopes = {\n /** Who the member is: `me`, `GET /api/v1/me`. */\n PROFILE_READ: \"profile.read\",\n /** Cash balance: `account`, `GET /api/v1/account/balance`, `balances:` channel. */\n BALANCE_READ: \"balance.read\",\n /** Positions, settlements, loyalty/fee/adjustment ledgers, `positions:`/`settlements:`. */\n PORTFOLIO_READ: \"portfolio.read\",\n /** Order and fill history, `orders:`/`fills:` channels. */\n ORDERS_READ: \"orders.read\",\n /** Deposit and withdrawal history (read only). */\n TRANSFERS_READ: \"transfers.read\",\n /** Place and cancel orders; arm `cancel_on_disconnect`. */\n ORDERS_WRITE: \"orders.write\",\n /** Accept the terms and conditions. */\n TERMS_WRITE: \"terms.write\",\n} as const;\nexport type MemberScope = (typeof MemberScopes)[keyof typeof MemberScopes];\n\n/** App (machine) scopes for `client_credentials` tokens. */\nexport const AppScopes = {\n /** Public market catalog (`GET /api/v1/markets`) and the public market feeds. */\n MARKET_DATA: \"market_data\",\n /** Public event catalog (`GET /api/v1/events`) and the `events` feed. */\n EVENTS: \"events\",\n} as const;\nexport type AppScope = (typeof AppScopes)[keyof typeof AppScopes];\n\n/** Both vocabularies under one name, for callers that do not care which. */\nexport const Scopes = { ...MemberScopes, ...AppScopes } as const;\nexport type Scope = MemberScope | AppScope;\n\n/** Every member scope, canonical order. */\nexport const ALL_MEMBER_SCOPES: readonly MemberScope[] = Object.values(MemberScopes);\n/** Every app scope, canonical order. */\nexport const ALL_APP_SCOPES: readonly AppScope[] = Object.values(AppScopes);\n\n/**\n * Pre-`resource.action` names the exchange accepts for one release and\n * canonicalises on entry. A token minted by an older exchange may still report\n * them in its `scope` string.\n */\nexport const LEGACY_SCOPES: Readonly<Record<string, MemberScope>> = {\n identity: MemberScopes.PROFILE_READ,\n balance: MemberScopes.BALANCE_READ,\n portfolio: MemberScopes.PORTFOLIO_READ,\n history: MemberScopes.ORDERS_READ,\n transfers: MemberScopes.TRANSFERS_READ,\n trade: MemberScopes.ORDERS_WRITE,\n onboarding: MemberScopes.TERMS_WRITE,\n};\n\n/** The current name for a scope; legacy names map forward, anything else passes through. */\nexport function canonicalScope(scope: string): string {\n return LEGACY_SCOPES[scope] ?? scope;\n}\n\n/** Split a space-delimited `scope` string into canonical, de-duplicated scopes. */\nexport function parseScopes(scope: string | null | undefined): string[] {\n if (!scope) return [];\n const out: string[] = [];\n for (const raw of scope.split(/\\s+/)) {\n if (!raw) continue;\n const s = canonicalScope(raw);\n if (!out.includes(s)) out.push(s);\n }\n return out;\n}\n\n/** Join scopes into the space-delimited wire form. */\nexport function formatScopes(scopes: readonly string[]): string {\n return scopes.join(\" \");\n}\n\nexport function isMemberScope(scope: string): scope is MemberScope {\n return (ALL_MEMBER_SCOPES as readonly string[]).includes(scope);\n}\n\nexport function isAppScope(scope: string): scope is AppScope {\n return (ALL_APP_SCOPES as readonly string[]).includes(scope);\n}\n","// The `oauth` auth path: OAuth 2.0 for ISVs acting on a member's behalf\n// (authorization code + PKCE, refresh with rotation, revoke, introspect) and for\n// an app acting as itself (`client_credentials` app tokens for the public\n// catalog and market feeds). See the exchange's docs/oauth_isv_plan.md.\n//\n// This module has three layers:\n// 1. `OAuthClient`: stateless flow machinery. Build the authorize URL,\n// exchange a code, refresh, revoke, mint an app token. Works for a\n// confidential client (client_secret_basic) and a public one (no secret,\n// `client_id` in the form, PKCE is the proof).\n// 2. `AppTokenProvider`: a cached, self-renewing client_credentials token.\n// 3. Adapters (`bearer` / `session` / `app`) that plug a token source into\n// `STX` (as its `auth` option) and `STXWebSocket`, and the\n// `memberClient()` / `appClient()` shortcuts that build that `STX`.\n//\n// One `OAuthClient` is one registered app. A process serving several apps (a\n// brand and its sister brand, each with its own client id) makes one per app;\n// nothing is shared between them.\n\nimport type { AuthProvider, AuthRequest, WebSocketAuthContext } from \"../auth.js\";\nimport { STX, type STXOptions } from \"../client.js\";\nimport { STXConfigException } from \"../exceptions.js\";\nimport { DEFAULT_ENDPOINTS, joinUrl, resolveOAuthConfig, type FetchLike } from \"./endpoints.js\";\nimport { STXGrantRevokedException, STXOAuthException } from \"./errors.js\";\nimport type { AuthorizationServerMetadata } from \"./metadata.js\";\nimport type { PendingAuthorization, PendingAuthorizationStore } from \"./pending.js\";\nimport { createPkce, generateState, type Pkce } from \"./pkce.js\";\nimport { rfcError } from \"./register.js\";\nimport { formatScopes, parseScopes } from \"./scopes.js\";\nimport type { StoredTokens, TokenStore } from \"./tokenStore.js\";\n\n/** Parsed OAuth token response (RFC 6749 section 5.1). */\nexport interface TokenSet {\n accessToken: string;\n /** Absent on a `client_credentials` app token. */\n refreshToken?: string;\n tokenType?: string;\n /** Lifetime of the access token in seconds. */\n expiresIn?: number;\n /** Absolute epoch-ms expiry derived from `expiresIn`. */\n expiresAt?: number;\n /** Space-delimited effective scope after STX's narrowing. */\n scope?: string;\n}\n\ntype OAuthEndpoints = Pick<import(\"./endpoints.js\").OAuthEndpoints, \"authorize\" | \"token\" | \"revoke\" | \"introspect\">;\n\nexport interface OAuthClientOptions {\n /** The exchange's host or URL, as `STX`'s `host`. Defaults to `STX_HOST`. */\n baseUrl?: string;\n /** Your app's client id. */\n clientId: string;\n /**\n * The client secret for a confidential client (`client_secret_basic`). Omit\n * for a public client registered with `token_endpoint_auth_method: none`: it\n * then identifies with `client_id` in the form and PKCE is its proof. A public\n * client cannot use `clientCredentials()`.\n */\n clientSecret?: string;\n /** The redirect URI registered with STX (exact-matched). Required for the code flow. */\n redirectUri?: string;\n /** Default scopes to request, space-delimited or as a list. */\n scope?: string | readonly string[];\n /** Endpoint overrides; absolute URLs (from discovery) or paths. */\n endpoints?: Partial<OAuthEndpoints>;\n fetch?: FetchLike;\n}\n\n/** Options for a store-backed member session adapter. */\nexport interface SessionOptions {\n /** Refresh this many ms before the access token expires. Default 30000. */\n skewMs?: number;\n /** Called with the new tokens after every successful refresh (already persisted). */\n onRefresh?: (tokens: StoredTokens) => void | Promise<void>;\n /** Called once when the grant is found revoked; the store entry is already deleted. */\n onGrantRevoked?: (err: STXGrantRevokedException) => void | Promise<void>;\n}\n\n/** `STX` options for the `memberClient()` / `appClient()` shortcuts; host and auth come from the OAuth client. */\nexport type OAuthRestOptions = Omit<\n STXOptions,\n \"auth\" | \"keyId\" | \"privateKey\" | \"signer\" | \"profile\" | \"region\" | \"env\" | \"host\"\n>;\n\n/** What `completeAuthorization()` returns. */\nexport interface CompletedAuthorization {\n tokens: TokenSet;\n /** The granted scopes, canonical names. May be narrower than requested. */\n scopes: string[];\n /** The `data` passed to `beginAuthorization()`. */\n data: Record<string, unknown> | undefined;\n /** The member key the tokens were stored under, when a store was given. */\n memberKey: string | undefined;\n}\n\n/** Where `completeAuthorization()` / `redeemAuthorization()` save the tokens. */\nexport interface RedeemOptions {\n store?: TokenStore;\n /** A key, or a function of the `data` given to `beginAuthorization()`. */\n memberKey?: string | ((data: Record<string, unknown> | undefined) => string);\n}\n\n/** A validated callback: the code and the pending sign-in its state named (now consumed). */\nexport interface ReadCallback {\n code: string;\n pending: PendingAuthorization;\n}\n\n/** The query of an OAuth callback, in any of the shapes a server framework hands over. */\nexport type CallbackInput = string | URL | URLSearchParams | Record<string, string | undefined | null>;\n\n/** The prepared inputs for one authorization redirect. */\nexport interface Authorization {\n /** The full `/oauth/authorize` URL to send the member's browser to. */\n url: string;\n /** The `state` to store against this pending sign-in and verify on return. */\n state: string;\n /** The PKCE verifier to keep server-side and present at code exchange. */\n codeVerifier: string;\n /** The PKCE challenge that was embedded in `url`. */\n codeChallenge: string;\n}\n\nexport interface AuthorizationParams {\n scope?: string | readonly string[];\n state?: string;\n /** `none` for a silent background reconnect (RFC: prompt=none). */\n prompt?: \"none\" | \"login\" | \"consent\";\n redirectUri?: string;\n /** Extra authorize params, passed through verbatim. */\n extraParams?: Record<string, string>;\n}\n\nexport class OAuthClient {\n readonly baseUrl: string;\n readonly clientId: string;\n private readonly clientSecret?: string;\n readonly redirectUri?: string;\n readonly scope?: string;\n readonly endpoints: OAuthEndpoints;\n private readonly fetch: FetchLike;\n /**\n * In-flight refreshes per token store and member, shared by every session\n * adapter this client makes, so a burst of 401s across requests refreshes\n * once. Two refreshes of one rotating token would trip reuse detection and\n * revoke the grant.\n */\n private readonly refreshes = new WeakMap<TokenStore, Map<string, Promise<StoredTokens | null>>>();\n /** One cached app token per requested scope. */\n private readonly appTokens = new Map<string, AppTokenProvider>();\n\n constructor(opts: OAuthClientOptions) {\n const cfg = resolveOAuthConfig({ baseUrl: opts.baseUrl, fetch: opts.fetch });\n this.baseUrl = cfg.baseUrl;\n this.fetch = cfg.fetch;\n this.clientId = opts.clientId;\n this.clientSecret = opts.clientSecret || undefined;\n this.redirectUri = opts.redirectUri;\n this.scope = normalizeScope(opts.scope);\n this.endpoints = {\n authorize: opts.endpoints?.authorize ?? DEFAULT_ENDPOINTS.authorize,\n token: opts.endpoints?.token ?? DEFAULT_ENDPOINTS.token,\n revoke: opts.endpoints?.revoke ?? DEFAULT_ENDPOINTS.revoke,\n introspect: opts.endpoints?.introspect ?? DEFAULT_ENDPOINTS.introspect,\n };\n }\n\n /**\n * Build a client from a discovered RFC 8414 document, so every endpoint is the\n * one the exchange advertised on the host you asked. The base URL is the\n * issuer unless overridden.\n */\n static fromMetadata(metadata: AuthorizationServerMetadata, opts: Omit<OAuthClientOptions, \"endpoints\">): OAuthClient {\n return new OAuthClient({\n ...opts,\n baseUrl: opts.baseUrl ?? metadata.issuer,\n endpoints: {\n authorize: metadata.authorization_endpoint,\n token: metadata.token_endpoint,\n ...(metadata.revocation_endpoint ? { revoke: metadata.revocation_endpoint } : {}),\n ...(metadata.introspection_endpoint ? { introspect: metadata.introspection_endpoint } : {}),\n },\n });\n }\n\n /** True for a public client (no secret): PKCE-only, no app tokens. */\n get isPublic(): boolean {\n return this.clientSecret === undefined;\n }\n\n // ---- Step 1+2: prepare the authorize redirect ---------------------------\n\n /**\n * Create a fresh PKCE pair (S256) + `state` and build the authorize URL in\n * one call. Persist `state` and `codeVerifier` against the member's pending\n * sign-in and verify `state` on the callback.\n */\n async authorizationUrl(params: AuthorizationParams = {}): Promise<Authorization> {\n const pkce: Pkce = await createPkce();\n const state = params.state ?? generateState();\n const url = this.buildAuthorizeUrl({\n state,\n codeChallenge: pkce.codeChallenge,\n scope: params.scope,\n prompt: params.prompt,\n redirectUri: params.redirectUri,\n extraParams: params.extraParams,\n });\n return { url, state, codeVerifier: pkce.codeVerifier, codeChallenge: pkce.codeChallenge };\n }\n\n /** Alias of `authorizationUrl()` kept from 0.1. */\n createAuthorization(params: AuthorizationParams = {}): Promise<Authorization> {\n return this.authorizationUrl(params);\n }\n\n /**\n * Start a sign-in: create PKCE + state, remember them (and `data`) in\n * `pending` under the state, and return the authorize URL to redirect to.\n * Finish with `completeAuthorization()` on the callback.\n */\n async beginAuthorization(\n pending: PendingAuthorizationStore,\n params: AuthorizationParams & { data?: Record<string, unknown>; ttlMs?: number } = {},\n ): Promise<Authorization> {\n const redirectUri = params.redirectUri ?? this.redirectUri;\n if (!redirectUri) throw new STXConfigException(\"redirectUri is required to build an authorize URL.\");\n const auth = await this.authorizationUrl({ ...params, redirectUri });\n await pending.put(auth.state, {\n codeVerifier: auth.codeVerifier,\n redirectUri,\n scope: normalizeScope(params.scope) ?? this.scope,\n expiresAt: Date.now() + (params.ttlMs ?? 10 * 60_000),\n data: params.data,\n });\n return auth;\n }\n\n /**\n * Finish a sign-in from the callback's query. Checks for an `error` from\n * the exchange (the member denied consent: `access_denied`), consumes the\n * `state` (single use; unknown or expired throws `invalid_state`), exchanges\n * the code with the stored PKCE verifier and, when `store` is given, saves\n * the tokens under `memberKey` (a string, or a function of the `data` passed\n * to `beginAuthorization()`).\n *\n * Every failure is an `STXOAuthException` whose `error` says which:\n * `access_denied` and friends from the redirect, `invalid_request` (no code\n * or state), `invalid_state`, or the token endpoint's own (`invalid_grant`\n * for a used, expired or mismatched code).\n */\n async completeAuthorization(\n pending: PendingAuthorizationStore,\n callback: CallbackInput,\n opts: RedeemOptions = {},\n ): Promise<CompletedAuthorization> {\n return this.redeemAuthorization(await readCallback(pending, callback, this.endpoints.authorize), opts);\n }\n\n /**\n * The second half of `completeAuthorization()`: exchange a callback already\n * read with `readCallback()`. Use the pair when one callback URL serves\n * several apps and the app is only known from the pending entry's `data`.\n */\n async redeemAuthorization(callback: ReadCallback, opts: RedeemOptions = {}): Promise<CompletedAuthorization> {\n const entry = callback.pending;\n const tokens = await this.exchangeCode({\n code: callback.code,\n codeVerifier: entry.codeVerifier,\n redirectUri: entry.redirectUri,\n });\n let memberKey: string | undefined;\n if (opts.store) {\n memberKey = typeof opts.memberKey === \"function\" ? opts.memberKey(entry.data) : opts.memberKey;\n if (!memberKey) throw new STXConfigException(\"Pass memberKey along with store.\");\n await opts.store.set(memberKey, tokenSetToStored(tokens));\n }\n return { tokens, scopes: parseScopes(tokens.scope), data: entry.data, memberKey };\n }\n\n /** Build the authorize URL from a challenge you already have. */\n buildAuthorizeUrl(params: {\n state: string;\n codeChallenge: string;\n scope?: string | readonly string[];\n prompt?: \"none\" | \"login\" | \"consent\";\n redirectUri?: string;\n extraParams?: Record<string, string>;\n }): string {\n const redirectUri = params.redirectUri ?? this.redirectUri;\n if (!redirectUri) {\n throw new STXConfigException(\"redirectUri is required to build an authorize URL.\");\n }\n const url = new URL(joinUrl(this.baseUrl, this.endpoints.authorize));\n const search: Record<string, string> = {\n response_type: \"code\",\n client_id: this.clientId,\n redirect_uri: redirectUri,\n scope: normalizeScope(params.scope) ?? this.scope ?? \"\",\n code_challenge: params.codeChallenge,\n code_challenge_method: \"S256\",\n state: params.state,\n ...(params.prompt ? { prompt: params.prompt } : {}),\n ...(params.extraParams ?? {}),\n };\n url.search = new URLSearchParams(search).toString();\n return url.toString();\n }\n\n // ---- Step 4: exchange the code ------------------------------------------\n\n /** Exchange an authorization code for tokens, proving PKCE with the verifier. */\n exchangeCode(args: {\n code: string;\n codeVerifier: string;\n redirectUri?: string;\n }): Promise<TokenSet> {\n const redirectUri = args.redirectUri ?? this.redirectUri;\n if (!redirectUri) {\n throw new STXConfigException(\"redirectUri is required to exchange a code.\");\n }\n return this.postToken(\n new URLSearchParams({\n grant_type: \"authorization_code\",\n code: args.code,\n redirect_uri: redirectUri,\n code_verifier: args.codeVerifier,\n }),\n );\n }\n\n // ---- Refresh (with rotation) --------------------------------------------\n\n /**\n * Trade a refresh token for a fresh access/refresh pair. STX ROTATES the\n * refresh token, so the caller MUST persist whatever comes back. A rejected\n * refresh (`invalid_grant`) means the grant was revoked, including STX's\n * reuse detection tripping on a replayed/retired token, and surfaces as\n * `STXGrantRevokedException`.\n */\n refreshToken(refreshToken: string): Promise<TokenSet> {\n return this.postToken(\n new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n }),\n );\n }\n\n /** Alias of `refreshToken()` kept from 0.1. */\n refresh(refreshToken: string): Promise<TokenSet> {\n return this.refreshToken(refreshToken);\n }\n\n // ---- client_credentials (app tokens) ------------------------------------\n\n /**\n * Mint an APP token (RFC 6749 section 4.4): the client acting as itself, no\n * member, no consent, no refresh token. Scoped to app scopes only\n * (`market_data`, `events`); omit `scope` for every app scope the client is\n * allowed. Requires a confidential client. For a cached, self-renewing\n * token use `appToken()`.\n */\n clientCredentials(scope?: string | readonly string[]): Promise<TokenSet> {\n if (this.isPublic) {\n throw new STXConfigException(\n \"client_credentials needs a client secret; a public client cannot mint an app token.\",\n );\n }\n const body = new URLSearchParams({ grant_type: \"client_credentials\" });\n const s = normalizeScope(scope);\n if (s) body.set(\"scope\", s);\n return this.postToken(body);\n }\n\n /**\n * A cached `client_credentials` token that re-mints itself before expiry.\n * The same scope returns the same provider, so every `STX` client and socket\n * built from this OAuth client shares one token.\n */\n appToken(scope?: string | readonly string[]): AppTokenProvider {\n const key = normalizeScope(scope) ?? \"\";\n let provider = this.appTokens.get(key);\n if (!provider) {\n provider = new AppTokenProvider(this, scope);\n this.appTokens.set(key, provider);\n }\n return provider;\n }\n\n // ---- Revoke (RFC 7009) --------------------------------------------------\n\n /** Revoke a token (either kind kills the pair). Always resolves on a 200. */\n async revoke(token: string, tokenTypeHint?: \"access_token\" | \"refresh_token\"): Promise<void> {\n const body = new URLSearchParams({ token });\n if (tokenTypeHint) body.set(\"token_type_hint\", tokenTypeHint);\n const res = await this.fetch(joinUrl(this.baseUrl, this.endpoints.revoke), {\n method: \"POST\",\n headers: this.formHeaders(),\n body: this.withClientId(body).toString(),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n throw this.oauthError(res.status, text, this.endpoints.revoke);\n }\n }\n\n /**\n * Unlink a member: revoke their grant at the exchange (best effort) and\n * delete their tokens from `store`. Resolves true if the exchange confirmed\n * the revoke, false if it could not be reached or refused; the local tokens\n * are deleted either way.\n */\n async unlink(store: TokenStore, memberKey: string): Promise<boolean> {\n const tokens = await store.get(memberKey);\n let revoked = false;\n try {\n if (tokens?.refreshToken) {\n await this.revoke(tokens.refreshToken, \"refresh_token\");\n revoked = true;\n } else if (tokens?.accessToken) {\n await this.revoke(tokens.accessToken, \"access_token\");\n revoked = true;\n }\n } catch {\n revoked = false;\n } finally {\n await store.delete(memberKey);\n }\n return revoked;\n }\n\n // ---- Introspect (RFC 7662) ----------------------------------------------\n\n /** Report a token's active state + scope. Confidential clients only. */\n async introspect(\n token: string,\n ): Promise<{ active: boolean; scope?: string; client_id?: string; [k: string]: unknown }> {\n const res = await this.fetch(joinUrl(this.baseUrl, this.endpoints.introspect), {\n method: \"POST\",\n headers: this.formHeaders(),\n body: new URLSearchParams({ token }).toString(),\n });\n const text = await res.text();\n if (!res.ok) throw this.oauthError(res.status, text, this.endpoints.introspect);\n return parseJsonBody(text, res.status, this.endpoints.introspect) as { active: boolean };\n }\n\n // ---- Adapter factories --------------------------------------------------\n\n /** A simple Bearer adapter around a known access token (no refresh). */\n bearer(accessToken: string): OAuthBearerAuth {\n return new OAuthBearerAuth(accessToken);\n }\n\n /**\n * A store-backed adapter that reads the member's tokens, attaches the Bearer\n * header, refreshes proactively / on 401 with rotation, and clears the store\n * (throwing `STXGrantRevokedException`) if the grant was revoked.\n */\n session(store: TokenStore, memberKey: string, opts: SessionOptions = {}): OAuthSessionAuth {\n return new OAuthSessionAuth(this, store, memberKey, opts);\n }\n\n /**\n * An adapter authenticated as the APP (client_credentials): the public\n * catalog (`markets()`, `events()`) and the public market channels. Re-mints\n * before expiry, once on a 401, and fresh on every socket (re)connect.\n */\n app(scope?: string | readonly string[]): OAuthAppAuth {\n return new OAuthAppAuth(this.appToken(scope));\n }\n\n /**\n * An `STX` client acting for one member, over `session(store,\n * memberKey)`: every `/api/v1` method (balance, positions, fills, orders,\n * place and cancel) with the Bearer token attached, refreshed before expiry\n * and on a 401, and `client.websocket()` for the member's channels over the\n * `x-stx-oauth-token` handshake.\n */\n memberClient(store: TokenStore, memberKey: string, opts: OAuthRestOptions & { session?: SessionOptions } = {}): STX {\n const { session, ...rest } = opts;\n return new STX({\n ...rest,\n host: this.baseUrl,\n fetch: rest.fetch ?? this.fetch,\n auth: this.session(store, memberKey, session),\n });\n }\n\n /**\n * An `STX` client acting as the app (client_credentials): the public\n * catalog (`markets()`, `events()`) and, through `websocket()`, the public\n * market channels. Scope defaults to every app scope the client may hold.\n */\n appClient(scope?: string | readonly string[], opts: OAuthRestOptions = {}): STX {\n return new STX({ ...opts, host: this.baseUrl, fetch: opts.fetch ?? this.fetch, auth: this.app(scope) });\n }\n\n /** @internal The in-flight refresh map for one store; see `OAuthSessionAuth`. */\n _refreshesFor(store: TokenStore): Map<string, Promise<StoredTokens | null>> {\n let map = this.refreshes.get(store);\n if (!map) {\n map = new Map();\n this.refreshes.set(store, map);\n }\n return map;\n }\n\n // ---- internals ----------------------------------------------------------\n\n /** `client_secret_basic` header, or undefined for a public client. */\n basicAuthHeader(): string | undefined {\n if (this.clientSecret === undefined) return undefined;\n const raw = `${this.clientId}:${this.clientSecret}`;\n return \"Basic \" + Buffer.from(raw).toString(\"base64\");\n }\n\n private formHeaders(): Record<string, string> {\n const basic = this.basicAuthHeader();\n return {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n ...(basic ? { Authorization: basic } : {}),\n };\n }\n\n /** A public client identifies with `client_id` in the form (RFC 6749 section 4.1.3). */\n private withClientId(body: URLSearchParams): URLSearchParams {\n if (this.isPublic) body.set(\"client_id\", this.clientId);\n return body;\n }\n\n private async postToken(body: URLSearchParams): Promise<TokenSet> {\n const res = await this.fetch(joinUrl(this.baseUrl, this.endpoints.token), {\n method: \"POST\",\n headers: this.formHeaders(),\n body: this.withClientId(body).toString(),\n });\n\n const text = await res.text();\n if (!res.ok) {\n const err = rfcError(text);\n // A rejected refresh is a dead grant (revoked, or reuse detection fired).\n if (res.status === 400 && err?.error === \"invalid_grant\" && body.get(\"grant_type\") === \"refresh_token\") {\n throw new STXGrantRevokedException(\n err.error_description\n ? `OAuth grant revoked: ${err.error_description}. The member must re-authorize.`\n : undefined,\n );\n }\n throw this.oauthError(res.status, text, this.endpoints.token);\n }\n return parseTokenResponse(text);\n }\n\n private oauthError(status: number, text: string, endpoint: string): STXOAuthException {\n const err = rfcError(text);\n const path = pathOf(endpoint);\n if (err) return new STXOAuthException(err.error, err.error_description, status, path);\n return new STXOAuthException(\"http_error\", text.slice(0, 300) || undefined, status, path);\n }\n}\n\n/** Parse a 2xx body as JSON; a body that is not JSON is `STXOAuthException(\"invalid_response\")`. */\nfunction parseJsonBody(text: string, status: number, endpoint: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n throw new STXOAuthException(\"invalid_response\", \"Response body is not JSON.\", status, pathOf(endpoint));\n }\n}\n\n/** Parse and normalize an RFC 6749 section 5.1 token response. */\nexport function parseTokenResponse(json: string | unknown): TokenSet {\n const parsed = typeof json === \"string\" ? parseJsonBody(json, 200, DEFAULT_ENDPOINTS.token) : json;\n const obj = parsed as Record<string, unknown>;\n if (!obj || typeof obj.access_token !== \"string\" || obj.access_token === \"\") {\n throw new STXOAuthException(\n \"invalid_response\",\n \"Token response missing access_token.\",\n 200,\n DEFAULT_ENDPOINTS.token,\n );\n }\n const set: TokenSet = { accessToken: obj.access_token };\n if (typeof obj.refresh_token === \"string\") set.refreshToken = obj.refresh_token;\n if (typeof obj.token_type === \"string\") set.tokenType = obj.token_type;\n if (typeof obj.expires_in === \"number\") {\n set.expiresIn = obj.expires_in;\n set.expiresAt = Date.now() + obj.expires_in * 1000;\n }\n if (typeof obj.scope === \"string\") set.scope = obj.scope;\n return set;\n}\n\n/** Convert a TokenSet into the shape the TokenStore persists. */\nexport function tokenSetToStored(set: TokenSet): StoredTokens {\n return {\n accessToken: set.accessToken,\n refreshToken: set.refreshToken,\n expiresAt: set.expiresAt,\n scope: set.scope,\n };\n}\n\n// ---- App tokens -------------------------------------------------------------\n\n/**\n * A cached `client_credentials` token. Mints on first use, re-mints\n * proactively when within `skewMs` of expiry (default 60s), dedupes\n * concurrent mints, and can be invalidated after a 401 so the next call mints\n * fresh. A token with no `expires_in` is treated as non-expiring; the 401\n * safety net still covers it.\n */\nexport class AppTokenProvider {\n private cached: { accessToken: string; expiresAt: number; scope?: string } | null = null;\n private inflight: Promise<string> | null = null;\n readonly skewMs: number;\n\n constructor(\n private readonly client: OAuthClient,\n private readonly scope?: string | readonly string[],\n opts: { skewMs?: number } = {},\n ) {\n this.skewMs = opts.skewMs ?? 60_000;\n }\n\n /** A valid access token, minting if missing or near expiry. */\n async get(): Promise<string> {\n const c = this.cached;\n if (c && Date.now() < c.expiresAt - this.skewMs) return c.accessToken;\n if (this.inflight) return this.inflight;\n this.inflight = this.mint().finally(() => {\n this.inflight = null;\n });\n return this.inflight;\n }\n\n /** Drop the cache so the next `get()` mints. Call after a 401. */\n invalidate(): void {\n this.cached = null;\n }\n\n /** Invalidate and mint now. Use before a socket reconnect. */\n fresh(): Promise<string> {\n this.invalidate();\n return this.get();\n }\n\n /** The effective scope the exchange granted the current token, if minted. */\n get grantedScope(): string | undefined {\n return this.cached?.scope;\n }\n\n private async mint(): Promise<string> {\n const set = await this.client.clientCredentials(this.scope);\n this.cached = {\n accessToken: set.accessToken,\n expiresAt: set.expiresAt ?? Number.POSITIVE_INFINITY,\n scope: set.scope,\n };\n return set.accessToken;\n }\n}\n\n// ---- Adapters --------------------------------------------------------------\n\n/** Bearer-token adapter with no refresh. Good for one-shot scripts. */\nexport class OAuthBearerAuth implements AuthProvider {\n readonly kind = \"oauth\";\n constructor(private accessToken: string) {}\n\n setAccessToken(token: string): void {\n this.accessToken = token;\n }\n\n async authHeaders(): Promise<Record<string, string>> {\n return { Authorization: `Bearer ${this.accessToken}` };\n }\n\n async websocketHeaders(): Promise<Record<string, string>> {\n // The OAuth socket handshake carries the token in a custom header, which a\n // browser WebSocket cannot set, hence the `ws` package.\n return { \"x-stx-oauth-token\": this.accessToken };\n }\n}\n\n/**\n * Store-backed OAuth adapter. Attaches the current member's access token,\n * refreshes proactively when it is near expiry and on a 401 (rotating and\n * persisting the new refresh token every time), and treats a revoked grant as\n * terminal: the store entry is deleted and `STXGrantRevokedException` thrown.\n *\n * Refreshes are single-flight per (store, member) across every adapter the\n * same `OAuthClient` makes, so concurrent requests for one member refresh\n * once. A 401 on a token another request has already replaced is retried with\n * the stored token, without a second refresh. Across processes, give the store\n * a `withLock()` so only one replica refreshes a member at a time.\n */\nexport class OAuthSessionAuth implements AuthProvider {\n readonly kind = \"oauth\";\n /** Ms of slack before expiry at which to refresh proactively. */\n readonly skewMs: number;\n /** The access token last put on the wire, to tell a stale 401 from a dead token. */\n private lastSent: string | undefined;\n\n constructor(\n private readonly client: OAuthClient,\n private readonly store: TokenStore,\n readonly memberKey: string,\n private readonly opts: SessionOptions = {},\n ) {\n this.skewMs = opts.skewMs ?? 30_000;\n }\n\n private async load(): Promise<StoredTokens | null> {\n return (await this.store.get(this.memberKey)) ?? null;\n }\n\n /** The member's current tokens, refreshed first if at or near expiry. */\n async tokens(): Promise<StoredTokens> {\n let tokens = await this.load();\n if (!tokens) {\n throw new STXConfigException(`No tokens stored for member \"${this.memberKey}\". Complete the OAuth flow first.`);\n }\n if (tokens.refreshToken && tokens.expiresAt !== undefined && tokens.expiresAt - Date.now() <= this.skewMs) {\n const refreshed = await this.refresh(tokens.refreshToken);\n if (refreshed) tokens = refreshed;\n }\n return tokens;\n }\n\n /** The granted scopes of the stored tokens, canonical names. */\n async scopes(): Promise<string[]> {\n return parseScopes((await this.load())?.scope);\n }\n\n async authHeaders(_request?: AuthRequest): Promise<Record<string, string>> {\n const tokens = await this.tokens();\n this.lastSent = tokens.accessToken;\n return { Authorization: `Bearer ${tokens.accessToken}` };\n }\n\n async onUnauthorized(): Promise<boolean> {\n const tokens = await this.load();\n if (!tokens) return false;\n // Another request (or replica) already rotated the pair: retry with it.\n if (this.lastSent !== undefined && tokens.accessToken !== this.lastSent) return true;\n if (!tokens.refreshToken) return false;\n const refreshed = await this.refresh(tokens.refreshToken);\n return refreshed !== null;\n }\n\n /** Called on every (re)connect, so a reconnect after expiry gets a fresh token. */\n async websocketHeaders(_context?: WebSocketAuthContext): Promise<Record<string, string>> {\n const tokens = await this.tokens();\n this.lastSent = tokens.accessToken;\n return { \"x-stx-oauth-token\": tokens.accessToken };\n }\n\n /**\n * Refresh with rotation, single-flight. Persists the new pair (keeping the\n * returned refresh token; the old one only if the server omitted it). On a\n * revoked grant, deletes the store entry and throws\n * `STXGrantRevokedException`. A transient failure resolves null.\n */\n refresh(refreshToken: string): Promise<StoredTokens | null> {\n const inflight = this.client._refreshesFor(this.store);\n const existing = inflight.get(this.memberKey);\n if (existing) return existing;\n const run = async (): Promise<StoredTokens | null> => {\n // Under a lock another replica may have refreshed first: use its result.\n const current = await this.load();\n if (current?.refreshToken && current.refreshToken !== refreshToken) return current;\n try {\n const set = await this.client.refreshToken(refreshToken);\n const stored: StoredTokens = {\n accessToken: set.accessToken,\n refreshToken: set.refreshToken ?? refreshToken,\n expiresAt: set.expiresAt,\n scope: set.scope ?? current?.scope,\n };\n await this.store.set(this.memberKey, stored);\n await this.opts.onRefresh?.(stored);\n return stored;\n } catch (err) {\n if (err instanceof STXGrantRevokedException) {\n // Reuse or revocation: drop the dead tokens so nothing retries them.\n await this.store.delete(this.memberKey);\n await this.opts.onGrantRevoked?.(err);\n throw err;\n }\n return null;\n }\n };\n const promise = (async () => {\n try {\n return this.store.withLock ? await this.store.withLock(this.memberKey, run) : await run();\n } finally {\n inflight.delete(this.memberKey);\n }\n })();\n inflight.set(this.memberKey, promise);\n return promise;\n }\n}\n\n/**\n * App-token adapter (client_credentials). A Bearer token on every request,\n * `x-stx-oauth-token` on the socket handshake. A 401 invalidates the cache and the request is\n * retried once with a fresh mint; every socket (re)connect mints fresh, never\n * reusing the token from a connection that just dropped.\n */\nexport class OAuthAppAuth implements AuthProvider {\n readonly kind = \"oauth_app\";\n\n constructor(readonly tokens: AppTokenProvider) {}\n\n async authHeaders(_request?: AuthRequest): Promise<Record<string, string>> {\n return { Authorization: `Bearer ${await this.tokens.get()}` };\n }\n\n async onUnauthorized(): Promise<boolean> {\n await this.tokens.fresh();\n return true;\n }\n\n /**\n * The first connect uses the cached token; a reconnect (or a caller that\n * does not say) mints fresh, never reusing the token from a connection that\n * just dropped.\n */\n async websocketHeaders(context?: WebSocketAuthContext): Promise<Record<string, string>> {\n const token = context?.reconnect === false ? await this.tokens.get() : await this.tokens.fresh();\n return { \"x-stx-oauth-token\": token };\n }\n}\n\nfunction normalizeScope(scope: string | readonly string[] | undefined): string | undefined {\n if (scope === undefined) return undefined;\n return typeof scope === \"string\" ? scope : formatScopes(scope);\n}\n\n/**\n * Validate an OAuth callback and consume its pending sign-in. Throws\n * `STXOAuthException` with the redirect's `error` (`access_denied` when the\n * member declined), `invalid_request` (no code or state) or `invalid_state`\n * (unknown, used or expired). Does not call the exchange.\n */\nexport async function readCallback(\n pending: PendingAuthorizationStore,\n callback: CallbackInput,\n authorizeEndpoint: string = DEFAULT_ENDPOINTS.authorize,\n): Promise<ReadCallback> {\n const q = callbackParams(callback);\n const where = pathOf(authorizeEndpoint);\n const error = q.get(\"error\");\n if (error) throw new STXOAuthException(error, q.get(\"error_description\") ?? undefined, 400, where);\n const code = q.get(\"code\");\n const state = q.get(\"state\");\n if (!code || !state) {\n throw new STXOAuthException(\"invalid_request\", \"The callback carries no code or no state.\", 400, where);\n }\n const entry = await pending.take(state);\n if (!entry) {\n throw new STXOAuthException(\n \"invalid_state\",\n \"Unknown, used or expired state; start the sign-in again.\",\n 400,\n where,\n );\n }\n return { code, pending: entry };\n}\n\nfunction callbackParams(input: CallbackInput): URLSearchParams {\n if (input instanceof URLSearchParams) return input;\n if (input instanceof URL) return input.searchParams;\n if (typeof input === \"string\") {\n const q = input.includes(\"?\") ? input.slice(input.indexOf(\"?\") + 1) : input;\n return new URLSearchParams(q.split(\"#\", 1)[0]);\n }\n const out = new URLSearchParams();\n for (const [k, v] of Object.entries(input)) if (typeof v === \"string\") out.set(k, v);\n return out;\n}\n\nfunction pathOf(endpoint: string): string {\n try {\n return /^https?:\\/\\//i.test(endpoint) ? new URL(endpoint).pathname : endpoint;\n } catch {\n return endpoint;\n }\n}\n","// OAuth discovery: RFC 8414 authorization-server metadata and RFC 9728\n// protected-resource metadata. The exchange builds `issuer` and every endpoint\n// on the host the request used, so fetch the document from the same base URL\n// you will send members to, and prefer its endpoints over the defaults.\n\nimport { STXAPIException } from \"../exceptions.js\";\nimport { joinUrl, resolveOAuthConfig, WELL_KNOWN, type FetchLike } from \"./endpoints.js\";\n\n/** RFC 8414 authorization-server metadata, as the exchange publishes it. */\nexport interface AuthorizationServerMetadata {\n issuer: string;\n authorization_endpoint: string;\n token_endpoint: string;\n revocation_endpoint?: string;\n introspection_endpoint?: string;\n /** Present only while dynamic client registration is enabled. */\n registration_endpoint?: string;\n scopes_supported?: string[];\n response_types_supported?: string[];\n grant_types_supported?: string[];\n code_challenge_methods_supported?: string[];\n token_endpoint_auth_methods_supported?: string[];\n [k: string]: unknown;\n}\n\n/** RFC 9728 protected-resource metadata. */\nexport interface ProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n scopes_supported?: string[];\n bearer_methods_supported?: string[];\n resource_name?: string;\n [k: string]: unknown;\n}\n\nexport interface DiscoveryOptions {\n fetch?: FetchLike;\n}\n\n/**\n * `GET <baseUrl>/.well-known/oauth-authorization-server`. Throws `STXAPIException`\n * on a non-2xx or a body that is not the metadata document.\n */\nexport async function discoverMetadata(\n baseUrl?: string,\n opts: DiscoveryOptions = {},\n): Promise<AuthorizationServerMetadata> {\n const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.authorizationServer, opts);\n const meta = doc as Partial<AuthorizationServerMetadata>;\n if (\n typeof meta.issuer !== \"string\" ||\n typeof meta.authorization_endpoint !== \"string\" ||\n typeof meta.token_endpoint !== \"string\"\n ) {\n throw httpError(\n 200,\n JSON.stringify(doc),\n WELL_KNOWN.authorizationServer + \" (missing issuer/authorization_endpoint/token_endpoint)\",\n );\n }\n return meta as AuthorizationServerMetadata;\n}\n\n/** `GET <baseUrl>/.well-known/oauth-protected-resource`. */\nexport async function discoverProtectedResource(\n baseUrl?: string,\n opts: DiscoveryOptions = {},\n): Promise<ProtectedResourceMetadata> {\n const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.protectedResource, opts);\n const meta = doc as Partial<ProtectedResourceMetadata>;\n if (typeof meta.resource !== \"string\" || !Array.isArray(meta.authorization_servers)) {\n throw httpError(\n 200,\n JSON.stringify(doc),\n WELL_KNOWN.protectedResource + \" (missing resource/authorization_servers)\",\n );\n }\n return meta as ProtectedResourceMetadata;\n}\n\nasync function fetchWellKnown(baseUrl: string | undefined, path: string, opts: DiscoveryOptions): Promise<unknown> {\n const cfg = resolveOAuthConfig({ baseUrl, fetch: opts.fetch });\n const res = await cfg.fetch(joinUrl(cfg.baseUrl, path), {\n method: \"GET\",\n headers: { Accept: \"application/json\" },\n });\n const text = await res.text();\n if (!res.ok) throw httpError(res.status, text, path);\n try {\n return JSON.parse(text) as unknown;\n } catch {\n throw httpError(res.status, text, path);\n }\n}\n\nfunction httpError(status: number, text: string, path: string): STXAPIException {\n return new STXAPIException(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {\n statusCode: status,\n body: text,\n path,\n });\n}\n","// The pluggable TokenStore: where an OAuth session's tokens live, keyed per\n// member. The SDK ships an in-memory default; production callers implement this\n// over Postgres/Redis/etc. and encrypt at rest. The OAuth session adapter reads\n// and writes tokens ONLY through this interface.\n\nexport interface StoredTokens {\n accessToken: string;\n refreshToken?: string;\n /** Epoch ms when the access token expires, or undefined if unknown. */\n expiresAt?: number;\n /** Space-delimited effective scope granted, if the server returned it. */\n scope?: string;\n}\n\n/**\n * Persistence for one member's tokens. `memberKey` is any stable string the\n * caller uses to identify a member (a user id, a session id, …). Methods may be\n * sync or async.\n */\nexport interface TokenStore {\n get(memberKey: string): Promise<StoredTokens | null> | StoredTokens | null;\n set(memberKey: string, tokens: StoredTokens): Promise<void> | void;\n delete(memberKey: string): Promise<void> | void;\n /**\n * Optional: run `fn` holding an exclusive lock on this member. Implement it\n * when several processes share the store, so only one of them refreshes a\n * member's rotating refresh token at a time (a second, concurrent refresh\n * with the same token trips reuse detection and revokes the grant). Within\n * one process the SDK already single-flights refreshes.\n */\n withLock?<T>(memberKey: string, fn: () => Promise<T>): Promise<T>;\n}\n\n/** Default in-memory store. Fine for scripts, demos and tests; not durable. */\nexport class MemoryTokenStore implements TokenStore {\n private readonly map = new Map<string, StoredTokens>();\n\n get(memberKey: string): StoredTokens | null {\n return this.map.get(memberKey) ?? null;\n }\n\n set(memberKey: string, tokens: StoredTokens): void {\n this.map.set(memberKey, tokens);\n }\n\n delete(memberKey: string): void {\n this.map.delete(memberKey);\n }\n}\n","// The server-side half of an authorization redirect: what was generated when\n// the member was sent to /oauth/authorize (the PKCE verifier, the redirect URI,\n// whatever the app needs to finish the link) keyed by the `state` that comes\n// back on the callback.\n//\n// A state is single use. `take()` returns and removes the entry in one step, so\n// a replayed callback finds nothing. Production callers implement this over\n// their session store or database; the in-memory default suits one process.\n\n/** One sign-in in progress. */\nexport interface PendingAuthorization {\n codeVerifier: string;\n /** The redirect URI sent to /authorize; the code exchange must repeat it. */\n redirectUri: string;\n /** The scope requested, space-delimited. */\n scope?: string;\n /** Epoch ms after which the entry is void. */\n expiresAt: number;\n /** Caller data carried to the callback: a user id, an app id, a return URL. */\n data?: Record<string, unknown>;\n}\n\nexport interface PendingAuthorizationStore {\n put(state: string, pending: PendingAuthorization): Promise<void> | void;\n /** Return and delete the entry for `state`, or null. Single use. */\n take(state: string): Promise<PendingAuthorization | null> | PendingAuthorization | null;\n}\n\n/** In-memory pending store. Expired entries are dropped on access. */\nexport class MemoryPendingAuthorizationStore implements PendingAuthorizationStore {\n private readonly map = new Map<string, PendingAuthorization>();\n\n put(state: string, pending: PendingAuthorization): void {\n this.sweep();\n this.map.set(state, pending);\n }\n\n take(state: string): PendingAuthorization | null {\n const entry = this.map.get(state) ?? null;\n this.map.delete(state);\n if (!entry || entry.expiresAt <= Date.now()) return null;\n return entry;\n }\n\n /** Entries not yet taken or expired. */\n get size(): number {\n this.sweep();\n return this.map.size;\n }\n\n private sweep(): void {\n const now = Date.now();\n for (const [k, v] of this.map) if (v.expiresAt <= now) this.map.delete(k);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAmBO,IAAM,oBAA8C;AAAA,EACzD,WAAW;AAAA,EACX,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,UAAU;AACZ;AAGO,IAAM,aAAa;AAAA,EACxB,qBAAqB;AAAA,EACrB,mBAAmB;AACrB;AASO,SAAS,mBAAmB,OAGjC;AACA,QAAM,MAAO,WAA0E,SAAS,OAAO,CAAC;AACxG,QAAM,OAAO,MAAM,WAAW,IAAI,YAAY,IAAI;AAClD,MAAI,CAAC,KAAM,OAAM,IAAI,mBAAmB,kEAAkE;AAC1G,QAAM,YAAY,MAAM,SAAU,WAAW;AAC7C,MAAI,OAAO,cAAc,YAAY;AACnC,UAAM,IAAI,mBAAmB,qEAAqE;AAAA,EACpG;AACA,SAAO,EAAE,SAAS,WAAW,MAAM,MAAM,IAAI,GAAG,OAAO,UAAU;AACnE;AAGO,SAAS,QAAQ,SAAiB,MAAsB;AAC7D,MAAI,gBAAgB,KAAK,IAAI,EAAG,QAAO;AACvC,SAAO,WAAW,KAAK,WAAW,GAAG,IAAI,OAAO,MAAM;AACxD;;;ACjDO,IAAM,oBAAN,cAAgC,2BAA2B;AAAA;AAAA,EAEvD;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAET,YACE,OACA,kBACA,QACA,UACA,YACA;AACA,UAAM,SAAS,QAAQ,IAAI,MAAM,IAAI,KAAK,GAAG,mBAAmB,KAAK,gBAAgB,KAAK,EAAE,IAAI;AAAA,MAC9F,YAAY;AAAA,MACZ,MAAM;AAAA,IACR,CAAC;AACD,SAAK,QAAQ;AACb,SAAK,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"sources":["../src/oauth/endpoints.ts","../src/oauth/errors.ts","../src/oauth/pkce.ts","../src/oauth/register.ts","../src/oauth/scopes.ts","../src/oauth/client.ts","../src/oauth/metadata.ts","../src/oauth/tokenStore.ts","../src/oauth/pending.ts"],"sourcesContent":["// OAuth endpoint paths and URL helpers. Every path is overridable, and\n// discovery (metadata.ts) supplies absolute URLs that win over these.\n\nimport { baseUrlFor } from \"../config.js\";\nimport { STXConfigException } from \"../exceptions.js\";\n\nexport interface OAuthEndpoints {\n /** Default `/oauth/authorize`. */\n authorize: string;\n /** Default `/oauth/token`. */\n token: string;\n /** Default `/oauth/revoke` (RFC 7009). */\n revoke: string;\n /** Default `/oauth/introspect` (RFC 7662). */\n introspect: string;\n /** Default `/oauth/register` (RFC 7591). */\n register: string;\n}\n\nexport const DEFAULT_ENDPOINTS: Readonly<OAuthEndpoints> = {\n authorize: \"/oauth/authorize\",\n token: \"/oauth/token\",\n revoke: \"/oauth/revoke\",\n introspect: \"/oauth/introspect\",\n register: \"/oauth/register\",\n};\n\n/** RFC 8414 / RFC 9728 discovery documents, relative to the base URL. */\nexport const WELL_KNOWN = {\n authorizationServer: \"/.well-known/oauth-authorization-server\",\n protectedResource: \"/.well-known/oauth-protected-resource\",\n} as const;\n\n/** A `fetch`-compatible function. Defaults to the global `fetch`. */\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\n/**\n * The base URL and fetch for an OAuth call. `baseUrl` is a host or URL (as\n * `STX`'s `host`); it falls back to STX_HOST / STX_BASE_URL.\n */\nexport function resolveOAuthConfig(input: { baseUrl?: string; fetch?: FetchLike }): {\n baseUrl: string;\n fetch: FetchLike;\n} {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n const host = input.baseUrl ?? env.STX_HOST ?? env.STX_BASE_URL;\n if (!host) throw new STXConfigException(\"An OAuth base URL is required. Pass { baseUrl } or set STX_HOST.\");\n const fetchImpl = input.fetch ?? (globalThis.fetch as FetchLike | undefined);\n if (typeof fetchImpl !== \"function\") {\n throw new STXConfigException(\"No fetch implementation available. Use Node 18+, or pass { fetch }.\");\n }\n return { baseUrl: baseUrlFor(null, null, host), fetch: fetchImpl };\n}\n\n/** Build an absolute URL from the base and a path (absolute URLs pass through). */\nexport function joinUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return baseUrl + (path.startsWith(\"/\") ? path : \"/\" + path);\n}\n","// OAuth errors. Both are STXAuthenticationException subclasses, so a caller\n// catching authentication failures from the REST client sees them too.\n\nimport { STXAuthenticationException } from \"../exceptions.js\";\n\n/**\n * An RFC 6749 section 5.2 (or RFC 7591 section 3.2.2) error body from an\n * OAuth protocol endpoint: `{\"error\": \"...\", \"error_description\": \"...\"}`.\n */\nexport class STXOAuthException extends STXAuthenticationException {\n /** The RFC error code: `invalid_client`, `invalid_grant`, `invalid_scope`, ... */\n readonly error: string;\n readonly errorDescription: string | undefined;\n /** The endpoint path that answered. */\n readonly endpoint: string;\n /** Seconds to wait when the endpoint answered 429 with Retry-After. */\n readonly retryAfter: number | undefined;\n\n constructor(\n error: string,\n errorDescription: string | undefined,\n status: number,\n endpoint: string,\n retryAfter?: number,\n ) {\n super(`OAuth ${endpoint} ${status} ${error}${errorDescription ? `: ${errorDescription}` : \"\"}`, {\n statusCode: status,\n path: endpoint,\n });\n this.error = error;\n this.errorDescription = errorDescription;\n this.endpoint = endpoint;\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * The OAuth grant is no longer valid: a refresh was rejected with\n * `invalid_grant` (the member revoked the app, or a retired or reused refresh\n * token tripped reuse detection and the whole grant was revoked). Send the\n * member back through consent.\n */\nexport class STXGrantRevokedException extends STXAuthenticationException {\n constructor(message = \"OAuth grant revoked: the member must re-authorize.\") {\n super(message, { statusCode: 400 });\n }\n}\n","// PKCE (RFC 7636) + state helpers for the OAuth authorization-code flow.\n//\n// Uses the global WebCrypto (`crypto.getRandomValues` / `crypto.subtle`),\n// available on Node 18+, Bun and Deno: no Node-specific imports here.\n\n/** Standard base64url (no padding), the encoding PKCE requires. */\nexport function base64url(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n const b64 = btoa(bin);\n return b64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction randomBytes(n: number): Uint8Array {\n const buf = new Uint8Array(n);\n crypto.getRandomValues(buf);\n return buf;\n}\n\n/**\n * A high-entropy `code_verifier`: 32 random bytes → 43-char base64url string,\n * within the RFC 7636 43–128 character range.\n */\nexport function generateCodeVerifier(): string {\n return base64url(randomBytes(32));\n}\n\n/** The S256 challenge is `base64url(SHA-256(verifier))`. STX rejects `plain`. */\nexport async function codeChallengeS256(verifier: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n return base64url(new Uint8Array(digest));\n}\n\n/** An opaque, unguessable CSRF `state` to tie /authorize to /callback. */\nexport function generateState(): string {\n return base64url(randomBytes(24));\n}\n\nexport interface Pkce {\n codeVerifier: string;\n codeChallenge: string;\n}\n\n/** Generate a verifier + its S256 challenge in one call. */\nexport async function createPkce(): Promise<Pkce> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await codeChallengeS256(codeVerifier);\n return { codeVerifier, codeChallenge };\n}\n","// RFC 7591 dynamic client registration: `POST /oauth/register`.\n//\n// Unauthenticated by design, so an MCP host or a first-time integrator can\n// obtain a client on the spot. A registration is inert until a member consents\n// on `/oauth/authorize`. Rules the exchange enforces (400 on violation):\n// - redirect URIs are absolute `https`, or `http` loopback (localhost,\n// 127.0.0.1, [::1]); no fragment\n// - `token_endpoint_auth_method` is `client_secret_basic` (default, returns a\n// one-time `client_secret`) or `none` (public client: no secret, PKCE only)\n// - `none` cannot be combined with `grant_types: [\"client_credentials\"]`\n// - `grant_types` is a subset of authorization_code / refresh_token /\n// client_credentials; `refresh_token` needs `authorization_code`\n// - `scope` may name member and app scopes; omitted means the exchange's\n// default member list\n\nimport { STXAPIException } from \"../exceptions.js\";\nimport { DEFAULT_ENDPOINTS, joinUrl, resolveOAuthConfig, type FetchLike } from \"./endpoints.js\";\nimport { STXOAuthException } from \"./errors.js\";\n\nexport type TokenEndpointAuthMethod = \"client_secret_basic\" | \"none\";\nexport type GrantType = \"authorization_code\" | \"refresh_token\" | \"client_credentials\";\n\n/** RFC 7591 section 2 client metadata accepted by the exchange. */\nexport interface ClientRegistrationRequest {\n client_name: string;\n redirect_uris: string[];\n /** Space-delimited. Defaults to the exchange's configured member scope list. */\n scope?: string;\n /** Default `client_secret_basic`. `none` registers a public (PKCE-only) client. */\n token_endpoint_auth_method?: TokenEndpointAuthMethod;\n /** Default `[\"authorization_code\", \"refresh_token\"]`. */\n grant_types?: GrantType[];\n /** Only `[\"code\"]` is supported. */\n response_types?: [\"code\"];\n client_uri?: string;\n logo_uri?: string;\n software_id?: string;\n software_version?: string;\n}\n\n/** RFC 7591 section 3.2.1 client information response. */\nexport interface ClientRegistration {\n client_id: string;\n /** Unix seconds. */\n client_id_issued_at: number;\n /** Present for a confidential client only; shown once, never recoverable. */\n client_secret?: string;\n /** `0` means never. Present with `client_secret`. */\n client_secret_expires_at?: number;\n client_name: string;\n redirect_uris: string[];\n /** The stored scopes, space-delimited, defaults applied. */\n scope: string;\n grant_types: GrantType[];\n response_types: string[];\n token_endpoint_auth_method: TokenEndpointAuthMethod;\n client_uri?: string;\n logo_uri?: string;\n software_id?: string;\n software_version?: string;\n}\n\nexport interface RegisterClientOptions {\n baseUrl?: string;\n /** Absolute `registration_endpoint` from discovery, or a path. Default `/oauth/register`. */\n registrationEndpoint?: string;\n fetch?: FetchLike;\n}\n\n/**\n * Register an OAuth client. Resolves with the client information on `201`.\n * Throws `STXOAuthException` with the RFC error code on `400`\n * (`invalid_redirect_uri`, `invalid_client_metadata`) and `429`\n * (`rate_limited`, with `retryAfter` seconds); `STXAPIException` on `404`\n * (registration disabled) and anything else.\n */\nexport async function registerClient(\n request: ClientRegistrationRequest,\n opts: RegisterClientOptions = {},\n): Promise<ClientRegistration> {\n const cfg = resolveOAuthConfig({ baseUrl: opts.baseUrl, fetch: opts.fetch });\n const endpoint = opts.registrationEndpoint ?? DEFAULT_ENDPOINTS.register;\n const url = joinUrl(cfg.baseUrl, endpoint);\n const path = new URL(url).pathname;\n\n const res = await cfg.fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", Accept: \"application/json\" },\n body: JSON.stringify(request),\n });\n const text = await res.text();\n\n if (res.status === 201 || res.status === 200) {\n let doc: unknown;\n try {\n doc = JSON.parse(text);\n } catch {\n throw httpError(res.status, text, path);\n }\n const reg = doc as Partial<ClientRegistration>;\n if (typeof reg.client_id !== \"string\" || reg.client_id === \"\") {\n throw httpError(res.status, text, path + \" (missing client_id)\");\n }\n return reg as ClientRegistration;\n }\n\n const err = rfcError(text);\n if (err) {\n const retryAfter = Number(res.headers.get(\"retry-after\"));\n throw new STXOAuthException(\n err.error,\n err.error_description,\n res.status,\n path,\n Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : undefined,\n );\n }\n throw httpError(res.status, text, path);\n}\n\n/** Parse an RFC 6749 section 5.2 error body, or null if the body is not one. */\nexport function rfcError(text: string): { error: string; error_description?: string } | null {\n try {\n const obj = JSON.parse(text) as Record<string, unknown>;\n if (typeof obj.error !== \"string\") return null;\n return {\n error: obj.error,\n error_description: typeof obj.error_description === \"string\" ? obj.error_description : undefined,\n };\n } catch {\n return null;\n }\n}\n\nfunction httpError(status: number, text: string, path: string): STXAPIException {\n return new STXAPIException(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {\n statusCode: status,\n body: text,\n path,\n });\n}\n","// The STX OAuth scope vocabulary, as the exchange defines it (the exchange is\n// the source of truth): two disjoint vocabularies, member\n// scopes (`resource.action`, granted to a user token through consent) and app\n// scopes (carried by a `client_credentials` app token, no user, no consent).\n//\n// No scope moves money. `transfers.read` is a read of deposit/withdrawal\n// history; there is no scope that initiates, approves or cancels a transfer.\n\n/** Member scopes, in the exchange's canonical order. */\nexport const MemberScopes = {\n /** Who the member is: `me`, `GET /api/v1/me`. */\n PROFILE_READ: \"profile.read\",\n /** Cash balance: `account`, `GET /api/v1/account/balance`, `balances:` channel. */\n BALANCE_READ: \"balance.read\",\n /** Positions, settlements, loyalty/fee/adjustment ledgers, `positions:`/`settlements:`. */\n PORTFOLIO_READ: \"portfolio.read\",\n /** Order and fill history, `orders:`/`fills:` channels. */\n ORDERS_READ: \"orders.read\",\n /** Deposit and withdrawal history (read only). */\n TRANSFERS_READ: \"transfers.read\",\n /** Place and cancel orders; arm `cancel_on_disconnect`. */\n ORDERS_WRITE: \"orders.write\",\n /** Accept the terms and conditions. */\n TERMS_WRITE: \"terms.write\",\n} as const;\nexport type MemberScope = (typeof MemberScopes)[keyof typeof MemberScopes];\n\n/** App (machine) scopes for `client_credentials` tokens. */\nexport const AppScopes = {\n /** The market catalog (`GET /api/v1/markets`) and the market data channels. */\n MARKET_DATA: \"market_data\",\n /** The event catalog (`GET /api/v1/events`) and the `events` channel. */\n EVENTS: \"events\",\n} as const;\nexport type AppScope = (typeof AppScopes)[keyof typeof AppScopes];\n\n/** Both vocabularies under one name, for callers that do not care which. */\nexport const Scopes = { ...MemberScopes, ...AppScopes } as const;\nexport type Scope = MemberScope | AppScope;\n\n/** Every member scope, canonical order. */\nexport const ALL_MEMBER_SCOPES: readonly MemberScope[] = Object.values(MemberScopes);\n/** Every app scope, canonical order. */\nexport const ALL_APP_SCOPES: readonly AppScope[] = Object.values(AppScopes);\n\n/**\n * Pre-`resource.action` names the exchange accepts for one release and\n * canonicalises on entry. A token minted by an older exchange may still report\n * them in its `scope` string.\n */\nexport const LEGACY_SCOPES: Readonly<Record<string, MemberScope>> = {\n identity: MemberScopes.PROFILE_READ,\n balance: MemberScopes.BALANCE_READ,\n portfolio: MemberScopes.PORTFOLIO_READ,\n history: MemberScopes.ORDERS_READ,\n transfers: MemberScopes.TRANSFERS_READ,\n trade: MemberScopes.ORDERS_WRITE,\n onboarding: MemberScopes.TERMS_WRITE,\n};\n\n/** The current name for a scope; legacy names map forward, anything else passes through. */\nexport function canonicalScope(scope: string): string {\n return LEGACY_SCOPES[scope] ?? scope;\n}\n\n/** Split a space-delimited `scope` string into canonical, de-duplicated scopes. */\nexport function parseScopes(scope: string | null | undefined): string[] {\n if (!scope) return [];\n const out: string[] = [];\n for (const raw of scope.split(/\\s+/)) {\n if (!raw) continue;\n const s = canonicalScope(raw);\n if (!out.includes(s)) out.push(s);\n }\n return out;\n}\n\n/** Join scopes into the space-delimited wire form. */\nexport function formatScopes(scopes: readonly string[]): string {\n return scopes.join(\" \");\n}\n\nexport function isMemberScope(scope: string): scope is MemberScope {\n return (ALL_MEMBER_SCOPES as readonly string[]).includes(scope);\n}\n\nexport function isAppScope(scope: string): scope is AppScope {\n return (ALL_APP_SCOPES as readonly string[]).includes(scope);\n}\n","// The `oauth` auth path: OAuth 2.0 for ISVs acting on a member's behalf\n// (authorization code + PKCE, refresh with rotation, revoke, introspect) and for\n// an app acting as itself (`client_credentials` app tokens for the public\n// catalog and market feeds). See the exchange's docs/oauth_isv_plan.md.\n//\n// This module has three layers:\n// 1. `OAuthClient`: stateless flow machinery. Build the authorize URL,\n// exchange a code, refresh, revoke, mint an app token. Works for a\n// confidential client (client_secret_basic) and a public one (no secret,\n// `client_id` in the form, PKCE is the proof).\n// 2. `AppTokenProvider`: a cached, self-renewing client_credentials token.\n// 3. Adapters (`bearer` / `session` / `app`) that plug a token source into\n// `STX` (as its `auth` option) and `STXWebSocket`, and the\n// `memberClient()` / `appClient()` shortcuts that build that `STX`.\n//\n// One `OAuthClient` is one registered app. A process serving several apps (a\n// brand and its sister brand, each with its own client id) makes one per app;\n// nothing is shared between them.\n\nimport type { AuthProvider, AuthRequest, WebSocketAuthContext } from \"../auth.js\";\nimport { STX, type STXOptions } from \"../client.js\";\nimport { STXConfigException } from \"../exceptions.js\";\nimport { DEFAULT_ENDPOINTS, joinUrl, resolveOAuthConfig, type FetchLike } from \"./endpoints.js\";\nimport { STXGrantRevokedException, STXOAuthException } from \"./errors.js\";\nimport type { AuthorizationServerMetadata } from \"./metadata.js\";\nimport type { PendingAuthorization, PendingAuthorizationStore } from \"./pending.js\";\nimport { createPkce, generateState, type Pkce } from \"./pkce.js\";\nimport { rfcError } from \"./register.js\";\nimport { formatScopes, parseScopes } from \"./scopes.js\";\nimport type { StoredTokens, TokenStore } from \"./tokenStore.js\";\n\n/** Parsed OAuth token response (RFC 6749 section 5.1). */\nexport interface TokenSet {\n accessToken: string;\n /** Absent on a `client_credentials` app token. */\n refreshToken?: string;\n tokenType?: string;\n /** Lifetime of the access token in seconds. */\n expiresIn?: number;\n /** Absolute epoch-ms expiry derived from `expiresIn`. */\n expiresAt?: number;\n /** Space-delimited effective scope after STX's narrowing. */\n scope?: string;\n}\n\ntype OAuthEndpoints = Pick<import(\"./endpoints.js\").OAuthEndpoints, \"authorize\" | \"token\" | \"revoke\" | \"introspect\">;\n\nexport interface OAuthClientOptions {\n /** The exchange's host or URL, as `STX`'s `host`. Defaults to `STX_HOST`. */\n baseUrl?: string;\n /** Your app's client id. */\n clientId: string;\n /**\n * The client secret for a confidential client (`client_secret_basic`). Omit\n * for a public client registered with `token_endpoint_auth_method: none`: it\n * then identifies with `client_id` in the form and PKCE is its proof. A public\n * client cannot use `clientCredentials()`.\n */\n clientSecret?: string;\n /** The redirect URI registered with STX (exact-matched). Required for the code flow. */\n redirectUri?: string;\n /** Default scopes to request, space-delimited or as a list. */\n scope?: string | readonly string[];\n /** Endpoint overrides; absolute URLs (from discovery) or paths. */\n endpoints?: Partial<OAuthEndpoints>;\n fetch?: FetchLike;\n}\n\n/** Options for a store-backed member session adapter. */\nexport interface SessionOptions {\n /** Refresh this many ms before the access token expires. Default 30000. */\n skewMs?: number;\n /** Called with the new tokens after every successful refresh (already persisted). */\n onRefresh?: (tokens: StoredTokens) => void | Promise<void>;\n /** Called once when the grant is found revoked; the store entry is already deleted. */\n onGrantRevoked?: (err: STXGrantRevokedException) => void | Promise<void>;\n}\n\n/** `STX` options for the `memberClient()` / `appClient()` shortcuts; host and auth come from the OAuth client. */\nexport type OAuthRestOptions = Omit<\n STXOptions,\n \"auth\" | \"keyId\" | \"privateKey\" | \"signer\" | \"profile\" | \"region\" | \"env\" | \"host\"\n>;\n\n/** What `completeAuthorization()` returns. */\nexport interface CompletedAuthorization {\n tokens: TokenSet;\n /** The granted scopes, canonical names. May be narrower than requested. */\n scopes: string[];\n /** The `data` passed to `beginAuthorization()`. */\n data: Record<string, unknown> | undefined;\n /** The member key the tokens were stored under, when a store was given. */\n memberKey: string | undefined;\n}\n\n/** Where `completeAuthorization()` / `redeemAuthorization()` save the tokens. */\nexport interface RedeemOptions {\n store?: TokenStore;\n /** A key, or a function of the `data` given to `beginAuthorization()`. */\n memberKey?: string | ((data: Record<string, unknown> | undefined) => string);\n}\n\n/** A validated callback: the code and the pending sign-in its state named (now consumed). */\nexport interface ReadCallback {\n code: string;\n pending: PendingAuthorization;\n}\n\n/** The query of an OAuth callback, in any of the shapes a server framework hands over. */\nexport type CallbackInput = string | URL | URLSearchParams | Record<string, string | undefined | null>;\n\n/** The prepared inputs for one authorization redirect. */\nexport interface Authorization {\n /** The full `/oauth/authorize` URL to send the member's browser to. */\n url: string;\n /** The `state` to store against this pending sign-in and verify on return. */\n state: string;\n /** The PKCE verifier to keep server-side and present at code exchange. */\n codeVerifier: string;\n /** The PKCE challenge that was embedded in `url`. */\n codeChallenge: string;\n}\n\nexport interface AuthorizationParams {\n scope?: string | readonly string[];\n state?: string;\n /** `none` for a silent background reconnect (RFC: prompt=none). */\n prompt?: \"none\" | \"login\" | \"consent\";\n redirectUri?: string;\n /** Extra authorize params, passed through verbatim. */\n extraParams?: Record<string, string>;\n}\n\nexport class OAuthClient {\n readonly baseUrl: string;\n readonly clientId: string;\n private readonly clientSecret?: string;\n readonly redirectUri?: string;\n readonly scope?: string;\n readonly endpoints: OAuthEndpoints;\n private readonly fetch: FetchLike;\n /**\n * In-flight refreshes per token store and member, shared by every session\n * adapter this client makes, so a burst of 401s across requests refreshes\n * once. Two refreshes of one rotating token would trip reuse detection and\n * revoke the grant.\n */\n private readonly refreshes = new WeakMap<TokenStore, Map<string, Promise<StoredTokens | null>>>();\n /** One cached app token per requested scope. */\n private readonly appTokens = new Map<string, AppTokenProvider>();\n\n constructor(opts: OAuthClientOptions) {\n const cfg = resolveOAuthConfig({ baseUrl: opts.baseUrl, fetch: opts.fetch });\n this.baseUrl = cfg.baseUrl;\n this.fetch = cfg.fetch;\n this.clientId = opts.clientId;\n this.clientSecret = opts.clientSecret || undefined;\n this.redirectUri = opts.redirectUri;\n this.scope = normalizeScope(opts.scope);\n this.endpoints = {\n authorize: opts.endpoints?.authorize ?? DEFAULT_ENDPOINTS.authorize,\n token: opts.endpoints?.token ?? DEFAULT_ENDPOINTS.token,\n revoke: opts.endpoints?.revoke ?? DEFAULT_ENDPOINTS.revoke,\n introspect: opts.endpoints?.introspect ?? DEFAULT_ENDPOINTS.introspect,\n };\n }\n\n /**\n * Build a client from a discovered RFC 8414 document, so every endpoint is the\n * one the exchange advertised on the host you asked. The base URL is the\n * issuer unless overridden.\n */\n static fromMetadata(metadata: AuthorizationServerMetadata, opts: Omit<OAuthClientOptions, \"endpoints\">): OAuthClient {\n return new OAuthClient({\n ...opts,\n baseUrl: opts.baseUrl ?? metadata.issuer,\n endpoints: {\n authorize: metadata.authorization_endpoint,\n token: metadata.token_endpoint,\n ...(metadata.revocation_endpoint ? { revoke: metadata.revocation_endpoint } : {}),\n ...(metadata.introspection_endpoint ? { introspect: metadata.introspection_endpoint } : {}),\n },\n });\n }\n\n /** True for a public client (no secret): PKCE-only, no app tokens. */\n get isPublic(): boolean {\n return this.clientSecret === undefined;\n }\n\n // ---- Step 1+2: prepare the authorize redirect ---------------------------\n\n /**\n * Create a fresh PKCE pair (S256) + `state` and build the authorize URL in\n * one call. Persist `state` and `codeVerifier` against the member's pending\n * sign-in and verify `state` on the callback.\n */\n async authorizationUrl(params: AuthorizationParams = {}): Promise<Authorization> {\n const pkce: Pkce = await createPkce();\n const state = params.state ?? generateState();\n const url = this.buildAuthorizeUrl({\n state,\n codeChallenge: pkce.codeChallenge,\n scope: params.scope,\n prompt: params.prompt,\n redirectUri: params.redirectUri,\n extraParams: params.extraParams,\n });\n return { url, state, codeVerifier: pkce.codeVerifier, codeChallenge: pkce.codeChallenge };\n }\n\n /** Alias of `authorizationUrl()` kept from 0.1. */\n createAuthorization(params: AuthorizationParams = {}): Promise<Authorization> {\n return this.authorizationUrl(params);\n }\n\n /**\n * Start a sign-in: create PKCE + state, remember them (and `data`) in\n * `pending` under the state, and return the authorize URL to redirect to.\n * Finish with `completeAuthorization()` on the callback.\n */\n async beginAuthorization(\n pending: PendingAuthorizationStore,\n params: AuthorizationParams & { data?: Record<string, unknown>; ttlMs?: number } = {},\n ): Promise<Authorization> {\n const redirectUri = params.redirectUri ?? this.redirectUri;\n if (!redirectUri) throw new STXConfigException(\"redirectUri is required to build an authorize URL.\");\n const auth = await this.authorizationUrl({ ...params, redirectUri });\n await pending.put(auth.state, {\n codeVerifier: auth.codeVerifier,\n redirectUri,\n scope: normalizeScope(params.scope) ?? this.scope,\n expiresAt: Date.now() + (params.ttlMs ?? 10 * 60_000),\n data: params.data,\n });\n return auth;\n }\n\n /**\n * Finish a sign-in from the callback's query. Checks for an `error` from\n * the exchange (the member denied consent: `access_denied`), consumes the\n * `state` (single use; unknown or expired throws `invalid_state`), exchanges\n * the code with the stored PKCE verifier and, when `store` is given, saves\n * the tokens under `memberKey` (a string, or a function of the `data` passed\n * to `beginAuthorization()`).\n *\n * Every failure is an `STXOAuthException` whose `error` says which:\n * `access_denied` and friends from the redirect, `invalid_request` (no code\n * or state), `invalid_state`, or the token endpoint's own (`invalid_grant`\n * for a used, expired or mismatched code).\n */\n async completeAuthorization(\n pending: PendingAuthorizationStore,\n callback: CallbackInput,\n opts: RedeemOptions = {},\n ): Promise<CompletedAuthorization> {\n return this.redeemAuthorization(await readCallback(pending, callback, this.endpoints.authorize), opts);\n }\n\n /**\n * The second half of `completeAuthorization()`: exchange a callback already\n * read with `readCallback()`. Use the pair when one callback URL serves\n * several apps and the app is only known from the pending entry's `data`.\n */\n async redeemAuthorization(callback: ReadCallback, opts: RedeemOptions = {}): Promise<CompletedAuthorization> {\n const entry = callback.pending;\n const tokens = await this.exchangeCode({\n code: callback.code,\n codeVerifier: entry.codeVerifier,\n redirectUri: entry.redirectUri,\n });\n let memberKey: string | undefined;\n if (opts.store) {\n memberKey = typeof opts.memberKey === \"function\" ? opts.memberKey(entry.data) : opts.memberKey;\n if (!memberKey) throw new STXConfigException(\"Pass memberKey along with store.\");\n await opts.store.set(memberKey, tokenSetToStored(tokens));\n }\n return { tokens, scopes: parseScopes(tokens.scope), data: entry.data, memberKey };\n }\n\n /** Build the authorize URL from a challenge you already have. */\n buildAuthorizeUrl(params: {\n state: string;\n codeChallenge: string;\n scope?: string | readonly string[];\n prompt?: \"none\" | \"login\" | \"consent\";\n redirectUri?: string;\n extraParams?: Record<string, string>;\n }): string {\n const redirectUri = params.redirectUri ?? this.redirectUri;\n if (!redirectUri) {\n throw new STXConfigException(\"redirectUri is required to build an authorize URL.\");\n }\n const url = new URL(joinUrl(this.baseUrl, this.endpoints.authorize));\n const search: Record<string, string> = {\n response_type: \"code\",\n client_id: this.clientId,\n redirect_uri: redirectUri,\n scope: normalizeScope(params.scope) ?? this.scope ?? \"\",\n code_challenge: params.codeChallenge,\n code_challenge_method: \"S256\",\n state: params.state,\n ...(params.prompt ? { prompt: params.prompt } : {}),\n ...(params.extraParams ?? {}),\n };\n url.search = new URLSearchParams(search).toString();\n return url.toString();\n }\n\n // ---- Step 4: exchange the code ------------------------------------------\n\n /** Exchange an authorization code for tokens, proving PKCE with the verifier. */\n exchangeCode(args: {\n code: string;\n codeVerifier: string;\n redirectUri?: string;\n }): Promise<TokenSet> {\n const redirectUri = args.redirectUri ?? this.redirectUri;\n if (!redirectUri) {\n throw new STXConfigException(\"redirectUri is required to exchange a code.\");\n }\n return this.postToken(\n new URLSearchParams({\n grant_type: \"authorization_code\",\n code: args.code,\n redirect_uri: redirectUri,\n code_verifier: args.codeVerifier,\n }),\n );\n }\n\n // ---- Refresh (with rotation) --------------------------------------------\n\n /**\n * Trade a refresh token for a fresh access/refresh pair. STX ROTATES the\n * refresh token, so the caller MUST persist whatever comes back. A rejected\n * refresh (`invalid_grant`) means the grant was revoked, including STX's\n * reuse detection tripping on a replayed/retired token, and surfaces as\n * `STXGrantRevokedException`.\n */\n refreshToken(refreshToken: string): Promise<TokenSet> {\n return this.postToken(\n new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n }),\n );\n }\n\n /** Alias of `refreshToken()` kept from 0.1. */\n refresh(refreshToken: string): Promise<TokenSet> {\n return this.refreshToken(refreshToken);\n }\n\n // ---- client_credentials (app tokens) ------------------------------------\n\n /**\n * Mint an APP token (RFC 6749 section 4.4): the client acting as itself, no\n * member, no consent, no refresh token. Scoped to app scopes only\n * (`market_data`, `events`); omit `scope` for every app scope the client is\n * allowed. Requires a confidential client. For a cached, self-renewing\n * token use `appToken()`.\n */\n clientCredentials(scope?: string | readonly string[]): Promise<TokenSet> {\n if (this.isPublic) {\n throw new STXConfigException(\n \"client_credentials needs a client secret; a public client cannot mint an app token.\",\n );\n }\n const body = new URLSearchParams({ grant_type: \"client_credentials\" });\n const s = normalizeScope(scope);\n if (s) body.set(\"scope\", s);\n return this.postToken(body);\n }\n\n /**\n * A cached `client_credentials` token that re-mints itself before expiry.\n * The same scope returns the same provider, so every `STX` client and socket\n * built from this OAuth client shares one token.\n */\n appToken(scope?: string | readonly string[]): AppTokenProvider {\n const key = normalizeScope(scope) ?? \"\";\n let provider = this.appTokens.get(key);\n if (!provider) {\n provider = new AppTokenProvider(this, scope);\n this.appTokens.set(key, provider);\n }\n return provider;\n }\n\n // ---- Revoke (RFC 7009) --------------------------------------------------\n\n /** Revoke a token (either kind kills the pair). Always resolves on a 200. */\n async revoke(token: string, tokenTypeHint?: \"access_token\" | \"refresh_token\"): Promise<void> {\n const body = new URLSearchParams({ token });\n if (tokenTypeHint) body.set(\"token_type_hint\", tokenTypeHint);\n const res = await this.fetch(joinUrl(this.baseUrl, this.endpoints.revoke), {\n method: \"POST\",\n headers: this.formHeaders(),\n body: this.withClientId(body).toString(),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n throw this.oauthError(res.status, text, this.endpoints.revoke);\n }\n }\n\n /**\n * Unlink a member: revoke their grant at the exchange (best effort) and\n * delete their tokens from `store`. Resolves true if the exchange confirmed\n * the revoke, false if it could not be reached or refused; the local tokens\n * are deleted either way.\n */\n async unlink(store: TokenStore, memberKey: string): Promise<boolean> {\n const tokens = await store.get(memberKey);\n let revoked = false;\n try {\n if (tokens?.refreshToken) {\n await this.revoke(tokens.refreshToken, \"refresh_token\");\n revoked = true;\n } else if (tokens?.accessToken) {\n await this.revoke(tokens.accessToken, \"access_token\");\n revoked = true;\n }\n } catch {\n revoked = false;\n } finally {\n await store.delete(memberKey);\n }\n return revoked;\n }\n\n // ---- Introspect (RFC 7662) ----------------------------------------------\n\n /** Report a token's active state + scope. Confidential clients only. */\n async introspect(\n token: string,\n ): Promise<{ active: boolean; scope?: string; client_id?: string; [k: string]: unknown }> {\n const res = await this.fetch(joinUrl(this.baseUrl, this.endpoints.introspect), {\n method: \"POST\",\n headers: this.formHeaders(),\n body: new URLSearchParams({ token }).toString(),\n });\n const text = await res.text();\n if (!res.ok) throw this.oauthError(res.status, text, this.endpoints.introspect);\n return parseJsonBody(text, res.status, this.endpoints.introspect) as { active: boolean };\n }\n\n // ---- Adapter factories --------------------------------------------------\n\n /** A simple Bearer adapter around a known access token (no refresh). */\n bearer(accessToken: string): OAuthBearerAuth {\n return new OAuthBearerAuth(accessToken);\n }\n\n /**\n * A store-backed adapter that reads the member's tokens, attaches the Bearer\n * header, refreshes proactively / on 401 with rotation, and clears the store\n * (throwing `STXGrantRevokedException`) if the grant was revoked.\n */\n session(store: TokenStore, memberKey: string, opts: SessionOptions = {}): OAuthSessionAuth {\n return new OAuthSessionAuth(this, store, memberKey, opts);\n }\n\n /**\n * An adapter authenticated as the APP (client_credentials): the market\n * catalog (`markets()`, `events()`) and the market data channels. Re-mints\n * before expiry, once on a 401, and fresh on every socket (re)connect.\n */\n app(scope?: string | readonly string[]): OAuthAppAuth {\n return new OAuthAppAuth(this.appToken(scope));\n }\n\n /**\n * An `STX` client acting for one member, over `session(store,\n * memberKey)`: every `/api/v1` method (balance, positions, fills, orders,\n * place and cancel) with the Bearer token attached, refreshed before expiry\n * and on a 401, and `client.websocket()` for the member's channels over the\n * `x-stx-oauth-token` handshake.\n */\n memberClient(store: TokenStore, memberKey: string, opts: OAuthRestOptions & { session?: SessionOptions } = {}): STX {\n const { session, ...rest } = opts;\n return new STX({\n ...rest,\n host: this.baseUrl,\n fetch: rest.fetch ?? this.fetch,\n auth: this.session(store, memberKey, session),\n });\n }\n\n /**\n * An `STX` client acting as the app (client_credentials): the public\n * catalog (`markets()`, `events()`) and, through `websocket()`, the public\n * market channels. Scope defaults to every app scope the client may hold.\n */\n appClient(scope?: string | readonly string[], opts: OAuthRestOptions = {}): STX {\n return new STX({ ...opts, host: this.baseUrl, fetch: opts.fetch ?? this.fetch, auth: this.app(scope) });\n }\n\n /** @internal The in-flight refresh map for one store; see `OAuthSessionAuth`. */\n _refreshesFor(store: TokenStore): Map<string, Promise<StoredTokens | null>> {\n let map = this.refreshes.get(store);\n if (!map) {\n map = new Map();\n this.refreshes.set(store, map);\n }\n return map;\n }\n\n // ---- internals ----------------------------------------------------------\n\n /** `client_secret_basic` header, or undefined for a public client. */\n basicAuthHeader(): string | undefined {\n if (this.clientSecret === undefined) return undefined;\n const raw = `${this.clientId}:${this.clientSecret}`;\n return \"Basic \" + Buffer.from(raw).toString(\"base64\");\n }\n\n private formHeaders(): Record<string, string> {\n const basic = this.basicAuthHeader();\n return {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n ...(basic ? { Authorization: basic } : {}),\n };\n }\n\n /** A public client identifies with `client_id` in the form (RFC 6749 section 4.1.3). */\n private withClientId(body: URLSearchParams): URLSearchParams {\n if (this.isPublic) body.set(\"client_id\", this.clientId);\n return body;\n }\n\n private async postToken(body: URLSearchParams): Promise<TokenSet> {\n const res = await this.fetch(joinUrl(this.baseUrl, this.endpoints.token), {\n method: \"POST\",\n headers: this.formHeaders(),\n body: this.withClientId(body).toString(),\n });\n\n const text = await res.text();\n if (!res.ok) {\n const err = rfcError(text);\n // A rejected refresh is a dead grant (revoked, or reuse detection fired).\n if (res.status === 400 && err?.error === \"invalid_grant\" && body.get(\"grant_type\") === \"refresh_token\") {\n throw new STXGrantRevokedException(\n err.error_description\n ? `OAuth grant revoked: ${err.error_description}. The member must re-authorize.`\n : undefined,\n );\n }\n throw this.oauthError(res.status, text, this.endpoints.token);\n }\n return parseTokenResponse(text);\n }\n\n private oauthError(status: number, text: string, endpoint: string): STXOAuthException {\n const err = rfcError(text);\n const path = pathOf(endpoint);\n if (err) return new STXOAuthException(err.error, err.error_description, status, path);\n return new STXOAuthException(\"http_error\", text.slice(0, 300) || undefined, status, path);\n }\n}\n\n/** Parse a 2xx body as JSON; a body that is not JSON is `STXOAuthException(\"invalid_response\")`. */\nfunction parseJsonBody(text: string, status: number, endpoint: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n throw new STXOAuthException(\"invalid_response\", \"Response body is not JSON.\", status, pathOf(endpoint));\n }\n}\n\n/** Parse and normalize an RFC 6749 section 5.1 token response. */\nexport function parseTokenResponse(json: string | unknown): TokenSet {\n const parsed = typeof json === \"string\" ? parseJsonBody(json, 200, DEFAULT_ENDPOINTS.token) : json;\n const obj = parsed as Record<string, unknown>;\n if (!obj || typeof obj.access_token !== \"string\" || obj.access_token === \"\") {\n throw new STXOAuthException(\n \"invalid_response\",\n \"Token response missing access_token.\",\n 200,\n DEFAULT_ENDPOINTS.token,\n );\n }\n const set: TokenSet = { accessToken: obj.access_token };\n if (typeof obj.refresh_token === \"string\") set.refreshToken = obj.refresh_token;\n if (typeof obj.token_type === \"string\") set.tokenType = obj.token_type;\n if (typeof obj.expires_in === \"number\") {\n set.expiresIn = obj.expires_in;\n set.expiresAt = Date.now() + obj.expires_in * 1000;\n }\n if (typeof obj.scope === \"string\") set.scope = obj.scope;\n return set;\n}\n\n/** Convert a TokenSet into the shape the TokenStore persists. */\nexport function tokenSetToStored(set: TokenSet): StoredTokens {\n return {\n accessToken: set.accessToken,\n refreshToken: set.refreshToken,\n expiresAt: set.expiresAt,\n scope: set.scope,\n };\n}\n\n// ---- App tokens -------------------------------------------------------------\n\n/**\n * A cached `client_credentials` token. Mints on first use, re-mints\n * proactively when within `skewMs` of expiry (default 60s), dedupes\n * concurrent mints, and can be invalidated after a 401 so the next call mints\n * fresh. A token with no `expires_in` is treated as non-expiring; the 401\n * safety net still covers it.\n */\nexport class AppTokenProvider {\n private cached: { accessToken: string; expiresAt: number; scope?: string } | null = null;\n private inflight: Promise<string> | null = null;\n readonly skewMs: number;\n\n constructor(\n private readonly client: OAuthClient,\n private readonly scope?: string | readonly string[],\n opts: { skewMs?: number } = {},\n ) {\n this.skewMs = opts.skewMs ?? 60_000;\n }\n\n /** A valid access token, minting if missing or near expiry. */\n async get(): Promise<string> {\n const c = this.cached;\n if (c && Date.now() < c.expiresAt - this.skewMs) return c.accessToken;\n if (this.inflight) return this.inflight;\n this.inflight = this.mint().finally(() => {\n this.inflight = null;\n });\n return this.inflight;\n }\n\n /** Drop the cache so the next `get()` mints. Call after a 401. */\n invalidate(): void {\n this.cached = null;\n }\n\n /** Invalidate and mint now. Use before a socket reconnect. */\n fresh(): Promise<string> {\n this.invalidate();\n return this.get();\n }\n\n /** The effective scope the exchange granted the current token, if minted. */\n get grantedScope(): string | undefined {\n return this.cached?.scope;\n }\n\n private async mint(): Promise<string> {\n const set = await this.client.clientCredentials(this.scope);\n this.cached = {\n accessToken: set.accessToken,\n expiresAt: set.expiresAt ?? Number.POSITIVE_INFINITY,\n scope: set.scope,\n };\n return set.accessToken;\n }\n}\n\n// ---- Adapters --------------------------------------------------------------\n\n/** Bearer-token adapter with no refresh. Good for one-shot scripts. */\nexport class OAuthBearerAuth implements AuthProvider {\n readonly kind = \"oauth\";\n constructor(private accessToken: string) {}\n\n setAccessToken(token: string): void {\n this.accessToken = token;\n }\n\n async authHeaders(): Promise<Record<string, string>> {\n return { Authorization: `Bearer ${this.accessToken}` };\n }\n\n async websocketHeaders(): Promise<Record<string, string>> {\n // The OAuth socket handshake carries the token in a custom header, which a\n // browser WebSocket cannot set, hence the `ws` package.\n return { \"x-stx-oauth-token\": this.accessToken };\n }\n}\n\n/**\n * Store-backed OAuth adapter. Attaches the current member's access token,\n * refreshes proactively when it is near expiry and on a 401 (rotating and\n * persisting the new refresh token every time), and treats a revoked grant as\n * terminal: the store entry is deleted and `STXGrantRevokedException` thrown.\n *\n * Refreshes are single-flight per (store, member) across every adapter the\n * same `OAuthClient` makes, so concurrent requests for one member refresh\n * once. A 401 on a token another request has already replaced is retried with\n * the stored token, without a second refresh. Across processes, give the store\n * a `withLock()` so only one replica refreshes a member at a time.\n */\nexport class OAuthSessionAuth implements AuthProvider {\n readonly kind = \"oauth\";\n /** Ms of slack before expiry at which to refresh proactively. */\n readonly skewMs: number;\n /** The access token last put on the wire, to tell a stale 401 from a dead token. */\n private lastSent: string | undefined;\n\n constructor(\n private readonly client: OAuthClient,\n private readonly store: TokenStore,\n readonly memberKey: string,\n private readonly opts: SessionOptions = {},\n ) {\n this.skewMs = opts.skewMs ?? 30_000;\n }\n\n private async load(): Promise<StoredTokens | null> {\n return (await this.store.get(this.memberKey)) ?? null;\n }\n\n /** The member's current tokens, refreshed first if at or near expiry. */\n async tokens(): Promise<StoredTokens> {\n let tokens = await this.load();\n if (!tokens) {\n throw new STXConfigException(`No tokens stored for member \"${this.memberKey}\". Complete the OAuth flow first.`);\n }\n if (tokens.refreshToken && tokens.expiresAt !== undefined && tokens.expiresAt - Date.now() <= this.skewMs) {\n const refreshed = await this.refresh(tokens.refreshToken);\n if (refreshed) tokens = refreshed;\n }\n return tokens;\n }\n\n /** The granted scopes of the stored tokens, canonical names. */\n async scopes(): Promise<string[]> {\n return parseScopes((await this.load())?.scope);\n }\n\n async authHeaders(_request?: AuthRequest): Promise<Record<string, string>> {\n const tokens = await this.tokens();\n this.lastSent = tokens.accessToken;\n return { Authorization: `Bearer ${tokens.accessToken}` };\n }\n\n async onUnauthorized(): Promise<boolean> {\n const tokens = await this.load();\n if (!tokens) return false;\n // Another request (or replica) already rotated the pair: retry with it.\n if (this.lastSent !== undefined && tokens.accessToken !== this.lastSent) return true;\n if (!tokens.refreshToken) return false;\n const refreshed = await this.refresh(tokens.refreshToken);\n return refreshed !== null;\n }\n\n /** Called on every (re)connect, so a reconnect after expiry gets a fresh token. */\n async websocketHeaders(_context?: WebSocketAuthContext): Promise<Record<string, string>> {\n const tokens = await this.tokens();\n this.lastSent = tokens.accessToken;\n return { \"x-stx-oauth-token\": tokens.accessToken };\n }\n\n /**\n * Refresh with rotation, single-flight. Persists the new pair (keeping the\n * returned refresh token; the old one only if the server omitted it). On a\n * revoked grant, deletes the store entry and throws\n * `STXGrantRevokedException`. A transient failure resolves null.\n */\n refresh(refreshToken: string): Promise<StoredTokens | null> {\n const inflight = this.client._refreshesFor(this.store);\n const existing = inflight.get(this.memberKey);\n if (existing) return existing;\n const run = async (): Promise<StoredTokens | null> => {\n // Under a lock another replica may have refreshed first: use its result.\n const current = await this.load();\n if (current?.refreshToken && current.refreshToken !== refreshToken) return current;\n try {\n const set = await this.client.refreshToken(refreshToken);\n const stored: StoredTokens = {\n accessToken: set.accessToken,\n refreshToken: set.refreshToken ?? refreshToken,\n expiresAt: set.expiresAt,\n scope: set.scope ?? current?.scope,\n };\n await this.store.set(this.memberKey, stored);\n await this.opts.onRefresh?.(stored);\n return stored;\n } catch (err) {\n if (err instanceof STXGrantRevokedException) {\n // Reuse or revocation: drop the dead tokens so nothing retries them.\n await this.store.delete(this.memberKey);\n await this.opts.onGrantRevoked?.(err);\n throw err;\n }\n return null;\n }\n };\n const promise = (async () => {\n try {\n return this.store.withLock ? await this.store.withLock(this.memberKey, run) : await run();\n } finally {\n inflight.delete(this.memberKey);\n }\n })();\n inflight.set(this.memberKey, promise);\n return promise;\n }\n}\n\n/**\n * App-token adapter (client_credentials). A Bearer token on every request,\n * `x-stx-oauth-token` on the socket handshake. A 401 invalidates the cache and the request is\n * retried once with a fresh mint; every socket (re)connect mints fresh, never\n * reusing the token from a connection that just dropped.\n */\nexport class OAuthAppAuth implements AuthProvider {\n readonly kind = \"oauth_app\";\n\n constructor(readonly tokens: AppTokenProvider) {}\n\n async authHeaders(_request?: AuthRequest): Promise<Record<string, string>> {\n return { Authorization: `Bearer ${await this.tokens.get()}` };\n }\n\n async onUnauthorized(): Promise<boolean> {\n await this.tokens.fresh();\n return true;\n }\n\n /**\n * The first connect uses the cached token; a reconnect (or a caller that\n * does not say) mints fresh, never reusing the token from a connection that\n * just dropped.\n */\n async websocketHeaders(context?: WebSocketAuthContext): Promise<Record<string, string>> {\n const token = context?.reconnect === false ? await this.tokens.get() : await this.tokens.fresh();\n return { \"x-stx-oauth-token\": token };\n }\n}\n\nfunction normalizeScope(scope: string | readonly string[] | undefined): string | undefined {\n if (scope === undefined) return undefined;\n return typeof scope === \"string\" ? scope : formatScopes(scope);\n}\n\n/**\n * Validate an OAuth callback and consume its pending sign-in. Throws\n * `STXOAuthException` with the redirect's `error` (`access_denied` when the\n * member declined), `invalid_request` (no code or state) or `invalid_state`\n * (unknown, used or expired). Does not call the exchange.\n */\nexport async function readCallback(\n pending: PendingAuthorizationStore,\n callback: CallbackInput,\n authorizeEndpoint: string = DEFAULT_ENDPOINTS.authorize,\n): Promise<ReadCallback> {\n const q = callbackParams(callback);\n const where = pathOf(authorizeEndpoint);\n const error = q.get(\"error\");\n if (error) throw new STXOAuthException(error, q.get(\"error_description\") ?? undefined, 400, where);\n const code = q.get(\"code\");\n const state = q.get(\"state\");\n if (!code || !state) {\n throw new STXOAuthException(\"invalid_request\", \"The callback carries no code or no state.\", 400, where);\n }\n const entry = await pending.take(state);\n if (!entry) {\n throw new STXOAuthException(\n \"invalid_state\",\n \"Unknown, used or expired state; start the sign-in again.\",\n 400,\n where,\n );\n }\n return { code, pending: entry };\n}\n\nfunction callbackParams(input: CallbackInput): URLSearchParams {\n if (input instanceof URLSearchParams) return input;\n if (input instanceof URL) return input.searchParams;\n if (typeof input === \"string\") {\n const q = input.includes(\"?\") ? input.slice(input.indexOf(\"?\") + 1) : input;\n return new URLSearchParams(q.split(\"#\", 1)[0]);\n }\n const out = new URLSearchParams();\n for (const [k, v] of Object.entries(input)) if (typeof v === \"string\") out.set(k, v);\n return out;\n}\n\nfunction pathOf(endpoint: string): string {\n try {\n return /^https?:\\/\\//i.test(endpoint) ? new URL(endpoint).pathname : endpoint;\n } catch {\n return endpoint;\n }\n}\n","// OAuth discovery: RFC 8414 authorization-server metadata and RFC 9728\n// protected-resource metadata. The exchange builds `issuer` and every endpoint\n// on the host the request used, so fetch the document from the same base URL\n// you will send members to, and prefer its endpoints over the defaults.\n\nimport { STXAPIException } from \"../exceptions.js\";\nimport { joinUrl, resolveOAuthConfig, WELL_KNOWN, type FetchLike } from \"./endpoints.js\";\n\n/** RFC 8414 authorization-server metadata, as the exchange publishes it. */\nexport interface AuthorizationServerMetadata {\n issuer: string;\n authorization_endpoint: string;\n token_endpoint: string;\n revocation_endpoint?: string;\n introspection_endpoint?: string;\n /** Present only while dynamic client registration is enabled. */\n registration_endpoint?: string;\n scopes_supported?: string[];\n response_types_supported?: string[];\n grant_types_supported?: string[];\n code_challenge_methods_supported?: string[];\n token_endpoint_auth_methods_supported?: string[];\n [k: string]: unknown;\n}\n\n/** RFC 9728 protected-resource metadata. */\nexport interface ProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n scopes_supported?: string[];\n bearer_methods_supported?: string[];\n resource_name?: string;\n [k: string]: unknown;\n}\n\nexport interface DiscoveryOptions {\n fetch?: FetchLike;\n}\n\n/**\n * `GET <baseUrl>/.well-known/oauth-authorization-server`. Throws `STXAPIException`\n * on a non-2xx or a body that is not the metadata document.\n */\nexport async function discoverMetadata(\n baseUrl?: string,\n opts: DiscoveryOptions = {},\n): Promise<AuthorizationServerMetadata> {\n const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.authorizationServer, opts);\n const meta = doc as Partial<AuthorizationServerMetadata>;\n if (\n typeof meta.issuer !== \"string\" ||\n typeof meta.authorization_endpoint !== \"string\" ||\n typeof meta.token_endpoint !== \"string\"\n ) {\n throw httpError(\n 200,\n JSON.stringify(doc),\n WELL_KNOWN.authorizationServer + \" (missing issuer/authorization_endpoint/token_endpoint)\",\n );\n }\n return meta as AuthorizationServerMetadata;\n}\n\n/** `GET <baseUrl>/.well-known/oauth-protected-resource`. */\nexport async function discoverProtectedResource(\n baseUrl?: string,\n opts: DiscoveryOptions = {},\n): Promise<ProtectedResourceMetadata> {\n const doc = await fetchWellKnown(baseUrl, WELL_KNOWN.protectedResource, opts);\n const meta = doc as Partial<ProtectedResourceMetadata>;\n if (typeof meta.resource !== \"string\" || !Array.isArray(meta.authorization_servers)) {\n throw httpError(\n 200,\n JSON.stringify(doc),\n WELL_KNOWN.protectedResource + \" (missing resource/authorization_servers)\",\n );\n }\n return meta as ProtectedResourceMetadata;\n}\n\nasync function fetchWellKnown(baseUrl: string | undefined, path: string, opts: DiscoveryOptions): Promise<unknown> {\n const cfg = resolveOAuthConfig({ baseUrl, fetch: opts.fetch });\n const res = await cfg.fetch(joinUrl(cfg.baseUrl, path), {\n method: \"GET\",\n headers: { Accept: \"application/json\" },\n });\n const text = await res.text();\n if (!res.ok) throw httpError(res.status, text, path);\n try {\n return JSON.parse(text) as unknown;\n } catch {\n throw httpError(res.status, text, path);\n }\n}\n\nfunction httpError(status: number, text: string, path: string): STXAPIException {\n return new STXAPIException(`HTTP ${status} from ${path}: ${text.slice(0, 500)}`, {\n statusCode: status,\n body: text,\n path,\n });\n}\n","// The pluggable TokenStore: where an OAuth session's tokens live, keyed per\n// member. The SDK ships an in-memory default; production callers implement this\n// over Postgres/Redis/etc. and encrypt at rest. The OAuth session adapter reads\n// and writes tokens ONLY through this interface.\n\nexport interface StoredTokens {\n accessToken: string;\n refreshToken?: string;\n /** Epoch ms when the access token expires, or undefined if unknown. */\n expiresAt?: number;\n /** Space-delimited effective scope granted, if the server returned it. */\n scope?: string;\n}\n\n/**\n * Persistence for one member's tokens. `memberKey` is any stable string the\n * caller uses to identify a member (a user id, a session id, …). Methods may be\n * sync or async.\n */\nexport interface TokenStore {\n get(memberKey: string): Promise<StoredTokens | null> | StoredTokens | null;\n set(memberKey: string, tokens: StoredTokens): Promise<void> | void;\n delete(memberKey: string): Promise<void> | void;\n /**\n * Optional: run `fn` holding an exclusive lock on this member. Implement it\n * when several processes share the store, so only one of them refreshes a\n * member's rotating refresh token at a time (a second, concurrent refresh\n * with the same token trips reuse detection and revokes the grant). Within\n * one process the SDK already single-flights refreshes.\n */\n withLock?<T>(memberKey: string, fn: () => Promise<T>): Promise<T>;\n}\n\n/** Default in-memory store. Fine for scripts, demos and tests; not durable. */\nexport class MemoryTokenStore implements TokenStore {\n private readonly map = new Map<string, StoredTokens>();\n\n get(memberKey: string): StoredTokens | null {\n return this.map.get(memberKey) ?? null;\n }\n\n set(memberKey: string, tokens: StoredTokens): void {\n this.map.set(memberKey, tokens);\n }\n\n delete(memberKey: string): void {\n this.map.delete(memberKey);\n }\n}\n","// The server-side half of an authorization redirect: what was generated when\n// the member was sent to /oauth/authorize (the PKCE verifier, the redirect URI,\n// whatever the app needs to finish the link) keyed by the `state` that comes\n// back on the callback.\n//\n// A state is single use. `take()` returns and removes the entry in one step, so\n// a replayed callback finds nothing. Production callers implement this over\n// their session store or database; the in-memory default suits one process.\n\n/** One sign-in in progress. */\nexport interface PendingAuthorization {\n codeVerifier: string;\n /** The redirect URI sent to /authorize; the code exchange must repeat it. */\n redirectUri: string;\n /** The scope requested, space-delimited. */\n scope?: string;\n /** Epoch ms after which the entry is void. */\n expiresAt: number;\n /** Caller data carried to the callback: a user id, an app id, a return URL. */\n data?: Record<string, unknown>;\n}\n\nexport interface PendingAuthorizationStore {\n put(state: string, pending: PendingAuthorization): Promise<void> | void;\n /** Return and delete the entry for `state`, or null. Single use. */\n take(state: string): Promise<PendingAuthorization | null> | PendingAuthorization | null;\n}\n\n/** In-memory pending store. Expired entries are dropped on access. */\nexport class MemoryPendingAuthorizationStore implements PendingAuthorizationStore {\n private readonly map = new Map<string, PendingAuthorization>();\n\n put(state: string, pending: PendingAuthorization): void {\n this.sweep();\n this.map.set(state, pending);\n }\n\n take(state: string): PendingAuthorization | null {\n const entry = this.map.get(state) ?? null;\n this.map.delete(state);\n if (!entry || entry.expiresAt <= Date.now()) return null;\n return entry;\n }\n\n /** Entries not yet taken or expired. */\n get size(): number {\n this.sweep();\n return this.map.size;\n }\n\n private sweep(): void {\n const now = Date.now();\n for (const [k, v] of this.map) if (v.expiresAt <= now) this.map.delete(k);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAmBO,IAAM,oBAA8C;AAAA,EACzD,WAAW;AAAA,EACX,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,UAAU;AACZ;AAGO,IAAM,aAAa;AAAA,EACxB,qBAAqB;AAAA,EACrB,mBAAmB;AACrB;AASO,SAAS,mBAAmB,OAGjC;AACA,QAAM,MAAO,WAA0E,SAAS,OAAO,CAAC;AACxG,QAAM,OAAO,MAAM,WAAW,IAAI,YAAY,IAAI;AAClD,MAAI,CAAC,KAAM,OAAM,IAAI,mBAAmB,kEAAkE;AAC1G,QAAM,YAAY,MAAM,SAAU,WAAW;AAC7C,MAAI,OAAO,cAAc,YAAY;AACnC,UAAM,IAAI,mBAAmB,qEAAqE;AAAA,EACpG;AACA,SAAO,EAAE,SAAS,WAAW,MAAM,MAAM,IAAI,GAAG,OAAO,UAAU;AACnE;AAGO,SAAS,QAAQ,SAAiB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C,UAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,KAAK;AACrC,SAAK,IAAI,OAAO,KAAK;AACrB,QAAI,CAAC,SAAS,MAAM,aAAa,KAAK,IAAI,EAAG,QAAO;AACpD,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,IAAI,OAAe;AACjB,SAAK,MAAM;AACX,WAAO,KAAK,IAAI;AAAA,EAClB;AAAA,EAEQ,QAAc;AACpB,UAAM,MAAM,KAAK,IAAI;AACrB,eAAW,CAAC,GAAG,CAAC,KAAK,KAAK,IAAK,KAAI,EAAE,aAAa,IAAK,MAAK,IAAI,OAAO,CAAC;AAAA,EAC1E;AACF;","names":["httpError"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stxapp/stx-typescript",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "The TypeScript SDK for the STX exchange: markets, trading, your account and live WebSocket channels, with API-key signing and typed responses.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|