@stxapp/stx-typescript 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/LICENSE +21 -0
- package/README.md +79 -0
- package/dist/chunk-R664LTIB.cjs +2774 -0
- package/dist/chunk-R664LTIB.cjs.map +1 -0
- package/dist/chunk-U3KT3I43.js +2774 -0
- package/dist/chunk-U3KT3I43.js.map +1 -0
- package/dist/client-5n7RRquU.d.cts +3355 -0
- package/dist/client-5n7RRquU.d.ts +3355 -0
- package/dist/index.cjs +121 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +55 -0
- package/dist/index.d.ts +55 -0
- package/dist/index.js +121 -0
- package/dist/index.js.map +1 -0
- package/dist/oauth.cjs +967 -0
- package/dist/oauth.cjs.map +1 -0
- package/dist/oauth.d.cts +644 -0
- package/dist/oauth.d.ts +644 -0
- package/dist/oauth.js +967 -0
- package/dist/oauth.js.map +1 -0
- package/package.json +93 -0
package/dist/oauth.d.cts
ADDED
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
import { a9 as STXAuthenticationException, g as AuthProvider, h as AuthRequest, aC as WebSocketAuthContext, aj as STXOptions, a7 as STX } from './client-5n7RRquU.cjs';
|
|
2
|
+
export { ae as STXForbiddenException, ag as STXInsufficientScopeException, ah as STXInvalidTokenException } from './client-5n7RRquU.cjs';
|
|
3
|
+
import 'node:crypto';
|
|
4
|
+
|
|
5
|
+
interface OAuthEndpoints$1 {
|
|
6
|
+
/** Default `/oauth/authorize`. */
|
|
7
|
+
authorize: string;
|
|
8
|
+
/** Default `/oauth/token`. */
|
|
9
|
+
token: string;
|
|
10
|
+
/** Default `/oauth/revoke` (RFC 7009). */
|
|
11
|
+
revoke: string;
|
|
12
|
+
/** Default `/oauth/introspect` (RFC 7662). */
|
|
13
|
+
introspect: string;
|
|
14
|
+
/** Default `/oauth/register` (RFC 7591). */
|
|
15
|
+
register: string;
|
|
16
|
+
}
|
|
17
|
+
declare const DEFAULT_ENDPOINTS: Readonly<OAuthEndpoints$1>;
|
|
18
|
+
/** RFC 8414 / RFC 9728 discovery documents, relative to the base URL. */
|
|
19
|
+
declare const WELL_KNOWN: {
|
|
20
|
+
readonly authorizationServer: "/.well-known/oauth-authorization-server";
|
|
21
|
+
readonly protectedResource: "/.well-known/oauth-protected-resource";
|
|
22
|
+
};
|
|
23
|
+
/** A `fetch`-compatible function. Defaults to the global `fetch`. */
|
|
24
|
+
type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
|
|
25
|
+
/** Build an absolute URL from the base and a path (absolute URLs pass through). */
|
|
26
|
+
declare function joinUrl(baseUrl: string, path: string): string;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* An RFC 6749 section 5.2 (or RFC 7591 section 3.2.2) error body from an
|
|
30
|
+
* OAuth protocol endpoint: `{"error": "...", "error_description": "..."}`.
|
|
31
|
+
*/
|
|
32
|
+
declare class STXOAuthException extends STXAuthenticationException {
|
|
33
|
+
/** The RFC error code: `invalid_client`, `invalid_grant`, `invalid_scope`, ... */
|
|
34
|
+
readonly error: string;
|
|
35
|
+
readonly errorDescription: string | undefined;
|
|
36
|
+
/** The endpoint path that answered. */
|
|
37
|
+
readonly endpoint: string;
|
|
38
|
+
/** Seconds to wait when the endpoint answered 429 with Retry-After. */
|
|
39
|
+
readonly retryAfter: number | undefined;
|
|
40
|
+
constructor(error: string, errorDescription: string | undefined, status: number, endpoint: string, retryAfter?: number);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The OAuth grant is no longer valid: a refresh was rejected with
|
|
44
|
+
* `invalid_grant` (the member revoked the app, or a retired or reused refresh
|
|
45
|
+
* token tripped reuse detection and the whole grant was revoked). Send the
|
|
46
|
+
* member back through consent.
|
|
47
|
+
*/
|
|
48
|
+
declare class STXGrantRevokedException extends STXAuthenticationException {
|
|
49
|
+
constructor(message?: string);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** RFC 8414 authorization-server metadata, as the exchange publishes it. */
|
|
53
|
+
interface AuthorizationServerMetadata {
|
|
54
|
+
issuer: string;
|
|
55
|
+
authorization_endpoint: string;
|
|
56
|
+
token_endpoint: string;
|
|
57
|
+
revocation_endpoint?: string;
|
|
58
|
+
introspection_endpoint?: string;
|
|
59
|
+
/** Present only while dynamic client registration is enabled. */
|
|
60
|
+
registration_endpoint?: string;
|
|
61
|
+
scopes_supported?: string[];
|
|
62
|
+
response_types_supported?: string[];
|
|
63
|
+
grant_types_supported?: string[];
|
|
64
|
+
code_challenge_methods_supported?: string[];
|
|
65
|
+
token_endpoint_auth_methods_supported?: string[];
|
|
66
|
+
[k: string]: unknown;
|
|
67
|
+
}
|
|
68
|
+
/** RFC 9728 protected-resource metadata. */
|
|
69
|
+
interface ProtectedResourceMetadata {
|
|
70
|
+
resource: string;
|
|
71
|
+
authorization_servers: string[];
|
|
72
|
+
scopes_supported?: string[];
|
|
73
|
+
bearer_methods_supported?: string[];
|
|
74
|
+
resource_name?: string;
|
|
75
|
+
[k: string]: unknown;
|
|
76
|
+
}
|
|
77
|
+
interface DiscoveryOptions {
|
|
78
|
+
fetch?: FetchLike;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* `GET <baseUrl>/.well-known/oauth-authorization-server`. Throws `STXAPIException`
|
|
82
|
+
* on a non-2xx or a body that is not the metadata document.
|
|
83
|
+
*/
|
|
84
|
+
declare function discoverMetadata(baseUrl?: string, opts?: DiscoveryOptions): Promise<AuthorizationServerMetadata>;
|
|
85
|
+
/** `GET <baseUrl>/.well-known/oauth-protected-resource`. */
|
|
86
|
+
declare function discoverProtectedResource(baseUrl?: string, opts?: DiscoveryOptions): Promise<ProtectedResourceMetadata>;
|
|
87
|
+
|
|
88
|
+
/** One sign-in in progress. */
|
|
89
|
+
interface PendingAuthorization {
|
|
90
|
+
codeVerifier: string;
|
|
91
|
+
/** The redirect URI sent to /authorize; the code exchange must repeat it. */
|
|
92
|
+
redirectUri: string;
|
|
93
|
+
/** The scope requested, space-delimited. */
|
|
94
|
+
scope?: string;
|
|
95
|
+
/** Epoch ms after which the entry is void. */
|
|
96
|
+
expiresAt: number;
|
|
97
|
+
/** Caller data carried to the callback: a user id, an app id, a return URL. */
|
|
98
|
+
data?: Record<string, unknown>;
|
|
99
|
+
}
|
|
100
|
+
interface PendingAuthorizationStore {
|
|
101
|
+
put(state: string, pending: PendingAuthorization): Promise<void> | void;
|
|
102
|
+
/** Return and delete the entry for `state`, or null. Single use. */
|
|
103
|
+
take(state: string): Promise<PendingAuthorization | null> | PendingAuthorization | null;
|
|
104
|
+
}
|
|
105
|
+
/** In-memory pending store. Expired entries are dropped on access. */
|
|
106
|
+
declare class MemoryPendingAuthorizationStore implements PendingAuthorizationStore {
|
|
107
|
+
private readonly map;
|
|
108
|
+
put(state: string, pending: PendingAuthorization): void;
|
|
109
|
+
take(state: string): PendingAuthorization | null;
|
|
110
|
+
/** Entries not yet taken or expired. */
|
|
111
|
+
get size(): number;
|
|
112
|
+
private sweep;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
interface StoredTokens {
|
|
116
|
+
accessToken: string;
|
|
117
|
+
refreshToken?: string;
|
|
118
|
+
/** Epoch ms when the access token expires, or undefined if unknown. */
|
|
119
|
+
expiresAt?: number;
|
|
120
|
+
/** Space-delimited effective scope granted, if the server returned it. */
|
|
121
|
+
scope?: string;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Persistence for one member's tokens. `memberKey` is any stable string the
|
|
125
|
+
* caller uses to identify a member (a user id, a session id, …). Methods may be
|
|
126
|
+
* sync or async.
|
|
127
|
+
*/
|
|
128
|
+
interface TokenStore {
|
|
129
|
+
get(memberKey: string): Promise<StoredTokens | null> | StoredTokens | null;
|
|
130
|
+
set(memberKey: string, tokens: StoredTokens): Promise<void> | void;
|
|
131
|
+
delete(memberKey: string): Promise<void> | void;
|
|
132
|
+
/**
|
|
133
|
+
* Optional: run `fn` holding an exclusive lock on this member. Implement it
|
|
134
|
+
* when several processes share the store, so only one of them refreshes a
|
|
135
|
+
* member's rotating refresh token at a time (a second, concurrent refresh
|
|
136
|
+
* with the same token trips reuse detection and revokes the grant). Within
|
|
137
|
+
* one process the SDK already single-flights refreshes.
|
|
138
|
+
*/
|
|
139
|
+
withLock?<T>(memberKey: string, fn: () => Promise<T>): Promise<T>;
|
|
140
|
+
}
|
|
141
|
+
/** Default in-memory store. Fine for scripts, demos and tests; not durable. */
|
|
142
|
+
declare class MemoryTokenStore implements TokenStore {
|
|
143
|
+
private readonly map;
|
|
144
|
+
get(memberKey: string): StoredTokens | null;
|
|
145
|
+
set(memberKey: string, tokens: StoredTokens): void;
|
|
146
|
+
delete(memberKey: string): void;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Parsed OAuth token response (RFC 6749 section 5.1). */
|
|
150
|
+
interface TokenSet {
|
|
151
|
+
accessToken: string;
|
|
152
|
+
/** Absent on a `client_credentials` app token. */
|
|
153
|
+
refreshToken?: string;
|
|
154
|
+
tokenType?: string;
|
|
155
|
+
/** Lifetime of the access token in seconds. */
|
|
156
|
+
expiresIn?: number;
|
|
157
|
+
/** Absolute epoch-ms expiry derived from `expiresIn`. */
|
|
158
|
+
expiresAt?: number;
|
|
159
|
+
/** Space-delimited effective scope after STX's narrowing. */
|
|
160
|
+
scope?: string;
|
|
161
|
+
}
|
|
162
|
+
type OAuthEndpoints = Pick<OAuthEndpoints$1, "authorize" | "token" | "revoke" | "introspect">;
|
|
163
|
+
interface OAuthClientOptions {
|
|
164
|
+
baseUrl?: string;
|
|
165
|
+
clientId: string;
|
|
166
|
+
/**
|
|
167
|
+
* The client secret for a confidential client (`client_secret_basic`). Omit
|
|
168
|
+
* for a public client registered with `token_endpoint_auth_method: none`: it
|
|
169
|
+
* then identifies with `client_id` in the form and PKCE is its proof. A public
|
|
170
|
+
* client cannot use `clientCredentials()`.
|
|
171
|
+
*/
|
|
172
|
+
clientSecret?: string;
|
|
173
|
+
/** The redirect URI registered with STX (exact-matched). Required for the code flow. */
|
|
174
|
+
redirectUri?: string;
|
|
175
|
+
/** Default scopes to request, space-delimited or as a list. */
|
|
176
|
+
scope?: string | readonly string[];
|
|
177
|
+
/** Endpoint overrides; absolute URLs (from discovery) or paths. */
|
|
178
|
+
endpoints?: Partial<OAuthEndpoints>;
|
|
179
|
+
fetch?: FetchLike;
|
|
180
|
+
}
|
|
181
|
+
/** Options for a store-backed member session adapter. */
|
|
182
|
+
interface SessionOptions {
|
|
183
|
+
/** Refresh this many ms before the access token expires. Default 30000. */
|
|
184
|
+
skewMs?: number;
|
|
185
|
+
/** Called with the new tokens after every successful refresh (already persisted). */
|
|
186
|
+
onRefresh?: (tokens: StoredTokens) => void | Promise<void>;
|
|
187
|
+
/** Called once when the grant is found revoked; the store entry is already deleted. */
|
|
188
|
+
onGrantRevoked?: (err: STXGrantRevokedException) => void | Promise<void>;
|
|
189
|
+
}
|
|
190
|
+
/** `STX` options for the `memberClient()` / `appClient()` shortcuts; host and auth come from the OAuth client. */
|
|
191
|
+
type OAuthRestOptions = Omit<STXOptions, "auth" | "keyId" | "privateKey" | "signer" | "profile" | "region" | "env" | "host">;
|
|
192
|
+
/** What `completeAuthorization()` returns. */
|
|
193
|
+
interface CompletedAuthorization {
|
|
194
|
+
tokens: TokenSet;
|
|
195
|
+
/** The granted scopes, canonical names. May be narrower than requested. */
|
|
196
|
+
scopes: string[];
|
|
197
|
+
/** The `data` passed to `beginAuthorization()`. */
|
|
198
|
+
data: Record<string, unknown> | undefined;
|
|
199
|
+
/** The member key the tokens were stored under, when a store was given. */
|
|
200
|
+
memberKey: string | undefined;
|
|
201
|
+
}
|
|
202
|
+
/** Where `completeAuthorization()` / `redeemAuthorization()` save the tokens. */
|
|
203
|
+
interface RedeemOptions {
|
|
204
|
+
store?: TokenStore;
|
|
205
|
+
/** A key, or a function of the `data` given to `beginAuthorization()`. */
|
|
206
|
+
memberKey?: string | ((data: Record<string, unknown> | undefined) => string);
|
|
207
|
+
}
|
|
208
|
+
/** A validated callback: the code and the pending sign-in its state named (now consumed). */
|
|
209
|
+
interface ReadCallback {
|
|
210
|
+
code: string;
|
|
211
|
+
pending: PendingAuthorization;
|
|
212
|
+
}
|
|
213
|
+
/** The query of an OAuth callback, in any of the shapes a server framework hands over. */
|
|
214
|
+
type CallbackInput = string | URL | URLSearchParams | Record<string, string | undefined | null>;
|
|
215
|
+
/** The prepared inputs for one authorization redirect. */
|
|
216
|
+
interface Authorization {
|
|
217
|
+
/** The full `/oauth/authorize` URL to send the member's browser to. */
|
|
218
|
+
url: string;
|
|
219
|
+
/** The `state` to store against this pending sign-in and verify on return. */
|
|
220
|
+
state: string;
|
|
221
|
+
/** The PKCE verifier to keep server-side and present at code exchange. */
|
|
222
|
+
codeVerifier: string;
|
|
223
|
+
/** The PKCE challenge that was embedded in `url`. */
|
|
224
|
+
codeChallenge: string;
|
|
225
|
+
}
|
|
226
|
+
interface AuthorizationParams {
|
|
227
|
+
scope?: string | readonly string[];
|
|
228
|
+
state?: string;
|
|
229
|
+
/** `none` for a silent background reconnect (RFC: prompt=none). */
|
|
230
|
+
prompt?: "none" | "login" | "consent";
|
|
231
|
+
redirectUri?: string;
|
|
232
|
+
/** Extra authorize params, passed through verbatim. */
|
|
233
|
+
extraParams?: Record<string, string>;
|
|
234
|
+
}
|
|
235
|
+
declare class OAuthClient {
|
|
236
|
+
readonly baseUrl: string;
|
|
237
|
+
readonly clientId: string;
|
|
238
|
+
private readonly clientSecret?;
|
|
239
|
+
readonly redirectUri?: string;
|
|
240
|
+
readonly scope?: string;
|
|
241
|
+
readonly endpoints: OAuthEndpoints;
|
|
242
|
+
private readonly fetch;
|
|
243
|
+
/**
|
|
244
|
+
* In-flight refreshes per token store and member, shared by every session
|
|
245
|
+
* adapter this client makes, so a burst of 401s across requests refreshes
|
|
246
|
+
* once. Two refreshes of one rotating token would trip reuse detection and
|
|
247
|
+
* revoke the grant.
|
|
248
|
+
*/
|
|
249
|
+
private readonly refreshes;
|
|
250
|
+
/** One cached app token per requested scope. */
|
|
251
|
+
private readonly appTokens;
|
|
252
|
+
constructor(opts: OAuthClientOptions);
|
|
253
|
+
/**
|
|
254
|
+
* Build a client from a discovered RFC 8414 document, so every endpoint is the
|
|
255
|
+
* one the exchange advertised on the host you asked. The base URL is the
|
|
256
|
+
* issuer unless overridden.
|
|
257
|
+
*/
|
|
258
|
+
static fromMetadata(metadata: AuthorizationServerMetadata, opts: Omit<OAuthClientOptions, "endpoints">): OAuthClient;
|
|
259
|
+
/** True for a public client (no secret): PKCE-only, no app tokens. */
|
|
260
|
+
get isPublic(): boolean;
|
|
261
|
+
/**
|
|
262
|
+
* Create a fresh PKCE pair (S256) + `state` and build the authorize URL in
|
|
263
|
+
* one call. Persist `state` and `codeVerifier` against the member's pending
|
|
264
|
+
* sign-in and verify `state` on the callback.
|
|
265
|
+
*/
|
|
266
|
+
authorizationUrl(params?: AuthorizationParams): Promise<Authorization>;
|
|
267
|
+
/** Alias of `authorizationUrl()` kept from 0.1. */
|
|
268
|
+
createAuthorization(params?: AuthorizationParams): Promise<Authorization>;
|
|
269
|
+
/**
|
|
270
|
+
* Start a sign-in: create PKCE + state, remember them (and `data`) in
|
|
271
|
+
* `pending` under the state, and return the authorize URL to redirect to.
|
|
272
|
+
* Finish with `completeAuthorization()` on the callback.
|
|
273
|
+
*/
|
|
274
|
+
beginAuthorization(pending: PendingAuthorizationStore, params?: AuthorizationParams & {
|
|
275
|
+
data?: Record<string, unknown>;
|
|
276
|
+
ttlMs?: number;
|
|
277
|
+
}): Promise<Authorization>;
|
|
278
|
+
/**
|
|
279
|
+
* Finish a sign-in from the callback's query. Checks for an `error` from
|
|
280
|
+
* the exchange (the member denied consent: `access_denied`), consumes the
|
|
281
|
+
* `state` (single use; unknown or expired throws `invalid_state`), exchanges
|
|
282
|
+
* the code with the stored PKCE verifier and, when `store` is given, saves
|
|
283
|
+
* the tokens under `memberKey` (a string, or a function of the `data` passed
|
|
284
|
+
* to `beginAuthorization()`).
|
|
285
|
+
*
|
|
286
|
+
* Every failure is an `STXOAuthException` whose `error` says which:
|
|
287
|
+
* `access_denied` and friends from the redirect, `invalid_request` (no code
|
|
288
|
+
* or state), `invalid_state`, or the token endpoint's own (`invalid_grant`
|
|
289
|
+
* for a used, expired or mismatched code).
|
|
290
|
+
*/
|
|
291
|
+
completeAuthorization(pending: PendingAuthorizationStore, callback: CallbackInput, opts?: RedeemOptions): Promise<CompletedAuthorization>;
|
|
292
|
+
/**
|
|
293
|
+
* The second half of `completeAuthorization()`: exchange a callback already
|
|
294
|
+
* read with `readCallback()`. Use the pair when one callback URL serves
|
|
295
|
+
* several apps and the app is only known from the pending entry's `data`.
|
|
296
|
+
*/
|
|
297
|
+
redeemAuthorization(callback: ReadCallback, opts?: RedeemOptions): Promise<CompletedAuthorization>;
|
|
298
|
+
/** Build the authorize URL from a challenge you already have. */
|
|
299
|
+
buildAuthorizeUrl(params: {
|
|
300
|
+
state: string;
|
|
301
|
+
codeChallenge: string;
|
|
302
|
+
scope?: string | readonly string[];
|
|
303
|
+
prompt?: "none" | "login" | "consent";
|
|
304
|
+
redirectUri?: string;
|
|
305
|
+
extraParams?: Record<string, string>;
|
|
306
|
+
}): string;
|
|
307
|
+
/** Exchange an authorization code for tokens, proving PKCE with the verifier. */
|
|
308
|
+
exchangeCode(args: {
|
|
309
|
+
code: string;
|
|
310
|
+
codeVerifier: string;
|
|
311
|
+
redirectUri?: string;
|
|
312
|
+
}): Promise<TokenSet>;
|
|
313
|
+
/**
|
|
314
|
+
* Trade a refresh token for a fresh access/refresh pair. STX ROTATES the
|
|
315
|
+
* refresh token, so the caller MUST persist whatever comes back. A rejected
|
|
316
|
+
* refresh (`invalid_grant`) means the grant was revoked, including STX's
|
|
317
|
+
* reuse detection tripping on a replayed/retired token, and surfaces as
|
|
318
|
+
* `STXGrantRevokedException`.
|
|
319
|
+
*/
|
|
320
|
+
refreshToken(refreshToken: string): Promise<TokenSet>;
|
|
321
|
+
/** Alias of `refreshToken()` kept from 0.1. */
|
|
322
|
+
refresh(refreshToken: string): Promise<TokenSet>;
|
|
323
|
+
/**
|
|
324
|
+
* Mint an APP token (RFC 6749 section 4.4): the client acting as itself, no
|
|
325
|
+
* member, no consent, no refresh token. Scoped to app scopes only
|
|
326
|
+
* (`market_data`, `events`); omit `scope` for every app scope the client is
|
|
327
|
+
* allowed. Requires a confidential client. For a cached, self-renewing
|
|
328
|
+
* token use `appToken()`.
|
|
329
|
+
*/
|
|
330
|
+
clientCredentials(scope?: string | readonly string[]): Promise<TokenSet>;
|
|
331
|
+
/**
|
|
332
|
+
* A cached `client_credentials` token that re-mints itself before expiry.
|
|
333
|
+
* The same scope returns the same provider, so every REST client and socket
|
|
334
|
+
* built from this OAuth client shares one token.
|
|
335
|
+
*/
|
|
336
|
+
appToken(scope?: string | readonly string[]): AppTokenProvider;
|
|
337
|
+
/** Revoke a token (either kind kills the pair). Always resolves on a 200. */
|
|
338
|
+
revoke(token: string, tokenTypeHint?: "access_token" | "refresh_token"): Promise<void>;
|
|
339
|
+
/**
|
|
340
|
+
* Unlink a member: revoke their grant at the exchange (best effort) and
|
|
341
|
+
* delete their tokens from `store`. Resolves true if the exchange confirmed
|
|
342
|
+
* the revoke, false if it could not be reached or refused; the local tokens
|
|
343
|
+
* are deleted either way.
|
|
344
|
+
*/
|
|
345
|
+
unlink(store: TokenStore, memberKey: string): Promise<boolean>;
|
|
346
|
+
/** Report a token's active state + scope. Confidential clients only. */
|
|
347
|
+
introspect(token: string): Promise<{
|
|
348
|
+
active: boolean;
|
|
349
|
+
scope?: string;
|
|
350
|
+
client_id?: string;
|
|
351
|
+
[k: string]: unknown;
|
|
352
|
+
}>;
|
|
353
|
+
/** A simple Bearer adapter around a known access token (no refresh). */
|
|
354
|
+
bearer(accessToken: string): OAuthBearerAuth;
|
|
355
|
+
/**
|
|
356
|
+
* A store-backed adapter that reads the member's tokens, attaches the Bearer
|
|
357
|
+
* header, refreshes proactively / on 401 with rotation, and clears the store
|
|
358
|
+
* (throwing `STXGrantRevokedException`) if the grant was revoked.
|
|
359
|
+
*/
|
|
360
|
+
session(store: TokenStore, memberKey: string, opts?: SessionOptions): OAuthSessionAuth;
|
|
361
|
+
/**
|
|
362
|
+
* An adapter authenticated as the APP (client_credentials): the public
|
|
363
|
+
* catalog over REST and the public market feeds over the socket. Re-mints
|
|
364
|
+
* before expiry, once on a 401, and fresh on every socket (re)connect.
|
|
365
|
+
*/
|
|
366
|
+
app(scope?: string | readonly string[]): OAuthAppAuth;
|
|
367
|
+
/**
|
|
368
|
+
* An `STX` REST client acting for one member, over `session(store,
|
|
369
|
+
* memberKey)`: every `/api/v1` method (balance, positions, fills, orders,
|
|
370
|
+
* place and cancel) with the Bearer token attached, refreshed before expiry
|
|
371
|
+
* and on a 401, and `client.websocket()` for the member's channels over the
|
|
372
|
+
* `x-stx-oauth-token` handshake.
|
|
373
|
+
*/
|
|
374
|
+
memberClient(store: TokenStore, memberKey: string, opts?: OAuthRestOptions & {
|
|
375
|
+
session?: SessionOptions;
|
|
376
|
+
}): STX;
|
|
377
|
+
/**
|
|
378
|
+
* An `STX` REST client acting as the app (client_credentials): the public
|
|
379
|
+
* catalog (`markets()`, `events()`) and, through `websocket()`, the public
|
|
380
|
+
* market channels. Scope defaults to every app scope the client may hold.
|
|
381
|
+
*/
|
|
382
|
+
appClient(scope?: string | readonly string[], opts?: OAuthRestOptions): STX;
|
|
383
|
+
/** @internal The in-flight refresh map for one store; see `OAuthSessionAuth`. */
|
|
384
|
+
_refreshesFor(store: TokenStore): Map<string, Promise<StoredTokens | null>>;
|
|
385
|
+
/** `client_secret_basic` header, or undefined for a public client. */
|
|
386
|
+
basicAuthHeader(): string | undefined;
|
|
387
|
+
private formHeaders;
|
|
388
|
+
/** A public client identifies with `client_id` in the form (RFC 6749 section 4.1.3). */
|
|
389
|
+
private withClientId;
|
|
390
|
+
private postToken;
|
|
391
|
+
private oauthError;
|
|
392
|
+
}
|
|
393
|
+
/** Parse and normalize an RFC 6749 section 5.1 token response. */
|
|
394
|
+
declare function parseTokenResponse(json: string | unknown): TokenSet;
|
|
395
|
+
/** Convert a TokenSet into the shape the TokenStore persists. */
|
|
396
|
+
declare function tokenSetToStored(set: TokenSet): StoredTokens;
|
|
397
|
+
/**
|
|
398
|
+
* A cached `client_credentials` token. Mints on first use, re-mints
|
|
399
|
+
* proactively when within `skewMs` of expiry (default 60s), dedupes
|
|
400
|
+
* concurrent mints, and can be invalidated after a 401 so the next call mints
|
|
401
|
+
* fresh. A token with no `expires_in` is treated as non-expiring; the 401
|
|
402
|
+
* safety net still covers it.
|
|
403
|
+
*/
|
|
404
|
+
declare class AppTokenProvider {
|
|
405
|
+
private readonly client;
|
|
406
|
+
private readonly scope?;
|
|
407
|
+
private cached;
|
|
408
|
+
private inflight;
|
|
409
|
+
readonly skewMs: number;
|
|
410
|
+
constructor(client: OAuthClient, scope?: (string | readonly string[]) | undefined, opts?: {
|
|
411
|
+
skewMs?: number;
|
|
412
|
+
});
|
|
413
|
+
/** A valid access token, minting if missing or near expiry. */
|
|
414
|
+
get(): Promise<string>;
|
|
415
|
+
/** Drop the cache so the next `get()` mints. Call after a 401. */
|
|
416
|
+
invalidate(): void;
|
|
417
|
+
/** Invalidate and mint now. Use before a socket reconnect. */
|
|
418
|
+
fresh(): Promise<string>;
|
|
419
|
+
/** The effective scope the exchange granted the current token, if minted. */
|
|
420
|
+
get grantedScope(): string | undefined;
|
|
421
|
+
private mint;
|
|
422
|
+
}
|
|
423
|
+
/** Bearer-token adapter with no refresh. Good for one-shot scripts. */
|
|
424
|
+
declare class OAuthBearerAuth implements AuthProvider {
|
|
425
|
+
private accessToken;
|
|
426
|
+
readonly kind = "oauth";
|
|
427
|
+
constructor(accessToken: string);
|
|
428
|
+
setAccessToken(token: string): void;
|
|
429
|
+
authHeaders(): Promise<Record<string, string>>;
|
|
430
|
+
websocketHeaders(): Promise<Record<string, string>>;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Store-backed OAuth adapter. Attaches the current member's access token,
|
|
434
|
+
* refreshes proactively when it is near expiry and on a 401 (rotating and
|
|
435
|
+
* persisting the new refresh token every time), and treats a revoked grant as
|
|
436
|
+
* terminal: the store entry is deleted and `STXGrantRevokedException` thrown.
|
|
437
|
+
*
|
|
438
|
+
* Refreshes are single-flight per (store, member) across every adapter the
|
|
439
|
+
* same `OAuthClient` makes, so concurrent requests for one member refresh
|
|
440
|
+
* once. A 401 on a token another request has already replaced is retried with
|
|
441
|
+
* the stored token, without a second refresh. Across processes, give the store
|
|
442
|
+
* a `withLock()` so only one replica refreshes a member at a time.
|
|
443
|
+
*/
|
|
444
|
+
declare class OAuthSessionAuth implements AuthProvider {
|
|
445
|
+
private readonly client;
|
|
446
|
+
private readonly store;
|
|
447
|
+
readonly memberKey: string;
|
|
448
|
+
private readonly opts;
|
|
449
|
+
readonly kind = "oauth";
|
|
450
|
+
/** Ms of slack before expiry at which to refresh proactively. */
|
|
451
|
+
readonly skewMs: number;
|
|
452
|
+
/** The access token last put on the wire, to tell a stale 401 from a dead token. */
|
|
453
|
+
private lastSent;
|
|
454
|
+
constructor(client: OAuthClient, store: TokenStore, memberKey: string, opts?: SessionOptions);
|
|
455
|
+
private load;
|
|
456
|
+
/** The member's current tokens, refreshed first if at or near expiry. */
|
|
457
|
+
tokens(): Promise<StoredTokens>;
|
|
458
|
+
/** The granted scopes of the stored tokens, canonical names. */
|
|
459
|
+
scopes(): Promise<string[]>;
|
|
460
|
+
authHeaders(_request?: AuthRequest): Promise<Record<string, string>>;
|
|
461
|
+
onUnauthorized(): Promise<boolean>;
|
|
462
|
+
/** Called on every (re)connect, so a reconnect after expiry gets a fresh token. */
|
|
463
|
+
websocketHeaders(_context?: WebSocketAuthContext): Promise<Record<string, string>>;
|
|
464
|
+
/**
|
|
465
|
+
* Refresh with rotation, single-flight. Persists the new pair (keeping the
|
|
466
|
+
* returned refresh token; the old one only if the server omitted it). On a
|
|
467
|
+
* revoked grant, deletes the store entry and throws
|
|
468
|
+
* `STXGrantRevokedException`. A transient failure resolves null.
|
|
469
|
+
*/
|
|
470
|
+
refresh(refreshToken: string): Promise<StoredTokens | null>;
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* App-token adapter (client_credentials). Bearer on REST, `x-stx-oauth-token`
|
|
474
|
+
* on the socket handshake. A 401 invalidates the cache and the request is
|
|
475
|
+
* retried once with a fresh mint; every socket (re)connect mints fresh, never
|
|
476
|
+
* reusing the token from a connection that just dropped.
|
|
477
|
+
*/
|
|
478
|
+
declare class OAuthAppAuth implements AuthProvider {
|
|
479
|
+
readonly tokens: AppTokenProvider;
|
|
480
|
+
readonly kind = "oauth_app";
|
|
481
|
+
constructor(tokens: AppTokenProvider);
|
|
482
|
+
authHeaders(_request?: AuthRequest): Promise<Record<string, string>>;
|
|
483
|
+
onUnauthorized(): Promise<boolean>;
|
|
484
|
+
/**
|
|
485
|
+
* The first connect uses the cached token; a reconnect (or a caller that
|
|
486
|
+
* does not say) mints fresh, never reusing the token from a connection that
|
|
487
|
+
* just dropped.
|
|
488
|
+
*/
|
|
489
|
+
websocketHeaders(context?: WebSocketAuthContext): Promise<Record<string, string>>;
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Validate an OAuth callback and consume its pending sign-in. Throws
|
|
493
|
+
* `STXOAuthException` with the redirect's `error` (`access_denied` when the
|
|
494
|
+
* member declined), `invalid_request` (no code or state) or `invalid_state`
|
|
495
|
+
* (unknown, used or expired). Does not call the exchange.
|
|
496
|
+
*/
|
|
497
|
+
declare function readCallback(pending: PendingAuthorizationStore, callback: CallbackInput, authorizeEndpoint?: string): Promise<ReadCallback>;
|
|
498
|
+
|
|
499
|
+
type TokenEndpointAuthMethod = "client_secret_basic" | "none";
|
|
500
|
+
type GrantType = "authorization_code" | "refresh_token" | "client_credentials";
|
|
501
|
+
/** RFC 7591 section 2 client metadata accepted by the exchange. */
|
|
502
|
+
interface ClientRegistrationRequest {
|
|
503
|
+
client_name: string;
|
|
504
|
+
redirect_uris: string[];
|
|
505
|
+
/** Space-delimited. Defaults to the exchange's configured member scope list. */
|
|
506
|
+
scope?: string;
|
|
507
|
+
/** Default `client_secret_basic`. `none` registers a public (PKCE-only) client. */
|
|
508
|
+
token_endpoint_auth_method?: TokenEndpointAuthMethod;
|
|
509
|
+
/** Default `["authorization_code", "refresh_token"]`. */
|
|
510
|
+
grant_types?: GrantType[];
|
|
511
|
+
/** Only `["code"]` is supported. */
|
|
512
|
+
response_types?: ["code"];
|
|
513
|
+
client_uri?: string;
|
|
514
|
+
logo_uri?: string;
|
|
515
|
+
software_id?: string;
|
|
516
|
+
software_version?: string;
|
|
517
|
+
}
|
|
518
|
+
/** RFC 7591 section 3.2.1 client information response. */
|
|
519
|
+
interface ClientRegistration {
|
|
520
|
+
client_id: string;
|
|
521
|
+
/** Unix seconds. */
|
|
522
|
+
client_id_issued_at: number;
|
|
523
|
+
/** Present for a confidential client only; shown once, never recoverable. */
|
|
524
|
+
client_secret?: string;
|
|
525
|
+
/** `0` means never. Present with `client_secret`. */
|
|
526
|
+
client_secret_expires_at?: number;
|
|
527
|
+
client_name: string;
|
|
528
|
+
redirect_uris: string[];
|
|
529
|
+
/** The stored scopes, space-delimited, defaults applied. */
|
|
530
|
+
scope: string;
|
|
531
|
+
grant_types: GrantType[];
|
|
532
|
+
response_types: string[];
|
|
533
|
+
token_endpoint_auth_method: TokenEndpointAuthMethod;
|
|
534
|
+
client_uri?: string;
|
|
535
|
+
logo_uri?: string;
|
|
536
|
+
software_id?: string;
|
|
537
|
+
software_version?: string;
|
|
538
|
+
}
|
|
539
|
+
interface RegisterClientOptions {
|
|
540
|
+
baseUrl?: string;
|
|
541
|
+
/** Absolute `registration_endpoint` from discovery, or a path. Default `/oauth/register`. */
|
|
542
|
+
registrationEndpoint?: string;
|
|
543
|
+
fetch?: FetchLike;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Register an OAuth client. Resolves with the client information on `201`.
|
|
547
|
+
* Throws `STXOAuthException` with the RFC error code on `400`
|
|
548
|
+
* (`invalid_redirect_uri`, `invalid_client_metadata`) and `429`
|
|
549
|
+
* (`rate_limited`, with `retryAfter` seconds); `STXAPIException` on `404`
|
|
550
|
+
* (registration disabled) and anything else.
|
|
551
|
+
*/
|
|
552
|
+
declare function registerClient(request: ClientRegistrationRequest, opts?: RegisterClientOptions): Promise<ClientRegistration>;
|
|
553
|
+
/** Parse an RFC 6749 section 5.2 error body, or null if the body is not one. */
|
|
554
|
+
declare function rfcError(text: string): {
|
|
555
|
+
error: string;
|
|
556
|
+
error_description?: string;
|
|
557
|
+
} | null;
|
|
558
|
+
|
|
559
|
+
/** Member scopes, in the exchange's canonical order. */
|
|
560
|
+
declare const MemberScopes: {
|
|
561
|
+
/** Who the member is: `me`, `GET /api/v1/me`. */
|
|
562
|
+
readonly PROFILE_READ: "profile.read";
|
|
563
|
+
/** Cash balance: `account`, `GET /api/v1/account/balance`, `balances:` channel. */
|
|
564
|
+
readonly BALANCE_READ: "balance.read";
|
|
565
|
+
/** Positions, settlements, loyalty/fee/adjustment ledgers, `positions:`/`settlements:`. */
|
|
566
|
+
readonly PORTFOLIO_READ: "portfolio.read";
|
|
567
|
+
/** Order and fill history, `orders:`/`fills:` channels. */
|
|
568
|
+
readonly ORDERS_READ: "orders.read";
|
|
569
|
+
/** Deposit and withdrawal history (read only). */
|
|
570
|
+
readonly TRANSFERS_READ: "transfers.read";
|
|
571
|
+
/** Place and cancel orders; arm `cancel_on_disconnect`. */
|
|
572
|
+
readonly ORDERS_WRITE: "orders.write";
|
|
573
|
+
/** Accept the terms and conditions. */
|
|
574
|
+
readonly TERMS_WRITE: "terms.write";
|
|
575
|
+
};
|
|
576
|
+
type MemberScope = (typeof MemberScopes)[keyof typeof MemberScopes];
|
|
577
|
+
/** App (machine) scopes for `client_credentials` tokens. */
|
|
578
|
+
declare const AppScopes: {
|
|
579
|
+
/** Public market catalog (`GET /api/v1/markets`) and the public market feeds. */
|
|
580
|
+
readonly MARKET_DATA: "market_data";
|
|
581
|
+
/** Public event catalog (`GET /api/v1/events`) and the `events` feed. */
|
|
582
|
+
readonly EVENTS: "events";
|
|
583
|
+
};
|
|
584
|
+
type AppScope = (typeof AppScopes)[keyof typeof AppScopes];
|
|
585
|
+
/** Both vocabularies under one name, for callers that do not care which. */
|
|
586
|
+
declare const Scopes: {
|
|
587
|
+
/** Public market catalog (`GET /api/v1/markets`) and the public market feeds. */
|
|
588
|
+
readonly MARKET_DATA: "market_data";
|
|
589
|
+
/** Public event catalog (`GET /api/v1/events`) and the `events` feed. */
|
|
590
|
+
readonly EVENTS: "events";
|
|
591
|
+
/** Who the member is: `me`, `GET /api/v1/me`. */
|
|
592
|
+
readonly PROFILE_READ: "profile.read";
|
|
593
|
+
/** Cash balance: `account`, `GET /api/v1/account/balance`, `balances:` channel. */
|
|
594
|
+
readonly BALANCE_READ: "balance.read";
|
|
595
|
+
/** Positions, settlements, loyalty/fee/adjustment ledgers, `positions:`/`settlements:`. */
|
|
596
|
+
readonly PORTFOLIO_READ: "portfolio.read";
|
|
597
|
+
/** Order and fill history, `orders:`/`fills:` channels. */
|
|
598
|
+
readonly ORDERS_READ: "orders.read";
|
|
599
|
+
/** Deposit and withdrawal history (read only). */
|
|
600
|
+
readonly TRANSFERS_READ: "transfers.read";
|
|
601
|
+
/** Place and cancel orders; arm `cancel_on_disconnect`. */
|
|
602
|
+
readonly ORDERS_WRITE: "orders.write";
|
|
603
|
+
/** Accept the terms and conditions. */
|
|
604
|
+
readonly TERMS_WRITE: "terms.write";
|
|
605
|
+
};
|
|
606
|
+
type Scope = MemberScope | AppScope;
|
|
607
|
+
/** Every member scope, canonical order. */
|
|
608
|
+
declare const ALL_MEMBER_SCOPES: readonly MemberScope[];
|
|
609
|
+
/** Every app scope, canonical order. */
|
|
610
|
+
declare const ALL_APP_SCOPES: readonly AppScope[];
|
|
611
|
+
/**
|
|
612
|
+
* Pre-`resource.action` names the exchange accepts for one release and
|
|
613
|
+
* canonicalises on entry. A token minted by an older exchange may still report
|
|
614
|
+
* them in its `scope` string.
|
|
615
|
+
*/
|
|
616
|
+
declare const LEGACY_SCOPES: Readonly<Record<string, MemberScope>>;
|
|
617
|
+
/** The current name for a scope; legacy names map forward, anything else passes through. */
|
|
618
|
+
declare function canonicalScope(scope: string): string;
|
|
619
|
+
/** Split a space-delimited `scope` string into canonical, de-duplicated scopes. */
|
|
620
|
+
declare function parseScopes(scope: string | null | undefined): string[];
|
|
621
|
+
/** Join scopes into the space-delimited wire form. */
|
|
622
|
+
declare function formatScopes(scopes: readonly string[]): string;
|
|
623
|
+
declare function isMemberScope(scope: string): scope is MemberScope;
|
|
624
|
+
declare function isAppScope(scope: string): scope is AppScope;
|
|
625
|
+
|
|
626
|
+
/** Standard base64url (no padding), the encoding PKCE requires. */
|
|
627
|
+
declare function base64url(bytes: Uint8Array): string;
|
|
628
|
+
/**
|
|
629
|
+
* A high-entropy `code_verifier`: 32 random bytes → 43-char base64url string,
|
|
630
|
+
* within the RFC 7636 43–128 character range.
|
|
631
|
+
*/
|
|
632
|
+
declare function generateCodeVerifier(): string;
|
|
633
|
+
/** The S256 challenge is `base64url(SHA-256(verifier))`. STX rejects `plain`. */
|
|
634
|
+
declare function codeChallengeS256(verifier: string): Promise<string>;
|
|
635
|
+
/** An opaque, unguessable CSRF `state` to tie /authorize to /callback. */
|
|
636
|
+
declare function generateState(): string;
|
|
637
|
+
interface Pkce {
|
|
638
|
+
codeVerifier: string;
|
|
639
|
+
codeChallenge: string;
|
|
640
|
+
}
|
|
641
|
+
/** Generate a verifier + its S256 challenge in one call. */
|
|
642
|
+
declare function createPkce(): Promise<Pkce>;
|
|
643
|
+
|
|
644
|
+
export { ALL_APP_SCOPES, ALL_MEMBER_SCOPES, type AppScope, AppScopes, AppTokenProvider, type Authorization, type AuthorizationParams, type AuthorizationServerMetadata, type CallbackInput, type ClientRegistration, type ClientRegistrationRequest, type CompletedAuthorization, DEFAULT_ENDPOINTS, type DiscoveryOptions, type FetchLike, type GrantType, LEGACY_SCOPES, type MemberScope, MemberScopes, MemoryPendingAuthorizationStore, MemoryTokenStore, OAuthAppAuth, OAuthBearerAuth, OAuthClient, type OAuthClientOptions, type OAuthEndpoints$1 as OAuthEndpoints, type OAuthRestOptions, OAuthSessionAuth, type PendingAuthorization, type PendingAuthorizationStore, type Pkce, type ProtectedResourceMetadata, type ReadCallback, type RedeemOptions, type RegisterClientOptions, STXAuthenticationException, STXGrantRevokedException, STXOAuthException, type Scope, Scopes, type SessionOptions, type StoredTokens, type TokenEndpointAuthMethod, type TokenSet, type TokenStore, WELL_KNOWN, base64url, canonicalScope, codeChallengeS256, createPkce, discoverMetadata, discoverProtectedResource, formatScopes, generateCodeVerifier, generateState, isAppScope, isMemberScope, joinUrl, parseScopes, parseTokenResponse, readCallback, registerClient, rfcError, tokenSetToStored };
|