@stxapp/stx-typescript 0.9.0-alpha.1 → 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/dist/oauth.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { av as STXAuthenticationException, g as AuthProvider, h as AuthRequest, a_ as WebSocketAuthContext, aF as STXOptions, at as STX } from './client-CNkaTuhG.cjs';
2
- export { aA as STXForbiddenException, aC as STXInsufficientScopeException, aD as STXInvalidTokenException } from './client-CNkaTuhG.cjs';
1
+ import { b3 as STXAuthenticationException, g as AuthProvider, h as AuthRequest, bE as WebSocketAuthContext, bi as STXOptions, b1 as STX } from './client-B-MMKiRt.cjs';
2
+ export { bb as STXForbiddenException, bd as STXIPNotAllowedException, be as STXInsufficientScopeException, bf as STXInvalidTokenException, bg as STXNotAvailableException, bm as STXTermsRequiredException } from './client-B-MMKiRt.cjs';
3
3
  import 'node:crypto';
4
4
 
5
5
  interface OAuthEndpoints$1 {
@@ -43,6 +43,11 @@ declare class STXOAuthException extends STXAuthenticationException {
43
43
  * verified.
44
44
  */
45
45
  readonly errorReason: string | undefined;
46
+ /**
47
+ * On an `invalid_scope` from the authorize callback, the scope the sign-in
48
+ * asked for (from the pending sign-in), so the cause can be named.
49
+ */
50
+ requestedScope: string | undefined;
46
51
  constructor(error: string, errorDescription: string | undefined, status: number, endpoint: string, retryAfter?: number, errorReason?: string);
47
52
  }
48
53
  /**
@@ -50,8 +55,9 @@ declare class STXOAuthException extends STXAuthenticationException {
50
55
  * `error=access_denied`. Either the member declined on the consent screen, or
51
56
  * their STX account cannot be connected (for example it is suspended or
52
57
  * closed). A member whose account is only still being verified gets
53
- * `STXAccountPendingException` instead. Nothing was granted and no tokens
54
- * exist; show your own "not connected" state.
58
+ * `STXAccountPendingException` instead, and one who left the STX terms page
59
+ * without agreeing gets `STXTermsNotAcceptedException`. Nothing was granted
60
+ * and no tokens exist; show your own "not connected" state.
55
61
  */
56
62
  declare class STXAccessDeniedException extends STXOAuthException {
57
63
  }
@@ -69,6 +75,19 @@ declare class STXAccessDeniedException extends STXOAuthException {
69
75
  */
70
76
  declare class STXAccountPendingException extends STXOAuthException {
71
77
  }
78
+ /**
79
+ * The member came back from the STX terms page without agreeing: the callback
80
+ * carries `error=terms_required`. STX shows that page during sign-in to a
81
+ * member who has not accepted the current terms. Nothing was granted and no
82
+ * tokens exist; show your own "not connected" state and let the member start
83
+ * again when they are ready.
84
+ *
85
+ * A member who is already connected when new terms take effect is a different
86
+ * case: their calls throw `STXTermsRequiredException`, which carries the page
87
+ * to send them to.
88
+ */
89
+ declare class STXTermsNotAcceptedException extends STXOAuthException {
90
+ }
72
91
  /**
73
92
  * The OAuth grant is no longer valid: a refresh was rejected with
74
93
  * `invalid_grant` (the member revoked the app, or a retired or reused refresh
@@ -108,8 +127,10 @@ interface DiscoveryOptions {
108
127
  fetch?: FetchLike;
109
128
  }
110
129
  /**
111
- * `GET <baseUrl>/.well-known/oauth-authorization-server`. Throws `STXAPIException`
112
- * on a non-2xx or a body that is not the metadata document.
130
+ * `GET <baseUrl>/.well-known/oauth-authorization-server`. Throws
131
+ * `STXNotAvailableException` (feature `oauth`) when the exchange has no OAuth
132
+ * (404, or a 403 page from the edge in front of it), and `STXAPIException` on
133
+ * any other non-2xx or a body that is not the metadata document.
113
134
  */
114
135
  declare function discoverMetadata(baseUrl?: string, opts?: DiscoveryOptions): Promise<AuthorizationServerMetadata>;
115
136
  /** `GET <baseUrl>/.well-known/oauth-protected-resource`. */
@@ -149,6 +170,14 @@ interface StoredTokens {
149
170
  expiresAt?: number;
150
171
  /** Space-delimited effective scope granted, if the server returned it. */
151
172
  scope?: string;
173
+ /**
174
+ * True when the last refresh said the member has not accepted the current
175
+ * STX terms. The tokens work; placing orders is refused until the member
176
+ * accepts at `termsUrl`. Absent once a later refresh no longer says so.
177
+ */
178
+ termsRequired?: boolean;
179
+ /** The STX page where the member accepts the terms. Present with `termsRequired`. */
180
+ termsUrl?: string;
152
181
  }
153
182
  /**
154
183
  * Persistence for one member's tokens. `memberKey` is any stable string the
@@ -190,6 +219,14 @@ interface TokenSet {
190
219
  scope?: string;
191
220
  /** The OpenID Connect ID token, when `openid` was granted. Verify it before trusting it (`createConnect` does). */
192
221
  idToken?: string;
222
+ /**
223
+ * True on a refresh when the member has not accepted the current STX terms.
224
+ * The refresh succeeded and the tokens work; placing orders is refused until
225
+ * the member accepts at `termsUrl`. Absent otherwise.
226
+ */
227
+ termsRequired?: boolean;
228
+ /** The STX page where the member accepts the terms. Present with `termsRequired`. */
229
+ termsUrl?: string;
193
230
  }
194
231
  type OAuthEndpoints = Pick<OAuthEndpoints$1, "authorize" | "token" | "revoke" | "introspect">;
195
232
  interface OAuthClientOptions {
@@ -210,6 +247,12 @@ interface OAuthClientOptions {
210
247
  scope?: string | readonly string[];
211
248
  /** Endpoint overrides; absolute URLs (from discovery) or paths. */
212
249
  endpoints?: Partial<OAuthEndpoints>;
250
+ /**
251
+ * The exchange's discovery document, when you have it (`OAuthClient.discover()`
252
+ * and `fromMetadata()` set it). With it, an `invalid_scope` for a scope the
253
+ * exchange does not list becomes `STXNotAvailableException`.
254
+ */
255
+ metadata?: AuthorizationServerMetadata;
213
256
  fetch?: FetchLike;
214
257
  }
215
258
  /** Options for a store-backed member session adapter. */
@@ -220,6 +263,14 @@ interface SessionOptions {
220
263
  onRefresh?: (tokens: StoredTokens) => void | Promise<void>;
221
264
  /** Called once when the grant is found revoked; the store entry is already deleted. */
222
265
  onGrantRevoked?: (err: STXGrantRevokedException) => void | Promise<void>;
266
+ /**
267
+ * Called after a refresh that says the member has not accepted the current
268
+ * STX terms (the new tokens are already persisted, and work). Send the
269
+ * member to `termsUrl` when they are next in your app.
270
+ */
271
+ onTermsRequired?: (info: {
272
+ termsUrl: string;
273
+ }) => void | Promise<void>;
223
274
  }
224
275
  /** `STX` options for the `memberClient()` / `appClient()` shortcuts; host and auth come from the OAuth client. */
225
276
  type OAuthRestOptions = Omit<STXOptions, "auth" | "keyId" | "privateKey" | "signer" | "profile" | "region" | "env" | "host">;
@@ -277,6 +328,8 @@ declare class OAuthClient {
277
328
  readonly redirectUri?: string;
278
329
  readonly scope?: string;
279
330
  readonly endpoints: OAuthEndpoints;
331
+ /** The discovery document this client was built from, if any. */
332
+ readonly metadata: AuthorizationServerMetadata | undefined;
280
333
  private readonly fetch;
281
334
  /**
282
335
  * In-flight refreshes per token store and member, shared by every session
@@ -293,7 +346,22 @@ declare class OAuthClient {
293
346
  * one the exchange advertised on the host you asked. The base URL is the
294
347
  * issuer unless overridden.
295
348
  */
296
- static fromMetadata(metadata: AuthorizationServerMetadata, opts: Omit<OAuthClientOptions, "endpoints">): OAuthClient;
349
+ static fromMetadata(metadata: AuthorizationServerMetadata, opts: Omit<OAuthClientOptions, "endpoints" | "metadata">): OAuthClient;
350
+ /**
351
+ * Fetch the exchange's discovery document and build a client from it. Throws
352
+ * `STXNotAvailableException` (feature `oauth`) on an exchange without OAuth,
353
+ * so an app can tell "not here yet" from a misconfiguration at start-up.
354
+ *
355
+ * const oauth = await OAuthClient.discover({
356
+ * baseUrl: "https://demo.stxapp.io",
357
+ * clientId: process.env.STX_CLIENT_ID!,
358
+ * clientSecret: process.env.STX_CLIENT_SECRET,
359
+ * redirectUri: "https://your.app/stx/callback",
360
+ * });
361
+ */
362
+ static discover(opts: Omit<OAuthClientOptions, "endpoints" | "metadata">): Promise<OAuthClient>;
363
+ /** The exchange host, e.g. `"demo.stxapp.io"`. */
364
+ get host(): string;
297
365
  /** True for a public client (no secret): PKCE-only, no app tokens. */
298
366
  get isPublic(): boolean;
299
367
  /**
@@ -315,7 +383,7 @@ declare class OAuthClient {
315
383
  }): Promise<Authorization>;
316
384
  /**
317
385
  * Finish a sign-in from the callback's query. Checks for an `error` from
318
- * the exchange (`access_denied`, `account_pending`), consumes the
386
+ * the exchange (`access_denied`, `account_pending`, `terms_required`), consumes the
319
387
  * `state` (single use; unknown or expired throws `invalid_state`), exchanges
320
388
  * the code with the stored PKCE verifier and, when `store` is given, saves
321
389
  * the tokens under `memberKey` (a string, or a function of the `data` passed
@@ -327,6 +395,14 @@ declare class OAuthClient {
327
395
  * for a used, expired or mismatched code).
328
396
  */
329
397
  completeAuthorization(pending: PendingAuthorizationStore, callback: CallbackInput, opts?: RedeemOptions): Promise<CompletedAuthorization>;
398
+ /**
399
+ * `STXNotAvailableException` for the first scope in `requested` that the
400
+ * discovery document does not list, or undefined when every scope is listed
401
+ * or there is no document to check against.
402
+ */
403
+ private unofferedScope;
404
+ /** `STXNotAvailableException` (feature `oauth`) for an OAuth endpoint the exchange does not have. */
405
+ private oauthMissing;
330
406
  /**
331
407
  * The second half of `completeAuthorization()`: exchange a callback already
332
408
  * read with `readCallback()`. Use the pair when one callback URL serves
@@ -354,6 +430,9 @@ declare class OAuthClient {
354
430
  * refresh (`invalid_grant`) means the grant was revoked, including STX's
355
431
  * reuse detection tripping on a replayed/retired token, and surfaces as
356
432
  * `STXGrantRevokedException`.
433
+ *
434
+ * While the member has not accepted the current STX terms the refresh still
435
+ * succeeds, and the result carries `termsRequired: true` and `termsUrl`.
357
436
  */
358
437
  refreshToken(refreshToken: string): Promise<TokenSet>;
359
438
  /** Alias of `refreshToken()` kept from 0.1. */
@@ -511,6 +590,8 @@ declare class OAuthSessionAuth implements AuthProvider {
511
590
  * revoked grant, deletes the store entry and throws
512
591
  * `STXGrantRevokedException`. While the member's account is still being
513
592
  * verified, keeps the store entry and throws `STXAccountPendingException`.
593
+ * A refresh that says the member has terms to accept is a success: the pair
594
+ * is stored with `termsRequired` and `termsUrl`, and `onTermsRequired` runs.
514
595
  * A transient failure resolves null.
515
596
  */
516
597
  refresh(refreshToken: string): Promise<StoredTokens | null>;
@@ -538,7 +619,9 @@ declare class OAuthAppAuth implements AuthProvider {
538
619
  * Validate an OAuth callback and consume its pending sign-in. Throws
539
620
  * `STXAccessDeniedException` (`access_denied`: the member declined, or STX did
540
621
  * not let them connect), `STXAccountPendingException` (`account_pending`: the
541
- * member's STX account is still being verified), or `STXOAuthException` with
622
+ * member's STX account is still being verified),
623
+ * `STXTermsNotAcceptedException` (`terms_required`: the member left the STX
624
+ * terms page without agreeing), or `STXOAuthException` with
542
625
  * any other redirect `error`, `invalid_request` (no code or state) or
543
626
  * `invalid_state` (unknown, used or expired). The state is checked and used up
544
627
  * first, so an error is reported only for a sign-in this app started. Does
@@ -546,6 +629,24 @@ declare class OAuthAppAuth implements AuthProvider {
546
629
  */
547
630
  declare function readCallback(pending: PendingAuthorizationStore, callback: CallbackInput, authorizeEndpoint?: string): Promise<ReadCallback>;
548
631
 
632
+ /**
633
+ * The URL to send the member's browser to so they can accept the current STX
634
+ * terms and come back to your app: `termsUrl` (from
635
+ * `STXTermsRequiredException.termsUrl`, or `termsUrl` on a refreshed token
636
+ * set) with `return_to` added.
637
+ *
638
+ * `returnTo` is the page in your app the member lands on afterwards. It must
639
+ * be one of your registered redirect URIs, or on the same origin as one. STX
640
+ * sends the member back to it unchanged.
641
+ *
642
+ * termsUrlWithReturn(
643
+ * "https://demo.stxapp.io/connect/terms?client_id=stxapp_client_9f2c41d7",
644
+ * "https://your.app/portfolio",
645
+ * );
646
+ * // https://demo.stxapp.io/connect/terms?client_id=stxapp_client_9f2c41d7&return_to=https%3A%2F%2Fyour.app%2Fportfolio
647
+ */
648
+ declare function termsUrlWithReturn(termsUrl: string, returnTo: string): string;
649
+
549
650
  /** The OpenID Connect discovery document, as far as `connect` uses it. */
550
651
  interface OpenIDConfiguration {
551
652
  issuer: string;
@@ -717,8 +818,6 @@ declare const MemberScopes: {
717
818
  readonly TRANSFERS_READ: "transfers.read";
718
819
  /** Place and cancel orders; arm `cancel_on_disconnect`. */
719
820
  readonly ORDERS_WRITE: "orders.write";
720
- /** Accept the terms and conditions. */
721
- readonly TERMS_WRITE: "terms.write";
722
821
  };
723
822
  type MemberScope = (typeof MemberScopes)[keyof typeof MemberScopes];
724
823
  /** App (machine) scopes for `client_credentials` tokens. */
@@ -751,8 +850,6 @@ declare const Scopes: {
751
850
  readonly TRANSFERS_READ: "transfers.read";
752
851
  /** Place and cancel orders; arm `cancel_on_disconnect`. */
753
852
  readonly ORDERS_WRITE: "orders.write";
754
- /** Accept the terms and conditions. */
755
- readonly TERMS_WRITE: "terms.write";
756
853
  };
757
854
  type Scope = MemberScope | AppScope;
758
855
  /** Every member scope, canonical order. */
@@ -767,7 +864,10 @@ declare const ALL_APP_SCOPES: readonly AppScope[];
767
864
  declare const LEGACY_SCOPES: Readonly<Record<string, MemberScope>>;
768
865
  /** The current name for a scope; legacy names map forward, anything else passes through. */
769
866
  declare function canonicalScope(scope: string): string;
770
- /** Split a space-delimited `scope` string into canonical, de-duplicated scopes. */
867
+ /**
868
+ * Split a space-delimited `scope` string into canonical, de-duplicated scopes.
869
+ * Retired scopes (`terms.write` and its older name `onboarding`) are left out.
870
+ */
771
871
  declare function parseScopes(scope: string | null | undefined): string[];
772
872
  /** Join scopes into the space-delimited wire form. */
773
873
  declare function formatScopes(scopes: readonly string[]): string;
@@ -792,4 +892,4 @@ interface Pkce {
792
892
  /** Generate a verifier + its S256 challenge in one call. */
793
893
  declare function createPkce(): Promise<Pkce>;
794
894
 
795
- 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, type Connect, type ConnectIdentity, type ConnectOptions, DEFAULT_ENDPOINTS, type DiscoveryOptions, type FetchLike, type FinishedSignIn, type GrantType, LEGACY_SCOPES, type MemberScope, MemberScopes, MemoryPendingAuthorizationStore, MemoryTokenStore, OAuthAppAuth, OAuthBearerAuth, OAuthClient, type OAuthClientOptions, type OAuthEndpoints$1 as OAuthEndpoints, type OAuthRestOptions, OAuthSessionAuth, type OpenIDConfiguration, type PendingAuthorization, type PendingAuthorizationStore, type Pkce, type ProtectedResourceMetadata, type ReadCallback, type RedeemOptions, type RegisterClientOptions, STXAccessDeniedException, STXAccountPendingException, STXAuthenticationException, STXGrantRevokedException, STXOAuthException, type SavedSignIn, type Scope, Scopes, type SessionOptions, type StartParams, type StartedSignIn, type StoredTokens, type TokenEndpointAuthMethod, type TokenSet, type TokenStore, WELL_KNOWN, base64url, canonicalScope, codeChallengeS256, createConnect, createPkce, discoverMetadata, discoverProtectedResource, formatScopes, generateCodeVerifier, generateState, isAppScope, isMemberScope, joinUrl, parseScopes, parseTokenResponse, readCallback, registerClient, rfcError, tokenSetToStored };
895
+ 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, type Connect, type ConnectIdentity, type ConnectOptions, DEFAULT_ENDPOINTS, type DiscoveryOptions, type FetchLike, type FinishedSignIn, type GrantType, LEGACY_SCOPES, type MemberScope, MemberScopes, MemoryPendingAuthorizationStore, MemoryTokenStore, OAuthAppAuth, OAuthBearerAuth, OAuthClient, type OAuthClientOptions, type OAuthEndpoints$1 as OAuthEndpoints, type OAuthRestOptions, OAuthSessionAuth, type OpenIDConfiguration, type PendingAuthorization, type PendingAuthorizationStore, type Pkce, type ProtectedResourceMetadata, type ReadCallback, type RedeemOptions, type RegisterClientOptions, STXAccessDeniedException, STXAccountPendingException, STXAuthenticationException, STXGrantRevokedException, STXOAuthException, STXTermsNotAcceptedException, type SavedSignIn, type Scope, Scopes, type SessionOptions, type StartParams, type StartedSignIn, type StoredTokens, type TokenEndpointAuthMethod, type TokenSet, type TokenStore, WELL_KNOWN, base64url, canonicalScope, codeChallengeS256, createConnect, createPkce, discoverMetadata, discoverProtectedResource, formatScopes, generateCodeVerifier, generateState, isAppScope, isMemberScope, joinUrl, parseScopes, parseTokenResponse, readCallback, registerClient, rfcError, termsUrlWithReturn, tokenSetToStored };
package/dist/oauth.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { av as STXAuthenticationException, g as AuthProvider, h as AuthRequest, a_ as WebSocketAuthContext, aF as STXOptions, at as STX } from './client-CNkaTuhG.js';
2
- export { aA as STXForbiddenException, aC as STXInsufficientScopeException, aD as STXInvalidTokenException } from './client-CNkaTuhG.js';
1
+ import { b3 as STXAuthenticationException, g as AuthProvider, h as AuthRequest, bE as WebSocketAuthContext, bi as STXOptions, b1 as STX } from './client-B-MMKiRt.js';
2
+ export { bb as STXForbiddenException, bd as STXIPNotAllowedException, be as STXInsufficientScopeException, bf as STXInvalidTokenException, bg as STXNotAvailableException, bm as STXTermsRequiredException } from './client-B-MMKiRt.js';
3
3
  import 'node:crypto';
4
4
 
5
5
  interface OAuthEndpoints$1 {
@@ -43,6 +43,11 @@ declare class STXOAuthException extends STXAuthenticationException {
43
43
  * verified.
44
44
  */
45
45
  readonly errorReason: string | undefined;
46
+ /**
47
+ * On an `invalid_scope` from the authorize callback, the scope the sign-in
48
+ * asked for (from the pending sign-in), so the cause can be named.
49
+ */
50
+ requestedScope: string | undefined;
46
51
  constructor(error: string, errorDescription: string | undefined, status: number, endpoint: string, retryAfter?: number, errorReason?: string);
47
52
  }
48
53
  /**
@@ -50,8 +55,9 @@ declare class STXOAuthException extends STXAuthenticationException {
50
55
  * `error=access_denied`. Either the member declined on the consent screen, or
51
56
  * their STX account cannot be connected (for example it is suspended or
52
57
  * closed). A member whose account is only still being verified gets
53
- * `STXAccountPendingException` instead. Nothing was granted and no tokens
54
- * exist; show your own "not connected" state.
58
+ * `STXAccountPendingException` instead, and one who left the STX terms page
59
+ * without agreeing gets `STXTermsNotAcceptedException`. Nothing was granted
60
+ * and no tokens exist; show your own "not connected" state.
55
61
  */
56
62
  declare class STXAccessDeniedException extends STXOAuthException {
57
63
  }
@@ -69,6 +75,19 @@ declare class STXAccessDeniedException extends STXOAuthException {
69
75
  */
70
76
  declare class STXAccountPendingException extends STXOAuthException {
71
77
  }
78
+ /**
79
+ * The member came back from the STX terms page without agreeing: the callback
80
+ * carries `error=terms_required`. STX shows that page during sign-in to a
81
+ * member who has not accepted the current terms. Nothing was granted and no
82
+ * tokens exist; show your own "not connected" state and let the member start
83
+ * again when they are ready.
84
+ *
85
+ * A member who is already connected when new terms take effect is a different
86
+ * case: their calls throw `STXTermsRequiredException`, which carries the page
87
+ * to send them to.
88
+ */
89
+ declare class STXTermsNotAcceptedException extends STXOAuthException {
90
+ }
72
91
  /**
73
92
  * The OAuth grant is no longer valid: a refresh was rejected with
74
93
  * `invalid_grant` (the member revoked the app, or a retired or reused refresh
@@ -108,8 +127,10 @@ interface DiscoveryOptions {
108
127
  fetch?: FetchLike;
109
128
  }
110
129
  /**
111
- * `GET <baseUrl>/.well-known/oauth-authorization-server`. Throws `STXAPIException`
112
- * on a non-2xx or a body that is not the metadata document.
130
+ * `GET <baseUrl>/.well-known/oauth-authorization-server`. Throws
131
+ * `STXNotAvailableException` (feature `oauth`) when the exchange has no OAuth
132
+ * (404, or a 403 page from the edge in front of it), and `STXAPIException` on
133
+ * any other non-2xx or a body that is not the metadata document.
113
134
  */
114
135
  declare function discoverMetadata(baseUrl?: string, opts?: DiscoveryOptions): Promise<AuthorizationServerMetadata>;
115
136
  /** `GET <baseUrl>/.well-known/oauth-protected-resource`. */
@@ -149,6 +170,14 @@ interface StoredTokens {
149
170
  expiresAt?: number;
150
171
  /** Space-delimited effective scope granted, if the server returned it. */
151
172
  scope?: string;
173
+ /**
174
+ * True when the last refresh said the member has not accepted the current
175
+ * STX terms. The tokens work; placing orders is refused until the member
176
+ * accepts at `termsUrl`. Absent once a later refresh no longer says so.
177
+ */
178
+ termsRequired?: boolean;
179
+ /** The STX page where the member accepts the terms. Present with `termsRequired`. */
180
+ termsUrl?: string;
152
181
  }
153
182
  /**
154
183
  * Persistence for one member's tokens. `memberKey` is any stable string the
@@ -190,6 +219,14 @@ interface TokenSet {
190
219
  scope?: string;
191
220
  /** The OpenID Connect ID token, when `openid` was granted. Verify it before trusting it (`createConnect` does). */
192
221
  idToken?: string;
222
+ /**
223
+ * True on a refresh when the member has not accepted the current STX terms.
224
+ * The refresh succeeded and the tokens work; placing orders is refused until
225
+ * the member accepts at `termsUrl`. Absent otherwise.
226
+ */
227
+ termsRequired?: boolean;
228
+ /** The STX page where the member accepts the terms. Present with `termsRequired`. */
229
+ termsUrl?: string;
193
230
  }
194
231
  type OAuthEndpoints = Pick<OAuthEndpoints$1, "authorize" | "token" | "revoke" | "introspect">;
195
232
  interface OAuthClientOptions {
@@ -210,6 +247,12 @@ interface OAuthClientOptions {
210
247
  scope?: string | readonly string[];
211
248
  /** Endpoint overrides; absolute URLs (from discovery) or paths. */
212
249
  endpoints?: Partial<OAuthEndpoints>;
250
+ /**
251
+ * The exchange's discovery document, when you have it (`OAuthClient.discover()`
252
+ * and `fromMetadata()` set it). With it, an `invalid_scope` for a scope the
253
+ * exchange does not list becomes `STXNotAvailableException`.
254
+ */
255
+ metadata?: AuthorizationServerMetadata;
213
256
  fetch?: FetchLike;
214
257
  }
215
258
  /** Options for a store-backed member session adapter. */
@@ -220,6 +263,14 @@ interface SessionOptions {
220
263
  onRefresh?: (tokens: StoredTokens) => void | Promise<void>;
221
264
  /** Called once when the grant is found revoked; the store entry is already deleted. */
222
265
  onGrantRevoked?: (err: STXGrantRevokedException) => void | Promise<void>;
266
+ /**
267
+ * Called after a refresh that says the member has not accepted the current
268
+ * STX terms (the new tokens are already persisted, and work). Send the
269
+ * member to `termsUrl` when they are next in your app.
270
+ */
271
+ onTermsRequired?: (info: {
272
+ termsUrl: string;
273
+ }) => void | Promise<void>;
223
274
  }
224
275
  /** `STX` options for the `memberClient()` / `appClient()` shortcuts; host and auth come from the OAuth client. */
225
276
  type OAuthRestOptions = Omit<STXOptions, "auth" | "keyId" | "privateKey" | "signer" | "profile" | "region" | "env" | "host">;
@@ -277,6 +328,8 @@ declare class OAuthClient {
277
328
  readonly redirectUri?: string;
278
329
  readonly scope?: string;
279
330
  readonly endpoints: OAuthEndpoints;
331
+ /** The discovery document this client was built from, if any. */
332
+ readonly metadata: AuthorizationServerMetadata | undefined;
280
333
  private readonly fetch;
281
334
  /**
282
335
  * In-flight refreshes per token store and member, shared by every session
@@ -293,7 +346,22 @@ declare class OAuthClient {
293
346
  * one the exchange advertised on the host you asked. The base URL is the
294
347
  * issuer unless overridden.
295
348
  */
296
- static fromMetadata(metadata: AuthorizationServerMetadata, opts: Omit<OAuthClientOptions, "endpoints">): OAuthClient;
349
+ static fromMetadata(metadata: AuthorizationServerMetadata, opts: Omit<OAuthClientOptions, "endpoints" | "metadata">): OAuthClient;
350
+ /**
351
+ * Fetch the exchange's discovery document and build a client from it. Throws
352
+ * `STXNotAvailableException` (feature `oauth`) on an exchange without OAuth,
353
+ * so an app can tell "not here yet" from a misconfiguration at start-up.
354
+ *
355
+ * const oauth = await OAuthClient.discover({
356
+ * baseUrl: "https://demo.stxapp.io",
357
+ * clientId: process.env.STX_CLIENT_ID!,
358
+ * clientSecret: process.env.STX_CLIENT_SECRET,
359
+ * redirectUri: "https://your.app/stx/callback",
360
+ * });
361
+ */
362
+ static discover(opts: Omit<OAuthClientOptions, "endpoints" | "metadata">): Promise<OAuthClient>;
363
+ /** The exchange host, e.g. `"demo.stxapp.io"`. */
364
+ get host(): string;
297
365
  /** True for a public client (no secret): PKCE-only, no app tokens. */
298
366
  get isPublic(): boolean;
299
367
  /**
@@ -315,7 +383,7 @@ declare class OAuthClient {
315
383
  }): Promise<Authorization>;
316
384
  /**
317
385
  * Finish a sign-in from the callback's query. Checks for an `error` from
318
- * the exchange (`access_denied`, `account_pending`), consumes the
386
+ * the exchange (`access_denied`, `account_pending`, `terms_required`), consumes the
319
387
  * `state` (single use; unknown or expired throws `invalid_state`), exchanges
320
388
  * the code with the stored PKCE verifier and, when `store` is given, saves
321
389
  * the tokens under `memberKey` (a string, or a function of the `data` passed
@@ -327,6 +395,14 @@ declare class OAuthClient {
327
395
  * for a used, expired or mismatched code).
328
396
  */
329
397
  completeAuthorization(pending: PendingAuthorizationStore, callback: CallbackInput, opts?: RedeemOptions): Promise<CompletedAuthorization>;
398
+ /**
399
+ * `STXNotAvailableException` for the first scope in `requested` that the
400
+ * discovery document does not list, or undefined when every scope is listed
401
+ * or there is no document to check against.
402
+ */
403
+ private unofferedScope;
404
+ /** `STXNotAvailableException` (feature `oauth`) for an OAuth endpoint the exchange does not have. */
405
+ private oauthMissing;
330
406
  /**
331
407
  * The second half of `completeAuthorization()`: exchange a callback already
332
408
  * read with `readCallback()`. Use the pair when one callback URL serves
@@ -354,6 +430,9 @@ declare class OAuthClient {
354
430
  * refresh (`invalid_grant`) means the grant was revoked, including STX's
355
431
  * reuse detection tripping on a replayed/retired token, and surfaces as
356
432
  * `STXGrantRevokedException`.
433
+ *
434
+ * While the member has not accepted the current STX terms the refresh still
435
+ * succeeds, and the result carries `termsRequired: true` and `termsUrl`.
357
436
  */
358
437
  refreshToken(refreshToken: string): Promise<TokenSet>;
359
438
  /** Alias of `refreshToken()` kept from 0.1. */
@@ -511,6 +590,8 @@ declare class OAuthSessionAuth implements AuthProvider {
511
590
  * revoked grant, deletes the store entry and throws
512
591
  * `STXGrantRevokedException`. While the member's account is still being
513
592
  * verified, keeps the store entry and throws `STXAccountPendingException`.
593
+ * A refresh that says the member has terms to accept is a success: the pair
594
+ * is stored with `termsRequired` and `termsUrl`, and `onTermsRequired` runs.
514
595
  * A transient failure resolves null.
515
596
  */
516
597
  refresh(refreshToken: string): Promise<StoredTokens | null>;
@@ -538,7 +619,9 @@ declare class OAuthAppAuth implements AuthProvider {
538
619
  * Validate an OAuth callback and consume its pending sign-in. Throws
539
620
  * `STXAccessDeniedException` (`access_denied`: the member declined, or STX did
540
621
  * not let them connect), `STXAccountPendingException` (`account_pending`: the
541
- * member's STX account is still being verified), or `STXOAuthException` with
622
+ * member's STX account is still being verified),
623
+ * `STXTermsNotAcceptedException` (`terms_required`: the member left the STX
624
+ * terms page without agreeing), or `STXOAuthException` with
542
625
  * any other redirect `error`, `invalid_request` (no code or state) or
543
626
  * `invalid_state` (unknown, used or expired). The state is checked and used up
544
627
  * first, so an error is reported only for a sign-in this app started. Does
@@ -546,6 +629,24 @@ declare class OAuthAppAuth implements AuthProvider {
546
629
  */
547
630
  declare function readCallback(pending: PendingAuthorizationStore, callback: CallbackInput, authorizeEndpoint?: string): Promise<ReadCallback>;
548
631
 
632
+ /**
633
+ * The URL to send the member's browser to so they can accept the current STX
634
+ * terms and come back to your app: `termsUrl` (from
635
+ * `STXTermsRequiredException.termsUrl`, or `termsUrl` on a refreshed token
636
+ * set) with `return_to` added.
637
+ *
638
+ * `returnTo` is the page in your app the member lands on afterwards. It must
639
+ * be one of your registered redirect URIs, or on the same origin as one. STX
640
+ * sends the member back to it unchanged.
641
+ *
642
+ * termsUrlWithReturn(
643
+ * "https://demo.stxapp.io/connect/terms?client_id=stxapp_client_9f2c41d7",
644
+ * "https://your.app/portfolio",
645
+ * );
646
+ * // https://demo.stxapp.io/connect/terms?client_id=stxapp_client_9f2c41d7&return_to=https%3A%2F%2Fyour.app%2Fportfolio
647
+ */
648
+ declare function termsUrlWithReturn(termsUrl: string, returnTo: string): string;
649
+
549
650
  /** The OpenID Connect discovery document, as far as `connect` uses it. */
550
651
  interface OpenIDConfiguration {
551
652
  issuer: string;
@@ -717,8 +818,6 @@ declare const MemberScopes: {
717
818
  readonly TRANSFERS_READ: "transfers.read";
718
819
  /** Place and cancel orders; arm `cancel_on_disconnect`. */
719
820
  readonly ORDERS_WRITE: "orders.write";
720
- /** Accept the terms and conditions. */
721
- readonly TERMS_WRITE: "terms.write";
722
821
  };
723
822
  type MemberScope = (typeof MemberScopes)[keyof typeof MemberScopes];
724
823
  /** App (machine) scopes for `client_credentials` tokens. */
@@ -751,8 +850,6 @@ declare const Scopes: {
751
850
  readonly TRANSFERS_READ: "transfers.read";
752
851
  /** Place and cancel orders; arm `cancel_on_disconnect`. */
753
852
  readonly ORDERS_WRITE: "orders.write";
754
- /** Accept the terms and conditions. */
755
- readonly TERMS_WRITE: "terms.write";
756
853
  };
757
854
  type Scope = MemberScope | AppScope;
758
855
  /** Every member scope, canonical order. */
@@ -767,7 +864,10 @@ declare const ALL_APP_SCOPES: readonly AppScope[];
767
864
  declare const LEGACY_SCOPES: Readonly<Record<string, MemberScope>>;
768
865
  /** The current name for a scope; legacy names map forward, anything else passes through. */
769
866
  declare function canonicalScope(scope: string): string;
770
- /** Split a space-delimited `scope` string into canonical, de-duplicated scopes. */
867
+ /**
868
+ * Split a space-delimited `scope` string into canonical, de-duplicated scopes.
869
+ * Retired scopes (`terms.write` and its older name `onboarding`) are left out.
870
+ */
771
871
  declare function parseScopes(scope: string | null | undefined): string[];
772
872
  /** Join scopes into the space-delimited wire form. */
773
873
  declare function formatScopes(scopes: readonly string[]): string;
@@ -792,4 +892,4 @@ interface Pkce {
792
892
  /** Generate a verifier + its S256 challenge in one call. */
793
893
  declare function createPkce(): Promise<Pkce>;
794
894
 
795
- 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, type Connect, type ConnectIdentity, type ConnectOptions, DEFAULT_ENDPOINTS, type DiscoveryOptions, type FetchLike, type FinishedSignIn, type GrantType, LEGACY_SCOPES, type MemberScope, MemberScopes, MemoryPendingAuthorizationStore, MemoryTokenStore, OAuthAppAuth, OAuthBearerAuth, OAuthClient, type OAuthClientOptions, type OAuthEndpoints$1 as OAuthEndpoints, type OAuthRestOptions, OAuthSessionAuth, type OpenIDConfiguration, type PendingAuthorization, type PendingAuthorizationStore, type Pkce, type ProtectedResourceMetadata, type ReadCallback, type RedeemOptions, type RegisterClientOptions, STXAccessDeniedException, STXAccountPendingException, STXAuthenticationException, STXGrantRevokedException, STXOAuthException, type SavedSignIn, type Scope, Scopes, type SessionOptions, type StartParams, type StartedSignIn, type StoredTokens, type TokenEndpointAuthMethod, type TokenSet, type TokenStore, WELL_KNOWN, base64url, canonicalScope, codeChallengeS256, createConnect, createPkce, discoverMetadata, discoverProtectedResource, formatScopes, generateCodeVerifier, generateState, isAppScope, isMemberScope, joinUrl, parseScopes, parseTokenResponse, readCallback, registerClient, rfcError, tokenSetToStored };
895
+ 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, type Connect, type ConnectIdentity, type ConnectOptions, DEFAULT_ENDPOINTS, type DiscoveryOptions, type FetchLike, type FinishedSignIn, type GrantType, LEGACY_SCOPES, type MemberScope, MemberScopes, MemoryPendingAuthorizationStore, MemoryTokenStore, OAuthAppAuth, OAuthBearerAuth, OAuthClient, type OAuthClientOptions, type OAuthEndpoints$1 as OAuthEndpoints, type OAuthRestOptions, OAuthSessionAuth, type OpenIDConfiguration, type PendingAuthorization, type PendingAuthorizationStore, type Pkce, type ProtectedResourceMetadata, type ReadCallback, type RedeemOptions, type RegisterClientOptions, STXAccessDeniedException, STXAccountPendingException, STXAuthenticationException, STXGrantRevokedException, STXOAuthException, STXTermsNotAcceptedException, type SavedSignIn, type Scope, Scopes, type SessionOptions, type StartParams, type StartedSignIn, type StoredTokens, type TokenEndpointAuthMethod, type TokenSet, type TokenStore, WELL_KNOWN, base64url, canonicalScope, codeChallengeS256, createConnect, createPkce, discoverMetadata, discoverProtectedResource, formatScopes, generateCodeVerifier, generateState, isAppScope, isMemberScope, joinUrl, parseScopes, parseTokenResponse, readCallback, registerClient, rfcError, termsUrlWithReturn, tokenSetToStored };