@amadeus-protocol/wallet-sdk 0.1.4 → 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/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.js +2 -1
- package/dist/crypto/message.js.map +1 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/transport/bridge.d.ts.map +1 -1
- package/dist/transport/bridge.js +1 -1
- package/dist/transport/bridge.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 +2 -11
- 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/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"}
|
package/dist/crypto/message.js
CHANGED
|
@@ -42,7 +42,8 @@ function verifyMessage(params) {
|
|
|
42
42
|
try {
|
|
43
43
|
assertMessage(params.message);
|
|
44
44
|
const publicKey = publicKeyFromAddress(params.address);
|
|
45
|
-
|
|
45
|
+
const signature = signatureFromBase58(params.signature);
|
|
46
|
+
return verifyHashed(signature, utf8ToBytes(params.message), publicKey, MESSAGE_DST);
|
|
46
47
|
} catch {
|
|
47
48
|
return false;
|
|
48
49
|
}
|
|
@@ -1 +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;
|
|
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"}
|
|
@@ -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.
|
|
@@ -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\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
|
|
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"}
|
|
@@ -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
|
@@ -5,16 +5,6 @@ import { generateApiKeyRequestSchema, signMessageRequestSchema, signTransactionR
|
|
|
5
5
|
import { generateApiKey } from "../crypto/apikey.js";
|
|
6
6
|
import { signMessage } from "../crypto/message.js";
|
|
7
7
|
//#region src/wallet/handler.ts
|
|
8
|
-
/**
|
|
9
|
-
* Wallet-side request dispatch. Once the mobile app has opened + guarded an
|
|
10
|
-
* inbound request and the user has approved it, this turns the request into a
|
|
11
|
-
* signed response by routing to the right primitive. Keeping it here means the
|
|
12
|
-
* app's approval screen only has to call one function; the wallet and extension
|
|
13
|
-
* share identical request semantics.
|
|
14
|
-
*
|
|
15
|
-
* IMPORTANT: call this only AFTER `guardRequest` (expiry + replay) has passed and
|
|
16
|
-
* the user has approved. It signs with the bound account's seed.
|
|
17
|
-
*/
|
|
18
8
|
function ok(id, result) {
|
|
19
9
|
return {
|
|
20
10
|
v: 1,
|
|
@@ -51,7 +41,8 @@ function handleRequest(request, ctx) {
|
|
|
51
41
|
contract: parsed.data.contract,
|
|
52
42
|
method: parsed.data.method,
|
|
53
43
|
args: parsed.data.args,
|
|
54
|
-
description: parsed.data.description
|
|
44
|
+
description: parsed.data.description,
|
|
45
|
+
network: ctx.network
|
|
55
46
|
});
|
|
56
47
|
return ok(request.id, signed);
|
|
57
48
|
}
|
|
@@ -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 { signMessage } from '../crypto/message'\nimport { WalletSdkError } from '../errors'\nimport {\n\tgenerateApiKeyRequestSchema,\n\tsignMessageRequestSchema,\n\tsignTransactionRequestSchema\n} from '../schema'\nimport { signTransaction } from '../tx'\nimport type { WalletRequest, WalletResponse } from '../transport/envelope'\n\nexport interface WalletHandlerContext {\n\t/** Seed (private key) of the account bound to this session. */\n\tseed: string\n\t/** Address (Base58 public key) of the bound account. */\n\taddress: string\n}\n\nfunction ok(id: string, result: unknown): WalletResponse {\n\treturn { v: PROTOCOL_VERSION, id, ok: true, result }\n}\n\nfunction fail(id: string, error: unknown): WalletResponse {\n\tconst code = error instanceof WalletSdkError ? error.code : 'INTERNAL'\n\tconst message = error instanceof Error ? error.message : 'unexpected error'\n\treturn { v: PROTOCOL_VERSION, id, ok: false, error: { code, message } }\n}\n\n/**\n * Service one approved request and return a response ready to seal. Never throws\n * — failures come back as `{ ok: false, error }` so the transport can always\n * reply. `amadeus_switchNetwork` is deliberately delegated to the app (it mutates\n * wallet runtime state), signalled with a distinct error the caller can branch on.\n */\nexport function handleRequest(request: WalletRequest, ctx: WalletHandlerContext): WalletResponse {\n\ttry {\n\t\tswitch (request.method) {\n\t\t\tcase 'amadeus_signTransaction': {\n\t\t\t\tconst parsed = signTransactionRequestSchema.safeParse(request.params)\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'invalid signTransaction params')\n\t\t\t\t}\n\t\t\t\tconst signed = signTransaction({\n\t\t\t\t\tseed: ctx.seed,\n\t\t\t\t\tcontract: parsed.data.contract,\n\t\t\t\t\tmethod: parsed.data.method,\n\t\t\t\t\targs: parsed.data.args,\n\t\t\t\t\tdescription: parsed.data.description\n\t\t\t\t})\n\t\t\t\treturn ok(request.id, signed)\n\t\t\t}\n\t\t\tcase 'amadeus_generateApiKey': {\n\t\t\t\tconst parsed = generateApiKeyRequestSchema.safeParse(request.params)\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'invalid generateApiKey params')\n\t\t\t\t}\n\t\t\t\tconst { apiKey } = generateApiKey({\n\t\t\t\t\tseed: ctx.seed,\n\t\t\t\t\taud: parsed.data.aud,\n\t\t\t\t\texpIn: parsed.data.exp_in\n\t\t\t\t})\n\t\t\t\treturn ok(request.id, { apiKey })\n\t\t\t}\n\t\t\tcase 'amadeus_getAccounts':\n\t\t\t\treturn ok(request.id, { accounts: [ctx.address] })\n\t\t\tcase 'amadeus_signMessage': {\n\t\t\t\tconst parsed = signMessageRequestSchema.safeParse(request.params)\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tthrow new WalletSdkError('INVALID_ARGUMENT', 'invalid signMessage params')\n\t\t\t\t}\n\t\t\t\tconst signed = signMessage({ seed: ctx.seed, message: parsed.data.message })\n\t\t\t\treturn ok(request.id, signed)\n\t\t\t}\n\t\t\tcase 'amadeus_switchNetwork':\n\t\t\t\tthrow new WalletSdkError(\n\t\t\t\t\t'INVALID_ARGUMENT',\n\t\t\t\t\t'amadeus_switchNetwork must be handled by the wallet app (it changes runtime state)'\n\t\t\t\t)\n\t\t\tdefault:\n\t\t\t\tthrow new WalletSdkError('INVALID_ARGUMENT', `unknown method`)\n\t\t}\n\t} catch (error) {\n\t\treturn fail(request.id, error)\n\t}\n}\n"],"mappings":"
|
|
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"
|