@portal-hq/utils 5.2.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.
@@ -5,7 +5,6 @@ exports.DEFAULT_HOSTS = {
5
5
  API: 'api.portalhq.io',
6
6
  MPC: 'mpc.portalhq.io',
7
7
  ENCLAVE_MPC: 'mpc-client.portalhq.io',
8
- WEBSOCKET: 'connect.portalhq.io',
9
8
  };
10
9
  /**
11
10
  * Canonical list of chains covered by the default gateway config. Single
@@ -182,7 +182,13 @@ class Storage {
182
182
  read() {
183
183
  throw new Error('[Portal] Storage method read cannot be called directly. Please extend Storage.');
184
184
  }
185
- write(privateKey) {
185
+ /**
186
+ * `options` carries the pair ids of the backup that produced the key, so
187
+ * storage can keep keys of different backups apart. Implementations may
188
+ * ignore it.
189
+ */
190
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
191
+ write(privateKey, _options) {
186
192
  throw new Error(`[Portal] Storage method write(${privateKey}) cannot be called directly. Please extend Storage.`);
187
193
  }
188
194
  validateOperations() {
@@ -17,7 +17,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.RpcErrorCodes = exports.ProviderRpcError = exports.mpcErrorFrom = exports.isPolicyViolation = exports.PolicyErrorId = exports.POLICY_ERROR_ID_PREFIX = exports.PortalPolicyError = exports.isIdempotencyRejection = exports.isIdempotencyKeyReused = exports.PortalIdempotencyErrorId = exports.PortalIdempotencyError = exports.PortalCredentialErrorReason = exports.PortalCredentialError = exports.PortalAuthErrorReason = exports.PortalAuthError = exports.NoAddressError = exports.MpcSigningError = exports.MissingOptionError = exports.InvalidGatewayConfigError = exports.InvalidChainIdError = exports.InvalidApiKeyError = exports.HttpError = exports.CloudStorageReadError = void 0;
20
+ exports.RpcErrorCodes = exports.ProviderRpcError = exports.mpcErrorFrom = exports.isPolicyViolation = exports.PolicyErrorId = exports.POLICY_ERROR_ID_PREFIX = exports.PortalPolicyError = exports.PortalPasskeyPrfErrorReason = exports.PortalPasskeyPrfError = exports.isIdempotencyRejection = exports.isIdempotencyKeyReused = exports.PortalIdempotencyErrorId = exports.PortalIdempotencyError = exports.PortalCredentialErrorReason = exports.PortalCredentialError = exports.PortalAuthErrorReason = exports.PortalAuthError = exports.NoAddressError = exports.MpcSigningError = exports.MissingOptionError = exports.InvalidGatewayConfigError = exports.InvalidChainIdError = exports.InvalidApiKeyError = exports.HttpError = exports.CloudStorageReadError = void 0;
21
21
  var cloud_storage_read_error_1 = require("./cloud-storage-read-error");
22
22
  Object.defineProperty(exports, "CloudStorageReadError", { enumerable: true, get: function () { return __importDefault(cloud_storage_read_error_1).default; } });
23
23
  var http_error_1 = require("./http-error");
@@ -46,6 +46,9 @@ Object.defineProperty(exports, "PortalIdempotencyError", { enumerable: true, get
46
46
  Object.defineProperty(exports, "PortalIdempotencyErrorId", { enumerable: true, get: function () { return portal_idempotency_error_1.PortalIdempotencyErrorId; } });
47
47
  Object.defineProperty(exports, "isIdempotencyKeyReused", { enumerable: true, get: function () { return portal_idempotency_error_1.isIdempotencyKeyReused; } });
48
48
  Object.defineProperty(exports, "isIdempotencyRejection", { enumerable: true, get: function () { return portal_idempotency_error_1.isIdempotencyRejection; } });
49
+ var portal_passkey_prf_error_1 = require("./portal-passkey-prf-error");
50
+ Object.defineProperty(exports, "PortalPasskeyPrfError", { enumerable: true, get: function () { return __importDefault(portal_passkey_prf_error_1).default; } });
51
+ Object.defineProperty(exports, "PortalPasskeyPrfErrorReason", { enumerable: true, get: function () { return portal_passkey_prf_error_1.PortalPasskeyPrfErrorReason; } });
49
52
  var portal_policy_error_1 = require("./portal-policy-error");
50
53
  Object.defineProperty(exports, "PortalPolicyError", { enumerable: true, get: function () { return __importDefault(portal_policy_error_1).default; } });
51
54
  Object.defineProperty(exports, "POLICY_ERROR_ID_PREFIX", { enumerable: true, get: function () { return portal_policy_error_1.POLICY_ERROR_ID_PREFIX; } });
@@ -14,8 +14,9 @@ exports.PortalAuthErrorReason = void 0;
14
14
  var PortalAuthErrorReason;
15
15
  (function (PortalAuthErrorReason) {
16
16
  /**
17
- * The backend refused to exchange the grant. Whatever the cause, the grant
18
- * is spent and cannot be retried: start a new sign-in.
17
+ * The backend refused the grant: it has expired, was already used, or is
18
+ * otherwise unusable. Whatever the cause, it cannot be retried: start a new
19
+ * sign-in.
19
20
  */
20
21
  PortalAuthErrorReason["GrantRejected"] = "GRANT_REJECTED";
21
22
  /**
@@ -23,10 +24,17 @@ var PortalAuthErrorReason;
23
24
  * grant. The user never completed the provider's flow.
24
25
  */
25
26
  PortalAuthErrorReason["ProviderRejected"] = "PROVIDER_REJECTED";
27
+ /**
28
+ * An OAuth redirect arrived that this SDK holds no pending sign-in for: it
29
+ * never started one on this device, or the one it started has expired.
30
+ * Nothing was sent to the backend. Start a new sign-in.
31
+ */
32
+ PortalAuthErrorReason["OAuthFlowNotStarted"] = "OAUTH_FLOW_NOT_STARTED";
26
33
  })(PortalAuthErrorReason = exports.PortalAuthErrorReason || (exports.PortalAuthErrorReason = {}));
27
34
  const authErrors = {
28
35
  [PortalAuthErrorReason.GrantRejected]: '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.',
29
36
  [PortalAuthErrorReason.ProviderRejected]: 'The authentication provider rejected the sign-in.',
37
+ [PortalAuthErrorReason.OAuthFlowNotStarted]: 'The sign-in could not be completed. Start a new sign-in.',
30
38
  };
31
39
  /**
32
40
  * Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.PortalPasskeyPrfErrorReason = void 0;
5
+ /** Why a passkey PRF backup could not be enrolled, read or decrypted. */
6
+ var PortalPasskeyPrfErrorReason;
7
+ (function (PortalPasskeyPrfErrorReason) {
8
+ /** The passkey ceremony failed before a secret was derived, for a reason other than the two below. */
9
+ PortalPasskeyPrfErrorReason["CeremonyFailed"] = "PRF_CEREMONY_FAILED";
10
+ /** The user dismissed the passkey prompt. */
11
+ PortalPasskeyPrfErrorReason["UserCancelled"] = "PRF_USER_CANCELLED";
12
+ /** The platform reported that it has no passkey to offer for this request. */
13
+ PortalPasskeyPrfErrorReason["PasskeyUnavailable"] = "PRF_PASSKEY_UNAVAILABLE";
14
+ /** No passkey has been enrolled for this client, so there is nothing to recover with. */
15
+ PortalPasskeyPrfErrorReason["CredentialNotFound"] = "PRF_CREDENTIAL_NOT_FOUND";
16
+ /** The backup could not be decrypted with the secret the passkey produced. */
17
+ PortalPasskeyPrfErrorReason["DecryptFailed"] = "PRF_DECRYPT_FAILED";
18
+ /** The device or passkey provider cannot evaluate the WebAuthn PRF extension. */
19
+ PortalPasskeyPrfErrorReason["NotSupported"] = "PRF_NOT_SUPPORTED";
20
+ /** The passkey was enrolled under a different relying party than the one configured. */
21
+ PortalPasskeyPrfErrorReason["RpIdMismatch"] = "PRF_RP_ID_MISMATCH";
22
+ })(PortalPasskeyPrfErrorReason = exports.PortalPasskeyPrfErrorReason || (exports.PortalPasskeyPrfErrorReason = {}));
23
+ const passkeyPrfErrors = {
24
+ [PortalPasskeyPrfErrorReason.CeremonyFailed]: 'The passkey request could not be completed.',
25
+ [PortalPasskeyPrfErrorReason.UserCancelled]: 'The passkey request was cancelled.',
26
+ [PortalPasskeyPrfErrorReason.PasskeyUnavailable]: 'The enrolled passkey is not available on this device.',
27
+ [PortalPasskeyPrfErrorReason.CredentialNotFound]: 'No passkey has been enrolled for this backup method.',
28
+ [PortalPasskeyPrfErrorReason.DecryptFailed]: 'The backup could not be decrypted with the secret from this passkey (wrong passkey or wrong ciphertext).',
29
+ [PortalPasskeyPrfErrorReason.NotSupported]: 'This device or passkey provider does not support the WebAuthn PRF extension.',
30
+ [PortalPasskeyPrfErrorReason.RpIdMismatch]: 'The passkey was enrolled under a different relying party.',
31
+ };
32
+ /**
33
+ * Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
34
+ * when a consumer's tree resolves two `@portal-hq/utils` — a dismissed prompt
35
+ * would then be reported as an unexpected MPC failure.
36
+ *
37
+ * This key and the members {@link PortalPasskeyPrfError.is} implies are a
38
+ * compatibility contract: changing either breaks recognition between copies.
39
+ */
40
+ const BRAND = Symbol.for('@portal-hq/utils/PortalPasskeyPrfError');
41
+ /**
42
+ * The single error every passkey PRF backup failure is normalized to; branch
43
+ * on `reason`.
44
+ */
45
+ class PortalPasskeyPrfError extends Error {
46
+ constructor({ reason, cause, context }) {
47
+ super(`[Portal] ${passkeyPrfErrors[reason]}${context ? ` ${context}` : ''}`);
48
+ /** @internal Cross-copy brand. Read it through {@link PortalPasskeyPrfError.is}. */
49
+ this[_a] = true;
50
+ Object.setPrototypeOf(this, PortalPasskeyPrfError.prototype);
51
+ this.reason = reason;
52
+ this.cause = cause;
53
+ }
54
+ /**
55
+ * Brand check — see BRAND. Narrowing a branded error from another copy to
56
+ * this class is intentional.
57
+ */
58
+ static is(error) {
59
+ return (typeof error === 'object' &&
60
+ error !== null &&
61
+ error[BRAND] === true);
62
+ }
63
+ /** True when the user chose not to continue, rather than something failing. */
64
+ get isUserCancelled() {
65
+ return this.reason === PortalPasskeyPrfErrorReason.UserCancelled;
66
+ }
67
+ }
68
+ _a = BRAND;
69
+ exports.default = PortalPasskeyPrfError;
@@ -118,5 +118,39 @@ var Events;
118
118
  Events["YieldXyzPerpsGetEvent"] = "YieldXyz Perps Get Event";
119
119
  Events["YieldXyzPerpsGetHealth"] = "YieldXyz Perps Get Health";
120
120
  Events["YieldXyzPerpsGetProvidersHealth"] = "YieldXyz Perps Get Providers Health";
121
+ Events["AggCreateLinkChallenge"] = "Agg Create Link Challenge";
122
+ Events["AggCreateLink"] = "Agg Create Link";
123
+ Events["AggGetLink"] = "Agg Get Link";
124
+ Events["AggDeleteLink"] = "Agg Delete Link";
125
+ Events["AggListEvents"] = "Agg List Events";
126
+ Events["AggGetEvent"] = "Agg Get Event";
127
+ Events["AggGetEventBootstrap"] = "Agg Get Event Bootstrap";
128
+ Events["AggListMarkets"] = "Agg List Markets";
129
+ Events["AggSearch"] = "Agg Search";
130
+ Events["AggListCategories"] = "Agg List Categories";
131
+ Events["AggGetVenueGeoPolicy"] = "Agg Get Venue Geo Policy";
132
+ Events["AggGetAppConfig"] = "Agg Get App Config";
133
+ Events["AggGetMidpoints"] = "Agg Get Midpoints";
134
+ Events["AggGetOrderbooks"] = "Agg Get Orderbooks";
135
+ Events["AggGetOutcomeOrderbook"] = "Agg Get Outcome Orderbook";
136
+ Events["AggGetChartBars"] = "Agg Get Chart Bars";
137
+ Events["AggGetChartHistoryManifest"] = "Agg Get Chart History Manifest";
138
+ Events["AggGetUser"] = "Agg Get User";
139
+ Events["AggGetDepositAddresses"] = "Agg Get Deposit Addresses";
140
+ Events["AggGetBalances"] = "Agg Get Balances";
141
+ Events["AggListPositions"] = "Agg List Positions";
142
+ Events["AggListOrders"] = "Agg List Orders";
143
+ Events["AggListActivity"] = "Agg List Activity";
144
+ Events["AggCreateQuote"] = "Agg Create Quote";
145
+ Events["AggCreateOrder"] = "Agg Create Order";
146
+ Events["AggGetOrder"] = "Agg Get Order";
147
+ Events["AggCreateLimitOrder"] = "Agg Create Limit Order";
148
+ Events["AggCreateDirectOrder"] = "Agg Create Direct Order";
149
+ Events["AggCancelOrder"] = "Agg Cancel Order";
150
+ Events["AggRedeemPositions"] = "Agg Redeem Positions";
151
+ Events["AggQuoteWithdrawable"] = "Agg Quote Withdrawable";
152
+ Events["AggPreviewWithdrawal"] = "Agg Preview Withdrawal";
153
+ Events["AggCreateWithdrawal"] = "Agg Create Withdrawal";
154
+ Events["AggGetWithdrawal"] = "Agg Get Withdrawal";
121
155
  })(Events || (Events = {}));
122
156
  exports.default = Events;
@@ -2,10 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const errors_1 = require("../errors");
4
4
  class HttpRequest {
5
- constructor({ body = {}, headers = {}, method, url }) {
5
+ constructor({ body = {}, headers = {}, method, rejectTransportFailures = false, url, }) {
6
6
  this.body = body;
7
7
  this.headers = headers;
8
8
  this.method = method;
9
+ this.rejectTransportFailures = rejectTransportFailures;
9
10
  this.url = url;
10
11
  this.request = new XMLHttpRequest();
11
12
  this.request.open(this.method, this.url, true);
@@ -22,11 +23,18 @@ class HttpRequest {
22
23
  else {
23
24
  this.request.send();
24
25
  }
26
+ if (this.rejectTransportFailures) {
27
+ this.request.onerror = () => reject(this.buildTransportError());
28
+ this.request.ontimeout = () => reject(this.buildTransportError());
29
+ }
25
30
  // Adds an event listener for when the request state changes
26
31
  this.request.onreadystatechange = () => {
27
32
  if (this.request.readyState === 4) {
28
33
  // readyState 4 means the request has completed
29
- if (this.request.status >= 300) {
34
+ if (this.rejectTransportFailures && this.request.status === 0) {
35
+ reject(this.buildTransportError());
36
+ }
37
+ else if (this.request.status >= 300) {
30
38
  // If we didn't get an 'OK' status, error out
31
39
  reject(new errors_1.HttpError({
32
40
  message: this.request.responseText,
@@ -42,6 +50,13 @@ class HttpRequest {
42
50
  };
43
51
  });
44
52
  }
53
+ buildTransportError() {
54
+ return new errors_1.HttpError({
55
+ message: `Network request to ${this.url} failed`,
56
+ status: 0,
57
+ statusText: 'Network Error',
58
+ });
59
+ }
45
60
  buildResponse() {
46
61
  // If the response is empty, just return an empty object
47
62
  if (this.request.status === 204) {
@@ -3,8 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.PortalMpcError = exports.PortalErrorCodeTypes = exports.PortalErrorCodes = exports.MPC_AUTH_FAILED_ERROR_ID = exports.PortalCredentialErrorReason = exports.PortalCredentialError = exports.PortalAuthErrorReason = exports.PortalAuthError = exports.NoAddressError = exports.MpcSigningError = exports.MissingOptionError = exports.InvalidGatewayConfigError = exports.InvalidChainIdError = exports.InvalidApiKeyError = exports.HttpError = exports.CloudStorageReadError = exports.Storage = exports.PortalRequestMethod = exports.PasswordStorage = exports.MpcStatuses = exports.KeychainAdapter = exports.convert = exports.convertCryptoToLocal = exports.convertLocalToCrypto = exports.staticApiKeyOf = exports.resolveCredentialToken = exports.resolveCredentials = exports.reportUnauthorized = exports.onCredentialsInvalidated = exports.invalidateCredentials = exports.failFromMpcError = exports.StaticCredentials = exports.DEFAULT_HOSTS = exports.buildDefaultGatewayConfig = exports.NAMESPACE_TO_CURVE = exports.ALL_CHAIN_IDS = exports.BITCOIN_CHAIN_IDS = exports.TRON_CHAIN_IDS = exports.SOLANA_CHAIN_IDS = exports.EVM_CHAIN_IDS = exports.DEFAULT_CHAIN_ID_CAIP2 = exports.DEFAULT_CHAIN_ID_NUMERIC = exports.CAIP2_CHAIN_ID_REGEX = exports.FRIENDLY_CHAIN_NAME_TO_CAIP2 = exports.SUPPORTED_BITCOIN_P2WPKH_CHAINS = exports.CHAIN_NAMESPACES = exports.getChainNameForId = exports.getChainIdForName = exports.chainNameToId = exports.chainIdToName = void 0;
7
- exports.sdkLogger = exports.UUID_V4_REGEX = exports.TRACE_ID_HEADER = exports.createExecutionContext = exports.generateTraceId = exports.EvaluateTransactionOperationType = exports.HttpRequester = exports.PortalRequests = exports.HttpRequest = exports.parseRequest = exports.numberToHexString = exports.getClientPlatformVersion = exports.Events = exports.validateIdempotencyKey = exports.PORTAL_IDEMPOTENCY_KEY_HEADER = exports.generateIdempotencyKey = exports.RpcErrorCodes = exports.ProviderRpcError = exports.mpcErrorFrom = exports.isPolicyViolation = exports.isMpcAuthFailure = exports.PolicyErrorId = exports.POLICY_ERROR_ID_PREFIX = exports.PortalPolicyError = exports.isIdempotencyRejection = exports.isIdempotencyKeyReused = exports.PortalIdempotencyErrorId = exports.PortalIdempotencyError = void 0;
6
+ exports.PortalErrorCodes = exports.MPC_AUTH_FAILED_ERROR_ID = exports.PortalCredentialErrorReason = exports.PortalCredentialError = exports.PortalAuthErrorReason = exports.PortalAuthError = exports.PortalPasskeyPrfErrorReason = exports.PortalPasskeyPrfError = exports.NoAddressError = exports.MpcSigningError = exports.MissingOptionError = exports.InvalidGatewayConfigError = exports.InvalidChainIdError = exports.InvalidApiKeyError = exports.HttpError = exports.CloudStorageReadError = exports.Storage = exports.PortalRequestMethod = exports.PasswordStorage = exports.MpcStatuses = exports.KeychainAdapter = exports.convert = exports.convertCryptoToLocal = exports.convertLocalToCrypto = exports.staticApiKeyOf = exports.resolveCredentialToken = exports.resolveCredentials = exports.reportUnauthorized = exports.onCredentialsInvalidated = exports.invalidateCredentials = exports.failFromMpcError = exports.StaticCredentials = exports.DEFAULT_HOSTS = exports.buildDefaultGatewayConfig = exports.NAMESPACE_TO_CURVE = exports.ALL_CHAIN_IDS = exports.BITCOIN_CHAIN_IDS = exports.TRON_CHAIN_IDS = exports.SOLANA_CHAIN_IDS = exports.EVM_CHAIN_IDS = exports.DEFAULT_CHAIN_ID_CAIP2 = exports.DEFAULT_CHAIN_ID_NUMERIC = exports.CAIP2_CHAIN_ID_REGEX = exports.FRIENDLY_CHAIN_NAME_TO_CAIP2 = exports.SUPPORTED_BITCOIN_P2WPKH_CHAINS = exports.CHAIN_NAMESPACES = exports.getChainNameForId = exports.getChainIdForName = exports.chainNameToId = exports.chainIdToName = void 0;
7
+ exports.sdkLogger = exports.UUID_V4_REGEX = exports.TRACE_ID_HEADER = exports.createExecutionContext = exports.generateTraceId = exports.EvaluateTransactionOperationType = exports.HttpRequester = exports.PortalRequests = exports.HttpRequest = exports.parseRequest = exports.numberToHexString = exports.getClientPlatformVersion = exports.Events = exports.validateIdempotencyKey = exports.PORTAL_IDEMPOTENCY_KEY_HEADER = exports.generateIdempotencyKey = exports.RpcErrorCodes = exports.ProviderRpcError = exports.mpcErrorFrom = exports.isPolicyViolation = exports.isMpcAuthFailure = exports.PolicyErrorId = exports.POLICY_ERROR_ID_PREFIX = exports.PortalPolicyError = exports.isIdempotencyRejection = exports.isIdempotencyKeyReused = exports.PortalIdempotencyErrorId = exports.PortalIdempotencyError = exports.PortalMpcError = exports.PortalErrorCodeTypes = void 0;
8
8
  var chains_1 = require("./chains");
9
9
  Object.defineProperty(exports, "chainIdToName", { enumerable: true, get: function () { return chains_1.chainIdToName; } });
10
10
  Object.defineProperty(exports, "chainNameToId", { enumerable: true, get: function () { return chains_1.chainNameToId; } });
@@ -53,6 +53,8 @@ Object.defineProperty(exports, "InvalidGatewayConfigError", { enumerable: true,
53
53
  Object.defineProperty(exports, "MissingOptionError", { enumerable: true, get: function () { return errors_1.MissingOptionError; } });
54
54
  Object.defineProperty(exports, "MpcSigningError", { enumerable: true, get: function () { return errors_1.MpcSigningError; } });
55
55
  Object.defineProperty(exports, "NoAddressError", { enumerable: true, get: function () { return errors_1.NoAddressError; } });
56
+ Object.defineProperty(exports, "PortalPasskeyPrfError", { enumerable: true, get: function () { return errors_1.PortalPasskeyPrfError; } });
57
+ Object.defineProperty(exports, "PortalPasskeyPrfErrorReason", { enumerable: true, get: function () { return errors_1.PortalPasskeyPrfErrorReason; } });
56
58
  Object.defineProperty(exports, "PortalAuthError", { enumerable: true, get: function () { return errors_1.PortalAuthError; } });
57
59
  Object.defineProperty(exports, "PortalAuthErrorReason", { enumerable: true, get: function () { return errors_1.PortalAuthErrorReason; } });
58
60
  Object.defineProperty(exports, "PortalCredentialError", { enumerable: true, get: function () { return errors_1.PortalCredentialError; } });
@@ -22,10 +22,12 @@ class HttpRequester {
22
22
  * the hook's own failure is swallowed and the original `HttpError` is always
23
23
  * what the caller sees.
24
24
  */
25
- send(requestOptions) {
25
+ send(requestOptions, options) {
26
26
  return __awaiter(this, void 0, void 0, function* () {
27
27
  try {
28
- return (yield new index_1.HttpRequest(requestOptions).send());
28
+ const sentOptions = (options === null || options === void 0 ? void 0 : options.rejectTransportFailures)
29
+ ? Object.assign(Object.assign({}, requestOptions), { rejectTransportFailures: true }) : requestOptions;
30
+ return (yield new index_1.HttpRequest(sentOptions).send());
29
31
  }
30
32
  catch (error) {
31
33
  if (this.onUnauthorized &&
@@ -53,7 +55,7 @@ class HttpRequester {
53
55
  url: `${this.baseUrl}${path}`,
54
56
  };
55
57
  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);
56
- return this.send(requestOptions);
58
+ return this.send(requestOptions, options);
57
59
  });
58
60
  }
59
61
  get(path, options) {
@@ -64,7 +66,7 @@ class HttpRequester {
64
66
  url: `${this.baseUrl}${path}`,
65
67
  };
66
68
  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);
67
- return this.send(requestOptions);
69
+ return this.send(requestOptions, options);
68
70
  });
69
71
  }
70
72
  post(path, options) {
@@ -78,7 +80,7 @@ class HttpRequester {
78
80
  if (options === null || options === void 0 ? void 0 : options.body) {
79
81
  requestOptions.body = options.body;
80
82
  }
81
- return this.send(requestOptions);
83
+ return this.send(requestOptions, options);
82
84
  });
83
85
  }
84
86
  put(path, options) {
@@ -92,7 +94,7 @@ class HttpRequester {
92
94
  if (options === null || options === void 0 ? void 0 : options.body) {
93
95
  requestOptions.body = options.body;
94
96
  }
95
- return this.send(requestOptions);
97
+ return this.send(requestOptions, options);
96
98
  });
97
99
  }
98
100
  patch(path, options) {
@@ -106,7 +108,7 @@ class HttpRequester {
106
108
  if (options === null || options === void 0 ? void 0 : options.body) {
107
109
  requestOptions.body = options.body;
108
110
  }
109
- return this.send(requestOptions);
111
+ return this.send(requestOptions, options);
110
112
  });
111
113
  }
112
114
  }
@@ -1 +1 @@
1
- { "version": "5.2.0" }
1
+ { "version": "6.0.0" }
@@ -2,7 +2,6 @@ export const DEFAULT_HOSTS = {
2
2
  API: 'api.portalhq.io',
3
3
  MPC: 'mpc.portalhq.io',
4
4
  ENCLAVE_MPC: 'mpc-client.portalhq.io',
5
- WEBSOCKET: 'connect.portalhq.io',
6
5
  };
7
6
  /**
8
7
  * Canonical list of chains covered by the default gateway config. Single
@@ -178,7 +178,13 @@ export class Storage {
178
178
  read() {
179
179
  throw new Error('[Portal] Storage method read cannot be called directly. Please extend Storage.');
180
180
  }
181
- write(privateKey) {
181
+ /**
182
+ * `options` carries the pair ids of the backup that produced the key, so
183
+ * storage can keep keys of different backups apart. Implementations may
184
+ * ignore it.
185
+ */
186
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
187
+ write(privateKey, _options) {
182
188
  throw new Error(`[Portal] Storage method write(${privateKey}) cannot be called directly. Please extend Storage.`);
183
189
  }
184
190
  validateOperations() {
@@ -10,5 +10,6 @@ export { default as PortalAuthError, PortalAuthErrorReason, } from './portal-aut
10
10
  export { default as PortalCredentialError, PortalCredentialErrorReason, } from './portal-credential-error';
11
11
  export * from './portal-error';
12
12
  export { default as PortalIdempotencyError, PortalIdempotencyErrorId, isIdempotencyKeyReused, isIdempotencyRejection, } from './portal-idempotency-error';
13
+ export { default as PortalPasskeyPrfError, PortalPasskeyPrfErrorReason, } from './portal-passkey-prf-error';
13
14
  export { default as PortalPolicyError, POLICY_ERROR_ID_PREFIX, PolicyErrorId, isPolicyViolation, mpcErrorFrom, } from './portal-policy-error';
14
15
  export { default as ProviderRpcError, RpcErrorCodes, } from './provider-rpc-error';
@@ -11,8 +11,9 @@ var _a;
11
11
  export var PortalAuthErrorReason;
12
12
  (function (PortalAuthErrorReason) {
13
13
  /**
14
- * The backend refused to exchange the grant. Whatever the cause, the grant
15
- * is spent and cannot be retried: start a new sign-in.
14
+ * The backend refused the grant: it has expired, was already used, or is
15
+ * otherwise unusable. Whatever the cause, it cannot be retried: start a new
16
+ * sign-in.
16
17
  */
17
18
  PortalAuthErrorReason["GrantRejected"] = "GRANT_REJECTED";
18
19
  /**
@@ -20,10 +21,17 @@ export var PortalAuthErrorReason;
20
21
  * grant. The user never completed the provider's flow.
21
22
  */
22
23
  PortalAuthErrorReason["ProviderRejected"] = "PROVIDER_REJECTED";
24
+ /**
25
+ * An OAuth redirect arrived that this SDK holds no pending sign-in for: it
26
+ * never started one on this device, or the one it started has expired.
27
+ * Nothing was sent to the backend. Start a new sign-in.
28
+ */
29
+ PortalAuthErrorReason["OAuthFlowNotStarted"] = "OAUTH_FLOW_NOT_STARTED";
23
30
  })(PortalAuthErrorReason || (PortalAuthErrorReason = {}));
24
31
  const authErrors = {
25
32
  [PortalAuthErrorReason.GrantRejected]: '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]: 'The authentication provider rejected the sign-in.',
34
+ [PortalAuthErrorReason.OAuthFlowNotStarted]: 'The sign-in could not be completed. Start a new sign-in.',
27
35
  };
28
36
  /**
29
37
  * Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
@@ -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;
@@ -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 >= 300) {
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) {
package/lib/esm/index.js CHANGED
@@ -3,7 +3,7 @@ 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, PortalIdempotencyError, PortalIdempotencyErrorId, isIdempotencyKeyReused, isIdempotencyRejection, 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
7
  export { generateIdempotencyKey, PORTAL_IDEMPOTENCY_KEY_HEADER, validateIdempotencyKey, } from './idempotency';
8
8
  export { default as Events } from './events';
9
9
  export { getClientPlatformVersion } from './version';
@@ -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
- return (yield new HttpRequest(requestOptions).send());
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": "5.2.0" }
1
+ { "version": "6.0.0" }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@portal-hq/utils",
3
- "version": "5.2.0",
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.18.6",
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.0.3",
26
+ "ts-jest": "^29.4.15",
27
27
  "typescript": "^4.8.4"
28
28
  },
29
- "gitHead": "a14b1c60fd0d4cb72839dc6ed81f6c9f251dd980"
29
+ "gitHead": "46892641739410fe8a216890ee906ec1d4f22ca2"
30
30
  }
@@ -2,7 +2,6 @@ export const DEFAULT_HOSTS = {
2
2
  API: 'api.portalhq.io',
3
3
  MPC: 'mpc.portalhq.io',
4
4
  ENCLAVE_MPC: 'mpc-client.portalhq.io',
5
- WEBSOCKET: 'connect.portalhq.io',
6
5
  } as const
7
6
 
8
7
  /**
@@ -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
 
@@ -286,6 +286,11 @@ export interface PortalCredentials {
286
286
  invalidate(): Promise<void>
287
287
  }
288
288
 
289
+ export interface GetClientOptions {
290
+ /** Rejects a network failure instead of resolving it as a missing client. */
291
+ rejectTransportFailures?: boolean
292
+ }
293
+
289
294
  export interface IPortalApi {
290
295
  /**
291
296
  * @deprecated Read the credential through `getToken()` instead.
@@ -312,8 +317,16 @@ export interface IPortalApi {
312
317
  ): Promise<GenerateApiResponse>
313
318
  getBackupSharesMetadata(chainId?: string): Promise<BackupSharePairMetadata[]>
314
319
  getBalances(chainId?: string, traceId?: string): Promise<Balance[]>
315
- getClient(traceId?: string): Promise<ClientResponse>
320
+ getClient(
321
+ traceId?: string,
322
+ options?: GetClientOptions,
323
+ ): Promise<ClientResponse>
316
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>
317
330
  getEnabledDapps(): Promise<Dapp[]>
318
331
  getNFTs(chainId?: string, traceId?: string): Promise<NFT[]>
319
332
  getNftAssets(chainId: string, traceId?: string): Promise<NFTAsset[]>
@@ -360,6 +373,7 @@ export interface IPortalApi {
360
373
  | 'GDRIVE'
361
374
  | 'ICLOUD'
362
375
  | 'PASSKEY'
376
+ | 'PASSKEY_PRF'
363
377
  | 'PASSWORD'
364
378
  | 'FIREBASE'
365
379
  | 'UNKNOWN',
@@ -372,6 +386,7 @@ export interface IPortalApi {
372
386
  | 'ICLOUD'
373
387
  | 'FIREBASE'
374
388
  | 'PASSKEY'
389
+ | 'PASSKEY_PRF'
375
390
  | 'PASSWORD'
376
391
  | 'UNKNOWN',
377
392
  ): Promise<void>
@@ -425,18 +440,6 @@ export interface IPortalApi {
425
440
  ): Promise<string>
426
441
  }
427
442
 
428
- export interface IPortalConnect {
429
- connected: boolean
430
- connect(uri: string): Promise<void>
431
- deinit(): void
432
- disconnect(): void
433
- emit(event: string, data: any): PortalConnect
434
- on(event: string, callback: EventHandler): PortalConnect
435
- once(event: string, callback: EventHandler): PortalConnect
436
- removeEventListener(event: string, listenerToRemove?: EventHandler): void
437
- setChainId(chainId: number): Promise<void>
438
- }
439
-
440
443
  export interface IPortalProvider {
441
444
  /**
442
445
  * @deprecated Read the credential through `credentials.getToken()` instead.
@@ -459,10 +462,7 @@ export interface IPortalProvider {
459
462
  once(event: string, callback: EventHandler): IPortalProvider
460
463
  removeEventListener(event: string, listenerToRemove?: EventHandler): void
461
464
  request(args: RequestArguments): Promise<any>
462
- setChainId(
463
- chainId: string | number,
464
- connect?: PortalConnect | undefined,
465
- ): Promise<IPortalProvider>
465
+ setChainId(chainId: string | number): Promise<IPortalProvider>
466
466
  }
467
467
 
468
468
  export abstract class KeychainAdapter {
@@ -589,9 +589,41 @@ export enum MpcStatuses {
589
589
  StoringShare = 'Storing share',
590
590
  }
591
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
+
592
600
  export abstract class Storage {
593
601
  public api?: IPortalApi
594
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
+
595
627
  delete(): Promise<boolean> {
596
628
  throw new Error(
597
629
  '[Portal] Storage method delete cannot be called directly. Please extend Storage.',
@@ -604,7 +636,13 @@ export abstract class Storage {
604
636
  )
605
637
  }
606
638
 
607
- write(privateKey: string): Promise<string> {
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> {
608
646
  throw new Error(
609
647
  `[Portal] Storage method write(${privateKey}) cannot be called directly. Please extend Storage.`,
610
648
  )
@@ -617,6 +655,15 @@ export abstract class Storage {
617
655
  }
618
656
  }
619
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
+
620
667
  export class PasswordStorage implements Storage {
621
668
  public api?: IPortalApi
622
669
 
@@ -648,6 +695,7 @@ export class PasswordStorage implements Storage {
648
695
  export type BackupMethod =
649
696
  | 'PASSWORD'
650
697
  | 'PASSKEY'
698
+ | 'PASSKEY_PRF'
651
699
  | 'GDRIVE'
652
700
  | 'ICLOUD'
653
701
  | 'CUSTOM'
@@ -24,6 +24,11 @@ export {
24
24
  isIdempotencyKeyReused,
25
25
  isIdempotencyRejection,
26
26
  } from './portal-idempotency-error'
27
+ export {
28
+ default as PortalPasskeyPrfError,
29
+ PortalPasskeyPrfErrorReason,
30
+ type PortalPasskeyPrfErrorOptions,
31
+ } from './portal-passkey-prf-error'
27
32
  export {
28
33
  default as PortalPolicyError,
29
34
  POLICY_ERROR_ID_PREFIX,
@@ -9,8 +9,9 @@
9
9
  */
10
10
  export enum PortalAuthErrorReason {
11
11
  /**
12
- * The backend refused to exchange the grant. Whatever the cause, the grant
13
- * is spent and cannot be retried: start a new sign-in.
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 {
@@ -0,0 +1,97 @@
1
+ /** Why a passkey PRF backup could not be enrolled, read or decrypted. */
2
+ export enum PortalPasskeyPrfErrorReason {
3
+ /** The passkey ceremony failed before a secret was derived, for a reason other than the two below. */
4
+ CeremonyFailed = 'PRF_CEREMONY_FAILED',
5
+ /** The user dismissed the passkey prompt. */
6
+ UserCancelled = 'PRF_USER_CANCELLED',
7
+ /** The platform reported that it has no passkey to offer for this request. */
8
+ PasskeyUnavailable = 'PRF_PASSKEY_UNAVAILABLE',
9
+ /** No passkey has been enrolled for this client, so there is nothing to recover with. */
10
+ CredentialNotFound = 'PRF_CREDENTIAL_NOT_FOUND',
11
+ /** The backup could not be decrypted with the secret the passkey produced. */
12
+ DecryptFailed = 'PRF_DECRYPT_FAILED',
13
+ /** The device or passkey provider cannot evaluate the WebAuthn PRF extension. */
14
+ NotSupported = 'PRF_NOT_SUPPORTED',
15
+ /** The passkey was enrolled under a different relying party than the one configured. */
16
+ RpIdMismatch = 'PRF_RP_ID_MISMATCH',
17
+ }
18
+
19
+ const passkeyPrfErrors: Record<PortalPasskeyPrfErrorReason, string> = {
20
+ [PortalPasskeyPrfErrorReason.CeremonyFailed]:
21
+ 'The passkey request could not be completed.',
22
+ [PortalPasskeyPrfErrorReason.UserCancelled]:
23
+ 'The passkey request was cancelled.',
24
+ [PortalPasskeyPrfErrorReason.PasskeyUnavailable]:
25
+ 'The enrolled passkey is not available on this device.',
26
+ [PortalPasskeyPrfErrorReason.CredentialNotFound]:
27
+ 'No passkey has been enrolled for this backup method.',
28
+ [PortalPasskeyPrfErrorReason.DecryptFailed]:
29
+ 'The backup could not be decrypted with the secret from this passkey (wrong passkey or wrong ciphertext).',
30
+ [PortalPasskeyPrfErrorReason.NotSupported]:
31
+ 'This device or passkey provider does not support the WebAuthn PRF extension.',
32
+ [PortalPasskeyPrfErrorReason.RpIdMismatch]:
33
+ 'The passkey was enrolled under a different relying party.',
34
+ }
35
+
36
+ export interface PortalPasskeyPrfErrorOptions {
37
+ reason: PortalPasskeyPrfErrorReason
38
+ /**
39
+ * The underlying failure, preserved for debugging. Deliberately kept off the
40
+ * message so platform internals are not surfaced to callers.
41
+ */
42
+ cause?: unknown
43
+ /** Extra detail appended to the message, for example the two relying party IDs. */
44
+ context?: string
45
+ }
46
+
47
+ /**
48
+ * Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
49
+ * when a consumer's tree resolves two `@portal-hq/utils` — a dismissed prompt
50
+ * would then be reported as an unexpected MPC failure.
51
+ *
52
+ * This key and the members {@link PortalPasskeyPrfError.is} implies are a
53
+ * compatibility contract: changing either breaks recognition between copies.
54
+ */
55
+ const BRAND: unique symbol = Symbol.for(
56
+ '@portal-hq/utils/PortalPasskeyPrfError',
57
+ )
58
+
59
+ /**
60
+ * The single error every passkey PRF backup failure is normalized to; branch
61
+ * on `reason`.
62
+ */
63
+ class PortalPasskeyPrfError extends Error {
64
+ public readonly reason: PortalPasskeyPrfErrorReason
65
+ public readonly cause?: unknown
66
+
67
+ /** @internal Cross-copy brand. Read it through {@link PortalPasskeyPrfError.is}. */
68
+ public readonly [BRAND] = true
69
+
70
+ constructor({ reason, cause, context }: PortalPasskeyPrfErrorOptions) {
71
+ super(`[Portal] ${passkeyPrfErrors[reason]}${context ? ` ${context}` : ''}`)
72
+
73
+ Object.setPrototypeOf(this, PortalPasskeyPrfError.prototype)
74
+
75
+ this.reason = reason
76
+ this.cause = cause
77
+ }
78
+
79
+ /**
80
+ * Brand check — see BRAND. Narrowing a branded error from another copy to
81
+ * this class is intentional.
82
+ */
83
+ public static is(error: unknown): error is PortalPasskeyPrfError {
84
+ return (
85
+ typeof error === 'object' &&
86
+ error !== null &&
87
+ (error as { [BRAND]?: unknown })[BRAND] === true
88
+ )
89
+ }
90
+
91
+ /** True when the user chose not to continue, rather than something failing. */
92
+ public get isUserCancelled(): boolean {
93
+ return this.reason === PortalPasskeyPrfErrorReason.UserCancelled
94
+ }
95
+ }
96
+
97
+ export default PortalPasskeyPrfError
@@ -125,6 +125,41 @@ enum Events {
125
125
  YieldXyzPerpsGetEvent = 'YieldXyz Perps Get Event',
126
126
  YieldXyzPerpsGetHealth = 'YieldXyz Perps Get Health',
127
127
  YieldXyzPerpsGetProvidersHealth = 'YieldXyz Perps Get Providers Health',
128
+
129
+ AggCreateLinkChallenge = 'Agg Create Link Challenge',
130
+ AggCreateLink = 'Agg Create Link',
131
+ AggGetLink = 'Agg Get Link',
132
+ AggDeleteLink = 'Agg Delete Link',
133
+ AggListEvents = 'Agg List Events',
134
+ AggGetEvent = 'Agg Get Event',
135
+ AggGetEventBootstrap = 'Agg Get Event Bootstrap',
136
+ AggListMarkets = 'Agg List Markets',
137
+ AggSearch = 'Agg Search',
138
+ AggListCategories = 'Agg List Categories',
139
+ AggGetVenueGeoPolicy = 'Agg Get Venue Geo Policy',
140
+ AggGetAppConfig = 'Agg Get App Config',
141
+ AggGetMidpoints = 'Agg Get Midpoints',
142
+ AggGetOrderbooks = 'Agg Get Orderbooks',
143
+ AggGetOutcomeOrderbook = 'Agg Get Outcome Orderbook',
144
+ AggGetChartBars = 'Agg Get Chart Bars',
145
+ AggGetChartHistoryManifest = 'Agg Get Chart History Manifest',
146
+ AggGetUser = 'Agg Get User',
147
+ AggGetDepositAddresses = 'Agg Get Deposit Addresses',
148
+ AggGetBalances = 'Agg Get Balances',
149
+ AggListPositions = 'Agg List Positions',
150
+ AggListOrders = 'Agg List Orders',
151
+ AggListActivity = 'Agg List Activity',
152
+ AggCreateQuote = 'Agg Create Quote',
153
+ AggCreateOrder = 'Agg Create Order',
154
+ AggGetOrder = 'Agg Get Order',
155
+ AggCreateLimitOrder = 'Agg Create Limit Order',
156
+ AggCreateDirectOrder = 'Agg Create Direct Order',
157
+ AggCancelOrder = 'Agg Cancel Order',
158
+ AggRedeemPositions = 'Agg Redeem Positions',
159
+ AggQuoteWithdrawable = 'Agg Quote Withdrawable',
160
+ AggPreviewWithdrawal = 'Agg Preview Withdrawal',
161
+ AggCreateWithdrawal = 'Agg Create Withdrawal',
162
+ AggGetWithdrawal = 'Agg Get Withdrawal',
128
163
  }
129
164
 
130
165
  export default Events
@@ -8,13 +8,21 @@ class HttpRequest {
8
8
  public body: Record<string, any>
9
9
  public headers: Record<string, any>
10
10
  public method: ValidHttpRequestMethods
11
+ public rejectTransportFailures: boolean
11
12
  public request: XMLHttpRequest
12
13
  public url: string
13
14
 
14
- constructor({ body = {}, headers = {}, method, url }: HttpRequestOptions) {
15
+ constructor({
16
+ body = {},
17
+ headers = {},
18
+ method,
19
+ rejectTransportFailures = false,
20
+ url,
21
+ }: HttpRequestOptions) {
15
22
  this.body = body
16
23
  this.headers = headers
17
24
  this.method = method
25
+ this.rejectTransportFailures = rejectTransportFailures
18
26
  this.url = url
19
27
 
20
28
  this.request = new XMLHttpRequest()
@@ -34,11 +42,18 @@ class HttpRequest {
34
42
  this.request.send()
35
43
  }
36
44
 
45
+ if (this.rejectTransportFailures) {
46
+ this.request.onerror = () => reject(this.buildTransportError())
47
+ this.request.ontimeout = () => reject(this.buildTransportError())
48
+ }
49
+
37
50
  // Adds an event listener for when the request state changes
38
51
  this.request.onreadystatechange = () => {
39
52
  if (this.request.readyState === 4) {
40
53
  // readyState 4 means the request has completed
41
- if (this.request.status >= 300) {
54
+ if (this.rejectTransportFailures && this.request.status === 0) {
55
+ reject(this.buildTransportError())
56
+ } else if (this.request.status >= 300) {
42
57
  // If we didn't get an 'OK' status, error out
43
58
  reject(
44
59
  new HttpError({
@@ -56,6 +71,14 @@ class HttpRequest {
56
71
  })
57
72
  }
58
73
 
74
+ private buildTransportError(): HttpError {
75
+ return new HttpError({
76
+ message: `Network request to ${this.url} failed`,
77
+ status: 0,
78
+ statusText: 'Network Error',
79
+ })
80
+ }
81
+
59
82
  private buildResponse<T>(): T {
60
83
  // If the response is empty, just return an empty object
61
84
  if (this.request.status === 204) {
package/src/index.ts CHANGED
@@ -36,8 +36,11 @@ export {
36
36
  export { convertLocalToCrypto, convertCryptoToLocal, convert } from './currency'
37
37
 
38
38
  export {
39
+ type BackupKeyMatcher,
40
+ type BackupKeyOptions,
41
+ type DerivedSecretStorage,
42
+ type GetClientOptions,
39
43
  type IPortalApi,
40
- type IPortalConnect,
41
44
  type IPortalProvider,
42
45
  KeychainAdapter,
43
46
  MpcStatuses,
@@ -60,6 +63,9 @@ export {
60
63
  MissingOptionError,
61
64
  MpcSigningError,
62
65
  NoAddressError,
66
+ PortalPasskeyPrfError,
67
+ PortalPasskeyPrfErrorReason,
68
+ type PortalPasskeyPrfErrorOptions,
63
69
  PortalAuthError,
64
70
  PortalAuthErrorReason,
65
71
  type PortalAuthErrorOptions,
@@ -22,9 +22,15 @@ class HttpRequester {
22
22
  * the hook's own failure is swallowed and the original `HttpError` is always
23
23
  * what the caller sees.
24
24
  */
25
- private async send<T>(requestOptions: HttpRequestOptions): Promise<T> {
25
+ private async send<T>(
26
+ requestOptions: HttpRequestOptions,
27
+ options?: HttpOptions,
28
+ ): Promise<T> {
26
29
  try {
27
- return (await new HttpRequest(requestOptions).send()) as T
30
+ const sentOptions = options?.rejectTransportFailures
31
+ ? { ...requestOptions, rejectTransportFailures: true }
32
+ : requestOptions
33
+ return (await new HttpRequest(sentOptions).send()) as T
28
34
  } catch (error) {
29
35
  if (
30
36
  this.onUnauthorized &&
@@ -64,7 +70,7 @@ class HttpRequester {
64
70
  options?.traceId,
65
71
  )
66
72
 
67
- return this.send<T>(requestOptions)
73
+ return this.send<T>(requestOptions, options)
68
74
  }
69
75
 
70
76
  public async get<T>(path: string, options?: HttpOptions): Promise<T> {
@@ -78,7 +84,7 @@ class HttpRequester {
78
84
  options?.traceId,
79
85
  )
80
86
 
81
- return this.send<T>(requestOptions)
87
+ return this.send<T>(requestOptions, options)
82
88
  }
83
89
 
84
90
  public async post<T>(path: string, options?: HttpOptions): Promise<T> {
@@ -96,7 +102,7 @@ class HttpRequester {
96
102
  requestOptions.body = options.body
97
103
  }
98
104
 
99
- return this.send<T>(requestOptions)
105
+ return this.send<T>(requestOptions, options)
100
106
  }
101
107
 
102
108
  public async put<T>(path: string, options: HttpOptions): Promise<T> {
@@ -114,7 +120,7 @@ class HttpRequester {
114
120
  requestOptions.body = options.body
115
121
  }
116
122
 
117
- return this.send<T>(requestOptions)
123
+ return this.send<T>(requestOptions, options)
118
124
  }
119
125
 
120
126
  public async patch<T>(path: string, options: HttpOptions): Promise<T> {
@@ -132,7 +138,7 @@ class HttpRequester {
132
138
  requestOptions.body = options.body
133
139
  }
134
140
 
135
- return this.send<T>(requestOptions)
141
+ return this.send<T>(requestOptions, options)
136
142
  }
137
143
  }
138
144
 
@@ -1 +1 @@
1
- { "version": "5.2.0" }
1
+ { "version": "6.0.0" }
package/types.d.ts CHANGED
@@ -241,6 +241,12 @@ export interface HttpErrorOptions {
241
241
  export interface HttpOptions {
242
242
  body?: Record<string, any>
243
243
  headers?: Record<string, any>
244
+ /**
245
+ * Rejects network errors, timeouts and status 0 responses instead of
246
+ * resolving them as empty successes. Opt-in so existing callers keep their
247
+ * behavior.
248
+ */
249
+ rejectTransportFailures?: boolean
244
250
  traceId?: string
245
251
  }
246
252
 
@@ -258,6 +264,7 @@ export interface HttpRequestOptions {
258
264
  body?: Record<string, any>
259
265
  headers?: Record<string, any>
260
266
  method: ValidHttpRequestMethods
267
+ rejectTransportFailures?: boolean
261
268
  url: string
262
269
  }
263
270
 
@@ -721,6 +728,38 @@ export interface OpenSeaMetadata {
721
728
 
722
729
  export interface BackupConfigs {
723
730
  passwordStorage?: PasswordStorageConfig
731
+ passkeyPrfStorage?: PasskeyPrfStorageConfig
732
+ }
733
+
734
+ /** Labels a passkey provider stores with a passkey and shows in its UI. */
735
+ export interface PasskeyPrfUser {
736
+ /** Account name the passkey provider stores alongside the passkey. */
737
+ name: string
738
+ /** Name shown to the user when they are asked to pick a passkey. */
739
+ displayName: string
740
+ }
741
+
742
+ /** Per-backup options for the passkey PRF backup method. */
743
+ export interface PasskeyPrfStorageConfig {
744
+ /**
745
+ * Labels for the passkey this backup creates. Used only when the client has
746
+ * no enrolled passkey yet: an enrolled passkey is reused, and its labels
747
+ * cannot be changed. Overrides the adapter's `user` option.
748
+ */
749
+ user?: PasskeyPrfUser
750
+ }
751
+
752
+ /**
753
+ * Identifies the passkey a client enrolled for the passkey PRF backup method.
754
+ * None of it is secret: the share-encryption secret is derived from the
755
+ * passkey on demand and is never stored.
756
+ */
757
+ export interface PasskeyPrfCredential {
758
+ /** Unpadded base64url WebAuthn credential ID. */
759
+ credentialId: string
760
+ /** Relying party the passkey is scoped to. Fixed once enrolled. */
761
+ rpId: string
762
+ transports?: string[]
724
763
  }
725
764
 
726
765
  export interface PasswordStorageConfig {