tigeropen 0.5.7 → 0.5.9

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.
Files changed (77) hide show
  1. package/README.md +159 -0
  2. package/dist/cjs/client/api-response.js +6 -5
  3. package/dist/cjs/index.js +4 -2
  4. package/dist/cjs/model/news-requests.js +9 -0
  5. package/dist/cjs/model/news.js +8 -0
  6. package/dist/cjs/news/index.js +8 -0
  7. package/dist/cjs/news/news-client.js +84 -0
  8. package/dist/cjs/push/pb/QuoteBasicData.js +37 -1
  9. package/dist/cjs/push/pb/QuoteData.js +37 -1
  10. package/dist/cjs/quote/quote-client.js +4 -1
  11. package/dist/cjs/trade/trade-client.js +26 -4
  12. package/dist/cjs/version.js +1 -1
  13. package/dist/esm/client/api-response.js +6 -5
  14. package/dist/esm/index.js +2 -1
  15. package/dist/esm/model/news-requests.js +8 -0
  16. package/dist/esm/model/news.js +7 -0
  17. package/dist/esm/news/index.js +4 -0
  18. package/dist/esm/news/news-client.js +80 -0
  19. package/dist/esm/push/pb/QuoteBasicData.js +37 -1
  20. package/dist/esm/push/pb/QuoteData.js +37 -1
  21. package/dist/esm/quote/quote-client.js +4 -1
  22. package/dist/esm/trade/trade-client.js +26 -4
  23. package/dist/esm/version.js +1 -1
  24. package/dist/types/index.d.ts +8 -4
  25. package/dist/types/model/contract.d.ts +8 -0
  26. package/dist/types/model/news-requests.d.ts +39 -0
  27. package/dist/types/model/news.d.ts +38 -0
  28. package/dist/types/model/order.d.ts +2 -0
  29. package/dist/types/model/quote.d.ts +16 -0
  30. package/dist/types/model/trade-requests.d.ts +20 -1
  31. package/dist/types/news/index.d.ts +5 -0
  32. package/dist/types/news/news-client.d.ts +60 -0
  33. package/dist/types/push/pb/QuoteBasicData.d.ts +14 -5
  34. package/dist/types/push/pb/QuoteData.d.ts +14 -5
  35. package/dist/types/quote/quote-client.d.ts +2 -1
  36. package/dist/types/trade/trade-client.d.ts +10 -2
  37. package/dist/types/version.d.ts +1 -1
  38. package/package.json +2 -3
  39. package/dist/cjs/auth/authentication.js +0 -74
  40. package/dist/cjs/auth/index.js +0 -24
  41. package/dist/cjs/auth/oauth2/client-registration.js +0 -44
  42. package/dist/cjs/auth/oauth2/device-authorization.js +0 -40
  43. package/dist/cjs/auth/oauth2/errors.js +0 -64
  44. package/dist/cjs/auth/oauth2/http-utils.js +0 -112
  45. package/dist/cjs/auth/oauth2/index.js +0 -42
  46. package/dist/cjs/auth/oauth2/loopback-receiver.js +0 -215
  47. package/dist/cjs/auth/oauth2/metadata.js +0 -34
  48. package/dist/cjs/auth/oauth2/oauth2-authentication.js +0 -74
  49. package/dist/cjs/auth/oauth2/session-manager.js +0 -762
  50. package/dist/cjs/auth/oauth2/token-store.js +0 -252
  51. package/dist/cjs/auth/oauth2/token.js +0 -76
  52. package/dist/esm/auth/authentication.js +0 -68
  53. package/dist/esm/auth/index.js +0 -3
  54. package/dist/esm/auth/oauth2/client-registration.js +0 -40
  55. package/dist/esm/auth/oauth2/device-authorization.js +0 -36
  56. package/dist/esm/auth/oauth2/errors.js +0 -59
  57. package/dist/esm/auth/oauth2/http-utils.js +0 -105
  58. package/dist/esm/auth/oauth2/index.js +0 -11
  59. package/dist/esm/auth/oauth2/loopback-receiver.js +0 -178
  60. package/dist/esm/auth/oauth2/metadata.js +0 -30
  61. package/dist/esm/auth/oauth2/oauth2-authentication.js +0 -70
  62. package/dist/esm/auth/oauth2/session-manager.js +0 -725
  63. package/dist/esm/auth/oauth2/token-store.js +0 -214
  64. package/dist/esm/auth/oauth2/token.js +0 -71
  65. package/dist/types/auth/authentication.d.ts +0 -98
  66. package/dist/types/auth/index.d.ts +0 -4
  67. package/dist/types/auth/oauth2/client-registration.d.ts +0 -32
  68. package/dist/types/auth/oauth2/device-authorization.d.ts +0 -40
  69. package/dist/types/auth/oauth2/errors.d.ts +0 -46
  70. package/dist/types/auth/oauth2/http-utils.d.ts +0 -21
  71. package/dist/types/auth/oauth2/index.d.ts +0 -16
  72. package/dist/types/auth/oauth2/loopback-receiver.d.ts +0 -29
  73. package/dist/types/auth/oauth2/metadata.d.ts +0 -32
  74. package/dist/types/auth/oauth2/oauth2-authentication.d.ts +0 -31
  75. package/dist/types/auth/oauth2/session-manager.d.ts +0 -241
  76. package/dist/types/auth/oauth2/token-store.d.ts +0 -49
  77. package/dist/types/auth/oauth2/token.d.ts +0 -56
