@amadeus-protocol/wallet-sdk 0.1.1 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bytes.d.ts.map +1 -1
- package/dist/constants.d.ts +15 -1
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +15 -1
- package/dist/constants.js.map +1 -1
- package/dist/crypto/apikey.js +4 -1
- package/dist/crypto/apikey.js.map +1 -1
- package/dist/crypto/box.js +2 -1
- package/dist/crypto/box.js.map +1 -1
- package/dist/crypto/connect.js +2 -1
- package/dist/crypto/connect.js.map +1 -1
- package/dist/crypto/message.d.ts +47 -0
- package/dist/crypto/message.d.ts.map +1 -0
- package/dist/crypto/message.js +54 -0
- package/dist/crypto/message.js.map +1 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/schema.d.ts +10 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +4 -2
- package/dist/schema.js.map +1 -1
- package/dist/transport/bridge.d.ts.map +1 -1
- package/dist/transport/bridge.js +2 -2
- package/dist/transport/bridge.js.map +1 -1
- package/dist/transport/envelope.d.ts +7 -0
- package/dist/transport/envelope.d.ts.map +1 -1
- package/dist/transport/envelope.js +4 -2
- package/dist/transport/envelope.js.map +1 -1
- package/dist/transport/session.js +10 -9
- package/dist/transport/session.js.map +1 -1
- package/dist/tx.d.ts +3 -9
- package/dist/tx.d.ts.map +1 -1
- package/dist/tx.js +12 -8
- package/dist/tx.js.map +1 -1
- package/dist/wallet/handler.d.ts +6 -0
- package/dist/wallet/handler.d.ts.map +1 -1
- package/dist/wallet/handler.js +13 -13
- package/dist/wallet/handler.js.map +1 -1
- package/package.json +4 -4
package/dist/bytes.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bytes.d.ts","names":[],"sources":["../src/bytes.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"bytes.d.ts","names":["concatBytes","nobleConcat","randomBytes","nobleRandom"],"sources":["../src/bytes.ts"],"mappings":";;cAeaA,sBAAWC;cACXC,sBAAWC;;iBAGR,SAAS;iBAIT,YAAY,gBAAgB;iBAI5B,YAAY,OAAO;;iBAKnB,MAAM,YAAY;;;;;;;iBAkBlB,WAAW,GAAG,YAAY,GAAG"}
|
package/dist/constants.d.ts
CHANGED
|
@@ -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;
|
|
@@ -72,5 +86,5 @@ declare const NETWORKS: readonly ["mainnet", "testnet", "custom"];
|
|
|
72
86
|
*/
|
|
73
87
|
declare const DEFAULT_BRIDGE_URL = "https://bridge.ama.one";
|
|
74
88
|
//#endregion
|
|
75
|
-
export { API_KEY_DST, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, DEFAULT_BRIDGE_URL, 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 };
|
|
76
90
|
//# sourceMappingURL=constants.d.ts.map
|
package/dist/constants.d.ts.map
CHANGED
|
@@ -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;;;;;;cAOA"}
|
|
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;
|
|
@@ -83,6 +97,6 @@ const NETWORKS = [
|
|
|
83
97
|
*/
|
|
84
98
|
const DEFAULT_BRIDGE_URL = "https://bridge.ama.one";
|
|
85
99
|
//#endregion
|
|
86
|
-
export { API_KEY_DST, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, DEFAULT_BRIDGE_URL, 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 };
|
|
87
101
|
|
|
88
102
|
//# sourceMappingURL=constants.js.map
|
package/dist/constants.js.map
CHANGED
|
@@ -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\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;;AAG3B,MAAa,yBAAyB;AACtC,MAAa,wBAAwB;AACrC,MAAa,mBAAmB;;;;;;;AAQhC,MAAa,4BAA4B;;
|
|
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"}
|
package/dist/crypto/apikey.js
CHANGED
|
@@ -30,8 +30,11 @@ function generateApiKey(params) {
|
|
|
30
30
|
aud: params.aud,
|
|
31
31
|
exp
|
|
32
32
|
}));
|
|
33
|
+
const signed = concatBytes(jsonBytes, pk);
|
|
34
|
+
const signature = signHashed(signed, sk, API_KEY_DST);
|
|
35
|
+
const token = concatBytes(jsonBytes, pk, signature);
|
|
33
36
|
return {
|
|
34
|
-
apiKey: toBase58(
|
|
37
|
+
apiKey: toBase58(token),
|
|
35
38
|
payload: {
|
|
36
39
|
aud: params.aud,
|
|
37
40
|
exp
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apikey.js","names":[],"sources":["../../src/crypto/apikey.ts"],"sourcesContent":["/**\n * BLS12-381 API-key bearer tokens — the ONE audited implementation, replacing\n * the byte-identical copies currently hand-rolled in the wallet extension\n * (`background/handlers/api-key.ts`) and hub/prime-hub (`utils/blsWallet.ts`).\n *\n * Token layout (concatenated, then Base58-encoded):\n * [ jsonBytes (variable) | pubkey (48) | signature (96) ]\n *\n * jsonBytes = utf8(JSON.stringify({ aud, exp })) // key order: aud THEN exp\n * exp = floor(now/1000) + expIn // unix seconds\n * signature = BLS.sign(sha256(jsonBytes || pubkey), sk, { DST: API_KEY_DST })\n *\n * Folding the pubkey into the signed hash blocks rogue-key attacks. `kbs.ama.one`\n * verifies against exactly this construction — do not alter the field order,\n * concatenation, or DST.\n */\n\nimport { fromBase58, toBase58 } from '@amadeus-protocol/sdk'\n\nimport {\n\tAPI_KEY_DST,\n\tMAX_API_KEY_STRING_LENGTH,\n\tPUBLIC_KEY_BYTE_LENGTH,\n\tSIGNATURE_BYTE_LENGTH\n} from '../constants'\nimport { WalletSdkError } from '../errors'\nimport { bytesToUtf8, concatBytes, utf8ToBytes } from '../bytes'\nimport { deriveSigner, signHashed, verifyHashed } from './bls'\n\nexport interface ApiKeyPayload {\n\taud: string\n\texp: number\n}\n\nexport interface GenerateApiKeyParams {\n\t/** Base58 wallet seed (private key). */\n\tseed: string\n\t/** Audience claim the bearer will present to. */\n\taud: string\n\t/** Lifetime in seconds from now. */\n\texpIn: number\n\t/** Override \"now\" (ms since epoch) — for deterministic tests. */\n\tnow?: number\n}\n\nexport interface GenerateApiKeyResult {\n\tapiKey: string\n\tpayload: ApiKeyPayload\n}\n\nexport function generateApiKey(params: GenerateApiKeyParams): GenerateApiKeyResult {\n\tif (!params.aud || params.aud.length === 0) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'aud is required')\n\t}\n\tif (!Number.isInteger(params.expIn) || params.expIn <= 0) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'expIn must be a positive integer (seconds)')\n\t}\n\n\tconst { sk, pk } = deriveSigner(params.seed)\n\tconst nowMs = params.now ?? Date.now()\n\tconst exp = Math.floor(nowMs / 1000) + params.expIn\n\n\t// IMPORTANT: object literal order (aud, then exp) fixes the JSON byte layout.\n\tconst jsonBytes = utf8ToBytes(JSON.stringify({ aud: params.aud, exp }))\n\tconst signed = concatBytes(jsonBytes, pk)\n\tconst signature = signHashed(signed, sk, API_KEY_DST)\n\tconst token = concatBytes(jsonBytes, pk, signature)\n\n\treturn { apiKey: toBase58(token), payload: { aud: params.aud, exp } }\n}\n\nexport interface DecodedApiKey {\n\tpayload: ApiKeyPayload\n\tpublicKey: Uint8Array\n\tsignature: Uint8Array\n\t/** The raw JSON bytes that were signed — needed to re-verify exactly. */\n\tjsonBytes: Uint8Array\n\t/** The signing address (Base58 of `publicKey`). */\n\taddress: string\n}\n\n/** Parse a token into its parts. Throws `WalletSdkError('INVALID_API_KEY')` on malformed input. */\nexport function decodeApiKey(apiKey: string): DecodedApiKey {\n\t// Bound untrusted input BEFORE the quadratic Base58 decode so an oversized\n\t// string can't stall the verifier (event-loop DoS).\n\tif (\n\t\ttypeof apiKey !== 'string' ||\n\t\tapiKey.length === 0 ||\n\t\tapiKey.length > MAX_API_KEY_STRING_LENGTH\n\t) {\n\t\tthrow new WalletSdkError('INVALID_API_KEY', 'api key length is out of range')\n\t}\n\n\tlet raw: Uint8Array\n\ttry {\n\t\traw = fromBase58(apiKey)\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_API_KEY', 'api key is not valid Base58')\n\t}\n\n\tconst jsonEnd = raw.length - PUBLIC_KEY_BYTE_LENGTH - SIGNATURE_BYTE_LENGTH\n\tif (jsonEnd <= 0) {\n\t\tthrow new WalletSdkError('INVALID_API_KEY', 'api key is too short to contain a payload')\n\t}\n\n\tconst jsonBytes = raw.slice(0, jsonEnd)\n\tconst publicKey = raw.slice(jsonEnd, jsonEnd + PUBLIC_KEY_BYTE_LENGTH)\n\tconst signature = raw.slice(jsonEnd + PUBLIC_KEY_BYTE_LENGTH)\n\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(bytesToUtf8(jsonBytes))\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_API_KEY', 'api key payload is not valid JSON')\n\t}\n\n\tif (\n\t\ttypeof parsed !== 'object' ||\n\t\tparsed === null ||\n\t\ttypeof (parsed as ApiKeyPayload).aud !== 'string' ||\n\t\ttypeof (parsed as ApiKeyPayload).exp !== 'number' ||\n\t\t!Number.isFinite((parsed as ApiKeyPayload).exp)\n\t) {\n\t\tthrow new WalletSdkError(\n\t\t\t'INVALID_API_KEY',\n\t\t\t'api key payload must be { aud: string, exp: number }'\n\t\t)\n\t}\n\n\tconst payload = parsed as ApiKeyPayload\n\treturn { payload, publicKey, signature, jsonBytes, address: toBase58(publicKey) }\n}\n\nexport interface VerifyApiKeyOptions {\n\t/** If provided, the token's `aud` must equal this. */\n\taud?: string\n\t/** Override \"now\" (ms since epoch) — for deterministic tests. */\n\tnow?: number\n\t/** Treat the token as expired this many seconds early (clock-skew guard). Default 0. */\n\tleewaySeconds?: number\n}\n\nexport type VerifyApiKeyResult =\n\t| { valid: true; payload: ApiKeyPayload; address: string }\n\t| { valid: false; reason: 'malformed' | 'bad_signature' | 'expired' | 'aud_mismatch' }\n\n/**\n * Full verification: structure -> BLS signature (under the API-key DST, with the\n * pubkey folded in) -> expiry -> optional audience. Returns a discriminated\n * result rather than throwing on the common \"invalid\" paths.\n */\nexport function verifyApiKey(\n\tapiKey: string,\n\toptions: VerifyApiKeyOptions = {}\n): VerifyApiKeyResult {\n\tlet decoded: DecodedApiKey\n\ttry {\n\t\tdecoded = decodeApiKey(apiKey)\n\t} catch {\n\t\treturn { valid: false, reason: 'malformed' }\n\t}\n\n\tconst signed = concatBytes(decoded.jsonBytes, decoded.publicKey)\n\tif (!verifyHashed(decoded.signature, signed, decoded.publicKey, API_KEY_DST)) {\n\t\treturn { valid: false, reason: 'bad_signature' }\n\t}\n\n\tconst nowSec = Math.floor((options.now ?? Date.now()) / 1000)\n\tconst leeway = options.leewaySeconds ?? 0\n\tif (decoded.payload.exp <= nowSec + leeway) {\n\t\treturn { valid: false, reason: 'expired' }\n\t}\n\n\tif (options.aud !== undefined && decoded.payload.aud !== options.aud) {\n\t\treturn { valid: false, reason: 'aud_mismatch' }\n\t}\n\n\treturn { valid: true, payload: decoded.payload, address: decoded.address }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,eAAe,QAAoD;CAClF,IAAI,CAAC,OAAO,OAAO,OAAO,IAAI,WAAW,GACxC,MAAM,IAAI,eAAe,oBAAoB,iBAAiB;CAE/D,IAAI,CAAC,OAAO,UAAU,OAAO,KAAK,KAAK,OAAO,SAAS,GACtD,MAAM,IAAI,eAAe,oBAAoB,4CAA4C;CAG1F,MAAM,EAAE,IAAI,OAAO,aAAa,OAAO,IAAI;CAC3C,MAAM,QAAQ,OAAO,OAAO,KAAK,IAAI;CACrC,MAAM,MAAM,KAAK,MAAM,QAAQ,GAAI,IAAI,OAAO;CAG9C,MAAM,YAAY,YAAY,KAAK,UAAU;EAAE,KAAK,OAAO;EAAK;CAAI,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"apikey.js","names":[],"sources":["../../src/crypto/apikey.ts"],"sourcesContent":["/**\n * BLS12-381 API-key bearer tokens — the ONE audited implementation, replacing\n * the byte-identical copies currently hand-rolled in the wallet extension\n * (`background/handlers/api-key.ts`) and hub/prime-hub (`utils/blsWallet.ts`).\n *\n * Token layout (concatenated, then Base58-encoded):\n * [ jsonBytes (variable) | pubkey (48) | signature (96) ]\n *\n * jsonBytes = utf8(JSON.stringify({ aud, exp })) // key order: aud THEN exp\n * exp = floor(now/1000) + expIn // unix seconds\n * signature = BLS.sign(sha256(jsonBytes || pubkey), sk, { DST: API_KEY_DST })\n *\n * Folding the pubkey into the signed hash blocks rogue-key attacks. `kbs.ama.one`\n * verifies against exactly this construction — do not alter the field order,\n * concatenation, or DST.\n */\n\nimport { fromBase58, toBase58 } from '@amadeus-protocol/sdk'\n\nimport {\n\tAPI_KEY_DST,\n\tMAX_API_KEY_STRING_LENGTH,\n\tPUBLIC_KEY_BYTE_LENGTH,\n\tSIGNATURE_BYTE_LENGTH\n} from '../constants'\nimport { WalletSdkError } from '../errors'\nimport { bytesToUtf8, concatBytes, utf8ToBytes } from '../bytes'\nimport { deriveSigner, signHashed, verifyHashed } from './bls'\n\nexport interface ApiKeyPayload {\n\taud: string\n\texp: number\n}\n\nexport interface GenerateApiKeyParams {\n\t/** Base58 wallet seed (private key). */\n\tseed: string\n\t/** Audience claim the bearer will present to. */\n\taud: string\n\t/** Lifetime in seconds from now. */\n\texpIn: number\n\t/** Override \"now\" (ms since epoch) — for deterministic tests. */\n\tnow?: number\n}\n\nexport interface GenerateApiKeyResult {\n\tapiKey: string\n\tpayload: ApiKeyPayload\n}\n\nexport function generateApiKey(params: GenerateApiKeyParams): GenerateApiKeyResult {\n\tif (!params.aud || params.aud.length === 0) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'aud is required')\n\t}\n\tif (!Number.isInteger(params.expIn) || params.expIn <= 0) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'expIn must be a positive integer (seconds)')\n\t}\n\n\tconst { sk, pk } = deriveSigner(params.seed)\n\tconst nowMs = params.now ?? Date.now()\n\tconst exp = Math.floor(nowMs / 1000) + params.expIn\n\n\t// IMPORTANT: object literal order (aud, then exp) fixes the JSON byte layout.\n\tconst jsonBytes = utf8ToBytes(JSON.stringify({ aud: params.aud, exp }))\n\tconst signed = concatBytes(jsonBytes, pk)\n\tconst signature = signHashed(signed, sk, API_KEY_DST)\n\tconst token = concatBytes(jsonBytes, pk, signature)\n\n\treturn { apiKey: toBase58(token), payload: { aud: params.aud, exp } }\n}\n\nexport interface DecodedApiKey {\n\tpayload: ApiKeyPayload\n\tpublicKey: Uint8Array\n\tsignature: Uint8Array\n\t/** The raw JSON bytes that were signed — needed to re-verify exactly. */\n\tjsonBytes: Uint8Array\n\t/** The signing address (Base58 of `publicKey`). */\n\taddress: string\n}\n\n/** Parse a token into its parts. Throws `WalletSdkError('INVALID_API_KEY')` on malformed input. */\nexport function decodeApiKey(apiKey: string): DecodedApiKey {\n\t// Bound untrusted input BEFORE the quadratic Base58 decode so an oversized\n\t// string can't stall the verifier (event-loop DoS).\n\tif (\n\t\ttypeof apiKey !== 'string' ||\n\t\tapiKey.length === 0 ||\n\t\tapiKey.length > MAX_API_KEY_STRING_LENGTH\n\t) {\n\t\tthrow new WalletSdkError('INVALID_API_KEY', 'api key length is out of range')\n\t}\n\n\tlet raw: Uint8Array\n\ttry {\n\t\traw = fromBase58(apiKey)\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_API_KEY', 'api key is not valid Base58')\n\t}\n\n\tconst jsonEnd = raw.length - PUBLIC_KEY_BYTE_LENGTH - SIGNATURE_BYTE_LENGTH\n\tif (jsonEnd <= 0) {\n\t\tthrow new WalletSdkError('INVALID_API_KEY', 'api key is too short to contain a payload')\n\t}\n\n\tconst jsonBytes = raw.slice(0, jsonEnd)\n\tconst publicKey = raw.slice(jsonEnd, jsonEnd + PUBLIC_KEY_BYTE_LENGTH)\n\tconst signature = raw.slice(jsonEnd + PUBLIC_KEY_BYTE_LENGTH)\n\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(bytesToUtf8(jsonBytes))\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_API_KEY', 'api key payload is not valid JSON')\n\t}\n\n\tif (\n\t\ttypeof parsed !== 'object' ||\n\t\tparsed === null ||\n\t\ttypeof (parsed as ApiKeyPayload).aud !== 'string' ||\n\t\ttypeof (parsed as ApiKeyPayload).exp !== 'number' ||\n\t\t!Number.isFinite((parsed as ApiKeyPayload).exp)\n\t) {\n\t\tthrow new WalletSdkError(\n\t\t\t'INVALID_API_KEY',\n\t\t\t'api key payload must be { aud: string, exp: number }'\n\t\t)\n\t}\n\n\tconst payload = parsed as ApiKeyPayload\n\treturn { payload, publicKey, signature, jsonBytes, address: toBase58(publicKey) }\n}\n\nexport interface VerifyApiKeyOptions {\n\t/** If provided, the token's `aud` must equal this. */\n\taud?: string\n\t/** Override \"now\" (ms since epoch) — for deterministic tests. */\n\tnow?: number\n\t/** Treat the token as expired this many seconds early (clock-skew guard). Default 0. */\n\tleewaySeconds?: number\n}\n\nexport type VerifyApiKeyResult =\n\t| { valid: true; payload: ApiKeyPayload; address: string }\n\t| { valid: false; reason: 'malformed' | 'bad_signature' | 'expired' | 'aud_mismatch' }\n\n/**\n * Full verification: structure -> BLS signature (under the API-key DST, with the\n * pubkey folded in) -> expiry -> optional audience. Returns a discriminated\n * result rather than throwing on the common \"invalid\" paths.\n */\nexport function verifyApiKey(\n\tapiKey: string,\n\toptions: VerifyApiKeyOptions = {}\n): VerifyApiKeyResult {\n\tlet decoded: DecodedApiKey\n\ttry {\n\t\tdecoded = decodeApiKey(apiKey)\n\t} catch {\n\t\treturn { valid: false, reason: 'malformed' }\n\t}\n\n\tconst signed = concatBytes(decoded.jsonBytes, decoded.publicKey)\n\tif (!verifyHashed(decoded.signature, signed, decoded.publicKey, API_KEY_DST)) {\n\t\treturn { valid: false, reason: 'bad_signature' }\n\t}\n\n\tconst nowSec = Math.floor((options.now ?? Date.now()) / 1000)\n\tconst leeway = options.leewaySeconds ?? 0\n\tif (decoded.payload.exp <= nowSec + leeway) {\n\t\treturn { valid: false, reason: 'expired' }\n\t}\n\n\tif (options.aud !== undefined && decoded.payload.aud !== options.aud) {\n\t\treturn { valid: false, reason: 'aud_mismatch' }\n\t}\n\n\treturn { valid: true, payload: decoded.payload, address: decoded.address }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,eAAe,QAAoD;CAClF,IAAI,CAAC,OAAO,OAAO,OAAO,IAAI,WAAW,GACxC,MAAM,IAAI,eAAe,oBAAoB,iBAAiB;CAE/D,IAAI,CAAC,OAAO,UAAU,OAAO,KAAK,KAAK,OAAO,SAAS,GACtD,MAAM,IAAI,eAAe,oBAAoB,4CAA4C;CAG1F,MAAM,EAAE,IAAI,OAAO,aAAa,OAAO,IAAI;CAC3C,MAAM,QAAQ,OAAO,OAAO,KAAK,IAAI;CACrC,MAAM,MAAM,KAAK,MAAM,QAAQ,GAAI,IAAI,OAAO;CAG9C,MAAM,YAAY,YAAY,KAAK,UAAU;EAAE,KAAK,OAAO;EAAK;CAAI,CAAC,CAAC;CACtE,MAAM,SAAS,YAAY,WAAW,EAAE;CACxC,MAAM,YAAY,WAAW,QAAQ,IAAI,WAAW;CACpD,MAAM,QAAQ,YAAY,WAAW,IAAI,SAAS;CAElD,OAAO;EAAE,QAAQ,SAAS,KAAK;EAAG,SAAS;GAAE,KAAK,OAAO;GAAK;EAAI;CAAE;AACrE;;AAaA,SAAgB,aAAa,QAA+B;CAG3D,IACC,OAAO,WAAW,YAClB,OAAO,WAAW,KAClB,OAAO,SAAA,MAEP,MAAM,IAAI,eAAe,mBAAmB,gCAAgC;CAG7E,IAAI;CACJ,IAAI;EACH,MAAM,WAAW,MAAM;CACxB,QAAQ;EACP,MAAM,IAAI,eAAe,mBAAmB,6BAA6B;CAC1E;CAEA,MAAM,UAAU,IAAI,SAAA,KAAA;CACpB,IAAI,WAAW,GACd,MAAM,IAAI,eAAe,mBAAmB,2CAA2C;CAGxF,MAAM,YAAY,IAAI,MAAM,GAAG,OAAO;CACtC,MAAM,YAAY,IAAI,MAAM,SAAS,UAAA,EAAgC;CACrE,MAAM,YAAY,IAAI,MAAM,UAAA,EAAgC;CAE5D,IAAI;CACJ,IAAI;EACH,SAAS,KAAK,MAAM,YAAY,SAAS,CAAC;CAC3C,QAAQ;EACP,MAAM,IAAI,eAAe,mBAAmB,mCAAmC;CAChF;CAEA,IACC,OAAO,WAAW,YAClB,WAAW,QACX,OAAQ,OAAyB,QAAQ,YACzC,OAAQ,OAAyB,QAAQ,YACzC,CAAC,OAAO,SAAU,OAAyB,GAAG,GAE9C,MAAM,IAAI,eACT,mBACA,sDACD;CAID,OAAO;EAAE,SAAA;EAAS;EAAW;EAAW;EAAW,SAAS,SAAS,SAAS;CAAE;AACjF;;;;;;AAoBA,SAAgB,aACf,QACA,UAA+B,CAAC,GACX;CACrB,IAAI;CACJ,IAAI;EACH,UAAU,aAAa,MAAM;CAC9B,QAAQ;EACP,OAAO;GAAE,OAAO;GAAO,QAAQ;EAAY;CAC5C;CAEA,MAAM,SAAS,YAAY,QAAQ,WAAW,QAAQ,SAAS;CAC/D,IAAI,CAAC,aAAa,QAAQ,WAAW,QAAQ,QAAQ,WAAA,oDAAsB,GAC1E,OAAO;EAAE,OAAO;EAAO,QAAQ;CAAgB;CAGhD,MAAM,SAAS,KAAK,OAAO,QAAQ,OAAO,KAAK,IAAI,KAAK,GAAI;CAC5D,MAAM,SAAS,QAAQ,iBAAiB;CACxC,IAAI,QAAQ,QAAQ,OAAO,SAAS,QACnC,OAAO;EAAE,OAAO;EAAO,QAAQ;CAAU;CAG1C,IAAI,QAAQ,QAAQ,KAAA,KAAa,QAAQ,QAAQ,QAAQ,QAAQ,KAChE,OAAO;EAAE,OAAO;EAAO,QAAQ;CAAe;CAG/C,OAAO;EAAE,OAAO;EAAM,SAAS,QAAQ;EAAS,SAAS,QAAQ;CAAQ;AAC1E"}
|
package/dist/crypto/box.js
CHANGED
|
@@ -21,8 +21,9 @@ import { x25519 } from "@noble/curves/ed25519";
|
|
|
21
21
|
/** Generate a fresh ephemeral x25519 session keypair. */
|
|
22
22
|
function generateSessionKeypair() {
|
|
23
23
|
const secretKey = randomBytes(32);
|
|
24
|
+
const publicKey = x25519.getPublicKey(secretKey);
|
|
24
25
|
return {
|
|
25
|
-
publicKey: toBase58(
|
|
26
|
+
publicKey: toBase58(publicKey),
|
|
26
27
|
secretKey
|
|
27
28
|
};
|
|
28
29
|
}
|
package/dist/crypto/box.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"box.js","names":[],"sources":["../../src/crypto/box.ts"],"sourcesContent":["/**\n * End-to-end encrypted session channel for cross-device transports (QR / bridge).\n *\n * Each side holds an ephemeral x25519 keypair; the shared secret is derived via\n * ECDH and run through SHA-256 into a 32-byte symmetric key, then messages are\n * sealed with XChaCha20-Poly1305 (24-byte random nonce per message, AEAD auth\n * tag). This stack is Hermes-safe — it reuses the same `@noble` crypto the mobile\n * app already ships, and the CSPRNG is the platform `crypto.getRandomValues`.\n *\n * The x25519 keypair here is ONLY for transport encryption. It is completely\n * separate from the wallet's BLS signing key — never conflate them.\n */\n\nimport { fromBase58, toBase58 } from '@amadeus-protocol/sdk'\nimport { xchacha20poly1305 } from '@noble/ciphers/chacha.js'\nimport { x25519 } from '@noble/curves/ed25519'\nimport { sha256 } from '@noble/hashes/sha2'\n\nimport {\n\tSESSION_NONCE_BYTE_LENGTH,\n\tSESSION_PUBLIC_KEY_BYTE_LENGTH,\n\tSESSION_SECRET_KEY_BYTE_LENGTH\n} from '../constants'\nimport { randomBytes } from '../bytes'\nimport { WalletSdkError } from '../errors'\n\nexport interface SessionKeypair {\n\t/** x25519 public key (Base58) — safe to send in the clear (in the QR / link). */\n\tpublicKey: string\n\t/** x25519 secret key (32 raw bytes) — keep in memory only, never persist. */\n\tsecretKey: Uint8Array\n}\n\n/** Generate a fresh ephemeral x25519 session keypair. */\nexport function generateSessionKeypair(): SessionKeypair {\n\tconst secretKey = randomBytes(SESSION_SECRET_KEY_BYTE_LENGTH)\n\tconst publicKey = x25519.getPublicKey(secretKey)\n\treturn { publicKey: toBase58(publicKey), secretKey }\n}\n\n/**\n * Derive the 32-byte symmetric key shared with a peer. Both sides call this with\n * (their own secret, the other's public) and get the same key.\n */\nexport function deriveSharedKey(theirPublicKeyBase58: string, mySecretKey: Uint8Array): Uint8Array {\n\tlet theirPublicKey: Uint8Array\n\ttry {\n\t\ttheirPublicKey = fromBase58(theirPublicKeyBase58)\n\t} catch {\n\t\tthrow new WalletSdkError('DECRYPT_FAILED', 'peer public key is not valid Base58')\n\t}\n\tif (theirPublicKey.length !== SESSION_PUBLIC_KEY_BYTE_LENGTH) {\n\t\tthrow new WalletSdkError('DECRYPT_FAILED', 'peer public key has the wrong length')\n\t}\n\t// noble rejects low-order / all-zero points by throwing — normalize that (and\n\t// any other malformed-key throw) to the module's fail-closed error type so the\n\t// whole path fails closed on a hostile peer key rather than leaking a raw Error.\n\tlet shared: Uint8Array\n\ttry {\n\t\tshared = x25519.getSharedSecret(mySecretKey, theirPublicKey)\n\t} catch {\n\t\tthrow new WalletSdkError(\n\t\t\t'DECRYPT_FAILED',\n\t\t\t'invalid peer public key (low-order or malformed)'\n\t\t)\n\t}\n\treturn sha256(shared)\n}\n\nexport interface SealedEnvelope {\n\t/** Base58 24-byte nonce. */\n\tnonce: string\n\t/** Base58 ciphertext (includes the Poly1305 auth tag). */\n\tciphertext: string\n}\n\n/** Seal plaintext with the shared key. Optional `aad` is authenticated but not encrypted. */\nexport function seal(\n\tsharedKey: Uint8Array,\n\tplaintext: Uint8Array,\n\taad?: Uint8Array\n): SealedEnvelope {\n\tconst nonce = randomBytes(SESSION_NONCE_BYTE_LENGTH)\n\tconst ciphertext = xchacha20poly1305(sharedKey, nonce, aad).encrypt(plaintext)\n\treturn { nonce: toBase58(nonce), ciphertext: toBase58(ciphertext) }\n}\n\n/**\n * Open a sealed envelope. Throws `WalletSdkError('DECRYPT_FAILED')` if the key is\n * wrong, the ciphertext/aad was tampered with, or the envelope is malformed —\n * i.e. it fails closed.\n */\nexport function open(\n\tsharedKey: Uint8Array,\n\tenvelope: SealedEnvelope,\n\taad?: Uint8Array\n): Uint8Array {\n\tlet nonce: Uint8Array\n\tlet ciphertext: Uint8Array\n\ttry {\n\t\tnonce = fromBase58(envelope.nonce)\n\t\tciphertext = fromBase58(envelope.ciphertext)\n\t} catch {\n\t\tthrow new WalletSdkError('DECRYPT_FAILED', 'sealed envelope is not valid Base58')\n\t}\n\tif (nonce.length !== SESSION_NONCE_BYTE_LENGTH) {\n\t\tthrow new WalletSdkError('DECRYPT_FAILED', 'nonce has the wrong length')\n\t}\n\ttry {\n\t\treturn xchacha20poly1305(sharedKey, nonce, aad).decrypt(ciphertext)\n\t} catch {\n\t\tthrow new WalletSdkError('DECRYPT_FAILED', 'authentication failed (wrong key or tampered)')\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,yBAAyC;CACxD,MAAM,YAAY,YAAA,EAA0C;
|
|
1
|
+
{"version":3,"file":"box.js","names":[],"sources":["../../src/crypto/box.ts"],"sourcesContent":["/**\n * End-to-end encrypted session channel for cross-device transports (QR / bridge).\n *\n * Each side holds an ephemeral x25519 keypair; the shared secret is derived via\n * ECDH and run through SHA-256 into a 32-byte symmetric key, then messages are\n * sealed with XChaCha20-Poly1305 (24-byte random nonce per message, AEAD auth\n * tag). This stack is Hermes-safe — it reuses the same `@noble` crypto the mobile\n * app already ships, and the CSPRNG is the platform `crypto.getRandomValues`.\n *\n * The x25519 keypair here is ONLY for transport encryption. It is completely\n * separate from the wallet's BLS signing key — never conflate them.\n */\n\nimport { fromBase58, toBase58 } from '@amadeus-protocol/sdk'\nimport { xchacha20poly1305 } from '@noble/ciphers/chacha.js'\nimport { x25519 } from '@noble/curves/ed25519'\nimport { sha256 } from '@noble/hashes/sha2'\n\nimport {\n\tSESSION_NONCE_BYTE_LENGTH,\n\tSESSION_PUBLIC_KEY_BYTE_LENGTH,\n\tSESSION_SECRET_KEY_BYTE_LENGTH\n} from '../constants'\nimport { randomBytes } from '../bytes'\nimport { WalletSdkError } from '../errors'\n\nexport interface SessionKeypair {\n\t/** x25519 public key (Base58) — safe to send in the clear (in the QR / link). */\n\tpublicKey: string\n\t/** x25519 secret key (32 raw bytes) — keep in memory only, never persist. */\n\tsecretKey: Uint8Array\n}\n\n/** Generate a fresh ephemeral x25519 session keypair. */\nexport function generateSessionKeypair(): SessionKeypair {\n\tconst secretKey = randomBytes(SESSION_SECRET_KEY_BYTE_LENGTH)\n\tconst publicKey = x25519.getPublicKey(secretKey)\n\treturn { publicKey: toBase58(publicKey), secretKey }\n}\n\n/**\n * Derive the 32-byte symmetric key shared with a peer. Both sides call this with\n * (their own secret, the other's public) and get the same key.\n */\nexport function deriveSharedKey(theirPublicKeyBase58: string, mySecretKey: Uint8Array): Uint8Array {\n\tlet theirPublicKey: Uint8Array\n\ttry {\n\t\ttheirPublicKey = fromBase58(theirPublicKeyBase58)\n\t} catch {\n\t\tthrow new WalletSdkError('DECRYPT_FAILED', 'peer public key is not valid Base58')\n\t}\n\tif (theirPublicKey.length !== SESSION_PUBLIC_KEY_BYTE_LENGTH) {\n\t\tthrow new WalletSdkError('DECRYPT_FAILED', 'peer public key has the wrong length')\n\t}\n\t// noble rejects low-order / all-zero points by throwing — normalize that (and\n\t// any other malformed-key throw) to the module's fail-closed error type so the\n\t// whole path fails closed on a hostile peer key rather than leaking a raw Error.\n\tlet shared: Uint8Array\n\ttry {\n\t\tshared = x25519.getSharedSecret(mySecretKey, theirPublicKey)\n\t} catch {\n\t\tthrow new WalletSdkError(\n\t\t\t'DECRYPT_FAILED',\n\t\t\t'invalid peer public key (low-order or malformed)'\n\t\t)\n\t}\n\treturn sha256(shared)\n}\n\nexport interface SealedEnvelope {\n\t/** Base58 24-byte nonce. */\n\tnonce: string\n\t/** Base58 ciphertext (includes the Poly1305 auth tag). */\n\tciphertext: string\n}\n\n/** Seal plaintext with the shared key. Optional `aad` is authenticated but not encrypted. */\nexport function seal(\n\tsharedKey: Uint8Array,\n\tplaintext: Uint8Array,\n\taad?: Uint8Array\n): SealedEnvelope {\n\tconst nonce = randomBytes(SESSION_NONCE_BYTE_LENGTH)\n\tconst ciphertext = xchacha20poly1305(sharedKey, nonce, aad).encrypt(plaintext)\n\treturn { nonce: toBase58(nonce), ciphertext: toBase58(ciphertext) }\n}\n\n/**\n * Open a sealed envelope. Throws `WalletSdkError('DECRYPT_FAILED')` if the key is\n * wrong, the ciphertext/aad was tampered with, or the envelope is malformed —\n * i.e. it fails closed.\n */\nexport function open(\n\tsharedKey: Uint8Array,\n\tenvelope: SealedEnvelope,\n\taad?: Uint8Array\n): Uint8Array {\n\tlet nonce: Uint8Array\n\tlet ciphertext: Uint8Array\n\ttry {\n\t\tnonce = fromBase58(envelope.nonce)\n\t\tciphertext = fromBase58(envelope.ciphertext)\n\t} catch {\n\t\tthrow new WalletSdkError('DECRYPT_FAILED', 'sealed envelope is not valid Base58')\n\t}\n\tif (nonce.length !== SESSION_NONCE_BYTE_LENGTH) {\n\t\tthrow new WalletSdkError('DECRYPT_FAILED', 'nonce has the wrong length')\n\t}\n\ttry {\n\t\treturn xchacha20poly1305(sharedKey, nonce, aad).decrypt(ciphertext)\n\t} catch {\n\t\tthrow new WalletSdkError('DECRYPT_FAILED', 'authentication failed (wrong key or tampered)')\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,yBAAyC;CACxD,MAAM,YAAY,YAAA,EAA0C;CAC5D,MAAM,YAAY,OAAO,aAAa,SAAS;CAC/C,OAAO;EAAE,WAAW,SAAS,SAAS;EAAG;CAAU;AACpD;;;;;AAMA,SAAgB,gBAAgB,sBAA8B,aAAqC;CAClG,IAAI;CACJ,IAAI;EACH,iBAAiB,WAAW,oBAAoB;CACjD,QAAQ;EACP,MAAM,IAAI,eAAe,kBAAkB,qCAAqC;CACjF;CACA,IAAI,eAAe,WAAA,IAClB,MAAM,IAAI,eAAe,kBAAkB,sCAAsC;CAKlF,IAAI;CACJ,IAAI;EACH,SAAS,OAAO,gBAAgB,aAAa,cAAc;CAC5D,QAAQ;EACP,MAAM,IAAI,eACT,kBACA,kDACD;CACD;CACA,OAAO,OAAO,MAAM;AACrB;;AAUA,SAAgB,KACf,WACA,WACA,KACiB;CACjB,MAAM,QAAQ,YAAA,EAAqC;CACnD,MAAM,aAAa,kBAAkB,WAAW,OAAO,GAAG,CAAC,CAAC,QAAQ,SAAS;CAC7E,OAAO;EAAE,OAAO,SAAS,KAAK;EAAG,YAAY,SAAS,UAAU;CAAE;AACnE;;;;;;AAOA,SAAgB,KACf,WACA,UACA,KACa;CACb,IAAI;CACJ,IAAI;CACJ,IAAI;EACH,QAAQ,WAAW,SAAS,KAAK;EACjC,aAAa,WAAW,SAAS,UAAU;CAC5C,QAAQ;EACP,MAAM,IAAI,eAAe,kBAAkB,qCAAqC;CACjF;CACA,IAAI,MAAM,WAAA,IACT,MAAM,IAAI,eAAe,kBAAkB,4BAA4B;CAExE,IAAI;EACH,OAAO,kBAAkB,WAAW,OAAO,GAAG,CAAC,CAAC,QAAQ,UAAU;CACnE,QAAQ;EACP,MAAM,IAAI,eAAe,kBAAkB,+CAA+C;CAC3F;AACD"}
|
package/dist/crypto/connect.js
CHANGED
|
@@ -49,7 +49,8 @@ function buildConnectTranscript(transcript) {
|
|
|
49
49
|
/** Wallet side: sign the transcript, returning a Base58 signature. */
|
|
50
50
|
function signConnect(params) {
|
|
51
51
|
const { sk } = deriveSigner(params.seed);
|
|
52
|
-
|
|
52
|
+
const signature = signHashed(buildConnectTranscript(params.transcript), sk, CONNECT_DST);
|
|
53
|
+
return toBase58(signature);
|
|
53
54
|
}
|
|
54
55
|
/**
|
|
55
56
|
* dApp side: verify the wallet controls `address` for this exact transcript.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.js","names":[],"sources":["../../src/crypto/connect.ts"],"sourcesContent":["/**\n * Connection-auth signatures. When a dApp asks the wallet to connect, it must\n * prove control of its address. The wallet signs a TRANSCRIPT that binds the\n * whole handshake — origin, both x25519 session public keys, the dApp's\n * challenge, and the request id — NOT just the raw challenge nonce.\n *\n * Signing only the nonce is a key-substitution MITM: an attacker replays a\n * harvested `sig(challenge)` under their own session keys and ends up with a\n * fully-authenticated session. Binding the session keys + origin into the signed\n * bytes closes that, the same property SIWE / CAIP-122 rely on.\n *\n * The transcript is length-prefixed and label-tagged so its bytes are\n * unambiguous, and signed under `CONNECT_DST` so a connect proof can never be\n * reused as a transaction, api-key, or any other signature.\n */\n\nimport { toBase58 } from '@amadeus-protocol/sdk'\n\nimport { CONNECT_DST, CONNECT_TRANSCRIPT_LABEL } from '../constants'\nimport { concatBytes, u32be, utf8ToBytes } from '../bytes'\nimport {\n\tderiveSigner,\n\tpublicKeyFromAddress,\n\tsignatureFromBase58,\n\tsignHashed,\n\tverifyHashed\n} from './bls'\n\nexport interface ConnectTranscript {\n\t/** The dApp's origin, e.g. \"https://app.amadeus.xyz\". */\n\torigin: string\n\t/** The dApp's ephemeral x25519 session public key (Base58). */\n\tdappPublicKey: string\n\t/** The wallet's ephemeral x25519 session public key (Base58). */\n\twalletPublicKey: string\n\t/** Random challenge nonce chosen by the dApp. */\n\tchallenge: string\n\t/** Unique id for this connect request. */\n\trequestId: string\n}\n\n/**\n * Deterministic canonical bytes for a transcript. Identical inputs -> identical\n * bytes on both wallet and dApp (that's the whole point of a shared package).\n * Every element is length-prefixed (including the label) so field boundaries are\n * unambiguous — no concatenation/canonicalization ambiguity even if the label is\n * ever made dynamic. Layout: u32(labelLen) ++ label ++ u32(fieldCount) ++\n * for each field: u32(len) ++ utf8(field).\n */\nexport function buildConnectTranscript(transcript: ConnectTranscript): Uint8Array {\n\tconst fields = [\n\t\ttranscript.origin,\n\t\ttranscript.dappPublicKey,\n\t\ttranscript.walletPublicKey,\n\t\ttranscript.challenge,\n\t\ttranscript.requestId\n\t]\n\tconst label = utf8ToBytes(CONNECT_TRANSCRIPT_LABEL)\n\tconst parts: Uint8Array[] = [u32be(label.length), label, u32be(fields.length)]\n\tfor (const field of fields) {\n\t\tconst bytes = utf8ToBytes(field)\n\t\tparts.push(u32be(bytes.length), bytes)\n\t}\n\treturn concatBytes(...parts)\n}\n\nexport interface SignConnectParams {\n\t/** Base58 wallet seed (private key). */\n\tseed: string\n\ttranscript: ConnectTranscript\n}\n\n/** Wallet side: sign the transcript, returning a Base58 signature. */\nexport function signConnect(params: SignConnectParams): string {\n\tconst { sk } = deriveSigner(params.seed)\n\tconst signature = signHashed(buildConnectTranscript(params.transcript), sk, CONNECT_DST)\n\treturn toBase58(signature)\n}\n\nexport interface VerifyConnectParams {\n\t/** The address (Base58 public key) that claims to have signed. */\n\taddress: string\n\ttranscript: ConnectTranscript\n\t/** The Base58 signature returned by the wallet. */\n\tsignature: string\n}\n\n/**\n * dApp side: verify the wallet controls `address` for this exact transcript.\n * Never throws — returns false on any malformed input or verification failure.\n */\nexport function verifyConnect(params: VerifyConnectParams): boolean {\n\tlet publicKey: Uint8Array\n\tlet signature: Uint8Array\n\ttry {\n\t\tpublicKey = publicKeyFromAddress(params.address)\n\t\tsignature = signatureFromBase58(params.signature)\n\t} catch {\n\t\treturn false\n\t}\n\treturn verifyHashed(\n\t\tsignature,\n\t\tbuildConnectTranscript(params.transcript),\n\t\tpublicKey,\n\t\tCONNECT_DST\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,uBAAuB,YAA2C;CACjF,MAAM,SAAS;EACd,WAAW;EACX,WAAW;EACX,WAAW;EACX,WAAW;EACX,WAAW;CACZ;CACA,MAAM,QAAQ,YAAY,wBAAwB;CAClD,MAAM,QAAsB;EAAC,MAAM,MAAM,MAAM;EAAG;EAAO,MAAM,OAAO,MAAM;CAAC;CAC7E,KAAK,MAAM,SAAS,QAAQ;EAC3B,MAAM,QAAQ,YAAY,KAAK;EAC/B,MAAM,KAAK,MAAM,MAAM,MAAM,GAAG,KAAK;CACtC;CACA,OAAO,YAAY,GAAG,KAAK;AAC5B;;AASA,SAAgB,YAAY,QAAmC;CAC9D,MAAM,EAAE,OAAO,aAAa,OAAO,IAAI;
|
|
1
|
+
{"version":3,"file":"connect.js","names":[],"sources":["../../src/crypto/connect.ts"],"sourcesContent":["/**\n * Connection-auth signatures. When a dApp asks the wallet to connect, it must\n * prove control of its address. The wallet signs a TRANSCRIPT that binds the\n * whole handshake — origin, both x25519 session public keys, the dApp's\n * challenge, and the request id — NOT just the raw challenge nonce.\n *\n * Signing only the nonce is a key-substitution MITM: an attacker replays a\n * harvested `sig(challenge)` under their own session keys and ends up with a\n * fully-authenticated session. Binding the session keys + origin into the signed\n * bytes closes that, the same property SIWE / CAIP-122 rely on.\n *\n * The transcript is length-prefixed and label-tagged so its bytes are\n * unambiguous, and signed under `CONNECT_DST` so a connect proof can never be\n * reused as a transaction, api-key, or any other signature.\n */\n\nimport { toBase58 } from '@amadeus-protocol/sdk'\n\nimport { CONNECT_DST, CONNECT_TRANSCRIPT_LABEL } from '../constants'\nimport { concatBytes, u32be, utf8ToBytes } from '../bytes'\nimport {\n\tderiveSigner,\n\tpublicKeyFromAddress,\n\tsignatureFromBase58,\n\tsignHashed,\n\tverifyHashed\n} from './bls'\n\nexport interface ConnectTranscript {\n\t/** The dApp's origin, e.g. \"https://app.amadeus.xyz\". */\n\torigin: string\n\t/** The dApp's ephemeral x25519 session public key (Base58). */\n\tdappPublicKey: string\n\t/** The wallet's ephemeral x25519 session public key (Base58). */\n\twalletPublicKey: string\n\t/** Random challenge nonce chosen by the dApp. */\n\tchallenge: string\n\t/** Unique id for this connect request. */\n\trequestId: string\n}\n\n/**\n * Deterministic canonical bytes for a transcript. Identical inputs -> identical\n * bytes on both wallet and dApp (that's the whole point of a shared package).\n * Every element is length-prefixed (including the label) so field boundaries are\n * unambiguous — no concatenation/canonicalization ambiguity even if the label is\n * ever made dynamic. Layout: u32(labelLen) ++ label ++ u32(fieldCount) ++\n * for each field: u32(len) ++ utf8(field).\n */\nexport function buildConnectTranscript(transcript: ConnectTranscript): Uint8Array {\n\tconst fields = [\n\t\ttranscript.origin,\n\t\ttranscript.dappPublicKey,\n\t\ttranscript.walletPublicKey,\n\t\ttranscript.challenge,\n\t\ttranscript.requestId\n\t]\n\tconst label = utf8ToBytes(CONNECT_TRANSCRIPT_LABEL)\n\tconst parts: Uint8Array[] = [u32be(label.length), label, u32be(fields.length)]\n\tfor (const field of fields) {\n\t\tconst bytes = utf8ToBytes(field)\n\t\tparts.push(u32be(bytes.length), bytes)\n\t}\n\treturn concatBytes(...parts)\n}\n\nexport interface SignConnectParams {\n\t/** Base58 wallet seed (private key). */\n\tseed: string\n\ttranscript: ConnectTranscript\n}\n\n/** Wallet side: sign the transcript, returning a Base58 signature. */\nexport function signConnect(params: SignConnectParams): string {\n\tconst { sk } = deriveSigner(params.seed)\n\tconst signature = signHashed(buildConnectTranscript(params.transcript), sk, CONNECT_DST)\n\treturn toBase58(signature)\n}\n\nexport interface VerifyConnectParams {\n\t/** The address (Base58 public key) that claims to have signed. */\n\taddress: string\n\ttranscript: ConnectTranscript\n\t/** The Base58 signature returned by the wallet. */\n\tsignature: string\n}\n\n/**\n * dApp side: verify the wallet controls `address` for this exact transcript.\n * Never throws — returns false on any malformed input or verification failure.\n */\nexport function verifyConnect(params: VerifyConnectParams): boolean {\n\tlet publicKey: Uint8Array\n\tlet signature: Uint8Array\n\ttry {\n\t\tpublicKey = publicKeyFromAddress(params.address)\n\t\tsignature = signatureFromBase58(params.signature)\n\t} catch {\n\t\treturn false\n\t}\n\treturn verifyHashed(\n\t\tsignature,\n\t\tbuildConnectTranscript(params.transcript),\n\t\tpublicKey,\n\t\tCONNECT_DST\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,uBAAuB,YAA2C;CACjF,MAAM,SAAS;EACd,WAAW;EACX,WAAW;EACX,WAAW;EACX,WAAW;EACX,WAAW;CACZ;CACA,MAAM,QAAQ,YAAY,wBAAwB;CAClD,MAAM,QAAsB;EAAC,MAAM,MAAM,MAAM;EAAG;EAAO,MAAM,OAAO,MAAM;CAAC;CAC7E,KAAK,MAAM,SAAS,QAAQ;EAC3B,MAAM,QAAQ,YAAY,KAAK;EAC/B,MAAM,KAAK,MAAM,MAAM,MAAM,GAAG,KAAK;CACtC;CACA,OAAO,YAAY,GAAG,KAAK;AAC5B;;AASA,SAAgB,YAAY,QAAmC;CAC9D,MAAM,EAAE,OAAO,aAAa,OAAO,IAAI;CACvC,MAAM,YAAY,WAAW,uBAAuB,OAAO,UAAU,GAAG,IAAI,WAAW;CACvF,OAAO,SAAS,SAAS;AAC1B;;;;;AAcA,SAAgB,cAAc,QAAsC;CACnE,IAAI;CACJ,IAAI;CACJ,IAAI;EACH,YAAY,qBAAqB,OAAO,OAAO;EAC/C,YAAY,oBAAoB,OAAO,SAAS;CACjD,QAAQ;EACP,OAAO;CACR;CACA,OAAO,aACN,WACA,uBAAuB,OAAO,UAAU,GACxC,WACA,WACD;AACD"}
|
|
@@ -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,54 @@
|
|
|
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
|
+
const signature = signatureFromBase58(params.signature);
|
|
46
|
+
return verifyHashed(signature, utf8ToBytes(params.message), publicKey, MESSAGE_DST);
|
|
47
|
+
} catch {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
export { signMessage, verifyMessage };
|
|
53
|
+
|
|
54
|
+
//# 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;EACrD,MAAM,YAAY,oBAAoB,OAAO,SAAS;EACtD,OAAO,aAAa,WAAW,YAAY,OAAO,OAAO,GAAG,WAAW,WAAW;CACnF,QAAQ;EACP,OAAO;CACR;AACD"}
|
package/dist/errors.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","names":[],"sources":["../src/errors.ts"],"mappings":";;KACY;cAWC,uBAAuB;WAC1B,MAAM;
|
|
1
|
+
{"version":3,"file":"errors.d.ts","names":[],"sources":["../src/errors.ts"],"mappings":";;KACY;cAWC,uBAAuB;WAC1B,MAAM;EAEH,YAAA,MAAM,oBAAoB"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { API_KEY_DST, CONNECT_DST, CONNECT_TRANSCRIPT_LABEL, DEFAULT_BRIDGE_URL, 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, DEFAULT_BRIDGE_URL, 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, DEFAULT_BRIDGE_URL, 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, DEFAULT_BRIDGE_URL, 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
|
package/dist/schema.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.d.ts","names":[],"sources":["../src/schema.ts"],"mappings":";;;
|
|
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
|
package/dist/schema.js.map
CHANGED
|
@@ -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 {
|
|
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;
|
|
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;EAEL,YAAA,SAAS;;EAaf,KAAK,YAAY,YAAY,mBAAmB;;;;;;;;EAmBtD,MACC,UAAU,OAAO,uBAAuB,eACxC,WAAW"}
|
package/dist/transport/bridge.js
CHANGED
|
@@ -16,7 +16,7 @@ import { sha256 } from "@noble/hashes/sha2";
|
|
|
16
16
|
* React Native (no EventSource/streaming dependency).
|
|
17
17
|
*/
|
|
18
18
|
/** Max bytes we will read from a (possibly hostile) relay response. */
|
|
19
|
-
const MAX_POLL_RESPONSE_BYTES =
|
|
19
|
+
const MAX_POLL_RESPONSE_BYTES = 8388608;
|
|
20
20
|
/**
|
|
21
21
|
* Derive the two per-direction secret channel ids from the session shared key.
|
|
22
22
|
* Both sides compute the same pair; a third party without the shared key cannot.
|
|
@@ -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
|
|
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;;;;;AAsBhC,SAAgB,qBAAqB,WAKnC;CACD,MAAM,WAAW,UAAkB,SAAS,OAAO,YAAY,YAAY,KAAK,GAAG,SAAS,CAAC,CAAC;CAC9F,OAAO;EACN,UAAU,QAAQ,6BAA6B;EAC/C,QAAQ,QAAQ,2BAA2B;CAC5C;AACD;;;;;;;;AASA,SAAgB,qBAAqB,qBAAqC;CACzE,OAAO,SACN,OACC,YAAY,YAAY,2BAA2B,GAAG,WAAW,mBAAmB,CAAC,CACtF,CACD;AACD;;;;;;AAOA,SAAgB,uBAAuB,KAAmB;CACzD,MAAM,QAAQ,uCAAuC,KAAK,GAAG;CAC7D,IAAI,CAAC,OACJ,MAAM,IAAI,eAAe,oBAAoB,wCAAwC;CAEtF,MAAM,SAAS,MAAM,EAAE,CAAC,YAAY;CACpC,MAAM,OAAO,MAAM,EAAE,CAAC,YAAY;CAElC,IAAI,WAAW,WAAY,WAAW,WADtB,SAAS,eAAe,SAAS,eAAe,SAAS,QACf;CAC1D,MAAM,IAAI,eACT,oBACA,4DACD;AACD;AAaA,IAAa,eAAb,MAA0B;CACzB;CACA;CACA;CACA;CAEA,YAAY,SAA8B;EACzC,uBAAuB,QAAQ,SAAS;EACxC,KAAK,YAAY,QAAQ,UAAU,QAAQ,OAAO,EAAE;EACpD,KAAK,WAAW,QAAQ;EAKxB,KAAK,YAAY,QAAQ,aAAa,MAAM,KAAK,UAAU;EAC3D,KAAK,kBAAkB,QAAQ,mBAAmB;CACnD;;CAGA,MAAM,KAAK,IAAY,IAAY,SAAiC;EACnE,MAAM,QAAqB;GAAE,MAAM,KAAK;GAAU;GAAI;GAAI;EAAQ;EAClE,MAAM,MAAM,MAAM,KAAK,UAAU,GAAG,KAAK,UAAU,cAAc,mBAAmB,EAAE,KAAK;GAC1F,QAAQ;GACR,SAAS,EAAE,gBAAgB,mBAAmB;GAC9C,MAAM,KAAK,UAAU,KAAK;EAC3B,CAAC;EACD,IAAI,CAAC,IAAI,IACR,MAAM,IAAI,eAAe,iBAAiB,uBAAuB,IAAI,QAAQ;CAE/E;;;;;;;;CASA,MACC,SACA,SACa;EACb,MAAM,aAAa,IAAI,gBAAgB;EAEvC,MAAM,OAAO,YAAoC;GAChD,MAAM,UAAU,iBAAiB,WAAW,MAAM,IAAI,KAAK,kBAAkB,MAAM,GAAI;GACvF,IAAI;IACH,MAAM,MAAM,GAAG,KAAK,UAAU,oBAAoB,mBAAmB,KAAK,QAAQ,EAAE,QAAQ,KAAK;IACjG,MAAM,MAAM,MAAM,KAAK,UAAU,KAAK,EAAE,QAAQ,WAAW,OAAO,CAAC;IACnE,IAAI,CAAC,IAAI,IACR,MAAM,IAAI,eAAe,iBAAiB,uBAAuB,IAAI,QAAQ;IAG9E,IADiB,OAAO,IAAI,QAAQ,IAAI,gBAAgB,KAAK,CAClD,IAAI,yBACd,MAAM,IAAI,eAAe,iBAAiB,2BAA2B;IAEtE,MAAM,OAAO,MAAM,IAAI,KAAK;IAC5B,IAAI,KAAK,SAAS,yBACjB,MAAM,IAAI,eAAe,iBAAiB,2BAA2B;IAEtE,MAAM,SAAS,KAAK,MAAM,IAAI;IAC9B,OAAO,MAAM,QAAQ,MAAM,IAAK,SAA2B,CAAC;GAC7D,UAAU;IACT,aAAa,OAAO;GACrB;EACD;EAEA,MAAM,OAAO,YAAY;GACxB,OAAO,CAAC,WAAW,OAAO,SACzB,IAAI;IACH,MAAM,SAAS,MAAM,KAAK;IAC1B,KAAK,MAAM,SAAS,QAAQ;KAC3B,IAAI,WAAW,OAAO,SAAS;KAC/B,MAAM,QAAQ,KAAK;IACpB;GACD,SAAS,OAAO;IACf,IAAI,WAAW,OAAO,SAAS;IAC/B,UAAU,KAAK;IACf,MAAM,IAAI,SAAS,YAAY,WAAW,SAAS,GAAI,CAAC;GACzD;EAEF;EAEA,KAAU;EACV,aAAa,WAAW,MAAM;CAC/B;AACD"}
|
|
@@ -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;;;;
|
|
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;
|
|
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\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;CAC7B;CACA;CACA;CACA;CACA;AACD;AA2BA,MAAM,sBAAsB,EAAE,OAAO;CACpC,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI;CAClB,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;CAC7B,QAAQ,EAAE,KAAK,cAAc;CAC7B,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACxB,QAAQ,EAAE,QAAQ;CAClB,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI;CACpB,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,SAAS;AAC9C,CAAC;AAED,MAAM,uBAAuB,EAAE,MAAM,CACpC,EAAE,OAAO;CACR,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI;CAClB,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;CAC7B,IAAI,EAAE,QAAQ,IAAI;CAClB,QAAQ,EAAE,QAAQ;AACnB,CAAC,GACD,EAAE,OAAO;CACR,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI;CAClB,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;CAC7B,IAAI,EAAE,QAAQ,KAAK;CACnB,OAAO,EAAE,OAAO;EAAE,MAAM,EAAE,OAAO;EAAG,SAAS,EAAE,OAAO;CAAE,CAAC;AAC1D,CAAC,CACF,CAAC;;AAGD,SAAgB,YAAY,QAQV;CACjB,MAAM,SAAS,KAAK,OAAO,OAAO,OAAO,KAAK,IAAI,KAAK,GAAI;CAC3D,OAAO;EACN,GAAA;EACA,IAAI,OAAO;EACX,QAAQ,OAAO;EACf,QAAQ,OAAO;EACf,QAAQ,OAAO;EACf,KAAK,UAAU,OAAO,cAAc;EACpC,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;CACrD;AACD;AAEA,SAAgB,YAAY,WAAuB,SAAwC;CAC1F,OAAO,KAAK,WAAW,YAAY,KAAK,UAAU,OAAO,CAAC,CAAC;AAC5D;;;;;;;AAQA,SAAgB,YAAY,WAAuB,UAAyC;CAC3F,MAAM,QAAQ,KAAK,WAAW,QAAQ;CACtC,IAAI;CACJ,IAAI;EACH,SAAS,KAAK,MAAM,YAAY,KAAK,CAAC;CACvC,QAAQ;EACP,MAAM,IAAI,eAAe,oBAAoB,2BAA2B;CACzE;CACA,MAAM,SAAS,oBAAoB,UAAU,MAAM;CACnD,IAAI,CAAC,OAAO,SACX,MAAM,IAAI,eAAe,oBAAoB,kCAAkC;CAEhF,OAAO,OAAO;AACf;AAEA,SAAgB,aAAa,WAAuB,UAA0C;CAC7F,OAAO,KAAK,WAAW,YAAY,KAAK,UAAU,QAAQ,CAAC,CAAC;AAC7D;;;;;AAMA,SAAgB,aACf,WACA,UACA,YACiB;CACjB,MAAM,QAAQ,KAAK,WAAW,QAAQ;CACtC,IAAI;CACJ,IAAI;EACH,SAAS,KAAK,MAAM,YAAY,KAAK,CAAC;CACvC,QAAQ;EACP,MAAM,IAAI,eAAe,oBAAoB,4BAA4B;CAC1E;CACA,MAAM,SAAS,qBAAqB,UAAU,MAAM;CACpD,IAAI,CAAC,OAAO,SACX,MAAM,IAAI,eAAe,oBAAoB,mCAAmC;CAEjF,MAAM,WAAW,OAAO;CACxB,IAAI,eAAe,KAAA,KAAa,SAAS,OAAO,YAC/C,MAAM,IAAI,eAAe,oBAAoB,wCAAwC;CAEtF,OAAO;AACR;AAaA,SAAgB,sBAAsB,aAAa,KAAmB;CACrE,MAAM,sBAAM,IAAI,IAAY;CAC5B,OAAO;EACN,MAAM,OAAO,IAAI,IAAI,EAAE;EACvB,MAAM,OAAO;GACZ,IAAI,IAAI,QAAQ,YAAY,IAAI,OAAO,IAAI,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,KAAe;GAC1E,IAAI,IAAI,EAAE;EACX;CACD;AACD;;;;;;AAOA,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"}
|
|
@@ -29,16 +29,17 @@ function createConnectRequest(options) {
|
|
|
29
29
|
const requestId = randomId();
|
|
30
30
|
const exp = Math.floor((options.now ?? Date.now()) / 1e3) + (options.ttlSeconds ?? 120);
|
|
31
31
|
const bridgeUrl = options.bridgeUrl ?? "https://bridge.ama.one";
|
|
32
|
+
const params = {
|
|
33
|
+
origin: options.origin,
|
|
34
|
+
dappPublicKey: dappKeypair.publicKey,
|
|
35
|
+
challenge,
|
|
36
|
+
requestId,
|
|
37
|
+
exp,
|
|
38
|
+
redirectLink: options.redirectLink,
|
|
39
|
+
bridgeUrl
|
|
40
|
+
};
|
|
32
41
|
return {
|
|
33
|
-
uri: buildConnectUri(
|
|
34
|
-
origin: options.origin,
|
|
35
|
-
dappPublicKey: dappKeypair.publicKey,
|
|
36
|
-
challenge,
|
|
37
|
-
requestId,
|
|
38
|
-
exp,
|
|
39
|
-
redirectLink: options.redirectLink,
|
|
40
|
-
bridgeUrl
|
|
41
|
-
}),
|
|
42
|
+
uri: buildConnectUri(params),
|
|
42
43
|
pending: {
|
|
43
44
|
requestId,
|
|
44
45
|
challenge,
|
|
@@ -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 { 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,EAAE,CAAC;CAC1C,MAAM,YAAY,SAAS;CAE3B,MAAM,MADS,KAAK,OAAO,QAAQ,OAAO,KAAK,IAAI,KAAK,GACvC,KAAK,QAAQ,cAAc;CAE5C,MAAM,YAAY,QAAQ,aAAA;
|
|
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,EAAE,CAAC;CAC1C,MAAM,YAAY,SAAS;CAE3B,MAAM,MADS,KAAK,OAAO,QAAQ,OAAO,KAAK,IAAI,KAAK,GACvC,KAAK,QAAQ,cAAc;CAE5C,MAAM,YAAY,QAAQ,aAAA;CAE1B,MAAM,SAA+B;EACpC,QAAQ,QAAQ;EAChB,eAAe,YAAY;EAC3B;EACA;EACA;EACA,cAAc,QAAQ;EACtB;CACD;CACA,OAAO;EACN,KAAK,gBAAgB,MAAM;EAC3B,SAAS;GACR;GACA;GACA,QAAQ,QAAQ;GAChB;GACA;GACA;EACD;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"}
|
package/dist/tx.d.ts
CHANGED
|
@@ -1,13 +1,5 @@
|
|
|
1
|
+
import { NetworkType } from "@amadeus-protocol/sdk";
|
|
1
2
|
//#region src/tx.d.ts
|
|
2
|
-
/**
|
|
3
|
-
* Transaction signing + submission.
|
|
4
|
-
*
|
|
5
|
-
* Signing reuses `@amadeus-protocol/sdk`'s `TransactionBuilder` verbatim (so the
|
|
6
|
-
* packed bytes are identical to what the extension produces today) and layers on
|
|
7
|
-
* the two behaviors the wallet's sign handler applies: restore JSON-transported
|
|
8
|
-
* binary args, and convert a `Coin.transfer` Base58 recipient to raw bytes.
|
|
9
|
-
* The wallet signs only; the caller submits the returned `txPacked` to a node.
|
|
10
|
-
*/
|
|
11
3
|
interface SignTransactionParams {
|
|
12
4
|
/** Base58 wallet seed (private key). */
|
|
13
5
|
seed: string;
|
|
@@ -16,6 +8,8 @@ interface SignTransactionParams {
|
|
|
16
8
|
/** Args may contain tagged binary values (see `encodeBinaryValues`). */
|
|
17
9
|
args: unknown[];
|
|
18
10
|
description?: string;
|
|
11
|
+
/** Network whose signing DST to bind to. Defaults to mainnet. */
|
|
12
|
+
network?: NetworkType;
|
|
19
13
|
}
|
|
20
14
|
interface SignedTransaction {
|
|
21
15
|
/** Base58 transaction hash. */
|
package/dist/tx.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tx.d.ts","names":[],"sources":["../src/tx.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"tx.d.ts","names":[],"sources":["../src/tx.ts"],"mappings":";;UAqBiB;;EAEhB;EACA;EACA;;EAEA;EACA;;EAEA,UAAU;;UAGM;;EAEhB;;EAEA;;iBAGe,gBAAgB,QAAQ,wBAAwB;UA0B/C;;EAEhB;;EAEA;;EAEA;;;;;;iBAOqB,kBACrB,qBAAqB,YACrB,SAAS,2BACP"}
|
package/dist/tx.js
CHANGED
|
@@ -1,25 +1,29 @@
|
|
|
1
1
|
import { WalletSdkError } from "./errors.js";
|
|
2
2
|
import { decodeBinaryValues } from "./binary.js";
|
|
3
|
-
import {
|
|
3
|
+
import { fromBase58, signContractCall } from "@amadeus-protocol/sdk";
|
|
4
4
|
//#region src/tx.ts
|
|
5
5
|
/**
|
|
6
6
|
* Transaction signing + submission.
|
|
7
7
|
*
|
|
8
|
-
* Signing
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
8
|
+
* Signing delegates to `@amadeus-protocol/sdk`'s `signContractCall` (so the packed
|
|
9
|
+
* bytes are identical to what the extension produces) and layers on the two
|
|
10
|
+
* behaviors the wallet's sign handler applies: restore JSON-transported binary
|
|
11
|
+
* args, and convert a `Coin.transfer` Base58 recipient to raw bytes. The signature
|
|
12
|
+
* is bound to the given network's DST so a testnet tx can't be replayed on mainnet
|
|
13
|
+
* (defaults to mainnet). The wallet signs only; the caller submits `txPacked`.
|
|
13
14
|
*/
|
|
14
15
|
function signTransaction(params) {
|
|
15
|
-
const builder = new TransactionBuilder(params.seed);
|
|
16
16
|
let processedArgs = decodeBinaryValues(params.args);
|
|
17
17
|
if (params.contract === "Coin" && params.method === "transfer" && typeof processedArgs[0] === "string") processedArgs = [
|
|
18
18
|
fromBase58(processedArgs[0]),
|
|
19
19
|
processedArgs[1],
|
|
20
20
|
processedArgs[2]
|
|
21
21
|
];
|
|
22
|
-
const { txHash, txPacked } =
|
|
22
|
+
const { txHash, txPacked } = signContractCall(params.seed, {
|
|
23
|
+
contract: params.contract,
|
|
24
|
+
method: params.method,
|
|
25
|
+
args: processedArgs
|
|
26
|
+
}, params.network);
|
|
23
27
|
return {
|
|
24
28
|
txHash,
|
|
25
29
|
txPacked: Array.from(txPacked)
|
package/dist/tx.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tx.js","names":[],"sources":["../src/tx.ts"],"sourcesContent":["/**\n * Transaction signing + submission.\n *\n * Signing
|
|
1
|
+
{"version":3,"file":"tx.js","names":[],"sources":["../src/tx.ts"],"sourcesContent":["/**\n * Transaction signing + submission.\n *\n * Signing delegates to `@amadeus-protocol/sdk`'s `signContractCall` (so the packed\n * bytes are identical to what the extension produces) and layers on the two\n * behaviors the wallet's sign handler applies: restore JSON-transported binary\n * args, and convert a `Coin.transfer` Base58 recipient to raw bytes. The signature\n * is bound to the given network's DST so a testnet tx can't be replayed on mainnet\n * (defaults to mainnet). The wallet signs only; the caller submits `txPacked`.\n */\n\nimport {\n\tfromBase58,\n\ttype NetworkType,\n\ttype SerializableValue,\n\tsignContractCall\n} from '@amadeus-protocol/sdk'\n\nimport { decodeBinaryValues } from './binary'\nimport { WalletSdkError } from './errors'\n\nexport interface SignTransactionParams {\n\t/** Base58 wallet seed (private key). */\n\tseed: string\n\tcontract: string\n\tmethod: string\n\t/** Args may contain tagged binary values (see `encodeBinaryValues`). */\n\targs: unknown[]\n\tdescription?: string\n\t/** Network whose signing DST to bind to. Defaults to mainnet. */\n\tnetwork?: NetworkType\n}\n\nexport interface SignedTransaction {\n\t/** Base58 transaction hash. */\n\ttxHash: string\n\t/** Packed transaction bytes as a plain number[] — ready to POST to a node. */\n\ttxPacked: number[]\n}\n\nexport function signTransaction(params: SignTransactionParams): SignedTransaction {\n\t// Restore any binary args that were wrapped for a JSON/text transport.\n\tlet processedArgs = decodeBinaryValues(params.args) as unknown[]\n\n\t// Coin.transfer's recipient (arg 0) is a Base58 address on the wire but must\n\t// be raw bytes for the SDK to encode it as BYTES. Matches the extension.\n\tif (\n\t\tparams.contract === 'Coin' &&\n\t\tparams.method === 'transfer' &&\n\t\ttypeof processedArgs[0] === 'string'\n\t) {\n\t\tprocessedArgs = [fromBase58(processedArgs[0]), processedArgs[1], processedArgs[2]]\n\t}\n\n\tconst { txHash, txPacked } = signContractCall(\n\t\tparams.seed,\n\t\t{\n\t\t\tcontract: params.contract,\n\t\t\tmethod: params.method,\n\t\t\targs: processedArgs as SerializableValue[]\n\t\t},\n\t\tparams.network\n\t)\n\treturn { txHash, txPacked: Array.from(txPacked) }\n}\n\nexport interface SubmitTransactionOptions {\n\t/** Base URL of the node API, e.g. \"https://mainnet-rpc.ama.one/api\". */\n\tnodeUrl: string\n\t/** Wait for inclusion (`/tx/submit_and_wait`) vs fire-and-forget (`/tx/submit`). */\n\twait?: boolean\n\t/** Abort the request after this many ms. */\n\ttimeoutMs?: number\n}\n\n/**\n * Submit packed transaction bytes to a node as an octet-stream, the way the\n * dApps do today. Returns the parsed JSON body when possible, else raw text.\n */\nexport async function submitTransaction(\n\ttxPacked: number[] | Uint8Array,\n\toptions: SubmitTransactionOptions\n): Promise<unknown> {\n\t// nodeUrl is trusted config, but guard the scheme so a stray file:// or other\n\t// non-http target can never be fetched.\n\tif (!/^https?:\\/\\//.test(options.nodeUrl)) {\n\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'nodeUrl must be an http(s) URL')\n\t}\n\n\tconst bytes = txPacked instanceof Uint8Array ? txPacked : Uint8Array.from(txPacked)\n\t// Hand fetch a standalone ArrayBuffer — a clean BodyInit across DOM lib\n\t// versions and RN, and it never carries a shared/offset backing buffer.\n\tconst body = bytes.buffer.slice(\n\t\tbytes.byteOffset,\n\t\tbytes.byteOffset + bytes.byteLength\n\t) as ArrayBuffer\n\tconst path = options.wait ? '/tx/submit_and_wait' : '/tx/submit'\n\tconst url = `${options.nodeUrl.replace(/\\/$/, '')}${path}`\n\n\t// Always arm a timeout so a hung node can't block the caller forever.\n\tconst controller = new AbortController()\n\tconst timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 30_000)\n\n\ttry {\n\t\tconst res = await fetch(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/octet-stream' },\n\t\t\tbody,\n\t\t\tsignal: controller.signal\n\t\t})\n\t\tconst text = await res.text()\n\t\tif (!res.ok) {\n\t\t\tthrow new WalletSdkError('SUBMIT_FAILED', `node returned ${res.status}: ${text}`)\n\t\t}\n\t\ttry {\n\t\t\treturn JSON.parse(text)\n\t\t} catch {\n\t\t\treturn text\n\t\t}\n\t} finally {\n\t\tclearTimeout(timer)\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAwCA,SAAgB,gBAAgB,QAAkD;CAEjF,IAAI,gBAAgB,mBAAmB,OAAO,IAAI;CAIlD,IACC,OAAO,aAAa,UACpB,OAAO,WAAW,cAClB,OAAO,cAAc,OAAO,UAE5B,gBAAgB;EAAC,WAAW,cAAc,EAAE;EAAG,cAAc;EAAI,cAAc;CAAE;CAGlF,MAAM,EAAE,QAAQ,aAAa,iBAC5B,OAAO,MACP;EACC,UAAU,OAAO;EACjB,QAAQ,OAAO;EACf,MAAM;CACP,GACA,OAAO,OACR;CACA,OAAO;EAAE;EAAQ,UAAU,MAAM,KAAK,QAAQ;CAAE;AACjD;;;;;AAeA,eAAsB,kBACrB,UACA,SACmB;CAGnB,IAAI,CAAC,eAAe,KAAK,QAAQ,OAAO,GACvC,MAAM,IAAI,eAAe,oBAAoB,gCAAgC;CAG9E,MAAM,QAAQ,oBAAoB,aAAa,WAAW,WAAW,KAAK,QAAQ;CAGlF,MAAM,OAAO,MAAM,OAAO,MACzB,MAAM,YACN,MAAM,aAAa,MAAM,UAC1B;CACA,MAAM,OAAO,QAAQ,OAAO,wBAAwB;CACpD,MAAM,MAAM,GAAG,QAAQ,QAAQ,QAAQ,OAAO,EAAE,IAAI;CAGpD,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,QAAQ,iBAAiB,WAAW,MAAM,GAAG,QAAQ,aAAa,GAAM;CAE9E,IAAI;EACH,MAAM,MAAM,MAAM,MAAM,KAAK;GAC5B,QAAQ;GACR,SAAS,EAAE,gBAAgB,2BAA2B;GACtD;GACA,QAAQ,WAAW;EACpB,CAAC;EACD,MAAM,OAAO,MAAM,IAAI,KAAK;EAC5B,IAAI,CAAC,IAAI,IACR,MAAM,IAAI,eAAe,iBAAiB,iBAAiB,IAAI,OAAO,IAAI,MAAM;EAEjF,IAAI;GACH,OAAO,KAAK,MAAM,IAAI;EACvB,QAAQ;GACP,OAAO;EACR;CACD,UAAU;EACT,aAAa,KAAK;CACnB;AACD"}
|
package/dist/wallet/handler.d.ts
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
import { WalletRequest, WalletResponse } from "../transport/envelope.js";
|
|
2
|
+
import { NetworkType } from "@amadeus-protocol/sdk";
|
|
2
3
|
//#region src/wallet/handler.d.ts
|
|
3
4
|
interface WalletHandlerContext {
|
|
4
5
|
/** Seed (private key) of the account bound to this session. */
|
|
5
6
|
seed: string;
|
|
6
7
|
/** Address (Base58 public key) of the bound account. */
|
|
7
8
|
address: string;
|
|
9
|
+
/**
|
|
10
|
+
* Active network. Transactions are signed with this network's DST so a tx
|
|
11
|
+
* signed on one network can't be replayed on another. Defaults to mainnet.
|
|
12
|
+
*/
|
|
13
|
+
network?: NetworkType;
|
|
8
14
|
}
|
|
9
15
|
/**
|
|
10
16
|
* Service one approved request and return a response ready to seal. Never throws
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handler.d.ts","names":[],"sources":["../../src/wallet/handler.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"handler.d.ts","names":[],"sources":["../../src/wallet/handler.ts"],"mappings":";;;UAyBiB;;EAEhB;;EAEA;;;;;EAKA,UAAU;;;;;;;;iBAmBK,cAAc,SAAS,eAAe,KAAK,uBAAuB"}
|
package/dist/wallet/handler.js
CHANGED
|
@@ -1,19 +1,10 @@
|
|
|
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
|
-
* Wallet-side request dispatch. Once the mobile app has opened + guarded an
|
|
9
|
-
* inbound request and the user has approved it, this turns the request into a
|
|
10
|
-
* signed response by routing to the right primitive. Keeping it here means the
|
|
11
|
-
* app's approval screen only has to call one function; the wallet and extension
|
|
12
|
-
* share identical request semantics.
|
|
13
|
-
*
|
|
14
|
-
* IMPORTANT: call this only AFTER `guardRequest` (expiry + replay) has passed and
|
|
15
|
-
* the user has approved. It signs with the bound account's seed.
|
|
16
|
-
*/
|
|
17
8
|
function ok(id, result) {
|
|
18
9
|
return {
|
|
19
10
|
v: 1,
|
|
@@ -50,7 +41,8 @@ function handleRequest(request, ctx) {
|
|
|
50
41
|
contract: parsed.data.contract,
|
|
51
42
|
method: parsed.data.method,
|
|
52
43
|
args: parsed.data.args,
|
|
53
|
-
description: parsed.data.description
|
|
44
|
+
description: parsed.data.description,
|
|
45
|
+
network: ctx.network
|
|
54
46
|
});
|
|
55
47
|
return ok(request.id, signed);
|
|
56
48
|
}
|
|
@@ -65,7 +57,15 @@ function handleRequest(request, ctx) {
|
|
|
65
57
|
return ok(request.id, { apiKey });
|
|
66
58
|
}
|
|
67
59
|
case "amadeus_getAccounts": return ok(request.id, { accounts: [ctx.address] });
|
|
68
|
-
case "amadeus_signMessage":
|
|
60
|
+
case "amadeus_signMessage": {
|
|
61
|
+
const parsed = signMessageRequestSchema.safeParse(request.params);
|
|
62
|
+
if (!parsed.success) throw new WalletSdkError("INVALID_ARGUMENT", "invalid signMessage params");
|
|
63
|
+
const signed = signMessage({
|
|
64
|
+
seed: ctx.seed,
|
|
65
|
+
message: parsed.data.message
|
|
66
|
+
});
|
|
67
|
+
return ok(request.id, signed);
|
|
68
|
+
}
|
|
69
69
|
case "amadeus_switchNetwork": throw new WalletSdkError("INVALID_ARGUMENT", "amadeus_switchNetwork must be handled by the wallet app (it changes runtime state)");
|
|
70
70
|
default: throw new WalletSdkError("INVALID_ARGUMENT", `unknown method`);
|
|
71
71
|
}
|
|
@@ -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 {
|
|
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 type { NetworkType } from '@amadeus-protocol/sdk'\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\t/**\n\t * Active network. Transactions are signed with this network's DST so a tx\n\t * signed on one network can't be replayed on another. Defaults to mainnet.\n\t */\n\tnetwork?: NetworkType\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\tnetwork: ctx.network\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":";;;;;;;AAqCA,SAAS,GAAG,IAAY,QAAiC;CACxD,OAAO;EAAE,GAAA;EAAqB;EAAI,IAAI;EAAM;CAAO;AACpD;AAEA,SAAS,KAAK,IAAY,OAAgC;CAGzD,OAAO;EAAE,GAAA;EAAqB;EAAI,IAAI;EAAO,OAAO;GAAE,MAFzC,iBAAiB,iBAAiB,MAAM,OAAO;GAEA,SAD5C,iBAAiB,QAAQ,MAAM,UAAU;EACW;CAAE;AACvE;;;;;;;AAQA,SAAgB,cAAc,SAAwB,KAA2C;CAChG,IAAI;EACH,QAAQ,QAAQ,QAAhB;GACC,KAAK,2BAA2B;IAC/B,MAAM,SAAS,6BAA6B,UAAU,QAAQ,MAAM;IACpE,IAAI,CAAC,OAAO,SACX,MAAM,IAAI,eAAe,oBAAoB,gCAAgC;IAE9E,MAAM,SAAS,gBAAgB;KAC9B,MAAM,IAAI;KACV,UAAU,OAAO,KAAK;KACtB,QAAQ,OAAO,KAAK;KACpB,MAAM,OAAO,KAAK;KAClB,aAAa,OAAO,KAAK;KACzB,SAAS,IAAI;IACd,CAAC;IACD,OAAO,GAAG,QAAQ,IAAI,MAAM;GAC7B;GACA,KAAK,0BAA0B;IAC9B,MAAM,SAAS,4BAA4B,UAAU,QAAQ,MAAM;IACnE,IAAI,CAAC,OAAO,SACX,MAAM,IAAI,eAAe,oBAAoB,+BAA+B;IAE7E,MAAM,EAAE,WAAW,eAAe;KACjC,MAAM,IAAI;KACV,KAAK,OAAO,KAAK;KACjB,OAAO,OAAO,KAAK;IACpB,CAAC;IACD,OAAO,GAAG,QAAQ,IAAI,EAAE,OAAO,CAAC;GACjC;GACA,KAAK,uBACJ,OAAO,GAAG,QAAQ,IAAI,EAAE,UAAU,CAAC,IAAI,OAAO,EAAE,CAAC;GAClD,KAAK,uBAAuB;IAC3B,MAAM,SAAS,yBAAyB,UAAU,QAAQ,MAAM;IAChE,IAAI,CAAC,OAAO,SACX,MAAM,IAAI,eAAe,oBAAoB,4BAA4B;IAE1E,MAAM,SAAS,YAAY;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.
|
|
3
|
+
"version": "0.1.5",
|
|
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,
|
|
@@ -51,11 +51,11 @@
|
|
|
51
51
|
"license": "MIT",
|
|
52
52
|
"repository": {
|
|
53
53
|
"type": "git",
|
|
54
|
-
"url": "git+https://github.com/
|
|
54
|
+
"url": "git+https://github.com/TypeError86/amadeus-wallet-sdk.git"
|
|
55
55
|
},
|
|
56
|
-
"homepage": "https://github.com/
|
|
56
|
+
"homepage": "https://github.com/TypeError86/amadeus-wallet-sdk#readme",
|
|
57
57
|
"bugs": {
|
|
58
|
-
"url": "https://github.com/
|
|
58
|
+
"url": "https://github.com/TypeError86/amadeus-wallet-sdk/issues"
|
|
59
59
|
},
|
|
60
60
|
"publishConfig": {
|
|
61
61
|
"access": "public"
|