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