@@ -1,214 +0,0 @@
1
- /**
2
- * File-backed OAuth 2.0 authorization state.
3
- *
4
- * Storage layout:
5
- *
6
- * ~/.tiger/openapi/
7
- * tokens/{clientId}.json authorization state, mode 0600, removed on logout
8
- * clients/{issuerHash}-{surface}.json dynamic registration, retained across logout
9
- *
10
- * Registration files are keyed by issuer because the client ID is not yet available
11
- * during lookup, and by surface so that each entry point registers its own client.
12
- * Without the surface, whichever entry point ran first would own the registration and
13
- * every other one would silently inherit its identity: one name on the user's
14
- * authorization page, one revocation switch for all of them, and one shared token file
15
- * whose refresh-token rotation they would race over.
16
- *
17
- * Token files need no surface: each surface registers a distinct client ID, so their
18
- * token files are already distinct. A manually configured client ID is shared on
19
- * purpose -- one client ID means one application.
20
- *
21
- * Storage root precedence is: explicit argument, `TIGEROPEN_HOME`, then
22
- * `~/.tiger/openapi`. The format is shared with the Java and Python SDKs.
23
- */
24
- import { createHash } from 'crypto';
25
- import * as fs from 'fs';
26
- import { homedir } from 'os';
27
- import * as path from 'path';
28
- import { OAuth2ClientRegistration } from './client-registration.js';
29
- import { OAuth2Category, OAuth2Error } from './errors.js';
30
- import { OAuth2Token, TOKEN_SCHEMA_VERSION } from './token.js';
31
- export const ENV_HOME = 'TIGEROPEN_HOME';
32
- /**
33
- * Entry point owning a registration. Tools built on this SDK must pass their own value,
34
- * otherwise they would be filed as the TypeScript SDK and share its client. Keep in
35
- * step with the Java SDK's `sdk-java` and the Python SDK's `sdk-python`.
36
- */
37
- export const DEFAULT_SURFACE = 'sdk-typescript';
38
- const SAFE_CHARS = /[^a-zA-Z0-9\-_.]/g;
39
- /**
40
- * Surfaces become part of a file name, so they are restricted rather than sanitised: a
41
- * silently rewritten surface would file two entry points under one name.
42
- */
43
- const SURFACE_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
44
- export class OAuth2TokenStore {
45
- /**
46
- * @param home storage root; defaults to `TIGEROPEN_HOME` then `~/.tiger/openapi`
47
- * @param surface entry point owning the registration, e.g. `sdk-typescript`, `cli`.
48
- * Lowercase alphanumerics and hyphens only
49
- */
50
- constructor(home, surface = DEFAULT_SURFACE) {
51
- const base = home || process.env[ENV_HOME] || path.join(homedir(), '.tiger', 'openapi');
52
- this.home = path.resolve(expandHome(base));
53
- this.surface = validateSurface(surface);
54
- }
55
- /** Load a token, treating a missing file or issuer mismatch as a cache miss. */
56
- loadToken(clientId, expectedIssuer) {
57
- const file = this.tokenFile(clientId);
58
- if (!fs.existsSync(file))
59
- return null;
60
- let token;
61
- try {
62
- token = OAuth2Token.fromJSON(JSON.parse(fs.readFileSync(file, 'utf-8')));
63
- }
64
- catch (e) {
65
- // A corrupt file tells us nothing; treat it as no authorization rather than crash.
66
- console.error(`[TigerOpen] read token file fail: ${file}`, e);
67
- return null;
68
- }
69
- if (!token)
70
- return null;
71
- if (token.schemaVersion !== TOKEN_SCHEMA_VERSION) {
72
- // Unknown schema versions are not interpreted.
73
- throw new OAuth2Error(OAuth2Category.StorageFailed, `unsupported token schema_version: ${token.schemaVersion}`);
74
- }
75
- if (expectedIssuer !== undefined && expectedIssuer !== token.issuer) {
76
- return null;
77
- }
78
- return token;
79
- }
80
- saveToken(token) {
81
- if (!token || !token.clientId) {
82
- throw new OAuth2Error(OAuth2Category.StorageFailed, 'token or clientId is empty, cannot save');
83
- }
84
- writeAtomic(this.tokenFile(token.clientId), JSON.stringify(token.toJSON(), null, 2));
85
- }
86
- /**
87
- * Delete authorization state while retaining client registration.
88
- *
89
- * @returns the path removed, or null when there was nothing to remove. A clientId is
90
- * not its own file name, so a caller reporting what it deleted has to be told rather
91
- * than build the path itself
92
- */
93
- deleteToken(clientId) {
94
- if (!clientId)
95
- return null;
96
- const file = this.tokenFile(clientId);
97
- return deleteFile(file) ? file : null;
98
- }
99
- loadClientId(issuer) {
100
- return this.loadClientRegistration(issuer)?.clientId ?? null;
101
- }
102
- loadClientRegistration(issuer) {
103
- const file = this.clientFile(issuer);
104
- if (!fs.existsSync(file))
105
- return null;
106
- try {
107
- return OAuth2ClientRegistration.fromJSON(JSON.parse(fs.readFileSync(file, 'utf-8')));
108
- }
109
- catch (e) {
110
- console.error(`[TigerOpen] read client registration file fail: ${file}`, e);
111
- return null;
112
- }
113
- }
114
- saveClientRegistration(registration) {
115
- if (!registration || !registration.issuer) {
116
- throw new OAuth2Error(OAuth2Category.StorageFailed, 'registration or issuer is empty, cannot save');
117
- }
118
- writeAtomic(this.clientFile(registration.issuer), JSON.stringify(registration.toJSON(), null, 2));
119
- }
120
- /** Delete registration state after an `invalid_client` response. */
121
- deleteClientRegistration(issuer) {
122
- if (!issuer)
123
- return;
124
- deleteFile(this.clientFile(issuer));
125
- }
126
- tokenFile(clientId) {
127
- return path.join(this.home, 'tokens', `${safeFileName(clientId)}.json`);
128
- }
129
- clientFile(issuer) {
130
- return path.join(this.home, 'clients', `${hashIssuer(issuer)}-${this.surface}.json`);
131
- }
132
- }
133
- /** Return the Java-compatible 32-character SHA-256 issuer file key. */
134
- export function hashIssuer(issuer) {
135
- return createHash('sha256').update(issuer || '', 'utf-8').digest('hex').slice(0, 32);
136
- }
137
- /** Sanitize an untrusted client ID for use as a file name. */
138
- function safeFileName(raw) {
139
- let name = (raw || '').replace(SAFE_CHARS, '_');
140
- while (name.includes('..')) {
141
- name = name.replace(/\.\./g, '__');
142
- }
143
- return name || '_';
144
- }
145
- /** Reject a surface that cannot be used verbatim as part of a file name. */
146
- function validateSurface(surface) {
147
- if (typeof surface !== 'string' || !SURFACE_PATTERN.test(surface)) {
148
- throw new OAuth2Error(OAuth2Category.StorageFailed, `invalid surface '${surface}': expected lowercase alphanumerics and hyphens, e.g. 'cli'`);
149
- }
150
- return surface;
151
- }
152
- function expandHome(value) {
153
- if (value === '~')
154
- return homedir();
155
- if (value.startsWith('~/') || value.startsWith(`~${path.sep}`)) {
156
- return path.join(homedir(), value.slice(2));
157
- }
158
- return value;
159
- }
160
- /** @returns true when the file was there and is now gone */
161
- function deleteFile(file) {
162
- try {
163
- if (fs.existsSync(file)) {
164
- fs.unlinkSync(file);
165
- return true;
166
- }
167
- }
168
- catch (e) {
169
- console.error(`[TigerOpen] delete file fail: ${file}`, e);
170
- }
171
- return false;
172
- }
173
- /**
174
- * Atomically replace a file through a same-directory temporary file.
175
- *
176
- * Same-filesystem replacement prevents partial JSON writes. Directories and files are
177
- * restricted to modes 0700 and 0600 where supported.
178
- */
179
- function writeAtomic(file, content) {
180
- const dir = path.dirname(file);
181
- try {
182
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
183
- restrict(dir, 0o700);
184
- // Same directory, so the rename below stays on one filesystem and is atomic.
185
- const tmp = path.join(dir, `.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
186
- try {
187
- fs.writeFileSync(tmp, content, { encoding: 'utf-8', mode: 0o600 });
188
- restrict(tmp, 0o600);
189
- fs.renameSync(tmp, file);
190
- }
191
- catch (e) {
192
- try {
193
- fs.unlinkSync(tmp);
194
- }
195
- catch {
196
- // The temporary file was never created; nothing to clean up.
197
- }
198
- throw e;
199
- }
200
- restrict(file, 0o600);
201
- }
202
- catch (e) {
203
- throw new OAuth2Error(OAuth2Category.StorageFailed, `write file fail: ${file}`, e);
204
- }
205
- }
206
- /** Restrict a credential file or directory where the platform supports it. */
207
- function restrict(target, mode) {
208
- try {
209
- fs.chmodSync(target, mode);
210
- }
211
- catch {
212
- // Windows and some network filesystems have no POSIX modes; the write still stands.
213
- }
214
- }
@@ -1,71 +0,0 @@
1
- /**
2
- * Persisted OAuth 2.0 authorization state.
3
- *
4
- * The `issuer` and `clientId` bind credentials to an authorization server and client,
5
- * preventing credential reuse across environments. The on-disk field names are
6
- * snake_case and shared with the Java and Python SDKs.
7
- */
8
- /** On-disk format version. An unrecognised version is an error, not a guess. */
9
- export const TOKEN_SCHEMA_VERSION = 1;
10
- export function currentMillis() {
11
- return Date.now();
12
- }
13
- /** An access token and its metadata. */
14
- export class OAuth2Token {
15
- constructor(init = {}) {
16
- this.schemaVersion = init.schemaVersion ?? TOKEN_SCHEMA_VERSION;
17
- this.issuer = init.issuer;
18
- this.clientId = init.clientId;
19
- this.accessToken = init.accessToken;
20
- this.refreshToken = init.refreshToken;
21
- this.tokenType = init.tokenType || 'Bearer';
22
- this.scope = init.scope;
23
- this.expiresAt = init.expiresAt ?? 0;
24
- }
25
- /** Time until expiry; negative once already expired. */
26
- remainingMillis() {
27
- return this.expiresAt - currentMillis();
28
- }
29
- /**
30
- * @param aheadMillis how early to refresh. The window exists because time passes
31
- * between sending a request and the server validating it, so using a token right up
32
- * to its expiry produces intermittent 401s
33
- */
34
- needsRefresh(aheadMillis) {
35
- return this.remainingMillis() <= aheadMillis;
36
- }
37
- hasRefreshToken() {
38
- return !!this.refreshToken;
39
- }
40
- toJSON() {
41
- return {
42
- schema_version: this.schemaVersion,
43
- issuer: this.issuer,
44
- client_id: this.clientId,
45
- access_token: this.accessToken,
46
- refresh_token: this.refreshToken,
47
- token_type: this.tokenType,
48
- scope: this.scope,
49
- expires_at: this.expiresAt,
50
- };
51
- }
52
- static fromJSON(data) {
53
- if (!data)
54
- return null;
55
- return new OAuth2Token({
56
- schemaVersion: data.schema_version ?? TOKEN_SCHEMA_VERSION,
57
- issuer: data.issuer,
58
- clientId: data.client_id,
59
- accessToken: data.access_token,
60
- refreshToken: data.refresh_token,
61
- tokenType: data.token_type || 'Bearer',
62
- scope: data.scope,
63
- expiresAt: data.expires_at ?? 0,
64
- });
65
- }
66
- /** Prints no token values. */
67
- toString() {
68
- return `OAuth2Token{clientId=${this.clientId}, issuer=${this.issuer}, scope=${this.scope}, `
69
- + `expiresAt=${this.expiresAt}, hasRefreshToken=${this.hasRefreshToken()}}`;
70
- }
71
- }
@@ -1,98 +0,0 @@
1
- /**
2
- * Request authentication interfaces.
3
- *
4
- * Implementations attach credentials, handle authentication retries, and release
5
- * resources. OAuth 2.0 authorization flows live in `OAuth2SessionManager`; this module
6
- * is the data plane and knows nothing about login.
7
- */
8
- /** Which kind of authentication. */
9
- export declare enum AuthenticationType {
10
- /** tigerId + RSA private key signature */
11
- Signature = "SIGNATURE",
12
- /** `Authorization: Bearer <access_token>` */
13
- OAuth2 = "OAUTH2"
14
- }
15
- /**
16
- * Per-request authentication context.
17
- *
18
- * Business parameters (`method`, `version`, `biz_content`, `timestamp`) are filled in by
19
- * the client and must not be modified by an authentication implementation.
20
- */
21
- export declare class RequestAuthContext {
22
- /** Request body parameters. Read-only as far as authentication is concerned. */
23
- readonly params: Record<string, string>;
24
- /**
25
- * Whether a request may be retried with a new credential after a 401.
26
- *
27
- * Order placement, modification, and cancellation are not retryable because a 401
28
- * does not prove that the operation was not executed.
29
- */
30
- readonly retryable: boolean;
31
- /** Full `Authorization` header value; undefined means do not send the header. */
32
- authorizationHeader?: string;
33
- constructor(params: Record<string, string>, retryable?: boolean);
34
- }
35
- /**
36
- * Credential snapshot used to coordinate authentication retries.
37
- *
38
- * Comparing the failed credential with current state detects rotation completed
39
- * elsewhere and avoids duplicate refresh requests.
40
- */
41
- export declare class AuthenticationAttempt {
42
- readonly authType: AuthenticationType;
43
- /**
44
- * Credential used by the request, including a raw OAuth 2.0 access token.
45
- *
46
- * This value is restricted to equality comparisons and must not be logged or exposed.
47
- */
48
- readonly credential: string | undefined;
49
- constructor(authType: AuthenticationType, credential: string | undefined);
50
- /** Never prints the credential value. */
51
- toString(): string;
52
- }
53
- /**
54
- * Authentication retry decision.
55
- *
56
- * A retry always supplies a new full `Authorization` header value, including the
57
- * `Bearer ` prefix. There is deliberately no "retry with the same credential" option:
58
- * that only collects the same 401 twice.
59
- */
60
- export declare class RetryDecision {
61
- private static readonly NO_RETRY;
62
- readonly shouldRetry: boolean;
63
- readonly authorizationHeader: string | undefined;
64
- private constructor();
65
- static noRetry(): RetryDecision;
66
- /** @param authorizationHeader full new header value, including `Bearer ` */
67
- static retry(authorizationHeader: string): RetryDecision;
68
- /** Never prints the header value. */
69
- toString(): string;
70
- }
71
- /** Authentication interface. */
72
- export interface Authentication {
73
- /**
74
- * Which kind of authentication. For logging and assertions; business logic should not
75
- * branch on it.
76
- */
77
- readonly authType: AuthenticationType;
78
- /**
79
- * Write the credential into the request and return a snapshot of which credential was
80
- * used.
81
- *
82
- * The OAuth2 implementation may refresh here, so this may reject with an
83
- * `OAuth2Error`.
84
- *
85
- * @returns snapshot, passed back to {@link onUnauthorized}
86
- */
87
- apply(context: RequestAuthContext): Promise<AuthenticationAttempt>;
88
- /**
89
- * Return the retry decision for an unauthorized response.
90
- *
91
- * Refresh applies only to HTTP 401 credential failures, never to HTTP 403, server
92
- * errors, or timeouts. Authentication retries occur at most once per request and
93
- * require a different credential.
94
- */
95
- onUnauthorized(attempt: AuthenticationAttempt | undefined, statusCode: number): Promise<RetryDecision>;
96
- /** Release resources. Must be called when switching authentication method. */
97
- close(): void;
98
- }
@@ -1,4 +0,0 @@
1
- /** Authentication layer: the request-level data plane plus the OAuth 2.0 control plane. */
2
- export { AuthenticationAttempt, AuthenticationType, RequestAuthContext, RetryDecision, } from './authentication';
3
- export type { Authentication } from './authentication';
4
- export * from './oauth2';
@@ -1,32 +0,0 @@
1
- /**
2
- * OAuth 2.0 dynamic client registration state (RFC 7591).
3
- *
4
- * Registration state is stored separately from tokens and retained across logout.
5
- * `registeredScopes` records the granted scope set; scope expansion requires a new
6
- * registration to avoid `invalid_scope`.
7
- */
8
- /** Raw on-disk shape, shared with the Java and Python SDKs. */
9
- export interface OAuth2ClientRegistrationJson {
10
- issuer?: string;
11
- client_id?: string;
12
- client_name?: string;
13
- registered_scopes?: string;
14
- client_id_issued_at?: number;
15
- }
16
- export declare class OAuth2ClientRegistration {
17
- issuer?: string;
18
- clientId?: string;
19
- clientName?: string;
20
- registeredScopes?: string;
21
- clientIdIssuedAt: number;
22
- constructor(init?: {
23
- issuer?: string;
24
- clientId?: string;
25
- clientName?: string;
26
- registeredScopes?: string;
27
- clientIdIssuedAt?: number;
28
- });
29
- toJSON(): OAuth2ClientRegistrationJson;
30
- static fromJSON(data: OAuth2ClientRegistrationJson | null | undefined): OAuth2ClientRegistration | null;
31
- toString(): string;
32
- }
@@ -1,40 +0,0 @@
1
- /** Device authorization response (RFC 8628). */
2
- /**
3
- * Default polling interval per RFC 8628 §3.5. Tiger's authorization server does not
4
- * return `interval`, so this default applies in practice.
5
- */
6
- export declare const DEFAULT_DEVICE_INTERVAL_SECONDS = 5;
7
- /** Raw shape of the device authorization response. */
8
- export interface OAuth2DeviceAuthorizationJson {
9
- device_code?: string;
10
- user_code?: string;
11
- verification_uri?: string;
12
- verification_uri_complete?: string;
13
- expires_in?: number;
14
- interval?: number;
15
- }
16
- export declare class OAuth2DeviceAuthorization {
17
- /** Credential used to redeem the token; it must not be displayed or logged. */
18
- deviceCode?: string;
19
- /** Short code presented to the resource owner. */
20
- userCode?: string;
21
- /** Verification URI presented to the resource owner. */
22
- verificationUri?: string;
23
- /** Verification URI with the user code included. */
24
- verificationUriComplete?: string;
25
- expiresIn: number;
26
- /** Polling interval in seconds; 0 means the server sent none */
27
- interval: number;
28
- constructor(init?: {
29
- deviceCode?: string;
30
- userCode?: string;
31
- verificationUri?: string;
32
- verificationUriComplete?: string;
33
- expiresIn?: number;
34
- interval?: number;
35
- });
36
- effectiveIntervalSeconds(): number;
37
- static fromJSON(data: OAuth2DeviceAuthorizationJson | null | undefined): OAuth2DeviceAuthorization | null;
38
- /** Prints no deviceCode. */
39
- toString(): string;
40
- }
@@ -1,46 +0,0 @@
1
- /**
2
- * Categorized errors from OAuth 2.0 authorization flows.
3
- *
4
- * Authorization server error details are retained in the error message.
5
- */
6
- /** Error category. Each one implies a different action. */
7
- export declare enum OAuth2Category {
8
- /** Cannot fetch authorization server metadata: wrong address, service down, no network */
9
- MetadataUnavailable = "METADATA_UNAVAILABLE",
10
- /** No usable client_id, and automatic registration is not possible */
11
- ClientRegistrationRequired = "CLIENT_REGISTRATION_REQUIRED",
12
- /** Callback stage failed: timeout, user denial, or state mismatch */
13
- CallbackFailed = "CALLBACK_FAILED",
14
- /**
15
- * Device flow not approved in time, or explicitly denied. Kept separate from
16
- * ReauthorizationRequired because only a new device authorization is needed -- the
17
- * stored token was not touched.
18
- */
19
- DeviceAuthorizationFailed = "DEVICE_AUTHORIZATION_FAILED",
20
- /** refresh_token expired, revoked, or never obtained. Retrying is pointless */
21
- ReauthorizationRequired = "REAUTHORIZATION_REQUIRED",
22
- /** Token endpoint call failed, and not in the terminal way above */
23
- TokenRequestFailed = "TOKEN_REQUEST_FAILED",
24
- /** Reading or writing the local token file failed */
25
- StorageFailed = "STORAGE_FAILED"
26
- }
27
- /** Thrown by any stage of the OAuth2 flow. */
28
- export declare class OAuth2Error extends Error {
29
- readonly category: OAuth2Category;
30
- readonly cause?: unknown;
31
- constructor(category: OAuth2Category, message: string, cause?: unknown);
32
- get reauthorizationRequired(): boolean;
33
- toString(): string;
34
- }
35
- /**
36
- * A grant the authorization server refused.
37
- *
38
- * Carries the error code so a caller can tell a rejected credential from a rejected
39
- * client registration. Its category is `ReauthorizationRequired`, so callers that only
40
- * know the public type behave as they would for any terminal authorization failure.
41
- */
42
- export declare class RejectedGrantError extends OAuth2Error {
43
- readonly error: string;
44
- constructor(error: string, description: string);
45
- get isClientRejected(): boolean;
46
- }
@@ -1,21 +0,0 @@
1
- /**
2
- * Every call here is a small JSON exchange with the authorization server, so a request
3
- * that has not answered in this long is not going to. Same values as the Java and
4
- * Python SDKs.
5
- */
6
- export declare const CONNECT_TIMEOUT_SECONDS = 5;
7
- export declare const READ_TIMEOUT_SECONDS = 10;
8
- /** Form fields whose value is null or undefined are skipped. */
9
- export type FormFields = Record<string, string | undefined | null>;
10
- export declare function getJson(url: string): Promise<Record<string, unknown>>;
11
- export declare function postJson(url: string, payload: unknown): Promise<Record<string, unknown>>;
12
- export declare function postForm(url: string, form: FormFields): Promise<Record<string, unknown>>;
13
- /**
14
- * Post a form and return the HTTP status without requiring a response body.
15
- *
16
- * RFC 7009 revocation returns an empty success body, so no parsing is performed.
17
- *
18
- * @returns the HTTP status code
19
- * @throws OAuth2Error on connection failure
20
- */
21
- export declare function postFormForStatus(url: string, form: FormFields): Promise<number>;
@@ -1,16 +0,0 @@
1
- /** OAuth 2.0 authentication, authorization flows, and token persistence. */
2
- export { OAuth2ClientRegistration } from './client-registration';
3
- export type { OAuth2ClientRegistrationJson } from './client-registration';
4
- export { OAuth2DeviceAuthorization, DEFAULT_DEVICE_INTERVAL_SECONDS } from './device-authorization';
5
- export type { OAuth2DeviceAuthorizationJson } from './device-authorization';
6
- export { OAuth2Category, OAuth2Error, RejectedGrantError } from './errors';
7
- export { LoopbackReceiver, CALLBACK_PATH } from './loopback-receiver';
8
- export { OAuth2Metadata } from './metadata';
9
- export { OAuth2Authentication, BEARER_PREFIX } from './oauth2-authentication';
10
- export { OAuth2SessionManager, BUILTIN_ISSUER, CLIENT_NAME, DEFAULT_AUTHORIZE_TIMEOUT_SECONDS, DEFAULT_MANUAL_CALLBACK_PORT, DEFAULT_REFRESH_AHEAD_MILLIS, ENV_ISSUER, MIN_USABLE_REMAINING_MILLIS, } from './session-manager';
11
- export type { AuthorizationUrlHandler, DeviceAuthorizationHandler, OAuth2SessionManagerOptions, } from './session-manager';
12
- export { OAuth2Token, TOKEN_SCHEMA_VERSION, currentMillis } from './token';
13
- export type { OAuth2TokenJson } from './token';
14
- export { OAuth2TokenStore, DEFAULT_SURFACE, ENV_HOME, hashIssuer } from './token-store';
15
- export type { TokenStore } from './token-store';
16
- export { CONNECT_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS } from './http-utils';
@@ -1,29 +0,0 @@
1
- export declare const CALLBACK_PATH = "/callback";
2
- /** Single-shot local callback server. */
3
- export declare class LoopbackReceiver {
4
- private readonly server;
5
- private port;
6
- private params;
7
- private fired;
8
- private waiters;
9
- private constructor();
10
- /**
11
- * Bind the receiver. It must be listening before the authorization request is issued.
12
- *
13
- * @param port port to bind; 0 lets the system assign a free one
14
- */
15
- static start(port?: number): Promise<LoopbackReceiver>;
16
- get redirectUri(): string;
17
- get boundPort(): number;
18
- /**
19
- * Wait for the browser callback.
20
- *
21
- * @returns the query parameters carried by the callback
22
- * @throws OAuth2Error on timeout
23
- */
24
- waitForCallback(timeoutSeconds: number): Promise<Record<string, string>>;
25
- close(): void;
26
- /** Record the callback params (first one wins) and return a snapshot of them. */
27
- private record;
28
- private release;
29
- }
@@ -1,32 +0,0 @@
1
- /**
2
- * Authorization server metadata (RFC 8414).
3
- *
4
- * Endpoints always come from metadata, never hardcoded, so switching environments only
5
- * means changing the issuer.
6
- */
7
- /** Raw shape of `{issuer}/.well-known/oauth-authorization-server`. */
8
- export interface OAuth2MetadataJson {
9
- issuer?: string;
10
- authorization_endpoint?: string;
11
- token_endpoint?: string;
12
- registration_endpoint?: string;
13
- device_authorization_endpoint?: string;
14
- revocation_endpoint?: string;
15
- scopes_supported?: string[];
16
- }
17
- export declare class OAuth2Metadata {
18
- issuer?: string;
19
- authorizationEndpoint?: string;
20
- tokenEndpoint?: string;
21
- /** Absent means only a manually configured clientId can be used */
22
- registrationEndpoint?: string;
23
- /** Absent means this environment does not support the device flow */
24
- deviceAuthorizationEndpoint?: string;
25
- /** RFC 7009 revocation. Absent means logout can only clear the local token */
26
- revocationEndpoint?: string;
27
- scopesSupported: string[];
28
- constructor(init?: Partial<Omit<OAuth2Metadata, 'scopesSupported'>> & {
29
- scopesSupported?: string[];
30
- });
31
- static fromJSON(data: OAuth2MetadataJson | null | undefined): OAuth2Metadata | null;
32
- }
@@ -1,31 +0,0 @@
1
- /** Request authentication backed by an OAuth 2.0 session manager. */
2
- import { AuthenticationAttempt, AuthenticationType, RequestAuthContext, RetryDecision, type Authentication } from '../authentication';
3
- import type { OAuth2SessionManager } from './session-manager';
4
- export declare const BEARER_PREFIX = "Bearer ";
5
- /** Authenticate with an OAuth2 access token. */
6
- export declare class OAuth2Authentication implements Authentication {
7
- private readonly sessions;
8
- constructor(sessionManager: OAuth2SessionManager);
9
- get authType(): AuthenticationType;
10
- get sessionManager(): OAuth2SessionManager;
11
- /**
12
- * Attach a Bearer token to the request context.
13
- *
14
- * Near-expiry refreshes use the session manager's single-flight synchronization.
15
- * Missing authorization rejects with `ReauthorizationRequired` without starting an
16
- * implicit browser flow.
17
- */
18
- apply(context: RequestAuthContext): Promise<AuthenticationAttempt>;
19
- /**
20
- * Process HTTP 401 responses.
21
- *
22
- * HTTP 403 indicates insufficient permission and cannot be resolved by refreshing a
23
- * token with the same scope. Server errors and timeouts are not credential failures.
24
- */
25
- onUnauthorized(attempt: AuthenticationAttempt | undefined, statusCode: number): Promise<RetryDecision>;
26
- /**
27
- * The session is owned by the application and may still be in use, so it is not
28
- * closed here.
29
- */
30
- close(): void;
31
- }