@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/esm/events/index.js
CHANGED
|
@@ -13,9 +13,7 @@ var Events;
|
|
|
13
13
|
Events["GetEnabledDapps"] = "Get Enabled Dapps";
|
|
14
14
|
Events["GetNFTs"] = "Get NFTs";
|
|
15
15
|
Events["GetNetworks"] = "Get Networks";
|
|
16
|
-
Events["GetQuote"] = "Get Quote";
|
|
17
16
|
Events["GetSigningShareMetadata"] = "Get Signing Share Metadata";
|
|
18
|
-
Events["GetSources"] = "Get Sources";
|
|
19
17
|
Events["GetTransactions"] = "Get Transactions";
|
|
20
18
|
Events["GetTransactionHistory"] = "Get Transaction History";
|
|
21
19
|
Events["PrepareClientEject"] = "Prepare Client Eject";
|
|
@@ -35,6 +33,18 @@ var Events;
|
|
|
35
33
|
Events["YieldXyzGetHistoricalActions"] = "YieldXyz Get Historical Actions";
|
|
36
34
|
Events["YieldXyzGetTransaction"] = "YieldXyz Get Transaction";
|
|
37
35
|
Events["YieldXyzTrack"] = "YieldXyz Track";
|
|
36
|
+
Events["YieldXyzBorrowGetIntegrations"] = "YieldXyz Borrow Get Integrations";
|
|
37
|
+
Events["YieldXyzBorrowGetIntegration"] = "YieldXyz Borrow Get Integration";
|
|
38
|
+
Events["YieldXyzBorrowGetMarkets"] = "YieldXyz Borrow Get Markets";
|
|
39
|
+
Events["YieldXyzBorrowGetMarket"] = "YieldXyz Borrow Get Market";
|
|
40
|
+
Events["YieldXyzBorrowGetPositions"] = "YieldXyz Borrow Get Positions";
|
|
41
|
+
Events["YieldXyzBorrowGetLiquidations"] = "YieldXyz Borrow Get Liquidations";
|
|
42
|
+
Events["YieldXyzBorrowCreateAction"] = "YieldXyz Borrow Create Action";
|
|
43
|
+
Events["YieldXyzBorrowGetActions"] = "YieldXyz Borrow Get Actions";
|
|
44
|
+
Events["YieldXyzBorrowGetAction"] = "YieldXyz Borrow Get Action";
|
|
45
|
+
Events["YieldXyzBorrowStepAction"] = "YieldXyz Borrow Step Action";
|
|
46
|
+
Events["YieldXyzBorrowSubmitTransaction"] = "YieldXyz Borrow Submit Transaction";
|
|
47
|
+
Events["YieldXyzBorrowGetHealth"] = "YieldXyz Borrow Get Health";
|
|
38
48
|
Events["LifiGetRoutes"] = "Lifi Get Routes";
|
|
39
49
|
Events["LifiGetQuote"] = "Lifi Get Quote";
|
|
40
50
|
Events["LifiGetStatus"] = "Lifi Get Status";
|
|
@@ -89,5 +99,22 @@ var Events;
|
|
|
89
99
|
Events["MeldGetBuyLimits"] = "Meld Get Buy Limits";
|
|
90
100
|
Events["MeldGetSellLimits"] = "Meld Get Sell Limits";
|
|
91
101
|
Events["MeldGetKycLimits"] = "Meld Get Kyc Limits";
|
|
102
|
+
Events["YieldXyzPerpsGetProviders"] = "YieldXyz Perps Get Providers";
|
|
103
|
+
Events["YieldXyzPerpsGetProvider"] = "YieldXyz Perps Get Provider";
|
|
104
|
+
Events["YieldXyzPerpsGetMarkets"] = "YieldXyz Perps Get Markets";
|
|
105
|
+
Events["YieldXyzPerpsGetMarket"] = "YieldXyz Perps Get Market";
|
|
106
|
+
Events["YieldXyzPerpsGetMarketCandles"] = "YieldXyz Perps Get Market Candles";
|
|
107
|
+
Events["YieldXyzPerpsGetPositions"] = "YieldXyz Perps Get Positions";
|
|
108
|
+
Events["YieldXyzPerpsGetOrders"] = "YieldXyz Perps Get Orders";
|
|
109
|
+
Events["YieldXyzPerpsGetBalances"] = "YieldXyz Perps Get Balances";
|
|
110
|
+
Events["YieldXyzPerpsCreateAction"] = "YieldXyz Perps Create Action";
|
|
111
|
+
Events["YieldXyzPerpsGetActions"] = "YieldXyz Perps Get Actions";
|
|
112
|
+
Events["YieldXyzPerpsGetAction"] = "YieldXyz Perps Get Action";
|
|
113
|
+
Events["YieldXyzPerpsSubmitTransaction"] = "YieldXyz Perps Submit Transaction";
|
|
114
|
+
Events["YieldXyzPerpsGetActivity"] = "YieldXyz Perps Get Activity";
|
|
115
|
+
Events["YieldXyzPerpsGetEvents"] = "YieldXyz Perps Get Events";
|
|
116
|
+
Events["YieldXyzPerpsGetEvent"] = "YieldXyz Perps Get Event";
|
|
117
|
+
Events["YieldXyzPerpsGetHealth"] = "YieldXyz Perps Get Health";
|
|
118
|
+
Events["YieldXyzPerpsGetProvidersHealth"] = "YieldXyz Perps Get Providers Health";
|
|
92
119
|
})(Events || (Events = {}));
|
|
93
120
|
export default Events;
|
package/lib/esm/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
export { chainIdToName, chainNameToId, getChainIdForName, getChainNameForId, CHAIN_NAMESPACES, SUPPORTED_BITCOIN_P2WPKH_CHAINS, FRIENDLY_CHAIN_NAME_TO_CAIP2, CAIP2_CHAIN_ID_REGEX, DEFAULT_CHAIN_ID_NUMERIC, DEFAULT_CHAIN_ID_CAIP2, EVM_CHAIN_IDS, SOLANA_CHAIN_IDS, TRON_CHAIN_IDS, BITCOIN_CHAIN_IDS, ALL_CHAIN_IDS, NAMESPACE_TO_CURVE, } from './chains';
|
|
2
2
|
export { buildDefaultGatewayConfig, DEFAULT_HOSTS } from './config';
|
|
3
|
+
export { StaticCredentials, failFromMpcError, invalidateCredentials, onCredentialsInvalidated, reportUnauthorized, resolveCredentials, resolveCredentialToken, staticApiKeyOf, } from './credentials';
|
|
3
4
|
export { convertLocalToCrypto, convertCryptoToLocal, convert } from './currency';
|
|
4
5
|
export { KeychainAdapter, MpcStatuses, PasswordStorage, PortalRequestMethod, Storage, } from './definitions';
|
|
5
|
-
export { CloudStorageReadError, HttpError, InvalidApiKeyError, InvalidChainIdError, InvalidGatewayConfigError, MissingOptionError, MpcSigningError, NoAddressError, PortalErrorCodes, PortalErrorCodeTypes, PortalMpcError, 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, PortalPolicyError, POLICY_ERROR_ID_PREFIX, PolicyErrorId, isMpcAuthFailure, isPolicyViolation, mpcErrorFrom, ProviderRpcError, RpcErrorCodes, } from './errors';
|
|
6
7
|
export { default as Events } from './events';
|
|
7
8
|
export { getClientPlatformVersion } from './version';
|
|
8
9
|
export { numberToHexString, parseRequest } from './eth-requests';
|
|
@@ -7,11 +7,38 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
7
7
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
8
|
});
|
|
9
9
|
};
|
|
10
|
+
import { HttpError } from '../errors';
|
|
10
11
|
import { HttpRequest } from '../index';
|
|
11
12
|
import { TRACE_ID_HEADER } from '../tracing';
|
|
12
13
|
class HttpRequester {
|
|
13
|
-
constructor({ baseUrl }) {
|
|
14
|
+
constructor({ baseUrl, onUnauthorized }) {
|
|
14
15
|
this.baseUrl = baseUrl;
|
|
16
|
+
this.onUnauthorized = onUnauthorized;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Sends a request, notifying `onUnauthorized` on 401. Observational only:
|
|
20
|
+
* the hook's own failure is swallowed and the original `HttpError` is always
|
|
21
|
+
* what the caller sees.
|
|
22
|
+
*/
|
|
23
|
+
send(requestOptions) {
|
|
24
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
25
|
+
try {
|
|
26
|
+
return (yield new HttpRequest(requestOptions).send());
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (this.onUnauthorized &&
|
|
30
|
+
error instanceof HttpError &&
|
|
31
|
+
error.status === 401) {
|
|
32
|
+
try {
|
|
33
|
+
yield this.onUnauthorized();
|
|
34
|
+
}
|
|
35
|
+
catch (_a) {
|
|
36
|
+
// Never let credential bookkeeping replace the original failure.
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
});
|
|
15
42
|
}
|
|
16
43
|
buildHeaders(headers = {}, traceId) {
|
|
17
44
|
return Object.assign(Object.assign({ 'Content-Type': 'application/json' }, headers), (traceId ? { [TRACE_ID_HEADER]: traceId } : {}));
|
|
@@ -24,9 +51,7 @@ class HttpRequester {
|
|
|
24
51
|
url: `${this.baseUrl}${path}`,
|
|
25
52
|
};
|
|
26
53
|
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);
|
|
27
|
-
|
|
28
|
-
const response = (yield request.send());
|
|
29
|
-
return response;
|
|
54
|
+
return this.send(requestOptions);
|
|
30
55
|
});
|
|
31
56
|
}
|
|
32
57
|
get(path, options) {
|
|
@@ -37,9 +62,7 @@ class HttpRequester {
|
|
|
37
62
|
url: `${this.baseUrl}${path}`,
|
|
38
63
|
};
|
|
39
64
|
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);
|
|
40
|
-
|
|
41
|
-
const response = (yield request.send());
|
|
42
|
-
return response;
|
|
65
|
+
return this.send(requestOptions);
|
|
43
66
|
});
|
|
44
67
|
}
|
|
45
68
|
post(path, options) {
|
|
@@ -53,9 +76,7 @@ class HttpRequester {
|
|
|
53
76
|
if (options === null || options === void 0 ? void 0 : options.body) {
|
|
54
77
|
requestOptions.body = options.body;
|
|
55
78
|
}
|
|
56
|
-
|
|
57
|
-
const response = (yield request.send());
|
|
58
|
-
return response;
|
|
79
|
+
return this.send(requestOptions);
|
|
59
80
|
});
|
|
60
81
|
}
|
|
61
82
|
put(path, options) {
|
|
@@ -69,9 +90,7 @@ class HttpRequester {
|
|
|
69
90
|
if (options === null || options === void 0 ? void 0 : options.body) {
|
|
70
91
|
requestOptions.body = options.body;
|
|
71
92
|
}
|
|
72
|
-
|
|
73
|
-
const response = (yield request.send());
|
|
74
|
-
return response;
|
|
93
|
+
return this.send(requestOptions);
|
|
75
94
|
});
|
|
76
95
|
}
|
|
77
96
|
patch(path, options) {
|
|
@@ -85,9 +104,7 @@ class HttpRequester {
|
|
|
85
104
|
if (options === null || options === void 0 ? void 0 : options.body) {
|
|
86
105
|
requestOptions.body = options.body;
|
|
87
106
|
}
|
|
88
|
-
|
|
89
|
-
const response = (yield request.send());
|
|
90
|
-
return response;
|
|
107
|
+
return this.send(requestOptions);
|
|
91
108
|
});
|
|
92
109
|
}
|
|
93
110
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{ "version": "
|
|
1
|
+
{ "version": "5.1.0" }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@portal-hq/utils",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "5.1.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": "354d4c662edfbed3dac786621e8ff351fe394ee8"
|
|
30
30
|
}
|
package/src/config/index.ts
CHANGED
|
@@ -21,6 +21,7 @@ export const SUPPORTED_CHAINS: ReadonlyArray<{
|
|
|
21
21
|
{ namespace: 'eip155', reference: '84532' },
|
|
22
22
|
{ namespace: 'eip155', reference: '143' },
|
|
23
23
|
{ namespace: 'eip155', reference: '10143' },
|
|
24
|
+
{ namespace: 'eip155', reference: '42161' },
|
|
24
25
|
{ namespace: 'solana', reference: '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp' },
|
|
25
26
|
{ namespace: 'solana', reference: 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1' },
|
|
26
27
|
]
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import { type PortalCredentials } from '../definitions'
|
|
2
|
+
import {
|
|
3
|
+
InvalidApiKeyError,
|
|
4
|
+
PortalCredentialError,
|
|
5
|
+
PortalCredentialErrorReason,
|
|
6
|
+
type PortalError,
|
|
7
|
+
isMpcAuthFailure,
|
|
8
|
+
mpcErrorFrom,
|
|
9
|
+
} from '../errors'
|
|
10
|
+
import { sdkLogger } from '../logger'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Cross-copy brand. The key and the branded shape (a string `value`) are a
|
|
14
|
+
* compatibility contract across versions — see `PortalCredentialError`.
|
|
15
|
+
*/
|
|
16
|
+
const BRAND: unique symbol = Symbol.for('@portal-hq/utils/StaticCredentials')
|
|
17
|
+
|
|
18
|
+
export class StaticCredentials implements PortalCredentials {
|
|
19
|
+
/**
|
|
20
|
+
* Public only so {@link staticApiKeyOf} can bridge subsystems that read a
|
|
21
|
+
* synchronous `apiKey`. Prefer `getToken()`.
|
|
22
|
+
*/
|
|
23
|
+
public readonly value: string
|
|
24
|
+
|
|
25
|
+
/** @internal Cross-copy brand. Read it through {@link StaticCredentials.is}. */
|
|
26
|
+
public readonly [BRAND] = true
|
|
27
|
+
|
|
28
|
+
constructor(apiKey: string) {
|
|
29
|
+
this.value = apiKey
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Brand check, not `instanceof` — an instance from another copy of this
|
|
34
|
+
* package must still match. Reports the brand only: callers reading a member
|
|
35
|
+
* must re-check it, as {@link staticApiKeyOf} does.
|
|
36
|
+
*/
|
|
37
|
+
public static is(credentials: unknown): credentials is StaticCredentials {
|
|
38
|
+
return (
|
|
39
|
+
typeof credentials === 'object' &&
|
|
40
|
+
credentials !== null &&
|
|
41
|
+
(credentials as { [BRAND]?: unknown })[BRAND] === true
|
|
42
|
+
)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
public getToken(): Promise<string> {
|
|
46
|
+
return Promise.resolve(this.value)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** No-op: a Client API Key is custodian-owned and holds no local state to drop. */
|
|
50
|
+
public invalidate(): Promise<void> {
|
|
51
|
+
return Promise.resolve()
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface CredentialSource {
|
|
56
|
+
/** A Client API Key. Mutually exclusive with `credentials`. */
|
|
57
|
+
apiKey?: string
|
|
58
|
+
/** Anything that can supply a credential — e.g. a `PortalAuth` session. */
|
|
59
|
+
credentials?: PortalCredentials
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Resolves the single credential source a component was constructed with.
|
|
64
|
+
*
|
|
65
|
+
* Throws `InvalidApiKeyError` when neither source is given — callers depend on
|
|
66
|
+
* that type.
|
|
67
|
+
*/
|
|
68
|
+
export function resolveCredentials({
|
|
69
|
+
apiKey,
|
|
70
|
+
credentials,
|
|
71
|
+
}: CredentialSource): PortalCredentials {
|
|
72
|
+
if (credentials && apiKey) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
'[Portal] Provide either `apiKey` or `credentials`, not both.',
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (credentials) {
|
|
79
|
+
return credentials
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (!apiKey) {
|
|
83
|
+
throw new InvalidApiKeyError()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return new StaticCredentials(apiKey)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The SDK's credential boundary: normalizes every failure to
|
|
91
|
+
* `PortalCredentialError`, since a host-supplied `PortalCredentials` can throw
|
|
92
|
+
* anything. A `PortalCredentialError` from the provider passes through
|
|
93
|
+
* untouched so its `reason` is never downgraded.
|
|
94
|
+
*/
|
|
95
|
+
export async function resolveCredentialToken(
|
|
96
|
+
credentials: PortalCredentials,
|
|
97
|
+
): Promise<string> {
|
|
98
|
+
let token: string
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
token = await credentials.getToken()
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (PortalCredentialError.is(error)) {
|
|
104
|
+
throw error
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
throw new PortalCredentialError({
|
|
108
|
+
reason: PortalCredentialErrorReason.ProviderFailure,
|
|
109
|
+
cause: error,
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (!token) {
|
|
114
|
+
throw new PortalCredentialError({
|
|
115
|
+
reason: PortalCredentialErrorReason.Unavailable,
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return token
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Keyed by the credential, not by subsystem, so several requesters 401-ing at
|
|
124
|
+
* once — all of which arrive here through `reportUnauthorized` — share one
|
|
125
|
+
* invalidation instead of each issuing a keychain delete.
|
|
126
|
+
*/
|
|
127
|
+
const invalidations = new WeakMap<PortalCredentials, Promise<void>>()
|
|
128
|
+
|
|
129
|
+
export function invalidateCredentials(
|
|
130
|
+
credentials: PortalCredentials,
|
|
131
|
+
): Promise<void> {
|
|
132
|
+
const inFlight = invalidations.get(credentials)
|
|
133
|
+
|
|
134
|
+
if (inFlight) {
|
|
135
|
+
return inFlight
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// A host-supplied `invalidate()` may throw synchronously or return something
|
|
139
|
+
// that is not a native Promise. Starting from `Promise.resolve()` turns both
|
|
140
|
+
// into a rejection here rather than a throw that escapes before the guard
|
|
141
|
+
// below is registered, which would silently disable deduplication.
|
|
142
|
+
const invalidation = Promise.resolve()
|
|
143
|
+
.then(() => credentials.invalidate())
|
|
144
|
+
.finally(() => {
|
|
145
|
+
invalidations.delete(credentials)
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
invalidations.set(credentials, invalidation)
|
|
149
|
+
|
|
150
|
+
return invalidation
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Host listeners, keyed by the credential rather than by the `Portal` holding
|
|
155
|
+
* it, so they are reachable from the 401 call sites — which see a credential
|
|
156
|
+
* and nothing else — and so a credential that is dropped takes its listeners
|
|
157
|
+
* with it.
|
|
158
|
+
*
|
|
159
|
+
* One entry is one subscription, never one callback: two subscribers may hand
|
|
160
|
+
* in the same function, and an entry keyed on the function itself would
|
|
161
|
+
* collapse them into one that either unsubscribe removes — silently
|
|
162
|
+
* deregistering a subscriber that never asked to be.
|
|
163
|
+
*/
|
|
164
|
+
const invalidationListeners = new WeakMap<PortalCredentials, Set<() => void>>()
|
|
165
|
+
|
|
166
|
+
/** Credentials already announced to the host, so each is reported once. */
|
|
167
|
+
const reported = new WeakSet<PortalCredentials>()
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Subscribes to the backend invalidating `credentials`. Returns an
|
|
171
|
+
* unsubscribe; see `Portal.onSessionInvalidated` for the host-facing contract.
|
|
172
|
+
*
|
|
173
|
+
* A credential can already have been reported before the host gets to
|
|
174
|
+
* subscribe — validity is discovered by making a request, so a host that
|
|
175
|
+
* awaits one before mounting its subscriber would otherwise never hear that
|
|
176
|
+
* the session is over, and nothing else exposes that state.
|
|
177
|
+
*/
|
|
178
|
+
export function onCredentialsInvalidated(
|
|
179
|
+
credentials: PortalCredentials,
|
|
180
|
+
listener: () => void,
|
|
181
|
+
): () => void {
|
|
182
|
+
const listeners = invalidationListeners.get(credentials) ?? new Set()
|
|
183
|
+
// This subscription's identity in `listeners`, distinct from every other
|
|
184
|
+
// subscription of the same `listener` — see the note on that map.
|
|
185
|
+
const subscription = () => listener()
|
|
186
|
+
|
|
187
|
+
listeners.add(subscription)
|
|
188
|
+
invalidationListeners.set(credentials, listeners)
|
|
189
|
+
|
|
190
|
+
// `notifyInvalidated` will not run again for this credential, so catch this
|
|
191
|
+
// subscription up itself. Deferred so the caller holds its unsubscribe
|
|
192
|
+
// before the callback can run, and re-checked then so a subscription
|
|
193
|
+
// dropped straight away stays silent — which is also what keeps a React
|
|
194
|
+
// effect that tears down and remounts within one commit to a single call.
|
|
195
|
+
// A Client API Key never reaches here: it is never recorded as reported.
|
|
196
|
+
if (reported.has(credentials)) {
|
|
197
|
+
void Promise.resolve().then(() => {
|
|
198
|
+
if (!listeners.has(subscription)) {
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
try {
|
|
203
|
+
subscription()
|
|
204
|
+
} catch {
|
|
205
|
+
// As in `notifyInvalidated`: a host callback failing is not this
|
|
206
|
+
// module's problem to propagate.
|
|
207
|
+
}
|
|
208
|
+
})
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return () => {
|
|
212
|
+
listeners.delete(subscription)
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* At most once per credential, and never for a Client API Key: that credential
|
|
218
|
+
* is custodian-owned, its `invalidate()` is a no-op, and there is no local
|
|
219
|
+
* session for a 401 to have ended.
|
|
220
|
+
*/
|
|
221
|
+
function notifyInvalidated(credentials: PortalCredentials): void {
|
|
222
|
+
if (StaticCredentials.is(credentials) || reported.has(credentials)) {
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
reported.add(credentials)
|
|
227
|
+
|
|
228
|
+
// Snapshot: a listener is free to unsubscribe itself, or subscribe another,
|
|
229
|
+
// from inside the callback.
|
|
230
|
+
for (const listener of Array.from(
|
|
231
|
+
invalidationListeners.get(credentials) ?? [],
|
|
232
|
+
)) {
|
|
233
|
+
try {
|
|
234
|
+
listener()
|
|
235
|
+
} catch {
|
|
236
|
+
// A host callback failing must not take the other listeners, the
|
|
237
|
+
// invalidation, or this bookkeeping down with it.
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* The 401 path every Portal-authenticated requester routes through: invalidate
|
|
244
|
+
* the credential, then tell the host its session ended.
|
|
245
|
+
*
|
|
246
|
+
* Kept separate from {@link invalidateCredentials}, which stays the plain
|
|
247
|
+
* operation a host-initiated sign-out uses — only a backend rejection is news
|
|
248
|
+
* to the host.
|
|
249
|
+
*
|
|
250
|
+
* Notifies even when the invalidation rejects: the token is dropped in memory
|
|
251
|
+
* first, so the session is over either way. The rejection still propagates,
|
|
252
|
+
* and every call site already treats it as bookkeeping that must not replace
|
|
253
|
+
* the original failure.
|
|
254
|
+
*/
|
|
255
|
+
export async function reportUnauthorized(
|
|
256
|
+
credentials: PortalCredentials,
|
|
257
|
+
): Promise<void> {
|
|
258
|
+
try {
|
|
259
|
+
await invalidateCredentials(credentials)
|
|
260
|
+
} finally {
|
|
261
|
+
notifyInvalidated(credentials)
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* The MPC equivalent of the 401 path above: the binary issues its own
|
|
267
|
+
* authenticated requests, so a rejected credential arrives as an `AUTH_FAILED`
|
|
268
|
+
* envelope rather than a status code any requester here can see.
|
|
269
|
+
*
|
|
270
|
+
* The binary's error is rethrown unchanged either way — the invalidation is
|
|
271
|
+
* bookkeeping, and callers keep branching on `PortalMpcError` and its `id`. A
|
|
272
|
+
* Policy Engine rejection is promoted to `PortalPolicyError`, a subclass, so
|
|
273
|
+
* that stays true.
|
|
274
|
+
*/
|
|
275
|
+
export async function failFromMpcError(
|
|
276
|
+
credentials: PortalCredentials,
|
|
277
|
+
error: PortalError,
|
|
278
|
+
): Promise<never> {
|
|
279
|
+
if (isMpcAuthFailure(error)) {
|
|
280
|
+
try {
|
|
281
|
+
await reportUnauthorized(credentials)
|
|
282
|
+
} catch (bookkeeping) {
|
|
283
|
+
sdkLogger.error(
|
|
284
|
+
'[Portal] Failed to invalidate a credential the MPC binary rejected',
|
|
285
|
+
bookkeeping,
|
|
286
|
+
)
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
throw mpcErrorFrom(error)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* The raw Client API Key behind a credential, or `''` when it is not a static
|
|
295
|
+
* key — never a wrong or stale token. Temporary bridge for subsystems that
|
|
296
|
+
* need a synchronous `apiKey`.
|
|
297
|
+
*/
|
|
298
|
+
export function staticApiKeyOf(credentials: PortalCredentials): string {
|
|
299
|
+
if (!StaticCredentials.is(credentials)) {
|
|
300
|
+
return ''
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// The brand identifies the shape, it does not prove it: an instance from
|
|
304
|
+
// another copy of this package is only structurally compatible, so re-check
|
|
305
|
+
// the type.
|
|
306
|
+
const { value } = credentials
|
|
307
|
+
|
|
308
|
+
return typeof value === 'string' ? value : ''
|
|
309
|
+
}
|
package/src/definitions/index.ts
CHANGED
|
@@ -48,8 +48,6 @@ import type {
|
|
|
48
48
|
PortalKeychainMetadata,
|
|
49
49
|
Presignature,
|
|
50
50
|
ProgressCallback,
|
|
51
|
-
QuoteArgs,
|
|
52
|
-
QuoteResponse,
|
|
53
51
|
Shares,
|
|
54
52
|
SigningSharePairMetadata,
|
|
55
53
|
SimulateTransactionParam,
|
|
@@ -220,8 +218,36 @@ export interface RawSignOptions {
|
|
|
220
218
|
|
|
221
219
|
export type SigningRequestParams = Eip1559 | LegacyTx
|
|
222
220
|
|
|
221
|
+
/**
|
|
222
|
+
* Supplies the credential `Portal` authenticates its API calls with.
|
|
223
|
+
*
|
|
224
|
+
* This is the entire contract between `Portal` and whatever owns the
|
|
225
|
+
* credential: there is no refresh, no polling, and no observers. A `PortalAuth`
|
|
226
|
+
* session implements it, and so can a host app that manages credentials itself.
|
|
227
|
+
*/
|
|
228
|
+
export interface PortalCredentials {
|
|
229
|
+
/**
|
|
230
|
+
* Resolves the credential to send. Called per request; returning the same
|
|
231
|
+
* value repeatedly is the normal case.
|
|
232
|
+
*/
|
|
233
|
+
getToken(): Promise<string>
|
|
234
|
+
/**
|
|
235
|
+
* Called when the backend rejects the credential with a 401, so a dead token
|
|
236
|
+
* is neither handed out again nor restored on the next launch.
|
|
237
|
+
*/
|
|
238
|
+
invalidate(): Promise<void>
|
|
239
|
+
}
|
|
240
|
+
|
|
223
241
|
export interface IPortalApi {
|
|
242
|
+
/**
|
|
243
|
+
* @deprecated Read the credential through `getToken()` instead.
|
|
244
|
+
*
|
|
245
|
+
* Only populated when the owning `Portal` was constructed with `apiKey`; it
|
|
246
|
+
* is an empty string when it was constructed with `credentials`.
|
|
247
|
+
*/
|
|
224
248
|
apiKey: string
|
|
249
|
+
credentials: PortalCredentials
|
|
250
|
+
getToken(): Promise<string>
|
|
225
251
|
apiUrl: string
|
|
226
252
|
requests: HttpRequester
|
|
227
253
|
buildTransaction(
|
|
@@ -244,15 +270,9 @@ export interface IPortalApi {
|
|
|
244
270
|
getNFTs(chainId?: string, traceId?: string): Promise<NFT[]>
|
|
245
271
|
getNftAssets(chainId: string, traceId?: string): Promise<NFTAsset[]>
|
|
246
272
|
getNetworks(): Promise<Network[]>
|
|
247
|
-
getQuote(
|
|
248
|
-
apiKey: string,
|
|
249
|
-
args: QuoteArgs,
|
|
250
|
-
chainId?: string,
|
|
251
|
-
): Promise<QuoteResponse>
|
|
252
273
|
getSigningSharesMetadata(
|
|
253
274
|
chainId?: string,
|
|
254
275
|
): Promise<SigningSharePairMetadata[]>
|
|
255
|
-
getSources(apiKey: string, chainId?: string): Promise<Record<string, string>>
|
|
256
276
|
getTransactions(
|
|
257
277
|
chainId?: string,
|
|
258
278
|
limit?: number,
|
|
@@ -370,7 +390,14 @@ export interface IPortalConnect {
|
|
|
370
390
|
}
|
|
371
391
|
|
|
372
392
|
export interface IPortalProvider {
|
|
393
|
+
/**
|
|
394
|
+
* @deprecated Read the credential through `credentials.getToken()` instead.
|
|
395
|
+
*
|
|
396
|
+
* Empty when the provider was constructed with `credentials` rather than an
|
|
397
|
+
* `apiKey`.
|
|
398
|
+
*/
|
|
373
399
|
apiKey: string
|
|
400
|
+
credentials: PortalCredentials
|
|
374
401
|
autoApprove: boolean
|
|
375
402
|
chainId?: string
|
|
376
403
|
log: Console
|
package/src/errors/http-error.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
type HttpErrorOptions,
|
|
3
|
+
type JsonObject,
|
|
4
|
+
type JsonValue,
|
|
5
|
+
} from '../../types'
|
|
2
6
|
|
|
3
7
|
class HttpError extends Error {
|
|
4
8
|
/** The HTTP status code that produced this error, so callers can distinguish retryable (5xx) from terminal (4xx) failures. */
|
|
5
9
|
public status: number
|
|
10
|
+
/** The Portal API error message (`error` in the response body), when present. */
|
|
11
|
+
public errorMessage?: string
|
|
12
|
+
/** The stable Portal API error identifier (`id` in the response body), when present. */
|
|
13
|
+
public id?: string
|
|
14
|
+
/** Structured error details (`details` in the response body), when present. */
|
|
15
|
+
public details?: JsonObject
|
|
6
16
|
|
|
7
17
|
constructor({ message, status, statusText }: HttpErrorOptions) {
|
|
8
18
|
super(`${status} - ${statusText}: ${message}`)
|
|
@@ -11,7 +21,36 @@ class HttpError extends Error {
|
|
|
11
21
|
Object.setPrototypeOf(this, HttpError.prototype)
|
|
12
22
|
|
|
13
23
|
this.status = status
|
|
24
|
+
|
|
25
|
+
const body = parseJsonBody(message)
|
|
26
|
+
if (!isJsonObject(body)) {
|
|
27
|
+
return
|
|
28
|
+
}
|
|
29
|
+
if (typeof body.error === 'string') {
|
|
30
|
+
this.errorMessage = body.error
|
|
31
|
+
}
|
|
32
|
+
if (typeof body.id === 'string') {
|
|
33
|
+
this.id = body.id
|
|
34
|
+
}
|
|
35
|
+
if (isJsonObject(body.details)) {
|
|
36
|
+
this.details = body.details
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function parseJsonBody(responseText: string): JsonValue | undefined {
|
|
42
|
+
if (responseText.trim() === '') {
|
|
43
|
+
return undefined
|
|
14
44
|
}
|
|
45
|
+
try {
|
|
46
|
+
return JSON.parse(responseText) as JsonValue
|
|
47
|
+
} catch {
|
|
48
|
+
return undefined
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function isJsonObject(value: JsonValue | undefined): value is JsonObject {
|
|
53
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
15
54
|
}
|
|
16
55
|
|
|
17
56
|
export default HttpError
|
package/src/errors/index.ts
CHANGED
|
@@ -6,7 +6,24 @@ 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 {
|
|
10
|
+
default as PortalAuthError,
|
|
11
|
+
PortalAuthErrorReason,
|
|
12
|
+
type PortalAuthErrorOptions,
|
|
13
|
+
} from './portal-auth-error'
|
|
14
|
+
export {
|
|
15
|
+
default as PortalCredentialError,
|
|
16
|
+
PortalCredentialErrorReason,
|
|
17
|
+
type PortalCredentialErrorOptions,
|
|
18
|
+
} from './portal-credential-error'
|
|
9
19
|
export * from './portal-error'
|
|
20
|
+
export {
|
|
21
|
+
default as PortalPolicyError,
|
|
22
|
+
POLICY_ERROR_ID_PREFIX,
|
|
23
|
+
PolicyErrorId,
|
|
24
|
+
isPolicyViolation,
|
|
25
|
+
mpcErrorFrom,
|
|
26
|
+
} from './portal-policy-error'
|
|
10
27
|
export {
|
|
11
28
|
default as ProviderRpcError,
|
|
12
29
|
RpcErrorCodes,
|