tigeropen 0.4.0 → 0.5.7
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/README.md +82 -2
- package/dist/cjs/auth/authentication.js +74 -0
- package/dist/cjs/auth/index.js +24 -0
- package/dist/cjs/auth/oauth2/client-registration.js +44 -0
- package/dist/cjs/auth/oauth2/device-authorization.js +40 -0
- package/dist/cjs/auth/oauth2/errors.js +64 -0
- package/dist/cjs/auth/oauth2/http-utils.js +112 -0
- package/dist/cjs/auth/oauth2/index.js +42 -0
- package/dist/cjs/auth/oauth2/loopback-receiver.js +215 -0
- package/dist/cjs/auth/oauth2/metadata.js +34 -0
- package/dist/cjs/auth/oauth2/oauth2-authentication.js +74 -0
- package/dist/cjs/auth/oauth2/session-manager.js +762 -0
- package/dist/cjs/auth/oauth2/token-store.js +252 -0
- package/dist/cjs/auth/oauth2/token.js +76 -0
- package/dist/cjs/client/api-response.js +28 -7
- package/dist/cjs/client/case-convert.js +4 -3
- package/dist/cjs/client/http-client.js +124 -8
- package/dist/cjs/client/token-methods.js +42 -0
- package/dist/cjs/config/client-config.js +115 -16
- package/dist/cjs/config/config-parser.js +19 -9
- package/dist/cjs/config/index.js +4 -1
- package/dist/cjs/config/token-manager.js +54 -4
- package/dist/cjs/index.js +53 -2
- package/dist/cjs/model/enums.js +18 -1
- package/dist/cjs/model/order-helpers.js +149 -0
- package/dist/cjs/push/index.js +1 -0
- package/dist/cjs/push/pb/Request.js +12 -1
- package/dist/cjs/push/proto-message.js +5 -1
- package/dist/cjs/push/push-client.js +69 -25
- package/dist/cjs/push/tick-util.js +172 -0
- package/dist/cjs/quote/quote-client.js +300 -70
- package/dist/cjs/trade/trade-client.js +186 -16
- package/dist/cjs/version.js +4 -0
- package/dist/esm/auth/authentication.js +68 -0
- package/dist/esm/auth/index.js +3 -0
- package/dist/esm/auth/oauth2/client-registration.js +40 -0
- package/dist/esm/auth/oauth2/device-authorization.js +36 -0
- package/dist/esm/auth/oauth2/errors.js +59 -0
- package/dist/esm/auth/oauth2/http-utils.js +105 -0
- package/dist/esm/auth/oauth2/index.js +11 -0
- package/dist/esm/auth/oauth2/loopback-receiver.js +178 -0
- package/dist/esm/auth/oauth2/metadata.js +30 -0
- package/dist/esm/auth/oauth2/oauth2-authentication.js +70 -0
- package/dist/esm/auth/oauth2/session-manager.js +725 -0
- package/dist/esm/auth/oauth2/token-store.js +214 -0
- package/dist/esm/auth/oauth2/token.js +71 -0
- package/dist/esm/client/api-request.js +1 -1
- package/dist/esm/client/api-response.js +29 -8
- package/dist/esm/client/case-convert.js +4 -3
- package/dist/esm/client/http-client.js +128 -12
- package/dist/esm/client/index.js +6 -6
- package/dist/esm/client/token-methods.js +37 -0
- package/dist/esm/config/client-config.js +118 -20
- package/dist/esm/config/config-parser.js +19 -9
- package/dist/esm/config/index.js +4 -3
- package/dist/esm/config/token-manager.js +55 -5
- package/dist/esm/index.js +15 -1
- package/dist/esm/logger/index.js +1 -1
- package/dist/esm/model/contract-helpers.js +1 -1
- package/dist/esm/model/enums.js +17 -0
- package/dist/esm/model/order-helpers.js +142 -1
- package/dist/esm/model/order-status.js +1 -1
- package/dist/esm/package.json +3 -0
- package/dist/esm/push/index.js +6 -5
- package/dist/esm/push/pb/PushData.js +11 -11
- package/dist/esm/push/pb/QuoteBasicData.js +1 -1
- package/dist/esm/push/pb/Request.js +12 -1
- package/dist/esm/push/pb/Response.js +1 -1
- package/dist/esm/push/pb/index.js +17 -17
- package/dist/esm/push/proto-message.js +8 -4
- package/dist/esm/push/push-client.js +76 -32
- package/dist/esm/push/tick-util.js +165 -0
- package/dist/esm/quote/index.js +1 -1
- package/dist/esm/quote/quote-client.js +269 -72
- package/dist/esm/signer/index.js +2 -2
- package/dist/esm/trade/index.js +1 -1
- package/dist/esm/trade/trade-client.js +156 -19
- package/dist/esm/version.js +1 -0
- package/dist/types/auth/authentication.d.ts +98 -0
- package/dist/types/auth/index.d.ts +4 -0
- package/dist/types/auth/oauth2/client-registration.d.ts +32 -0
- package/dist/types/auth/oauth2/device-authorization.d.ts +40 -0
- package/dist/types/auth/oauth2/errors.d.ts +46 -0
- package/dist/types/auth/oauth2/http-utils.d.ts +21 -0
- package/dist/types/auth/oauth2/index.d.ts +16 -0
- package/dist/types/auth/oauth2/loopback-receiver.d.ts +29 -0
- package/dist/types/auth/oauth2/metadata.d.ts +32 -0
- package/dist/types/auth/oauth2/oauth2-authentication.d.ts +31 -0
- package/dist/types/auth/oauth2/session-manager.d.ts +241 -0
- package/dist/types/auth/oauth2/token-store.d.ts +49 -0
- package/dist/types/auth/oauth2/token.d.ts +56 -0
- package/dist/types/client/api-response.d.ts +6 -4
- package/dist/types/client/case-convert.d.ts +3 -1
- package/dist/types/client/http-client.d.ts +32 -1
- package/dist/types/client/token-methods.d.ts +34 -0
- package/dist/types/config/client-config.d.ts +22 -1
- package/dist/types/config/index.d.ts +3 -1
- package/dist/types/config/token-manager.d.ts +27 -3
- package/dist/types/index.d.ts +22 -1
- package/dist/types/model/enums.d.ts +18 -2
- package/dist/types/model/order-helpers.d.ts +52 -1
- package/dist/types/model/order.d.ts +127 -10
- package/dist/types/model/quote-requests.d.ts +27 -15
- package/dist/types/model/quote.d.ts +151 -24
- package/dist/types/model/trade-requests.d.ts +123 -4
- package/dist/types/model/trade.d.ts +121 -17
- package/dist/types/push/callbacks.d.ts +3 -7
- package/dist/types/push/index.d.ts +2 -1
- package/dist/types/push/pb/Request.d.ts +1 -0
- package/dist/types/push/proto-message.d.ts +4 -1
- package/dist/types/push/push-client.d.ts +38 -3
- package/dist/types/push/tick-util.d.ts +30 -0
- package/dist/types/quote/quote-client.d.ts +101 -36
- package/dist/types/trade/trade-client.d.ts +69 -14
- package/dist/types/version.d.ts +1 -0
- package/package.json +9 -4
|
@@ -1,8 +1,52 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
2
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
36
|
exports.TradeClient = void 0;
|
|
37
|
+
/**
|
|
38
|
+
* TradeClient — trading client.
|
|
39
|
+
*
|
|
40
|
+
* All methods return strongly-typed responses; request parameters are
|
|
41
|
+
* written in camelCase in TypeScript and converted to snake_case on the wire.
|
|
42
|
+
*
|
|
43
|
+
* v0.4.0: 所有查询类方法改为 Request 对象签名(OrdersRequest 等),补齐 17
|
|
44
|
+
* 个新方法(账户管理 / 资产分析 / 资金调拨 / 持仓划转等)。
|
|
45
|
+
*/
|
|
46
|
+
const http_client_1 = require("../client/http-client");
|
|
4
47
|
const api_request_1 = require("../client/api-request");
|
|
5
48
|
const api_response_1 = require("../client/api-response");
|
|
49
|
+
const tokenMethods = __importStar(require("../client/token-methods"));
|
|
6
50
|
const order_status_1 = require("../model/order-status");
|
|
7
51
|
/** Normalize `Order.status` field in-place (handles int → string). */
|
|
8
52
|
function normalizeOrderInPlace(o) {
|
|
@@ -25,12 +69,51 @@ function withAccount(req, account) {
|
|
|
25
69
|
}
|
|
26
70
|
/** Trading client wrapping all trade-related APIs. */
|
|
27
71
|
class TradeClient {
|
|
28
|
-
constructor(httpClient, account) {
|
|
72
|
+
constructor(httpClient, account, secretKey) {
|
|
29
73
|
this.httpClient = httpClient;
|
|
30
74
|
this.account = account;
|
|
75
|
+
this.secretKey = secretKey;
|
|
76
|
+
}
|
|
77
|
+
/** Create a TradeClient directly from a ClientConfig — no need to construct HttpClient manually. */
|
|
78
|
+
static fromConfig(config, account, secretKey) {
|
|
79
|
+
return new TradeClient(new http_client_1.HttpClient(config), account, secretKey);
|
|
80
|
+
}
|
|
81
|
+
// ── Token management ──────────────────────────────────────────────────────
|
|
82
|
+
/** Call the `user_token_refresh` API and return the new token. Read-only. */
|
|
83
|
+
async queryToken() {
|
|
84
|
+
return tokenMethods.queryToken(this.httpClient);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Refresh the token: call the API, update the in-memory config token, and
|
|
88
|
+
* optionally persist via the provided TokenManager (file + writer callback).
|
|
89
|
+
*
|
|
90
|
+
* @param tokenManager - optional TokenManager for file persistence and writer callback
|
|
91
|
+
*/
|
|
92
|
+
async refreshToken(tokenManager) {
|
|
93
|
+
return tokenMethods.refreshToken(this.httpClient, tokenManager);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Start background token auto-refresh. Returns a TokenManager that can be
|
|
97
|
+
* used to stop the background task via `tm.stopAutoRefresh()`.
|
|
98
|
+
*
|
|
99
|
+
* @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
|
|
100
|
+
* @param checkIntervalMs - How often to check, in milliseconds (default 300 000 / 5 min).
|
|
101
|
+
* @param tokenWriter - Optional callback invoked after each successful refresh.
|
|
102
|
+
*/
|
|
103
|
+
startTokenAutoRefresh(refreshDurationSecs, checkIntervalMs, tokenWriter) {
|
|
104
|
+
return tokenMethods.startTokenAutoRefresh(this.httpClient, refreshDurationSecs, checkIntervalMs, tokenWriter);
|
|
31
105
|
}
|
|
32
106
|
async callInto(method, bizParams) {
|
|
33
|
-
|
|
107
|
+
// Inject secretKey into every request when available (institution accounts require it).
|
|
108
|
+
// Individual methods that already set secretKey will not be overwritten (|| not &&).
|
|
109
|
+
let params = bizParams;
|
|
110
|
+
if (this.secretKey && params !== null && typeof params === 'object' && !Array.isArray(params)) {
|
|
111
|
+
const p = params;
|
|
112
|
+
if (p['secretKey'] == null && p['secret_key'] == null) {
|
|
113
|
+
params = { ...p, secretKey: this.secretKey };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const request = (0, api_request_1.createApiRequest)(method, params);
|
|
34
117
|
const response = await this.httpClient.executeRequest(request);
|
|
35
118
|
return (0, api_response_1.unmarshalData)(response.data);
|
|
36
119
|
}
|
|
@@ -62,17 +145,60 @@ class TradeClient {
|
|
|
62
145
|
});
|
|
63
146
|
}
|
|
64
147
|
// === Order operations ===
|
|
148
|
+
/**
|
|
149
|
+
* Prepare an order request for the wire.
|
|
150
|
+
*
|
|
151
|
+
* The gateway expects `algo_params` as a `[{tag, value}, ...]` array
|
|
152
|
+
* (matching the Python SDK's AlgoParams.to_dict serialization), not the
|
|
153
|
+
* plain object shape that reads naturally in TypeScript. This helper
|
|
154
|
+
* normalizes the object form into the array form on outbound payloads
|
|
155
|
+
* so callers can pass the natural object and TWAP/VWAP orders work end
|
|
156
|
+
* to end without wire-format workarounds.
|
|
157
|
+
*
|
|
158
|
+
* Fields with undefined/null values are dropped; empty algoParams
|
|
159
|
+
* becomes an empty array rather than being stripped, matching the
|
|
160
|
+
* Python SDK behavior when the user passes an empty AlgoParams().
|
|
161
|
+
*/
|
|
162
|
+
marshalOrderForWire(order) {
|
|
163
|
+
const { algoParams, ...rest } = order;
|
|
164
|
+
const withAccount = { ...rest, account: this.account };
|
|
165
|
+
if (algoParams === undefined)
|
|
166
|
+
return withAccount;
|
|
167
|
+
// Already a tag/value array (advanced callers who want raw control)
|
|
168
|
+
if (Array.isArray(algoParams)) {
|
|
169
|
+
withAccount.algoParams = algoParams;
|
|
170
|
+
return withAccount;
|
|
171
|
+
}
|
|
172
|
+
// Object shape → tag/value array.
|
|
173
|
+
// Keys are converted to snake_case explicitly here (e.g. `startTime` →
|
|
174
|
+
// `start_time`) so they land correctly in the `tag` string that the
|
|
175
|
+
// gateway reads. `keysToSnakeCase` only rewrites object *keys*, not
|
|
176
|
+
// string *values*, so `tag` would be left camelCase if we didn't do
|
|
177
|
+
// this conversion ourselves.
|
|
178
|
+
const tagValues = [];
|
|
179
|
+
for (const [key, value] of Object.entries(algoParams)) {
|
|
180
|
+
if (value === undefined || value === null)
|
|
181
|
+
continue;
|
|
182
|
+
const snakeKey = key.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase());
|
|
183
|
+
tagValues.push({ tag: snakeKey, value });
|
|
184
|
+
}
|
|
185
|
+
withAccount.algoParams = tagValues;
|
|
186
|
+
return withAccount;
|
|
187
|
+
}
|
|
65
188
|
async placeOrder(order) {
|
|
66
|
-
return this.callInto('place_order',
|
|
189
|
+
return this.callInto('place_order', this.marshalOrderForWire(order));
|
|
67
190
|
}
|
|
68
191
|
async previewOrder(order) {
|
|
69
|
-
return this.callInto('preview_order',
|
|
192
|
+
return this.callInto('preview_order', this.marshalOrderForWire(order));
|
|
70
193
|
}
|
|
71
194
|
async modifyOrder(id, order) {
|
|
72
|
-
return this.callInto('modify_order', { ...
|
|
195
|
+
return this.callInto('modify_order', { ...this.marshalOrderForWire(order), id });
|
|
73
196
|
}
|
|
74
|
-
async cancelOrder(id) {
|
|
75
|
-
|
|
197
|
+
async cancelOrder(id, secretKey) {
|
|
198
|
+
const params = { account: this.account, id };
|
|
199
|
+
if (secretKey !== undefined)
|
|
200
|
+
params.secretKey = secretKey; // per-call override takes precedence; undefined means use config default
|
|
201
|
+
return this.callInto('cancel_order', params);
|
|
76
202
|
}
|
|
77
203
|
// === Order queries (BREAKING v0.4.0) ===
|
|
78
204
|
/**
|
|
@@ -109,14 +235,11 @@ class TradeClient {
|
|
|
109
235
|
}
|
|
110
236
|
/**
|
|
111
237
|
* Get a single order by ID (v0.4.0 new).
|
|
112
|
-
* Wire method: `orders` with id/order_id param; server returns a single Order object
|
|
113
|
-
* (not `{items:[]}` envelope).
|
|
114
|
-
*
|
|
115
238
|
* Returns `undefined` if no match.
|
|
116
239
|
*/
|
|
117
240
|
async getOrder(req) {
|
|
118
241
|
const merged = withAccount(req, this.account);
|
|
119
|
-
const out = await this.callInto('
|
|
242
|
+
const out = await this.callInto('order_no', merged);
|
|
120
243
|
if (!out || (!out.id && !out.orderId))
|
|
121
244
|
return undefined;
|
|
122
245
|
normalizeOrderInPlace(out);
|
|
@@ -134,11 +257,17 @@ class TradeClient {
|
|
|
134
257
|
async getPositions(req) {
|
|
135
258
|
return this.callIntoItems('positions', withAccount(req, this.account));
|
|
136
259
|
}
|
|
137
|
-
/**
|
|
260
|
+
/**
|
|
261
|
+
* Query assets. v0.4.0: supports sub-account list and aggregation options.
|
|
262
|
+
* `assetQuoteType`(ETH / RTH / OVERNIGHT) 选择资产行情口径。
|
|
263
|
+
*/
|
|
138
264
|
async getAssets(req) {
|
|
139
265
|
return this.callIntoItems('assets', withAccount(req, this.account));
|
|
140
266
|
}
|
|
141
|
-
/**
|
|
267
|
+
/**
|
|
268
|
+
* Query prime assets. v0.4.0: takes AssetsRequest for filters.
|
|
269
|
+
* `assetQuoteType`(ETH / RTH / OVERNIGHT) 选择资产行情口径。
|
|
270
|
+
*/
|
|
142
271
|
async getPrimeAssets(req) {
|
|
143
272
|
return this.callInto('prime_assets', withAccount(req, this.account));
|
|
144
273
|
}
|
|
@@ -159,7 +288,10 @@ class TradeClient {
|
|
|
159
288
|
async getAnalyticsAsset(req) {
|
|
160
289
|
return this.callIntoItems('analytics_asset', withAccount(req, this.account));
|
|
161
290
|
}
|
|
162
|
-
/**
|
|
291
|
+
/**
|
|
292
|
+
* Aggregate assets (prime) by base currency.
|
|
293
|
+
* `assetQuoteType`(ETH / RTH / OVERNIGHT) 选择资产行情口径。
|
|
294
|
+
*/
|
|
163
295
|
async getAggregateAssets(req) {
|
|
164
296
|
return this.callInto('aggregate_assets', withAccount(req, this.account));
|
|
165
297
|
}
|
|
@@ -194,9 +326,10 @@ class TradeClient {
|
|
|
194
326
|
async getFundDetails(req) {
|
|
195
327
|
return this.callIntoItems('fund_details', withAccount(req, this.account));
|
|
196
328
|
}
|
|
197
|
-
/** Funding history (wire method: `transfer_fund`).
|
|
329
|
+
/** Funding history (wire method: `transfer_fund`).
|
|
330
|
+
* Server returns bare list (no items wrapper). */
|
|
198
331
|
async getFundingHistory(req) {
|
|
199
|
-
return this.
|
|
332
|
+
return this.callInto('transfer_fund', withAccount(req, this.account));
|
|
200
333
|
}
|
|
201
334
|
// ===== v0.4.0 NEW: Internal / external position transfer =====
|
|
202
335
|
/**
|
|
@@ -230,5 +363,42 @@ class TradeClient {
|
|
|
230
363
|
merged.accountId = this.account;
|
|
231
364
|
return this.callIntoItems('position_transfer_external_records', merged);
|
|
232
365
|
}
|
|
366
|
+
/** 行权检验:预估行权/作废后正股持仓变化 (wire: option_exercise_check) */
|
|
367
|
+
async checkOptionExercise(req) {
|
|
368
|
+
const merged = { ...req };
|
|
369
|
+
if (!merged.account)
|
|
370
|
+
merged.account = this.account;
|
|
371
|
+
return this.callInto('option_exercise_check', merged);
|
|
372
|
+
}
|
|
373
|
+
/** 查询可行权持仓列表 (wire: option_exercise_position) */
|
|
374
|
+
async getOptionExercisePositions(req) {
|
|
375
|
+
const merged = { ...req };
|
|
376
|
+
if (!merged.account)
|
|
377
|
+
merged.account = this.account;
|
|
378
|
+
return this.callInto('option_exercise_position', merged);
|
|
379
|
+
}
|
|
380
|
+
/** 提交行权/作废申请 (wire: option_exercise_submit) */
|
|
381
|
+
async submitOptionExercise(req) {
|
|
382
|
+
const merged = { ...req };
|
|
383
|
+
if (!merged.account)
|
|
384
|
+
merged.account = this.account;
|
|
385
|
+
const result = await this.callInto('option_exercise_submit', merged);
|
|
386
|
+
return result ?? false;
|
|
387
|
+
}
|
|
388
|
+
/** 分页查询行权记录 (wire: option_exercise_record) */
|
|
389
|
+
async getOptionExerciseRecords(req) {
|
|
390
|
+
const merged = { ...req };
|
|
391
|
+
if (!merged.account)
|
|
392
|
+
merged.account = this.account;
|
|
393
|
+
return this.callInto('option_exercise_record', merged);
|
|
394
|
+
}
|
|
395
|
+
/** 撤销行权申请 (wire: option_exercise_cancel) */
|
|
396
|
+
async cancelOptionExercise(req) {
|
|
397
|
+
const merged = { ...req };
|
|
398
|
+
if (!merged.account)
|
|
399
|
+
merged.account = this.account;
|
|
400
|
+
const result = await this.callInto('option_exercise_cancel', merged);
|
|
401
|
+
return result ?? false;
|
|
402
|
+
}
|
|
233
403
|
}
|
|
234
404
|
exports.TradeClient = TradeClient;
|
|
@@ -0,0 +1,68 @@
|
|
|
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 var AuthenticationType;
|
|
10
|
+
(function (AuthenticationType) {
|
|
11
|
+
/** tigerId + RSA private key signature */
|
|
12
|
+
AuthenticationType["Signature"] = "SIGNATURE";
|
|
13
|
+
/** `Authorization: Bearer <access_token>` */
|
|
14
|
+
AuthenticationType["OAuth2"] = "OAUTH2";
|
|
15
|
+
})(AuthenticationType || (AuthenticationType = {}));
|
|
16
|
+
/**
|
|
17
|
+
* Per-request authentication context.
|
|
18
|
+
*
|
|
19
|
+
* Business parameters (`method`, `version`, `biz_content`, `timestamp`) are filled in by
|
|
20
|
+
* the client and must not be modified by an authentication implementation.
|
|
21
|
+
*/
|
|
22
|
+
export class RequestAuthContext {
|
|
23
|
+
constructor(params, retryable = true) {
|
|
24
|
+
this.params = params;
|
|
25
|
+
this.retryable = retryable;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Credential snapshot used to coordinate authentication retries.
|
|
30
|
+
*
|
|
31
|
+
* Comparing the failed credential with current state detects rotation completed
|
|
32
|
+
* elsewhere and avoids duplicate refresh requests.
|
|
33
|
+
*/
|
|
34
|
+
export class AuthenticationAttempt {
|
|
35
|
+
constructor(authType, credential) {
|
|
36
|
+
this.authType = authType;
|
|
37
|
+
this.credential = credential;
|
|
38
|
+
}
|
|
39
|
+
/** Never prints the credential value. */
|
|
40
|
+
toString() {
|
|
41
|
+
return `AuthenticationAttempt{type=${this.authType}, credential=${this.credential === undefined ? '<none>' : '***'}}`;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Authentication retry decision.
|
|
46
|
+
*
|
|
47
|
+
* A retry always supplies a new full `Authorization` header value, including the
|
|
48
|
+
* `Bearer ` prefix. There is deliberately no "retry with the same credential" option:
|
|
49
|
+
* that only collects the same 401 twice.
|
|
50
|
+
*/
|
|
51
|
+
export class RetryDecision {
|
|
52
|
+
constructor(shouldRetry, authorizationHeader) {
|
|
53
|
+
this.shouldRetry = shouldRetry;
|
|
54
|
+
this.authorizationHeader = authorizationHeader;
|
|
55
|
+
}
|
|
56
|
+
static noRetry() {
|
|
57
|
+
return RetryDecision.NO_RETRY;
|
|
58
|
+
}
|
|
59
|
+
/** @param authorizationHeader full new header value, including `Bearer ` */
|
|
60
|
+
static retry(authorizationHeader) {
|
|
61
|
+
return new RetryDecision(true, authorizationHeader);
|
|
62
|
+
}
|
|
63
|
+
/** Never prints the header value. */
|
|
64
|
+
toString() {
|
|
65
|
+
return `RetryDecision{shouldRetry=${this.shouldRetry}}`;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
RetryDecision.NO_RETRY = new RetryDecision(false, undefined);
|
|
@@ -0,0 +1,40 @@
|
|
|
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
|
+
export class OAuth2ClientRegistration {
|
|
9
|
+
constructor(init = {}) {
|
|
10
|
+
this.issuer = init.issuer;
|
|
11
|
+
this.clientId = init.clientId;
|
|
12
|
+
this.clientName = init.clientName;
|
|
13
|
+
this.registeredScopes = init.registeredScopes;
|
|
14
|
+
this.clientIdIssuedAt = init.clientIdIssuedAt ?? 0;
|
|
15
|
+
}
|
|
16
|
+
toJSON() {
|
|
17
|
+
return {
|
|
18
|
+
issuer: this.issuer,
|
|
19
|
+
client_id: this.clientId,
|
|
20
|
+
client_name: this.clientName,
|
|
21
|
+
registered_scopes: this.registeredScopes,
|
|
22
|
+
client_id_issued_at: this.clientIdIssuedAt,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
static fromJSON(data) {
|
|
26
|
+
if (!data)
|
|
27
|
+
return null;
|
|
28
|
+
return new OAuth2ClientRegistration({
|
|
29
|
+
issuer: data.issuer,
|
|
30
|
+
clientId: data.client_id,
|
|
31
|
+
clientName: data.client_name,
|
|
32
|
+
registeredScopes: data.registered_scopes,
|
|
33
|
+
clientIdIssuedAt: data.client_id_issued_at ?? 0,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
toString() {
|
|
37
|
+
return `OAuth2ClientRegistration{issuer=${this.issuer}, clientId=${this.clientId}, `
|
|
38
|
+
+ `clientName=${this.clientName}, registeredScopes=${this.registeredScopes}}`;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
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 const DEFAULT_DEVICE_INTERVAL_SECONDS = 5;
|
|
7
|
+
export class OAuth2DeviceAuthorization {
|
|
8
|
+
constructor(init = {}) {
|
|
9
|
+
this.deviceCode = init.deviceCode;
|
|
10
|
+
this.userCode = init.userCode;
|
|
11
|
+
this.verificationUri = init.verificationUri;
|
|
12
|
+
this.verificationUriComplete = init.verificationUriComplete;
|
|
13
|
+
this.expiresIn = init.expiresIn ?? 0;
|
|
14
|
+
this.interval = init.interval ?? 0;
|
|
15
|
+
}
|
|
16
|
+
effectiveIntervalSeconds() {
|
|
17
|
+
return this.interval > 0 ? this.interval : DEFAULT_DEVICE_INTERVAL_SECONDS;
|
|
18
|
+
}
|
|
19
|
+
static fromJSON(data) {
|
|
20
|
+
if (!data)
|
|
21
|
+
return null;
|
|
22
|
+
return new OAuth2DeviceAuthorization({
|
|
23
|
+
deviceCode: data.device_code,
|
|
24
|
+
userCode: data.user_code,
|
|
25
|
+
verificationUri: data.verification_uri,
|
|
26
|
+
verificationUriComplete: data.verification_uri_complete,
|
|
27
|
+
expiresIn: data.expires_in ?? 0,
|
|
28
|
+
interval: data.interval ?? 0,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/** Prints no deviceCode. */
|
|
32
|
+
toString() {
|
|
33
|
+
return `OAuth2DeviceAuthorization{userCode=${this.userCode}, verificationUri=${this.verificationUri}, `
|
|
34
|
+
+ `expiresIn=${this.expiresIn}, interval=${this.interval}}`;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
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 var OAuth2Category;
|
|
8
|
+
(function (OAuth2Category) {
|
|
9
|
+
/** Cannot fetch authorization server metadata: wrong address, service down, no network */
|
|
10
|
+
OAuth2Category["MetadataUnavailable"] = "METADATA_UNAVAILABLE";
|
|
11
|
+
/** No usable client_id, and automatic registration is not possible */
|
|
12
|
+
OAuth2Category["ClientRegistrationRequired"] = "CLIENT_REGISTRATION_REQUIRED";
|
|
13
|
+
/** Callback stage failed: timeout, user denial, or state mismatch */
|
|
14
|
+
OAuth2Category["CallbackFailed"] = "CALLBACK_FAILED";
|
|
15
|
+
/**
|
|
16
|
+
* Device flow not approved in time, or explicitly denied. Kept separate from
|
|
17
|
+
* ReauthorizationRequired because only a new device authorization is needed -- the
|
|
18
|
+
* stored token was not touched.
|
|
19
|
+
*/
|
|
20
|
+
OAuth2Category["DeviceAuthorizationFailed"] = "DEVICE_AUTHORIZATION_FAILED";
|
|
21
|
+
/** refresh_token expired, revoked, or never obtained. Retrying is pointless */
|
|
22
|
+
OAuth2Category["ReauthorizationRequired"] = "REAUTHORIZATION_REQUIRED";
|
|
23
|
+
/** Token endpoint call failed, and not in the terminal way above */
|
|
24
|
+
OAuth2Category["TokenRequestFailed"] = "TOKEN_REQUEST_FAILED";
|
|
25
|
+
/** Reading or writing the local token file failed */
|
|
26
|
+
OAuth2Category["StorageFailed"] = "STORAGE_FAILED";
|
|
27
|
+
})(OAuth2Category || (OAuth2Category = {}));
|
|
28
|
+
/** Thrown by any stage of the OAuth2 flow. */
|
|
29
|
+
export class OAuth2Error extends Error {
|
|
30
|
+
constructor(category, message, cause) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.name = 'OAuth2Error';
|
|
33
|
+
this.category = category;
|
|
34
|
+
this.cause = cause;
|
|
35
|
+
}
|
|
36
|
+
get reauthorizationRequired() {
|
|
37
|
+
return this.category === OAuth2Category.ReauthorizationRequired;
|
|
38
|
+
}
|
|
39
|
+
toString() {
|
|
40
|
+
return `OAuth2Error{${this.category}: ${this.message}}`;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A grant the authorization server refused.
|
|
45
|
+
*
|
|
46
|
+
* Carries the error code so a caller can tell a rejected credential from a rejected
|
|
47
|
+
* client registration. Its category is `ReauthorizationRequired`, so callers that only
|
|
48
|
+
* know the public type behave as they would for any terminal authorization failure.
|
|
49
|
+
*/
|
|
50
|
+
export class RejectedGrantError extends OAuth2Error {
|
|
51
|
+
constructor(error, description) {
|
|
52
|
+
super(OAuth2Category.ReauthorizationRequired, `token request rejected: ${error} ${description}`);
|
|
53
|
+
this.name = 'RejectedGrantError';
|
|
54
|
+
this.error = error;
|
|
55
|
+
}
|
|
56
|
+
get isClientRejected() {
|
|
57
|
+
return this.error === 'invalid_client';
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP helpers for OAuth 2.0 JSON and form-encoded requests.
|
|
3
|
+
*
|
|
4
|
+
* OAuth error responses retain 4xx response bodies for protocol-level error handling.
|
|
5
|
+
*/
|
|
6
|
+
import { OAuth2Category, OAuth2Error } from './errors.js';
|
|
7
|
+
/**
|
|
8
|
+
* Every call here is a small JSON exchange with the authorization server, so a request
|
|
9
|
+
* that has not answered in this long is not going to. Same values as the Java and
|
|
10
|
+
* Python SDKs.
|
|
11
|
+
*/
|
|
12
|
+
export const CONNECT_TIMEOUT_SECONDS = 5;
|
|
13
|
+
export const READ_TIMEOUT_SECONDS = 10;
|
|
14
|
+
/** Combined budget handed to `AbortSignal.timeout`; fetch does not split the two. */
|
|
15
|
+
const REQUEST_TIMEOUT_MS = (CONNECT_TIMEOUT_SECONDS + READ_TIMEOUT_SECONDS) * 1000;
|
|
16
|
+
const JSON_CONTENT_TYPE = 'application/json; charset=utf-8';
|
|
17
|
+
const FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=utf-8';
|
|
18
|
+
function encodeForm(form) {
|
|
19
|
+
const params = new URLSearchParams();
|
|
20
|
+
for (const [key, value] of Object.entries(form)) {
|
|
21
|
+
if (value !== undefined && value !== null) {
|
|
22
|
+
params.append(key, value);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return params.toString();
|
|
26
|
+
}
|
|
27
|
+
export async function getJson(url) {
|
|
28
|
+
return execute('GET', url, undefined, undefined);
|
|
29
|
+
}
|
|
30
|
+
export async function postJson(url, payload) {
|
|
31
|
+
return execute('POST', url, JSON.stringify(payload), JSON_CONTENT_TYPE);
|
|
32
|
+
}
|
|
33
|
+
export async function postForm(url, form) {
|
|
34
|
+
return execute('POST', url, encodeForm(form), FORM_CONTENT_TYPE);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Post a form and return the HTTP status without requiring a response body.
|
|
38
|
+
*
|
|
39
|
+
* RFC 7009 revocation returns an empty success body, so no parsing is performed.
|
|
40
|
+
*
|
|
41
|
+
* @returns the HTTP status code
|
|
42
|
+
* @throws OAuth2Error on connection failure
|
|
43
|
+
*/
|
|
44
|
+
export async function postFormForStatus(url, form) {
|
|
45
|
+
let response;
|
|
46
|
+
try {
|
|
47
|
+
response = await fetch(url, {
|
|
48
|
+
method: 'POST',
|
|
49
|
+
headers: { Accept: 'application/json', 'Content-Type': FORM_CONTENT_TYPE },
|
|
50
|
+
body: encodeForm(form),
|
|
51
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
throw new OAuth2Error(OAuth2Category.TokenRequestFailed, `request fail: ${url}`, e);
|
|
56
|
+
}
|
|
57
|
+
return response.status;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Send the request and parse the response body as an object.
|
|
61
|
+
*
|
|
62
|
+
* A 4xx returns its body instead of throwing: OAuth2 errors (`invalid_grant`,
|
|
63
|
+
* `authorization_pending` and friends) live in the 4xx body, and the caller needs the
|
|
64
|
+
* `error` field to tell "wait and retry" from "re-authorize". Only a connection failure
|
|
65
|
+
* or a non-JSON response throws.
|
|
66
|
+
*/
|
|
67
|
+
async function execute(method, url, body, contentType) {
|
|
68
|
+
const headers = { Accept: 'application/json' };
|
|
69
|
+
if (contentType) {
|
|
70
|
+
headers['Content-Type'] = contentType;
|
|
71
|
+
}
|
|
72
|
+
let response;
|
|
73
|
+
try {
|
|
74
|
+
response = await fetch(url, {
|
|
75
|
+
method,
|
|
76
|
+
headers,
|
|
77
|
+
body,
|
|
78
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
catch (e) {
|
|
82
|
+
throw new OAuth2Error(OAuth2Category.MetadataUnavailable, `request fail: ${url}`, e);
|
|
83
|
+
}
|
|
84
|
+
let text;
|
|
85
|
+
try {
|
|
86
|
+
text = await response.text();
|
|
87
|
+
}
|
|
88
|
+
catch (e) {
|
|
89
|
+
throw new OAuth2Error(OAuth2Category.TokenRequestFailed, `cannot decode response from ${url}, http status ${response.status}`, e);
|
|
90
|
+
}
|
|
91
|
+
if (!text) {
|
|
92
|
+
throw new OAuth2Error(OAuth2Category.TokenRequestFailed, `empty response from ${url}, http status ${response.status}`);
|
|
93
|
+
}
|
|
94
|
+
let parsed;
|
|
95
|
+
try {
|
|
96
|
+
parsed = JSON.parse(text);
|
|
97
|
+
}
|
|
98
|
+
catch (e) {
|
|
99
|
+
throw new OAuth2Error(OAuth2Category.TokenRequestFailed, `non-JSON response from ${url}, http status ${response.status}`, e);
|
|
100
|
+
}
|
|
101
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
102
|
+
throw new OAuth2Error(OAuth2Category.TokenRequestFailed, `unexpected response from ${url}, http status ${response.status}`);
|
|
103
|
+
}
|
|
104
|
+
return parsed;
|
|
105
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** OAuth 2.0 authentication, authorization flows, and token persistence. */
|
|
2
|
+
export { OAuth2ClientRegistration } from './client-registration.js';
|
|
3
|
+
export { OAuth2DeviceAuthorization, DEFAULT_DEVICE_INTERVAL_SECONDS } from './device-authorization.js';
|
|
4
|
+
export { OAuth2Category, OAuth2Error, RejectedGrantError } from './errors.js';
|
|
5
|
+
export { LoopbackReceiver, CALLBACK_PATH } from './loopback-receiver.js';
|
|
6
|
+
export { OAuth2Metadata } from './metadata.js';
|
|
7
|
+
export { OAuth2Authentication, BEARER_PREFIX } from './oauth2-authentication.js';
|
|
8
|
+
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.js';
|
|
9
|
+
export { OAuth2Token, TOKEN_SCHEMA_VERSION, currentMillis } from './token.js';
|
|
10
|
+
export { OAuth2TokenStore, DEFAULT_SURFACE, ENV_HOME, hashIssuer } from './token-store.js';
|
|
11
|
+
export { CONNECT_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS } from './http-utils.js';
|