@stxapp/stx-typescript 0.8.3 → 0.9.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 +36 -0
- package/README.md +42 -0
- package/dist/{chunk-SIYERAKK.js → chunk-46XK6VDD.js} +406 -27
- package/dist/chunk-46XK6VDD.js.map +1 -0
- package/dist/{chunk-SI3EILHN.cjs → chunk-R77AZ5UH.cjs} +470 -91
- package/dist/chunk-R77AZ5UH.cjs.map +1 -0
- package/dist/{client-BrHjO1__.d.ts → client-B-MMKiRt.d.cts} +249 -17
- package/dist/{client-BrHjO1__.d.cts → client-B-MMKiRt.d.ts} +249 -17
- package/dist/index.cjs +14 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +13 -1
- package/dist/oauth.cjs +566 -94
- package/dist/oauth.cjs.map +1 -1
- package/dist/oauth.d.cts +264 -19
- package/dist/oauth.d.ts +264 -19
- package/dist/oauth.js +537 -65
- package/dist/oauth.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-SI3EILHN.cjs.map +0 -1
- package/dist/chunk-SIYERAKK.js.map +0 -1
package/dist/oauth.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/tssdk/tssdk/dist/oauth.cjs","../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"],"names":["httpError"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACQO,IAAM,kBAAA,EAA8C;AAAA,EACzD,SAAA,EAAW,kBAAA;AAAA,EACX,KAAA,EAAO,cAAA;AAAA,EACP,MAAA,EAAQ,eAAA;AAAA,EACR,UAAA,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AA;AAC2B,EAAA;AACa,EAAA;AACrC,EAAA;AACoB,IAAA;AAChB,EAAA;AACgC,IAAA;AACxC,EAAA;AACF;AAEgF;AACrC,EAAA;AAC3B,IAAA;AACN,IAAA;AACN,IAAA;AACD,EAAA;AACH;APoxB+C;AACA;AQx1BK;AACG,kBAAA;AAET,EAAA;AACR,IAAA;AACpC,EAAA;AAEmD,EAAA;AACnB,IAAA;AAChC,EAAA;AAEgC,EAAA;AACL,IAAA;AAC3B,EAAA;AACF;ARu1B+C;AACA;AS32BmC;AACnB,kBAAA;AAEL,EAAA;AAC3C,IAAA;AACgB,IAAA;AAC7B,EAAA;AAEiD,EAAA;AACV,IAAA;AAChB,IAAA;AACqB,IAAA;AACnC,IAAA;AACT,EAAA;AAAA;AAGmB,EAAA;AACN,IAAA;AACK,IAAA;AAClB,EAAA;AAEsB,EAAA;AACC,IAAA;AACgB,IAAA;AACvC,EAAA;AACF;ATy2B+C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/tssdk/tssdk/dist/oauth.cjs","sourcesContent":[null,"// 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`, an event's players) and the `events` channel. */\n EVENTS: \"events\",\n /** Create markets (`POST /api/v1/markets`). Granted by STX only. */\n MARKETS_WRITE: \"markets.write\",\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"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/tssdk/tssdk/dist/oauth.cjs","../src/oauth/endpoints.ts","../src/oauth/errors.ts","../src/oauth/metadata.ts","../src/oauth/pkce.ts","../src/oauth/register.ts","../src/oauth/scopes.ts","../src/oauth/client.ts","../src/oauth/terms.ts","../src/oauth/connect.ts","../src/oauth/tokenStore.ts","../src/oauth/pending.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACIO,IAAM,kBAAA,EAA8C;AAAA,EACzD,SAAA,EAAW,kBAAA;AAAA,EACX,KAAA,EAAO,cAAA;AAAA,EACP,MAAA,EAAQ,eAAA;AAAA,EACR,UAAA,EAAY,mBAAA;AAAA,EACZ,QAAA,EAAU;AACZ,CAAA;AAGO,IAAM,WAAA,EAAa;AAAA,EACxB,mBAAA,EAAqB,yCAAA;AAAA,EACrB,iBAAA,EAAmB;AACrB,CAAA;AASO,SAAS,kBAAA,CAAmB,KAAA,EAGjC;AACA,EAAA,MAAM,IAAA,mCAAO,UAAA,mBAA0E,OAAA,6BAAS,KAAA,UAAO,CAAC,GAAA;AACxG,EAAA,MAAM,KAAA,oCAAO,KAAA,CAAM,OAAA,UAAW,GAAA,CAAI,UAAA,UAAY,GAAA,CAAI,cAAA;AAClD,EAAA,GAAA,CAAI,CAAC,IAAA,EAAM,MAAM,IAAI,yCAAA,CAAmB,kEAAkE,CAAA;AAC1G,EAAA,MAAM,UAAA,mBAAY,KAAA,CAAM,KAAA,UAAU,UAAA,CAAW,OAAA;AAC7C,EAAA,GAAA,CAAI,OAAO,UAAA,IAAc,UAAA,EAAY;AACnC,IAAA,MAAM,IAAI,yCAAA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AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/tssdk/tssdk/dist/oauth.cjs","sourcesContent":[null,"// 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. All 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 * STX's own, narrower reason, when the answer carries one. `account_pending`\n * on an `invalid_grant` means the member's STX account is still being\n * verified.\n */\n readonly errorReason: string | undefined;\n /**\n * On an `invalid_scope` from the authorize callback, the scope the sign-in\n * asked for (from the pending sign-in), so the cause can be named.\n */\n requestedScope: string | undefined;\n\n constructor(\n error: string,\n errorDescription: string | undefined,\n status: number,\n endpoint: string,\n retryAfter?: number,\n errorReason?: string,\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 this.errorReason = errorReason;\n }\n}\n\n/**\n * The member came back without connecting: the callback carries\n * `error=access_denied`. Either the member declined on the consent screen, or\n * their STX account cannot be connected (for example it is suspended or\n * closed). A member whose account is only still being verified gets\n * `STXAccountPendingException` instead, and one who left the STX terms page\n * without agreeing gets `STXTermsNotAcceptedException`. Nothing was granted\n * and no tokens exist; show your own \"not connected\" state.\n */\nexport class STXAccessDeniedException extends STXOAuthException {}\n\n/**\n * The member's STX account is still being verified, so STX issues no tokens\n * for them yet. It arrives two ways:\n *\n * - On the callback (`error` is `account_pending`): the member signed in but\n * cannot connect yet. No tokens exist. Show your own \"we'll let you know\"\n * state and start again once STX has approved the account.\n * - From the token endpoint (`error` is `invalid_grant`, `errorReason` is\n * `account_pending`), on a code exchange or a refresh. On a refresh the\n * connection has not ended: keep the stored tokens, because the same refresh\n * token works once the member is verified. `OAuthSessionAuth` keeps them.\n */\nexport class STXAccountPendingException extends STXOAuthException {}\n\n/**\n * The member came back from the STX terms page without agreeing: the callback\n * carries `error=terms_required`. STX shows that page during sign-in to a\n * member who has not accepted the current terms. Nothing was granted and no\n * tokens exist; show your own \"not connected\" state and let the member start\n * again when they are ready.\n *\n * A member who is already connected when new terms take effect is a different\n * case: their calls throw `STXTermsRequiredException`, which carries the page\n * to send them to.\n */\nexport class STXTermsNotAcceptedException extends STXOAuthException {}\n\n/**\n * The error an authorize callback carries, as the most specific class:\n * `STXAccountPendingException`, `STXTermsNotAcceptedException`,\n * `STXAccessDeniedException`, or `STXOAuthException` for any other code.\n */\nexport function callbackError(\n error: string,\n errorDescription: string | undefined,\n endpoint: string,\n): STXOAuthException {\n const Class =\n error === \"account_pending\"\n ? STXAccountPendingException\n : error === \"terms_required\"\n ? STXTermsNotAcceptedException\n : error === \"access_denied\"\n ? STXAccessDeniedException\n : STXOAuthException;\n return new Class(error, errorDescription, 400, endpoint);\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","// 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 { isEdgeBlock, STXAPIException, STXNotAvailableException } 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\n * `STXNotAvailableException` (feature `oauth`) when the exchange has no OAuth\n * (404, or a 403 page from the edge in front of it), and `STXAPIException` on\n * any other 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.status === 404 || isEdgeBlock(res.status, text)) {\n throw new STXNotAvailableException(\"oauth\", new URL(cfg.baseUrl).host, {\n statusCode: res.status,\n body: text,\n method: \"GET\",\n path,\n });\n }\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","// 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 err.error_reason,\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; error_reason?: 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 error_reason: typeof obj.error_reason === \"string\" ? obj.error_reason : 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} 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`, an event's players) and the `events` channel. */\n EVENTS: \"events\",\n /** Create markets (`POST /api/v1/markets`). Granted by STX only. */\n MARKETS_WRITE: \"markets.write\",\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};\n\n/**\n * Scopes the exchange no longer has. A member accepts the STX terms on an STX\n * page, so no scope lets an app accept them. The exchange ignores these in a\n * request, and a token minted earlier may still report one.\n */\nconst RETIRED_SCOPES: ReadonlySet<string> = new Set([\"terms.write\", \"onboarding\"]);\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/**\n * Split a space-delimited `scope` string into canonical, de-duplicated scopes.\n * Retired scopes (`terms.write` and its older name `onboarding`) are left out.\n */\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 || RETIRED_SCOPES.has(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 apps 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 { isEdgeBlock, STXConfigException, STXNotAvailableException } from \"../exceptions.js\";\nimport { DEFAULT_ENDPOINTS, joinUrl, resolveOAuthConfig, type FetchLike } from \"./endpoints.js\";\nimport { callbackError, STXAccountPendingException, STXGrantRevokedException, STXOAuthException } from \"./errors.js\";\nimport { type AuthorizationServerMetadata, type DiscoveryOptions, discoverMetadata } 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 /** The OpenID Connect ID token, when `openid` was granted. Verify it before trusting it (`createConnect` does). */\n idToken?: string;\n /**\n * True on a refresh when the member has not accepted the current STX terms.\n * The refresh succeeded and the tokens work; placing orders is refused until\n * the member accepts at `termsUrl`. Absent otherwise.\n */\n termsRequired?: boolean;\n /** The STX page where the member accepts the terms. Present with `termsRequired`. */\n termsUrl?: 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 /**\n * The exchange's discovery document, when you have it (`OAuthClient.discover()`\n * and `fromMetadata()` set it). With it, an `invalid_scope` for a scope the\n * exchange does not list becomes `STXNotAvailableException`.\n */\n metadata?: AuthorizationServerMetadata;\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 * Called after a refresh that says the member has not accepted the current\n * STX terms (the new tokens are already persisted, and work). Send the\n * member to `termsUrl` when they are next in your app.\n */\n onTermsRequired?: (info: { termsUrl: string }) => 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 /** Go straight to a sign-in provider instead of STX's login page: `google`, `apple` or `x`. */\n connection?: string;\n /** The member's email, if you know it, so the provider can preselect the account. */\n loginHint?: 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 /** The discovery document this client was built from, if any. */\n readonly metadata: AuthorizationServerMetadata | undefined;\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.metadata = opts.metadata;\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(\n metadata: AuthorizationServerMetadata,\n opts: Omit<OAuthClientOptions, \"endpoints\" | \"metadata\">,\n ): OAuthClient {\n return new OAuthClient({\n ...opts,\n metadata,\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 /**\n * Fetch the exchange's discovery document and build a client from it. Throws\n * `STXNotAvailableException` (feature `oauth`) on an exchange without OAuth,\n * so an app can tell \"not here yet\" from a misconfiguration at start-up.\n *\n * const oauth = await OAuthClient.discover({\n * baseUrl: \"https://demo.stxapp.io\",\n * clientId: process.env.STX_CLIENT_ID!,\n * clientSecret: process.env.STX_CLIENT_SECRET,\n * redirectUri: \"https://your.app/stx/callback\",\n * });\n */\n static async discover(opts: Omit<OAuthClientOptions, \"endpoints\" | \"metadata\">): Promise<OAuthClient> {\n const discovery: DiscoveryOptions = opts.fetch ? { fetch: opts.fetch } : {};\n const metadata = await discoverMetadata(opts.baseUrl, discovery);\n return OAuthClient.fromMetadata(metadata, { ...opts, baseUrl: opts.baseUrl ?? metadata.issuer });\n }\n\n /** The exchange host, e.g. `\"demo.stxapp.io\"`. */\n get host(): string {\n return new URL(this.baseUrl).host;\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: {\n ...(params.connection ? { connection: params.connection } : {}),\n ...(params.loginHint ? { login_hint: params.loginHint } : {}),\n ...(params.extraParams ?? {}),\n },\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 (`access_denied`, `account_pending`, `terms_required`), 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 let read: ReadCallback;\n try {\n read = await readCallback(pending, callback, this.endpoints.authorize);\n } catch (err) {\n if (err instanceof STXOAuthException && err.error === \"invalid_scope\") {\n throw this.unofferedScope(err.requestedScope ?? this.scope, err) ?? err;\n }\n throw err;\n }\n return this.redeemAuthorization(read, opts);\n }\n\n /**\n * `STXNotAvailableException` for the first scope in `requested` that the\n * discovery document does not list, or undefined when every scope is listed\n * or there is no document to check against.\n */\n private unofferedScope(requested: string | undefined, cause: unknown): STXNotAvailableException | undefined {\n const offered = this.metadata?.scopes_supported;\n if (!offered || !requested) return undefined;\n const missing = parseScopes(requested).find((s) => !offered.includes(s));\n if (!missing) return undefined;\n return new STXNotAvailableException(`scope:${missing}`, this.host, { statusCode: 400, cause });\n }\n\n /** `STXNotAvailableException` (feature `oauth`) for an OAuth endpoint the exchange does not have. */\n private oauthMissing(status: number, text: string, endpoint: string): STXNotAvailableException | undefined {\n if (status !== 404 && !isEdgeBlock(status, text)) return undefined;\n return new STXNotAvailableException(\"oauth\", this.host, {\n statusCode: status,\n body: text,\n method: \"POST\",\n path: pathOf(endpoint),\n });\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 * While the member has not accepted the current STX terms the refresh still\n * succeeds, and the result carries `termsRequired: true` and `termsUrl`.\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 /**\n * Revoke a token. A refresh token ends the member's grant (every token on it);\n * an access token revokes only its pair. Always resolves on a 200.\n */\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 (\n this.oauthMissing(res.status, text, this.endpoints.revoke) ??\n this.oauthError(res.status, text, this.endpoints.revoke)\n );\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) {\n throw (\n this.oauthMissing(res.status, text, this.endpoints.introspect) ??\n this.oauthError(res.status, text, this.endpoints.introspect)\n );\n }\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 /**\n * `client_secret_basic` header, or undefined for a public client. Both parts\n * are form-urlencoded before base64, as RFC 6749 section 2.3.1 requires.\n */\n basicAuthHeader(): string | undefined {\n if (this.clientSecret === undefined) return undefined;\n const raw = `${formEncode(this.clientId)}:${formEncode(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 missing = this.oauthMissing(res.status, text, this.endpoints.token);\n if (missing) throw missing;\n const err = rfcError(text);\n if (err?.error === \"invalid_scope\") {\n const unoffered = this.unofferedScope(\n body.get(\"scope\") ?? undefined,\n this.oauthError(res.status, text, this.endpoints.token),\n );\n if (unoffered) throw unoffered;\n }\n // The member's account is still being verified: no tokens yet, but the\n // grant stands. Checked first, so a refresh is not taken for a dead grant.\n if (err?.error === \"invalid_grant\" && err.error_reason === \"account_pending\") {\n throw new STXAccountPendingException(\n err.error,\n err.error_description,\n res.status,\n pathOf(this.endpoints.token),\n undefined,\n err.error_reason,\n );\n }\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, undefined, err.error_reason);\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 if (typeof obj.id_token === \"string\") set.idToken = obj.id_token;\n if (obj.terms_required === true) {\n set.termsRequired = true;\n if (typeof obj.terms_url === \"string\") set.termsUrl = obj.terms_url;\n }\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 ...termsState(set),\n };\n}\n\n/** The terms fields of a token set, present only while the member has terms to accept. */\nfunction termsState(set: TokenSet): Pick<StoredTokens, \"termsRequired\" | \"termsUrl\"> {\n if (!set.termsRequired) return {};\n return { termsRequired: true, ...(set.termsUrl ? { termsUrl: set.termsUrl } : {}) };\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`. While the member's account is still being\n * verified, keeps the store entry and throws `STXAccountPendingException`.\n * A refresh that says the member has terms to accept is a success: the pair\n * is stored with `termsRequired` and `termsUrl`, and `onTermsRequired` runs.\n * 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 ...termsState(set),\n };\n await this.store.set(this.memberKey, stored);\n await this.opts.onRefresh?.(stored);\n if (stored.termsUrl) await this.opts.onTermsRequired?.({ termsUrl: stored.termsUrl });\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 // The account is still being verified: the tokens stay, since the same\n // refresh token works once the member is verified. The caller hears why.\n if (err instanceof STXAccountPendingException) throw err;\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\n/** `application/x-www-form-urlencoded` encoding of one value. */\nfunction formEncode(value: string): string {\n return new URLSearchParams({ v: value }).toString().slice(2);\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 * `STXAccessDeniedException` (`access_denied`: the member declined, or STX did\n * not let them connect), `STXAccountPendingException` (`account_pending`: the\n * member's STX account is still being verified),\n * `STXTermsNotAcceptedException` (`terms_required`: the member left the STX\n * terms page without agreeing), or `STXOAuthException` with\n * any other redirect `error`, `invalid_request` (no code or state) or\n * `invalid_state` (unknown, used or expired). The state is checked and used up\n * first, so an error is reported only for a sign-in this app started. Does\n * 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 const code = q.get(\"code\");\n const state = q.get(\"state\");\n if (!error && (!code || !state)) {\n throw new STXOAuthException(\"invalid_request\", \"The callback carries no code or no state.\", 400, where);\n }\n // The state is checked, and used up, before anything the callback says is\n // believed: an error counts only for a sign-in this app started.\n const entry = state ? await pending.take(state) : null;\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 if (error) {\n const err = callbackError(error, q.get(\"error_description\") ?? undefined, where);\n err.requestedScope = entry.scope;\n throw err;\n }\n return { code: code as string, pending: entry };\n}\n\nexport function 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","// Where to send a member who has to accept the current STX terms. A member\n// accepts them on an STX page, signed in to their own account; an app cannot\n// accept for them.\n\n/**\n * The URL to send the member's browser to so they can accept the current STX\n * terms and come back to your app: `termsUrl` (from\n * `STXTermsRequiredException.termsUrl`, or `termsUrl` on a refreshed token\n * set) with `return_to` added.\n *\n * `returnTo` is the page in your app the member lands on afterwards. It must\n * be one of your registered redirect URIs, or on the same origin as one. STX\n * sends the member back to it unchanged.\n *\n * termsUrlWithReturn(\n * \"https://demo.stxapp.io/connect/terms?client_id=stxapp_client_9f2c41d7\",\n * \"https://your.app/portfolio\",\n * );\n * // https://demo.stxapp.io/connect/terms?client_id=stxapp_client_9f2c41d7&return_to=https%3A%2F%2Fyour.app%2Fportfolio\n */\nexport function termsUrlWithReturn(termsUrl: string, returnTo: string): string {\n const hashAt = termsUrl.indexOf(\"#\");\n const base = hashAt === -1 ? termsUrl : termsUrl.slice(0, hashAt);\n const hash = hashAt === -1 ? \"\" : termsUrl.slice(hashAt);\n const queryAt = base.indexOf(\"?\");\n const path = queryAt === -1 ? base : base.slice(0, queryAt);\n const params = new URLSearchParams(queryAt === -1 ? \"\" : base.slice(queryAt + 1));\n params.set(\"return_to\", returnTo);\n return `${path}?${params.toString()}${hash}`;\n}\n","// Sign in with your STX account: OpenID Connect on top of the\n// authorization-code flow, for a server that wants both who the member is and\n// their trading grant from one round trip. Endpoints come from the issuer's\n// discovery document.\n//\n// Server-side only: the client secret and the tokens never belong in a browser.\n\nimport type { webcrypto } from \"node:crypto\";\nimport { isEdgeBlock, STXConfigException, STXNotAvailableException } from \"../exceptions.js\";\nimport { callbackParams, OAuthClient, type CallbackInput, type TokenSet } from \"./client.js\";\nimport { joinUrl, type FetchLike } from \"./endpoints.js\";\nimport { callbackError, STXOAuthException } from \"./errors.js\";\nimport { createPkce, generateState } from \"./pkce.js\";\nimport { formatScopes } from \"./scopes.js\";\n\n/** The OpenID Connect discovery document, as far as `connect` uses it. */\nexport interface OpenIDConfiguration {\n issuer: string;\n authorization_endpoint: string;\n token_endpoint: string;\n jwks_uri: string;\n userinfo_endpoint?: string;\n revocation_endpoint?: string;\n id_token_signing_alg_values_supported?: string[];\n [k: string]: unknown;\n}\n\nexport interface ConnectOptions {\n /** The exchange's public URL, e.g. `https://demo.stxapp.io`. Must equal the discovery `issuer`. */\n issuer: string;\n clientId: string;\n /** Your client secret. `connect` is for confidential (server-side) clients. */\n clientSecret: string;\n /** The redirect URI registered with STX (exact-matched). */\n redirectUri: string;\n /** Default scopes. `openid` is always added. */\n scopes?: string | readonly string[];\n /** Allowed clock skew when checking `exp` and `iat`, in seconds. Default 60. */\n clockSkewSeconds?: number;\n fetch?: FetchLike;\n}\n\nexport interface StartParams {\n /** Go straight to a sign-in provider instead of STX's login page: `google`, `apple` or `x`. */\n connection?: string;\n /** The member's email, if you know it, so the provider can preselect the account. */\n loginHint?: string;\n /** Overrides the default scopes for this sign-in. `openid` is always added. */\n scopes?: string | readonly string[];\n /** Overrides the default redirect URI for this sign-in. */\n redirectUri?: string;\n /** `none` for a silent reconnect; `login` or `consent` to force those screens. */\n prompt?: \"none\" | \"login\" | \"consent\";\n}\n\n/** What to keep in your server session between `start()` and `finish()`. */\nexport interface SavedSignIn {\n state: string;\n codeVerifier: string;\n nonce: string;\n redirectUri?: string;\n}\n\nexport interface StartedSignIn extends SavedSignIn {\n /** Send the member's browser here. */\n url: string;\n}\n\n/** The member, from the verified ID token or the userinfo endpoint. */\nexport interface ConnectIdentity {\n /** Stable STX member id for your app. Key your user record on this, not on email. */\n sub: string;\n email?: string;\n emailVerified?: boolean;\n /** Every claim in the verified ID token, or in the userinfo answer. */\n claims: Record<string, unknown>;\n}\n\nexport interface FinishedSignIn {\n tokens: TokenSet & { idToken: string };\n identity: ConnectIdentity;\n}\n\nexport interface Connect {\n start(params?: StartParams): Promise<StartedSignIn>;\n finish(callback: CallbackInput, saved: SavedSignIn): Promise<FinishedSignIn>;\n /** STX rotates refresh tokens: store whatever comes back. */\n refresh(refreshToken: string): Promise<TokenSet>;\n /**\n * Revoke one token. A refresh token ends the member's whole connection (every\n * token on it, and the next sign-in asks for consent again); an access token\n * revokes only that pair.\n */\n revoke(token: string, tokenTypeHint?: \"access_token\" | \"refresh_token\"): Promise<void>;\n /**\n * Disconnect the member: revokes the refresh token, which ends the connection\n * at STX. Falls back to the access token when there is no refresh token.\n */\n disconnect(tokens: Pick<TokenSet, \"accessToken\" | \"refreshToken\">): Promise<void>;\n /**\n * The member's claims from the userinfo endpoint, read with their access\n * token (it must carry `openid`). The same claims `finish()` already\n * verified in the ID token; use this to read them again later. Pass the\n * `sub` you stored for the member and an answer about anyone else is\n * refused. A dead token, or one without `openid`, throws `STXOAuthException`\n * with `invalid_token`.\n */\n userInfo(accessToken: string, expected?: { sub?: string }): Promise<ConnectIdentity>;\n /** The discovery document, fetched once and cached. */\n configuration(): Promise<OpenIDConfiguration>;\n}\n\ninterface Jwk {\n kid?: string;\n kty: string;\n alg?: string;\n use?: string;\n [k: string]: unknown;\n}\n\n/** Create a `connect` helper for one STX environment. */\nexport function createConnect(opts: ConnectOptions): Connect {\n if (!opts.issuer) throw new STXConfigException(\"issuer is required.\");\n if (!opts.clientId || !opts.clientSecret) throw new STXConfigException(\"clientId and clientSecret are required.\");\n if (!opts.redirectUri) throw new STXConfigException(\"redirectUri is required.\");\n\n const issuer = opts.issuer.replace(/\\/+$/, \"\");\n const fetchImpl = opts.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 const skew = opts.clockSkewSeconds ?? 60;\n\n let config: Promise<OpenIDConfiguration> | undefined;\n let client: Promise<OAuthClient> | undefined;\n let keys: Promise<Jwk[]> | undefined;\n\n const configuration = (): Promise<OpenIDConfiguration> => {\n config ??= fetchJson(fetchImpl, joinUrl(issuer, \"/.well-known/openid-configuration\"), \"connect\").then((doc) => {\n const c = doc as Partial<OpenIDConfiguration>;\n if (\n typeof c.issuer !== \"string\" ||\n typeof c.authorization_endpoint !== \"string\" ||\n typeof c.token_endpoint !== \"string\" ||\n typeof c.jwks_uri !== \"string\"\n ) {\n throw new STXOAuthException(\n \"invalid_configuration\",\n \"The discovery document is incomplete.\",\n 0,\n \"/.well-known/openid-configuration\",\n );\n }\n if (c.issuer.replace(/\\/+$/, \"\") !== issuer) {\n throw new STXOAuthException(\n \"invalid_configuration\",\n `The discovery issuer ${c.issuer} does not match ${issuer}.`,\n 0,\n \"/.well-known/openid-configuration\",\n );\n }\n return c as OpenIDConfiguration;\n });\n config.catch(() => {\n config = undefined;\n });\n return config;\n };\n\n const oauth = (): Promise<OAuthClient> => {\n client ??= configuration().then(\n (c) =>\n new OAuthClient({\n baseUrl: issuer,\n clientId: opts.clientId,\n clientSecret: opts.clientSecret,\n redirectUri: opts.redirectUri,\n fetch: fetchImpl,\n endpoints: {\n authorize: c.authorization_endpoint,\n token: c.token_endpoint,\n ...(c.revocation_endpoint ? { revoke: c.revocation_endpoint } : {}),\n },\n }),\n );\n client.catch(() => {\n client = undefined;\n });\n return client;\n };\n\n const jwks = async (refresh = false): Promise<Jwk[]> => {\n if (refresh) keys = undefined;\n keys ??= configuration()\n .then((c) => fetchJson(fetchImpl, c.jwks_uri))\n .then((doc) => {\n const list = (doc as { keys?: unknown }).keys;\n if (!Array.isArray(list))\n throw new STXOAuthException(\"invalid_configuration\", \"The key set has no keys.\", 0, \"jwks_uri\");\n return list as Jwk[];\n });\n keys.catch(() => {\n keys = undefined;\n });\n return keys;\n };\n\n return {\n configuration,\n\n async start(params: StartParams = {}): Promise<StartedSignIn> {\n const c = await oauth();\n const pkce = await createPkce();\n const state = generateState();\n const nonce = generateState();\n const redirectUri = params.redirectUri ?? opts.redirectUri;\n const extraParams: Record<string, string> = { nonce };\n if (params.connection) extraParams.connection = params.connection;\n if (params.loginHint) extraParams.login_hint = params.loginHint;\n const url = c.buildAuthorizeUrl({\n state,\n codeChallenge: pkce.codeChallenge,\n scope: withOpenId(params.scopes ?? opts.scopes),\n prompt: params.prompt,\n redirectUri,\n extraParams,\n });\n return { url, state, codeVerifier: pkce.codeVerifier, nonce, redirectUri };\n },\n\n async finish(callback: CallbackInput, saved: SavedSignIn): Promise<FinishedSignIn> {\n const q = callbackParams(callback);\n // The authorize path the issuer published, for the errors below.\n const where = pathOf((await configuration()).authorization_endpoint);\n const error = q.get(\"error\");\n const code = q.get(\"code\");\n const state = q.get(\"state\");\n if (!error && (!code || !state)) {\n throw new STXOAuthException(\"invalid_request\", \"The callback carries no code or no state.\", 400, where);\n }\n // The state is checked before anything the callback says is believed:\n // an error counts only for the sign-in it belongs to.\n if (!state || !saved?.state || !constantTimeEqual(state, saved.state)) {\n throw new STXOAuthException(\"invalid_state\", \"The state does not match this sign-in; start again.\", 400, where);\n }\n if (error) throw callbackError(error, q.get(\"error_description\") ?? undefined, where);\n const c = await oauth();\n const tokens = await c.exchangeCode({\n code: code as string,\n codeVerifier: saved.codeVerifier,\n redirectUri: saved.redirectUri ?? opts.redirectUri,\n });\n const idToken = tokens.idToken;\n if (!idToken) {\n throw new STXOAuthException(\n \"invalid_id_token\",\n \"The token response has no id_token; request the openid scope.\",\n 0,\n \"/oauth/token\",\n );\n }\n const claims = await verifyIdToken(idToken, {\n issuer: (await configuration()).issuer,\n clientId: opts.clientId,\n nonce: saved.nonce,\n skew,\n keys: jwks,\n });\n return { tokens: { ...tokens, idToken }, identity: identityFrom(claims) };\n },\n\n async userInfo(accessToken: string, expected: { sub?: string } = {}): Promise<ConnectIdentity> {\n const endpoint = (await configuration()).userinfo_endpoint;\n if (!endpoint) {\n throw new STXOAuthException(\n \"invalid_configuration\",\n \"The discovery document names no userinfo endpoint.\",\n 0,\n \"/.well-known/openid-configuration\",\n );\n }\n // The path the issuer published, for the errors below.\n const where = pathOf(endpoint);\n const res = await fetchImpl(endpoint, {\n method: \"GET\",\n headers: { Accept: \"application/json\", Authorization: `Bearer ${accessToken}` },\n });\n const text = await res.text();\n if (res.status === 404 || isEdgeBlock(res.status, text)) {\n throw new STXNotAvailableException(\"connect\", new URL(endpoint).host, {\n statusCode: res.status,\n body: text,\n method: \"GET\",\n path: where,\n });\n }\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n body = undefined;\n }\n const claims = (body && typeof body === \"object\" ? body : {}) as Record<string, unknown>;\n if (!res.ok) {\n const error = typeof claims.error === \"string\" ? claims.error : res.status === 401 ? \"invalid_token\" : \"error\";\n const description = typeof claims.error_description === \"string\" ? claims.error_description : undefined;\n const reason = typeof claims.error_reason === \"string\" ? claims.error_reason : undefined;\n throw new STXOAuthException(error, description, res.status, where, undefined, reason);\n }\n const fail = (why: string): never => {\n throw new STXOAuthException(\"invalid_userinfo\", why, 0, where);\n };\n if (typeof claims.sub !== \"string\" || claims.sub === \"\") fail(\"The userinfo answer has no subject.\");\n // OpenID Connect Core 5.3.2: an answer about another subject must not be used.\n if (expected.sub !== undefined && claims.sub !== expected.sub) {\n fail(\"The userinfo answer is about a different member.\");\n }\n return identityFrom(claims);\n },\n\n async refresh(refreshToken: string): Promise<TokenSet> {\n return (await oauth()).refreshToken(refreshToken);\n },\n\n async revoke(token: string, tokenTypeHint?: \"access_token\" | \"refresh_token\"): Promise<void> {\n return (await oauth()).revoke(token, tokenTypeHint);\n },\n\n async disconnect(tokens: Pick<TokenSet, \"accessToken\" | \"refreshToken\">): Promise<void> {\n const client = await oauth();\n if (tokens.refreshToken) return client.revoke(tokens.refreshToken, \"refresh_token\");\n return client.revoke(tokens.accessToken, \"access_token\");\n },\n };\n}\n\nfunction pathOf(url: string): string {\n try {\n return new URL(url).pathname;\n } catch {\n return url;\n }\n}\n\nfunction identityFrom(claims: Record<string, unknown>): ConnectIdentity {\n return {\n sub: claims.sub as string,\n ...(typeof claims.email === \"string\" ? { email: claims.email } : {}),\n ...(claims.email_verified !== undefined\n ? { emailVerified: claims.email_verified === true || claims.email_verified === \"true\" }\n : {}),\n claims,\n };\n}\n\nfunction withOpenId(scopes: string | readonly string[] | undefined): string {\n const list = scopes === undefined ? [] : typeof scopes === \"string\" ? scopes.split(/\\s+/) : [...scopes];\n const set = new Set(list.filter(Boolean));\n set.delete(\"openid\");\n return formatScopes([\"openid\", ...set]);\n}\n\n/**\n * GET a JSON document. With `feature`, a 404 or an edge block (a 403 that is\n * not JSON) means the exchange does not have that feature.\n */\nasync function fetchJson(fetchImpl: FetchLike, url: string, feature?: string): Promise<unknown> {\n const res = await fetchImpl(url, { method: \"GET\", headers: { Accept: \"application/json\" } });\n const text = await res.text();\n if (feature && (res.status === 404 || isEdgeBlock(res.status, text))) {\n throw new STXNotAvailableException(feature, new URL(url).host, {\n statusCode: res.status,\n body: text,\n method: \"GET\",\n path: new URL(url).pathname,\n });\n }\n if (!res.ok) {\n throw new STXOAuthException(\"invalid_configuration\", `GET ${url} returned ${res.status}.`, res.status, url);\n }\n try {\n return JSON.parse(text);\n } catch {\n throw new STXOAuthException(\"invalid_configuration\", `GET ${url} did not return JSON.`, res.status, url);\n }\n}\n\nconst ALGORITHMS: Record<\n string,\n {\n import: webcrypto.RsaHashedImportParams | webcrypto.EcKeyImportParams;\n verify: webcrypto.AlgorithmIdentifier | webcrypto.EcdsaParams;\n }\n> = {\n RS256: {\n import: { name: \"RSASSA-PKCS1-v1_5\", hash: \"SHA-256\" },\n verify: { name: \"RSASSA-PKCS1-v1_5\" },\n },\n ES256: {\n import: { name: \"ECDSA\", namedCurve: \"P-256\" },\n verify: { name: \"ECDSA\", hash: \"SHA-256\" },\n },\n};\n\nasync function verifyIdToken(\n token: string,\n expected: {\n issuer: string;\n clientId: string;\n nonce: string;\n skew: number;\n keys: (refresh?: boolean) => Promise<Jwk[]>;\n },\n): Promise<Record<string, unknown>> {\n const fail = (why: string): never => {\n throw new STXOAuthException(\"invalid_id_token\", why, 0, \"/oauth/token\");\n };\n const parts = token.split(\".\");\n if (parts.length !== 3) fail(\"The ID token is not a JWT.\");\n const [h, p, s] = parts as [string, string, string];\n const header = decodeJson(h) as { alg?: string; kid?: string } | undefined;\n const claims = decodeJson(p) as Record<string, unknown> | undefined;\n if (!header || !claims) return fail(\"The ID token is malformed.\");\n const alg = header.alg ?? \"\";\n const algorithm = ALGORITHMS[alg];\n if (!algorithm) return fail(`Unsupported ID token algorithm ${alg}.`);\n\n const pick = (list: Jwk[]) =>\n list.find((k) => (header.kid ? k.kid === header.kid : true) && (!k.alg || k.alg === alg) && k.use !== \"enc\");\n let jwk = pick(await expected.keys());\n // A key the cached set does not have yet: the issuer may have rotated.\n if (!jwk && header.kid) jwk = pick(await expected.keys(true));\n if (!jwk) return fail(\"No published key matches the ID token.\");\n\n const { kid: _kid, alg: _alg, use: _use, key_ops: _ops, ...material } = jwk;\n const key = await crypto.subtle.importKey(\"jwk\", material as webcrypto.JsonWebKey, algorithm.import, false, [\n \"verify\",\n ]);\n const ok = await crypto.subtle.verify(\n algorithm.verify,\n key,\n base64urlDecode(s),\n new TextEncoder().encode(`${h}.${p}`),\n );\n if (!ok) fail(\"The ID token signature does not verify.\");\n\n if (claims.iss !== expected.issuer) fail(\"The ID token was issued by someone else.\");\n const aud = claims.aud;\n const audiences = Array.isArray(aud) ? aud : [aud];\n if (!audiences.includes(expected.clientId)) fail(\"The ID token is for another app.\");\n if (audiences.length > 1 && claims.azp !== expected.clientId) fail(\"The ID token is for another app.\");\n const now = Math.floor(Date.now() / 1000);\n if (typeof claims.exp !== \"number\" || claims.exp + expected.skew < now) fail(\"The ID token has expired.\");\n if (typeof claims.iat === \"number\" && claims.iat - expected.skew > now) fail(\"The ID token is not valid yet.\");\n if (typeof claims.nonce !== \"string\" || !constantTimeEqual(claims.nonce, expected.nonce)) {\n fail(\"The ID token nonce does not match this sign-in.\");\n }\n if (typeof claims.sub !== \"string\" || claims.sub === \"\") fail(\"The ID token has no subject.\");\n return claims;\n}\n\nfunction decodeJson(segment: string): unknown {\n try {\n return JSON.parse(new TextDecoder().decode(base64urlDecode(segment)));\n } catch {\n return undefined;\n }\n}\n\nfunction base64urlDecode(segment: string): Uint8Array {\n const b64 = segment.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"===\".slice((segment.length + 3) % 4);\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return diff === 0;\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 * True when the last refresh said the member has not accepted the current\n * STX terms. The tokens work; placing orders is refused until the member\n * accepts at `termsUrl`. Absent once a later refresh no longer says so.\n */\n termsRequired?: boolean;\n /** The STX page where the member accepts the terms. Present with `termsRequired`. */\n termsUrl?: 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"]}
|