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
|
@@ -0,0 +1,214 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
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
|
+
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Requests use camelCase parameters in TypeScript (idiomatic), but the
|
|
5
5
|
* server wire format is snake_case, so we convert keys before serializing.
|
|
6
6
|
*/
|
|
7
|
-
import { keysToSnakeCase } from './case-convert';
|
|
7
|
+
import { keysToSnakeCase } from './case-convert.js';
|
|
8
8
|
/**
|
|
9
9
|
* Create an API request, serializing business parameters to JSON as bizContent.
|
|
10
10
|
* camelCase keys are automatically converted to snake_case to match the server.
|
|
@@ -1,13 +1,35 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* API response parsing.
|
|
3
3
|
*/
|
|
4
|
-
import { TigerError } from './errors';
|
|
4
|
+
import { TigerError } from './errors.js';
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
6
|
+
* Replaces bare int64 values (≥17 digits, not part of a float) with quoted
|
|
7
|
+
* strings so they survive JSON.parse without precision loss.
|
|
8
|
+
* 17+ digits are guaranteed to exceed Number.MAX_SAFE_INTEGER (≈9.007e15),
|
|
9
|
+
* so 16-digit microsecond timestamps remain as numbers.
|
|
10
|
+
*/
|
|
11
|
+
function patchLargeIntegers(text) {
|
|
12
|
+
const strings = [];
|
|
13
|
+
const masked = text.replace(/"(?:[^"\\]|\\.)*"/g, (match) => {
|
|
14
|
+
strings.push(match);
|
|
15
|
+
return '\x01' + (strings.length - 1) + '\x01';
|
|
16
|
+
});
|
|
17
|
+
// Match bare integers preceded by a JSON structural character or line start,
|
|
18
|
+
// not followed by decimal point or exponent (avoids matching float components).
|
|
19
|
+
// The `m` flag makes `^` match line-start for multi-line JSON.
|
|
20
|
+
const patched = masked.replace(/([:,\[{]|^)\s*(-?\d{17,})(?![.\deE])/gm, (full, prefix, num) => {
|
|
21
|
+
return prefix + '"' + num + '"';
|
|
22
|
+
});
|
|
23
|
+
return patched.replace(/\x01(\d+)\x01/g, (_, i) => strings[parseInt(i, 10)]);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Parse the raw HTTP response body. Throws TigerError when code != 0.
|
|
27
|
+
*
|
|
28
|
+
* patchLargeIntegers is applied before JSON.parse to preserve int64 order IDs
|
|
29
|
+
* (e.g. 28868646234578944) as strings rather than losing precision.
|
|
8
30
|
*/
|
|
9
31
|
export function parseApiResponse(body) {
|
|
10
|
-
const resp = JSON.parse(body);
|
|
32
|
+
const resp = JSON.parse(patchLargeIntegers(body));
|
|
11
33
|
if (resp.code !== 0) {
|
|
12
34
|
throw new TigerError(resp.code, resp.message);
|
|
13
35
|
}
|
|
@@ -15,16 +37,15 @@ export function parseApiResponse(body) {
|
|
|
15
37
|
}
|
|
16
38
|
/**
|
|
17
39
|
* Decode an ApiResponse.data payload into a typed value.
|
|
18
|
-
* Handles
|
|
19
|
-
*
|
|
40
|
+
* Handles double-encoded JSON (where `data` is a JSON string wrapping JSON),
|
|
41
|
+
* seen on some trade endpoints.
|
|
20
42
|
*/
|
|
21
43
|
export function unmarshalData(data) {
|
|
22
44
|
if (data == null)
|
|
23
45
|
return undefined;
|
|
24
46
|
if (typeof data === 'string') {
|
|
25
|
-
// Attempt to parse JSON string (double-encoded case)
|
|
26
47
|
try {
|
|
27
|
-
return JSON.parse(data);
|
|
48
|
+
return JSON.parse(patchLargeIntegers(data));
|
|
28
49
|
}
|
|
29
50
|
catch {
|
|
30
51
|
return data;
|
|
@@ -13,7 +13,9 @@ export function camelToSnake(key) {
|
|
|
13
13
|
/**
|
|
14
14
|
* Recursively convert all object keys from camelCase to snake_case.
|
|
15
15
|
* Preserves arrays, primitives, and Date/null/undefined.
|
|
16
|
-
*
|
|
16
|
+
*
|
|
17
|
+
* Note: camelToSnake is idempotent for pure snake_case keys (no uppercase
|
|
18
|
+
* letters → no replacements), so no pre-check is needed.
|
|
17
19
|
*/
|
|
18
20
|
export function keysToSnakeCase(value) {
|
|
19
21
|
if (Array.isArray(value)) {
|
|
@@ -22,8 +24,7 @@ export function keysToSnakeCase(value) {
|
|
|
22
24
|
if (value && typeof value === 'object' && value.constructor === Object) {
|
|
23
25
|
const out = {};
|
|
24
26
|
for (const [k, v] of Object.entries(value)) {
|
|
25
|
-
|
|
26
|
-
out[newKey] = keysToSnakeCase(v);
|
|
27
|
+
out[camelToSnake(k)] = keysToSnakeCase(v);
|
|
27
28
|
}
|
|
28
29
|
return out;
|
|
29
30
|
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
import { TokenManager } from '../config/token-manager.js';
|
|
2
|
+
import { getSignContent } from '../signer/sign-content.js';
|
|
3
|
+
import { signWithRSA, verifyWithRSA } from '../signer/signer.js';
|
|
4
|
+
import { TigerError } from './errors.js';
|
|
5
|
+
import { defaultRetryPolicy } from './retry.js';
|
|
6
|
+
import { parseApiResponse, unmarshalData } from './api-response.js';
|
|
7
|
+
import { SDK_VERSION } from '../version.js';
|
|
8
8
|
/** User-Agent 字符串 */
|
|
9
9
|
const USER_AGENT = `openapi-typescript-sdk-${SDK_VERSION}`;
|
|
10
10
|
/** 默认字符集 */
|
|
@@ -13,14 +13,45 @@ const DEFAULT_CHARSET = 'UTF-8';
|
|
|
13
13
|
const DEFAULT_SIGN_TYPE = 'RSA';
|
|
14
14
|
/** 默认 API 版本 */
|
|
15
15
|
const DEFAULT_VERSION = '2.0';
|
|
16
|
+
/** Token 刷新 API 方法名 */
|
|
17
|
+
const METHOD_TOKEN_REFRESH = 'user_token_refresh';
|
|
18
|
+
/** 默认后台 token 检查间隔(毫秒):5 分钟 */
|
|
19
|
+
const DEFAULT_TOKEN_CHECK_INTERVAL = 5 * 60 * 1000;
|
|
16
20
|
/**
|
|
17
21
|
* HttpClient handles HTTP requests, signing, retry, and timeout
|
|
18
22
|
*/
|
|
19
23
|
export class HttpClient {
|
|
20
24
|
constructor(config, retryPolicy, options) {
|
|
25
|
+
/** non-null when auto-refresh is active */
|
|
26
|
+
this.tokenManager = null;
|
|
21
27
|
this.config = config;
|
|
22
28
|
this.retryPolicy = retryPolicy ?? defaultRetryPolicy();
|
|
23
29
|
this.targetUrl = options?.useQuoteServerUrl ? config.quoteServerUrl : config.serverUrl;
|
|
30
|
+
// Auto-start token refresh when tokenRefreshDuration is configured (mirrors Go SDK behaviour)
|
|
31
|
+
if (config.tokenRefreshDuration && config.tokenRefreshDuration > 0) {
|
|
32
|
+
const interval = config.tokenCheckInterval ?? DEFAULT_TOKEN_CHECK_INTERVAL;
|
|
33
|
+
const opts = {
|
|
34
|
+
refreshDuration: config.tokenRefreshDuration,
|
|
35
|
+
refreshInterval: interval,
|
|
36
|
+
};
|
|
37
|
+
if (config.tokenWriter) {
|
|
38
|
+
opts.tokenWriter = config.tokenWriter;
|
|
39
|
+
}
|
|
40
|
+
if (config.tokenLoader) {
|
|
41
|
+
opts.tokenLoader = config.tokenLoader;
|
|
42
|
+
}
|
|
43
|
+
this.tokenManager = this.startTokenAutoRefresh(null, opts);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Stop the background token auto-refresh timer.
|
|
48
|
+
* Call this when the HttpClient is no longer needed to avoid timer leaks.
|
|
49
|
+
*/
|
|
50
|
+
close() {
|
|
51
|
+
if (this.tokenManager) {
|
|
52
|
+
this.tokenManager.stopAutoRefresh();
|
|
53
|
+
this.tokenManager = null;
|
|
54
|
+
}
|
|
24
55
|
}
|
|
25
56
|
/**
|
|
26
57
|
* Build common request parameters
|
|
@@ -31,7 +62,11 @@ export class HttpClient {
|
|
|
31
62
|
method: apiMethod,
|
|
32
63
|
charset: DEFAULT_CHARSET,
|
|
33
64
|
sign_type: DEFAULT_SIGN_TYPE,
|
|
34
|
-
timestamp:
|
|
65
|
+
timestamp: (() => {
|
|
66
|
+
const d = new Date();
|
|
67
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
68
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
69
|
+
})(),
|
|
35
70
|
version: version || DEFAULT_VERSION,
|
|
36
71
|
biz_content: bizContent,
|
|
37
72
|
};
|
|
@@ -58,6 +93,7 @@ export class HttpClient {
|
|
|
58
93
|
const headers = {
|
|
59
94
|
'Content-Type': 'application/json;charset=UTF-8',
|
|
60
95
|
'User-Agent': USER_AGENT,
|
|
96
|
+
'Connection': 'close',
|
|
61
97
|
};
|
|
62
98
|
if (this.config.token) {
|
|
63
99
|
headers['Authorization'] = this.config.token;
|
|
@@ -68,7 +104,8 @@ export class HttpClient {
|
|
|
68
104
|
body,
|
|
69
105
|
signal: AbortSignal.timeout(this.config.timeout * 1000),
|
|
70
106
|
});
|
|
71
|
-
|
|
107
|
+
const text = await response.text();
|
|
108
|
+
return text;
|
|
72
109
|
}
|
|
73
110
|
/**
|
|
74
111
|
* Execute a structured API request, returning a parsed ApiResponse.
|
|
@@ -95,6 +132,10 @@ export class HttpClient {
|
|
|
95
132
|
}
|
|
96
133
|
catch (err) {
|
|
97
134
|
lastErr = err;
|
|
135
|
+
// Only retry on network errors, not API business errors (TigerError with code)
|
|
136
|
+
if (err.code !== undefined && err.code !== -1) {
|
|
137
|
+
throw err; // API returned a business error code, don't retry
|
|
138
|
+
}
|
|
98
139
|
if (!this.retryPolicy.shouldRetry(request.method)) {
|
|
99
140
|
throw err;
|
|
100
141
|
}
|
|
@@ -107,9 +148,10 @@ export class HttpClient {
|
|
|
107
148
|
*
|
|
108
149
|
* @param apiMethod - API method name (e.g. "market_state", "place_order")
|
|
109
150
|
* @param requestJson - Raw biz_content JSON string
|
|
151
|
+
* @param version - Optional API version override (default: "2.0")
|
|
110
152
|
* @returns Raw response JSON string, unparsed
|
|
111
153
|
*/
|
|
112
|
-
async execute(apiMethod, requestJson) {
|
|
154
|
+
async execute(apiMethod, requestJson, version) {
|
|
113
155
|
// Parameter validation
|
|
114
156
|
if (!apiMethod) {
|
|
115
157
|
throw new TigerError(-1, 'api_method must not be empty');
|
|
@@ -120,7 +162,7 @@ export class HttpClient {
|
|
|
120
162
|
catch {
|
|
121
163
|
throw new TigerError(-1, 'request_json is not valid JSON');
|
|
122
164
|
}
|
|
123
|
-
const params = this.buildCommonParams(apiMethod, requestJson);
|
|
165
|
+
const params = this.buildCommonParams(apiMethod, requestJson, version);
|
|
124
166
|
const sign = this.signParams(params);
|
|
125
167
|
params['sign'] = sign;
|
|
126
168
|
let lastErr;
|
|
@@ -141,6 +183,10 @@ export class HttpClient {
|
|
|
141
183
|
}
|
|
142
184
|
catch (err) {
|
|
143
185
|
lastErr = err;
|
|
186
|
+
// Don't retry API business errors
|
|
187
|
+
if (err.code !== undefined && err.code !== -1) {
|
|
188
|
+
throw err;
|
|
189
|
+
}
|
|
144
190
|
if (!this.retryPolicy.shouldRetry(apiMethod)) {
|
|
145
191
|
throw err;
|
|
146
192
|
}
|
|
@@ -148,6 +194,75 @@ export class HttpClient {
|
|
|
148
194
|
}
|
|
149
195
|
throw lastErr;
|
|
150
196
|
}
|
|
197
|
+
/**
|
|
198
|
+
* 调用 user_token_refresh 接口获取新 token,返回新 token 字符串。
|
|
199
|
+
* 此方法仅查询,不修改 config 中的 token。
|
|
200
|
+
*/
|
|
201
|
+
async queryToken() {
|
|
202
|
+
const params = this.buildCommonParams(METHOD_TOKEN_REFRESH, '{}');
|
|
203
|
+
const sign = this.signParams(params);
|
|
204
|
+
params['sign'] = sign;
|
|
205
|
+
const body = await this.doHttpPost(params);
|
|
206
|
+
const response = parseApiResponse(body);
|
|
207
|
+
this.verifyResponseSign(params['timestamp'], response.sign);
|
|
208
|
+
const data = unmarshalData(response.data);
|
|
209
|
+
const newToken = data?.token;
|
|
210
|
+
if (!newToken) {
|
|
211
|
+
throw new TigerError(-1, '服务端返回空 token');
|
|
212
|
+
}
|
|
213
|
+
return newToken;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* 刷新 token:调用接口获取新 token 后更新 config.token。
|
|
217
|
+
*
|
|
218
|
+
* @param tokenManager - 可选外部 TokenManager;若提供则调用 setToken() 写文件并触发回调。
|
|
219
|
+
* 若 NewHttpClient 已自动启动内部 TokenManager,其内存 token 也会同步更新。
|
|
220
|
+
*/
|
|
221
|
+
async refreshToken(tokenManager) {
|
|
222
|
+
const newToken = await this.queryToken();
|
|
223
|
+
this.config.token = newToken;
|
|
224
|
+
// Keep internal tokenManager in sync so shouldTokenRefresh stays accurate.
|
|
225
|
+
if (this.tokenManager && tokenManager !== this.tokenManager) {
|
|
226
|
+
this.tokenManager.syncToken(newToken);
|
|
227
|
+
}
|
|
228
|
+
if (tokenManager) {
|
|
229
|
+
tokenManager.setToken(newToken);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* 启动后台 token 自动刷新。
|
|
234
|
+
*
|
|
235
|
+
* @param tokenManager - 可为 null:SDK 内部自动创建一个仅内存的 TokenManager,
|
|
236
|
+
* 适合直接通过 token 在代码里设置、不使用文件的场景。
|
|
237
|
+
* @param options - 仅在 tokenManager 为 null 时生效,用于配置内部 TokenManager
|
|
238
|
+
* (refreshDuration / refreshInterval / tokenWriter / tokenLoader)。
|
|
239
|
+
* @returns 使用或创建的 TokenManager 实例
|
|
240
|
+
*/
|
|
241
|
+
startTokenAutoRefresh(tokenManager, options) {
|
|
242
|
+
if (!tokenManager) {
|
|
243
|
+
tokenManager = new TokenManager(options);
|
|
244
|
+
// 从 config.token 同步当前 token,使 shouldTokenRefresh 能正确判断。
|
|
245
|
+
// 若 config.token 暂时为空(异步 tokenLoader 尚未 resolve),则先异步加载。
|
|
246
|
+
if (this.config.token) {
|
|
247
|
+
tokenManager.syncToken(this.config.token);
|
|
248
|
+
}
|
|
249
|
+
else if (options?.tokenLoader) {
|
|
250
|
+
// tokenLoader 可能是异步的;在后台 resolve 后同步到 config.token 和 TokenManager。
|
|
251
|
+
Promise.resolve(options.tokenLoader()).then((t) => {
|
|
252
|
+
if (t) {
|
|
253
|
+
this.config.token = t;
|
|
254
|
+
tokenManager.syncToken(t);
|
|
255
|
+
}
|
|
256
|
+
}).catch(() => { });
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
tokenManager.startAutoRefresh(async () => {
|
|
260
|
+
const newToken = await this.queryToken();
|
|
261
|
+
this.config.token = newToken;
|
|
262
|
+
return newToken;
|
|
263
|
+
});
|
|
264
|
+
return tokenManager;
|
|
265
|
+
}
|
|
151
266
|
/** Delay for the specified milliseconds */
|
|
152
267
|
sleep(ms) {
|
|
153
268
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -161,7 +276,8 @@ export class HttpClient {
|
|
|
161
276
|
*/
|
|
162
277
|
verifyResponseSign(timestamp, signBase64) {
|
|
163
278
|
if (!signBase64) {
|
|
164
|
-
|
|
279
|
+
// Some endpoints don't return a signature; skip verification silently.
|
|
280
|
+
return;
|
|
165
281
|
}
|
|
166
282
|
const valid = verifyWithRSA(this.config.tigerPublicKey, timestamp, signBase64);
|
|
167
283
|
if (!valid) {
|
package/dist/esm/client/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Transport layer exports.
|
|
3
3
|
*/
|
|
4
|
-
export { HttpClient } from './http-client';
|
|
5
|
-
export { TigerError, classifyErrorCode } from './errors';
|
|
6
|
-
export { RetryPolicy, defaultRetryPolicy, isTradeOperation } from './retry';
|
|
7
|
-
export { createApiRequest } from './api-request';
|
|
8
|
-
export { parseApiResponse, unmarshalData } from './api-response';
|
|
9
|
-
export { camelToSnake, keysToSnakeCase } from './case-convert';
|
|
4
|
+
export { HttpClient } from './http-client.js';
|
|
5
|
+
export { TigerError, classifyErrorCode } from './errors.js';
|
|
6
|
+
export { RetryPolicy, defaultRetryPolicy, isTradeOperation } from './retry.js';
|
|
7
|
+
export { createApiRequest } from './api-request.js';
|
|
8
|
+
export { parseApiResponse, unmarshalData } from './api-response.js';
|
|
9
|
+
export { camelToSnake, keysToSnakeCase } from './case-convert.js';
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Call the `user_token_refresh` API and return the new token string.
|
|
3
|
+
* Read-only: does NOT update the stored token.
|
|
4
|
+
* Use `refreshToken()` to also update the in-memory config and optionally persist.
|
|
5
|
+
*/
|
|
6
|
+
export async function queryToken(httpClient) {
|
|
7
|
+
return httpClient.queryToken();
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Refresh the token: call the API, update the in-memory config token, and
|
|
11
|
+
* optionally persist via the provided TokenManager (file + writer callback).
|
|
12
|
+
*
|
|
13
|
+
* @param httpClient - The underlying HTTP client
|
|
14
|
+
* @param tokenManager - optional TokenManager for file persistence and writer callback
|
|
15
|
+
*/
|
|
16
|
+
export async function refreshToken(httpClient, tokenManager) {
|
|
17
|
+
return httpClient.refreshToken(tokenManager);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Start background token auto-refresh. Returns a TokenManager that can be
|
|
21
|
+
* used to stop the background task via `tm.stopAutoRefresh()`.
|
|
22
|
+
*
|
|
23
|
+
* @param httpClient - The underlying HTTP client
|
|
24
|
+
* @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
|
|
25
|
+
* When the token age exceeds this value the refresh is triggered.
|
|
26
|
+
* @param checkIntervalMs - How often to check whether a refresh is needed,
|
|
27
|
+
* in milliseconds. Defaults to 300 000 ms (5 minutes).
|
|
28
|
+
* @param tokenWriter - Optional callback invoked with the new token string
|
|
29
|
+
* after each successful refresh.
|
|
30
|
+
*/
|
|
31
|
+
export function startTokenAutoRefresh(httpClient, refreshDurationSecs, checkIntervalMs, tokenWriter) {
|
|
32
|
+
return httpClient.startTokenAutoRefresh(null, {
|
|
33
|
+
refreshDuration: refreshDurationSecs,
|
|
34
|
+
refreshInterval: checkIntervalMs,
|
|
35
|
+
tokenWriter,
|
|
36
|
+
});
|
|
37
|
+
}
|