@portal-hq/utils 5.1.0 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/commonjs/errors/index.js +6 -1
- package/lib/commonjs/errors/portal-idempotency-error.js +74 -0
- package/lib/commonjs/idempotency/index.js +74 -0
- package/lib/commonjs/index.js +9 -1
- package/lib/commonjs/version/version.json +1 -1
- package/lib/esm/errors/index.js +1 -0
- package/lib/esm/errors/portal-idempotency-error.js +69 -0
- package/lib/esm/idempotency/index.js +66 -0
- package/lib/esm/index.js +2 -1
- package/lib/esm/version/version.json +1 -1
- package/package.json +2 -2
- package/src/definitions/index.ts +48 -0
- package/src/errors/index.ts +7 -0
- package/src/errors/portal-idempotency-error.ts +91 -0
- package/src/idempotency/index.ts +97 -0
- package/src/index.ts +11 -0
- package/src/version/version.json +1 -1
- package/types.d.ts +1 -0
|
@@ -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.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,11 @@ 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; } });
|
|
44
49
|
var portal_policy_error_1 = require("./portal-policy-error");
|
|
45
50
|
Object.defineProperty(exports, "PortalPolicyError", { enumerable: true, get: function () { return __importDefault(portal_policy_error_1).default; } });
|
|
46
51
|
Object.defineProperty(exports, "POLICY_ERROR_ID_PREFIX", { enumerable: true, get: function () { return portal_policy_error_1.POLICY_ERROR_ID_PREFIX; } });
|
|
@@ -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,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;
|
package/lib/commonjs/index.js
CHANGED
|
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
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;
|
|
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;
|
|
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; } });
|
|
@@ -61,6 +61,10 @@ Object.defineProperty(exports, "MPC_AUTH_FAILED_ERROR_ID", { enumerable: true, g
|
|
|
61
61
|
Object.defineProperty(exports, "PortalErrorCodes", { enumerable: true, get: function () { return errors_1.PortalErrorCodes; } });
|
|
62
62
|
Object.defineProperty(exports, "PortalErrorCodeTypes", { enumerable: true, get: function () { return errors_1.PortalErrorCodeTypes; } });
|
|
63
63
|
Object.defineProperty(exports, "PortalMpcError", { enumerable: true, get: function () { return errors_1.PortalMpcError; } });
|
|
64
|
+
Object.defineProperty(exports, "PortalIdempotencyError", { enumerable: true, get: function () { return errors_1.PortalIdempotencyError; } });
|
|
65
|
+
Object.defineProperty(exports, "PortalIdempotencyErrorId", { enumerable: true, get: function () { return errors_1.PortalIdempotencyErrorId; } });
|
|
66
|
+
Object.defineProperty(exports, "isIdempotencyKeyReused", { enumerable: true, get: function () { return errors_1.isIdempotencyKeyReused; } });
|
|
67
|
+
Object.defineProperty(exports, "isIdempotencyRejection", { enumerable: true, get: function () { return errors_1.isIdempotencyRejection; } });
|
|
64
68
|
Object.defineProperty(exports, "PortalPolicyError", { enumerable: true, get: function () { return errors_1.PortalPolicyError; } });
|
|
65
69
|
Object.defineProperty(exports, "POLICY_ERROR_ID_PREFIX", { enumerable: true, get: function () { return errors_1.POLICY_ERROR_ID_PREFIX; } });
|
|
66
70
|
Object.defineProperty(exports, "PolicyErrorId", { enumerable: true, get: function () { return errors_1.PolicyErrorId; } });
|
|
@@ -69,6 +73,10 @@ Object.defineProperty(exports, "isPolicyViolation", { enumerable: true, get: fun
|
|
|
69
73
|
Object.defineProperty(exports, "mpcErrorFrom", { enumerable: true, get: function () { return errors_1.mpcErrorFrom; } });
|
|
70
74
|
Object.defineProperty(exports, "ProviderRpcError", { enumerable: true, get: function () { return errors_1.ProviderRpcError; } });
|
|
71
75
|
Object.defineProperty(exports, "RpcErrorCodes", { enumerable: true, get: function () { return errors_1.RpcErrorCodes; } });
|
|
76
|
+
var idempotency_1 = require("./idempotency");
|
|
77
|
+
Object.defineProperty(exports, "generateIdempotencyKey", { enumerable: true, get: function () { return idempotency_1.generateIdempotencyKey; } });
|
|
78
|
+
Object.defineProperty(exports, "PORTAL_IDEMPOTENCY_KEY_HEADER", { enumerable: true, get: function () { return idempotency_1.PORTAL_IDEMPOTENCY_KEY_HEADER; } });
|
|
79
|
+
Object.defineProperty(exports, "validateIdempotencyKey", { enumerable: true, get: function () { return idempotency_1.validateIdempotencyKey; } });
|
|
72
80
|
var events_1 = require("./events");
|
|
73
81
|
Object.defineProperty(exports, "Events", { enumerable: true, get: function () { return __importDefault(events_1).default; } });
|
|
74
82
|
var version_1 = require("./version");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{ "version": "5.
|
|
1
|
+
{ "version": "5.2.0" }
|
package/lib/esm/errors/index.js
CHANGED
|
@@ -9,5 +9,6 @@ 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';
|
|
12
13
|
export { default as PortalPolicyError, POLICY_ERROR_ID_PREFIX, PolicyErrorId, isPolicyViolation, mpcErrorFrom, } from './portal-policy-error';
|
|
13
14
|
export { default as ProviderRpcError, RpcErrorCodes, } from './provider-rpc-error';
|
|
@@ -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;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import PortalIdempotencyError from '../errors/portal-idempotency-error';
|
|
2
|
+
import { generateTraceId } from '../tracing';
|
|
3
|
+
/**
|
|
4
|
+
* The HTTP header the Enclave MPC API reads a transaction broadcast's
|
|
5
|
+
* idempotency key from.
|
|
6
|
+
*/
|
|
7
|
+
export const PORTAL_IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key';
|
|
8
|
+
const IDEMPOTENCY_KEY_MAX_LENGTH = 255;
|
|
9
|
+
/** RFC 3986 unreserved characters, the only ones Portal accepts in a key. */
|
|
10
|
+
const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._~-]+$/;
|
|
11
|
+
const uuidV4FromRandomValues = (getRandomValues) => {
|
|
12
|
+
const bytes = getRandomValues(new Uint8Array(16));
|
|
13
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
14
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
15
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
16
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Generates an idempotency key: a lowercase UUID v4. Generate one per logical
|
|
20
|
+
* operation, store it with the pending operation, and reuse it only to retry
|
|
21
|
+
* that identical request.
|
|
22
|
+
*
|
|
23
|
+
* The key comes from `crypto.randomUUID` or `crypto.getRandomValues` when the
|
|
24
|
+
* runtime provides one. Hermes provides neither unless the app installs a
|
|
25
|
+
* polyfill such as `react-native-get-random-values`; without one the key is
|
|
26
|
+
* built from `Math.random`, which keeps keys unique in practice but is not a
|
|
27
|
+
* cryptographic source.
|
|
28
|
+
*/
|
|
29
|
+
export const generateIdempotencyKey = () => {
|
|
30
|
+
const runtimeCrypto = typeof crypto === 'undefined' ? undefined : crypto;
|
|
31
|
+
if (typeof (runtimeCrypto === null || runtimeCrypto === void 0 ? void 0 : runtimeCrypto.randomUUID) === 'function') {
|
|
32
|
+
return runtimeCrypto.randomUUID().toLowerCase();
|
|
33
|
+
}
|
|
34
|
+
if (typeof (runtimeCrypto === null || runtimeCrypto === void 0 ? void 0 : runtimeCrypto.getRandomValues) === 'function') {
|
|
35
|
+
return uuidV4FromRandomValues(runtimeCrypto.getRandomValues.bind(runtimeCrypto));
|
|
36
|
+
}
|
|
37
|
+
// With neither API available, generateTraceId builds the key from
|
|
38
|
+
// Math.random.
|
|
39
|
+
return generateTraceId().toLowerCase();
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Trims `key` the way Portal does (`String.prototype.trim`) and checks it
|
|
43
|
+
* against Portal's rules: 1–255 characters of `A-Z a-z 0-9 . _ ~ -`.
|
|
44
|
+
*
|
|
45
|
+
* @internal Exported only so the SDK packages can share it across the package
|
|
46
|
+
* boundary. Not part of the public API.
|
|
47
|
+
*
|
|
48
|
+
* @returns The trimmed key, which is the value the SDK sends.
|
|
49
|
+
* @throws {PortalIdempotencyError} `invalidKey`, naming the rule that failed.
|
|
50
|
+
*/
|
|
51
|
+
export const validateIdempotencyKey = (key) => {
|
|
52
|
+
if (typeof key !== 'string') {
|
|
53
|
+
throw new PortalIdempotencyError('invalidKey', 'idempotencyKey must be a string');
|
|
54
|
+
}
|
|
55
|
+
const trimmed = key.trim();
|
|
56
|
+
if (trimmed.length === 0) {
|
|
57
|
+
throw new PortalIdempotencyError('invalidKey', 'idempotencyKey must not be empty or whitespace-only');
|
|
58
|
+
}
|
|
59
|
+
if (trimmed.length > IDEMPOTENCY_KEY_MAX_LENGTH) {
|
|
60
|
+
throw new PortalIdempotencyError('invalidKey', `idempotencyKey must be at most ${IDEMPOTENCY_KEY_MAX_LENGTH} characters`);
|
|
61
|
+
}
|
|
62
|
+
if (!IDEMPOTENCY_KEY_PATTERN.test(trimmed)) {
|
|
63
|
+
throw new PortalIdempotencyError('invalidKey', "idempotencyKey may only contain the characters A-Z, a-z, 0-9, '.', '_', '~' and '-'");
|
|
64
|
+
}
|
|
65
|
+
return trimmed;
|
|
66
|
+
};
|
package/lib/esm/index.js
CHANGED
|
@@ -3,7 +3,8 @@ export { buildDefaultGatewayConfig, DEFAULT_HOSTS } from './config';
|
|
|
3
3
|
export { StaticCredentials, failFromMpcError, invalidateCredentials, onCredentialsInvalidated, reportUnauthorized, resolveCredentials, resolveCredentialToken, staticApiKeyOf, } from './credentials';
|
|
4
4
|
export { convertLocalToCrypto, convertCryptoToLocal, convert } from './currency';
|
|
5
5
|
export { KeychainAdapter, MpcStatuses, PasswordStorage, PortalRequestMethod, Storage, } from './definitions';
|
|
6
|
-
export { CloudStorageReadError, HttpError, InvalidApiKeyError, InvalidChainIdError, InvalidGatewayConfigError, MissingOptionError, MpcSigningError, NoAddressError, PortalAuthError, PortalAuthErrorReason, PortalCredentialError, PortalCredentialErrorReason, MPC_AUTH_FAILED_ERROR_ID, PortalErrorCodes, PortalErrorCodeTypes, PortalMpcError, PortalPolicyError, POLICY_ERROR_ID_PREFIX, PolicyErrorId, isMpcAuthFailure, isPolicyViolation, mpcErrorFrom, ProviderRpcError, RpcErrorCodes, } from './errors';
|
|
6
|
+
export { CloudStorageReadError, HttpError, InvalidApiKeyError, InvalidChainIdError, InvalidGatewayConfigError, MissingOptionError, MpcSigningError, NoAddressError, PortalAuthError, PortalAuthErrorReason, PortalCredentialError, PortalCredentialErrorReason, MPC_AUTH_FAILED_ERROR_ID, PortalErrorCodes, PortalErrorCodeTypes, PortalMpcError, PortalIdempotencyError, PortalIdempotencyErrorId, isIdempotencyKeyReused, isIdempotencyRejection, PortalPolicyError, POLICY_ERROR_ID_PREFIX, PolicyErrorId, isMpcAuthFailure, isPolicyViolation, mpcErrorFrom, ProviderRpcError, RpcErrorCodes, } from './errors';
|
|
7
|
+
export { generateIdempotencyKey, PORTAL_IDEMPOTENCY_KEY_HEADER, validateIdempotencyKey, } from './idempotency';
|
|
7
8
|
export { default as Events } from './events';
|
|
8
9
|
export { getClientPlatformVersion } from './version';
|
|
9
10
|
export { numberToHexString, parseRequest } from './eth-requests';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{ "version": "5.
|
|
1
|
+
{ "version": "5.2.0" }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@portal-hq/utils",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.2.0",
|
|
4
4
|
"main": "lib/commonjs/index",
|
|
5
5
|
"module": "lib/esm/index",
|
|
6
6
|
"source": "src/index",
|
|
@@ -26,5 +26,5 @@
|
|
|
26
26
|
"ts-jest": "^29.0.3",
|
|
27
27
|
"typescript": "^4.8.4"
|
|
28
28
|
},
|
|
29
|
-
"gitHead": "
|
|
29
|
+
"gitHead": "a14b1c60fd0d4cb72839dc6ed81f6c9f251dd980"
|
|
30
30
|
}
|
package/src/definitions/index.ts
CHANGED
|
@@ -85,6 +85,30 @@ export interface RequestOptions {
|
|
|
85
85
|
sponsorGas?: boolean
|
|
86
86
|
signatureApprovalMemo?: string
|
|
87
87
|
traceId?: string
|
|
88
|
+
/**
|
|
89
|
+
* Makes a transaction broadcast safe to retry: while Portal remembers a key
|
|
90
|
+
* (at least 24 hours) it broadcasts it at most once. Honoured for
|
|
91
|
+
* `eth_sendTransaction`, `sol_signAndSendTransaction` and
|
|
92
|
+
* `sol_signAndConfirmTransaction`; ignored with a warning for any other
|
|
93
|
+
* method. Surrounding whitespace is trimmed, and the key must then be 1–255
|
|
94
|
+
* characters of `A-Z a-z 0-9 . _ ~ -`, otherwise the request throws a
|
|
95
|
+
* `PortalIdempotencyError` before the approval prompt. A key on
|
|
96
|
+
* `eth_sendRawTransaction` or `sol_sendTransaction` also throws, because
|
|
97
|
+
* Portal cannot deduplicate a transaction that is already signed.
|
|
98
|
+
*
|
|
99
|
+
* Portal recognises a retry only when its `chainId`, `method` and `params`
|
|
100
|
+
* match the first request's, with `params` compared as the JSON string the
|
|
101
|
+
* SDK sends. Retry with the same transaction object: the same fields in a
|
|
102
|
+
* different order serialize differently, and the retry can be rejected with
|
|
103
|
+
* `IDEMPOTENCY_KEY_REUSED`. No rejection returns the original transaction
|
|
104
|
+
* hash.
|
|
105
|
+
*
|
|
106
|
+
* With presignatures on, a presignature attempt that fails after reaching
|
|
107
|
+
* Portal leaves the fallback sign reusing the key, so Portal can reject it
|
|
108
|
+
* (for example with `IDEMPOTENT_REQUEST_IN_PROGRESS`) where a request without
|
|
109
|
+
* a key would have been signed.
|
|
110
|
+
*/
|
|
111
|
+
idempotencyKey?: string
|
|
88
112
|
}
|
|
89
113
|
|
|
90
114
|
export enum PortalRequestMethod {
|
|
@@ -209,6 +233,30 @@ export interface SendAssetParams {
|
|
|
209
233
|
* to underlying API requests to aid in observability.
|
|
210
234
|
*/
|
|
211
235
|
traceId?: string
|
|
236
|
+
/**
|
|
237
|
+
* Optional idempotency key for the broadcast, honoured on EVM and Solana
|
|
238
|
+
* chains (see `RequestOptions.idempotencyKey`). A key on a Bitcoin chain
|
|
239
|
+
* throws a `PortalIdempotencyError` before the transaction is built.
|
|
240
|
+
*
|
|
241
|
+
* `sendAsset` rebuilds the transaction on every call, and a retry is
|
|
242
|
+
* recognised only when the rebuilt transaction matches the first one. An EVM
|
|
243
|
+
* build carries no nonce or gas, so with unchanged inputs it normally
|
|
244
|
+
* matches and the retry is rejected with the first request's status (for
|
|
245
|
+
* example `IDEMPOTENT_REQUEST_ALREADY_COMPLETED`). A Solana build carries a
|
|
246
|
+
* new recent blockhash, so the retry is usually rejected with
|
|
247
|
+
* `IDEMPOTENCY_KEY_REUSED`, which does not say whether the first transfer
|
|
248
|
+
* is in progress, completed or failed. Either way the transfer is not
|
|
249
|
+
* broadcast twice under this key, and no rejection returns the original
|
|
250
|
+
* transaction hash.
|
|
251
|
+
*
|
|
252
|
+
* Before sending the transfer again under a new key, confirm on-chain that
|
|
253
|
+
* the first one did not land: on Solana, wait until it is confirmed or its
|
|
254
|
+
* recent blockhash has expired; on EVM, until it is confirmed or the
|
|
255
|
+
* account's nonce has moved past it. For predictable retries, build the
|
|
256
|
+
* transaction once and send it with `portal.request` and the same key on
|
|
257
|
+
* every attempt.
|
|
258
|
+
*/
|
|
259
|
+
idempotencyKey?: string
|
|
212
260
|
}
|
|
213
261
|
|
|
214
262
|
export interface RawSignOptions {
|
package/src/errors/index.ts
CHANGED
|
@@ -17,6 +17,13 @@ export {
|
|
|
17
17
|
type PortalCredentialErrorOptions,
|
|
18
18
|
} from './portal-credential-error'
|
|
19
19
|
export * from './portal-error'
|
|
20
|
+
export {
|
|
21
|
+
default as PortalIdempotencyError,
|
|
22
|
+
type PortalIdempotencyErrorReason,
|
|
23
|
+
PortalIdempotencyErrorId,
|
|
24
|
+
isIdempotencyKeyReused,
|
|
25
|
+
isIdempotencyRejection,
|
|
26
|
+
} from './portal-idempotency-error'
|
|
20
27
|
export {
|
|
21
28
|
default as PortalPolicyError,
|
|
22
29
|
POLICY_ERROR_ID_PREFIX,
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The IDs Portal returns when it refuses a request because of its idempotency
|
|
3
|
+
* key. None of them carries the original transaction hash, and several mean
|
|
4
|
+
* Portal cannot confirm whether the transaction reached the chain: look it up
|
|
5
|
+
* before sending the operation again under a new key.
|
|
6
|
+
*/
|
|
7
|
+
export const PortalIdempotencyErrorId = {
|
|
8
|
+
RequestInProgress: 'IDEMPOTENT_REQUEST_IN_PROGRESS',
|
|
9
|
+
RequestAlreadyCompleted: 'IDEMPOTENT_REQUEST_ALREADY_COMPLETED',
|
|
10
|
+
RequestPreviouslyFailed: 'IDEMPOTENT_REQUEST_PREVIOUSLY_FAILED',
|
|
11
|
+
RequestUnexpectedState: 'IDEMPOTENT_REQUEST_UNEXPECTED_STATE',
|
|
12
|
+
KeyReused: 'IDEMPOTENCY_KEY_REUSED',
|
|
13
|
+
TxMissing: 'IDEMPOTENT_TX_MISSING',
|
|
14
|
+
} as const
|
|
15
|
+
|
|
16
|
+
const IDEMPOTENCY_ERROR_IDS: ReadonlySet<string> = new Set(
|
|
17
|
+
Object.values(PortalIdempotencyErrorId),
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
const errorIdOf = (error: unknown): unknown =>
|
|
21
|
+
typeof error === 'object' && error !== null
|
|
22
|
+
? (error as { id?: unknown }).id
|
|
23
|
+
: undefined
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Whether Portal refused the request because of its idempotency key: the
|
|
27
|
+
* error's `id` is one of {@link PortalIdempotencyErrorId}. Accepts a raw error
|
|
28
|
+
* envelope or a thrown error, and matches the ID exactly, never the message or
|
|
29
|
+
* `code`.
|
|
30
|
+
*/
|
|
31
|
+
export const isIdempotencyRejection = (error: unknown): boolean => {
|
|
32
|
+
const id = errorIdOf(error)
|
|
33
|
+
|
|
34
|
+
return typeof id === 'string' && IDEMPOTENCY_ERROR_IDS.has(id)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Whether the idempotency key was already used for a request with a different
|
|
39
|
+
* payload ({@link PortalIdempotencyErrorId.KeyReused}).
|
|
40
|
+
*/
|
|
41
|
+
export const isIdempotencyKeyReused = (error: unknown): boolean =>
|
|
42
|
+
errorIdOf(error) === PortalIdempotencyErrorId.KeyReused
|
|
43
|
+
|
|
44
|
+
export type PortalIdempotencyErrorReason = 'invalidKey' | 'unsupportedTarget'
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
|
|
48
|
+
* when a consumer's tree resolves two `@portal-hq/utils`.
|
|
49
|
+
*
|
|
50
|
+
* This key and the members {@link PortalIdempotencyError.is} implies are a
|
|
51
|
+
* compatibility contract: changing either breaks recognition between copies.
|
|
52
|
+
*/
|
|
53
|
+
const BRAND: unique symbol = Symbol.for(
|
|
54
|
+
'@portal-hq/utils/PortalIdempotencyError',
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Thrown by the SDK, before anything is signed or sent, when an idempotency key
|
|
59
|
+
* cannot be used: `invalidKey` for a key that breaks Portal's rules, and
|
|
60
|
+
* `unsupportedTarget` for a key on a broadcast Portal cannot deduplicate. The
|
|
61
|
+
* message names the problem and never contains the key.
|
|
62
|
+
*/
|
|
63
|
+
class PortalIdempotencyError extends Error {
|
|
64
|
+
public readonly reason: PortalIdempotencyErrorReason
|
|
65
|
+
|
|
66
|
+
/** @internal Cross-copy brand. Read it through {@link PortalIdempotencyError.is}. */
|
|
67
|
+
public readonly [BRAND] = true
|
|
68
|
+
|
|
69
|
+
constructor(reason: PortalIdempotencyErrorReason, message: string) {
|
|
70
|
+
super(message)
|
|
71
|
+
|
|
72
|
+
Object.setPrototypeOf(this, PortalIdempotencyError.prototype)
|
|
73
|
+
|
|
74
|
+
this.name = 'PortalIdempotencyError'
|
|
75
|
+
this.reason = reason
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Brand check — see BRAND. Narrowing a branded error from another copy to
|
|
80
|
+
* this class is intentional.
|
|
81
|
+
*/
|
|
82
|
+
public static is(error: unknown): error is PortalIdempotencyError {
|
|
83
|
+
return (
|
|
84
|
+
typeof error === 'object' &&
|
|
85
|
+
error !== null &&
|
|
86
|
+
(error as { [BRAND]?: unknown })[BRAND] === true
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export default PortalIdempotencyError
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import PortalIdempotencyError from '../errors/portal-idempotency-error'
|
|
2
|
+
import { generateTraceId } from '../tracing'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The HTTP header the Enclave MPC API reads a transaction broadcast's
|
|
6
|
+
* idempotency key from.
|
|
7
|
+
*/
|
|
8
|
+
export const PORTAL_IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key'
|
|
9
|
+
|
|
10
|
+
const IDEMPOTENCY_KEY_MAX_LENGTH = 255
|
|
11
|
+
|
|
12
|
+
/** RFC 3986 unreserved characters, the only ones Portal accepts in a key. */
|
|
13
|
+
const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._~-]+$/
|
|
14
|
+
|
|
15
|
+
const uuidV4FromRandomValues = (getRandomValues: Crypto['getRandomValues']) => {
|
|
16
|
+
const bytes = getRandomValues(new Uint8Array(16))
|
|
17
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40
|
|
18
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
|
19
|
+
const hex = Array.from(bytes, (byte) =>
|
|
20
|
+
byte.toString(16).padStart(2, '0'),
|
|
21
|
+
).join('')
|
|
22
|
+
|
|
23
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Generates an idempotency key: a lowercase UUID v4. Generate one per logical
|
|
28
|
+
* operation, store it with the pending operation, and reuse it only to retry
|
|
29
|
+
* that identical request.
|
|
30
|
+
*
|
|
31
|
+
* The key comes from `crypto.randomUUID` or `crypto.getRandomValues` when the
|
|
32
|
+
* runtime provides one. Hermes provides neither unless the app installs a
|
|
33
|
+
* polyfill such as `react-native-get-random-values`; without one the key is
|
|
34
|
+
* built from `Math.random`, which keeps keys unique in practice but is not a
|
|
35
|
+
* cryptographic source.
|
|
36
|
+
*/
|
|
37
|
+
export const generateIdempotencyKey = (): string => {
|
|
38
|
+
const runtimeCrypto = typeof crypto === 'undefined' ? undefined : crypto
|
|
39
|
+
|
|
40
|
+
if (typeof runtimeCrypto?.randomUUID === 'function') {
|
|
41
|
+
return runtimeCrypto.randomUUID().toLowerCase()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (typeof runtimeCrypto?.getRandomValues === 'function') {
|
|
45
|
+
return uuidV4FromRandomValues(
|
|
46
|
+
runtimeCrypto.getRandomValues.bind(runtimeCrypto),
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// With neither API available, generateTraceId builds the key from
|
|
51
|
+
// Math.random.
|
|
52
|
+
return generateTraceId().toLowerCase()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Trims `key` the way Portal does (`String.prototype.trim`) and checks it
|
|
57
|
+
* against Portal's rules: 1–255 characters of `A-Z a-z 0-9 . _ ~ -`.
|
|
58
|
+
*
|
|
59
|
+
* @internal Exported only so the SDK packages can share it across the package
|
|
60
|
+
* boundary. Not part of the public API.
|
|
61
|
+
*
|
|
62
|
+
* @returns The trimmed key, which is the value the SDK sends.
|
|
63
|
+
* @throws {PortalIdempotencyError} `invalidKey`, naming the rule that failed.
|
|
64
|
+
*/
|
|
65
|
+
export const validateIdempotencyKey = (key: unknown): string => {
|
|
66
|
+
if (typeof key !== 'string') {
|
|
67
|
+
throw new PortalIdempotencyError(
|
|
68
|
+
'invalidKey',
|
|
69
|
+
'idempotencyKey must be a string',
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const trimmed = key.trim()
|
|
74
|
+
|
|
75
|
+
if (trimmed.length === 0) {
|
|
76
|
+
throw new PortalIdempotencyError(
|
|
77
|
+
'invalidKey',
|
|
78
|
+
'idempotencyKey must not be empty or whitespace-only',
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (trimmed.length > IDEMPOTENCY_KEY_MAX_LENGTH) {
|
|
83
|
+
throw new PortalIdempotencyError(
|
|
84
|
+
'invalidKey',
|
|
85
|
+
`idempotencyKey must be at most ${IDEMPOTENCY_KEY_MAX_LENGTH} characters`,
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (!IDEMPOTENCY_KEY_PATTERN.test(trimmed)) {
|
|
90
|
+
throw new PortalIdempotencyError(
|
|
91
|
+
'invalidKey',
|
|
92
|
+
"idempotencyKey may only contain the characters A-Z, a-z, 0-9, '.', '_', '~' and '-'",
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return trimmed
|
|
97
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -71,6 +71,11 @@ export {
|
|
|
71
71
|
PortalErrorCodes,
|
|
72
72
|
PortalErrorCodeTypes,
|
|
73
73
|
PortalMpcError,
|
|
74
|
+
PortalIdempotencyError,
|
|
75
|
+
type PortalIdempotencyErrorReason,
|
|
76
|
+
PortalIdempotencyErrorId,
|
|
77
|
+
isIdempotencyKeyReused,
|
|
78
|
+
isIdempotencyRejection,
|
|
74
79
|
PortalPolicyError,
|
|
75
80
|
POLICY_ERROR_ID_PREFIX,
|
|
76
81
|
PolicyErrorId,
|
|
@@ -81,6 +86,12 @@ export {
|
|
|
81
86
|
RpcErrorCodes,
|
|
82
87
|
} from './errors'
|
|
83
88
|
|
|
89
|
+
export {
|
|
90
|
+
generateIdempotencyKey,
|
|
91
|
+
PORTAL_IDEMPOTENCY_KEY_HEADER,
|
|
92
|
+
validateIdempotencyKey,
|
|
93
|
+
} from './idempotency'
|
|
94
|
+
|
|
84
95
|
export { default as Events } from './events'
|
|
85
96
|
|
|
86
97
|
export { getClientPlatformVersion } from './version'
|
package/src/version/version.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{ "version": "5.
|
|
1
|
+
{ "version": "5.2.0" }
|
package/types.d.ts
CHANGED