@portal-hq/utils 4.9.0 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/commonjs/config/index.js +1 -0
- package/lib/commonjs/credentials/index.js +262 -0
- package/lib/commonjs/errors/http-error.js +27 -0
- package/lib/commonjs/errors/index.js +13 -1
- package/lib/commonjs/errors/portal-auth-error.js +63 -0
- package/lib/commonjs/errors/portal-credential-error.js +58 -0
- package/lib/commonjs/errors/portal-error.js +13 -1
- package/lib/commonjs/errors/portal-policy-error.js +83 -0
- package/lib/commonjs/events/index.js +29 -2
- package/lib/commonjs/index.js +22 -2
- package/lib/commonjs/requesters/http.js +33 -16
- package/lib/commonjs/version/version.json +1 -1
- package/lib/esm/config/index.js +1 -0
- package/lib/esm/credentials/index.js +251 -0
- package/lib/esm/errors/http-error.js +27 -0
- package/lib/esm/errors/index.js +3 -0
- package/lib/esm/errors/portal-auth-error.js +60 -0
- package/lib/esm/errors/portal-credential-error.js +55 -0
- package/lib/esm/errors/portal-error.js +11 -0
- package/lib/esm/errors/portal-policy-error.js +77 -0
- package/lib/esm/events/index.js +29 -2
- package/lib/esm/index.js +2 -1
- package/lib/esm/requesters/http.js +33 -16
- package/lib/esm/version/version.json +1 -1
- package/package.json +2 -2
- package/src/config/index.ts +1 -0
- package/src/credentials/index.ts +309 -0
- package/src/definitions/index.ts +35 -8
- package/src/errors/http-error.ts +40 -1
- package/src/errors/index.ts +17 -0
- package/src/errors/portal-auth-error.ts +86 -0
- package/src/errors/portal-credential-error.ts +80 -0
- package/src/errors/portal-error.ts +14 -0
- package/src/errors/portal-policy-error.ts +97 -0
- package/src/events/index.ts +30 -2
- package/src/index.ts +26 -0
- package/src/requesters/http.ts +35 -21
- package/src/version/version.json +1 -1
- package/types.d.ts +60 -36
package/lib/commonjs/index.js
CHANGED
|
@@ -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.
|
|
7
|
-
exports.sdkLogger = exports.UUID_V4_REGEX = void 0;
|
|
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;
|
|
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; } });
|
|
@@ -25,6 +25,15 @@ Object.defineProperty(exports, "NAMESPACE_TO_CURVE", { enumerable: true, get: fu
|
|
|
25
25
|
var config_1 = require("./config");
|
|
26
26
|
Object.defineProperty(exports, "buildDefaultGatewayConfig", { enumerable: true, get: function () { return config_1.buildDefaultGatewayConfig; } });
|
|
27
27
|
Object.defineProperty(exports, "DEFAULT_HOSTS", { enumerable: true, get: function () { return config_1.DEFAULT_HOSTS; } });
|
|
28
|
+
var credentials_1 = require("./credentials");
|
|
29
|
+
Object.defineProperty(exports, "StaticCredentials", { enumerable: true, get: function () { return credentials_1.StaticCredentials; } });
|
|
30
|
+
Object.defineProperty(exports, "failFromMpcError", { enumerable: true, get: function () { return credentials_1.failFromMpcError; } });
|
|
31
|
+
Object.defineProperty(exports, "invalidateCredentials", { enumerable: true, get: function () { return credentials_1.invalidateCredentials; } });
|
|
32
|
+
Object.defineProperty(exports, "onCredentialsInvalidated", { enumerable: true, get: function () { return credentials_1.onCredentialsInvalidated; } });
|
|
33
|
+
Object.defineProperty(exports, "reportUnauthorized", { enumerable: true, get: function () { return credentials_1.reportUnauthorized; } });
|
|
34
|
+
Object.defineProperty(exports, "resolveCredentials", { enumerable: true, get: function () { return credentials_1.resolveCredentials; } });
|
|
35
|
+
Object.defineProperty(exports, "resolveCredentialToken", { enumerable: true, get: function () { return credentials_1.resolveCredentialToken; } });
|
|
36
|
+
Object.defineProperty(exports, "staticApiKeyOf", { enumerable: true, get: function () { return credentials_1.staticApiKeyOf; } });
|
|
28
37
|
var currency_1 = require("./currency");
|
|
29
38
|
Object.defineProperty(exports, "convertLocalToCrypto", { enumerable: true, get: function () { return currency_1.convertLocalToCrypto; } });
|
|
30
39
|
Object.defineProperty(exports, "convertCryptoToLocal", { enumerable: true, get: function () { return currency_1.convertCryptoToLocal; } });
|
|
@@ -44,9 +53,20 @@ Object.defineProperty(exports, "InvalidGatewayConfigError", { enumerable: true,
|
|
|
44
53
|
Object.defineProperty(exports, "MissingOptionError", { enumerable: true, get: function () { return errors_1.MissingOptionError; } });
|
|
45
54
|
Object.defineProperty(exports, "MpcSigningError", { enumerable: true, get: function () { return errors_1.MpcSigningError; } });
|
|
46
55
|
Object.defineProperty(exports, "NoAddressError", { enumerable: true, get: function () { return errors_1.NoAddressError; } });
|
|
56
|
+
Object.defineProperty(exports, "PortalAuthError", { enumerable: true, get: function () { return errors_1.PortalAuthError; } });
|
|
57
|
+
Object.defineProperty(exports, "PortalAuthErrorReason", { enumerable: true, get: function () { return errors_1.PortalAuthErrorReason; } });
|
|
58
|
+
Object.defineProperty(exports, "PortalCredentialError", { enumerable: true, get: function () { return errors_1.PortalCredentialError; } });
|
|
59
|
+
Object.defineProperty(exports, "PortalCredentialErrorReason", { enumerable: true, get: function () { return errors_1.PortalCredentialErrorReason; } });
|
|
60
|
+
Object.defineProperty(exports, "MPC_AUTH_FAILED_ERROR_ID", { enumerable: true, get: function () { return errors_1.MPC_AUTH_FAILED_ERROR_ID; } });
|
|
47
61
|
Object.defineProperty(exports, "PortalErrorCodes", { enumerable: true, get: function () { return errors_1.PortalErrorCodes; } });
|
|
48
62
|
Object.defineProperty(exports, "PortalErrorCodeTypes", { enumerable: true, get: function () { return errors_1.PortalErrorCodeTypes; } });
|
|
49
63
|
Object.defineProperty(exports, "PortalMpcError", { enumerable: true, get: function () { return errors_1.PortalMpcError; } });
|
|
64
|
+
Object.defineProperty(exports, "PortalPolicyError", { enumerable: true, get: function () { return errors_1.PortalPolicyError; } });
|
|
65
|
+
Object.defineProperty(exports, "POLICY_ERROR_ID_PREFIX", { enumerable: true, get: function () { return errors_1.POLICY_ERROR_ID_PREFIX; } });
|
|
66
|
+
Object.defineProperty(exports, "PolicyErrorId", { enumerable: true, get: function () { return errors_1.PolicyErrorId; } });
|
|
67
|
+
Object.defineProperty(exports, "isMpcAuthFailure", { enumerable: true, get: function () { return errors_1.isMpcAuthFailure; } });
|
|
68
|
+
Object.defineProperty(exports, "isPolicyViolation", { enumerable: true, get: function () { return errors_1.isPolicyViolation; } });
|
|
69
|
+
Object.defineProperty(exports, "mpcErrorFrom", { enumerable: true, get: function () { return errors_1.mpcErrorFrom; } });
|
|
50
70
|
Object.defineProperty(exports, "ProviderRpcError", { enumerable: true, get: function () { return errors_1.ProviderRpcError; } });
|
|
51
71
|
Object.defineProperty(exports, "RpcErrorCodes", { enumerable: true, get: function () { return errors_1.RpcErrorCodes; } });
|
|
52
72
|
var events_1 = require("./events");
|
|
@@ -9,11 +9,38 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
const errors_1 = require("../errors");
|
|
12
13
|
const index_1 = require("../index");
|
|
13
14
|
const tracing_1 = require("../tracing");
|
|
14
15
|
class HttpRequester {
|
|
15
|
-
constructor({ baseUrl }) {
|
|
16
|
+
constructor({ baseUrl, onUnauthorized }) {
|
|
16
17
|
this.baseUrl = baseUrl;
|
|
18
|
+
this.onUnauthorized = onUnauthorized;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Sends a request, notifying `onUnauthorized` on 401. Observational only:
|
|
22
|
+
* the hook's own failure is swallowed and the original `HttpError` is always
|
|
23
|
+
* what the caller sees.
|
|
24
|
+
*/
|
|
25
|
+
send(requestOptions) {
|
|
26
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
27
|
+
try {
|
|
28
|
+
return (yield new index_1.HttpRequest(requestOptions).send());
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
if (this.onUnauthorized &&
|
|
32
|
+
error instanceof errors_1.HttpError &&
|
|
33
|
+
error.status === 401) {
|
|
34
|
+
try {
|
|
35
|
+
yield this.onUnauthorized();
|
|
36
|
+
}
|
|
37
|
+
catch (_a) {
|
|
38
|
+
// Never let credential bookkeeping replace the original failure.
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
});
|
|
17
44
|
}
|
|
18
45
|
buildHeaders(headers = {}, traceId) {
|
|
19
46
|
return Object.assign(Object.assign({ 'Content-Type': 'application/json' }, headers), (traceId ? { [tracing_1.TRACE_ID_HEADER]: traceId } : {}));
|
|
@@ -26,9 +53,7 @@ class HttpRequester {
|
|
|
26
53
|
url: `${this.baseUrl}${path}`,
|
|
27
54
|
};
|
|
28
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);
|
|
29
|
-
|
|
30
|
-
const response = (yield request.send());
|
|
31
|
-
return response;
|
|
56
|
+
return this.send(requestOptions);
|
|
32
57
|
});
|
|
33
58
|
}
|
|
34
59
|
get(path, options) {
|
|
@@ -39,9 +64,7 @@ class HttpRequester {
|
|
|
39
64
|
url: `${this.baseUrl}${path}`,
|
|
40
65
|
};
|
|
41
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);
|
|
42
|
-
|
|
43
|
-
const response = (yield request.send());
|
|
44
|
-
return response;
|
|
67
|
+
return this.send(requestOptions);
|
|
45
68
|
});
|
|
46
69
|
}
|
|
47
70
|
post(path, options) {
|
|
@@ -55,9 +78,7 @@ class HttpRequester {
|
|
|
55
78
|
if (options === null || options === void 0 ? void 0 : options.body) {
|
|
56
79
|
requestOptions.body = options.body;
|
|
57
80
|
}
|
|
58
|
-
|
|
59
|
-
const response = (yield request.send());
|
|
60
|
-
return response;
|
|
81
|
+
return this.send(requestOptions);
|
|
61
82
|
});
|
|
62
83
|
}
|
|
63
84
|
put(path, options) {
|
|
@@ -71,9 +92,7 @@ class HttpRequester {
|
|
|
71
92
|
if (options === null || options === void 0 ? void 0 : options.body) {
|
|
72
93
|
requestOptions.body = options.body;
|
|
73
94
|
}
|
|
74
|
-
|
|
75
|
-
const response = (yield request.send());
|
|
76
|
-
return response;
|
|
95
|
+
return this.send(requestOptions);
|
|
77
96
|
});
|
|
78
97
|
}
|
|
79
98
|
patch(path, options) {
|
|
@@ -87,9 +106,7 @@ class HttpRequester {
|
|
|
87
106
|
if (options === null || options === void 0 ? void 0 : options.body) {
|
|
88
107
|
requestOptions.body = options.body;
|
|
89
108
|
}
|
|
90
|
-
|
|
91
|
-
const response = (yield request.send());
|
|
92
|
-
return response;
|
|
109
|
+
return this.send(requestOptions);
|
|
93
110
|
});
|
|
94
111
|
}
|
|
95
112
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{ "version": "
|
|
1
|
+
{ "version": "5.1.0" }
|
package/lib/esm/config/index.js
CHANGED
|
@@ -17,6 +17,7 @@ export const SUPPORTED_CHAINS = [
|
|
|
17
17
|
{ namespace: 'eip155', reference: '84532' },
|
|
18
18
|
{ namespace: 'eip155', reference: '143' },
|
|
19
19
|
{ namespace: 'eip155', reference: '10143' },
|
|
20
|
+
{ namespace: 'eip155', reference: '42161' },
|
|
20
21
|
{ namespace: 'solana', reference: '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' },
|
|
21
22
|
{ namespace: 'solana', reference: 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1' },
|
|
22
23
|
];
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
var _a;
|
|
11
|
+
import { InvalidApiKeyError, PortalCredentialError, PortalCredentialErrorReason, isMpcAuthFailure, mpcErrorFrom, } from '../errors';
|
|
12
|
+
import { sdkLogger } from '../logger';
|
|
13
|
+
/**
|
|
14
|
+
* Cross-copy brand. The key and the branded shape (a string `value`) are a
|
|
15
|
+
* compatibility contract across versions — see `PortalCredentialError`.
|
|
16
|
+
*/
|
|
17
|
+
const BRAND = Symbol.for('@portal-hq/utils/StaticCredentials');
|
|
18
|
+
export class StaticCredentials {
|
|
19
|
+
constructor(apiKey) {
|
|
20
|
+
/** @internal Cross-copy brand. Read it through {@link StaticCredentials.is}. */
|
|
21
|
+
this[_a] = true;
|
|
22
|
+
this.value = apiKey;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Brand check, not `instanceof` — an instance from another copy of this
|
|
26
|
+
* package must still match. Reports the brand only: callers reading a member
|
|
27
|
+
* must re-check it, as {@link staticApiKeyOf} does.
|
|
28
|
+
*/
|
|
29
|
+
static is(credentials) {
|
|
30
|
+
return (typeof credentials === 'object' &&
|
|
31
|
+
credentials !== null &&
|
|
32
|
+
credentials[BRAND] === true);
|
|
33
|
+
}
|
|
34
|
+
getToken() {
|
|
35
|
+
return Promise.resolve(this.value);
|
|
36
|
+
}
|
|
37
|
+
/** No-op: a Client API Key is custodian-owned and holds no local state to drop. */
|
|
38
|
+
invalidate() {
|
|
39
|
+
return Promise.resolve();
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
_a = BRAND;
|
|
43
|
+
/**
|
|
44
|
+
* Resolves the single credential source a component was constructed with.
|
|
45
|
+
*
|
|
46
|
+
* Throws `InvalidApiKeyError` when neither source is given — callers depend on
|
|
47
|
+
* that type.
|
|
48
|
+
*/
|
|
49
|
+
export function resolveCredentials({ apiKey, credentials, }) {
|
|
50
|
+
if (credentials && apiKey) {
|
|
51
|
+
throw new Error('[Portal] Provide either `apiKey` or `credentials`, not both.');
|
|
52
|
+
}
|
|
53
|
+
if (credentials) {
|
|
54
|
+
return credentials;
|
|
55
|
+
}
|
|
56
|
+
if (!apiKey) {
|
|
57
|
+
throw new InvalidApiKeyError();
|
|
58
|
+
}
|
|
59
|
+
return new StaticCredentials(apiKey);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The SDK's credential boundary: normalizes every failure to
|
|
63
|
+
* `PortalCredentialError`, since a host-supplied `PortalCredentials` can throw
|
|
64
|
+
* anything. A `PortalCredentialError` from the provider passes through
|
|
65
|
+
* untouched so its `reason` is never downgraded.
|
|
66
|
+
*/
|
|
67
|
+
export function resolveCredentialToken(credentials) {
|
|
68
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
69
|
+
let token;
|
|
70
|
+
try {
|
|
71
|
+
token = yield credentials.getToken();
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (PortalCredentialError.is(error)) {
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
throw new PortalCredentialError({
|
|
78
|
+
reason: PortalCredentialErrorReason.ProviderFailure,
|
|
79
|
+
cause: error,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (!token) {
|
|
83
|
+
throw new PortalCredentialError({
|
|
84
|
+
reason: PortalCredentialErrorReason.Unavailable,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
return token;
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Keyed by the credential, not by subsystem, so several requesters 401-ing at
|
|
92
|
+
* once — all of which arrive here through `reportUnauthorized` — share one
|
|
93
|
+
* invalidation instead of each issuing a keychain delete.
|
|
94
|
+
*/
|
|
95
|
+
const invalidations = new WeakMap();
|
|
96
|
+
export function invalidateCredentials(credentials) {
|
|
97
|
+
const inFlight = invalidations.get(credentials);
|
|
98
|
+
if (inFlight) {
|
|
99
|
+
return inFlight;
|
|
100
|
+
}
|
|
101
|
+
// A host-supplied `invalidate()` may throw synchronously or return something
|
|
102
|
+
// that is not a native Promise. Starting from `Promise.resolve()` turns both
|
|
103
|
+
// into a rejection here rather than a throw that escapes before the guard
|
|
104
|
+
// below is registered, which would silently disable deduplication.
|
|
105
|
+
const invalidation = Promise.resolve()
|
|
106
|
+
.then(() => credentials.invalidate())
|
|
107
|
+
.finally(() => {
|
|
108
|
+
invalidations.delete(credentials);
|
|
109
|
+
});
|
|
110
|
+
invalidations.set(credentials, invalidation);
|
|
111
|
+
return invalidation;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Host listeners, keyed by the credential rather than by the `Portal` holding
|
|
115
|
+
* it, so they are reachable from the 401 call sites — which see a credential
|
|
116
|
+
* and nothing else — and so a credential that is dropped takes its listeners
|
|
117
|
+
* with it.
|
|
118
|
+
*
|
|
119
|
+
* One entry is one subscription, never one callback: two subscribers may hand
|
|
120
|
+
* in the same function, and an entry keyed on the function itself would
|
|
121
|
+
* collapse them into one that either unsubscribe removes — silently
|
|
122
|
+
* deregistering a subscriber that never asked to be.
|
|
123
|
+
*/
|
|
124
|
+
const invalidationListeners = new WeakMap();
|
|
125
|
+
/** Credentials already announced to the host, so each is reported once. */
|
|
126
|
+
const reported = new WeakSet();
|
|
127
|
+
/**
|
|
128
|
+
* Subscribes to the backend invalidating `credentials`. Returns an
|
|
129
|
+
* unsubscribe; see `Portal.onSessionInvalidated` for the host-facing contract.
|
|
130
|
+
*
|
|
131
|
+
* A credential can already have been reported before the host gets to
|
|
132
|
+
* subscribe — validity is discovered by making a request, so a host that
|
|
133
|
+
* awaits one before mounting its subscriber would otherwise never hear that
|
|
134
|
+
* the session is over, and nothing else exposes that state.
|
|
135
|
+
*/
|
|
136
|
+
export function onCredentialsInvalidated(credentials, listener) {
|
|
137
|
+
var _b;
|
|
138
|
+
const listeners = (_b = invalidationListeners.get(credentials)) !== null && _b !== void 0 ? _b : new Set();
|
|
139
|
+
// This subscription's identity in `listeners`, distinct from every other
|
|
140
|
+
// subscription of the same `listener` — see the note on that map.
|
|
141
|
+
const subscription = () => listener();
|
|
142
|
+
listeners.add(subscription);
|
|
143
|
+
invalidationListeners.set(credentials, listeners);
|
|
144
|
+
// `notifyInvalidated` will not run again for this credential, so catch this
|
|
145
|
+
// subscription up itself. Deferred so the caller holds its unsubscribe
|
|
146
|
+
// before the callback can run, and re-checked then so a subscription
|
|
147
|
+
// dropped straight away stays silent — which is also what keeps a React
|
|
148
|
+
// effect that tears down and remounts within one commit to a single call.
|
|
149
|
+
// A Client API Key never reaches here: it is never recorded as reported.
|
|
150
|
+
if (reported.has(credentials)) {
|
|
151
|
+
void Promise.resolve().then(() => {
|
|
152
|
+
if (!listeners.has(subscription)) {
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
try {
|
|
156
|
+
subscription();
|
|
157
|
+
}
|
|
158
|
+
catch (_b) {
|
|
159
|
+
// As in `notifyInvalidated`: a host callback failing is not this
|
|
160
|
+
// module's problem to propagate.
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
return () => {
|
|
165
|
+
listeners.delete(subscription);
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* At most once per credential, and never for a Client API Key: that credential
|
|
170
|
+
* is custodian-owned, its `invalidate()` is a no-op, and there is no local
|
|
171
|
+
* session for a 401 to have ended.
|
|
172
|
+
*/
|
|
173
|
+
function notifyInvalidated(credentials) {
|
|
174
|
+
var _b;
|
|
175
|
+
if (StaticCredentials.is(credentials) || reported.has(credentials)) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
reported.add(credentials);
|
|
179
|
+
// Snapshot: a listener is free to unsubscribe itself, or subscribe another,
|
|
180
|
+
// from inside the callback.
|
|
181
|
+
for (const listener of Array.from((_b = invalidationListeners.get(credentials)) !== null && _b !== void 0 ? _b : [])) {
|
|
182
|
+
try {
|
|
183
|
+
listener();
|
|
184
|
+
}
|
|
185
|
+
catch (_c) {
|
|
186
|
+
// A host callback failing must not take the other listeners, the
|
|
187
|
+
// invalidation, or this bookkeeping down with it.
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* The 401 path every Portal-authenticated requester routes through: invalidate
|
|
193
|
+
* the credential, then tell the host its session ended.
|
|
194
|
+
*
|
|
195
|
+
* Kept separate from {@link invalidateCredentials}, which stays the plain
|
|
196
|
+
* operation a host-initiated sign-out uses — only a backend rejection is news
|
|
197
|
+
* to the host.
|
|
198
|
+
*
|
|
199
|
+
* Notifies even when the invalidation rejects: the token is dropped in memory
|
|
200
|
+
* first, so the session is over either way. The rejection still propagates,
|
|
201
|
+
* and every call site already treats it as bookkeeping that must not replace
|
|
202
|
+
* the original failure.
|
|
203
|
+
*/
|
|
204
|
+
export function reportUnauthorized(credentials) {
|
|
205
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
206
|
+
try {
|
|
207
|
+
yield invalidateCredentials(credentials);
|
|
208
|
+
}
|
|
209
|
+
finally {
|
|
210
|
+
notifyInvalidated(credentials);
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* The MPC equivalent of the 401 path above: the binary issues its own
|
|
216
|
+
* authenticated requests, so a rejected credential arrives as an `AUTH_FAILED`
|
|
217
|
+
* envelope rather than a status code any requester here can see.
|
|
218
|
+
*
|
|
219
|
+
* The binary's error is rethrown unchanged either way — the invalidation is
|
|
220
|
+
* bookkeeping, and callers keep branching on `PortalMpcError` and its `id`. A
|
|
221
|
+
* Policy Engine rejection is promoted to `PortalPolicyError`, a subclass, so
|
|
222
|
+
* that stays true.
|
|
223
|
+
*/
|
|
224
|
+
export function failFromMpcError(credentials, error) {
|
|
225
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
226
|
+
if (isMpcAuthFailure(error)) {
|
|
227
|
+
try {
|
|
228
|
+
yield reportUnauthorized(credentials);
|
|
229
|
+
}
|
|
230
|
+
catch (bookkeeping) {
|
|
231
|
+
sdkLogger.error('[Portal] Failed to invalidate a credential the MPC binary rejected', bookkeeping);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
throw mpcErrorFrom(error);
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The raw Client API Key behind a credential, or `''` when it is not a static
|
|
239
|
+
* key — never a wrong or stale token. Temporary bridge for subsystems that
|
|
240
|
+
* need a synchronous `apiKey`.
|
|
241
|
+
*/
|
|
242
|
+
export function staticApiKeyOf(credentials) {
|
|
243
|
+
if (!StaticCredentials.is(credentials)) {
|
|
244
|
+
return '';
|
|
245
|
+
}
|
|
246
|
+
// The brand identifies the shape, it does not prove it: an instance from
|
|
247
|
+
// another copy of this package is only structurally compatible, so re-check
|
|
248
|
+
// the type.
|
|
249
|
+
const { value } = credentials;
|
|
250
|
+
return typeof value === 'string' ? value : '';
|
|
251
|
+
}
|
|
@@ -4,6 +4,33 @@ class HttpError extends Error {
|
|
|
4
4
|
// Set the prototype explicitly.
|
|
5
5
|
Object.setPrototypeOf(this, HttpError.prototype);
|
|
6
6
|
this.status = status;
|
|
7
|
+
const body = parseJsonBody(message);
|
|
8
|
+
if (!isJsonObject(body)) {
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
if (typeof body.error === 'string') {
|
|
12
|
+
this.errorMessage = body.error;
|
|
13
|
+
}
|
|
14
|
+
if (typeof body.id === 'string') {
|
|
15
|
+
this.id = body.id;
|
|
16
|
+
}
|
|
17
|
+
if (isJsonObject(body.details)) {
|
|
18
|
+
this.details = body.details;
|
|
19
|
+
}
|
|
7
20
|
}
|
|
8
21
|
}
|
|
22
|
+
function parseJsonBody(responseText) {
|
|
23
|
+
if (responseText.trim() === '') {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
return JSON.parse(responseText);
|
|
28
|
+
}
|
|
29
|
+
catch (_a) {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function isJsonObject(value) {
|
|
34
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
35
|
+
}
|
|
9
36
|
export default HttpError;
|
package/lib/esm/errors/index.js
CHANGED
|
@@ -6,5 +6,8 @@ export { default as InvalidGatewayConfigError } from './invalid-gateway-config-e
|
|
|
6
6
|
export { default as MissingOptionError } from './missing-option-error';
|
|
7
7
|
export { default as MpcSigningError } from './mpc-signing-error';
|
|
8
8
|
export { default as NoAddressError } from './no-address-error';
|
|
9
|
+
export { default as PortalAuthError, PortalAuthErrorReason, } from './portal-auth-error';
|
|
10
|
+
export { default as PortalCredentialError, PortalCredentialErrorReason, } from './portal-credential-error';
|
|
9
11
|
export * from './portal-error';
|
|
12
|
+
export { default as PortalPolicyError, POLICY_ERROR_ID_PREFIX, PolicyErrorId, isPolicyViolation, mpcErrorFrom, } from './portal-policy-error';
|
|
10
13
|
export { default as ProviderRpcError, RpcErrorCodes, } from './provider-rpc-error';
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
var _a;
|
|
2
|
+
/**
|
|
3
|
+
* Why a Client Auth login could not be completed.
|
|
4
|
+
*
|
|
5
|
+
* The backend answers every unusable grant with the same undifferentiated 401
|
|
6
|
+
* — replayed, expired, forged, wrong auth environment, and disabled or invalid
|
|
7
|
+
* auth method are deliberately indistinguishable — so these reasons describe
|
|
8
|
+
* what the SDK actually knows and the action the host should take, not what
|
|
9
|
+
* went wrong server-side.
|
|
10
|
+
*/
|
|
11
|
+
export var PortalAuthErrorReason;
|
|
12
|
+
(function (PortalAuthErrorReason) {
|
|
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.
|
|
16
|
+
*/
|
|
17
|
+
PortalAuthErrorReason["GrantRejected"] = "GRANT_REJECTED";
|
|
18
|
+
/**
|
|
19
|
+
* The authentication provider sent the user back with an error instead of a
|
|
20
|
+
* grant. The user never completed the provider's flow.
|
|
21
|
+
*/
|
|
22
|
+
PortalAuthErrorReason["ProviderRejected"] = "PROVIDER_REJECTED";
|
|
23
|
+
})(PortalAuthErrorReason || (PortalAuthErrorReason = {}));
|
|
24
|
+
const authErrors = {
|
|
25
|
+
[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
|
+
[PortalAuthErrorReason.ProviderRejected]: 'The authentication provider rejected the sign-in.',
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
|
|
30
|
+
* when a consumer's tree resolves two `@portal-hq/utils`.
|
|
31
|
+
*
|
|
32
|
+
* This key and the members {@link PortalAuthError.is} implies are a
|
|
33
|
+
* compatibility contract: changing either breaks recognition between copies.
|
|
34
|
+
*/
|
|
35
|
+
const BRAND = Symbol.for('@portal-hq/utils/PortalAuthError');
|
|
36
|
+
/**
|
|
37
|
+
* The single error every Client Auth completion failure is normalized to;
|
|
38
|
+
* branch on `reason`.
|
|
39
|
+
*/
|
|
40
|
+
class PortalAuthError extends Error {
|
|
41
|
+
constructor({ reason, detail, cause }) {
|
|
42
|
+
super(`[PortalAuth] ${authErrors[reason]}${detail ? ` (${detail})` : ''}`);
|
|
43
|
+
/** @internal Cross-copy brand. Read it through {@link PortalAuthError.is}. */
|
|
44
|
+
this[_a] = true;
|
|
45
|
+
Object.setPrototypeOf(this, PortalAuthError.prototype);
|
|
46
|
+
this.reason = reason;
|
|
47
|
+
this.cause = cause;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Brand check — see BRAND. Narrowing a branded error from another copy to
|
|
51
|
+
* this class is intentional.
|
|
52
|
+
*/
|
|
53
|
+
static is(error) {
|
|
54
|
+
return (typeof error === 'object' &&
|
|
55
|
+
error !== null &&
|
|
56
|
+
error[BRAND] === true);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
_a = BRAND;
|
|
60
|
+
export default PortalAuthError;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
var _a;
|
|
2
|
+
/** Why a credential could not be turned into a usable token. */
|
|
3
|
+
export var PortalCredentialErrorReason;
|
|
4
|
+
(function (PortalCredentialErrorReason) {
|
|
5
|
+
/** Resolution succeeded but produced nothing usable. */
|
|
6
|
+
PortalCredentialErrorReason["Unavailable"] = "CREDENTIAL_UNAVAILABLE";
|
|
7
|
+
/** The credential provider itself failed — a storage read, a custom
|
|
8
|
+
* `PortalCredentials` implementation throwing, and so on. */
|
|
9
|
+
PortalCredentialErrorReason["ProviderFailure"] = "CREDENTIAL_PROVIDER_FAILURE";
|
|
10
|
+
/** The credential is known to be dead: the session was invalidated. */
|
|
11
|
+
PortalCredentialErrorReason["SessionInvalidated"] = "SESSION_INVALIDATED";
|
|
12
|
+
})(PortalCredentialErrorReason || (PortalCredentialErrorReason = {}));
|
|
13
|
+
const credentialErrors = {
|
|
14
|
+
[PortalCredentialErrorReason.Unavailable]: 'No credential was available. Provide an apiKey or credentials when constructing Portal.',
|
|
15
|
+
[PortalCredentialErrorReason.ProviderFailure]: 'The credential provider failed to supply a credential.',
|
|
16
|
+
[PortalCredentialErrorReason.SessionInvalidated]: 'The session is no longer valid. Authenticate again to obtain a new one.',
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
|
|
20
|
+
* when a consumer's tree resolves two `@portal-hq/utils` — a real
|
|
21
|
+
* `SessionInvalidated` then silently degrades to a provider failure.
|
|
22
|
+
*
|
|
23
|
+
* This key and the members {@link PortalCredentialError.is} implies are a
|
|
24
|
+
* compatibility contract: changing either breaks recognition between copies.
|
|
25
|
+
*/
|
|
26
|
+
const BRAND = Symbol.for('@portal-hq/utils/PortalCredentialError');
|
|
27
|
+
/**
|
|
28
|
+
* The single error every credential resolution failure is normalized to; branch
|
|
29
|
+
* on `reason`.
|
|
30
|
+
*/
|
|
31
|
+
class PortalCredentialError extends Error {
|
|
32
|
+
constructor({ reason, cause }) {
|
|
33
|
+
super(`[Portal] ${credentialErrors[reason]}`);
|
|
34
|
+
/** @internal Cross-copy brand. Read it through {@link PortalCredentialError.is}. */
|
|
35
|
+
this[_a] = true;
|
|
36
|
+
Object.setPrototypeOf(this, PortalCredentialError.prototype);
|
|
37
|
+
this.reason = reason;
|
|
38
|
+
this.cause = cause;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Brand check — see BRAND. Narrowing a branded error from another copy to
|
|
42
|
+
* this class is intentional.
|
|
43
|
+
*/
|
|
44
|
+
static is(error) {
|
|
45
|
+
return (typeof error === 'object' &&
|
|
46
|
+
error !== null &&
|
|
47
|
+
error[BRAND] === true);
|
|
48
|
+
}
|
|
49
|
+
/** True when re-authentication is the only way forward. */
|
|
50
|
+
get requiresReauthentication() {
|
|
51
|
+
return this.reason === PortalCredentialErrorReason.SessionInvalidated;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
_a = BRAND;
|
|
55
|
+
export default PortalCredentialError;
|
|
@@ -73,3 +73,14 @@ export class PortalMpcError extends Error {
|
|
|
73
73
|
this.id = error.id;
|
|
74
74
|
}
|
|
75
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* The MPC binary issues its own authenticated requests, so the SDK never sees
|
|
78
|
+
* the HTTP 401 behind a rejected credential — this ID is the only form it
|
|
79
|
+
* reaches us in. Matched on the ID, never the companion `code`, which exists
|
|
80
|
+
* only for clients predating these IDs.
|
|
81
|
+
*/
|
|
82
|
+
export const MPC_AUTH_FAILED_ERROR_ID = 'AUTH_FAILED';
|
|
83
|
+
/** Accepts a raw error envelope or a thrown {@link PortalMpcError}. */
|
|
84
|
+
export const isMpcAuthFailure = (error) => typeof error === 'object' &&
|
|
85
|
+
error !== null &&
|
|
86
|
+
error.id === MPC_AUTH_FAILED_ERROR_ID;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
var _a;
|
|
2
|
+
import { PortalMpcError } from './portal-error';
|
|
3
|
+
/**
|
|
4
|
+
* Every Policy Engine rejection the gateway emits carries an ID under this
|
|
5
|
+
* prefix. Classification is by prefix, not by a known-ID list, so a policy kind
|
|
6
|
+
* added to the gateway later is still recognised without an SDK release.
|
|
7
|
+
*/
|
|
8
|
+
export const POLICY_ERROR_ID_PREFIX = 'POLICY_';
|
|
9
|
+
/** The policy IDs the gateway emits today. The set is open — see the prefix. */
|
|
10
|
+
export const PolicyErrorId = {
|
|
11
|
+
AmountLimitExceeded: 'POLICY_AMOUNT_LIMIT_EXCEEDED',
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Whether an error reports a Policy Engine rejection.
|
|
15
|
+
*
|
|
16
|
+
* Accepts a raw error envelope or a thrown {@link PortalMpcError}. Matched on
|
|
17
|
+
* the ID, never the companion `code` — the binary maps policy IDs onto a
|
|
18
|
+
* generic legacy code — and never on the message text.
|
|
19
|
+
*/
|
|
20
|
+
export const isPolicyViolation = (error) => {
|
|
21
|
+
if (typeof error !== 'object' || error === null) {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
const { id } = error;
|
|
25
|
+
return typeof id === 'string' && id.startsWith(POLICY_ERROR_ID_PREFIX);
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
|
|
29
|
+
* when a consumer's tree resolves two `@portal-hq/utils` — a real policy
|
|
30
|
+
* rejection would then silently degrade to an ordinary MPC failure.
|
|
31
|
+
*
|
|
32
|
+
* This key and the members {@link PortalPolicyError.is} implies are a
|
|
33
|
+
* compatibility contract: changing either breaks recognition between copies.
|
|
34
|
+
*/
|
|
35
|
+
const BRAND = Symbol.for('@portal-hq/utils/PortalPolicyError');
|
|
36
|
+
/**
|
|
37
|
+
* A transaction the Policy Engine refused to sign. Extends
|
|
38
|
+
* {@link PortalMpcError} so callers already branching on that type, or reading
|
|
39
|
+
* its `id`, keep working unchanged. `id` always carries the `POLICY_*`
|
|
40
|
+
* identifier here, even though the inherited type leaves it optional.
|
|
41
|
+
*
|
|
42
|
+
* The rejection is terminal: the same request will be refused again, so it is
|
|
43
|
+
* not retried and it never invalidates the credential — the session is fine,
|
|
44
|
+
* the transaction is not.
|
|
45
|
+
*/
|
|
46
|
+
export class PortalPolicyError extends PortalMpcError {
|
|
47
|
+
constructor(error, cause) {
|
|
48
|
+
super(error);
|
|
49
|
+
/** @internal Cross-copy brand. Read it through {@link PortalPolicyError.is}. */
|
|
50
|
+
this[_a] = true;
|
|
51
|
+
Object.setPrototypeOf(this, PortalPolicyError.prototype);
|
|
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
|
+
}
|
|
64
|
+
_a = BRAND;
|
|
65
|
+
/**
|
|
66
|
+
* Builds the error for an MPC envelope, promoting a Policy Engine rejection to
|
|
67
|
+
* {@link PortalPolicyError}. Every other envelope stays a {@link PortalMpcError},
|
|
68
|
+
* so only the policy path changes shape.
|
|
69
|
+
*
|
|
70
|
+
* @internal Exported only so the provider packages can share it across the
|
|
71
|
+
* package boundary. Not part of the public API — catch {@link PortalPolicyError}
|
|
72
|
+
* or call {@link isPolicyViolation} instead.
|
|
73
|
+
*/
|
|
74
|
+
export const mpcErrorFrom = (error, cause) => isPolicyViolation(error)
|
|
75
|
+
? new PortalPolicyError(error, cause)
|
|
76
|
+
: new PortalMpcError(error);
|
|
77
|
+
export default PortalPolicyError;
|