@amadeus-protocol/wallet-sdk 0.1.0 → 0.1.4

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.
@@ -25,6 +25,14 @@ declare const API_KEY_DST = "AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_APIKEY_"
25
25
  * from every other DST so a connect proof is unusable anywhere else.
26
26
  */
27
27
  declare const CONNECT_DST = "AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_CONNECT_";
28
+ /**
29
+ * Arbitrary-message ("personal sign") signatures. NEW in this package — no prior
30
+ * verifier, so no backward-compat constraint. Its distinct DST is the safety
31
+ * guarantee: a message signed here can NEVER verify as a transaction (`TX_DST`),
32
+ * an API key (`API_KEY_DST`), or a connect proof, so a dApp can't trick a user
33
+ * into blind-signing a payload that is secretly valid under another protocol.
34
+ */
35
+ declare const MESSAGE_DST = "AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_MSG_";
28
36
  /** Byte lengths of the Amadeus BLS12-381 "long-signature" variant (G1 pk / G2 sig). */
29
37
  declare const PUBLIC_KEY_BYTE_LENGTH = 48;
30
38
  declare const SIGNATURE_BYTE_LENGTH = 96;
@@ -36,6 +44,12 @@ declare const SEED_BYTE_LENGTH = 64;
36
44
  * for a multi-hundred-char audience claim.
37
45
  */
38
46
  declare const MAX_API_KEY_STRING_LENGTH = 1024;
47
+ /**
48
+ * Hard cap on a to-be-signed message (UTF-8 chars). Bounds untrusted input shown
49
+ * in the approval UI and hashed for signing; generous enough for SIWE-style
50
+ * multi-line login messages while refusing a megabyte blob.
51
+ */
52
+ declare const MAX_MESSAGE_LENGTH = 4096;
39
53
  /** x25519 / xchacha20-poly1305 session-box parameters. */
40
54
  declare const SESSION_PUBLIC_KEY_BYTE_LENGTH = 32;
41
55
  declare const SESSION_SECRET_KEY_BYTE_LENGTH = 32;
