@amadeus-protocol/wallet-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +73 -0
  2. package/dist/binary.d.ts +30 -0
  3. package/dist/binary.d.ts.map +1 -0
  4. package/dist/binary.js +56 -0
  5. package/dist/binary.js.map +1 -0
  6. package/dist/bytes.d.ts +20 -0
  7. package/dist/bytes.d.ts.map +1 -0
  8. package/dist/bytes.js +48 -0
  9. package/dist/bytes.js.map +1 -0
  10. package/dist/client/injected.d.ts +41 -0
  11. package/dist/client/injected.d.ts.map +1 -0
  12. package/dist/client/injected.js +87 -0
  13. package/dist/client/injected.js.map +1 -0
  14. package/dist/constants.d.ts +70 -0
  15. package/dist/constants.d.ts.map +1 -0
  16. package/dist/constants.js +82 -0
  17. package/dist/constants.js.map +1 -0
  18. package/dist/crypto/apikey.d.ts +72 -0
  19. package/dist/crypto/apikey.d.ts.map +1 -0
  20. package/dist/crypto/apikey.js +109 -0
  21. package/dist/crypto/apikey.js.map +1 -0
  22. package/dist/crypto/bls.d.ts +31 -0
  23. package/dist/crypto/bls.d.ts.map +1 -0
  24. package/dist/crypto/bls.js +65 -0
  25. package/dist/crypto/bls.js.map +1 -0
  26. package/dist/crypto/box.d.ts +43 -0
  27. package/dist/crypto/box.d.ts.map +1 -0
  28. package/dist/crypto/box.js +82 -0
  29. package/dist/crypto/box.js.map +1 -0
  30. package/dist/crypto/connect.d.ts +59 -0
  31. package/dist/crypto/connect.d.ts.map +1 -0
  32. package/dist/crypto/connect.js +72 -0
  33. package/dist/crypto/connect.js.map +1 -0
  34. package/dist/errors.d.ts +10 -0
  35. package/dist/errors.d.ts.map +1 -0
  36. package/dist/errors.js +14 -0
  37. package/dist/errors.js.map +1 -0
  38. package/dist/index.d.ts +18 -0
  39. package/dist/index.js +18 -0
  40. package/dist/react/index.d.ts +20 -0
  41. package/dist/react/index.d.ts.map +1 -0
  42. package/dist/react/index.js +95 -0
  43. package/dist/react/index.js.map +1 -0
  44. package/dist/schema.d.ts +63 -0
  45. package/dist/schema.d.ts.map +1 -0
  46. package/dist/schema.js +52 -0
  47. package/dist/schema.js.map +1 -0
  48. package/dist/transport/bridge.d.ts +82 -0
  49. package/dist/transport/bridge.d.ts.map +1 -0
  50. package/dist/transport/bridge.js +125 -0
  51. package/dist/transport/bridge.js.map +1 -0
  52. package/dist/transport/envelope.d.ts +73 -0
  53. package/dist/transport/envelope.d.ts.map +1 -0
  54. package/dist/transport/envelope.js +123 -0
  55. package/dist/transport/envelope.js.map +1 -0
  56. package/dist/transport/session.d.ts +70 -0
  57. package/dist/transport/session.d.ts.map +1 -0
  58. package/dist/transport/session.js +119 -0
  59. package/dist/transport/session.js.map +1 -0
  60. package/dist/transport/uri.d.ts +49 -0
  61. package/dist/transport/uri.d.ts.map +1 -0
  62. package/dist/transport/uri.js +101 -0
  63. package/dist/transport/uri.js.map +1 -0
  64. package/dist/tx.d.ts +42 -0
  65. package/dist/tx.d.ts.map +1 -0
  66. package/dist/tx.js +61 -0
  67. package/dist/tx.js.map +1 -0
  68. package/dist/types.d.ts +80 -0
  69. package/dist/types.d.ts.map +1 -0
  70. package/dist/types.js +14 -0
  71. package/dist/types.js.map +1 -0
  72. package/dist/wallet/handler.d.ts +18 -0
  73. package/dist/wallet/handler.d.ts.map +1 -0
  74. package/dist/wallet/handler.js +79 -0
  75. package/dist/wallet/handler.js.map +1 -0
  76. package/package.json +92 -0
