@portal-hq/utils 5.1.0 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/commonjs/config/index.js +0 -1
- package/lib/commonjs/definitions/index.js +7 -1
- package/lib/commonjs/errors/index.js +9 -1
- package/lib/commonjs/errors/portal-auth-error.js +10 -2
- package/lib/commonjs/errors/portal-idempotency-error.js +74 -0
- package/lib/commonjs/errors/portal-passkey-prf-error.js +69 -0
- package/lib/commonjs/events/index.js +34 -0
- package/lib/commonjs/http-request/index.js +17 -2
- package/lib/commonjs/idempotency/index.js +74 -0
- package/lib/commonjs/index.js +12 -2
- package/lib/commonjs/requesters/http.js +9 -7
- package/lib/commonjs/version/version.json +1 -1
- package/lib/esm/config/index.js +0 -1
- package/lib/esm/definitions/index.js +7 -1
- package/lib/esm/errors/index.js +2 -0
- package/lib/esm/errors/portal-auth-error.js +10 -2
- package/lib/esm/errors/portal-idempotency-error.js +69 -0
- package/lib/esm/errors/portal-passkey-prf-error.js +66 -0
- package/lib/esm/events/index.js +34 -0
- package/lib/esm/http-request/index.js +17 -2
- package/lib/esm/idempotency/index.js +66 -0
- package/lib/esm/index.js +2 -1
- package/lib/esm/requesters/http.js +9 -7
- package/lib/esm/version/version.json +1 -1
- package/package.json +4 -4
- package/src/config/index.ts +0 -1
- package/src/definitions/index.ts +116 -20
- package/src/errors/index.ts +12 -0
- package/src/errors/portal-auth-error.ts +11 -2
- package/src/errors/portal-idempotency-error.ts +91 -0
- package/src/errors/portal-passkey-prf-error.ts +97 -0
- package/src/events/index.ts +35 -0
- package/src/http-request/index.ts +25 -2
- package/src/idempotency/index.ts +97 -0
- package/src/index.ts +18 -1
- package/src/requesters/http.ts +13 -7
- package/src/version/version.json +1 -1
- package/types.d.ts +40 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
var _a;
|
|
2
|
+
/** Why a passkey PRF backup could not be enrolled, read or decrypted. */
|
|
3
|
+
export var PortalPasskeyPrfErrorReason;
|
|
4
|
+
(function (PortalPasskeyPrfErrorReason) {
|
|
5
|
+
/** The passkey ceremony failed before a secret was derived, for a reason other than the two below. */
|
|
6
|
+
PortalPasskeyPrfErrorReason["CeremonyFailed"] = "PRF_CEREMONY_FAILED";
|
|
7
|
+
/** The user dismissed the passkey prompt. */
|
|
8
|
+
PortalPasskeyPrfErrorReason["UserCancelled"] = "PRF_USER_CANCELLED";
|
|
9
|
+
/** The platform reported that it has no passkey to offer for this request. */
|
|
10
|
+
PortalPasskeyPrfErrorReason["PasskeyUnavailable"] = "PRF_PASSKEY_UNAVAILABLE";
|
|
11
|
+
/** No passkey has been enrolled for this client, so there is nothing to recover with. */
|
|
12
|
+
PortalPasskeyPrfErrorReason["CredentialNotFound"] = "PRF_CREDENTIAL_NOT_FOUND";
|
|
13
|
+
/** The backup could not be decrypted with the secret the passkey produced. */
|
|
14
|
+
PortalPasskeyPrfErrorReason["DecryptFailed"] = "PRF_DECRYPT_FAILED";
|
|
15
|
+
/** The device or passkey provider cannot evaluate the WebAuthn PRF extension. */
|
|
16
|
+
PortalPasskeyPrfErrorReason["NotSupported"] = "PRF_NOT_SUPPORTED";
|
|
17
|
+
/** The passkey was enrolled under a different relying party than the one configured. */
|
|
18
|
+
PortalPasskeyPrfErrorReason["RpIdMismatch"] = "PRF_RP_ID_MISMATCH";
|
|
19
|
+
})(PortalPasskeyPrfErrorReason || (PortalPasskeyPrfErrorReason = {}));
|
|
20
|
+
const passkeyPrfErrors = {
|
|
21
|
+
[PortalPasskeyPrfErrorReason.CeremonyFailed]: 'The passkey request could not be completed.',
|
|
22
|
+
[PortalPasskeyPrfErrorReason.UserCancelled]: 'The passkey request was cancelled.',
|
|
23
|
+
[PortalPasskeyPrfErrorReason.PasskeyUnavailable]: 'The enrolled passkey is not available on this device.',
|
|
24
|
+
[PortalPasskeyPrfErrorReason.CredentialNotFound]: 'No passkey has been enrolled for this backup method.',
|
|
25
|
+
[PortalPasskeyPrfErrorReason.DecryptFailed]: 'The backup could not be decrypted with the secret from this passkey (wrong passkey or wrong ciphertext).',
|
|
26
|
+
[PortalPasskeyPrfErrorReason.NotSupported]: 'This device or passkey provider does not support the WebAuthn PRF extension.',
|
|
27
|
+
[PortalPasskeyPrfErrorReason.RpIdMismatch]: 'The passkey was enrolled under a different relying party.',
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
|
|
31
|
+
* when a consumer's tree resolves two `@portal-hq/utils` — a dismissed prompt
|
|
32
|
+
* would then be reported as an unexpected MPC failure.
|
|
33
|
+
*
|
|
34
|
+
* This key and the members {@link PortalPasskeyPrfError.is} implies are a
|
|
35
|
+
* compatibility contract: changing either breaks recognition between copies.
|
|
36
|
+
*/
|
|
37
|
+
const BRAND = Symbol.for('@portal-hq/utils/PortalPasskeyPrfError');
|
|
38
|
+
/**
|
|
39
|
+
* The single error every passkey PRF backup failure is normalized to; branch
|
|
40
|
+
* on `reason`.
|
|
41
|
+
*/
|
|
42
|
+
class PortalPasskeyPrfError extends Error {
|
|
43
|
+
constructor({ reason, cause, context }) {
|
|
44
|
+
super(`[Portal] ${passkeyPrfErrors[reason]}${context ? ` ${context}` : ''}`);
|
|
45
|
+
/** @internal Cross-copy brand. Read it through {@link PortalPasskeyPrfError.is}. */
|
|
46
|
+
this[_a] = true;
|
|
47
|
+
Object.setPrototypeOf(this, PortalPasskeyPrfError.prototype);
|
|
48
|
+
this.reason = reason;
|
|
49
|
+
this.cause = cause;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Brand check — see BRAND. Narrowing a branded error from another copy to
|
|
53
|
+
* this class is intentional.
|
|
54
|
+
*/
|
|
55
|
+
static is(error) {
|
|
56
|
+
return (typeof error === 'object' &&
|
|
57
|
+
error !== null &&
|
|
58
|
+
error[BRAND] === true);
|
|
59
|
+
}
|
|
60
|
+
/** True when the user chose not to continue, rather than something failing. */
|
|
61
|
+
get isUserCancelled() {
|
|
62
|
+
return this.reason === PortalPasskeyPrfErrorReason.UserCancelled;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
_a = BRAND;
|
|
66
|
+
export default PortalPasskeyPrfError;
|
package/lib/esm/events/index.js
CHANGED
|
@@ -116,5 +116,39 @@ var Events;
|
|
|
116
116
|
Events["YieldXyzPerpsGetEvent"] = "YieldXyz Perps Get Event";
|
|
117
117
|
Events["YieldXyzPerpsGetHealth"] = "YieldXyz Perps Get Health";
|
|
118
118
|
Events["YieldXyzPerpsGetProvidersHealth"] = "YieldXyz Perps Get Providers Health";
|
|
119
|
+
Events["AggCreateLinkChallenge"] = "Agg Create Link Challenge";
|
|
120
|
+
Events["AggCreateLink"] = "Agg Create Link";
|
|
121
|
+
Events["AggGetLink"] = "Agg Get Link";
|
|
122
|
+
Events["AggDeleteLink"] = "Agg Delete Link";
|
|
123
|
+
Events["AggListEvents"] = "Agg List Events";
|
|
124
|
+
Events["AggGetEvent"] = "Agg Get Event";
|
|
125
|
+
Events["AggGetEventBootstrap"] = "Agg Get Event Bootstrap";
|
|
126
|
+
Events["AggListMarkets"] = "Agg List Markets";
|
|
127
|
+
Events["AggSearch"] = "Agg Search";
|
|
128
|
+
Events["AggListCategories"] = "Agg List Categories";
|
|
129
|
+
Events["AggGetVenueGeoPolicy"] = "Agg Get Venue Geo Policy";
|
|
130
|
+
Events["AggGetAppConfig"] = "Agg Get App Config";
|
|
131
|
+
Events["AggGetMidpoints"] = "Agg Get Midpoints";
|
|
132
|
+
Events["AggGetOrderbooks"] = "Agg Get Orderbooks";
|
|
133
|
+
Events["AggGetOutcomeOrderbook"] = "Agg Get Outcome Orderbook";
|
|
134
|
+
Events["AggGetChartBars"] = "Agg Get Chart Bars";
|
|
135
|
+
Events["AggGetChartHistoryManifest"] = "Agg Get Chart History Manifest";
|
|
136
|
+
Events["AggGetUser"] = "Agg Get User";
|
|
137
|
+
Events["AggGetDepositAddresses"] = "Agg Get Deposit Addresses";
|
|
138
|
+
Events["AggGetBalances"] = "Agg Get Balances";
|
|
139
|
+
Events["AggListPositions"] = "Agg List Positions";
|
|
140
|
+
Events["AggListOrders"] = "Agg List Orders";
|
|
141
|
+
Events["AggListActivity"] = "Agg List Activity";
|
|
142
|
+
Events["AggCreateQuote"] = "Agg Create Quote";
|
|
143
|
+
Events["AggCreateOrder"] = "Agg Create Order";
|
|
144
|
+
Events["AggGetOrder"] = "Agg Get Order";
|
|
145
|
+
Events["AggCreateLimitOrder"] = "Agg Create Limit Order";
|
|
146
|
+
Events["AggCreateDirectOrder"] = "Agg Create Direct Order";
|
|
147
|
+
Events["AggCancelOrder"] = "Agg Cancel Order";
|
|
148
|
+
Events["AggRedeemPositions"] = "Agg Redeem Positions";
|
|
149
|
+
Events["AggQuoteWithdrawable"] = "Agg Quote Withdrawable";
|
|
150
|
+
Events["AggPreviewWithdrawal"] = "Agg Preview Withdrawal";
|
|
151
|
+
Events["AggCreateWithdrawal"] = "Agg Create Withdrawal";
|
|
152
|
+
Events["AggGetWithdrawal"] = "Agg Get Withdrawal";
|
|
119
153
|
})(Events || (Events = {}));
|
|
120
154
|
export default Events;
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { HttpError } from '../errors';
|
|
2
2
|
class HttpRequest {
|
|
3
|
-
constructor({ body = {}, headers = {}, method, url }) {
|
|
3
|
+
constructor({ body = {}, headers = {}, method, rejectTransportFailures = false, url, }) {
|
|
4
4
|
this.body = body;
|
|
5
5
|
this.headers = headers;
|
|
6
6
|
this.method = method;
|
|
7
|
+
this.rejectTransportFailures = rejectTransportFailures;
|
|
7
8
|
this.url = url;
|
|
8
9
|
this.request = new XMLHttpRequest();
|
|
9
10
|
this.request.open(this.method, this.url, true);
|
|
@@ -20,11 +21,18 @@ class HttpRequest {
|
|
|
20
21
|
else {
|
|
21
22
|
this.request.send();
|
|
22
23
|
}
|
|
24
|
+
if (this.rejectTransportFailures) {
|
|
25
|
+
this.request.onerror = () => reject(this.buildTransportError());
|
|
26
|
+
this.request.ontimeout = () => reject(this.buildTransportError());
|
|
27
|
+
}
|
|
23
28
|
// Adds an event listener for when the request state changes
|
|
24
29
|
this.request.onreadystatechange = () => {
|
|
25
30
|
if (this.request.readyState === 4) {
|
|
26
31
|
// readyState 4 means the request has completed
|
|
27
|
-
if (this.request.status
|
|
32
|
+
if (this.rejectTransportFailures && this.request.status === 0) {
|
|
33
|
+
reject(this.buildTransportError());
|
|
34
|
+
}
|
|
35
|
+
else if (this.request.status >= 300) {
|
|
28
36
|
// If we didn't get an 'OK' status, error out
|
|
29
37
|
reject(new HttpError({
|
|
30
38
|
message: this.request.responseText,
|
|
@@ -40,6 +48,13 @@ class HttpRequest {
|
|
|
40
48
|
};
|
|
41
49
|
});
|
|
42
50
|
}
|
|
51
|
+
buildTransportError() {
|
|
52
|
+
return new HttpError({
|
|
53
|
+
message: `Network request to ${this.url} failed`,
|
|
54
|
+
status: 0,
|
|
55
|
+
statusText: 'Network Error',
|
|
56
|
+
});
|
|
57
|
+
}
|
|
43
58
|
buildResponse() {
|
|
44
59
|
// If the response is empty, just return an empty object
|
|
45
60
|
if (this.request.status === 204) {
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import PortalIdempotencyError from '../errors/portal-idempotency-error';
|
|
2
|
+
import { generateTraceId } from '../tracing';
|
|
3
|
+
/**
|
|
4
|
+
* The HTTP header the Enclave MPC API reads a transaction broadcast's
|
|
5
|
+
* idempotency key from.
|
|
6
|
+
*/
|
|
7
|
+
export const PORTAL_IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key';
|
|
8
|
+
const IDEMPOTENCY_KEY_MAX_LENGTH = 255;
|
|
9
|
+
/** RFC 3986 unreserved characters, the only ones Portal accepts in a key. */
|
|
10
|
+
const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._~-]+$/;
|
|
11
|
+
const uuidV4FromRandomValues = (getRandomValues) => {
|
|
12
|
+
const bytes = getRandomValues(new Uint8Array(16));
|
|
13
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
14
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
15
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
16
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Generates an idempotency key: a lowercase UUID v4. Generate one per logical
|
|
20
|
+
* operation, store it with the pending operation, and reuse it only to retry
|
|
21
|
+
* that identical request.
|
|
22
|
+
*
|
|
23
|
+
* The key comes from `crypto.randomUUID` or `crypto.getRandomValues` when the
|
|
24
|
+
* runtime provides one. Hermes provides neither unless the app installs a
|
|
25
|
+
* polyfill such as `react-native-get-random-values`; without one the key is
|
|
26
|
+
* built from `Math.random`, which keeps keys unique in practice but is not a
|
|
27
|
+
* cryptographic source.
|
|
28
|
+
*/
|
|
29
|
+
export const generateIdempotencyKey = () => {
|
|
30
|
+
const runtimeCrypto = typeof crypto === 'undefined' ? undefined : crypto;
|
|
31
|
+
if (typeof (runtimeCrypto === null || runtimeCrypto === void 0 ? void 0 : runtimeCrypto.randomUUID) === 'function') {
|
|
32
|
+
return runtimeCrypto.randomUUID().toLowerCase();
|
|
33
|
+
}
|
|
34
|
+
if (typeof (runtimeCrypto === null || runtimeCrypto === void 0 ? void 0 : runtimeCrypto.getRandomValues) === 'function') {
|
|
35
|
+
return uuidV4FromRandomValues(runtimeCrypto.getRandomValues.bind(runtimeCrypto));
|
|
36
|
+
}
|
|
37
|
+
// With neither API available, generateTraceId builds the key from
|
|
38
|
+
// Math.random.
|
|
39
|
+
return generateTraceId().toLowerCase();
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Trims `key` the way Portal does (`String.prototype.trim`) and checks it
|
|
43
|
+
* against Portal's rules: 1–255 characters of `A-Z a-z 0-9 . _ ~ -`.
|
|
44
|
+
*
|
|
45
|
+
* @internal Exported only so the SDK packages can share it across the package
|
|
46
|
+
* boundary. Not part of the public API.
|
|
47
|
+
*
|
|
48
|
+
* @returns The trimmed key, which is the value the SDK sends.
|
|
49
|
+
* @throws {PortalIdempotencyError} `invalidKey`, naming the rule that failed.
|
|
50
|
+
*/
|
|
51
|
+
export const validateIdempotencyKey = (key) => {
|
|
52
|
+
if (typeof key !== 'string') {
|
|
53
|
+
throw new PortalIdempotencyError('invalidKey', 'idempotencyKey must be a string');
|
|
54
|
+
}
|
|
55
|
+
const trimmed = key.trim();
|
|
56
|
+
if (trimmed.length === 0) {
|
|
57
|
+
throw new PortalIdempotencyError('invalidKey', 'idempotencyKey must not be empty or whitespace-only');
|
|
58
|
+
}
|
|
59
|
+
if (trimmed.length > IDEMPOTENCY_KEY_MAX_LENGTH) {
|
|
60
|
+
throw new PortalIdempotencyError('invalidKey', `idempotencyKey must be at most ${IDEMPOTENCY_KEY_MAX_LENGTH} characters`);
|
|
61
|
+
}
|
|
62
|
+
if (!IDEMPOTENCY_KEY_PATTERN.test(trimmed)) {
|
|
63
|
+
throw new PortalIdempotencyError('invalidKey', "idempotencyKey may only contain the characters A-Z, a-z, 0-9, '.', '_', '~' and '-'");
|
|
64
|
+
}
|
|
65
|
+
return trimmed;
|
|
66
|
+
};
|
package/lib/esm/index.js
CHANGED
|
@@ -3,7 +3,8 @@ export { buildDefaultGatewayConfig, DEFAULT_HOSTS } from './config';
|
|
|
3
3
|
export { StaticCredentials, failFromMpcError, invalidateCredentials, onCredentialsInvalidated, reportUnauthorized, resolveCredentials, resolveCredentialToken, staticApiKeyOf, } from './credentials';
|
|
4
4
|
export { convertLocalToCrypto, convertCryptoToLocal, convert } from './currency';
|
|
5
5
|
export { KeychainAdapter, MpcStatuses, PasswordStorage, PortalRequestMethod, Storage, } from './definitions';
|
|
6
|
-
export { CloudStorageReadError, HttpError, InvalidApiKeyError, InvalidChainIdError, InvalidGatewayConfigError, MissingOptionError, MpcSigningError, NoAddressError, PortalAuthError, PortalAuthErrorReason, PortalCredentialError, PortalCredentialErrorReason, MPC_AUTH_FAILED_ERROR_ID, PortalErrorCodes, PortalErrorCodeTypes, PortalMpcError, PortalPolicyError, POLICY_ERROR_ID_PREFIX, PolicyErrorId, isMpcAuthFailure, isPolicyViolation, mpcErrorFrom, ProviderRpcError, RpcErrorCodes, } from './errors';
|
|
6
|
+
export { CloudStorageReadError, HttpError, InvalidApiKeyError, InvalidChainIdError, InvalidGatewayConfigError, MissingOptionError, MpcSigningError, NoAddressError, PortalPasskeyPrfError, PortalPasskeyPrfErrorReason, PortalAuthError, PortalAuthErrorReason, PortalCredentialError, PortalCredentialErrorReason, MPC_AUTH_FAILED_ERROR_ID, PortalErrorCodes, PortalErrorCodeTypes, PortalMpcError, PortalIdempotencyError, PortalIdempotencyErrorId, isIdempotencyKeyReused, isIdempotencyRejection, PortalPolicyError, POLICY_ERROR_ID_PREFIX, PolicyErrorId, isMpcAuthFailure, isPolicyViolation, mpcErrorFrom, ProviderRpcError, RpcErrorCodes, } from './errors';
|
|
7
|
+
export { generateIdempotencyKey, PORTAL_IDEMPOTENCY_KEY_HEADER, validateIdempotencyKey, } from './idempotency';
|
|
7
8
|
export { default as Events } from './events';
|
|
8
9
|
export { getClientPlatformVersion } from './version';
|
|
9
10
|
export { numberToHexString, parseRequest } from './eth-requests';
|
|
@@ -20,10 +20,12 @@ class HttpRequester {
|
|
|
20
20
|
* the hook's own failure is swallowed and the original `HttpError` is always
|
|
21
21
|
* what the caller sees.
|
|
22
22
|
*/
|
|
23
|
-
send(requestOptions) {
|
|
23
|
+
send(requestOptions, options) {
|
|
24
24
|
return __awaiter(this, void 0, void 0, function* () {
|
|
25
25
|
try {
|
|
26
|
-
|
|
26
|
+
const sentOptions = (options === null || options === void 0 ? void 0 : options.rejectTransportFailures)
|
|
27
|
+
? Object.assign(Object.assign({}, requestOptions), { rejectTransportFailures: true }) : requestOptions;
|
|
28
|
+
return (yield new HttpRequest(sentOptions).send());
|
|
27
29
|
}
|
|
28
30
|
catch (error) {
|
|
29
31
|
if (this.onUnauthorized &&
|
|
@@ -51,7 +53,7 @@ class HttpRequester {
|
|
|
51
53
|
url: `${this.baseUrl}${path}`,
|
|
52
54
|
};
|
|
53
55
|
requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
|
|
54
|
-
return this.send(requestOptions);
|
|
56
|
+
return this.send(requestOptions, options);
|
|
55
57
|
});
|
|
56
58
|
}
|
|
57
59
|
get(path, options) {
|
|
@@ -62,7 +64,7 @@ class HttpRequester {
|
|
|
62
64
|
url: `${this.baseUrl}${path}`,
|
|
63
65
|
};
|
|
64
66
|
requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
|
|
65
|
-
return this.send(requestOptions);
|
|
67
|
+
return this.send(requestOptions, options);
|
|
66
68
|
});
|
|
67
69
|
}
|
|
68
70
|
post(path, options) {
|
|
@@ -76,7 +78,7 @@ class HttpRequester {
|
|
|
76
78
|
if (options === null || options === void 0 ? void 0 : options.body) {
|
|
77
79
|
requestOptions.body = options.body;
|
|
78
80
|
}
|
|
79
|
-
return this.send(requestOptions);
|
|
81
|
+
return this.send(requestOptions, options);
|
|
80
82
|
});
|
|
81
83
|
}
|
|
82
84
|
put(path, options) {
|
|
@@ -90,7 +92,7 @@ class HttpRequester {
|
|
|
90
92
|
if (options === null || options === void 0 ? void 0 : options.body) {
|
|
91
93
|
requestOptions.body = options.body;
|
|
92
94
|
}
|
|
93
|
-
return this.send(requestOptions);
|
|
95
|
+
return this.send(requestOptions, options);
|
|
94
96
|
});
|
|
95
97
|
}
|
|
96
98
|
patch(path, options) {
|
|
@@ -104,7 +106,7 @@ class HttpRequester {
|
|
|
104
106
|
if (options === null || options === void 0 ? void 0 : options.body) {
|
|
105
107
|
requestOptions.body = options.body;
|
|
106
108
|
}
|
|
107
|
-
return this.send(requestOptions);
|
|
109
|
+
return this.send(requestOptions, options);
|
|
108
110
|
});
|
|
109
111
|
}
|
|
110
112
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{ "version": "
|
|
1
|
+
{ "version": "6.0.0" }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@portal-hq/utils",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "6.0.0",
|
|
4
4
|
"main": "lib/commonjs/index",
|
|
5
5
|
"module": "lib/esm/index",
|
|
6
6
|
"source": "src/index",
|
|
@@ -19,12 +19,12 @@
|
|
|
19
19
|
"test": "jest"
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
22
|
-
"@babel/preset-typescript": "^7.
|
|
22
|
+
"@babel/preset-typescript": "^7.29.7",
|
|
23
23
|
"@types/jest": "^29.2.0",
|
|
24
24
|
"jest": "^29.2.1",
|
|
25
25
|
"jest-environment-jsdom": "^29.2.2",
|
|
26
|
-
"ts-jest": "^29.
|
|
26
|
+
"ts-jest": "^29.4.15",
|
|
27
27
|
"typescript": "^4.8.4"
|
|
28
28
|
},
|
|
29
|
-
"gitHead": "
|
|
29
|
+
"gitHead": "46892641739410fe8a216890ee906ec1d4f22ca2"
|
|
30
30
|
}
|
package/src/config/index.ts
CHANGED
package/src/definitions/index.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import PortalConnect from '@portal-hq/connect'
|
|
2
1
|
import { BackupMethodsUpperCase } from '@portal-hq/core/src/mpc'
|
|
3
2
|
import {
|
|
4
3
|
AssetsResponse,
|
|
@@ -45,6 +44,8 @@ import type {
|
|
|
45
44
|
GetTransactionsOrder,
|
|
46
45
|
NFT,
|
|
47
46
|
Network,
|
|
47
|
+
PasskeyPrfCredential,
|
|
48
|
+
PasskeyPrfStorageConfig,
|
|
48
49
|
PortalKeychainMetadata,
|
|
49
50
|
Presignature,
|
|
50
51
|
ProgressCallback,
|
|
@@ -77,7 +78,6 @@ export interface RequestArguments {
|
|
|
77
78
|
method: string
|
|
78
79
|
params?: unknown[] | SigningRequestParams
|
|
79
80
|
chainId?: string
|
|
80
|
-
connect?: PortalConnect
|
|
81
81
|
options?: RequestOptions
|
|
82
82
|
}
|
|
83
83
|
|
|
@@ -85,6 +85,30 @@ export interface RequestOptions {
|
|
|
85
85
|
sponsorGas?: boolean
|
|
86
86
|
signatureApprovalMemo?: string
|
|
87
87
|
traceId?: string
|
|
88
|
+
/**
|
|
89
|
+
* Makes a transaction broadcast safe to retry: while Portal remembers a key
|
|
90
|
+
* (at least 24 hours) it broadcasts it at most once. Honoured for
|
|
91
|
+
* `eth_sendTransaction`, `sol_signAndSendTransaction` and
|
|
92
|
+
* `sol_signAndConfirmTransaction`; ignored with a warning for any other
|
|
93
|
+
* method. Surrounding whitespace is trimmed, and the key must then be 1–255
|
|
94
|
+
* characters of `A-Z a-z 0-9 . _ ~ -`, otherwise the request throws a
|
|
95
|
+
* `PortalIdempotencyError` before the approval prompt. A key on
|
|
96
|
+
* `eth_sendRawTransaction` or `sol_sendTransaction` also throws, because
|
|
97
|
+
* Portal cannot deduplicate a transaction that is already signed.
|
|
98
|
+
*
|
|
99
|
+
* Portal recognises a retry only when its `chainId`, `method` and `params`
|
|
100
|
+
* match the first request's, with `params` compared as the JSON string the
|
|
101
|
+
* SDK sends. Retry with the same transaction object: the same fields in a
|
|
102
|
+
* different order serialize differently, and the retry can be rejected with
|
|
103
|
+
* `IDEMPOTENCY_KEY_REUSED`. No rejection returns the original transaction
|
|
104
|
+
* hash.
|
|
105
|
+
*
|
|
106
|
+
* With presignatures on, a presignature attempt that fails after reaching
|
|
107
|
+
* Portal leaves the fallback sign reusing the key, so Portal can reject it
|
|
108
|
+
* (for example with `IDEMPOTENT_REQUEST_IN_PROGRESS`) where a request without
|
|
109
|
+
* a key would have been signed.
|
|
110
|
+
*/
|
|
111
|
+
idempotencyKey?: string
|
|
88
112
|
}
|
|
89
113
|
|
|
90
114
|
export enum PortalRequestMethod {
|
|
@@ -209,6 +233,30 @@ export interface SendAssetParams {
|
|
|
209
233
|
* to underlying API requests to aid in observability.
|
|
210
234
|
*/
|
|
211
235
|
traceId?: string
|
|
236
|
+
/**
|
|
237
|
+
* Optional idempotency key for the broadcast, honoured on EVM and Solana
|
|
238
|
+
* chains (see `RequestOptions.idempotencyKey`). A key on a Bitcoin chain
|
|
239
|
+
* throws a `PortalIdempotencyError` before the transaction is built.
|
|
240
|
+
*
|
|
241
|
+
* `sendAsset` rebuilds the transaction on every call, and a retry is
|
|
242
|
+
* recognised only when the rebuilt transaction matches the first one. An EVM
|
|
243
|
+
* build carries no nonce or gas, so with unchanged inputs it normally
|
|
244
|
+
* matches and the retry is rejected with the first request's status (for
|
|
245
|
+
* example `IDEMPOTENT_REQUEST_ALREADY_COMPLETED`). A Solana build carries a
|
|
246
|
+
* new recent blockhash, so the retry is usually rejected with
|
|
247
|
+
* `IDEMPOTENCY_KEY_REUSED`, which does not say whether the first transfer
|
|
248
|
+
* is in progress, completed or failed. Either way the transfer is not
|
|
249
|
+
* broadcast twice under this key, and no rejection returns the original
|
|
250
|
+
* transaction hash.
|
|
251
|
+
*
|
|
252
|
+
* Before sending the transfer again under a new key, confirm on-chain that
|
|
253
|
+
* the first one did not land: on Solana, wait until it is confirmed or its
|
|
254
|
+
* recent blockhash has expired; on EVM, until it is confirmed or the
|
|
255
|
+
* account's nonce has moved past it. For predictable retries, build the
|
|
256
|
+
* transaction once and send it with `portal.request` and the same key on
|
|
257
|
+
* every attempt.
|
|
258
|
+
*/
|
|
259
|
+
idempotencyKey?: string
|
|
212
260
|
}
|
|
213
261
|
|
|
214
262
|
export interface RawSignOptions {
|
|
@@ -238,6 +286,11 @@ export interface PortalCredentials {
|
|
|
238
286
|
invalidate(): Promise<void>
|
|
239
287
|
}
|
|
240
288
|
|
|
289
|
+
export interface GetClientOptions {
|
|
290
|
+
/** Rejects a network failure instead of resolving it as a missing client. */
|
|
291
|
+
rejectTransportFailures?: boolean
|
|
292
|
+
}
|
|
293
|
+
|
|
241
294
|
export interface IPortalApi {
|
|
242
295
|
/**
|
|
243
296
|
* @deprecated Read the credential through `getToken()` instead.
|
|
@@ -264,8 +317,16 @@ export interface IPortalApi {
|
|
|
264
317
|
): Promise<GenerateApiResponse>
|
|
265
318
|
getBackupSharesMetadata(chainId?: string): Promise<BackupSharePairMetadata[]>
|
|
266
319
|
getBalances(chainId?: string, traceId?: string): Promise<Balance[]>
|
|
267
|
-
getClient(
|
|
320
|
+
getClient(
|
|
321
|
+
traceId?: string,
|
|
322
|
+
options?: GetClientOptions,
|
|
323
|
+
): Promise<ClientResponse>
|
|
268
324
|
getClientCipherText(backupSharePairId: string): Promise<string>
|
|
325
|
+
/** Resolves to `null` when the client has not enrolled a passkey. */
|
|
326
|
+
getPasskeyPrfCredential(): Promise<PasskeyPrfCredential | null>
|
|
327
|
+
storePasskeyPrfCredential(
|
|
328
|
+
credential: PasskeyPrfCredential,
|
|
329
|
+
): Promise<PasskeyPrfCredential>
|
|
269
330
|
getEnabledDapps(): Promise<Dapp[]>
|
|
270
331
|
getNFTs(chainId?: string, traceId?: string): Promise<NFT[]>
|
|
271
332
|
getNftAssets(chainId: string, traceId?: string): Promise<NFTAsset[]>
|
|
@@ -312,6 +373,7 @@ export interface IPortalApi {
|
|
|
312
373
|
| 'GDRIVE'
|
|
313
374
|
| 'ICLOUD'
|
|
314
375
|
| 'PASSKEY'
|
|
376
|
+
| 'PASSKEY_PRF'
|
|
315
377
|
| 'PASSWORD'
|
|
316
378
|
| 'FIREBASE'
|
|
317
379
|
| 'UNKNOWN',
|
|
@@ -324,6 +386,7 @@ export interface IPortalApi {
|
|
|
324
386
|
| 'ICLOUD'
|
|
325
387
|
| 'FIREBASE'
|
|
326
388
|
| 'PASSKEY'
|
|
389
|
+
| 'PASSKEY_PRF'
|
|
327
390
|
| 'PASSWORD'
|
|
328
391
|
| 'UNKNOWN',
|
|
329
392
|
): Promise<void>
|
|
@@ -377,18 +440,6 @@ export interface IPortalApi {
|
|
|
377
440
|
): Promise<string>
|
|
378
441
|
}
|
|
379
442
|
|
|
380
|
-
export interface IPortalConnect {
|
|
381
|
-
connected: boolean
|
|
382
|
-
connect(uri: string): Promise<void>
|
|
383
|
-
deinit(): void
|
|
384
|
-
disconnect(): void
|
|
385
|
-
emit(event: string, data: any): PortalConnect
|
|
386
|
-
on(event: string, callback: EventHandler): PortalConnect
|
|
387
|
-
once(event: string, callback: EventHandler): PortalConnect
|
|
388
|
-
removeEventListener(event: string, listenerToRemove?: EventHandler): void
|
|
389
|
-
setChainId(chainId: number): Promise<void>
|
|
390
|
-
}
|
|
391
|
-
|
|
392
443
|
export interface IPortalProvider {
|
|
393
444
|
/**
|
|
394
445
|
* @deprecated Read the credential through `credentials.getToken()` instead.
|
|
@@ -411,10 +462,7 @@ export interface IPortalProvider {
|
|
|
411
462
|
once(event: string, callback: EventHandler): IPortalProvider
|
|
412
463
|
removeEventListener(event: string, listenerToRemove?: EventHandler): void
|
|
413
464
|
request(args: RequestArguments): Promise<any>
|
|
414
|
-
setChainId(
|
|
415
|
-
chainId: string | number,
|
|
416
|
-
connect?: PortalConnect | undefined,
|
|
417
|
-
): Promise<IPortalProvider>
|
|
465
|
+
setChainId(chainId: string | number): Promise<IPortalProvider>
|
|
418
466
|
}
|
|
419
467
|
|
|
420
468
|
export abstract class KeychainAdapter {
|
|
@@ -541,9 +589,41 @@ export enum MpcStatuses {
|
|
|
541
589
|
StoringShare = 'Storing share',
|
|
542
590
|
}
|
|
543
591
|
|
|
592
|
+
/** The backup share pair ids of one backup operation, one per curve. */
|
|
593
|
+
export interface BackupKeyOptions {
|
|
594
|
+
backupSharePairIds: string[]
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** Resolves true when the candidate key decrypts the backup being recovered. */
|
|
598
|
+
export type BackupKeyMatcher = (key: string) => Promise<boolean>
|
|
599
|
+
|
|
544
600
|
export abstract class Storage {
|
|
545
601
|
public api?: IPortalApi
|
|
546
602
|
|
|
603
|
+
/**
|
|
604
|
+
* Optional. Lets recovery try every key the storage holds for the client,
|
|
605
|
+
* preferring keys labelled with `options.backupSharePairIds`, instead of
|
|
606
|
+
* relying on `read()`. Resolves null when no stored key is accepted.
|
|
607
|
+
*/
|
|
608
|
+
readFirstMatchingKey?(
|
|
609
|
+
matches: BackupKeyMatcher,
|
|
610
|
+
options?: BackupKeyOptions,
|
|
611
|
+
): Promise<string | null>
|
|
612
|
+
|
|
613
|
+
/**
|
|
614
|
+
* Optional. Deletes keys labelled with the given backup share pair ids.
|
|
615
|
+
* Called only after a newer backup has completed; never deletes unlabelled
|
|
616
|
+
* keys.
|
|
617
|
+
*/
|
|
618
|
+
deleteBackupKeys?(options: BackupKeyOptions): Promise<void>
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* Optional. Copies the key labelled with `options.backupSharePairIds` to the
|
|
622
|
+
* single unlabelled key that SDKs without labelled keys read. Called only
|
|
623
|
+
* after the API confirms those pairs as the active backup.
|
|
624
|
+
*/
|
|
625
|
+
promoteBackupKey?(options: BackupKeyOptions): Promise<void>
|
|
626
|
+
|
|
547
627
|
delete(): Promise<boolean> {
|
|
548
628
|
throw new Error(
|
|
549
629
|
'[Portal] Storage method delete cannot be called directly. Please extend Storage.',
|
|
@@ -556,7 +636,13 @@ export abstract class Storage {
|
|
|
556
636
|
)
|
|
557
637
|
}
|
|
558
638
|
|
|
559
|
-
|
|
639
|
+
/**
|
|
640
|
+
* `options` carries the pair ids of the backup that produced the key, so
|
|
641
|
+
* storage can keep keys of different backups apart. Implementations may
|
|
642
|
+
* ignore it.
|
|
643
|
+
*/
|
|
644
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
645
|
+
write(privateKey: string, _options?: BackupKeyOptions): Promise<string> {
|
|
560
646
|
throw new Error(
|
|
561
647
|
`[Portal] Storage method write(${privateKey}) cannot be called directly. Please extend Storage.`,
|
|
562
648
|
)
|
|
@@ -569,6 +655,15 @@ export abstract class Storage {
|
|
|
569
655
|
}
|
|
570
656
|
}
|
|
571
657
|
|
|
658
|
+
/**
|
|
659
|
+
* A backup method whose share-encryption secret is derived on demand rather
|
|
660
|
+
* than generated and then stored. `read()` returns the secret for an existing
|
|
661
|
+
* enrollment and never creates one; `enroll()` is what backup calls, and may.
|
|
662
|
+
*/
|
|
663
|
+
export interface DerivedSecretStorage extends Storage {
|
|
664
|
+
enroll(options?: PasskeyPrfStorageConfig): Promise<string>
|
|
665
|
+
}
|
|
666
|
+
|
|
572
667
|
export class PasswordStorage implements Storage {
|
|
573
668
|
public api?: IPortalApi
|
|
574
669
|
|
|
@@ -600,6 +695,7 @@ export class PasswordStorage implements Storage {
|
|
|
600
695
|
export type BackupMethod =
|
|
601
696
|
| 'PASSWORD'
|
|
602
697
|
| 'PASSKEY'
|
|
698
|
+
| 'PASSKEY_PRF'
|
|
603
699
|
| 'GDRIVE'
|
|
604
700
|
| 'ICLOUD'
|
|
605
701
|
| 'CUSTOM'
|
package/src/errors/index.ts
CHANGED
|
@@ -17,6 +17,18 @@ export {
|
|
|
17
17
|
type PortalCredentialErrorOptions,
|
|
18
18
|
} from './portal-credential-error'
|
|
19
19
|
export * from './portal-error'
|
|
20
|
+
export {
|
|
21
|
+
default as PortalIdempotencyError,
|
|
22
|
+
type PortalIdempotencyErrorReason,
|
|
23
|
+
PortalIdempotencyErrorId,
|
|
24
|
+
isIdempotencyKeyReused,
|
|
25
|
+
isIdempotencyRejection,
|
|
26
|
+
} from './portal-idempotency-error'
|
|
27
|
+
export {
|
|
28
|
+
default as PortalPasskeyPrfError,
|
|
29
|
+
PortalPasskeyPrfErrorReason,
|
|
30
|
+
type PortalPasskeyPrfErrorOptions,
|
|
31
|
+
} from './portal-passkey-prf-error'
|
|
20
32
|
export {
|
|
21
33
|
default as PortalPolicyError,
|
|
22
34
|
POLICY_ERROR_ID_PREFIX,
|
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
*/
|
|
10
10
|
export enum PortalAuthErrorReason {
|
|
11
11
|
/**
|
|
12
|
-
* The backend refused
|
|
13
|
-
*
|
|
12
|
+
* The backend refused the grant: it has expired, was already used, or is
|
|
13
|
+
* otherwise unusable. Whatever the cause, it cannot be retried: start a new
|
|
14
|
+
* sign-in.
|
|
14
15
|
*/
|
|
15
16
|
GrantRejected = 'GRANT_REJECTED',
|
|
16
17
|
/**
|
|
@@ -18,6 +19,12 @@ export enum PortalAuthErrorReason {
|
|
|
18
19
|
* grant. The user never completed the provider's flow.
|
|
19
20
|
*/
|
|
20
21
|
ProviderRejected = 'PROVIDER_REJECTED',
|
|
22
|
+
/**
|
|
23
|
+
* An OAuth redirect arrived that this SDK holds no pending sign-in for: it
|
|
24
|
+
* never started one on this device, or the one it started has expired.
|
|
25
|
+
* Nothing was sent to the backend. Start a new sign-in.
|
|
26
|
+
*/
|
|
27
|
+
OAuthFlowNotStarted = 'OAUTH_FLOW_NOT_STARTED',
|
|
21
28
|
}
|
|
22
29
|
|
|
23
30
|
const authErrors: Record<PortalAuthErrorReason, string> = {
|
|
@@ -25,6 +32,8 @@ const authErrors: Record<PortalAuthErrorReason, string> = {
|
|
|
25
32
|
'The authentication grant was rejected. It may already have been used, expired, or been issued for a different auth environment. Start a new sign-in.',
|
|
26
33
|
[PortalAuthErrorReason.ProviderRejected]:
|
|
27
34
|
'The authentication provider rejected the sign-in.',
|
|
35
|
+
[PortalAuthErrorReason.OAuthFlowNotStarted]:
|
|
36
|
+
'The sign-in could not be completed. Start a new sign-in.',
|
|
28
37
|
}
|
|
29
38
|
|
|
30
39
|
export interface PortalAuthErrorOptions {
|