@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.
Files changed (38) hide show
  1. package/lib/commonjs/config/index.js +0 -1
  2. package/lib/commonjs/definitions/index.js +7 -1
  3. package/lib/commonjs/errors/index.js +9 -1
  4. package/lib/commonjs/errors/portal-auth-error.js +10 -2
  5. package/lib/commonjs/errors/portal-idempotency-error.js +74 -0
  6. package/lib/commonjs/errors/portal-passkey-prf-error.js +69 -0
  7. package/lib/commonjs/events/index.js +34 -0
  8. package/lib/commonjs/http-request/index.js +17 -2
  9. package/lib/commonjs/idempotency/index.js +74 -0
  10. package/lib/commonjs/index.js +12 -2
  11. package/lib/commonjs/requesters/http.js +9 -7
  12. package/lib/commonjs/version/version.json +1 -1
  13. package/lib/esm/config/index.js +0 -1
  14. package/lib/esm/definitions/index.js +7 -1
  15. package/lib/esm/errors/index.js +2 -0
  16. package/lib/esm/errors/portal-auth-error.js +10 -2
  17. package/lib/esm/errors/portal-idempotency-error.js +69 -0
  18. package/lib/esm/errors/portal-passkey-prf-error.js +66 -0
  19. package/lib/esm/events/index.js +34 -0
  20. package/lib/esm/http-request/index.js +17 -2
  21. package/lib/esm/idempotency/index.js +66 -0
  22. package/lib/esm/index.js +2 -1
  23. package/lib/esm/requesters/http.js +9 -7
  24. package/lib/esm/version/version.json +1 -1
  25. package/package.json +4 -4
  26. package/src/config/index.ts +0 -1
  27. package/src/definitions/index.ts +116 -20
  28. package/src/errors/index.ts +12 -0
  29. package/src/errors/portal-auth-error.ts +11 -2
  30. package/src/errors/portal-idempotency-error.ts +91 -0
  31. package/src/errors/portal-passkey-prf-error.ts +97 -0
  32. package/src/events/index.ts +35 -0
  33. package/src/http-request/index.ts +25 -2
  34. package/src/idempotency/index.ts +97 -0
  35. package/src/index.ts +18 -1
  36. package/src/requesters/http.ts +13 -7
  37. package/src/version/version.json +1 -1
  38. package/types.d.ts +40 -0
@@ -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.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");
@@ -41,6 +41,14 @@ var portal_credential_error_1 = require("./portal-credential-error");
41
41
  Object.defineProperty(exports, "PortalCredentialError", { enumerable: true, get: function () { return __importDefault(portal_credential_error_1).default; } });
42
42
  Object.defineProperty(exports, "PortalCredentialErrorReason", { enumerable: true, get: function () { return portal_credential_error_1.PortalCredentialErrorReason; } });
43
43
  __exportStar(require("./portal-error"), exports);
44
+ var portal_idempotency_error_1 = require("./portal-idempotency-error");
45
+ Object.defineProperty(exports, "PortalIdempotencyError", { enumerable: true, get: function () { return __importDefault(portal_idempotency_error_1).default; } });
46
+ Object.defineProperty(exports, "PortalIdempotencyErrorId", { enumerable: true, get: function () { return portal_idempotency_error_1.PortalIdempotencyErrorId; } });
47
+ Object.defineProperty(exports, "isIdempotencyKeyReused", { enumerable: true, get: function () { return portal_idempotency_error_1.isIdempotencyKeyReused; } });
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; } });
44
52
  var portal_policy_error_1 = require("./portal-policy-error");
45
53
  Object.defineProperty(exports, "PortalPolicyError", { enumerable: true, get: function () { return __importDefault(portal_policy_error_1).default; } });