@@ -0,0 +1,72 @@
1
+ //#region src/crypto/apikey.d.ts
2
+ /**
3
+ * BLS12-381 API-key bearer tokens — the ONE audited implementation, replacing
4
+ * the byte-identical copies currently hand-rolled in the wallet extension
5
+ * (`background/handlers/api-key.ts`) and hub/prime-hub (`utils/blsWallet.ts`).
6
+ *
7
+ * Token layout (concatenated, then Base58-encoded):
8
+ * [ jsonBytes (variable) | pubkey (48) | signature (96) ]
9
+ *
10
+ * jsonBytes = utf8(JSON.stringify({ aud, exp })) // key order: aud THEN exp
11
+ * exp = floor(now/1000) + expIn // unix seconds
12
+ * signature = BLS.sign(sha256(jsonBytes || pubkey), sk, { DST: API_KEY_DST })
13
+ *
14
+ * Folding the pubkey into the signed hash blocks rogue-key attacks. `kbs.ama.one`
15
+ * verifies against exactly this construction — do not alter the field order,
16
+ * concatenation, or DST.
17
+ */
18
+ interface ApiKeyPayload {
19
+ aud: string;
20
+ exp: number;
21
+ }
22
+ interface GenerateApiKeyParams {
23
+ /** Base58 wallet seed (private key). */
24
+ seed: string;
25
+ /** Audience claim the bearer will present to. */
26
+ aud: string;
27
+ /** Lifetime in seconds from now. */
28
+ expIn: number;
29
+ /** Override "now" (ms since epoch) — for deterministic tests. */
30
+ now?: number;
31
+ }
32
+ interface GenerateApiKeyResult {
33
+ apiKey: string;
34
+ payload: ApiKeyPayload;
35
+ }
36
+ declare function generateApiKey(params: GenerateApiKeyParams): GenerateApiKeyResult;
37
+ interface DecodedApiKey {
38
+ payload: ApiKeyPayload;
39
+ publicKey: Uint8Array;
40
+ signature: Uint8Array;
41
+ /** The raw JSON bytes that were signed — needed to re-verify exactly. */
42
+ jsonBytes: Uint8Array;
43
+ /** The signing address (Base58 of `publicKey`). */
44
+ address: string;
45
+ }
46
+ /** Parse a token into its parts. Throws `WalletSdkError('INVALID_API_KEY')` on malformed input. */
47
+ declare function decodeApiKey(apiKey: string): DecodedApiKey;
48
+ interface VerifyApiKeyOptions {
49
+ /** If provided, the token's `aud` must equal this. */
50
+ aud?: string;
51
+ /** Override "now" (ms since epoch) — for deterministic tests. */
52
+ now?: number;
53
+ /** Treat the token as expired this many seconds early (clock-skew guard). Default 0. */
54
+ leewaySeconds?: number;
55
+ }
56
+ type VerifyApiKeyResult = {
57
+ valid: true;
58
+ payload: ApiKeyPayload;
59
+ address: string;
60
+ } | {
61
+ valid: false;
62
+ reason: 'malformed' | 'bad_signature' | 'expired' | 'aud_mismatch';
63
+ };
64
+ /**
65
+ * Full verification: structure -> BLS signature (under the API-key DST, with the
66
+ * pubkey folded in) -> expiry -> optional audience. Returns a discriminated
67
+ * result rather than throwing on the common "invalid" paths.
68
+ */
69
+ declare function verifyApiKey(apiKey: string, options?: VerifyApiKeyOptions): VerifyApiKeyResult;
70
+ //#endregion
71
+ export { ApiKeyPayload, DecodedApiKey, GenerateApiKeyParams, GenerateApiKeyResult, VerifyApiKeyOptions, VerifyApiKeyResult, decodeApiKey, generateApiKey, verifyApiKey };
72
+ //# sourceMappingURL=apikey.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apikey.d.ts","names":[],"sources":["../../src/crypto/apikey.ts"],"mappings":";;;;;;;;;;;;;;;;;UA6BiB;EAChB;EACA;;UAGgB;;EAEhB;;EAEA;;EAEA;;EAEA;;UAGgB;EAChB;EACA,SAAS;;iBAGM,eAAe,QAAQ,uBAAuB;UAqB7C;EAChB,SAAS;EACT,WAAW;EACX,WAAW;;EAEX,WAAW;;EAEX;;;iBAIe,aAAa,iBAAiB;UAmD7B;;EAEhB;;EAEA;;EAEA;;KAGW;EACP;EAAa,SAAS;EAAe;;EACrC;EAAc;;;;;;;iBAOH,aACf,gBACA,UAAS,sBACP"}
@@ -0,0 +1,109 @@
1
+ import { API_KEY_DST } from "../constants.js";
2
+ import { WalletSdkError } from "../errors.js";
3
+ import { bytesToUtf8, concatBytes, utf8ToBytes } from "../bytes.js";
4
+ import { deriveSigner, signHashed, verifyHashed } from "./bls.js";
5
+ import { fromBase58, toBase58 } from "@amadeus-protocol/sdk";
6
+ //#region src/crypto/apikey.ts
7
+ /**
8
+ * BLS12-381 API-key bearer tokens — the ONE audited implementation, replacing
9
+ * the byte-identical copies currently hand-rolled in the wallet extension
10
+ * (`background/handlers/api-key.ts`) and hub/prime-hub (`utils/blsWallet.ts`).
11
+ *
12
+ * Token layout (concatenated, then Base58-encoded):
13
+ * [ jsonBytes (variable) | pubkey (48) | signature (96) ]
14
+ *
15
+ * jsonBytes = utf8(JSON.stringify({ aud, exp })) // key order: aud THEN exp
16
+ * exp = floor(now/1000) + expIn // unix seconds
17
+ * signature = BLS.sign(sha256(jsonBytes || pubkey), sk, { DST: API_KEY_DST })
18
+ *
19
+ * Folding the pubkey into the signed hash blocks rogue-key attacks. `kbs.ama.one`
20
+ * verifies against exactly this construction — do not alter the field order,
21
+ * concatenation, or DST.
22
+ */
23
+ function generateApiKey(params) {
24
+ if (!params.aud || params.aud.length === 0) throw new WalletSdkError("INVALID_ARGUMENT", "aud is required");
25
+ if (!Number.isInteger(params.expIn) || params.expIn <= 0) throw new WalletSdkError("INVALID_ARGUMENT", "expIn must be a positive integer (seconds)");
26
+ const { sk, pk } = deriveSigner(params.seed);
27
+ const nowMs = params.now ?? Date.now();
28
+ const exp = Math.floor(nowMs / 1e3) + params.expIn;
29
+ const jsonBytes = utf8ToBytes(JSON.stringify({
30
+ aud: params.aud,
31
+ exp
32
+ }));
33
+ return {
34
+ apiKey: toBase58(concatBytes(jsonBytes, pk, signHashed(concatBytes(jsonBytes, pk), sk, API_KEY_DST))),
35
+ payload: {
36
+ aud: params.aud,
37
+ exp
38
+ }
39
+ };
40
+ }
41
+ /** Parse a token into its parts. Throws `WalletSdkError('INVALID_API_KEY')` on malformed input. */
42
+ function decodeApiKey(apiKey) {
43
+ if (typeof apiKey !== "string" || apiKey.length === 0 || apiKey.length > 1024) throw new WalletSdkError("INVALID_API_KEY", "api key length is out of range");
44
+ let raw;
45
+ try {
46
+ raw = fromBase58(apiKey);
47
+ } catch {
48
+ throw new WalletSdkError("INVALID_API_KEY", "api key is not valid Base58");
49
+ }
50
+ const jsonEnd = raw.length - 48 - 96;
51
+ if (jsonEnd <= 0) throw new WalletSdkError("INVALID_API_KEY", "api key is too short to contain a payload");
52
+ const jsonBytes = raw.slice(0, jsonEnd);
53
+ const publicKey = raw.slice(jsonEnd, jsonEnd + 48);
54
+ const signature = raw.slice(jsonEnd + 48);
55
+ let parsed;
56
+ try {
57
+ parsed = JSON.parse(bytesToUtf8(jsonBytes));
58
+ } catch {
59
+ throw new WalletSdkError("INVALID_API_KEY", "api key payload is not valid JSON");
60
+ }
61
+ if (typeof parsed !== "object" || parsed === null || typeof parsed.aud !== "string" || typeof parsed.exp !== "number" || !Number.isFinite(parsed.exp)) throw new WalletSdkError("INVALID_API_KEY", "api key payload must be { aud: string, exp: number }");
62
+ return {
63
+ payload: parsed,
64
+ publicKey,
65
+ signature,
66
+ jsonBytes,
67
+ address: toBase58(publicKey)
68
+ };
69
+ }
70
+ /**
71
+ * Full verification: structure -> BLS signature (under the API-key DST, with the
72
+ * pubkey folded in) -> expiry -> optional audience. Returns a discriminated
73
+ * result rather than throwing on the common "invalid" paths.
74
+ */
75
+ function verifyApiKey(apiKey, options = {}) {
76
+ let decoded;
77
+ try {
78
+ decoded = decodeApiKey(apiKey);
79
+ } catch {
80
+ return {
81
+ valid: false,
82
+ reason: "malformed"
83
+ };
84
+ }
85
+ const signed = concatBytes(decoded.jsonBytes, decoded.publicKey);
86
+ if (!verifyHashed(decoded.signature, signed, decoded.publicKey, "AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_APIKEY_")) return {
87
+ valid: false,
88
+ reason: "bad_signature"
89
+ };
90
+ const nowSec = Math.floor((options.now ?? Date.now()) / 1e3);
91
+ const leeway = options.leewaySeconds ?? 0;
92
+ if (decoded.payload.exp <= nowSec + leeway) return {
93
+ valid: false,
94
+ reason: "expired"
95
+ };
96
+ if (options.aud !== void 0 && decoded.payload.aud !== options.aud) return {
97
+ valid: false,
98
+ reason: "aud_mismatch"
99
+ };
100
+ return {
101
+ valid: true,
102
+ payload: decoded.payload,
103
+ address: decoded.address
104
+ };
105
+ }
106
+ //#endregion
107
+ export { decodeApiKey, generateApiKey, verifyApiKey };
108
+
109
+ //# sourceMappingURL=apikey.js.map
@@ -0,0 +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;CAKtE,OAAO;EAAE,QAAQ,SAFH,YAAY,WAAW,IADnB,WADH,YAAY,WAAW,EACJ,GAAG,IAAI,WACQ,CAEnB,CAAC;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"}
@@ -0,0 +1,31 @@
1
+ //#region src/crypto/bls.d.ts
2
+ /**
3
+ * Low-level BLS12-381 signing primitives, mirroring the exact recipe used by
4
+ * `@amadeus-protocol/sdk` (`signing.ts`) and the wallet extension: hash the
5
+ * payload with SHA-256, then `bls.sign(hash, sk, { DST })`. Amadeus uses the
6
+ * "long-signature" variant — G1 public keys (48 bytes) and G2 signatures
7
+ * (96 bytes) — via the deprecated top-level `bls.sign`/`bls.verify` API that the
8
+ * SDK also uses, so bytes stay identical. Key derivation is reused from the SDK.
9
+ */
10
+ interface SignerKeys {
11
+ /** 32-byte scalar secret key. */
12
+ sk: Uint8Array;
13
+ /** 48-byte G1 public key (also the Base58 address). */
14
+ pk: Uint8Array;
15
+ }
16
+ /** Derive the BLS signer keys from a Base58 seed (the wallet's private key). */
17
+ declare function deriveSigner(seedBase58: string): SignerKeys;
18
+ /**
19
+ * Sign `sha256(payload)` under the given DST. `payload` is the raw message
20
+ * bytes (NOT already hashed) — the SHA-256 happens here, matching the SDK.
21
+ */
22
+ declare function signHashed(payload: Uint8Array, sk: Uint8Array, dst: string): Uint8Array;
23
+ /** Verify a signature over `sha256(payload)` under the given DST. Never throws. */
24
+ declare function verifyHashed(signature: Uint8Array, payload: Uint8Array, publicKey: Uint8Array, dst: string): boolean;
25
+ /** Decode a Base58 address into its 48-byte public key, validating length. */
26
+ declare function publicKeyFromAddress(address: string): Uint8Array;
27
+ /** Decode a Base58 signature into its 96 raw bytes, validating length. */
28
+ declare function signatureFromBase58(signature: string): Uint8Array;
29
+ //#endregion
30
+ export { SignerKeys, deriveSigner, publicKeyFromAddress, signHashed, signatureFromBase58, verifyHashed };
31
+ //# sourceMappingURL=bls.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bls.d.ts","names":[],"sources":["../../src/crypto/bls.ts"],"mappings":";;;;;;;;;UAgBiB;;EAEhB,IAAI;;EAEJ,IAAI;;;iBAIW,aAAa,qBAAqB;;;;;iBAUlC,WAAW,SAAS,YAAY,IAAI,YAAY,cAAc;;iBAM9D,aACf,WAAW,YACX,SAAS,YACT,WAAW,YACX;;iBAWe,qBAAqB,kBAAkB;;iBAiBvC,oBAAoB,oBAAoB"}
@@ -0,0 +1,65 @@
1
+ import "../constants.js";
2
+ import { WalletSdkError } from "../errors.js";
3
+ import { deriveSkAndSeed64FromBase58Seed, fromBase58, getPublicKey } from "@amadeus-protocol/sdk";
4
+ import { bls12_381 } from "@noble/curves/bls12-381";
5
+ import { sha256 } from "@noble/hashes/sha2";
6
+ //#region src/crypto/bls.ts
7
+ /**
8
+ * Low-level BLS12-381 signing primitives, mirroring the exact recipe used by
9
+ * `@amadeus-protocol/sdk` (`signing.ts`) and the wallet extension: hash the
10
+ * payload with SHA-256, then `bls.sign(hash, sk, { DST })`. Amadeus uses the
11
+ * "long-signature" variant — G1 public keys (48 bytes) and G2 signatures
12
+ * (96 bytes) — via the deprecated top-level `bls.sign`/`bls.verify` API that the
13
+ * SDK also uses, so bytes stay identical. Key derivation is reused from the SDK.
14
+ */
15
+ /** Derive the BLS signer keys from a Base58 seed (the wallet's private key). */
16
+ function deriveSigner(seedBase58) {
17
+ const { sk, seed64 } = deriveSkAndSeed64FromBase58Seed(seedBase58);
18
+ return {
19
+ sk,
20
+ pk: getPublicKey(seed64)
21
+ };
22
+ }
23
+ /**
24
+ * Sign `sha256(payload)` under the given DST. `payload` is the raw message
25
+ * bytes (NOT already hashed) — the SHA-256 happens here, matching the SDK.
26
+ */
27
+ function signHashed(payload, sk, dst) {
28
+ const hash = sha256(payload);
29
+ return bls12_381.sign(hash, sk, { DST: dst });
30
+ }
31
+ /** Verify a signature over `sha256(payload)` under the given DST. Never throws. */
32
+ function verifyHashed(signature, payload, publicKey, dst) {
33
+ try {
34
+ const hash = sha256(payload);
35
+ return bls12_381.verify(signature, hash, publicKey, { DST: dst });
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+ /** Decode a Base58 address into its 48-byte public key, validating length. */
41
+ function publicKeyFromAddress(address) {
42
+ let pk;
43
+ try {
44
+ pk = fromBase58(address);
45
+ } catch {
46
+ throw new WalletSdkError("INVALID_ADDRESS", "address is not valid Base58");
47
+ }
48
+ if (pk.length !== 48) throw new WalletSdkError("INVALID_ADDRESS", `address must decode to 48 bytes, got ${pk.length}`);
49
+ return pk;
50
+ }
51
+ /** Decode a Base58 signature into its 96 raw bytes, validating length. */
52
+ function signatureFromBase58(signature) {
53
+ let sig;
54
+ try {
55
+ sig = fromBase58(signature);
56
+ } catch {
57
+ throw new WalletSdkError("INVALID_SIGNATURE", "signature is not valid Base58");
58
+ }
59
+ if (sig.length !== 96) throw new WalletSdkError("INVALID_SIGNATURE", `signature must be 96 bytes, got ${sig.length}`);
60
+ return sig;
61
+ }
62
+ //#endregion
63
+ export { deriveSigner, publicKeyFromAddress, signHashed, signatureFromBase58, verifyHashed };
64
+
65
+ //# sourceMappingURL=bls.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bls.js","names":["bls"],"sources":["../../src/crypto/bls.ts"],"sourcesContent":["/**\n * Low-level BLS12-381 signing primitives, mirroring the exact recipe used by\n * `@amadeus-protocol/sdk` (`signing.ts`) and the wallet extension: hash the\n * payload with SHA-256, then `bls.sign(hash, sk, { DST })`. Amadeus uses the\n * \"long-signature\" variant — G1 public keys (48 bytes) and G2 signatures\n * (96 bytes) — via the deprecated top-level `bls.sign`/`bls.verify` API that the\n * SDK also uses, so bytes stay identical. Key derivation is reused from the SDK.\n */\n\nimport { deriveSkAndSeed64FromBase58Seed, fromBase58, getPublicKey } from '@amadeus-protocol/sdk'\nimport { bls12_381 as bls } from '@noble/curves/bls12-381'\nimport { sha256 } from '@noble/hashes/sha2'\n\nimport { PUBLIC_KEY_BYTE_LENGTH, SIGNATURE_BYTE_LENGTH } from '../constants'\nimport { WalletSdkError } from '../errors'\n\nexport interface SignerKeys {\n\t/** 32-byte scalar secret key. */\n\tsk: Uint8Array\n\t/** 48-byte G1 public key (also the Base58 address). */\n\tpk: Uint8Array\n}\n\n/** Derive the BLS signer keys from a Base58 seed (the wallet's private key). */\nexport function deriveSigner(seedBase58: string): SignerKeys {\n\tconst { sk, seed64 } = deriveSkAndSeed64FromBase58Seed(seedBase58)\n\tconst pk = getPublicKey(seed64)\n\treturn { sk, pk }\n}\n\n/**\n * Sign `sha256(payload)` under the given DST. `payload` is the raw message\n * bytes (NOT already hashed) — the SHA-256 happens here, matching the SDK.\n */\nexport function signHashed(payload: Uint8Array, sk: Uint8Array, dst: string): Uint8Array {\n\tconst hash = sha256(payload)\n\treturn bls.sign(hash, sk, { DST: dst })\n}\n\n/** Verify a signature over `sha256(payload)` under the given DST. Never throws. */\nexport function verifyHashed(\n\tsignature: Uint8Array,\n\tpayload: Uint8Array,\n\tpublicKey: Uint8Array,\n\tdst: string\n): boolean {\n\ttry {\n\t\tconst hash = sha256(payload)\n\t\treturn bls.verify(signature, hash, publicKey, { DST: dst })\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/** Decode a Base58 address into its 48-byte public key, validating length. */\nexport function publicKeyFromAddress(address: string): Uint8Array {\n\tlet pk: Uint8Array\n\ttry {\n\t\tpk = fromBase58(address)\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_ADDRESS', 'address is not valid Base58')\n\t}\n\tif (pk.length !== PUBLIC_KEY_BYTE_LENGTH) {\n\t\tthrow new WalletSdkError(\n\t\t\t'INVALID_ADDRESS',\n\t\t\t`address must decode to ${PUBLIC_KEY_BYTE_LENGTH} bytes, got ${pk.length}`\n\t\t)\n\t}\n\treturn pk\n}\n\n/** Decode a Base58 signature into its 96 raw bytes, validating length. */\nexport function signatureFromBase58(signature: string): Uint8Array {\n\tlet sig: Uint8Array\n\ttry {\n\t\tsig = fromBase58(signature)\n\t} catch {\n\t\tthrow new WalletSdkError('INVALID_SIGNATURE', 'signature is not valid Base58')\n\t}\n\tif (sig.length !== SIGNATURE_BYTE_LENGTH) {\n\t\tthrow new WalletSdkError(\n\t\t\t'INVALID_SIGNATURE',\n\t\t\t`signature must be ${SIGNATURE_BYTE_LENGTH} bytes, got ${sig.length}`\n\t\t)\n\t}\n\treturn sig\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,SAAgB,aAAa,YAAgC;CAC5D,MAAM,EAAE,IAAI,WAAW,gCAAgC,UAAU;CAEjE,OAAO;EAAE;EAAI,IADF,aAAa,MACV;CAAE;AACjB;;;;;AAMA,SAAgB,WAAW,SAAqB,IAAgB,KAAyB;CACxF,MAAM,OAAO,OAAO,OAAO;CAC3B,OAAOA,UAAI,KAAK,MAAM,IAAI,EAAE,KAAK,IAAI,CAAC;AACvC;;AAGA,SAAgB,aACf,WACA,SACA,WACA,KACU;CACV,IAAI;EACH,MAAM,OAAO,OAAO,OAAO;EAC3B,OAAOA,UAAI,OAAO,WAAW,MAAM,WAAW,EAAE,KAAK,IAAI,CAAC;CAC3D,QAAQ;EACP,OAAO;CACR;AACD;;AAGA,SAAgB,qBAAqB,SAA6B;CACjE,IAAI;CACJ,IAAI;EACH,KAAK,WAAW,OAAO;CACxB,QAAQ;EACP,MAAM,IAAI,eAAe,mBAAmB,6BAA6B;CAC1E;CACA,IAAI,GAAG,WAAA,IACN,MAAM,IAAI,eACT,mBACA,wCAA+D,GAAG,QACnE;CAED,OAAO;AACR;;AAGA,SAAgB,oBAAoB,WAA+B;CAClE,IAAI;CACJ,IAAI;EACH,MAAM,WAAW,SAAS;CAC3B,QAAQ;EACP,MAAM,IAAI,eAAe,qBAAqB,+BAA+B;CAC9E;CACA,IAAI,IAAI,WAAA,IACP,MAAM,IAAI,eACT,qBACA,mCAAyD,IAAI,QAC9D;CAED,OAAO;AACR"}
@@ -0,0 +1,43 @@
1
+ //#region src/crypto/box.d.ts
2
+ /**
3
+ * End-to-end encrypted session channel for cross-device transports (QR / bridge).
4
+ *
5
+ * Each side holds an ephemeral x25519 keypair; the shared secret is derived via
6
+ * ECDH and run through SHA-256 into a 32-byte symmetric key, then messages are
7
+ * sealed with XChaCha20-Poly1305 (24-byte random nonce per message, AEAD auth
8
+ * tag). This stack is Hermes-safe — it reuses the same `@noble` crypto the mobile
9
+ * app already ships, and the CSPRNG is the platform `crypto.getRandomValues`.
10
+ *
11
+ * The x25519 keypair here is ONLY for transport encryption. It is completely
12
+ * separate from the wallet's BLS signing key — never conflate them.
13
+ */
14
+ interface SessionKeypair {
15
+ /** x25519 public key (Base58) — safe to send in the clear (in the QR / link). */
16
+ publicKey: string;
17
+ /** x25519 secret key (32 raw bytes) — keep in memory only, never persist. */
18
+ secretKey: Uint8Array;
19
+ }
20
+ /** Generate a fresh ephemeral x25519 session keypair. */
21
+ declare function generateSessionKeypair(): SessionKeypair;
22
+ /**
23
+ * Derive the 32-byte symmetric key shared with a peer. Both sides call this with
24
+ * (their own secret, the other's public) and get the same key.
25
+ */
26
+ declare function deriveSharedKey(theirPublicKeyBase58: string, mySecretKey: Uint8Array): Uint8Array;
27
+ interface SealedEnvelope {
28
+ /** Base58 24-byte nonce. */
29
+ nonce: string;
30
+ /** Base58 ciphertext (includes the Poly1305 auth tag). */
31
+ ciphertext: string;
32
+ }
33
+ /** Seal plaintext with the shared key. Optional `aad` is authenticated but not encrypted. */
34
+ declare function seal(sharedKey: Uint8Array, plaintext: Uint8Array, aad?: Uint8Array): SealedEnvelope;
35
+ /**
36
+ * Open a sealed envelope. Throws `WalletSdkError('DECRYPT_FAILED')` if the key is
37
+ * wrong, the ciphertext/aad was tampered with, or the envelope is malformed —
38
+ * i.e. it fails closed.
39
+ */
40
+ declare function open(sharedKey: Uint8Array, envelope: SealedEnvelope, aad?: Uint8Array): Uint8Array;
41
+ //#endregion
42
+ export { SealedEnvelope, SessionKeypair, deriveSharedKey, generateSessionKeypair, open, seal };
43
+ //# sourceMappingURL=box.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"box.d.ts","names":[],"sources":["../../src/crypto/box.ts"],"mappings":";;;;;;;;;;;;;UA0BiB;;EAEhB;;EAEA,WAAW;;;iBAII,0BAA0B;;;;;iBAU1B,gBAAgB,8BAA8B,aAAa,aAAa;UAyBvE;;EAEhB;;EAEA;;;iBAIe,KACf,WAAW,YACX,WAAW,YACX,MAAM,aACJ;;;;;;iBAWa,KACf,WAAW,YACX,UAAU,gBACV,MAAM,aACJ"}
@@ -0,0 +1,82 @@
1
+ import "../constants.js";
2
+ import { WalletSdkError } from "../errors.js";
3
+ import { randomBytes } from "../bytes.js";
4
+ import { fromBase58, toBase58 } from "@amadeus-protocol/sdk";
5
+ import { sha256 } from "@noble/hashes/sha2";
6
+ import { xchacha20poly1305 } from "@noble/ciphers/chacha.js";
7
+ import { x25519 } from "@noble/curves/ed25519";
8
+ //#region src/crypto/box.ts
9
+ /**
10
+ * End-to-end encrypted session channel for cross-device transports (QR / bridge).
11
+ *
12
+ * Each side holds an ephemeral x25519 keypair; the shared secret is derived via
13
+ * ECDH and run through SHA-256 into a 32-byte symmetric key, then messages are
14
+ * sealed with XChaCha20-Poly1305 (24-byte random nonce per message, AEAD auth
15
+ * tag). This stack is Hermes-safe — it reuses the same `@noble` crypto the mobile
16
+ * app already ships, and the CSPRNG is the platform `crypto.getRandomValues`.
17
+ *
18
+ * The x25519 keypair here is ONLY for transport encryption. It is completely
19
+ * separate from the wallet's BLS signing key — never conflate them.
20
+ */
21
+ /** Generate a fresh ephemeral x25519 session keypair. */
22
+ function generateSessionKeypair() {
23
+ const secretKey = randomBytes(32);
24
+ return {
25
+ publicKey: toBase58(x25519.getPublicKey(secretKey)),
26
+ secretKey
27
+ };
28
+ }
29
+ /**
30
+ * Derive the 32-byte symmetric key shared with a peer. Both sides call this with
31
+ * (their own secret, the other's public) and get the same key.
32
+ */
33
+ function deriveSharedKey(theirPublicKeyBase58, mySecretKey) {
34
+ let theirPublicKey;
35
+ try {
36
+ theirPublicKey = fromBase58(theirPublicKeyBase58);
37
+ } catch {
38
+ throw new WalletSdkError("DECRYPT_FAILED", "peer public key is not valid Base58");
39
+ }
40
+ if (theirPublicKey.length !== 32) throw new WalletSdkError("DECRYPT_FAILED", "peer public key has the wrong length");
41
+ let shared;
42
+ try {
43
+ shared = x25519.getSharedSecret(mySecretKey, theirPublicKey);
44
+ } catch {
45
+ throw new WalletSdkError("DECRYPT_FAILED", "invalid peer public key (low-order or malformed)");
46
+ }
47
+ return sha256(shared);
48
+ }
49
+ /** Seal plaintext with the shared key. Optional `aad` is authenticated but not encrypted. */
50
+ function seal(sharedKey, plaintext, aad) {
51
+ const nonce = randomBytes(24);
52
+ const ciphertext = xchacha20poly1305(sharedKey, nonce, aad).encrypt(plaintext);
53
+ return {
54
+ nonce: toBase58(nonce),
55
+ ciphertext: toBase58(ciphertext)
56
+ };
57
+ }
58
+ /**
59
+ * Open a sealed envelope. Throws `WalletSdkError('DECRYPT_FAILED')` if the key is
60
+ * wrong, the ciphertext/aad was tampered with, or the envelope is malformed —
61
+ * i.e. it fails closed.
62
+ */
63
+ function open(sharedKey, envelope, aad) {
64
+ let nonce;
65
+ let ciphertext;
66
+ try {
67
+ nonce = fromBase58(envelope.nonce);
68
+ ciphertext = fromBase58(envelope.ciphertext);
69
+ } catch {
70
+ throw new WalletSdkError("DECRYPT_FAILED", "sealed envelope is not valid Base58");
71
+ }
72
+ if (nonce.length !== 24) throw new WalletSdkError("DECRYPT_FAILED", "nonce has the wrong length");
73
+ try {
74
+ return xchacha20poly1305(sharedKey, nonce, aad).decrypt(ciphertext);
75
+ } catch {
76
+ throw new WalletSdkError("DECRYPT_FAILED", "authentication failed (wrong key or tampered)");
77
+ }
78
+ }
79
+ //#endregion
80
+ export { deriveSharedKey, generateSessionKeypair, open, seal };
81
+
82
+ //# sourceMappingURL=box.js.map
@@ -0,0 +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;CAE5D,OAAO;EAAE,WAAW,SADF,OAAO,aAAa,SACD,CAAC;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"}
@@ -0,0 +1,59 @@
1
+ //#region src/crypto/connect.d.ts
2
+ /**
3
+ * Connection-auth signatures. When a dApp asks the wallet to connect, it must
4
+ * prove control of its address. The wallet signs a TRANSCRIPT that binds the
5
+ * whole handshake — origin, both x25519 session public keys, the dApp's
6
+ * challenge, and the request id — NOT just the raw challenge nonce.
7
+ *
8
+ * Signing only the nonce is a key-substitution MITM: an attacker replays a
9
+ * harvested `sig(challenge)` under their own session keys and ends up with a
10
+ * fully-authenticated session. Binding the session keys + origin into the signed
11
+ * bytes closes that, the same property SIWE / CAIP-122 rely on.
12
+ *
13
+ * The transcript is length-prefixed and label-tagged so its bytes are
14
+ * unambiguous, and signed under `CONNECT_DST` so a connect proof can never be
15
+ * reused as a transaction, api-key, or any other signature.
16
+ */
17
+ interface ConnectTranscript {
18
+ /** The dApp's origin, e.g. "https://app.amadeus.xyz". */
19
+ origin: string;
20
+ /** The dApp's ephemeral x25519 session public key (Base58). */
21
+ dappPublicKey: string;
22
+ /** The wallet's ephemeral x25519 session public key (Base58). */
23
+ walletPublicKey: string;
24
+ /** Random challenge nonce chosen by the dApp. */
25
+ challenge: string;
26
+ /** Unique id for this connect request. */
27
+ requestId: string;
28
+ }
29
+ /**
30
+ * Deterministic canonical bytes for a transcript. Identical inputs -> identical
31
+ * bytes on both wallet and dApp (that's the whole point of a shared package).
32
+ * Every element is length-prefixed (including the label) so field boundaries are
33
+ * unambiguous — no concatenation/canonicalization ambiguity even if the label is
34
+ * ever made dynamic. Layout: u32(labelLen) ++ label ++ u32(fieldCount) ++
35
+ * for each field: u32(len) ++ utf8(field).
36
+ */
37
+ declare function buildConnectTranscript(transcript: ConnectTranscript): Uint8Array;
38
+ interface SignConnectParams {
39
+ /** Base58 wallet seed (private key). */
40
+ seed: string;
41
+ transcript: ConnectTranscript;
42
+ }
43
+ /** Wallet side: sign the transcript, returning a Base58 signature. */
44
+ declare function signConnect(params: SignConnectParams): string;
45
+ interface VerifyConnectParams {
46
+ /** The address (Base58 public key) that claims to have signed. */
47
+ address: string;
48
+ transcript: ConnectTranscript;
49
+ /** The Base58 signature returned by the wallet. */
50
+ signature: string;
51
+ }
52
+ /**
53
+ * dApp side: verify the wallet controls `address` for this exact transcript.
54
+ * Never throws — returns false on any malformed input or verification failure.
55
+ */
56
+ declare function verifyConnect(params: VerifyConnectParams): boolean;
57
+ //#endregion
58
+ export { ConnectTranscript, SignConnectParams, VerifyConnectParams, buildConnectTranscript, signConnect, verifyConnect };
59
+ //# sourceMappingURL=connect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect.d.ts","names":[],"sources":["../../src/crypto/connect.ts"],"mappings":";;;;;;;;;;;;;;;;UA4BiB;;EAEhB;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;iBAWe,uBAAuB,YAAY,oBAAoB;UAiBtD;;EAEhB;EACA,YAAY;;;iBAIG,YAAY,QAAQ;UAMnB;;EAEhB;EACA,YAAY;;EAEZ;;;;;;iBAOe,cAAc,QAAQ"}
@@ -0,0 +1,72 @@
1
+ import { CONNECT_DST, CONNECT_TRANSCRIPT_LABEL } from "../constants.js";
2
+ import { concatBytes, u32be, utf8ToBytes } from "../bytes.js";
3
+ import { deriveSigner, publicKeyFromAddress, signHashed, signatureFromBase58, verifyHashed } from "./bls.js";
4
+ import { toBase58 } from "@amadeus-protocol/sdk";
5
+ //#region src/crypto/connect.ts
6
+ /**
7
+ * Connection-auth signatures. When a dApp asks the wallet to connect, it must
8
+ * prove control of its address. The wallet signs a TRANSCRIPT that binds the
9
+ * whole handshake — origin, both x25519 session public keys, the dApp's
10
+ * challenge, and the request id — NOT just the raw challenge nonce.
11
+ *
12
+ * Signing only the nonce is a key-substitution MITM: an attacker replays a
13
+ * harvested `sig(challenge)` under their own session keys and ends up with a
14
+ * fully-authenticated session. Binding the session keys + origin into the signed
15
+ * bytes closes that, the same property SIWE / CAIP-122 rely on.
16
+ *
17
+ * The transcript is length-prefixed and label-tagged so its bytes are
18
+ * unambiguous, and signed under `CONNECT_DST` so a connect proof can never be
19
+ * reused as a transaction, api-key, or any other signature.
20
+ */
21
+ /**
22
+ * Deterministic canonical bytes for a transcript. Identical inputs -> identical
23
+ * bytes on both wallet and dApp (that's the whole point of a shared package).
24
+ * Every element is length-prefixed (including the label) so field boundaries are
25
+ * unambiguous — no concatenation/canonicalization ambiguity even if the label is
26
+ * ever made dynamic. Layout: u32(labelLen) ++ label ++ u32(fieldCount) ++
27
+ * for each field: u32(len) ++ utf8(field).
28
+ */
29
+ function buildConnectTranscript(transcript) {
30
+ const fields = [
31
+ transcript.origin,
32
+ transcript.dappPublicKey,
33
+ transcript.walletPublicKey,
34
+ transcript.challenge,
35
+ transcript.requestId
36
+ ];
37
+ const label = utf8ToBytes(CONNECT_TRANSCRIPT_LABEL);
38
+ const parts = [
39
+ u32be(label.length),
40
+ label,
41
+ u32be(fields.length)
42
+ ];
43
+ for (const field of fields) {
44
+ const bytes = utf8ToBytes(field);
45
+ parts.push(u32be(bytes.length), bytes);
46
+ }
47
+ return concatBytes(...parts);
48
+ }
49
+ /** Wallet side: sign the transcript, returning a Base58 signature. */
50
+ function signConnect(params) {
51
+ const { sk } = deriveSigner(params.seed);
52
+ return toBase58(signHashed(buildConnectTranscript(params.transcript), sk, CONNECT_DST));
53
+ }
54
+ /**
55
+ * dApp side: verify the wallet controls `address` for this exact transcript.
56
+ * Never throws — returns false on any malformed input or verification failure.
57
+ */
58
+ function verifyConnect(params) {
59
+ let publicKey;
60
+ let signature;
61
+ try {
62
+ publicKey = publicKeyFromAddress(params.address);
63
+ signature = signatureFromBase58(params.signature);
64
+ } catch {
65
+ return false;
66
+ }
67
+ return verifyHashed(signature, buildConnectTranscript(params.transcript), publicKey, CONNECT_DST);
68
+ }
69
+ //#endregion
70
+ export { buildConnectTranscript, signConnect, verifyConnect };
71
+
72
+ //# sourceMappingURL=connect.js.map
@@ -0,0 +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;CAEvC,OAAO,SADW,WAAW,uBAAuB,OAAO,UAAU,GAAG,IAAI,WACpD,CAAC;AAC1B;;;;;AAcA,SAAgB,cAAc,QAAsC;CACnE,IAAI;CACJ,IAAI;CACJ,IAAI;EACH,YAAY,qBAAqB,OAAO,OAAO;EAC/C,YAAY,oBAAoB,OAAO,SAAS;CACjD,QAAQ;EACP,OAAO;CACR;CACA,OAAO,aACN,WACA,uBAAuB,OAAO,UAAU,GACxC,WACA,WACD;AACD"}
@@ -0,0 +1,10 @@
1
+ //#region src/errors.d.ts
2
+ /** Stable error codes so callers can branch without string-matching messages. */
3
+ type WalletSdkErrorCode = 'INVALID_API_KEY' | 'BAD_SIGNATURE' | 'EXPIRED' | 'AUD_MISMATCH' | 'INVALID_ADDRESS' | 'INVALID_SIGNATURE' | 'INVALID_ARGUMENT' | 'SUBMIT_FAILED' | 'DECRYPT_FAILED';
4
+ declare class WalletSdkError extends Error {
5
+ readonly code: WalletSdkErrorCode;
6
+ constructor(code: WalletSdkErrorCode, message: string);
7
+ }
8
+ //#endregion
9
+ export { WalletSdkError, WalletSdkErrorCode };
10
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","names":[],"sources":["../src/errors.ts"],"mappings":";;KACY;cAWC,uBAAuB;WAC1B,MAAM;cAEH,MAAM,oBAAoB"}
package/dist/errors.js ADDED
@@ -0,0 +1,14 @@
1
+ //#region src/errors.ts
2
+ var WalletSdkError = class WalletSdkError extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.name = "WalletSdkError";
7
+ this.code = code;
8
+ Object.setPrototypeOf(this, WalletSdkError.prototype);
9
+ }
10
+ };
11
+ //#endregion
12
+ export { WalletSdkError };
13
+
14
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Stable error codes so callers can branch without string-matching messages. */\nexport type WalletSdkErrorCode =\n\t| 'INVALID_API_KEY'\n\t| 'BAD_SIGNATURE'\n\t| 'EXPIRED'\n\t| 'AUD_MISMATCH'\n\t| 'INVALID_ADDRESS'\n\t| 'INVALID_SIGNATURE'\n\t| 'INVALID_ARGUMENT'\n\t| 'SUBMIT_FAILED'\n\t| 'DECRYPT_FAILED'\n\nexport class WalletSdkError extends Error {\n\treadonly code: WalletSdkErrorCode\n\n\tconstructor(code: WalletSdkErrorCode, message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'WalletSdkError'\n\t\tthis.code = code\n\t\t// Restore prototype chain for instanceof across transpile targets.\n\t\tObject.setPrototypeOf(this, WalletSdkError.prototype)\n\t}\n}\n"],"mappings":";AAYA,IAAa,iBAAb,MAAa,uBAAuB,MAAM;CACzC;CAEA,YAAY,MAA0B,SAAiB;EACtD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EAEZ,OAAO,eAAe,MAAM,eAAe,SAAS;CACrD;AACD"}