@amadeus-protocol/wallet-sdk 0.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/README.md +73 -0
- package/dist/binary.d.ts +30 -0
- package/dist/binary.d.ts.map +1 -0
- package/dist/binary.js +56 -0
- package/dist/binary.js.map +1 -0
- package/dist/bytes.d.ts +20 -0
- package/dist/bytes.d.ts.map +1 -0
- package/dist/bytes.js +48 -0
- package/dist/bytes.js.map +1 -0
- package/dist/client/injected.d.ts +41 -0
- package/dist/client/injected.d.ts.map +1 -0
- package/dist/client/injected.js +87 -0
- package/dist/client/injected.js.map +1 -0
- package/dist/constants.d.ts +70 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +82 -0
- package/dist/constants.js.map +1 -0
- package/dist/crypto/apikey.d.ts +72 -0
- package/dist/crypto/apikey.d.ts.map +1 -0
- package/dist/crypto/apikey.js +109 -0
- package/dist/crypto/apikey.js.map +1 -0
- package/dist/crypto/bls.d.ts +31 -0
- package/dist/crypto/bls.d.ts.map +1 -0
- package/dist/crypto/bls.js +65 -0
- package/dist/crypto/bls.js.map +1 -0
- package/dist/crypto/box.d.ts +43 -0
- package/dist/crypto/box.d.ts.map +1 -0
- package/dist/crypto/box.js +82 -0
- package/dist/crypto/box.js.map +1 -0
- package/dist/crypto/connect.d.ts +59 -0
- package/dist/crypto/connect.d.ts.map +1 -0
- package/dist/crypto/connect.js +72 -0
- package/dist/crypto/connect.js.map +1 -0
- package/dist/errors.d.ts +10 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +14 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +18 -0
- package/dist/react/index.d.ts +20 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +95 -0
- package/dist/react/index.js.map +1 -0
- package/dist/schema.d.ts +63 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +52 -0
- package/dist/schema.js.map +1 -0
- package/dist/transport/bridge.d.ts +82 -0
- package/dist/transport/bridge.d.ts.map +1 -0
- package/dist/transport/bridge.js +125 -0
- package/dist/transport/bridge.js.map +1 -0
- package/dist/transport/envelope.d.ts +73 -0
- package/dist/transport/envelope.d.ts.map +1 -0
- package/dist/transport/envelope.js +123 -0
- package/dist/transport/envelope.js.map +1 -0
- package/dist/transport/session.d.ts +70 -0
- package/dist/transport/session.d.ts.map +1 -0
- package/dist/transport/session.js +119 -0
- package/dist/transport/session.js.map +1 -0
- package/dist/transport/uri.d.ts +49 -0
- package/dist/transport/uri.d.ts.map +1 -0
- package/dist/transport/uri.js +101 -0
- package/dist/transport/uri.js.map +1 -0
- package/dist/tx.d.ts +42 -0
- package/dist/tx.d.ts.map +1 -0
- package/dist/tx.js +61 -0
- package/dist/tx.js.map +1 -0
- package/dist/types.d.ts +80 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +14 -0
- package/dist/types.js.map +1 -0
- package/dist/wallet/handler.d.ts +18 -0
- package/dist/wallet/handler.d.ts.map +1 -0
- package/dist/wallet/handler.js +79 -0
- package/dist/wallet/handler.js.map +1 -0
- package/package.json +92 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { API_KEY_DST, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, MAX_API_KEY_STRING_LENGTH, NETWORKS, PROTOCOL_VERSION, PROVIDER_EVENTS, PROVIDER_GLOBAL, PUBLIC_KEY_BYTE_LENGTH, SEED_BYTE_LENGTH, SESSION_NONCE_BYTE_LENGTH, SESSION_PUBLIC_KEY_BYTE_LENGTH, SESSION_SECRET_KEY_BYTE_LENGTH, SIGNATURE_BYTE_LENGTH, TX_DST, WALLET_INITIALIZED_EVENT, WALLET_WINDOW_EVENTS } from "./constants.js";
|
|
2
|
+
import { WalletSdkError, WalletSdkErrorCode } from "./errors.js";
|
|
3
|
+
import { bytesToUtf8, concatBytes, equalBytes, randomBytes, randomId, u32be, utf8ToBytes } from "./bytes.js";
|
|
4
|
+
import { BYTES_TAG, TaggedBytes, decodeBinaryValues, describeBinaryValues, encodeBinaryValues, isTaggedBytes } from "./binary.js";
|
|
5
|
+
import { SignTransactionParams, SignedTransaction, SubmitTransactionOptions, signTransaction, submitTransaction } from "./tx.js";
|
|
6
|
+
import { AmadeusEventPayloadMap, AmadeusNetwork, AmadeusProvider, AmadeusProviderEvent, GenerateApiKeyRequest, GenerateApiKeyResponse, SignTransactionRequest, SignTransactionResponse, getAmadeusProvider, isProviderAvailable } from "./types.js";
|
|
7
|
+
import { ConnectTranscriptInput, GenerateApiKeyRequestInput, SignTransactionRequestInput, addressSchema, connectTranscriptSchema, generateApiKeyRequestSchema, networkSchema, originSchema, sessionPublicKeySchema, signTransactionRequestSchema } from "./schema.js";
|
|
8
|
+
import { SignerKeys, deriveSigner, publicKeyFromAddress, signHashed, signatureFromBase58, verifyHashed } from "./crypto/bls.js";
|
|
9
|
+
import { ApiKeyPayload, DecodedApiKey, GenerateApiKeyParams, GenerateApiKeyResult, VerifyApiKeyOptions, VerifyApiKeyResult, decodeApiKey, generateApiKey, verifyApiKey } from "./crypto/apikey.js";
|
|
10
|
+
import { ConnectTranscript, SignConnectParams, VerifyConnectParams, buildConnectTranscript, signConnect, verifyConnect } from "./crypto/connect.js";
|
|
11
|
+
import { SealedEnvelope, SessionKeypair, deriveSharedKey, generateSessionKeypair, open, seal } from "./crypto/box.js";
|
|
12
|
+
import { SeenStore, WALLET_METHODS, WalletMethod, WalletRequest, WalletResponse, createMemorySeenStore, guardRequest, makeRequest, openRequest, openResponse, sealRequest, sealResponse } from "./transport/envelope.js";
|
|
13
|
+
import { ConnectRequestParams, ConnectResponseParams, URI_SCHEME, buildConnectResponseUri, buildConnectUri, parseConnectResponseUri, parseConnectUri } from "./transport/uri.js";
|
|
14
|
+
import { EstablishedSession, PendingConnect, WalletSession, approveConnect, completeConnect, createConnectRequest, isConnectRequestExpired } from "./transport/session.js";
|
|
15
|
+
import { BridgeClient, BridgeClientOptions, BridgeFrame, assertAllowedBridgeUrl, deriveBridgeChannels, deriveConnectChannel } from "./transport/bridge.js";
|
|
16
|
+
import { WalletHandlerContext, handleRequest } from "./wallet/handler.js";
|
|
17
|
+
import { ApiKeyStore, WalletClient, createInjectedWalletClient } from "./client/injected.js";
|
|
18
|
+
export { API_KEY_DST, AmadeusEventPayloadMap, AmadeusNetwork, AmadeusProvider, AmadeusProviderEvent, ApiKeyPayload, ApiKeyStore, BYTES_TAG, BridgeClient, BridgeClientOptions, BridgeFrame, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, ConnectRequestParams, ConnectResponseParams, ConnectTranscript, ConnectTranscriptInput, DecodedApiKey, EstablishedSession, GenerateApiKeyParams, GenerateApiKeyRequest, GenerateApiKeyRequestInput, GenerateApiKeyResponse, GenerateApiKeyResult, MAX_API_KEY_STRING_LENGTH, NETWORKS, PROTOCOL_VERSION, PROVIDER_EVENTS, PROVIDER_GLOBAL, PUBLIC_KEY_BYTE_LENGTH, PendingConnect, SEED_BYTE_LENGTH, SESSION_NONCE_BYTE_LENGTH, SESSION_PUBLIC_KEY_BYTE_LENGTH, SESSION_SECRET_KEY_BYTE_LENGTH, SIGNATURE_BYTE_LENGTH, SealedEnvelope, SeenStore, SessionKeypair, SignConnectParams, SignTransactionParams, SignTransactionRequest, SignTransactionRequestInput, SignTransactionResponse, SignedTransaction, SignerKeys, SubmitTransactionOptions, TX_DST, TaggedBytes, URI_SCHEME, VerifyApiKeyOptions, VerifyApiKeyResult, VerifyConnectParams, WALLET_INITIALIZED_EVENT, WALLET_METHODS, WALLET_WINDOW_EVENTS, WalletClient, WalletHandlerContext, WalletMethod, WalletRequest, WalletResponse, WalletSdkError, WalletSdkErrorCode, WalletSession, addressSchema, approveConnect, assertAllowedBridgeUrl, buildConnectResponseUri, buildConnectTranscript, buildConnectUri, bytesToUtf8, completeConnect, concatBytes, connectTranscriptSchema, createConnectRequest, createInjectedWalletClient, createMemorySeenStore, decodeApiKey, decodeBinaryValues, deriveBridgeChannels, deriveConnectChannel, deriveSharedKey, deriveSigner, describeBinaryValues, encodeBinaryValues, equalBytes, generateApiKey, generateApiKeyRequestSchema, generateSessionKeypair, getAmadeusProvider, guardRequest, handleRequest, isConnectRequestExpired, isProviderAvailable, isTaggedBytes, makeRequest, networkSchema, open, openRequest, openResponse, originSchema, parseConnectResponseUri, parseConnectUri, publicKeyFromAddress, randomBytes, randomId, seal, sealRequest, sealResponse, sessionPublicKeySchema, signConnect, signHashed, signTransaction, signTransactionRequestSchema, signatureFromBase58, submitTransaction, u32be, utf8ToBytes, verifyApiKey, verifyConnect, verifyHashed };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { API_KEY_DST, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, MAX_API_KEY_STRING_LENGTH, NETWORKS, PROTOCOL_VERSION, PROVIDER_EVENTS, PROVIDER_GLOBAL, PUBLIC_KEY_BYTE_LENGTH, SEED_BYTE_LENGTH, SESSION_NONCE_BYTE_LENGTH, SESSION_PUBLIC_KEY_BYTE_LENGTH, SESSION_SECRET_KEY_BYTE_LENGTH, SIGNATURE_BYTE_LENGTH, TX_DST, WALLET_INITIALIZED_EVENT, WALLET_WINDOW_EVENTS } from "./constants.js";
|
|
2
|
+
import { WalletSdkError } from "./errors.js";
|
|
3
|
+
import { bytesToUtf8, concatBytes, equalBytes, randomBytes, randomId, u32be, utf8ToBytes } from "./bytes.js";
|
|
4
|
+
import { BYTES_TAG, decodeBinaryValues, describeBinaryValues, encodeBinaryValues, isTaggedBytes } from "./binary.js";
|
|
5
|
+
import { signTransaction, submitTransaction } from "./tx.js";
|
|
6
|
+
import { getAmadeusProvider, isProviderAvailable } from "./types.js";
|
|
7
|
+
import { addressSchema, connectTranscriptSchema, generateApiKeyRequestSchema, networkSchema, originSchema, sessionPublicKeySchema, signTransactionRequestSchema } from "./schema.js";
|
|
8
|
+
import { deriveSigner, publicKeyFromAddress, signHashed, signatureFromBase58, verifyHashed } from "./crypto/bls.js";
|
|
9
|
+
import { decodeApiKey, generateApiKey, verifyApiKey } from "./crypto/apikey.js";
|
|
10
|
+
import { buildConnectTranscript, signConnect, verifyConnect } from "./crypto/connect.js";
|
|
11
|
+
import { deriveSharedKey, generateSessionKeypair, open, seal } from "./crypto/box.js";
|
|
12
|
+
import { WALLET_METHODS, createMemorySeenStore, guardRequest, makeRequest, openRequest, openResponse, sealRequest, sealResponse } from "./transport/envelope.js";
|
|
13
|
+
import { URI_SCHEME, buildConnectResponseUri, buildConnectUri, parseConnectResponseUri, parseConnectUri } from "./transport/uri.js";
|
|
14
|
+
import { approveConnect, completeConnect, createConnectRequest, isConnectRequestExpired } from "./transport/session.js";
|
|
15
|
+
import { BridgeClient, assertAllowedBridgeUrl, deriveBridgeChannels, deriveConnectChannel } from "./transport/bridge.js";
|
|
16
|
+
import { handleRequest } from "./wallet/handler.js";
|
|
17
|
+
import { createInjectedWalletClient } from "./client/injected.js";
|
|
18
|
+
export { API_KEY_DST, BYTES_TAG, BridgeClient, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, MAX_API_KEY_STRING_LENGTH, NETWORKS, PROTOCOL_VERSION, PROVIDER_EVENTS, PROVIDER_GLOBAL, PUBLIC_KEY_BYTE_LENGTH, SEED_BYTE_LENGTH, SESSION_NONCE_BYTE_LENGTH, SESSION_PUBLIC_KEY_BYTE_LENGTH, SESSION_SECRET_KEY_BYTE_LENGTH, SIGNATURE_BYTE_LENGTH, TX_DST, URI_SCHEME, WALLET_INITIALIZED_EVENT, WALLET_METHODS, WALLET_WINDOW_EVENTS, WalletSdkError, addressSchema, approveConnect, assertAllowedBridgeUrl, buildConnectResponseUri, buildConnectTranscript, buildConnectUri, bytesToUtf8, completeConnect, concatBytes, connectTranscriptSchema, createConnectRequest, createInjectedWalletClient, createMemorySeenStore, decodeApiKey, decodeBinaryValues, deriveBridgeChannels, deriveConnectChannel, deriveSharedKey, deriveSigner, describeBinaryValues, encodeBinaryValues, equalBytes, generateApiKey, generateApiKeyRequestSchema, generateSessionKeypair, getAmadeusProvider, guardRequest, handleRequest, isConnectRequestExpired, isProviderAvailable, isTaggedBytes, makeRequest, networkSchema, open, openRequest, openResponse, originSchema, parseConnectResponseUri, parseConnectUri, publicKeyFromAddress, randomBytes, randomId, seal, sealRequest, sealResponse, sessionPublicKeySchema, signConnect, signHashed, signTransaction, signTransactionRequestSchema, signatureFromBase58, submitTransaction, u32be, utf8ToBytes, verifyApiKey, verifyConnect, verifyHashed };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { SignTransactionRequest, SignTransactionResponse } from "../types.js";
|
|
2
|
+
import { WalletClient } from "../client/injected.js";
|
|
3
|
+
//#region src/react/index.d.ts
|
|
4
|
+
type WalletStatus = 'unavailable' | 'disconnected' | 'connecting' | 'connected';
|
|
5
|
+
interface UseWalletResult {
|
|
6
|
+
client: WalletClient;
|
|
7
|
+
status: WalletStatus;
|
|
8
|
+
account: string | null;
|
|
9
|
+
network: string | null;
|
|
10
|
+
isAvailable: boolean;
|
|
11
|
+
connect: () => Promise<void>;
|
|
12
|
+
disconnect: () => void;
|
|
13
|
+
signTransaction: (request: SignTransactionRequest) => Promise<SignTransactionResponse>;
|
|
14
|
+
signAndSubmit: WalletClient['signAndSubmit'];
|
|
15
|
+
ensureApiKey: WalletClient['ensureApiKey'];
|
|
16
|
+
}
|
|
17
|
+
declare function useWallet(): UseWalletResult;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { UseWalletResult, WalletStatus, useWallet };
|
|
20
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/react/index.ts"],"mappings":";;;KAoBY;UAEK;EAChB,QAAQ;EACR,QAAQ;EACR;EACA;EACA;EACA,eAAe;EACf;EACA,kBAAkB,SAAS,2BAA2B,QAAQ;EAC9D,eAAe;EACf,cAAc;;iBAGC,aAAa"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { WALLET_INITIALIZED_EVENT } from "../constants.js";
|
|
2
|
+
import { createInjectedWalletClient } from "../client/injected.js";
|
|
3
|
+
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
4
|
+
//#region src/react/index.ts
|
|
5
|
+
/**
|
|
6
|
+
* React ergonomics for dApps: a single `useWallet()` hook over the injected
|
|
7
|
+
* provider client. It fixes the `amadeus#initialized` vs `amadeus-wallet#initialized`
|
|
8
|
+
* detection bug once (dApps historically listened for the wrong name) and wires
|
|
9
|
+
* the provider's account/network/disconnect events into state.
|
|
10
|
+
*
|
|
11
|
+
* Imported from the `@amadeus-protocol/wallet-sdk/react` subpath so non-React
|
|
12
|
+
* consumers (the mobile wallet, node verifiers) never pull in React.
|
|
13
|
+
*/
|
|
14
|
+
function useWallet() {
|
|
15
|
+
const client = useMemo(() => createInjectedWalletClient(), []);
|
|
16
|
+
const [status, setStatus] = useState(() => client.isAvailable() ? "disconnected" : "unavailable");
|
|
17
|
+
const [account, setAccount] = useState(null);
|
|
18
|
+
const [network, setNetwork] = useState(null);
|
|
19
|
+
useEffect(() => {
|
|
20
|
+
if (typeof window === "undefined") return;
|
|
21
|
+
const onInit = () => {
|
|
22
|
+
if (client.isAvailable()) setStatus((s) => s === "unavailable" ? "disconnected" : s);
|
|
23
|
+
};
|
|
24
|
+
window.addEventListener(WALLET_INITIALIZED_EVENT, onInit);
|
|
25
|
+
if (client.isAvailable()) {
|
|
26
|
+
client.getAccount().then((a) => {
|
|
27
|
+
if (a) {
|
|
28
|
+
setAccount(a);
|
|
29
|
+
setStatus("connected");
|
|
30
|
+
}
|
|
31
|
+
}).catch(() => {});
|
|
32
|
+
client.getNetwork().then(setNetwork).catch(() => {});
|
|
33
|
+
}
|
|
34
|
+
return () => window.removeEventListener(WALLET_INITIALIZED_EVENT, onInit);
|
|
35
|
+
}, [client]);
|
|
36
|
+
useEffect(() => {
|
|
37
|
+
if (!client.isAvailable()) return;
|
|
38
|
+
const applyAccounts = (accounts) => {
|
|
39
|
+
const next = accounts[0] ?? null;
|
|
40
|
+
setAccount(next);
|
|
41
|
+
setStatus(next ? "connected" : "disconnected");
|
|
42
|
+
};
|
|
43
|
+
const onAccountsChanged = (d) => applyAccounts(d.accounts);
|
|
44
|
+
const onConnect = (d) => {
|
|
45
|
+
applyAccounts(d.accounts);
|
|
46
|
+
setNetwork(d.network);
|
|
47
|
+
};
|
|
48
|
+
const onDisconnect = () => {
|
|
49
|
+
setAccount(null);
|
|
50
|
+
setStatus("disconnected");
|
|
51
|
+
};
|
|
52
|
+
const onNetworkChanged = (d) => setNetwork(d.network);
|
|
53
|
+
client.on("accountsChanged", onAccountsChanged);
|
|
54
|
+
client.on("connect", onConnect);
|
|
55
|
+
client.on("disconnect", onDisconnect);
|
|
56
|
+
client.on("networkChanged", onNetworkChanged);
|
|
57
|
+
return () => {
|
|
58
|
+
client.off("accountsChanged", onAccountsChanged);
|
|
59
|
+
client.off("connect", onConnect);
|
|
60
|
+
client.off("disconnect", onDisconnect);
|
|
61
|
+
client.off("networkChanged", onNetworkChanged);
|
|
62
|
+
};
|
|
63
|
+
}, [client]);
|
|
64
|
+
const connect = useCallback(async () => {
|
|
65
|
+
setStatus("connecting");
|
|
66
|
+
try {
|
|
67
|
+
const a = await client.connect();
|
|
68
|
+
setAccount(a);
|
|
69
|
+
setStatus("connected");
|
|
70
|
+
} catch (error) {
|
|
71
|
+
setStatus(client.isAvailable() ? "disconnected" : "unavailable");
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}, [client]);
|
|
75
|
+
const disconnect = useCallback(() => {
|
|
76
|
+
setAccount(null);
|
|
77
|
+
setStatus("disconnected");
|
|
78
|
+
}, []);
|
|
79
|
+
return {
|
|
80
|
+
client,
|
|
81
|
+
status,
|
|
82
|
+
account,
|
|
83
|
+
network,
|
|
84
|
+
isAvailable: client.isAvailable(),
|
|
85
|
+
connect,
|
|
86
|
+
disconnect,
|
|
87
|
+
signTransaction: client.signTransaction,
|
|
88
|
+
signAndSubmit: client.signAndSubmit,
|
|
89
|
+
ensureApiKey: client.ensureApiKey
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
export { useWallet };
|
|
94
|
+
|
|
95
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/react/index.ts"],"sourcesContent":["/**\n * React ergonomics for dApps: a single `useWallet()` hook over the injected\n * provider client. It fixes the `amadeus#initialized` vs `amadeus-wallet#initialized`\n * detection bug once (dApps historically listened for the wrong name) and wires\n * the provider's account/network/disconnect events into state.\n *\n * Imported from the `@amadeus-protocol/wallet-sdk/react` subpath so non-React\n * consumers (the mobile wallet, node verifiers) never pull in React.\n */\n\nimport { useCallback, useEffect, useMemo, useState } from 'react'\n\nimport { createInjectedWalletClient, type WalletClient } from '../client/injected'\nimport { WALLET_INITIALIZED_EVENT } from '../constants'\nimport type {\n\tAmadeusEventPayloadMap,\n\tSignTransactionRequest,\n\tSignTransactionResponse\n} from '../types'\n\nexport type WalletStatus = 'unavailable' | 'disconnected' | 'connecting' | 'connected'\n\nexport interface UseWalletResult {\n\tclient: WalletClient\n\tstatus: WalletStatus\n\taccount: string | null\n\tnetwork: string | null\n\tisAvailable: boolean\n\tconnect: () => Promise<void>\n\tdisconnect: () => void\n\tsignTransaction: (request: SignTransactionRequest) => Promise<SignTransactionResponse>\n\tsignAndSubmit: WalletClient['signAndSubmit']\n\tensureApiKey: WalletClient['ensureApiKey']\n}\n\nexport function useWallet(): UseWalletResult {\n\tconst client = useMemo(() => createInjectedWalletClient(), [])\n\tconst [status, setStatus] = useState<WalletStatus>(() =>\n\t\tclient.isAvailable() ? 'disconnected' : 'unavailable'\n\t)\n\tconst [account, setAccount] = useState<string | null>(null)\n\tconst [network, setNetwork] = useState<string | null>(null)\n\n\t// Detect a (possibly late-injected) provider, then read initial account/network.\n\tuseEffect(() => {\n\t\tif (typeof window === 'undefined') return\n\t\tconst onInit = () => {\n\t\t\tif (client.isAvailable()) setStatus((s) => (s === 'unavailable' ? 'disconnected' : s))\n\t\t}\n\t\twindow.addEventListener(WALLET_INITIALIZED_EVENT, onInit)\n\t\tif (client.isAvailable()) {\n\t\t\tclient\n\t\t\t\t.getAccount()\n\t\t\t\t.then((a) => {\n\t\t\t\t\tif (a) {\n\t\t\t\t\t\tsetAccount(a)\n\t\t\t\t\t\tsetStatus('connected')\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch(() => {})\n\t\t\tclient\n\t\t\t\t.getNetwork()\n\t\t\t\t.then(setNetwork)\n\t\t\t\t.catch(() => {})\n\t\t}\n\t\treturn () => window.removeEventListener(WALLET_INITIALIZED_EVENT, onInit)\n\t}, [client])\n\n\t// Mirror provider events into state.\n\tuseEffect(() => {\n\t\tif (!client.isAvailable()) return\n\t\tconst applyAccounts = (accounts: string[]) => {\n\t\t\tconst next = accounts[0] ?? null\n\t\t\tsetAccount(next)\n\t\t\tsetStatus(next ? 'connected' : 'disconnected')\n\t\t}\n\t\tconst onAccountsChanged = (d: AmadeusEventPayloadMap['accountsChanged']) =>\n\t\t\tapplyAccounts(d.accounts)\n\t\tconst onConnect = (d: AmadeusEventPayloadMap['connect']) => {\n\t\t\tapplyAccounts(d.accounts)\n\t\t\tsetNetwork(d.network)\n\t\t}\n\t\tconst onDisconnect = () => {\n\t\t\tsetAccount(null)\n\t\t\tsetStatus('disconnected')\n\t\t}\n\t\tconst onNetworkChanged = (d: AmadeusEventPayloadMap['networkChanged']) =>\n\t\t\tsetNetwork(d.network)\n\n\t\tclient.on('accountsChanged', onAccountsChanged)\n\t\tclient.on('connect', onConnect)\n\t\tclient.on('disconnect', onDisconnect)\n\t\tclient.on('networkChanged', onNetworkChanged)\n\t\treturn () => {\n\t\t\tclient.off('accountsChanged', onAccountsChanged)\n\t\t\tclient.off('connect', onConnect)\n\t\t\tclient.off('disconnect', onDisconnect)\n\t\t\tclient.off('networkChanged', onNetworkChanged)\n\t\t}\n\t}, [client])\n\n\tconst connect = useCallback(async () => {\n\t\tsetStatus('connecting')\n\t\ttry {\n\t\t\tconst a = await client.connect()\n\t\t\tsetAccount(a)\n\t\t\tsetStatus('connected')\n\t\t} catch (error) {\n\t\t\tsetStatus(client.isAvailable() ? 'disconnected' : 'unavailable')\n\t\t\tthrow error\n\t\t}\n\t}, [client])\n\n\tconst disconnect = useCallback(() => {\n\t\tsetAccount(null)\n\t\tsetStatus('disconnected')\n\t}, [])\n\n\treturn {\n\t\tclient,\n\t\tstatus,\n\t\taccount,\n\t\tnetwork,\n\t\tisAvailable: client.isAvailable(),\n\t\tconnect,\n\t\tdisconnect,\n\t\tsignTransaction: client.signTransaction,\n\t\tsignAndSubmit: client.signAndSubmit,\n\t\tensureApiKey: client.ensureApiKey\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAmCA,SAAgB,YAA6B;CAC5C,MAAM,SAAS,cAAc,2BAA2B,GAAG,CAAC,CAAC;CAC7D,MAAM,CAAC,QAAQ,aAAa,eAC3B,OAAO,YAAY,IAAI,iBAAiB,aACzC;CACA,MAAM,CAAC,SAAS,cAAc,SAAwB,IAAI;CAC1D,MAAM,CAAC,SAAS,cAAc,SAAwB,IAAI;CAG1D,gBAAgB;EACf,IAAI,OAAO,WAAW,aAAa;EACnC,MAAM,eAAe;GACpB,IAAI,OAAO,YAAY,GAAG,WAAW,MAAO,MAAM,gBAAgB,iBAAiB,CAAE;EACtF;EACA,OAAO,iBAAiB,0BAA0B,MAAM;EACxD,IAAI,OAAO,YAAY,GAAG;GACzB,OACE,WAAW,CAAC,CACZ,MAAM,MAAM;IACZ,IAAI,GAAG;KACN,WAAW,CAAC;KACZ,UAAU,WAAW;IACtB;GACD,CAAC,CAAC,CACD,YAAY,CAAC,CAAC;GAChB,OACE,WAAW,CAAC,CACZ,KAAK,UAAU,CAAC,CAChB,YAAY,CAAC,CAAC;EACjB;EACA,aAAa,OAAO,oBAAoB,0BAA0B,MAAM;CACzE,GAAG,CAAC,MAAM,CAAC;CAGX,gBAAgB;EACf,IAAI,CAAC,OAAO,YAAY,GAAG;EAC3B,MAAM,iBAAiB,aAAuB;GAC7C,MAAM,OAAO,SAAS,MAAM;GAC5B,WAAW,IAAI;GACf,UAAU,OAAO,cAAc,cAAc;EAC9C;EACA,MAAM,qBAAqB,MAC1B,cAAc,EAAE,QAAQ;EACzB,MAAM,aAAa,MAAyC;GAC3D,cAAc,EAAE,QAAQ;GACxB,WAAW,EAAE,OAAO;EACrB;EACA,MAAM,qBAAqB;GAC1B,WAAW,IAAI;GACf,UAAU,cAAc;EACzB;EACA,MAAM,oBAAoB,MACzB,WAAW,EAAE,OAAO;EAErB,OAAO,GAAG,mBAAmB,iBAAiB;EAC9C,OAAO,GAAG,WAAW,SAAS;EAC9B,OAAO,GAAG,cAAc,YAAY;EACpC,OAAO,GAAG,kBAAkB,gBAAgB;EAC5C,aAAa;GACZ,OAAO,IAAI,mBAAmB,iBAAiB;GAC/C,OAAO,IAAI,WAAW,SAAS;GAC/B,OAAO,IAAI,cAAc,YAAY;GACrC,OAAO,IAAI,kBAAkB,gBAAgB;EAC9C;CACD,GAAG,CAAC,MAAM,CAAC;CAEX,MAAM,UAAU,YAAY,YAAY;EACvC,UAAU,YAAY;EACtB,IAAI;GACH,MAAM,IAAI,MAAM,OAAO,QAAQ;GAC/B,WAAW,CAAC;GACZ,UAAU,WAAW;EACtB,SAAS,OAAO;GACf,UAAU,OAAO,YAAY,IAAI,iBAAiB,aAAa;GAC/D,MAAM;EACP;CACD,GAAG,CAAC,MAAM,CAAC;CAEX,MAAM,aAAa,kBAAkB;EACpC,WAAW,IAAI;EACf,UAAU,cAAc;CACzB,GAAG,CAAC,CAAC;CAEL,OAAO;EACN;EACA;EACA;EACA;EACA,aAAa,OAAO,YAAY;EAChC;EACA;EACA,iBAAiB,OAAO;EACxB,eAAe,OAAO;EACtB,cAAc,OAAO;CACtB;AACD"}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region src/schema.d.ts
|
|
3
|
+
/** http(s) origin, matching the extension's `originSchema`. */
|
|
4
|
+
declare const originSchema: z.ZodEffects<z.ZodString, string, string>;
|
|
5
|
+
/** A Base58 string that decodes to a 48-byte Amadeus public key / address. */
|
|
6
|
+
declare const addressSchema: z.ZodEffects<z.ZodString, string, string>;
|
|
7
|
+
/** A Base58 string that decodes to a 32-byte x25519 session public key. */
|
|
8
|
+
declare const sessionPublicKeySchema: z.ZodEffects<z.ZodString, string, string>;
|
|
9
|
+
declare const networkSchema: z.ZodEnum<["mainnet", "testnet", "custom"]>;
|
|
10
|
+
/** `signTransaction` params — mirrors `ExternalSignRequestMessageSchema`. */
|
|
11
|
+
declare const signTransactionRequestSchema: z.ZodObject<{
|
|
12
|
+
contract: z.ZodString;
|
|
13
|
+
method: z.ZodString;
|
|
14
|
+
args: z.ZodArray<z.ZodUnknown, "many">;
|
|
15
|
+
description: z.ZodOptional<z.ZodString>;
|
|
16
|
+
}, "strip", z.ZodTypeAny, {
|
|
17
|
+
contract: string;
|
|
18
|
+
method: string;
|
|
19
|
+
args: unknown[];
|
|
20
|
+
description?: string | undefined;
|
|
21
|
+
}, {
|
|
22
|
+
contract: string;
|
|
23
|
+
method: string;
|
|
24
|
+
args: unknown[];
|
|
25
|
+
description?: string | undefined;
|
|
26
|
+
}>;
|
|
27
|
+
/** `generateApiKey` params — mirrors `ExternalApiKeyRequestMessageSchema`. */
|
|
28
|
+
declare const generateApiKeyRequestSchema: z.ZodObject<{
|
|
29
|
+
aud: z.ZodString;
|
|
30
|
+
exp_in: z.ZodNumber;
|
|
31
|
+
}, "strip", z.ZodTypeAny, {
|
|
32
|
+
aud: string;
|
|
33
|
+
exp_in: number;
|
|
34
|
+
}, {
|
|
35
|
+
aud: string;
|
|
36
|
+
exp_in: number;
|
|
37
|
+
}>;
|
|
38
|
+
/** The connect transcript fields carried by a deep link / QR payload. */
|
|
39
|
+
declare const connectTranscriptSchema: z.ZodObject<{
|
|
40
|
+
origin: z.ZodEffects<z.ZodString, string, string>;
|
|
41
|
+
dappPublicKey: z.ZodEffects<z.ZodString, string, string>;
|
|
42
|
+
walletPublicKey: z.ZodEffects<z.ZodString, string, string>;
|
|
43
|
+
challenge: z.ZodString;
|
|
44
|
+
requestId: z.ZodString;
|
|
45
|
+
}, "strip", z.ZodTypeAny, {
|
|
46
|
+
origin: string;
|
|
47
|
+
dappPublicKey: string;
|
|
48
|
+
walletPublicKey: string;
|
|
49
|
+
challenge: string;
|
|
50
|
+
requestId: string;
|
|
51
|
+
}, {
|
|
52
|
+
origin: string;
|
|
53
|
+
dappPublicKey: string;
|
|
54
|
+
walletPublicKey: string;
|
|
55
|
+
challenge: string;
|
|
56
|
+
requestId: string;
|
|
57
|
+
}>;
|
|
58
|
+
type SignTransactionRequestInput = z.infer<typeof signTransactionRequestSchema>;
|
|
59
|
+
type GenerateApiKeyRequestInput = z.infer<typeof generateApiKeyRequestSchema>;
|
|
60
|
+
type ConnectTranscriptInput = z.infer<typeof connectTranscriptSchema>;
|
|
61
|
+
//#endregion
|
|
62
|
+
export { ConnectTranscriptInput, GenerateApiKeyRequestInput, SignTransactionRequestInput, addressSchema, connectTranscriptSchema, generateApiKeyRequestSchema, networkSchema, originSchema, sessionPublicKeySchema, signTransactionRequestSchema };
|
|
63
|
+
//# sourceMappingURL=schema.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.d.ts","names":[],"sources":["../src/schema.ts"],"mappings":";;;cA4Ba,cAAY,EAAA,WAAA,EAAA;;cAKZ,eAAa,EAAA,WAAA,EAAA;;cAGb,wBAAsB,EAAA,WAAA,EAAA;cAKtB,eAAa,EAAA;;cAGb,8BAA4B,EAAA;;;;;;;;;;;;;;;;;cAQ5B,6BAA2B,EAAA;;;;;;;;;;;cAM3B,yBAAuB,EAAA;;;;;;;;;;;;;;;;;;;KAQxB,8BAA8B,EAAE,aAAa;KAC7C,6BAA6B,EAAE,aAAa;KAC5C,yBAAyB,EAAE,aAAa"}
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { NETWORKS } from "./constants.js";
|
|
2
|
+
import { fromBase58 } from "@amadeus-protocol/sdk";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
//#region src/schema.ts
|
|
5
|
+
/**
|
|
6
|
+
* Runtime validation for untrusted wire input (deep links, QR payloads, bridge
|
|
7
|
+
* frames, cross-origin messages). Validate BEFORE any request is shown for
|
|
8
|
+
* approval or signed. Zod is used here because it is already the schema library
|
|
9
|
+
* on the wallet + dApp side; the lower-level SDK uses `effect` internally, which
|
|
10
|
+
* is intentionally not a dependency of this package.
|
|
11
|
+
*/
|
|
12
|
+
/** A Base58 string that decodes to exactly `length` bytes. */
|
|
13
|
+
function base58OfLength(length, label) {
|
|
14
|
+
return z.string().refine((v) => {
|
|
15
|
+
try {
|
|
16
|
+
return fromBase58(v).length === length;
|
|
17
|
+
} catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}, { message: `${label} must decode to ${length} bytes` });
|
|
21
|
+
}
|
|
22
|
+
/** http(s) origin, matching the extension's `originSchema`. */
|
|
23
|
+
const originSchema = z.string().refine((v) => /^https?:\/\//.test(v), { message: "origin must be an http(s) URL" });
|
|
24
|
+
/** A Base58 string that decodes to a 48-byte Amadeus public key / address. */
|
|
25
|
+
const addressSchema = base58OfLength(48, "address");
|
|
26
|
+
/** A Base58 string that decodes to a 32-byte x25519 session public key. */
|
|
27
|
+
const sessionPublicKeySchema = base58OfLength(32, "session public key");
|
|
28
|
+
const networkSchema = z.enum(NETWORKS);
|
|
29
|
+
/** `signTransaction` params — mirrors `ExternalSignRequestMessageSchema`. */
|
|
30
|
+
const signTransactionRequestSchema = z.object({
|
|
31
|
+
contract: z.string().min(1),
|
|
32
|
+
method: z.string().min(1),
|
|
33
|
+
args: z.array(z.unknown()),
|
|
34
|
+
description: z.string().optional()
|
|
35
|
+
});
|
|
36
|
+
/** `generateApiKey` params — mirrors `ExternalApiKeyRequestMessageSchema`. */
|
|
37
|
+
const generateApiKeyRequestSchema = z.object({
|
|
38
|
+
aud: z.string().min(1),
|
|
39
|
+
exp_in: z.number().int().positive()
|
|
40
|
+
});
|
|
41
|
+
/** The connect transcript fields carried by a deep link / QR payload. */
|
|
42
|
+
const connectTranscriptSchema = z.object({
|
|
43
|
+
origin: originSchema,
|
|
44
|
+
dappPublicKey: sessionPublicKeySchema,
|
|
45
|
+
walletPublicKey: sessionPublicKeySchema,
|
|
46
|
+
challenge: z.string().min(1),
|
|
47
|
+
requestId: z.string().min(1)
|
|
48
|
+
});
|
|
49
|
+
//#endregion
|
|
50
|
+
export { addressSchema, connectTranscriptSchema, generateApiKeyRequestSchema, networkSchema, originSchema, sessionPublicKeySchema, signTransactionRequestSchema };
|
|
51
|
+
|
|
52
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.js","names":[],"sources":["../src/schema.ts"],"sourcesContent":["/**\n * Runtime validation for untrusted wire input (deep links, QR payloads, bridge\n * frames, cross-origin messages). Validate BEFORE any request is shown for\n * approval or signed. Zod is used here because it is already the schema library\n * on the wallet + dApp side; the lower-level SDK uses `effect` internally, which\n * is intentionally not a dependency of this package.\n */\n\nimport { fromBase58 } from '@amadeus-protocol/sdk'\nimport { z } from 'zod'\n\nimport { NETWORKS, PUBLIC_KEY_BYTE_LENGTH, SESSION_PUBLIC_KEY_BYTE_LENGTH } from './constants'\n\n/** A Base58 string that decodes to exactly `length` bytes. */\nfunction base58OfLength(length: number, label: string) {\n\treturn z.string().refine(\n\t\t(v) => {\n\t\t\ttry {\n\t\t\t\treturn fromBase58(v).length === length\n\t\t\t} catch {\n\t\t\t\treturn false\n\t\t\t}\n\t\t},\n\t\t{ message: `${label} must decode to ${length} bytes` }\n\t)\n}\n\n/** http(s) origin, matching the extension's `originSchema`. */\nexport const originSchema = z\n\t.string()\n\t.refine((v) => /^https?:\\/\\//.test(v), { message: 'origin must be an http(s) URL' })\n\n/** A Base58 string that decodes to a 48-byte Amadeus public key / address. */\nexport const addressSchema = base58OfLength(PUBLIC_KEY_BYTE_LENGTH, 'address')\n\n/** A Base58 string that decodes to a 32-byte x25519 session public key. */\nexport const sessionPublicKeySchema = base58OfLength(\n\tSESSION_PUBLIC_KEY_BYTE_LENGTH,\n\t'session public key'\n)\n\nexport const networkSchema = z.enum(NETWORKS)\n\n/** `signTransaction` params — mirrors `ExternalSignRequestMessageSchema`. */\nexport const signTransactionRequestSchema = z.object({\n\tcontract: z.string().min(1),\n\tmethod: z.string().min(1),\n\targs: z.array(z.unknown()),\n\tdescription: z.string().optional()\n})\n\n/** `generateApiKey` params — mirrors `ExternalApiKeyRequestMessageSchema`. */\nexport const generateApiKeyRequestSchema = z.object({\n\taud: z.string().min(1),\n\texp_in: z.number().int().positive()\n})\n\n/** The connect transcript fields carried by a deep link / QR payload. */\nexport const connectTranscriptSchema = z.object({\n\torigin: originSchema,\n\tdappPublicKey: sessionPublicKeySchema,\n\twalletPublicKey: sessionPublicKeySchema,\n\tchallenge: z.string().min(1),\n\trequestId: z.string().min(1)\n})\n\nexport type SignTransactionRequestInput = z.infer<typeof signTransactionRequestSchema>\nexport type GenerateApiKeyRequestInput = z.infer<typeof generateApiKeyRequestSchema>\nexport type ConnectTranscriptInput = z.infer<typeof connectTranscriptSchema>\n"],"mappings":";;;;;;;;;;;;AAcA,SAAS,eAAe,QAAgB,OAAe;CACtD,OAAO,EAAE,OAAO,CAAC,CAAC,QAChB,MAAM;EACN,IAAI;GACH,OAAO,WAAW,CAAC,CAAC,CAAC,WAAW;EACjC,QAAQ;GACP,OAAO;EACR;CACD,GACA,EAAE,SAAS,GAAG,MAAM,kBAAkB,OAAO,QAAQ,CACtD;AACD;;AAGA,MAAa,eAAe,EAC1B,OAAO,CAAC,CACR,QAAQ,MAAM,eAAe,KAAK,CAAC,GAAG,EAAE,SAAS,gCAAgC,CAAC;;AAGpF,MAAa,gBAAgB,eAAA,IAAuC,SAAS;;AAG7E,MAAa,yBAAyB,eAAA,IAErC,oBACD;AAEA,MAAa,gBAAgB,EAAE,KAAK,QAAQ;;AAG5C,MAAa,+BAA+B,EAAE,OAAO;CACpD,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CAC1B,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACxB,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC;CACzB,aAAa,EAAE,OAAO,CAAC,CAAC,SAAS;AAClC,CAAC;;AAGD,MAAa,8BAA8B,EAAE,OAAO;CACnD,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACrB,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;AACnC,CAAC;;AAGD,MAAa,0BAA0B,EAAE,OAAO;CAC/C,QAAQ;CACR,eAAe;CACf,iBAAiB;CACjB,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CAC3B,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;AAC5B,CAAC"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
//#region src/transport/bridge.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Client for the cross-device relay ("bridge"). After the connect handshake both
|
|
4
|
+
* sides hold a shared key; from it they derive TWO SECRET channel ids (one per
|
|
5
|
+
* direction) via `deriveBridgeChannels`. Each side listens on one channel and
|
|
6
|
+
* sends on the other. Because the channel ids are derived from the shared key —
|
|
7
|
+
* NOT from the public session keys — a third party who only observes the connect
|
|
8
|
+
* handshake cannot address, drain, or flood a session's channels. The relay stays
|
|
9
|
+
* dumb and untrusted: it only moves sealed ciphertext between opaque channel ids.
|
|
10
|
+
*
|
|
11
|
+
* Transport is long-polling over `fetch` — universal across Node, browsers, and
|
|
12
|
+
* React Native (no EventSource/streaming dependency).
|
|
13
|
+
*/
|
|
14
|
+
interface BridgeFrame {
|
|
15
|
+
/** Sender channel (informational). */
|
|
16
|
+
from: string;
|
|
17
|
+
/** Recipient channel id this frame is addressed to. */
|
|
18
|
+
to: string;
|
|
19
|
+
/** Unique frame id (also the request/response id) — for dedupe. */
|
|
20
|
+
id: string;
|
|
21
|
+
/**
|
|
22
|
+
* The JSON payload. Post-connect this is a sealed (E2E-encrypted) envelope;
|
|
23
|
+
* the ONE exception is the connect response (public handshake data, integrity
|
|
24
|
+
* protected by the connect signature) sent on the connect channel before a
|
|
25
|
+
* shared key exists.
|
|
26
|
+
*/
|
|
27
|
+
payload: unknown;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Derive the two per-direction secret channel ids from the session shared key.
|
|
31
|
+
* Both sides compute the same pair; a third party without the shared key cannot.
|
|
32
|
+
*/
|
|
33
|
+
declare function deriveBridgeChannels(sharedKey: Uint8Array): {
|
|
34
|
+
/** Channel the wallet listens on / the dApp sends to. */
|
|
35
|
+
toWallet: string;
|
|
36
|
+
/** Channel the dApp listens on / the wallet sends to. */
|
|
37
|
+
toDapp: string;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Channel the dApp listens on for the CONNECT RESPONSE (cross-device / QR), before
|
|
41
|
+
* a shared key exists. Derived from the dApp's PUBLIC session key (which is in the
|
|
42
|
+
* connect QR), so the dApp can listen for it immediately. The response carried
|
|
43
|
+
* here is public handshake data whose integrity is verified by the connect
|
|
44
|
+
* signature (`verifyConnect`), so a forged response is rejected.
|
|
45
|
+
*/
|
|
46
|
+
declare function deriveConnectChannel(dappPublicKeyBase58: string): string;
|
|
47
|
+
/**
|
|
48
|
+
* Reject a bridge URL that isn't https (http is allowed only for localhost dev).
|
|
49
|
+
* Blocks the wallet being pointed at file://, internal http hosts, or other
|
|
50
|
+
* SSRF/forced-beacon targets by an attacker-supplied connect link.
|
|
51
|
+
*/
|
|
52
|
+
declare function assertAllowedBridgeUrl(url: string): void;
|
|
53
|
+
interface BridgeClientOptions {
|
|
54
|
+
/** Relay base URL, e.g. "https://bridge.ama.one". */
|
|
55
|
+
bridgeUrl: string;
|
|
56
|
+
/** This side's channel id to listen on (from `deriveBridgeChannels`). */
|
|
57
|
+
clientId: string;
|
|
58
|
+
/** Override fetch (tests / non-standard runtimes). */
|
|
59
|
+
fetchImpl?: typeof fetch;
|
|
60
|
+
/** How long the relay holds a long-poll before returning empty (seconds). */
|
|
61
|
+
pollWaitSeconds?: number;
|
|
62
|
+
}
|
|
63
|
+
declare class BridgeClient {
|
|
64
|
+
private readonly bridgeUrl;
|
|
65
|
+
private readonly clientId;
|
|
66
|
+
private readonly fetchImpl;
|
|
67
|
+
private readonly pollWaitSeconds;
|
|
68
|
+
constructor(options: BridgeClientOptions);
|
|
69
|
+
/** Send a frame (sealed envelope, or plaintext connect response) to a channel id. */
|
|
70
|
+
send(to: string, id: string, payload: unknown): Promise<void>;
|
|
71
|
+
/**
|
|
72
|
+
* Start long-polling for frames on this client's channel. Returns a `stop()`
|
|
73
|
+
* function. `onFrame` is invoked per received frame; transient errors go to
|
|
74
|
+
* `onError` (if given) and the loop retries after a short backoff. Each poll
|
|
75
|
+
* has a hard timeout and a response-size cap so a hostile/hung relay can't
|
|
76
|
+
* stall the loop or exhaust memory.
|
|
77
|
+
*/
|
|
78
|
+
start(onFrame: (frame: BridgeFrame) => void | Promise<void>, onError?: (error: unknown) => void): () => void;
|
|
79
|
+
}
|
|
80
|
+
//#endregion
|
|
81
|
+
export { BridgeClient, BridgeClientOptions, BridgeFrame, assertAllowedBridgeUrl, deriveBridgeChannels, deriveConnectChannel };
|
|
82
|
+
//# sourceMappingURL=bridge.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bridge.d.ts","names":[],"sources":["../../src/transport/bridge.ts"],"mappings":";;;;;;;;;;;;;UAsBiB;;EAEhB;;EAEA;;EAEA;;;;;;;EAOA;;;;;;iBAOe,qBAAqB,WAAW;;EAE/C;;EAEA;;;;;;;;;iBAgBe,qBAAqB;;;;;;iBAarB,uBAAuB;UAetB;;EAEhB;;EAEA;;EAEA,mBAAmB;;EAEnB;;cAGY;mBACK;mBACA;mBACA;mBACA;cAEL,SAAS;;EASf,KAAK,YAAY,YAAY,mBAAmB;;;;;;;;EAmBtD,MACC,UAAU,OAAO,uBAAuB,eACxC,WAAW"}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { WalletSdkError } from "../errors.js";
|
|
2
|
+
import { concatBytes, utf8ToBytes } from "../bytes.js";
|
|
3
|
+
import { fromBase58, toBase58 } from "@amadeus-protocol/sdk";
|
|
4
|
+
import { sha256 } from "@noble/hashes/sha2";
|
|
5
|
+
//#region src/transport/bridge.ts
|
|
6
|
+
/**
|
|
7
|
+
* Client for the cross-device relay ("bridge"). After the connect handshake both
|
|
8
|
+
* sides hold a shared key; from it they derive TWO SECRET channel ids (one per
|
|
9
|
+
* direction) via `deriveBridgeChannels`. Each side listens on one channel and
|
|
10
|
+
* sends on the other. Because the channel ids are derived from the shared key —
|
|
11
|
+
* NOT from the public session keys — a third party who only observes the connect
|
|
12
|
+
* handshake cannot address, drain, or flood a session's channels. The relay stays
|
|
13
|
+
* dumb and untrusted: it only moves sealed ciphertext between opaque channel ids.
|
|
14
|
+
*
|
|
15
|
+
* Transport is long-polling over `fetch` — universal across Node, browsers, and
|
|
16
|
+
* React Native (no EventSource/streaming dependency).
|
|
17
|
+
*/
|
|
18
|
+
/** Max bytes we will read from a (possibly hostile) relay response. */
|
|
19
|
+
const MAX_POLL_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
20
|
+
/**
|
|
21
|
+
* Derive the two per-direction secret channel ids from the session shared key.
|
|
22
|
+
* Both sides compute the same pair; a third party without the shared key cannot.
|
|
23
|
+
*/
|
|
24
|
+
function deriveBridgeChannels(sharedKey) {
|
|
25
|
+
const channel = (label) => toBase58(sha256(concatBytes(utf8ToBytes(label), sharedKey)));
|
|
26
|
+
return {
|
|
27
|
+
toWallet: channel("amadeus-bridge/to-wallet/v1"),
|
|
28
|
+
toDapp: channel("amadeus-bridge/to-dapp/v1")
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Channel the dApp listens on for the CONNECT RESPONSE (cross-device / QR), before
|
|
33
|
+
* a shared key exists. Derived from the dApp's PUBLIC session key (which is in the
|
|
34
|
+
* connect QR), so the dApp can listen for it immediately. The response carried
|
|
35
|
+
* here is public handshake data whose integrity is verified by the connect
|
|
36
|
+
* signature (`verifyConnect`), so a forged response is rejected.
|
|
37
|
+
*/
|
|
38
|
+
function deriveConnectChannel(dappPublicKeyBase58) {
|
|
39
|
+
return toBase58(sha256(concatBytes(utf8ToBytes("amadeus-bridge/connect/v1"), fromBase58(dappPublicKeyBase58))));
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Reject a bridge URL that isn't https (http is allowed only for localhost dev).
|
|
43
|
+
* Blocks the wallet being pointed at file://, internal http hosts, or other
|
|
44
|
+
* SSRF/forced-beacon targets by an attacker-supplied connect link.
|
|
45
|
+
*/
|
|
46
|
+
function assertAllowedBridgeUrl(url) {
|
|
47
|
+
const match = /^([a-z][a-z0-9+.-]*):\/\/([^/:?#]+)/i.exec(url);
|
|
48
|
+
if (!match) throw new WalletSdkError("INVALID_ARGUMENT", "bridge URL is not a valid absolute URL");
|
|
49
|
+
const scheme = match[1].toLowerCase();
|
|
50
|
+
const host = match[2].toLowerCase();
|
|
51
|
+
if (scheme === "https" || scheme === "http" && (host === "localhost" || host === "127.0.0.1" || host === "::1")) return;
|
|
52
|
+
throw new WalletSdkError("INVALID_ARGUMENT", "bridge URL must be https (http allowed only for localhost)");
|
|
53
|
+
}
|
|
54
|
+
var BridgeClient = class {
|
|
55
|
+
bridgeUrl;
|
|
56
|
+
clientId;
|
|
57
|
+
fetchImpl;
|
|
58
|
+
pollWaitSeconds;
|
|
59
|
+
constructor(options) {
|
|
60
|
+
assertAllowedBridgeUrl(options.bridgeUrl);
|
|
61
|
+
this.bridgeUrl = options.bridgeUrl.replace(/\/$/, "");
|
|
62
|
+
this.clientId = options.clientId;
|
|
63
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
64
|
+
this.pollWaitSeconds = options.pollWaitSeconds ?? 25;
|
|
65
|
+
}
|
|
66
|
+
/** Send a frame (sealed envelope, or plaintext connect response) to a channel id. */
|
|
67
|
+
async send(to, id, payload) {
|
|
68
|
+
const frame = {
|
|
69
|
+
from: this.clientId,
|
|
70
|
+
to,
|
|
71
|
+
id,
|
|
72
|
+
payload
|
|
73
|
+
};
|
|
74
|
+
const res = await this.fetchImpl(`${this.bridgeUrl}/message?to=${encodeURIComponent(to)}`, {
|
|
75
|
+
method: "POST",
|
|
76
|
+
headers: { "Content-Type": "application/json" },
|
|
77
|
+
body: JSON.stringify(frame)
|
|
78
|
+
});
|
|
79
|
+
if (!res.ok) throw new WalletSdkError("SUBMIT_FAILED", `bridge send failed: ${res.status}`);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Start long-polling for frames on this client's channel. Returns a `stop()`
|
|
83
|
+
* function. `onFrame` is invoked per received frame; transient errors go to
|
|
84
|
+
* `onError` (if given) and the loop retries after a short backoff. Each poll
|
|
85
|
+
* has a hard timeout and a response-size cap so a hostile/hung relay can't
|
|
86
|
+
* stall the loop or exhaust memory.
|
|
87
|
+
*/
|
|
88
|
+
start(onFrame, onError) {
|
|
89
|
+
const controller = new AbortController();
|
|
90
|
+
const poll = async () => {
|
|
91
|
+
const timeout = setTimeout(() => controller.abort(), (this.pollWaitSeconds + 10) * 1e3);
|
|
92
|
+
try {
|
|
93
|
+
const url = `${this.bridgeUrl}/events?client_id=${encodeURIComponent(this.clientId)}&wait=${this.pollWaitSeconds}`;
|
|
94
|
+
const res = await this.fetchImpl(url, { signal: controller.signal });
|
|
95
|
+
if (!res.ok) throw new WalletSdkError("SUBMIT_FAILED", `bridge poll failed: ${res.status}`);
|
|
96
|
+
if (Number(res.headers.get("content-length") ?? 0) > MAX_POLL_RESPONSE_BYTES) throw new WalletSdkError("SUBMIT_FAILED", "bridge response too large");
|
|
97
|
+
const text = await res.text();
|
|
98
|
+
if (text.length > MAX_POLL_RESPONSE_BYTES) throw new WalletSdkError("SUBMIT_FAILED", "bridge response too large");
|
|
99
|
+
const parsed = JSON.parse(text);
|
|
100
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
101
|
+
} finally {
|
|
102
|
+
clearTimeout(timeout);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const loop = async () => {
|
|
106
|
+
while (!controller.signal.aborted) try {
|
|
107
|
+
const frames = await poll();
|
|
108
|
+
for (const frame of frames) {
|
|
109
|
+
if (controller.signal.aborted) break;
|
|
110
|
+
await onFrame(frame);
|
|
111
|
+
}
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (controller.signal.aborted) break;
|
|
114
|
+
onError?.(error);
|
|
115
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
loop();
|
|
119
|
+
return () => controller.abort();
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
//#endregion
|
|
123
|
+
export { BridgeClient, assertAllowedBridgeUrl, deriveBridgeChannels, deriveConnectChannel };
|
|
124
|
+
|
|
125
|
+
//# sourceMappingURL=bridge.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bridge.js","names":[],"sources":["../../src/transport/bridge.ts"],"sourcesContent":["/**\n * Client for the cross-device relay (\"bridge\"). After the connect handshake both\n * sides hold a shared key; from it they derive TWO SECRET channel ids (one per\n * direction) via `deriveBridgeChannels`. Each side listens on one channel and\n * sends on the other. Because the channel ids are derived from the shared key —\n * NOT from the public session keys — a third party who only observes the connect\n * handshake cannot address, drain, or flood a session's channels. The relay stays\n * dumb and untrusted: it only moves sealed ciphertext between opaque channel ids.\n *\n * Transport is long-polling over `fetch` — universal across Node, browsers, and\n * React Native (no EventSource/streaming dependency).\n */\n\nimport { fromBase58, toBase58 } from '@amadeus-protocol/sdk'\nimport { sha256 } from '@noble/hashes/sha2'\n\nimport { concatBytes, utf8ToBytes } from '../bytes'\nimport { WalletSdkError } from '../errors'\n\n/** Max bytes we will read from a (possibly hostile) relay response. */\nconst MAX_POLL_RESPONSE_BYTES = 8 * 1024 * 1024\n\nexport interface BridgeFrame {\n\t/** Sender channel (informational). */\n\tfrom: string\n\t/** Recipient channel id this frame is addressed to. */\n\tto: string\n\t/** Unique frame id (also the request/response id) — for dedupe. */\n\tid: string\n\t/**\n\t * The JSON payload. Post-connect this is a sealed (E2E-encrypted) envelope;\n\t * the ONE exception is the connect response (public handshake data, integrity\n\t * protected by the connect signature) sent on the connect channel before a\n\t * shared key exists.\n\t */\n\tpayload: unknown\n}\n\n/**\n * Derive the two per-direction secret channel ids from the session shared key.\n * Both sides compute the same pair; a third party without the shared key cannot.\n */\nexport function deriveBridgeChannels(sharedKey: Uint8Array): {\n\t/** Channel the wallet listens on / the dApp sends to. */\n\ttoWallet: string\n\t/** Channel the dApp listens on / the wallet sends to. */\n\ttoDapp: string\n} {\n\tconst channel = (label: string) => toBase58(sha256(concatBytes(utf8ToBytes(label), sharedKey)))\n\treturn {\n\t\ttoWallet: channel('amadeus-bridge/to-wallet/v1'),\n\t\ttoDapp: channel('amadeus-bridge/to-dapp/v1')\n\t}\n}\n\n/**\n * Channel the dApp listens on for the CONNECT RESPONSE (cross-device / QR), before\n * a shared key exists. Derived from the dApp's PUBLIC session key (which is in the\n * connect QR), so the dApp can listen for it immediately. The response carried\n * here is public handshake data whose integrity is verified by the connect\n * signature (`verifyConnect`), so a forged response is rejected.\n */\nexport function deriveConnectChannel(dappPublicKeyBase58: string): string {\n\treturn toBase58(\n\t\tsha256(\n\t\t\tconcatBytes(utf8ToBytes('amadeus-bridge/connect/v1'), fromBase58(dappPublicKeyBase58))\n\t\t)\n\t)\n}\n\n/**\n * Reject a bridge URL that isn't https (http is allowed only for localhost dev).\n * Blocks the wallet being pointed at file://, internal http hosts, or other\n * SSRF/forced-beacon targets by an attacker-supplied connect link.\n */\nexport function assertAllowedBridgeUrl(url: string): void {\n\tconst match = /^([a-z][a-z0-9+.-]*):\\/\\/([^/:?#]+)/i.exec(url)\n\tif (!match) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'bridge URL is not a valid absolute URL')\n\t}\n\tconst scheme = match[1].toLowerCase()\n\tconst host = match[2].toLowerCase()\n\tconst isLocal = host === 'localhost' || host === '127.0.0.1' || host === '::1'\n\tif (scheme === 'https' || (scheme === 'http' && isLocal)) return\n\tthrow new WalletSdkError(\n\t\t'INVALID_ARGUMENT',\n\t\t'bridge URL must be https (http allowed only for localhost)'\n\t)\n}\n\nexport interface BridgeClientOptions {\n\t/** Relay base URL, e.g. \"https://bridge.ama.one\". */\n\tbridgeUrl: string\n\t/** This side's channel id to listen on (from `deriveBridgeChannels`). */\n\tclientId: string\n\t/** Override fetch (tests / non-standard runtimes). */\n\tfetchImpl?: typeof fetch\n\t/** How long the relay holds a long-poll before returning empty (seconds). */\n\tpollWaitSeconds?: number\n}\n\nexport class BridgeClient {\n\tprivate readonly bridgeUrl: string\n\tprivate readonly clientId: string\n\tprivate readonly fetchImpl: typeof fetch\n\tprivate readonly pollWaitSeconds: number\n\n\tconstructor(options: BridgeClientOptions) {\n\t\tassertAllowedBridgeUrl(options.bridgeUrl)\n\t\tthis.bridgeUrl = options.bridgeUrl.replace(/\\/$/, '')\n\t\tthis.clientId = options.clientId\n\t\tthis.fetchImpl = options.fetchImpl ?? fetch\n\t\tthis.pollWaitSeconds = options.pollWaitSeconds ?? 25\n\t}\n\n\t/** Send a frame (sealed envelope, or plaintext connect response) to a channel id. */\n\tasync send(to: string, id: string, payload: unknown): Promise<void> {\n\t\tconst frame: BridgeFrame = { from: this.clientId, to, id, payload }\n\t\tconst res = await this.fetchImpl(`${this.bridgeUrl}/message?to=${encodeURIComponent(to)}`, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\tbody: JSON.stringify(frame)\n\t\t})\n\t\tif (!res.ok) {\n\t\t\tthrow new WalletSdkError('SUBMIT_FAILED', `bridge send failed: ${res.status}`)\n\t\t}\n\t}\n\n\t/**\n\t * Start long-polling for frames on this client's channel. Returns a `stop()`\n\t * function. `onFrame` is invoked per received frame; transient errors go to\n\t * `onError` (if given) and the loop retries after a short backoff. Each poll\n\t * has a hard timeout and a response-size cap so a hostile/hung relay can't\n\t * stall the loop or exhaust memory.\n\t */\n\tstart(\n\t\tonFrame: (frame: BridgeFrame) => void | Promise<void>,\n\t\tonError?: (error: unknown) => void\n\t): () => void {\n\t\tconst controller = new AbortController()\n\n\t\tconst poll = async (): Promise<BridgeFrame[]> => {\n\t\t\tconst timeout = setTimeout(() => controller.abort(), (this.pollWaitSeconds + 10) * 1000)\n\t\t\ttry {\n\t\t\t\tconst url = `${this.bridgeUrl}/events?client_id=${encodeURIComponent(this.clientId)}&wait=${this.pollWaitSeconds}`\n\t\t\t\tconst res = await this.fetchImpl(url, { signal: controller.signal })\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tthrow new WalletSdkError('SUBMIT_FAILED', `bridge poll failed: ${res.status}`)\n\t\t\t\t}\n\t\t\t\tconst declared = Number(res.headers.get('content-length') ?? 0)\n\t\t\t\tif (declared > MAX_POLL_RESPONSE_BYTES) {\n\t\t\t\t\tthrow new WalletSdkError('SUBMIT_FAILED', 'bridge response too large')\n\t\t\t\t}\n\t\t\t\tconst text = await res.text()\n\t\t\t\tif (text.length > MAX_POLL_RESPONSE_BYTES) {\n\t\t\t\t\tthrow new WalletSdkError('SUBMIT_FAILED', 'bridge response too large')\n\t\t\t\t}\n\t\t\t\tconst parsed = JSON.parse(text)\n\t\t\t\treturn Array.isArray(parsed) ? (parsed as BridgeFrame[]) : []\n\t\t\t} finally {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t}\n\t\t}\n\n\t\tconst loop = async () => {\n\t\t\twhile (!controller.signal.aborted) {\n\t\t\t\ttry {\n\t\t\t\t\tconst frames = await poll()\n\t\t\t\t\tfor (const frame of frames) {\n\t\t\t\t\t\tif (controller.signal.aborted) break\n\t\t\t\t\t\tawait onFrame(frame)\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (controller.signal.aborted) break\n\t\t\t\t\tonError?.(error)\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1000))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid loop()\n\t\treturn () => controller.abort()\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,MAAM,0BAA0B,IAAI,OAAO;;;;;AAsB3C,SAAgB,qBAAqB,WAKnC;CACD,MAAM,WAAW,UAAkB,SAAS,OAAO,YAAY,YAAY,KAAK,GAAG,SAAS,CAAC,CAAC;CAC9F,OAAO;EACN,UAAU,QAAQ,6BAA6B;EAC/C,QAAQ,QAAQ,2BAA2B;CAC5C;AACD;;;;;;;;AASA,SAAgB,qBAAqB,qBAAqC;CACzE,OAAO,SACN,OACC,YAAY,YAAY,2BAA2B,GAAG,WAAW,mBAAmB,CAAC,CACtF,CACD;AACD;;;;;;AAOA,SAAgB,uBAAuB,KAAmB;CACzD,MAAM,QAAQ,uCAAuC,KAAK,GAAG;CAC7D,IAAI,CAAC,OACJ,MAAM,IAAI,eAAe,oBAAoB,wCAAwC;CAEtF,MAAM,SAAS,MAAM,EAAE,CAAC,YAAY;CACpC,MAAM,OAAO,MAAM,EAAE,CAAC,YAAY;CAElC,IAAI,WAAW,WAAY,WAAW,WADtB,SAAS,eAAe,SAAS,eAAe,SAAS,QACf;CAC1D,MAAM,IAAI,eACT,oBACA,4DACD;AACD;AAaA,IAAa,eAAb,MAA0B;CACzB;CACA;CACA;CACA;CAEA,YAAY,SAA8B;EACzC,uBAAuB,QAAQ,SAAS;EACxC,KAAK,YAAY,QAAQ,UAAU,QAAQ,OAAO,EAAE;EACpD,KAAK,WAAW,QAAQ;EACxB,KAAK,YAAY,QAAQ,aAAa;EACtC,KAAK,kBAAkB,QAAQ,mBAAmB;CACnD;;CAGA,MAAM,KAAK,IAAY,IAAY,SAAiC;EACnE,MAAM,QAAqB;GAAE,MAAM,KAAK;GAAU;GAAI;GAAI;EAAQ;EAClE,MAAM,MAAM,MAAM,KAAK,UAAU,GAAG,KAAK,UAAU,cAAc,mBAAmB,EAAE,KAAK;GAC1F,QAAQ;GACR,SAAS,EAAE,gBAAgB,mBAAmB;GAC9C,MAAM,KAAK,UAAU,KAAK;EAC3B,CAAC;EACD,IAAI,CAAC,IAAI,IACR,MAAM,IAAI,eAAe,iBAAiB,uBAAuB,IAAI,QAAQ;CAE/E;;;;;;;;CASA,MACC,SACA,SACa;EACb,MAAM,aAAa,IAAI,gBAAgB;EAEvC,MAAM,OAAO,YAAoC;GAChD,MAAM,UAAU,iBAAiB,WAAW,MAAM,IAAI,KAAK,kBAAkB,MAAM,GAAI;GACvF,IAAI;IACH,MAAM,MAAM,GAAG,KAAK,UAAU,oBAAoB,mBAAmB,KAAK,QAAQ,EAAE,QAAQ,KAAK;IACjG,MAAM,MAAM,MAAM,KAAK,UAAU,KAAK,EAAE,QAAQ,WAAW,OAAO,CAAC;IACnE,IAAI,CAAC,IAAI,IACR,MAAM,IAAI,eAAe,iBAAiB,uBAAuB,IAAI,QAAQ;IAG9E,IADiB,OAAO,IAAI,QAAQ,IAAI,gBAAgB,KAAK,CAClD,IAAI,yBACd,MAAM,IAAI,eAAe,iBAAiB,2BAA2B;IAEtE,MAAM,OAAO,MAAM,IAAI,KAAK;IAC5B,IAAI,KAAK,SAAS,yBACjB,MAAM,IAAI,eAAe,iBAAiB,2BAA2B;IAEtE,MAAM,SAAS,KAAK,MAAM,IAAI;IAC9B,OAAO,MAAM,QAAQ,MAAM,IAAK,SAA2B,CAAC;GAC7D,UAAU;IACT,aAAa,OAAO;GACrB;EACD;EAEA,MAAM,OAAO,YAAY;GACxB,OAAO,CAAC,WAAW,OAAO,SACzB,IAAI;IACH,MAAM,SAAS,MAAM,KAAK;IAC1B,KAAK,MAAM,SAAS,QAAQ;KAC3B,IAAI,WAAW,OAAO,SAAS;KAC/B,MAAM,QAAQ,KAAK;IACpB;GACD,SAAS,OAAO;IACf,IAAI,WAAW,OAAO,SAAS;IAC/B,UAAU,KAAK;IACf,MAAM,IAAI,SAAS,YAAY,WAAW,SAAS,GAAI,CAAC;GACzD;EAEF;EAEA,KAAU;EACV,aAAa,WAAW,MAAM;CAC/B;AACD"}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { SealedEnvelope } from "../crypto/box.js";
|
|
2
|
+
//#region src/transport/envelope.d.ts
|
|
3
|
+
declare const WALLET_METHODS: readonly ["amadeus_signTransaction", "amadeus_signMessage", "amadeus_getAccounts", "amadeus_generateApiKey", "amadeus_switchNetwork"];
|
|
4
|
+
type WalletMethod = (typeof WALLET_METHODS)[number];
|
|
5
|
+
interface WalletRequest {
|
|
6
|
+
/** Protocol version. */
|
|
7
|
+
v: number;
|
|
8
|
+
/** Unique, one-time request id (replay key). */
|
|
9
|
+
id: string;
|
|
10
|
+
method: WalletMethod;
|
|
11
|
+
/** The dApp origin, echoed for display in the approval UI. */
|
|
12
|
+
origin: string;
|
|
13
|
+
params: unknown;
|
|
14
|
+
/** Unix-seconds expiry. */
|
|
15
|
+
exp: number;
|
|
16
|
+
}
|
|
17
|
+
type WalletResponse = {
|
|
18
|
+
v: number;
|
|
19
|
+
id: string;
|
|
20
|
+
ok: true;
|
|
21
|
+
result: unknown;
|
|
22
|
+
} | {
|
|
23
|
+
v: number;
|
|
24
|
+
id: string;
|
|
25
|
+
ok: false;
|
|
26
|
+
error: {
|
|
27
|
+
code: string;
|
|
28
|
+
message: string;
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
/** Build an unsealed request with the current protocol version and a TTL. */
|
|
32
|
+
declare function makeRequest(params: {
|
|
33
|
+
id: string;
|
|
34
|
+
method: WalletMethod;
|
|
35
|
+
origin: string;
|
|
36
|
+
params: unknown;
|
|
37
|
+
ttlSeconds?: number;
|
|
38
|
+
now?: number;
|
|
39
|
+
}): WalletRequest;
|
|
40
|
+
declare function sealRequest(sharedKey: Uint8Array, request: WalletRequest): SealedEnvelope;
|
|
41
|
+
/**
|
|
42
|
+
* Decrypt + structurally validate an inbound request. Throws `DECRYPT_FAILED` if
|
|
43
|
+
* the envelope is not authentic, `INVALID_ARGUMENT` if the plaintext is not a
|
|
44
|
+
* well-formed request. Does NOT check expiry/replay — call `guardRequest` for
|
|
45
|
+
* that policy step (kept separate so the crypto and the policy are distinct).
|
|
46
|
+
*/
|
|
47
|
+
declare function openRequest(sharedKey: Uint8Array, envelope: SealedEnvelope): WalletRequest;
|
|
48
|
+
declare function sealResponse(sharedKey: Uint8Array, response: WalletResponse): SealedEnvelope;
|
|
49
|
+
/**
|
|
50
|
+
* Decrypt + validate an inbound response, optionally asserting it answers
|
|
51
|
+
* `expectedId` (defends against a swapped/mismatched reply).
|
|
52
|
+
*/
|
|
53
|
+
declare function openResponse(sharedKey: Uint8Array, envelope: SealedEnvelope, expectedId?: string): WalletResponse;
|
|
54
|
+
/**
|
|
55
|
+
* A one-time-id store for replay defense. The in-memory default is fine for a
|
|
56
|
+
* single process; the mobile wallet should supply a PERSISTED implementation
|
|
57
|
+
* (e.g. expo-secure-store) so a crash/relaunch inside the TTL window can't let a
|
|
58
|
+
* captured approval replay. `has`+`add` must be atomic in the persisted impl.
|
|
59
|
+
*/
|
|
60
|
+
interface SeenStore {
|
|
61
|
+
has(id: string): boolean;
|
|
62
|
+
add(id: string): void;
|
|
63
|
+
}
|
|
64
|
+
declare function createMemorySeenStore(maxEntries?: number): SeenStore;
|
|
65
|
+
/**
|
|
66
|
+
* Policy gate: enforce expiry + one-time id BEFORE acting on a request (i.e.
|
|
67
|
+
* before building/signing anything). Atomic check-and-add against `store`.
|
|
68
|
+
* Throws `EXPIRED` or `INVALID_ARGUMENT` (duplicate).
|
|
69
|
+
*/
|
|
70
|
+
declare function guardRequest(request: WalletRequest, store: SeenStore, now?: number): void;
|
|
71
|
+
//#endregion
|
|
72
|
+
export { SeenStore, WALLET_METHODS, WalletMethod, WalletRequest, WalletResponse, createMemorySeenStore, guardRequest, makeRequest, openRequest, openResponse, sealRequest, sealResponse };
|
|
73
|
+
//# sourceMappingURL=envelope.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"envelope.d.ts","names":[],"sources":["../../src/transport/envelope.ts"],"mappings":";;cAiBa;KAQD,uBAAuB;UAElB;;EAEhB;;EAEA;EACA,QAAQ;;EAER;EACA;;EAEA;;KAGW;EACP;EAAW;EAAY;EAAU;;EACjC;EAAW;EAAY;EAAW;IAAS;IAAc;;;;iBA2B9C,YAAY;EAC3B;EACA,QAAQ;EACR;EACA;EACA;EACA;IACG;iBAYY,YAAY,WAAW,YAAY,SAAS,gBAAgB;;;;;;;iBAU5D,YAAY,WAAW,YAAY,UAAU,iBAAiB;iBAe9D,aAAa,WAAW,YAAY,UAAU,iBAAiB;;;;;iBAQ/D,aACf,WAAW,YACX,UAAU,gBACV,sBACE;;;;;;;UAyBc;EAChB,IAAI;EACJ,IAAI;;iBAGW,sBAAsB,sBAAsB;;;;;;iBAgB5C,aAAa,SAAS,eAAe,OAAO,WAAW"}
|