46
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,74 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.isIdempotencyKeyReused = exports.isIdempotencyRejection = exports.PortalIdempotencyErrorId = void 0;
5
+ /**
6
+ * The IDs Portal returns when it refuses a request because of its idempotency
7
+ * key. None of them carries the original transaction hash, and several mean
8
+ * Portal cannot confirm whether the transaction reached the chain: look it up
9
+ * before sending the operation again under a new key.
10
+ */
11
+ exports.PortalIdempotencyErrorId = {
12
+ RequestInProgress: 'IDEMPOTENT_REQUEST_IN_PROGRESS',
13
+ RequestAlreadyCompleted: 'IDEMPOTENT_REQUEST_ALREADY_COMPLETED',
14
+ RequestPreviouslyFailed: 'IDEMPOTENT_REQUEST_PREVIOUSLY_FAILED',
15
+ RequestUnexpectedState: 'IDEMPOTENT_REQUEST_UNEXPECTED_STATE',
16
+ KeyReused: 'IDEMPOTENCY_KEY_REUSED',
17
+ TxMissing: 'IDEMPOTENT_TX_MISSING',
18
+ };
19
+ const IDEMPOTENCY_ERROR_IDS = new Set(Object.values(exports.PortalIdempotencyErrorId));
20
+ const errorIdOf = (error) => typeof error === 'object' && error !== null
21
+ ? error.id
22
+ : undefined;
23
+ /**
24
+ * Whether Portal refused the request because of its idempotency key: the
25
+ * error's `id` is one of {@link PortalIdempotencyErrorId}. Accepts a raw error
26
+ * envelope or a thrown error, and matches the ID exactly, never the message or
27
+ * `code`.
28
+ */
29
+ const isIdempotencyRejection = (error) => {
30
+ const id = errorIdOf(error);
31
+ return typeof id === 'string' && IDEMPOTENCY_ERROR_IDS.has(id);
32
+ };
33
+ exports.isIdempotencyRejection = isIdempotencyRejection;
34
+ /**
35
+ * Whether the idempotency key was already used for a request with a different
36
+ * payload ({@link PortalIdempotencyErrorId.KeyReused}).
37
+ */
38
+ const isIdempotencyKeyReused = (error) => errorIdOf(error) === exports.PortalIdempotencyErrorId.KeyReused;
39
+ exports.isIdempotencyKeyReused = isIdempotencyKeyReused;
40
+ /**
41
+ * Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
42
+ * when a consumer's tree resolves two `@portal-hq/utils`.
43
+ *
44
+ * This key and the members {@link PortalIdempotencyError.is} implies are a
45
+ * compatibility contract: changing either breaks recognition between copies.
46
+ */
47
+ const BRAND = Symbol.for('@portal-hq/utils/PortalIdempotencyError');
48
+ /**
49
+ * Thrown by the SDK, before anything is signed or sent, when an idempotency key
50
+ * cannot be used: `invalidKey` for a key that breaks Portal's rules, and
51
+ * `unsupportedTarget` for a key on a broadcast Portal cannot deduplicate. The
52
+ * message names the problem and never contains the key.
53
+ */
54
+ class PortalIdempotencyError extends Error {
55
+ constructor(reason, message) {
56
+ super(message);
57
+ /** @internal Cross-copy brand. Read it through {@link PortalIdempotencyError.is}. */
58
+ this[_a] = true;
59
+ Object.setPrototypeOf(this, PortalIdempotencyError.prototype);
60
+ this.name = 'PortalIdempotencyError';
61
+ this.reason = reason;
62
+ }
63
+ /**
64
+ * Brand check — see BRAND. Narrowing a branded error from another copy to
65
+ * this class is intentional.
66
+ */
67
+ static is(error) {
68
+ return (typeof error === 'object' &&
69
+ error !== null &&
70
+ error[BRAND] === true);
71
+ }
72
+ }
73
+ _a = BRAND;
74
+ exports.default = PortalIdempotencyError;
@@ -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) {
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.validateIdempotencyKey = exports.generateIdempotencyKey = exports.PORTAL_IDEMPOTENCY_KEY_HEADER = void 0;
7
+ const portal_idempotency_error_1 = __importDefault(require("../errors/portal-idempotency-error"));
8
+ const tracing_1 = require("../tracing");
9
+ /**
10
+ * The HTTP header the Enclave MPC API reads a transaction broadcast's
11
+ * idempotency key from.
12
+ */
13
+ exports.PORTAL_IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key';
14
+ const IDEMPOTENCY_KEY_MAX_LENGTH = 255;
15
+ /** RFC 3986 unreserved characters, the only ones Portal accepts in a key. */
16
+ const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._~-]+$/;
17
+ const uuidV4FromRandomValues = (getRandomValues) => {
18
+ const bytes = getRandomValues(new Uint8Array(16));
19
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
20
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
21
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
22
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
23
+ };
24
+ /**
25
+ * Generates an idempotency key: a lowercase UUID v4. Generate one per logical
26
+ * operation, store it with the pending operation, and reuse it only to retry
27
+ * that identical request.
28
+ *
29
+ * The key comes from `crypto.randomUUID` or `crypto.getRandomValues` when the
30
+ * runtime provides one. Hermes provides neither unless the app installs a
31
+ * polyfill such as `react-native-get-random-values`; without one the key is
32
+ * built from `Math.random`, which keeps keys unique in practice but is not a
33
+ * cryptographic source.
34
+ */
35
+ const generateIdempotencyKey = () => {
36
+ const runtimeCrypto = typeof crypto === 'undefined' ? undefined : crypto;
37
+ if (typeof (runtimeCrypto === null || runtimeCrypto === void 0 ? void 0 : runtimeCrypto.randomUUID) === 'function') {
38
+ return runtimeCrypto.randomUUID().toLowerCase();
39
+ }
40
+ if (typeof (runtimeCrypto === null || runtimeCrypto === void 0 ? void 0 : runtimeCrypto.getRandomValues) === 'function') {
41
+ return uuidV4FromRandomValues(runtimeCrypto.getRandomValues.bind(runtimeCrypto));
42
+ }
43
+ // With neither API available, generateTraceId builds the key from
44
+ // Math.random.
45
+ return (0, tracing_1.generateTraceId)().toLowerCase();
46
+ };
47
+ exports.generateIdempotencyKey = generateIdempotencyKey;
48
+ /**
49
+ * Trims `key` the way Portal does (`String.prototype.trim`) and checks it
50
+ * against Portal's rules: 1–255 characters of `A-Z a-z 0-9 . _ ~ -`.
51
+ *
52
+ * @internal Exported only so the SDK packages can share it across the package
53
+ * boundary. Not part of the public API.
54
+ *
55
+ * @returns The trimmed key, which is the value the SDK sends.
56
+ * @throws {PortalIdempotencyError} `invalidKey`, naming the rule that failed.
57
+ */
58
+ const validateIdempotencyKey = (key) => {
59
+ if (typeof key !== 'string') {
60
+ throw new portal_idempotency_error_1.default('invalidKey', 'idempotencyKey must be a string');
61
+ }
62
+ const trimmed = key.trim();
63
+ if (trimmed.length === 0) {
64
+ throw new portal_idempotency_error_1.default('invalidKey', 'idempotencyKey must not be empty or whitespace-only');
65
+ }
66
+ if (trimmed.length > IDEMPOTENCY_KEY_MAX_LENGTH) {
67
+ throw new portal_idempotency_error_1.default('invalidKey', `idempotencyKey must be at most ${IDEMPOTENCY_KEY_MAX_LENGTH} characters`);
68
+ }
69
+ if (!IDEMPOTENCY_KEY_PATTERN.test(trimmed)) {
70
+ throw new portal_idempotency_error_1.default('invalidKey', "idempotencyKey may only contain the characters A-Z, a-z, 0-9, '.', '_', '~' and '-'");
71
+ }
72
+ return trimmed;
73
+ };
74
+ exports.validateIdempotencyKey = validateIdempotencyKey;
@@ -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.RpcErrorCodes = exports.ProviderRpcError = exports.mpcErrorFrom = exports.isPolicyViolation = exports.isMpcAuthFailure = exports.PolicyErrorId = exports.POLICY_ERROR_ID_PREFIX = exports.PortalPolicyError = 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; } });
@@ -61,6 +63,10 @@ Object.defineProperty(exports, "MPC_AUTH_FAILED_ERROR_ID", { enumerable: true, g
61
63
  Object.defineProperty(exports, "PortalErrorCodes", { enumerable: true, get: function () { return errors_1.PortalErrorCodes; } });
62
64
  Object.defineProperty(exports, "PortalErrorCodeTypes", { enumerable: true, get: function () { return errors_1.PortalErrorCodeTypes; } });
63
65
  Object.defineProperty(exports, "PortalMpcError", { enumerable: true, get: function () { return errors_1.PortalMpcError; } });
66
+ Object.defineProperty(exports, "PortalIdempotencyError", { enumerable: true, get: function () { return errors_1.PortalIdempotencyError; } });
67
+ Object.defineProperty(exports, "PortalIdempotencyErrorId", { enumerable: true, get: function () { return errors_1.PortalIdempotencyErrorId; } });
68
+ Object.defineProperty(exports, "isIdempotencyKeyReused", { enumerable: true, get: function () { return errors_1.isIdempotencyKeyReused; } });
69
+ Object.defineProperty(exports, "isIdempotencyRejection", { enumerable: true, get: function () { return errors_1.isIdempotencyRejection; } });
64
70
  Object.defineProperty(exports, "PortalPolicyError", { enumerable: true, get: function () { return errors_1.PortalPolicyError; } });
65
71
  Object.defineProperty(exports, "POLICY_ERROR_ID_PREFIX", { enumerable: true, get: function () { return errors_1.POLICY_ERROR_ID_PREFIX; } });
66
72
  Object.defineProperty(exports, "PolicyErrorId", { enumerable: true, get: function () { return errors_1.PolicyErrorId; } });
@@ -69,6 +75,10 @@ Object.defineProperty(exports, "isPolicyViolation", { enumerable: true, get: fun
69
75
  Object.defineProperty(exports, "mpcErrorFrom", { enumerable: true, get: function () { return errors_1.mpcErrorFrom; } });
70
76
  Object.defineProperty(exports, "ProviderRpcError", { enumerable: true, get: function () { return errors_1.ProviderRpcError; } });
71
77
  Object.defineProperty(exports, "RpcErrorCodes", { enumerable: true, get: function () { return errors_1.RpcErrorCodes; } });
78
+ var idempotency_1 = require("./idempotency");
79
+ Object.defineProperty(exports, "generateIdempotencyKey", { enumerable: true, get: function () { return idempotency_1.generateIdempotencyKey; } });
80
+ Object.defineProperty(exports, "PORTAL_IDEMPOTENCY_KEY_HEADER", { enumerable: true, get: function () { return idempotency_1.PORTAL_IDEMPOTENCY_KEY_HEADER; } });
81
+ Object.defineProperty(exports, "validateIdempotencyKey", { enumerable: true, get: function () { return idempotency_1.validateIdempotencyKey; } });
72
82
  var events_1 = require("./events");
73
83
  Object.defineProperty(exports, "Events", { enumerable: true, get: function () { return __importDefault(events_1).default; } });
74
84
  var version_1 = require("./version");
@@ -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.1.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() {
@@ -9,5 +9,7 @@ export { default as NoAddressError } from './no-address-error';
9
9
  export { default as PortalAuthError, PortalAuthErrorReason, } from './portal-auth-error';
10
10
  export { default as PortalCredentialError, PortalCredentialErrorReason, } from './portal-credential-error';
11
11
  export * from './portal-error';
12
+ export { default as PortalIdempotencyError, PortalIdempotencyErrorId, isIdempotencyKeyReused, isIdempotencyRejection, } from './portal-idempotency-error';
13
+ export { default as PortalPasskeyPrfError, PortalPasskeyPrfErrorReason, } from './portal-passkey-prf-error';
12
14
  export { default as PortalPolicyError, POLICY_ERROR_ID_PREFIX, PolicyErrorId, isPolicyViolation, mpcErrorFrom, } from './portal-policy-error';
13
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,69 @@
1
+ var _a;
2
+ /**
3
+ * The IDs Portal returns when it refuses a request because of its idempotency
4
+ * key. None of them carries the original transaction hash, and several mean
5
+ * Portal cannot confirm whether the transaction reached the chain: look it up
6
+ * before sending the operation again under a new key.
7
+ */
8
+ export const PortalIdempotencyErrorId = {
9
+ RequestInProgress: 'IDEMPOTENT_REQUEST_IN_PROGRESS',
10
+ RequestAlreadyCompleted: 'IDEMPOTENT_REQUEST_ALREADY_COMPLETED',
11
+ RequestPreviouslyFailed: 'IDEMPOTENT_REQUEST_PREVIOUSLY_FAILED',
12
+ RequestUnexpectedState: 'IDEMPOTENT_REQUEST_UNEXPECTED_STATE',
13
+ KeyReused: 'IDEMPOTENCY_KEY_REUSED',
14
+ TxMissing: 'IDEMPOTENT_TX_MISSING',
15
+ };
16
+ const IDEMPOTENCY_ERROR_IDS = new Set(Object.values(PortalIdempotencyErrorId));
17
+ const errorIdOf = (error) => typeof error === 'object' && error !== null
18
+ ? error.id
19
+ : undefined;
20
+ /**
21
+ * Whether Portal refused the request because of its idempotency key: the
22
+ * error's `id` is one of {@link PortalIdempotencyErrorId}. Accepts a raw error
23
+ * envelope or a thrown error, and matches the ID exactly, never the message or
24
+ * `code`.
25
+ */
26
+ export const isIdempotencyRejection = (error) => {
27
+ const id = errorIdOf(error);
28
+ return typeof id === 'string' && IDEMPOTENCY_ERROR_IDS.has(id);
29
+ };
30
+ /**
31
+ * Whether the idempotency key was already used for a request with a different
32
+ * payload ({@link PortalIdempotencyErrorId.KeyReused}).
33
+ */
34
+ export const isIdempotencyKeyReused = (error) => errorIdOf(error) === PortalIdempotencyErrorId.KeyReused;
35
+ /**
36
+ * Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
37
+ * when a consumer's tree resolves two `@portal-hq/utils`.
38
+ *
39
+ * This key and the members {@link PortalIdempotencyError.is} implies are a
40
+ * compatibility contract: changing either breaks recognition between copies.
41
+ */
42
+ const BRAND = Symbol.for('@portal-hq/utils/PortalIdempotencyError');
43
+ /**
44
+ * Thrown by the SDK, before anything is signed or sent, when an idempotency key
45
+ * cannot be used: `invalidKey` for a key that breaks Portal's rules, and
46
+ * `unsupportedTarget` for a key on a broadcast Portal cannot deduplicate. The
47
+ * message names the problem and never contains the key.
48
+ */
49
+ class PortalIdempotencyError extends Error {
50
+ constructor(reason, message) {
51
+ super(message);
52
+ /** @internal Cross-copy brand. Read it through {@link PortalIdempotencyError.is}. */
53
+ this[_a] = true;
54
+ Object.setPrototypeOf(this, PortalIdempotencyError.prototype);
55
+ this.name = 'PortalIdempotencyError';
56
+ this.reason = reason;
57
+ }
58
+ /**
59
+ * Brand check — see BRAND. Narrowing a branded error from another copy to
60
+ * this class is intentional.
61
+ */
62
+ static is(error) {
63
+ return (typeof error === 'object' &&
64
+ error !== null &&
65
+ error[BRAND] === true);
66
+ }
67
+ }
68
+ _a = BRAND;
69
+ export default PortalIdempotencyError;