@@ -65,6 +79,12 @@ declare const WALLET_WINDOW_EVENTS: {
65
79
  declare const PROVIDER_EVENTS: readonly ["accountsChanged", "connect", "disconnect", "lock", "unlock", "networkChanged"];
66
80
  /** The valid networks the wallet exposes. */
67
81
  declare const NETWORKS: readonly ["mainnet", "testnet", "custom"];
82
+ /**
83
+ * Default cross-device relay ("bridge") URL. dApps that don't pass their own
84
+ * `bridgeUrl` to `createConnectRequest` fall back to this. Must be https (the
85
+ * wallet rejects non-https bridge URLs via `assertAllowedBridgeUrl`).
86
+ */
87
+ declare const DEFAULT_BRIDGE_URL = "https://bridge.ama.one";
68
88
  //#endregion
69
- export { 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 };
89
+ export { API_KEY_DST, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, DEFAULT_BRIDGE_URL, MAX_API_KEY_STRING_LENGTH, MAX_MESSAGE_LENGTH, MESSAGE_DST, 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 };
70
90
  //# sourceMappingURL=constants.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.ts","names":[],"sources":["../src/constants.ts"],"mappings":";;;;;;;;;;;;;cAaa;;;;;;;cAQA;;;;;;cAOA;;cAGA;cACA;cACA;;;;;;;cAQA;;cAGA;cACA;cACA;;cAGA;;cAGA;;cAGA;;;;;;cAOA;;cAGA;;;;;;;;;cAUA;;cAUA"}
1
+ {"version":3,"file":"constants.d.ts","names":[],"sources":["../src/constants.ts"],"mappings":";;;;;;;;;;;;;cAaa;;;;;;;cAQA;;;;;;cAOA;;;;;;;;cASA;;cAGA;cACA;cACA;;;;;;;cAQA;;;;;;cAOA;;cAGA;cACA;cACA;;cAGA;;cAGA;;cAGA;;;;;;cAOA;;cAGA;;;;;;;;;cAUA;;cAUA;;;;;;cAOA"}
package/dist/constants.js CHANGED
@@ -25,6 +25,14 @@ const API_KEY_DST = "AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_APIKEY_";
25
25
  * from every other DST so a connect proof is unusable anywhere else.
26
26
  */
27
27
  const CONNECT_DST = "AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_CONNECT_";
28
+ /**
29
+ * Arbitrary-message ("personal sign") signatures. NEW in this package — no prior
30
+ * verifier, so no backward-compat constraint. Its distinct DST is the safety
31
+ * guarantee: a message signed here can NEVER verify as a transaction (`TX_DST`),
32
+ * an API key (`API_KEY_DST`), or a connect proof, so a dApp can't trick a user
33
+ * into blind-signing a payload that is secretly valid under another protocol.
34
+ */
35
+ const MESSAGE_DST = "AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_MSG_";
28
36
  /** Byte lengths of the Amadeus BLS12-381 "long-signature" variant (G1 pk / G2 sig). */
29
37
  const PUBLIC_KEY_BYTE_LENGTH = 48;
30
38
  const SIGNATURE_BYTE_LENGTH = 96;
@@ -36,6 +44,12 @@ const SEED_BYTE_LENGTH = 64;
36
44
  * for a multi-hundred-char audience claim.
37
45
  */
38
46
  const MAX_API_KEY_STRING_LENGTH = 1024;
47
+ /**
48
+ * Hard cap on a to-be-signed message (UTF-8 chars). Bounds untrusted input shown
49
+ * in the approval UI and hashed for signing; generous enough for SIWE-style
50
+ * multi-line login messages while refusing a megabyte blob.
51
+ */
52
+ const MAX_MESSAGE_LENGTH = 4096;
39
53
  /** x25519 / xchacha20-poly1305 session-box parameters. */
40
54
  const SESSION_PUBLIC_KEY_BYTE_LENGTH = 32;
41
55
  const SESSION_SECRET_KEY_BYTE_LENGTH = 32;
@@ -76,7 +90,13 @@ const NETWORKS = [
76
90
  "testnet",
77
91
  "custom"
78
92
  ];
93
+ /**
94
+ * Default cross-device relay ("bridge") URL. dApps that don't pass their own
95
+ * `bridgeUrl` to `createConnectRequest` fall back to this. Must be https (the
96
+ * wallet rejects non-https bridge URLs via `assertAllowedBridgeUrl`).
97
+ */
98
+ const DEFAULT_BRIDGE_URL = "https://bridge.ama.one";
79
99
  //#endregion
80
- export { 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 };
100
+ export { API_KEY_DST, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, DEFAULT_BRIDGE_URL, MAX_API_KEY_STRING_LENGTH, MAX_MESSAGE_LENGTH, MESSAGE_DST, 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 };
81
101
 
82
102
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["/**\n * Protocol constants for the Amadeus dApp <-> wallet connection layer.\n *\n * The Domain Separation Tags (DSTs) below are the single most safety-critical\n * values in this package. A signature made under one DST can NEVER verify under\n * another (BLS hash-to-curve mixes the DST into the point), which is exactly how\n * we guarantee an auth signature can never be replayed as a transaction, and\n * vice-versa. Two of these (`TX`, `APIKEY`) already exist in production — in\n * `@amadeus-protocol/sdk` and in the wallet extension respectively — and MUST\n * stay byte-for-byte identical here or existing tokens/txs stop verifying.\n */\n\n/** Transactions. Owned by `@amadeus-protocol/sdk` (`signing.ts`). Do not change. */\nexport const TX_DST = 'AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_TX_'\n\n/**\n * KBS bearer / API-key tokens. Currently hand-rolled identically in the wallet\n * extension (`background/handlers/api-key.ts`) and in hub/prime-hub\n * (`utils/blsWallet.ts`). This package is the one audited home for it. Do not\n * change — `kbs.ama.one` verifies against this exact tag.\n */\nexport const API_KEY_DST = 'AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_APIKEY_'\n\n/**\n * Connection-auth transcript signatures. NEW in this package — nothing verified\n * it before, so there is no backward-compat constraint. Deliberately distinct\n * from every other DST so a connect proof is unusable anywhere else.\n */\nexport const CONNECT_DST = 'AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_CONNECT_'\n\n/** Byte lengths of the Amadeus BLS12-381 \"long-signature\" variant (G1 pk / G2 sig). */\nexport const PUBLIC_KEY_BYTE_LENGTH = 48\nexport const SIGNATURE_BYTE_LENGTH = 96\nexport const SEED_BYTE_LENGTH = 64\n\n/**\n * Hard cap on the length of an api-key string accepted for decoding. A genuine\n * token is ~260 chars; this bounds untrusted input BEFORE the (quadratic) Base58\n * decode so a huge string can't stall the verifier's event loop. Generous enough\n * for a multi-hundred-char audience claim.\n */\nexport const MAX_API_KEY_STRING_LENGTH = 1024\n\n/** x25519 / xchacha20-poly1305 session-box parameters. */\nexport const SESSION_PUBLIC_KEY_BYTE_LENGTH = 32\nexport const SESSION_SECRET_KEY_BYTE_LENGTH = 32\nexport const SESSION_NONCE_BYTE_LENGTH = 24\n\n/** Wire protocol version. Absent in the extension today; new requests carry it. */\nexport const PROTOCOL_VERSION = 1\n\n/** Label mixed into the connect transcript so its bytes are unambiguous. */\nexport const CONNECT_TRANSCRIPT_LABEL = 'amadeus-connect/v1'\n\n/** The injected-provider global name and feature-detect flag. */\nexport const PROVIDER_GLOBAL = 'amadeus'\n\n/**\n * The canonical wallet-ready window event. NOTE: several dApps historically\n * listened for the WRONG name `amadeus#initialized`; the real one the extension\n * dispatches is `amadeus-wallet#initialized`. Consumers should use this constant.\n */\nexport const WALLET_INITIALIZED_EVENT = 'amadeus-wallet#initialized'\n\n/** All window CustomEvents the wallet dispatches on the page. */\nexport const WALLET_WINDOW_EVENTS = {\n\tinitialized: 'amadeus-wallet#initialized',\n\tconnected: 'amadeus-wallet#connected',\n\tdisconnected: 'amadeus-wallet#disconnected',\n\tlocked: 'amadeus-wallet#locked',\n\tunlocked: 'amadeus-wallet#unlocked',\n\tnetworkChanged: 'amadeus-wallet#networkChanged'\n} as const\n\n/** Provider `.on()` event names (EIP-1193-style). */\nexport const PROVIDER_EVENTS = [\n\t'accountsChanged',\n\t'connect',\n\t'disconnect',\n\t'lock',\n\t'unlock',\n\t'networkChanged'\n] as const\n\n/** The valid networks the wallet exposes. */\nexport const NETWORKS = ['mainnet', 'testnet', 'custom'] as const\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,SAAS;;;;;;;AAQtB,MAAa,cAAc;;;;;;AAO3B,MAAa,cAAc;;AAG3B,MAAa,yBAAyB;AACtC,MAAa,wBAAwB;AACrC,MAAa,mBAAmB;;;;;;;AAQhC,MAAa,4BAA4B;;AAGzC,MAAa,iCAAiC;AAC9C,MAAa,iCAAiC;AAC9C,MAAa,4BAA4B;;AAGzC,MAAa,mBAAmB;;AAGhC,MAAa,2BAA2B;;AAGxC,MAAa,kBAAkB;;;;;;AAO/B,MAAa,2BAA2B;;AAGxC,MAAa,uBAAuB;CACnC,aAAa;CACb,WAAW;CACX,cAAc;CACd,QAAQ;CACR,UAAU;CACV,gBAAgB;AACjB;;AAGA,MAAa,kBAAkB;CAC9B;CACA;CACA;CACA;CACA;CACA;AACD;;AAGA,MAAa,WAAW;CAAC;CAAW;CAAW;AAAQ"}
1
+ {"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["/**\n * Protocol constants for the Amadeus dApp <-> wallet connection layer.\n *\n * The Domain Separation Tags (DSTs) below are the single most safety-critical\n * values in this package. A signature made under one DST can NEVER verify under\n * another (BLS hash-to-curve mixes the DST into the point), which is exactly how\n * we guarantee an auth signature can never be replayed as a transaction, and\n * vice-versa. Two of these (`TX`, `APIKEY`) already exist in production — in\n * `@amadeus-protocol/sdk` and in the wallet extension respectively — and MUST\n * stay byte-for-byte identical here or existing tokens/txs stop verifying.\n */\n\n/** Transactions. Owned by `@amadeus-protocol/sdk` (`signing.ts`). Do not change. */\nexport const TX_DST = 'AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_TX_'\n\n/**\n * KBS bearer / API-key tokens. Currently hand-rolled identically in the wallet\n * extension (`background/handlers/api-key.ts`) and in hub/prime-hub\n * (`utils/blsWallet.ts`). This package is the one audited home for it. Do not\n * change — `kbs.ama.one` verifies against this exact tag.\n */\nexport const API_KEY_DST = 'AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_APIKEY_'\n\n/**\n * Connection-auth transcript signatures. NEW in this package — nothing verified\n * it before, so there is no backward-compat constraint. Deliberately distinct\n * from every other DST so a connect proof is unusable anywhere else.\n */\nexport const CONNECT_DST = 'AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_CONNECT_'\n\n/**\n * Arbitrary-message (\"personal sign\") signatures. NEW in this package — no prior\n * verifier, so no backward-compat constraint. Its distinct DST is the safety\n * guarantee: a message signed here can NEVER verify as a transaction (`TX_DST`),\n * an API key (`API_KEY_DST`), or a connect proof, so a dApp can't trick a user\n * into blind-signing a payload that is secretly valid under another protocol.\n */\nexport const MESSAGE_DST = 'AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_MSG_'\n\n/** Byte lengths of the Amadeus BLS12-381 \"long-signature\" variant (G1 pk / G2 sig). */\nexport const PUBLIC_KEY_BYTE_LENGTH = 48\nexport const SIGNATURE_BYTE_LENGTH = 96\nexport const SEED_BYTE_LENGTH = 64\n\n/**\n * Hard cap on the length of an api-key string accepted for decoding. A genuine\n * token is ~260 chars; this bounds untrusted input BEFORE the (quadratic) Base58\n * decode so a huge string can't stall the verifier's event loop. Generous enough\n * for a multi-hundred-char audience claim.\n */\nexport const MAX_API_KEY_STRING_LENGTH = 1024\n\n/**\n * Hard cap on a to-be-signed message (UTF-8 chars). Bounds untrusted input shown\n * in the approval UI and hashed for signing; generous enough for SIWE-style\n * multi-line login messages while refusing a megabyte blob.\n */\nexport const MAX_MESSAGE_LENGTH = 4096\n\n/** x25519 / xchacha20-poly1305 session-box parameters. */\nexport const SESSION_PUBLIC_KEY_BYTE_LENGTH = 32\nexport const SESSION_SECRET_KEY_BYTE_LENGTH = 32\nexport const SESSION_NONCE_BYTE_LENGTH = 24\n\n/** Wire protocol version. Absent in the extension today; new requests carry it. */\nexport const PROTOCOL_VERSION = 1\n\n/** Label mixed into the connect transcript so its bytes are unambiguous. */\nexport const CONNECT_TRANSCRIPT_LABEL = 'amadeus-connect/v1'\n\n/** The injected-provider global name and feature-detect flag. */\nexport const PROVIDER_GLOBAL = 'amadeus'\n\n/**\n * The canonical wallet-ready window event. NOTE: several dApps historically\n * listened for the WRONG name `amadeus#initialized`; the real one the extension\n * dispatches is `amadeus-wallet#initialized`. Consumers should use this constant.\n */\nexport const WALLET_INITIALIZED_EVENT = 'amadeus-wallet#initialized'\n\n/** All window CustomEvents the wallet dispatches on the page. */\nexport const WALLET_WINDOW_EVENTS = {\n\tinitialized: 'amadeus-wallet#initialized',\n\tconnected: 'amadeus-wallet#connected',\n\tdisconnected: 'amadeus-wallet#disconnected',\n\tlocked: 'amadeus-wallet#locked',\n\tunlocked: 'amadeus-wallet#unlocked',\n\tnetworkChanged: 'amadeus-wallet#networkChanged'\n} as const\n\n/** Provider `.on()` event names (EIP-1193-style). */\nexport const PROVIDER_EVENTS = [\n\t'accountsChanged',\n\t'connect',\n\t'disconnect',\n\t'lock',\n\t'unlock',\n\t'networkChanged'\n] as const\n\n/** The valid networks the wallet exposes. */\nexport const NETWORKS = ['mainnet', 'testnet', 'custom'] as const\n\n/**\n * Default cross-device relay (\"bridge\") URL. dApps that don't pass their own\n * `bridgeUrl` to `createConnectRequest` fall back to this. Must be https (the\n * wallet rejects non-https bridge URLs via `assertAllowedBridgeUrl`).\n */\nexport const DEFAULT_BRIDGE_URL = 'https://bridge.ama.one'\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,SAAS;;;;;;;AAQtB,MAAa,cAAc;;;;;;AAO3B,MAAa,cAAc;;;;;;;;AAS3B,MAAa,cAAc;;AAG3B,MAAa,yBAAyB;AACtC,MAAa,wBAAwB;AACrC,MAAa,mBAAmB;;;;;;;AAQhC,MAAa,4BAA4B;;;;;;AAOzC,MAAa,qBAAqB;;AAGlC,MAAa,iCAAiC;AAC9C,MAAa,iCAAiC;AAC9C,MAAa,4BAA4B;;AAGzC,MAAa,mBAAmB;;AAGhC,MAAa,2BAA2B;;AAGxC,MAAa,kBAAkB;;;;;;AAO/B,MAAa,2BAA2B;;AAGxC,MAAa,uBAAuB;CACnC,aAAa;CACb,WAAW;CACX,cAAc;CACd,QAAQ;CACR,UAAU;CACV,gBAAgB;AACjB;;AAGA,MAAa,kBAAkB;CAC9B;CACA;CACA;CACA;CACA;CACA;AACD;;AAGA,MAAa,WAAW;CAAC;CAAW;CAAW;AAAQ;;;;;;AAOvD,MAAa,qBAAqB"}
@@ -0,0 +1,47 @@
1
+ //#region src/crypto/message.d.ts
2
+ /**
3
+ * Arbitrary-message signing ("personal sign") — the wallet proves control of an
4
+ * account over a human-readable string (a login challenge, a terms acceptance, a
5
+ * nonce). Unlike a transaction it never touches the chain; unlike an API key it
6
+ * carries no audience/expiry — it is just a signature the dApp (or its backend)
7
+ * can verify with `verifyMessage`.
8
+ *
9
+ * Recipe: signature = BLS.sign(sha256(utf8(message)), sk, { DST: MESSAGE_DST }).
10
+ * The dedicated `MESSAGE_DST` is what makes this safe to expose: BLS mixes the
11
+ * DST into the curve point, so a message signature can never be replayed as a
12
+ * transaction or API-key signature (and vice-versa). No pubkey is folded in — a
13
+ * single signature is already bound to its signer through verification against a
14
+ * known address, so there is no rogue-key surface here.
15
+ */
16
+ interface SignMessageParams {
17
+ /** Base58 wallet seed (private key). */
18
+ seed: string;
19
+ /** The UTF-8 message to sign. */
20
+ message: string;
21
+ }
22
+ interface SignMessageResult {
23
+ /** The message that was signed, echoed back for display/verification. */
24
+ message: string;
25
+ /** Base58 BLS signature (96 bytes). */
26
+ signature: string;
27
+ /** The signing address (Base58 public key). */
28
+ address: string;
29
+ }
30
+ /** Sign a UTF-8 message under `MESSAGE_DST`. */
31
+ declare function signMessage(params: SignMessageParams): SignMessageResult;
32
+ interface VerifyMessageParams {
33
+ /** The UTF-8 message that was signed. */
34
+ message: string;
35
+ /** Base58 BLS signature returned by `signMessage`. */
36
+ signature: string;
37
+ /** The Base58 address (public key) that should have signed it. */
38
+ address: string;
39
+ }
40
+ /**
41
+ * Verify a message signature against a claimed address. Never throws — malformed
42
+ * input (bad Base58, wrong length, over-long message) returns `false`.
43
+ */
44
+ declare function verifyMessage(params: VerifyMessageParams): boolean;
45
+ //#endregion
46
+ export { SignMessageParams, SignMessageResult, VerifyMessageParams, signMessage, verifyMessage };
47
+ //# sourceMappingURL=message.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"message.d.ts","names":[],"sources":["../../src/crypto/message.ts"],"mappings":";;;;;;;;;;;;;;;UAsBiB;;EAEhB;;EAEA;;UAGgB;;EAEhB;;EAEA;;EAEA;;;iBAiBe,YAAY,QAAQ,oBAAoB;UAOvC;;EAEhB;;EAEA;;EAEA;;;;;;iBAOe,cAAc,QAAQ"}
@@ -0,0 +1,53 @@
1
+ import { MAX_MESSAGE_LENGTH, MESSAGE_DST } from "../constants.js";
2
+ import { WalletSdkError } from "../errors.js";
3
+ import { utf8ToBytes } from "../bytes.js";
4
+ import { deriveSigner, publicKeyFromAddress, signHashed, signatureFromBase58, verifyHashed } from "./bls.js";
5
+ import { toBase58 } from "@amadeus-protocol/sdk";
6
+ //#region src/crypto/message.ts
7
+ /**
8
+ * Arbitrary-message signing ("personal sign") — the wallet proves control of an
9
+ * account over a human-readable string (a login challenge, a terms acceptance, a
10
+ * nonce). Unlike a transaction it never touches the chain; unlike an API key it
11
+ * carries no audience/expiry — it is just a signature the dApp (or its backend)
12
+ * can verify with `verifyMessage`.
13
+ *
14
+ * Recipe: signature = BLS.sign(sha256(utf8(message)), sk, { DST: MESSAGE_DST }).
15
+ * The dedicated `MESSAGE_DST` is what makes this safe to expose: BLS mixes the
16
+ * DST into the curve point, so a message signature can never be replayed as a
17
+ * transaction or API-key signature (and vice-versa). No pubkey is folded in — a
18
+ * single signature is already bound to its signer through verification against a
19
+ * known address, so there is no rogue-key surface here.
20
+ */
21
+ /** Assert a message is a non-empty string within the length bound. */
22
+ function assertMessage(message) {
23
+ if (typeof message !== "string" || message.length === 0) throw new WalletSdkError("INVALID_ARGUMENT", "message is required");
24
+ if (message.length > 4096) throw new WalletSdkError("INVALID_ARGUMENT", `message exceeds ${MAX_MESSAGE_LENGTH} characters`);
25
+ }
26
+ /** Sign a UTF-8 message under `MESSAGE_DST`. */
27
+ function signMessage(params) {
28
+ assertMessage(params.message);
29
+ const { sk, pk } = deriveSigner(params.seed);
30
+ const signature = signHashed(utf8ToBytes(params.message), sk, MESSAGE_DST);
31
+ return {
32
+ message: params.message,
33
+ signature: toBase58(signature),
34
+ address: toBase58(pk)
35
+ };
36
+ }
37
+ /**
38
+ * Verify a message signature against a claimed address. Never throws — malformed
39
+ * input (bad Base58, wrong length, over-long message) returns `false`.
40
+ */
41
+ function verifyMessage(params) {
42
+ try {
43
+ assertMessage(params.message);
44
+ const publicKey = publicKeyFromAddress(params.address);
45
+ return verifyHashed(signatureFromBase58(params.signature), utf8ToBytes(params.message), publicKey, MESSAGE_DST);
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
50
+ //#endregion
51
+ export { signMessage, verifyMessage };
52
+
53
+ //# sourceMappingURL=message.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"message.js","names":[],"sources":["../../src/crypto/message.ts"],"sourcesContent":["/**\n * Arbitrary-message signing (\"personal sign\") — the wallet proves control of an\n * account over a human-readable string (a login challenge, a terms acceptance, a\n * nonce). Unlike a transaction it never touches the chain; unlike an API key it\n * carries no audience/expiry — it is just a signature the dApp (or its backend)\n * can verify with `verifyMessage`.\n *\n * Recipe: signature = BLS.sign(sha256(utf8(message)), sk, { DST: MESSAGE_DST }).\n * The dedicated `MESSAGE_DST` is what makes this safe to expose: BLS mixes the\n * DST into the curve point, so a message signature can never be replayed as a\n * transaction or API-key signature (and vice-versa). No pubkey is folded in — a\n * single signature is already bound to its signer through verification against a\n * known address, so there is no rogue-key surface here.\n */\n\nimport { toBase58 } from '@amadeus-protocol/sdk'\n\nimport { MAX_MESSAGE_LENGTH, MESSAGE_DST } from '../constants'\nimport { WalletSdkError } from '../errors'\nimport { utf8ToBytes } from '../bytes'\nimport { deriveSigner, publicKeyFromAddress, signatureFromBase58, signHashed, verifyHashed } from './bls'\n\nexport interface SignMessageParams {\n\t/** Base58 wallet seed (private key). */\n\tseed: string\n\t/** The UTF-8 message to sign. */\n\tmessage: string\n}\n\nexport interface SignMessageResult {\n\t/** The message that was signed, echoed back for display/verification. */\n\tmessage: string\n\t/** Base58 BLS signature (96 bytes). */\n\tsignature: string\n\t/** The signing address (Base58 public key). */\n\taddress: string\n}\n\n/** Assert a message is a non-empty string within the length bound. */\nfunction assertMessage(message: string): void {\n\tif (typeof message !== 'string' || message.length === 0) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'message is required')\n\t}\n\tif (message.length > MAX_MESSAGE_LENGTH) {\n\t\tthrow new WalletSdkError(\n\t\t\t'INVALID_ARGUMENT',\n\t\t\t`message exceeds ${MAX_MESSAGE_LENGTH} characters`\n\t\t)\n\t}\n}\n\n/** Sign a UTF-8 message under `MESSAGE_DST`. */\nexport function signMessage(params: SignMessageParams): SignMessageResult {\n\tassertMessage(params.message)\n\tconst { sk, pk } = deriveSigner(params.seed)\n\tconst signature = signHashed(utf8ToBytes(params.message), sk, MESSAGE_DST)\n\treturn { message: params.message, signature: toBase58(signature), address: toBase58(pk) }\n}\n\nexport interface VerifyMessageParams {\n\t/** The UTF-8 message that was signed. */\n\tmessage: string\n\t/** Base58 BLS signature returned by `signMessage`. */\n\tsignature: string\n\t/** The Base58 address (public key) that should have signed it. */\n\taddress: string\n}\n\n/**\n * Verify a message signature against a claimed address. Never throws — malformed\n * input (bad Base58, wrong length, over-long message) returns `false`.\n */\nexport function verifyMessage(params: VerifyMessageParams): boolean {\n\ttry {\n\t\tassertMessage(params.message)\n\t\tconst publicKey = publicKeyFromAddress(params.address)\n\t\tconst signature = signatureFromBase58(params.signature)\n\t\treturn verifyHashed(signature, utf8ToBytes(params.message), publicKey, MESSAGE_DST)\n\t} catch {\n\t\treturn false\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,SAAS,cAAc,SAAuB;CAC7C,IAAI,OAAO,YAAY,YAAY,QAAQ,WAAW,GACrD,MAAM,IAAI,eAAe,oBAAoB,qBAAqB;CAEnE,IAAI,QAAQ,SAAA,MACX,MAAM,IAAI,eACT,oBACA,mBAAmB,mBAAmB,YACvC;AAEF;;AAGA,SAAgB,YAAY,QAA8C;CACzE,cAAc,OAAO,OAAO;CAC5B,MAAM,EAAE,IAAI,OAAO,aAAa,OAAO,IAAI;CAC3C,MAAM,YAAY,WAAW,YAAY,OAAO,OAAO,GAAG,IAAI,WAAW;CACzE,OAAO;EAAE,SAAS,OAAO;EAAS,WAAW,SAAS,SAAS;EAAG,SAAS,SAAS,EAAE;CAAE;AACzF;;;;;AAeA,SAAgB,cAAc,QAAsC;CACnE,IAAI;EACH,cAAc,OAAO,OAAO;EAC5B,MAAM,YAAY,qBAAqB,OAAO,OAAO;EAErD,OAAO,aADW,oBAAoB,OAAO,SACjB,GAAG,YAAY,OAAO,OAAO,GAAG,WAAW,WAAW;CACnF,QAAQ;EACP,OAAO;CACR;AACD"}
package/dist/index.d.ts CHANGED
@@ -1,12 +1,13 @@
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";
1
+ import { API_KEY_DST, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, DEFAULT_BRIDGE_URL, MAX_API_KEY_STRING_LENGTH, MAX_MESSAGE_LENGTH, MESSAGE_DST, 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
2
  import { WalletSdkError, WalletSdkErrorCode } from "./errors.js";
3
3
  import { bytesToUtf8, concatBytes, equalBytes, randomBytes, randomId, u32be, utf8ToBytes } from "./bytes.js";
4
4
  import { BYTES_TAG, TaggedBytes, decodeBinaryValues, describeBinaryValues, encodeBinaryValues, isTaggedBytes } from "./binary.js";
5
5
  import { SignTransactionParams, SignedTransaction, SubmitTransactionOptions, signTransaction, submitTransaction } from "./tx.js";
6
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";
7
+ import { ConnectTranscriptInput, GenerateApiKeyRequestInput, SignMessageRequestInput, SignTransactionRequestInput, addressSchema, connectTranscriptSchema, generateApiKeyRequestSchema, networkSchema, originSchema, sessionPublicKeySchema, signMessageRequestSchema, signTransactionRequestSchema } from "./schema.js";
8
8
  import { SignerKeys, deriveSigner, publicKeyFromAddress, signHashed, signatureFromBase58, verifyHashed } from "./crypto/bls.js";
9
9
  import { ApiKeyPayload, DecodedApiKey, GenerateApiKeyParams, GenerateApiKeyResult, VerifyApiKeyOptions, VerifyApiKeyResult, decodeApiKey, generateApiKey, verifyApiKey } from "./crypto/apikey.js";
10
+ import { SignMessageParams, SignMessageResult, VerifyMessageParams, signMessage, verifyMessage } from "./crypto/message.js";
10
11
  import { ConnectTranscript, SignConnectParams, VerifyConnectParams, buildConnectTranscript, signConnect, verifyConnect } from "./crypto/connect.js";
11
12
  import { SealedEnvelope, SessionKeypair, deriveSharedKey, generateSessionKeypair, open, seal } from "./crypto/box.js";
12
13
  import { SeenStore, WALLET_METHODS, WalletMethod, WalletRequest, WalletResponse, createMemorySeenStore, guardRequest, makeRequest, openRequest, openResponse, sealRequest, sealResponse } from "./transport/envelope.js";
@@ -15,4 +16,4 @@ import { EstablishedSession, PendingConnect, WalletSession, approveConnect, comp
15
16
  import { BridgeClient, BridgeClientOptions, BridgeFrame, assertAllowedBridgeUrl, deriveBridgeChannels, deriveConnectChannel } from "./transport/bridge.js";
16
17
  import { WalletHandlerContext, handleRequest } from "./wallet/handler.js";
17
18
  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 };
19
+ export { API_KEY_DST, AmadeusEventPayloadMap, AmadeusNetwork, AmadeusProvider, AmadeusProviderEvent, ApiKeyPayload, ApiKeyStore, BYTES_TAG, BridgeClient, BridgeClientOptions, BridgeFrame, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, ConnectRequestParams, ConnectResponseParams, ConnectTranscript, ConnectTranscriptInput, DEFAULT_BRIDGE_URL, DecodedApiKey, EstablishedSession, GenerateApiKeyParams, GenerateApiKeyRequest, GenerateApiKeyRequestInput, GenerateApiKeyResponse, GenerateApiKeyResult, MAX_API_KEY_STRING_LENGTH, MAX_MESSAGE_LENGTH, MESSAGE_DST, 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, SignMessageParams, SignMessageRequestInput, SignMessageResult, SignTransactionParams, SignTransactionRequest, SignTransactionRequestInput, SignTransactionResponse, SignedTransaction, SignerKeys, SubmitTransactionOptions, TX_DST, TaggedBytes, URI_SCHEME, VerifyApiKeyOptions, VerifyApiKeyResult, VerifyConnectParams, VerifyMessageParams, 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, signMessage, signMessageRequestSchema, signTransaction, signTransactionRequestSchema, signatureFromBase58, submitTransaction, u32be, utf8ToBytes, verifyApiKey, verifyConnect, verifyHashed, verifyMessage };
package/dist/index.js CHANGED
@@ -1,12 +1,13 @@
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";
1
+ import { API_KEY_DST, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, DEFAULT_BRIDGE_URL, MAX_API_KEY_STRING_LENGTH, MAX_MESSAGE_LENGTH, MESSAGE_DST, 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
2
  import { WalletSdkError } from "./errors.js";
3
3
  import { bytesToUtf8, concatBytes, equalBytes, randomBytes, randomId, u32be, utf8ToBytes } from "./bytes.js";
4
4
  import { BYTES_TAG, decodeBinaryValues, describeBinaryValues, encodeBinaryValues, isTaggedBytes } from "./binary.js";
5
5
  import { signTransaction, submitTransaction } from "./tx.js";
6
6
  import { getAmadeusProvider, isProviderAvailable } from "./types.js";
7
- import { addressSchema, connectTranscriptSchema, generateApiKeyRequestSchema, networkSchema, originSchema, sessionPublicKeySchema, signTransactionRequestSchema } from "./schema.js";
7
+ import { addressSchema, connectTranscriptSchema, generateApiKeyRequestSchema, networkSchema, originSchema, sessionPublicKeySchema, signMessageRequestSchema, signTransactionRequestSchema } from "./schema.js";
8
8
  import { deriveSigner, publicKeyFromAddress, signHashed, signatureFromBase58, verifyHashed } from "./crypto/bls.js";
9
9
  import { decodeApiKey, generateApiKey, verifyApiKey } from "./crypto/apikey.js";
10
+ import { signMessage, verifyMessage } from "./crypto/message.js";
10
11
  import { buildConnectTranscript, signConnect, verifyConnect } from "./crypto/connect.js";
11
12
  import { deriveSharedKey, generateSessionKeypair, open, seal } from "./crypto/box.js";
12
13
  import { WALLET_METHODS, createMemorySeenStore, guardRequest, makeRequest, openRequest, openResponse, sealRequest, sealResponse } from "./transport/envelope.js";
@@ -15,4 +16,4 @@ import { approveConnect, completeConnect, createConnectRequest, isConnectRequest
15
16
  import { BridgeClient, assertAllowedBridgeUrl, deriveBridgeChannels, deriveConnectChannel } from "./transport/bridge.js";
16
17
  import { handleRequest } from "./wallet/handler.js";
17
18
  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 };
19
+ export { API_KEY_DST, BYTES_TAG, BridgeClient, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, DEFAULT_BRIDGE_URL, MAX_API_KEY_STRING_LENGTH, MAX_MESSAGE_LENGTH, MESSAGE_DST, 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, signMessage, signMessageRequestSchema, signTransaction, signTransactionRequestSchema, signatureFromBase58, submitTransaction, u32be, utf8ToBytes, verifyApiKey, verifyConnect, verifyHashed, verifyMessage };
package/dist/schema.d.ts CHANGED
@@ -35,6 +35,14 @@ declare const generateApiKeyRequestSchema: z.ZodObject<{
35
35
  aud: string;
36
36
  exp_in: number;
37
37
  }>;
38
+ /** `signMessage` params — an arbitrary UTF-8 message, bounded for safety. */
39
+ declare const signMessageRequestSchema: z.ZodObject<{
40
+ message: z.ZodString;
41
+ }, "strip", z.ZodTypeAny, {
42
+ message: string;
43
+ }, {
44
+ message: string;
45
+ }>;
38
46
  /** The connect transcript fields carried by a deep link / QR payload. */
39
47
  declare const connectTranscriptSchema: z.ZodObject<{
40
48
  origin: z.ZodEffects<z.ZodString, string, string>;
@@ -57,7 +65,8 @@ declare const connectTranscriptSchema: z.ZodObject<{
57
65
  }>;
58
66
  type SignTransactionRequestInput = z.infer<typeof signTransactionRequestSchema>;
59
67
  type GenerateApiKeyRequestInput = z.infer<typeof generateApiKeyRequestSchema>;
68
+ type SignMessageRequestInput = z.infer<typeof signMessageRequestSchema>;
60
69
  type ConnectTranscriptInput = z.infer<typeof connectTranscriptSchema>;
61
70
  //#endregion
62
- export { ConnectTranscriptInput, GenerateApiKeyRequestInput, SignTransactionRequestInput, addressSchema, connectTranscriptSchema, generateApiKeyRequestSchema, networkSchema, originSchema, sessionPublicKeySchema, signTransactionRequestSchema };
71
+ export { ConnectTranscriptInput, GenerateApiKeyRequestInput, SignMessageRequestInput, SignTransactionRequestInput, addressSchema, connectTranscriptSchema, generateApiKeyRequestSchema, networkSchema, originSchema, sessionPublicKeySchema, signMessageRequestSchema, signTransactionRequestSchema };
63
72
  //# sourceMappingURL=schema.d.ts.map
@@ -1 +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"}
1
+ {"version":3,"file":"schema.d.ts","names":[],"sources":["../src/schema.ts"],"mappings":";;;cAiCa,cAAY,EAAA,WAAA,EAAA;;cAKZ,eAAa,EAAA,WAAA,EAAA;;cAGb,wBAAsB,EAAA,WAAA,EAAA;cAKtB,eAAa,EAAA;;cAGb,8BAA4B,EAAA;;;;;;;;;;;;;;;;;cAQ5B,6BAA2B,EAAA;;;;;;;;;;;cAM3B,0BAAwB,EAAA;;;;;;;;cAKxB,yBAAuB,EAAA;;;;;;;;;;;;;;;;;;;KAQxB,8BAA8B,EAAE,aAAa;KAC7C,6BAA6B,EAAE,aAAa;KAC5C,0BAA0B,EAAE,aAAa;KACzC,yBAAyB,EAAE,aAAa"}
package/dist/schema.js CHANGED
@@ -1,4 +1,4 @@
1
- import { NETWORKS } from "./constants.js";
1
+ import { MAX_MESSAGE_LENGTH, NETWORKS } from "./constants.js";
2
2
  import { fromBase58 } from "@amadeus-protocol/sdk";
3
3
  import { z } from "zod";
4
4
  //#region src/schema.ts
@@ -38,6 +38,8 @@ const generateApiKeyRequestSchema = z.object({
38
38
  aud: z.string().min(1),
39
39
  exp_in: z.number().int().positive()
40
40
  });
41
+ /** `signMessage` params — an arbitrary UTF-8 message, bounded for safety. */
42
+ const signMessageRequestSchema = z.object({ message: z.string().min(1).max(MAX_MESSAGE_LENGTH) });
41
43
  /** The connect transcript fields carried by a deep link / QR payload. */
42
44
  const connectTranscriptSchema = z.object({
43
45
  origin: originSchema,
@@ -47,6 +49,6 @@ const connectTranscriptSchema = z.object({
47
49
  requestId: z.string().min(1)
48
50
  });
49
51
  //#endregion
50
- export { addressSchema, connectTranscriptSchema, generateApiKeyRequestSchema, networkSchema, originSchema, sessionPublicKeySchema, signTransactionRequestSchema };
52
+ export { addressSchema, connectTranscriptSchema, generateApiKeyRequestSchema, networkSchema, originSchema, sessionPublicKeySchema, signMessageRequestSchema, signTransactionRequestSchema };
51
53
 
52
54
  //# sourceMappingURL=schema.js.map
@@ -1 +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"}
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 {\n\tMAX_MESSAGE_LENGTH,\n\tNETWORKS,\n\tPUBLIC_KEY_BYTE_LENGTH,\n\tSESSION_PUBLIC_KEY_BYTE_LENGTH\n} 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/** `signMessage` params — an arbitrary UTF-8 message, bounded for safety. */\nexport const signMessageRequestSchema = z.object({\n\tmessage: z.string().min(1).max(MAX_MESSAGE_LENGTH)\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 SignMessageRequestInput = z.infer<typeof signMessageRequestSchema>\nexport type ConnectTranscriptInput = z.infer<typeof connectTranscriptSchema>\n"],"mappings":";;;;;;;;;;;;AAmBA,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,2BAA2B,EAAE,OAAO,EAChD,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,kBAAkB,EAClD,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"}
@@ -1 +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"}
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;;EAaf,KAAK,YAAY,YAAY,mBAAmB;;;;;;;;EAmBtD,MACC,UAAU,OAAO,uBAAuB,eACxC,WAAW"}
@@ -60,7 +60,7 @@ var BridgeClient = class {
60
60
  assertAllowedBridgeUrl(options.bridgeUrl);
61
61
  this.bridgeUrl = options.bridgeUrl.replace(/\/$/, "");
62
62
  this.clientId = options.clientId;
63
- this.fetchImpl = options.fetchImpl ?? fetch;
63
+ this.fetchImpl = options.fetchImpl ?? fetch.bind(globalThis);
64
64
  this.pollWaitSeconds = options.pollWaitSeconds ?? 25;
65
65
  }
66
66
  /** Send a frame (sealed envelope, or plaintext connect response) to a channel id. */
@@ -1 +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;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I,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"}
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\t// Bind to the global: a bare `fetch` reference called as `this.fetchImpl(...)`\n\t\t// is detached from its global and throws \"Illegal invocation\" in browsers\n\t\t// (WebIDL requires `this` to be the Window/WorkerGlobalScope). Node/RN tolerate\n\t\t// it, which is why this only surfaces in a real browser dApp.\n\t\tthis.fetchImpl = options.fetchImpl ?? fetch.bind(globalThis)\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,uB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AK,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"}
@@ -13,6 +13,12 @@ interface WalletRequest {
13
13
  params: unknown;
14
14
  /** Unix-seconds expiry. */
15
15
  exp: number;
16
+ /**
17
+ * Optional Base58 address the dApp wants to act with. The wallet resolves the
18
+ * matching account's seed to sign; absent → the session's bound account. Lets
19
+ * a multi-account dApp choose which account signs without reconnecting.
20
+ */
21
+ account?: string;
16
22
  }
17
23
  type WalletResponse = {
18
24
  v: number;
@@ -34,6 +40,7 @@ declare function makeRequest(params: {
34
40
  method: WalletMethod;
35
41
  origin: string;
36
42
  params: unknown;
43
+ account?: string;
37
44
  ttlSeconds?: number;
38
45
  now?: number;
39
46
  }): WalletRequest;
@@ -1 +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"}
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;;;;;;EAMA;;KAGW;EACP;EAAW;EAAY;EAAU;;EACjC;EAAW;EAAY;EAAW;IAAS;IAAc;;;;iBA4B9C,YAAY;EAC3B;EACA,QAAQ;EACR;EACA;EACA;EACA;EACA;IACG;iBAaY,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"}
@@ -26,7 +26,8 @@ const walletRequestSchema = z.object({
26
26
  method: z.enum(WALLET_METHODS),
27
27
  origin: z.string().min(1),
28
28
  params: z.unknown(),
29
- exp: z.number().int()
29
+ exp: z.number().int(),
30
+ account: z.string().min(1).max(128).optional()
30
31
  });
31
32
  const walletResponseSchema = z.union([z.object({
32
33
  v: z.number().int(),
@@ -51,7 +52,8 @@ function makeRequest(params) {
51
52
  method: params.method,
52
53
  origin: params.origin,
53
54
  params: params.params,
54
- exp: nowSec + (params.ttlSeconds ?? 120)
55
+ exp: nowSec + (params.ttlSeconds ?? 120),
56
+ ...params.account ? { account: params.account } : {}
55
57
  };
56
58
  }
57
59
  function sealRequest(sharedKey, request) {
@@ -1 +1 @@
1
- {"version":3,"file":"envelope.js","names":[],"sources":["../../src/transport/envelope.ts"],"sourcesContent":["/**\n * The encrypted request/response envelope that flows over ANY transport (deep\n * link, QR, or the cross-device bridge). Post-connect, both sides hold the x25519\n * shared key, so every request and response is sealed — even same-device deep\n * links carry ciphertext, so a hijacked scheme yields an unusable blob.\n *\n * Methods mirror the wallet extension's provider vocabulary so a dApp integrates\n * once against the same names on every transport.\n */\n\nimport { z } from 'zod'\n\nimport { PROTOCOL_VERSION } from '../constants'\nimport { bytesToUtf8, utf8ToBytes } from '../bytes'\nimport { open, seal, type SealedEnvelope } from '../crypto/box'\nimport { WalletSdkError } from '../errors'\n\nexport const WALLET_METHODS = [\n\t'amadeus_signTransaction',\n\t'amadeus_signMessage',\n\t'amadeus_getAccounts',\n\t'amadeus_generateApiKey',\n\t'amadeus_switchNetwork'\n] as const\n\nexport type WalletMethod = (typeof WALLET_METHODS)[number]\n\nexport interface WalletRequest {\n\t/** Protocol version. */\n\tv: number\n\t/** Unique, one-time request id (replay key). */\n\tid: string\n\tmethod: WalletMethod\n\t/** The dApp origin, echoed for display in the approval UI. */\n\torigin: string\n\tparams: unknown\n\t/** Unix-seconds expiry. */\n\texp: number\n}\n\nexport type WalletResponse =\n\t| { v: number; id: string; ok: true; result: unknown }\n\t| { v: number; id: string; ok: false; error: { code: string; message: string } }\n\nconst walletRequestSchema = z.object({\n\tv: z.number().int(),\n\tid: z.string().min(1).max(128),\n\tmethod: z.enum(WALLET_METHODS),\n\torigin: z.string().min(1),\n\tparams: z.unknown(),\n\texp: z.number().int()\n})\n\nconst walletResponseSchema = z.union([\n\tz.object({\n\t\tv: z.number().int(),\n\t\tid: z.string().min(1).max(128),\n\t\tok: z.literal(true),\n\t\tresult: z.unknown()\n\t}),\n\tz.object({\n\t\tv: z.number().int(),\n\t\tid: z.string().min(1).max(128),\n\t\tok: z.literal(false),\n\t\terror: z.object({ code: z.string(), message: z.string() })\n\t})\n])\n\n/** Build an unsealed request with the current protocol version and a TTL. */\nexport function makeRequest(params: {\n\tid: string\n\tmethod: WalletMethod\n\torigin: string\n\tparams: unknown\n\tttlSeconds?: number\n\tnow?: number\n}): WalletRequest {\n\tconst nowSec = Math.floor((params.now ?? Date.now()) / 1000)\n\treturn {\n\t\tv: PROTOCOL_VERSION,\n\t\tid: params.id,\n\t\tmethod: params.method,\n\t\torigin: params.origin,\n\t\tparams: params.params,\n\t\texp: nowSec + (params.ttlSeconds ?? 120)\n\t}\n}\n\nexport function sealRequest(sharedKey: Uint8Array, request: WalletRequest): SealedEnvelope {\n\treturn seal(sharedKey, utf8ToBytes(JSON.stringify(request)))\n}\n\n/**\n * Decrypt + structurally validate an inbound request. Throws `DECRYPT_FAILED` if\n * the envelope is not authentic, `INVALID_ARGUMENT` if the plaintext is not a\n * well-formed request. Does NOT check expiry/replay — call `guardRequest` for\n * that policy step (kept separate so the crypto and the policy are distinct).\n */\nexport function openRequest(sharedKey: Uint8Array, envelope: SealedEnvelope): WalletRequest {\n\tconst bytes = open(sharedKey, envelope)\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(bytesToUtf8(bytes))\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'request is not valid JSON')\n\t}\n\tconst result = walletRequestSchema.safeParse(parsed)\n\tif (!result.success) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'request failed schema validation')\n\t}\n\treturn result.data as WalletRequest\n}\n\nexport function sealResponse(sharedKey: Uint8Array, response: WalletResponse): SealedEnvelope {\n\treturn seal(sharedKey, utf8ToBytes(JSON.stringify(response)))\n}\n\n/**\n * Decrypt + validate an inbound response, optionally asserting it answers\n * `expectedId` (defends against a swapped/mismatched reply).\n */\nexport function openResponse(\n\tsharedKey: Uint8Array,\n\tenvelope: SealedEnvelope,\n\texpectedId?: string\n): WalletResponse {\n\tconst bytes = open(sharedKey, envelope)\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(bytesToUtf8(bytes))\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response is not valid JSON')\n\t}\n\tconst result = walletResponseSchema.safeParse(parsed)\n\tif (!result.success) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response failed schema validation')\n\t}\n\tconst response = result.data as WalletResponse\n\tif (expectedId !== undefined && response.id !== expectedId) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response id does not match the request')\n\t}\n\treturn response\n}\n\n/**\n * A one-time-id store for replay defense. The in-memory default is fine for a\n * single process; the mobile wallet should supply a PERSISTED implementation\n * (e.g. expo-secure-store) so a crash/relaunch inside the TTL window can't let a\n * captured approval replay. `has`+`add` must be atomic in the persisted impl.\n */\nexport interface SeenStore {\n\thas(id: string): boolean\n\tadd(id: string): void\n}\n\nexport function createMemorySeenStore(maxEntries = 10_000): SeenStore {\n\tconst ids = new Set<string>()\n\treturn {\n\t\thas: (id) => ids.has(id),\n\t\tadd: (id) => {\n\t\t\tif (ids.size >= maxEntries) ids.delete(ids.values().next().value as string)\n\t\t\tids.add(id)\n\t\t}\n\t}\n}\n\n/**\n * Policy gate: enforce expiry + one-time id BEFORE acting on a request (i.e.\n * before building/signing anything). Atomic check-and-add against `store`.\n * Throws `EXPIRED` or `INVALID_ARGUMENT` (duplicate).\n */\nexport function guardRequest(request: WalletRequest, store: SeenStore, now?: number): void {\n\tconst nowSec = Math.floor((now ?? Date.now()) / 1000)\n\tif (request.exp <= nowSec) {\n\t\tthrow new WalletSdkError('EXPIRED', 'request has expired')\n\t}\n\tif (store.has(request.id)) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'duplicate request id (replay)')\n\t}\n\tstore.add(request.id)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAa,iBAAiB;CAC7B;CACA;CACA;CACA;CACA;AACD;AAqBA,MAAM,sBAAsB,EAAE,OAAO;CACpC,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI;CAClB,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;CAC7B,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sourcesContent":["/**\n * The encrypted request/response envelope that flows over ANY transport (deep\n * link, QR, or the cross-device bridge). Post-connect, both sides hold the x25519\n * shared key, so every request and response is sealed — even same-device deep\n * links carry ciphertext, so a hijacked scheme yields an unusable blob.\n *\n * Methods mirror the wallet extension's provider vocabulary so a dApp integrates\n * once against the same names on every transport.\n */\n\nimport { z } from 'zod'\n\nimport { PROTOCOL_VERSION } from '../constants'\nimport { bytesToUtf8, utf8ToBytes } from '../bytes'\nimport { open, seal, type SealedEnvelope } from '../crypto/box'\nimport { WalletSdkError } from '../errors'\n\nexport const WALLET_METHODS = [\n\t'amadeus_signTransaction',\n\t'amadeus_signMessage',\n\t'amadeus_getAccounts',\n\t'amadeus_generateApiKey',\n\t'amadeus_switchNetwork'\n] as const\n\nexport type WalletMethod = (typeof WALLET_METHODS)[number]\n\nexport interface WalletRequest {\n\t/** Protocol version. */\n\tv: number\n\t/** Unique, one-time request id (replay key). */\n\tid: string\n\tmethod: WalletMethod\n\t/** The dApp origin, echoed for display in the approval UI. */\n\torigin: string\n\tparams: unknown\n\t/** Unix-seconds expiry. */\n\texp: number\n\t/**\n\t * Optional Base58 address the dApp wants to act with. The wallet resolves the\n\t * matching account's seed to sign; absent → the session's bound account. Lets\n\t * a multi-account dApp choose which account signs without reconnecting.\n\t */\n\taccount?: string\n}\n\nexport type WalletResponse =\n\t| { v: number; id: string; ok: true; result: unknown }\n\t| { v: number; id: string; ok: false; error: { code: string; message: string } }\n\nconst walletRequestSchema = z.object({\n\tv: z.number().int(),\n\tid: z.string().min(1).max(128),\n\tmethod: z.enum(WALLET_METHODS),\n\torigin: z.string().min(1),\n\tparams: z.unknown(),\n\texp: z.number().int(),\n\taccount: z.string().min(1).max(128).optional()\n})\n\nconst walletResponseSchema = z.union([\n\tz.object({\n\t\tv: z.number().int(),\n\t\tid: z.string().min(1).max(128),\n\t\tok: z.literal(true),\n\t\tresult: z.unknown()\n\t}),\n\tz.object({\n\t\tv: z.number().int(),\n\t\tid: z.string().min(1).max(128),\n\t\tok: z.literal(false),\n\t\terror: z.object({ code: z.string(), message: z.string() })\n\t})\n])\n\n/** Build an unsealed request with the current protocol version and a TTL. */\nexport function makeRequest(params: {\n\tid: string\n\tmethod: WalletMethod\n\torigin: string\n\tparams: unknown\n\taccount?: string\n\tttlSeconds?: number\n\tnow?: number\n}): WalletRequest {\n\tconst nowSec = Math.floor((params.now ?? Date.now()) / 1000)\n\treturn {\n\t\tv: PROTOCOL_VERSION,\n\t\tid: params.id,\n\t\tmethod: params.method,\n\t\torigin: params.origin,\n\t\tparams: params.params,\n\t\texp: nowSec + (params.ttlSeconds ?? 120),\n\t\t...(params.account ? { account: params.account } : {})\n\t}\n}\n\nexport function sealRequest(sharedKey: Uint8Array, request: WalletRequest): SealedEnvelope {\n\treturn seal(sharedKey, utf8ToBytes(JSON.stringify(request)))\n}\n\n/**\n * Decrypt + structurally validate an inbound request. Throws `DECRYPT_FAILED` if\n * the envelope is not authentic, `INVALID_ARGUMENT` if the plaintext is not a\n * well-formed request. Does NOT check expiry/replay — call `guardRequest` for\n * that policy step (kept separate so the crypto and the policy are distinct).\n */\nexport function openRequest(sharedKey: Uint8Array, envelope: SealedEnvelope): WalletRequest {\n\tconst bytes = open(sharedKey, envelope)\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(bytesToUtf8(bytes))\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'request is not valid JSON')\n\t}\n\tconst result = walletRequestSchema.safeParse(parsed)\n\tif (!result.success) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'request failed schema validation')\n\t}\n\treturn result.data as WalletRequest\n}\n\nexport function sealResponse(sharedKey: Uint8Array, response: WalletResponse): SealedEnvelope {\n\treturn seal(sharedKey, utf8ToBytes(JSON.stringify(response)))\n}\n\n/**\n * Decrypt + validate an inbound response, optionally asserting it answers\n * `expectedId` (defends against a swapped/mismatched reply).\n */\nexport function openResponse(\n\tsharedKey: Uint8Array,\n\tenvelope: SealedEnvelope,\n\texpectedId?: string\n): WalletResponse {\n\tconst bytes = open(sharedKey, envelope)\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(bytesToUtf8(bytes))\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response is not valid JSON')\n\t}\n\tconst result = walletResponseSchema.safeParse(parsed)\n\tif (!result.success) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response failed schema validation')\n\t}\n\tconst response = result.data as WalletResponse\n\tif (expectedId !== undefined && response.id !== expectedId) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response id does not match the request')\n\t}\n\treturn response\n}\n\n/**\n * A one-time-id store for replay defense. The in-memory default is fine for a\n * single process; the mobile wallet should supply a PERSISTED implementation\n * (e.g. expo-secure-store) so a crash/relaunch inside the TTL window can't let a\n * captured approval replay. `has`+`add` must be atomic in the persisted impl.\n */\nexport interface SeenStore {\n\thas(id: string): boolean\n\tadd(id: string): void\n}\n\nexport function createMemorySeenStore(maxEntries = 10_000): SeenStore {\n\tconst ids = new Set<string>()\n\treturn {\n\t\thas: (id) => ids.has(id),\n\t\tadd: (id) => {\n\t\t\tif (ids.size >= maxEntries) ids.delete(ids.values().next().value as string)\n\t\t\tids.add(id)\n\t\t}\n\t}\n}\n\n/**\n * Policy gate: enforce expiry + one-time id BEFORE acting on a request (i.e.\n * before building/signing anything). Atomic check-and-add against `store`.\n * Throws `EXPIRED` or `INVALID_ARGUMENT` (duplicate).\n */\nexport function guardRequest(request: WalletRequest, store: SeenStore, now?: number): void {\n\tconst nowSec = Math.floor((now ?? Date.now()) / 1000)\n\tif (request.exp <= nowSec) {\n\t\tthrow new WalletSdkError('EXPIRED', 'request has expired')\n\t}\n\tif (store.has(request.id)) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'duplicate request id (replay)')\n\t}\n\tstore.add(request.id)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAa,iBAAiB;CAC7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SAAgB,aAAa,SAAwB,OAAkB,KAAoB;CAC1F,MAAM,SAAS,KAAK,OAAO,OAAO,KAAK,IAAI,KAAK,GAAI;CACpD,IAAI,QAAQ,OAAO,QAClB,MAAM,IAAI,eAAe,WAAW,qBAAqB;CAE1D,IAAI,MAAM,IAAI,QAAQ,EAAE,GACvB,MAAM,IAAI,eAAe,oBAAoB,+BAA+B;CAE7E,MAAM,IAAI,QAAQ,EAAE;AACrB"}
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.ts","names":[],"sources":["../../src/transport/session.ts"],"mappings":";;;;UA4BiB;EAChB;EACA;EACA;;EAEA,aAAa;EACb;EACA;;UAGgB;;EAEhB;;EAEA,WAAW;;EAEX;;EAEA;EACA;;EAEA;;;iBAIe,qBAAqB;EACpC;EACA;EACA;EACA;EACA;;EACK;EAAa,SAAS;;;;;;;iBAkCZ,gBACf,SAAS,gBACT,UAAU,wBACR;UA4Bc;;EAEhB,UAAU;;EAEV,WAAW;;EAEX,eAAe;;EAEf;;EAEA;;;;;;;;iBASe,eACf,SAAS,sBACT;EAAW;EAAc;IACvB;;iBA4Ba,wBAAwB,SAAS,sBAAsB"}
1
+ {"version":3,"file":"session.d.ts","names":[],"sources":["../../src/transport/session.ts"],"mappings":";;;;UA6BiB;EAChB;EACA;EACA;;EAEA,aAAa;EACb;EACA;;UAGgB;;EAEhB;;EAEA,WAAW;;EAEX;;EAEA;EACA;;EAEA;;;iBAIe,qBAAqB;EACpC;EACA;EACA;EACA;EACA;;EACK;EAAa,SAAS;;;;;;;iBAoCZ,gBACf,SAAS,gBACT,UAAU,wBACR;UA4Bc;;EAEhB,UAAU;;EAEV,WAAW;;EAEX,eAAe;;EAEf;;EAEA;;;;;;;;iBASe,eACf,SAAS,sBACT;EAAW;EAAc;IACvB;;iBA4Ba,wBAAwB,SAAS,sBAAsB"}
@@ -1,3 +1,4 @@
1
+ import "../constants.js";
1
2
  import { WalletSdkError } from "../errors.js";
2
3
  import { randomBytes, randomId } from "../bytes.js";
3
4
  import { signConnect, verifyConnect } from "../crypto/connect.js";
@@ -27,6 +28,7 @@ function createConnectRequest(options) {
27
28
  const challenge = toBase58(randomBytes(16));
28
29
  const requestId = randomId();
29
30
  const exp = Math.floor((options.now ?? Date.now()) / 1e3) + (options.ttlSeconds ?? 120);
31
+ const bridgeUrl = options.bridgeUrl ?? "https://bridge.ama.one";
30
32
  return {
31
33
  uri: buildConnectUri({
32
34
  origin: options.origin,
@@ -35,7 +37,7 @@ function createConnectRequest(options) {
35
37
  requestId,
36
38
  exp,
37
39
  redirectLink: options.redirectLink,
38
- bridgeUrl: options.bridgeUrl
40
+ bridgeUrl
39
41
  }),
40
42
  pending: {
41
43
  requestId,
@@ -43,7 +45,7 @@ function createConnectRequest(options) {
43
45
  origin: options.origin,
44
46
  dappKeypair,
45
47
  exp,
46
- bridgeUrl: options.bridgeUrl
48
+ bridgeUrl
47
49
  }
48
50
  };
49
51
  }
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","names":[],"sources":["../../src/transport/session.ts"],"sourcesContent":["/**\n * The connect handshake, orchestrated for both sides. This is where the crypto\n * primitives (connect transcript signing + x25519 box) and the URI transport\n * come together into an actual dApp <-> wallet session.\n *\n * Flow:\n * dApp: createConnectRequest() -> show `uri` (link/QR), keep `pending`\n * wallet: parseConnectUri(uri) -> [approve in UI] -> approveConnect()\n * -> return `response` to the dApp\n * dApp: completeConnect(pending, response) -> EstablishedSession\n *\n * After that both sides hold the same `sharedKey` and exchange sealed envelopes\n * (see envelope.ts). The wallet signs the transcript binding origin + BOTH\n * session keys + challenge + requestId, so a captured proof can't be replayed\n * under substituted keys.\n */\n\nimport { toBase58 } from '@amadeus-protocol/sdk'\n\nimport { randomBytes, randomId } from '../bytes'\nimport { signConnect, verifyConnect, type ConnectTranscript } from '../crypto/connect'\nimport { deriveSharedKey, generateSessionKeypair, type SessionKeypair } from '../crypto/box'\nimport { WalletSdkError } from '../errors'\nimport { buildConnectUri, type ConnectRequestParams, type ConnectResponseParams } from './uri'\n\n// ── dApp side ───────────────────────────────────────────────────────────────\n\n/** State the dApp keeps locally between issuing a connect request and completing it. */\nexport interface PendingConnect {\n\trequestId: string\n\tchallenge: string\n\torigin: string\n\t/** The dApp's ephemeral session keypair (secret stays local). */\n\tdappKeypair: SessionKeypair\n\texp: number\n\tbridgeUrl?: string\n}\n\nexport interface EstablishedSession {\n\t/** The connected wallet address (Base58 public key). */\n\taddress: string\n\t/** 32-byte symmetric key for sealing/opening envelopes. Keep in memory only. */\n\tsharedKey: Uint8Array\n\t/** The wallet's session key — the peer's bridge client id to send frames to. */\n\twalletPublicKey: string\n\t/** This dApp's session key — its own bridge client id to listen on. */\n\tselfPublicKey: string\n\torigin: string\n\t/** Relay base URL for post-connect sealed messages, if provided. */\n\tbridgeUrl?: string\n}\n\n/** dApp: create a connect request. Returns the URI to display and the pending state to keep. */\nexport function createConnectRequest(options: {\n\torigin: string\n\tredirectLink?: string\n\tbridgeUrl?: string\n\tttlSeconds?: number\n\tnow?: number\n}): { uri: string; pending: PendingConnect } {\n\tconst dappKeypair = generateSessionKeypair()\n\tconst challenge = toBase58(randomBytes(16))\n\tconst requestId = randomId()\n\tconst nowSec = Math.floor((options.now ?? Date.now()) / 1000)\n\tconst exp = nowSec + (options.ttlSeconds ?? 120)\n\n\tconst params: ConnectRequestParams = {\n\t\torigin: options.origin,\n\t\tdappPublicKey: dappKeypair.publicKey,\n\t\tchallenge,\n\t\trequestId,\n\t\texp,\n\t\tredirectLink: options.redirectLink,\n\t\tbridgeUrl: options.bridgeUrl\n\t}\n\treturn {\n\t\turi: buildConnectUri(params),\n\t\tpending: {\n\t\t\trequestId,\n\t\t\tchallenge,\n\t\t\torigin: options.origin,\n\t\t\tdappKeypair,\n\t\t\texp,\n\t\t\tbridgeUrl: options.bridgeUrl\n\t\t}\n\t}\n}\n\n/**\n * dApp: verify the wallet's connect response and establish the session. Throws\n * `INVALID_ARGUMENT` if the response is for a different request, or\n * `BAD_SIGNATURE` if the connect proof does not verify against the transcript.\n */\nexport function completeConnect(\n\tpending: PendingConnect,\n\tresponse: ConnectResponseParams\n): EstablishedSession {\n\tif (response.requestId !== pending.requestId) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response does not match the pending request')\n\t}\n\tconst transcript: ConnectTranscript = {\n\t\torigin: pending.origin,\n\t\tdappPublicKey: pending.dappKeypair.publicKey,\n\t\twalletPublicKey: response.walletPublicKey,\n\t\tchallenge: pending.challenge,\n\t\trequestId: pending.requestId\n\t}\n\tif (!verifyConnect({ address: response.address, transcript, signature: response.signature })) {\n\t\tthrow new WalletSdkError('BAD_SIGNATURE', 'connect proof failed verification')\n\t}\n\t// deriveSharedKey validates the wallet's session key (fails closed on a bad point).\n\tconst sharedKey = deriveSharedKey(response.walletPublicKey, pending.dappKeypair.secretKey)\n\treturn {\n\t\taddress: response.address,\n\t\tsharedKey,\n\t\twalletPublicKey: response.walletPublicKey,\n\t\tselfPublicKey: pending.dappKeypair.publicKey,\n\t\torigin: pending.origin,\n\t\tbridgeUrl: pending.bridgeUrl\n\t}\n}\n\n// ── wallet side ───────────────────────────────────────────────────────────────\n\nexport interface WalletSession {\n\t/** The response to hand back to the dApp (via callback URI or bridge frame). */\n\tresponse: ConnectResponseParams\n\t/** 32-byte symmetric key for sealing/opening envelopes. Keep in memory only. */\n\tsharedKey: Uint8Array\n\t/** The wallet's ephemeral session keypair for this dApp (its own bridge client id). */\n\twalletKeypair: SessionKeypair\n\t/** The dApp's session key — the peer's bridge client id to send frames to. */\n\tpeerPublicKey: string\n\t/** Relay base URL for post-connect sealed messages, if the dApp supplied one. */\n\tbridgeUrl?: string\n}\n\n/**\n * Wallet: approve a connect request and produce the signed response + session.\n * Call this ONLY AFTER the user has approved in the UI and the request's expiry\n * has been checked. `address` is the account that will be bound to this session\n * (bind to a specific account, not the live \"active\" one).\n */\nexport function approveConnect(\n\trequest: ConnectRequestParams,\n\toptions: { seed: string; address: string }\n): WalletSession {\n\tconst walletKeypair = generateSessionKeypair()\n\tconst transcript: ConnectTranscript = {\n\t\torigin: request.origin,\n\t\tdappPublicKey: request.dappPublicKey,\n\t\twalletPublicKey: walletKeypair.publicKey,\n\t\tchallenge: request.challenge,\n\t\trequestId: request.requestId\n\t}\n\tconst signature = signConnect({ seed: options.seed, transcript })\n\t// deriveSharedKey validates the dApp's session key (fails closed on a bad point).\n\tconst sharedKey = deriveSharedKey(request.dappPublicKey, walletKeypair.secretKey)\n\n\treturn {\n\t\tresponse: {\n\t\t\trequestId: request.requestId,\n\t\t\taddress: options.address,\n\t\t\twalletPublicKey: walletKeypair.publicKey,\n\t\t\tsignature\n\t\t},\n\t\tsharedKey,\n\t\twalletKeypair,\n\t\tpeerPublicKey: request.dappPublicKey,\n\t\tbridgeUrl: request.bridgeUrl\n\t}\n}\n\n/** Whether a parsed connect request has expired (wallet should reject/re-park). */\nexport function isConnectRequestExpired(request: ConnectRequestParams, now?: number): boolean {\n\treturn request.exp <= Math.floor((now ?? Date.now()) / 1000)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqDA,SAAgB,qBAAqB,SAMQ;CAC5C,MAAM,cAAc,uBAAuB;CAC3C,MAAM,YAAY,SAAS,YAAY,EAAE,CAAC;CAC1C,MAAM,YAAY,SAAS;CAE3B,MAAM,MADS,KAAK,OAAO,QAAQ,OAAO,KAAK,IAAI,KAAK,GACvC,KAAK,QAAQ,cAAc;CAW5C,OAAO;EACN,KAAK,gBAAgB;GATrB,QAAQ,QAAQ;GAChB,eAAe,YAAY;GAC3B;GACA;GACA;GACA,cAAc,QAAQ;GACtB,WAAW,QAAQ;EAGO,CAAC;EAC3B,SAAS;GACR;GACA;GACA,QAAQ,QAAQ;GAChB;GACA;GACA,WAAW,QAAQ;EACpB;CACD;AACD;;;;;;AAOA,SAAgB,gBACf,SACA,UACqB;CACrB,IAAI,SAAS,cAAc,QAAQ,WAClC,MAAM,IAAI,eAAe,oBAAoB,6CAA6C;CAE3F,MAAM,aAAgC;EACrC,QAAQ,QAAQ;EAChB,eAAe,QAAQ,YAAY;EACnC,iBAAiB,SAAS;EAC1B,WAAW,QAAQ;EACnB,WAAW,QAAQ;CACpB;CACA,IAAI,CAAC,cAAc;EAAE,SAAS,SAAS;EAAS;EAAY,WAAW,SAAS;CAAU,CAAC,GAC1F,MAAM,IAAI,eAAe,iBAAiB,mCAAmC;CAG9E,MAAM,YAAY,gBAAgB,SAAS,iBAAiB,QAAQ,YAAY,SAAS;CACzF,OAAO;EACN,SAAS,SAAS;EAClB;EACA,iBAAiB,SAAS;EAC1B,eAAe,QAAQ,YAAY;EACnC,QAAQ,QAAQ;EAChB,WAAW,QAAQ;CACpB;AACD;;;;;;;AAuBA,SAAgB,eACf,SACA,SACgB;CAChB,MAAM,gBAAgB,uBAAuB;CAC7C,MAAM,aAAgC;EACrC,QAAQ,QAAQ;EAChB,eAAe,QAAQ;EACvB,iBAAiB,cAAc;EAC/B,WAAW,QAAQ;EACnB,WAAW,QAAQ;CACpB;CACA,MAAM,YAAY,YAAY;EAAE,MAAM,QAAQ;EAAM;CAAW,CAAC;CAEhE,MAAM,YAAY,gBAAgB,QAAQ,eAAe,cAAc,SAAS;CAEhF,OAAO;EACN,UAAU;GACT,WAAW,QAAQ;GACnB,SAAS,QAAQ;GACjB,iBAAiB,cAAc;GAC/B;EACD;EACA;EACA;EACA,eAAe,QAAQ;EACvB,WAAW,QAAQ;CACpB;AACD;;AAGA,SAAgB,wBAAwB,SAA+B,KAAuB;CAC7F,OAAO,QAAQ,OAAO,KAAK,OAAO,OAAO,KAAK,IAAI,KAAK,GAAI;AAC5D"}
1
+ {"version":3,"file":"session.js","names":[],"sources":["../../src/transport/session.ts"],"sourcesContent":["/**\n * The connect handshake, orchestrated for both sides. This is where the crypto\n * primitives (connect transcript signing + x25519 box) and the URI transport\n * come together into an actual dApp <-> wallet session.\n *\n * Flow:\n * dApp: createConnectRequest() -> show `uri` (link/QR), keep `pending`\n * wallet: parseConnectUri(uri) -> [approve in UI] -> approveConnect()\n * -> return `response` to the dApp\n * dApp: completeConnect(pending, response) -> EstablishedSession\n *\n * After that both sides hold the same `sharedKey` and exchange sealed envelopes\n * (see envelope.ts). The wallet signs the transcript binding origin + BOTH\n * session keys + challenge + requestId, so a captured proof can't be replayed\n * under substituted keys.\n */\n\nimport { toBase58 } from '@amadeus-protocol/sdk'\n\nimport { DEFAULT_BRIDGE_URL } from '../constants'\nimport { randomBytes, randomId } from '../bytes'\nimport { signConnect, verifyConnect, type ConnectTranscript } from '../crypto/connect'\nimport { deriveSharedKey, generateSessionKeypair, type SessionKeypair } from '../crypto/box'\nimport { WalletSdkError } from '../errors'\nimport { buildConnectUri, type ConnectRequestParams, type ConnectResponseParams } from './uri'\n\n// ── dApp side ───────────────────────────────────────────────────────────────\n\n/** State the dApp keeps locally between issuing a connect request and completing it. */\nexport interface PendingConnect {\n\trequestId: string\n\tchallenge: string\n\torigin: string\n\t/** The dApp's ephemeral session keypair (secret stays local). */\n\tdappKeypair: SessionKeypair\n\texp: number\n\tbridgeUrl?: string\n}\n\nexport interface EstablishedSession {\n\t/** The connected wallet address (Base58 public key). */\n\taddress: string\n\t/** 32-byte symmetric key for sealing/opening envelopes. Keep in memory only. */\n\tsharedKey: Uint8Array\n\t/** The wallet's session key — the peer's bridge client id to send frames to. */\n\twalletPublicKey: string\n\t/** This dApp's session key — its own bridge client id to listen on. */\n\tselfPublicKey: string\n\torigin: string\n\t/** Relay base URL for post-connect sealed messages, if provided. */\n\tbridgeUrl?: string\n}\n\n/** dApp: create a connect request. Returns the URI to display and the pending state to keep. */\nexport function createConnectRequest(options: {\n\torigin: string\n\tredirectLink?: string\n\tbridgeUrl?: string\n\tttlSeconds?: number\n\tnow?: number\n}): { uri: string; pending: PendingConnect } {\n\tconst dappKeypair = generateSessionKeypair()\n\tconst challenge = toBase58(randomBytes(16))\n\tconst requestId = randomId()\n\tconst nowSec = Math.floor((options.now ?? Date.now()) / 1000)\n\tconst exp = nowSec + (options.ttlSeconds ?? 120)\n\t// Fall back to the production relay when the dApp doesn't pin its own.\n\tconst bridgeUrl = options.bridgeUrl ?? DEFAULT_BRIDGE_URL\n\n\tconst params: ConnectRequestParams = {\n\t\torigin: options.origin,\n\t\tdappPublicKey: dappKeypair.publicKey,\n\t\tchallenge,\n\t\trequestId,\n\t\texp,\n\t\tredirectLink: options.redirectLink,\n\t\tbridgeUrl\n\t}\n\treturn {\n\t\turi: buildConnectUri(params),\n\t\tpending: {\n\t\t\trequestId,\n\t\t\tchallenge,\n\t\t\torigin: options.origin,\n\t\t\tdappKeypair,\n\t\t\texp,\n\t\t\tbridgeUrl\n\t\t}\n\t}\n}\n\n/**\n * dApp: verify the wallet's connect response and establish the session. Throws\n * `INVALID_ARGUMENT` if the response is for a different request, or\n * `BAD_SIGNATURE` if the connect proof does not verify against the transcript.\n */\nexport function completeConnect(\n\tpending: PendingConnect,\n\tresponse: ConnectResponseParams\n): EstablishedSession {\n\tif (response.requestId !== pending.requestId) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'response does not match the pending request')\n\t}\n\tconst transcript: ConnectTranscript = {\n\t\torigin: pending.origin,\n\t\tdappPublicKey: pending.dappKeypair.publicKey,\n\t\twalletPublicKey: response.walletPublicKey,\n\t\tchallenge: pending.challenge,\n\t\trequestId: pending.requestId\n\t}\n\tif (!verifyConnect({ address: response.address, transcript, signature: response.signature })) {\n\t\tthrow new WalletSdkError('BAD_SIGNATURE', 'connect proof failed verification')\n\t}\n\t// deriveSharedKey validates the wallet's session key (fails closed on a bad point).\n\tconst sharedKey = deriveSharedKey(response.walletPublicKey, pending.dappKeypair.secretKey)\n\treturn {\n\t\taddress: response.address,\n\t\tsharedKey,\n\t\twalletPublicKey: response.walletPublicKey,\n\t\tselfPublicKey: pending.dappKeypair.publicKey,\n\t\torigin: pending.origin,\n\t\tbridgeUrl: pending.bridgeUrl\n\t}\n}\n\n// ── wallet side ───────────────────────────────────────────────────────────────\n\nexport interface WalletSession {\n\t/** The response to hand back to the dApp (via callback URI or bridge frame). */\n\tresponse: ConnectResponseParams\n\t/** 32-byte symmetric key for sealing/opening envelopes. Keep in memory only. */\n\tsharedKey: Uint8Array\n\t/** The wallet's ephemeral session keypair for this dApp (its own bridge client id). */\n\twalletKeypair: SessionKeypair\n\t/** The dApp's session key — the peer's bridge client id to send frames to. */\n\tpeerPublicKey: string\n\t/** Relay base URL for post-connect sealed messages, if the dApp supplied one. */\n\tbridgeUrl?: string\n}\n\n/**\n * Wallet: approve a connect request and produce the signed response + session.\n * Call this ONLY AFTER the user has approved in the UI and the request's expiry\n * has been checked. `address` is the account that will be bound to this session\n * (bind to a specific account, not the live \"active\" one).\n */\nexport function approveConnect(\n\trequest: ConnectRequestParams,\n\toptions: { seed: string; address: string }\n): WalletSession {\n\tconst walletKeypair = generateSessionKeypair()\n\tconst transcript: ConnectTranscript = {\n\t\torigin: request.origin,\n\t\tdappPublicKey: request.dappPublicKey,\n\t\twalletPublicKey: walletKeypair.publicKey,\n\t\tchallenge: request.challenge,\n\t\trequestId: request.requestId\n\t}\n\tconst signature = signConnect({ seed: options.seed, transcript })\n\t// deriveSharedKey validates the dApp's session key (fails closed on a bad point).\n\tconst sharedKey = deriveSharedKey(request.dappPublicKey, walletKeypair.secretKey)\n\n\treturn {\n\t\tresponse: {\n\t\t\trequestId: request.requestId,\n\t\t\taddress: options.address,\n\t\t\twalletPublicKey: walletKeypair.publicKey,\n\t\t\tsignature\n\t\t},\n\t\tsharedKey,\n\t\twalletKeypair,\n\t\tpeerPublicKey: request.dappPublicKey,\n\t\tbridgeUrl: request.bridgeUrl\n\t}\n}\n\n/** Whether a parsed connect request has expired (wallet should reject/re-park). */\nexport function isConnectRequestExpired(request: ConnectRequestParams, now?: number): boolean {\n\treturn request.exp <= Math.floor((now ?? Date.now()) / 1000)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAgB,qBAAqB,SAMQ;CAC5C,MAAM,cAAc,uBAAuB;CAC3C,MAAM,YAAY,SAAS,YAAY,EA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;GACT,WAAW,QAAQ;GACnB,SAAS,QAAQ;GACjB,iBAAiB,cAAc;GAC/B;EACD;EACA;EACA;EACA,eAAe,QAAQ;EACvB,WAAW,QAAQ;CACpB;AACD;;AAGA,SAAgB,wBAAwB,SAA+B,KAAuB;CAC7F,OAAO,QAAQ,OAAO,KAAK,OAAO,OAAO,KAAK,IAAI,KAAK,GAAI;AAC5D"}
@@ -1 +1 @@
1
- {"version":3,"file":"handler.d.ts","names":[],"sources":["../../src/wallet/handler.ts"],"mappings":";;UAkBiB;;EAEhB;;EAEA;;;;;;;;iBAmBe,cAAc,SAAS,eAAe,KAAK,uBAAuB"}
1
+ {"version":3,"file":"handler.d.ts","names":[],"sources":["../../src/wallet/handler.ts"],"mappings":";;UAuBiB;;EAEhB;;EAEA;;;;;;;;iBAmBe,cAAc,SAAS,eAAe,KAAK,uBAAuB"}
@@ -1,8 +1,9 @@
1
1
  import "../constants.js";
2
2
  import { WalletSdkError } from "../errors.js";
3
3
  import { signTransaction } from "../tx.js";
4
- import { generateApiKeyRequestSchema, signTransactionRequestSchema } from "../schema.js";
4
+ import { generateApiKeyRequestSchema, signMessageRequestSchema, signTransactionRequestSchema } from "../schema.js";
5
5
  import { generateApiKey } from "../crypto/apikey.js";
6
+ import { signMessage } from "../crypto/message.js";
6
7
  //#region src/wallet/handler.ts
7
8
  /**
8
9
  * Wallet-side request dispatch. Once the mobile app has opened + guarded an
@@ -65,7 +66,15 @@ function handleRequest(request, ctx) {
65
66
  return ok(request.id, { apiKey });
66
67
  }
67
68
  case "amadeus_getAccounts": return ok(request.id, { accounts: [ctx.address] });
68
- case "amadeus_signMessage": throw new WalletSdkError("INVALID_ARGUMENT", "amadeus_signMessage is not supported yet");
69
+ case "amadeus_signMessage": {
70
+ const parsed = signMessageRequestSchema.safeParse(request.params);
71
+ if (!parsed.success) throw new WalletSdkError("INVALID_ARGUMENT", "invalid signMessage params");
72
+ const signed = signMessage({
73
+ seed: ctx.seed,
74
+ message: parsed.data.message
75
+ });
76
+ return ok(request.id, signed);
77
+ }
69
78
  case "amadeus_switchNetwork": throw new WalletSdkError("INVALID_ARGUMENT", "amadeus_switchNetwork must be handled by the wallet app (it changes runtime state)");
70
79
  default: throw new WalletSdkError("INVALID_ARGUMENT", `unknown method`);
71
80
  }
@@ -1 +1 @@
1
- {"version":3,"file":"handler.js","names":[],"sources":["../../src/wallet/handler.ts"],"sourcesContent":["/**\n * Wallet-side request dispatch. Once the mobile app has opened + guarded an\n * inbound request and the user has approved it, this turns the request into a\n * signed response by routing to the right primitive. Keeping it here means the\n * app's approval screen only has to call one function; the wallet and extension\n * share identical request semantics.\n *\n * IMPORTANT: call this only AFTER `guardRequest` (expiry + replay) has passed and\n * the user has approved. It signs with the bound account's seed.\n */\n\nimport { PROTOCOL_VERSION } from '../constants'\nimport { generateApiKey } from '../crypto/apikey'\nimport { WalletSdkError } from '../errors'\nimport { generateApiKeyRequestSchema, signTransactionRequestSchema } from '../schema'\nimport { signTransaction } from '../tx'\nimport type { WalletRequest, WalletResponse } from '../transport/envelope'\n\nexport interface WalletHandlerContext {\n\t/** Seed (private key) of the account bound to this session. */\n\tseed: string\n\t/** Address (Base58 public key) of the bound account. */\n\taddress: string\n}\n\nfunction ok(id: string, result: unknown): WalletResponse {\n\treturn { v: PROTOCOL_VERSION, id, ok: true, result }\n}\n\nfunction fail(id: string, error: unknown): WalletResponse {\n\tconst code = error instanceof WalletSdkError ? error.code : 'INTERNAL'\n\tconst message = error instanceof Error ? error.message : 'unexpected error'\n\treturn { v: PROTOCOL_VERSION, id, ok: false, error: { code, message } }\n}\n\n/**\n * Service one approved request and return a response ready to seal. Never throws\n * — failures come back as `{ ok: false, error }` so the transport can always\n * reply. `amadeus_switchNetwork` is deliberately delegated to the app (it mutates\n * wallet runtime state), signalled with a distinct error the caller can branch on.\n */\nexport function handleRequest(request: WalletRequest, ctx: WalletHandlerContext): WalletResponse {\n\ttry {\n\t\tswitch (request.method) {\n\t\t\tcase 'amadeus_signTransaction': {\n\t\t\t\tconst parsed = signTransactionRequestSchema.safeParse(request.params)\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'invalid signTransaction params')\n\t\t\t\t}\n\t\t\t\tconst signed = signTransaction({\n\t\t\t\t\tseed: ctx.seed,\n\t\t\t\t\tcontract: parsed.data.contract,\n\t\t\t\t\tmethod: parsed.data.method,\n\t\t\t\t\targs: parsed.data.args,\n\t\t\t\t\tdescription: parsed.data.description\n\t\t\t\t})\n\t\t\t\treturn ok(request.id, signed)\n\t\t\t}\n\t\t\tcase 'amadeus_generateApiKey': {\n\t\t\t\tconst parsed = generateApiKeyRequestSchema.safeParse(request.params)\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'invalid generateApiKey params')\n\t\t\t\t}\n\t\t\t\tconst { apiKey } = generateApiKey({\n\t\t\t\t\tseed: ctx.seed,\n\t\t\t\t\taud: parsed.data.aud,\n\t\t\t\t\texpIn: parsed.data.exp_in\n\t\t\t\t})\n\t\t\t\treturn ok(request.id, { apiKey })\n\t\t\t}\n\t\t\tcase 'amadeus_getAccounts':\n\t\t\t\treturn ok(request.id, { accounts: [ctx.address] })\n\t\t\tcase 'amadeus_signMessage':\n\t\t\t\t// Structured, non-oracle message signing is not exposed in v0.1.\n\t\t\t\tthrow new WalletSdkError(\n\t\t\t\t\t'INVALID_ARGUMENT',\n\t\t\t\t\t'amadeus_signMessage is not supported yet'\n\t\t\t\t)\n\t\t\tcase 'amadeus_switchNetwork':\n\t\t\t\tthrow new WalletSdkError(\n\t\t\t\t\t'INVALID_ARGUMENT',\n\t\t\t\t\t'amadeus_switchNetwork must be handled by the wallet app (it changes runtime state)'\n\t\t\t\t)\n\t\t\tdefault:\n\t\t\t\tthrow new WalletSdkError('INVALID_ARGUMENT', `unknown method`)\n\t\t}\n\t} catch (error) {\n\t\treturn fail(request.id, error)\n\t}\n}\n"],"mappings":";;;;;;;;;;;;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OAAO;EACf,OAAO,KAAK,QAAQ,IAAI,KAAK;CAC9B;AACD"}
1
+ {"version":3,"file":"handler.js","names":[],"sources":["../../src/wallet/handler.ts"],"sourcesContent":["/**\n * Wallet-side request dispatch. Once the mobile app has opened + guarded an\n * inbound request and the user has approved it, this turns the request into a\n * signed response by routing to the right primitive. Keeping it here means the\n * app's approval screen only has to call one function; the wallet and extension\n * share identical request semantics.\n *\n * IMPORTANT: call this only AFTER `guardRequest` (expiry + replay) has passed and\n * the user has approved. It signs with the bound account's seed.\n */\n\nimport { PROTOCOL_VERSION } from '../constants'\nimport { generateApiKey } from '../crypto/apikey'\nimport { signMessage } from '../crypto/message'\nimport { WalletSdkError } from '../errors'\nimport {\n\tgenerateApiKeyRequestSchema,\n\tsignMessageRequestSchema,\n\tsignTransactionRequestSchema\n} from '../schema'\nimport { signTransaction } from '../tx'\nimport type { WalletRequest, WalletResponse } from '../transport/envelope'\n\nexport interface WalletHandlerContext {\n\t/** Seed (private key) of the account bound to this session. */\n\tseed: string\n\t/** Address (Base58 public key) of the bound account. */\n\taddress: string\n}\n\nfunction ok(id: string, result: unknown): WalletResponse {\n\treturn { v: PROTOCOL_VERSION, id, ok: true, result }\n}\n\nfunction fail(id: string, error: unknown): WalletResponse {\n\tconst code = error instanceof WalletSdkError ? error.code : 'INTERNAL'\n\tconst message = error instanceof Error ? error.message : 'unexpected error'\n\treturn { v: PROTOCOL_VERSION, id, ok: false, error: { code, message } }\n}\n\n/**\n * Service one approved request and return a response ready to seal. Never throws\n * — failures come back as `{ ok: false, error }` so the transport can always\n * reply. `amadeus_switchNetwork` is deliberately delegated to the app (it mutates\n * wallet runtime state), signalled with a distinct error the caller can branch on.\n */\nexport function handleRequest(request: WalletRequest, ctx: WalletHandlerContext): WalletResponse {\n\ttry {\n\t\tswitch (request.method) {\n\t\t\tcase 'amadeus_signTransaction': {\n\t\t\t\tconst parsed = signTransactionRequestSchema.safeParse(request.params)\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'invalid signTransaction params')\n\t\t\t\t}\n\t\t\t\tconst signed = signTransaction({\n\t\t\t\t\tseed: ctx.seed,\n\t\t\t\t\tcontract: parsed.data.contract,\n\t\t\t\t\tmethod: parsed.data.method,\n\t\t\t\t\targs: parsed.data.args,\n\t\t\t\t\tdescription: parsed.data.description\n\t\t\t\t})\n\t\t\t\treturn ok(request.id, signed)\n\t\t\t}\n\t\t\tcase 'amadeus_generateApiKey': {\n\t\t\t\tconst parsed = generateApiKeyRequestSchema.safeParse(request.params)\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'invalid generateApiKey params')\n\t\t\t\t}\n\t\t\t\tconst { apiKey } = generateApiKey({\n\t\t\t\t\tseed: ctx.seed,\n\t\t\t\t\taud: parsed.data.aud,\n\t\t\t\t\texpIn: parsed.data.exp_in\n\t\t\t\t})\n\t\t\t\treturn ok(request.id, { apiKey })\n\t\t\t}\n\t\t\tcase 'amadeus_getAccounts':\n\t\t\t\treturn ok(request.id, { accounts: [ctx.address] })\n\t\t\tcase 'amadeus_signMessage': {\n\t\t\t\tconst parsed = signMessageRequestSchema.safeParse(request.params)\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'invalid signMessage params')\n\t\t\t\t}\n\t\t\t\tconst signed = signMessage({ seed: ctx.seed, message: parsed.data.message })\n\t\t\t\treturn ok(request.id, signed)\n\t\t\t}\n\t\t\tcase 'amadeus_switchNetwork':\n\t\t\t\tthrow new WalletSdkError(\n\t\t\t\t\t'INVALID_ARGUMENT',\n\t\t\t\t\t'amadeus_switchNetwork must be handled by the wallet app (it changes runtime state)'\n\t\t\t\t)\n\t\t\tdefault:\n\t\t\t\tthrow new WalletSdkError('INVALID_ARGUMENT', `unknown method`)\n\t\t}\n\t} catch (error) {\n\t\treturn fail(request.id, error)\n\t}\n}\n"],"mappings":";;;;;;;;;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Y;KAAE,MAAM,IAAI;KAAM,SAAS,OAAO,KAAK;IAAQ,CAAC;IAC3E,OAAO,GAAG,QAAQ,IAAI,MAAM;GAC7B;GACA,KAAK,yBACJ,MAAM,IAAI,eACT,oBACA,oFACD;GACD,SACC,MAAM,IAAI,eAAe,oBAAoB,gBAAgB;EAC/D;CACD,SAAS,OAAO;EACf,OAAO,KAAK,QAAQ,IAAI,KAAK;CAC9B;AACD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amadeus-protocol/wallet-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.4",
4
4
  "description": "Shared dApp <-> wallet connection layer for Amadeus Protocol: BLS API-key tokens, transaction signing, message/connect signing, and the typed provider contract. One audited implementation for the wallet, the extension, and every dApp.",
5
5
  "type": "module",
6
6
  "sideEffects": false,