@mysten/seal 0.2.0 → 0.3.1

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 (108) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/cjs/bcs.d.ts +132 -0
  3. package/dist/cjs/bcs.js +67 -0
  4. package/dist/cjs/bcs.js.map +7 -0
  5. package/dist/cjs/client.d.ts +83 -0
  6. package/dist/cjs/client.js +283 -0
  7. package/dist/cjs/client.js.map +7 -0
  8. package/dist/cjs/decrypt.d.ts +15 -0
  9. package/dist/cjs/decrypt.js +94 -0
  10. package/dist/cjs/decrypt.js.map +7 -0
  11. package/dist/cjs/dem.d.ts +36 -0
  12. package/dist/cjs/dem.js +173 -0
  13. package/dist/cjs/dem.js.map +7 -0
  14. package/dist/cjs/elgamal.js.map +2 -2
  15. package/dist/cjs/encrypt.d.ts +14 -5
  16. package/dist/cjs/encrypt.js +52 -22
  17. package/dist/cjs/encrypt.js.map +3 -3
  18. package/dist/cjs/error.d.ts +58 -0
  19. package/dist/cjs/error.js +175 -0
  20. package/dist/cjs/error.js.map +7 -0
  21. package/dist/cjs/ibe.d.ts +13 -17
  22. package/dist/cjs/ibe.js +25 -28
  23. package/dist/cjs/ibe.js.map +2 -2
  24. package/dist/cjs/index.d.ts +3 -5
  25. package/dist/cjs/index.js +5 -11
  26. package/dist/cjs/index.js.map +2 -2
  27. package/dist/cjs/kdf.d.ts +7 -2
  28. package/dist/cjs/kdf.js +37 -2
  29. package/dist/cjs/kdf.js.map +3 -3
  30. package/dist/cjs/key-server.d.ts +5 -5
  31. package/dist/cjs/key-server.js +24 -21
  32. package/dist/cjs/key-server.js.map +2 -2
  33. package/dist/cjs/keys.d.ts +17 -0
  34. package/dist/cjs/keys.js +61 -0
  35. package/dist/cjs/keys.js.map +7 -0
  36. package/dist/cjs/session-key.d.ts +20 -14
  37. package/dist/cjs/session-key.js +90 -23
  38. package/dist/cjs/session-key.js.map +2 -2
  39. package/dist/cjs/types.d.ts +1 -86
  40. package/dist/cjs/types.js +0 -32
  41. package/dist/cjs/types.js.map +2 -2
  42. package/dist/cjs/utils.d.ts +2 -1
  43. package/dist/cjs/utils.js +17 -5
  44. package/dist/cjs/utils.js.map +2 -2
  45. package/dist/cjs/version.d.ts +1 -0
  46. package/dist/cjs/version.js +25 -0
  47. package/dist/cjs/version.js.map +7 -0
  48. package/dist/esm/bcs.d.ts +132 -0
  49. package/dist/esm/bcs.js +47 -0
  50. package/dist/esm/bcs.js.map +7 -0
  51. package/dist/esm/client.d.ts +83 -0
  52. package/dist/esm/client.js +268 -0
  53. package/dist/esm/client.js.map +7 -0
  54. package/dist/esm/decrypt.d.ts +15 -0
  55. package/dist/esm/decrypt.js +74 -0
  56. package/dist/esm/decrypt.js.map +7 -0
  57. package/dist/esm/dem.d.ts +36 -0
  58. package/dist/esm/dem.js +153 -0
  59. package/dist/esm/dem.js.map +7 -0
  60. package/dist/esm/elgamal.js.map +2 -2
  61. package/dist/esm/encrypt.d.ts +14 -5
  62. package/dist/esm/encrypt.js +49 -19
  63. package/dist/esm/encrypt.js.map +3 -3
  64. package/dist/esm/error.d.ts +58 -0
  65. package/dist/esm/error.js +155 -0
  66. package/dist/esm/error.js.map +7 -0
  67. package/dist/esm/ibe.d.ts +13 -17
  68. package/dist/esm/ibe.js +25 -28
  69. package/dist/esm/ibe.js.map +2 -2
  70. package/dist/esm/index.d.ts +3 -5
  71. package/dist/esm/index.js +5 -16
  72. package/dist/esm/index.js.map +2 -2
  73. package/dist/esm/kdf.d.ts +7 -2
  74. package/dist/esm/kdf.js +37 -2
  75. package/dist/esm/kdf.js.map +3 -3
  76. package/dist/esm/key-server.d.ts +5 -5
  77. package/dist/esm/key-server.js +29 -21
  78. package/dist/esm/key-server.js.map +2 -2
  79. package/dist/esm/keys.d.ts +17 -0
  80. package/dist/esm/keys.js +41 -0
  81. package/dist/esm/keys.js.map +7 -0
  82. package/dist/esm/session-key.d.ts +20 -14
  83. package/dist/esm/session-key.js +95 -24
  84. package/dist/esm/session-key.js.map +2 -2
  85. package/dist/esm/types.d.ts +1 -86
  86. package/dist/esm/types.js +0 -28
  87. package/dist/esm/types.js.map +3 -3
  88. package/dist/esm/utils.d.ts +2 -1
  89. package/dist/esm/utils.js +17 -5
  90. package/dist/esm/utils.js.map +2 -2
  91. package/dist/esm/version.d.ts +1 -0
  92. package/dist/esm/version.js +5 -0
  93. package/dist/esm/version.js.map +7 -0
  94. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  95. package/dist/tsconfig.tsbuildinfo +1 -1
  96. package/package.json +6 -5
  97. package/dist/cjs/aes.d.ts +0 -18
  98. package/dist/cjs/aes.js +0 -111
  99. package/dist/cjs/aes.js.map +0 -7
  100. package/dist/cjs/key-store.d.ts +0 -49
  101. package/dist/cjs/key-store.js +0 -203
  102. package/dist/cjs/key-store.js.map +0 -7
  103. package/dist/esm/aes.d.ts +0 -18
  104. package/dist/esm/aes.js +0 -91
  105. package/dist/esm/aes.js.map +0 -7
  106. package/dist/esm/key-store.d.ts +0 -49
  107. package/dist/esm/key-store.js +0 -183
  108. package/dist/esm/key-store.js.map +0 -7
@@ -1,26 +1,26 @@
1
- import { fromBase64, fromHex, toHex } from "@mysten/bcs";
2
- import { bcs } from "@mysten/sui/bcs";
1
+ import { fromBase64, fromHex } from "@mysten/bcs";
3
2
  import { bls12_381 } from "@noble/curves/bls12-381";
3
+ import { KeyServerMove } from "./bcs.js";
4
+ import {
5
+ InvalidGetObjectError,
6
+ SealAPIError,
7
+ UnsupportedFeatureError,
8
+ UnsupportedNetworkError
9
+ } from "./error.js";
4
10
  import { DST_POP } from "./ibe.js";
11
+ import { PACKAGE_VERSION } from "./version.js";
5
12
  var KeyServerType = /* @__PURE__ */ ((KeyServerType2) => {
6
13
  KeyServerType2[KeyServerType2["BonehFranklinBLS12381"] = 0] = "BonehFranklinBLS12381";
7
14
  return KeyServerType2;
8
15
  })(KeyServerType || {});
9
- const KeyServerMove = bcs.struct("KeyServer", {
10
- id: bcs.Address,
11
- name: bcs.string(),
12
- url: bcs.string(),
13
- key_type: bcs.u8(),
14
- pk: bcs.vector(bcs.u8())
15
- });
16
16
  function getAllowlistedKeyServers(network) {
17
17
  if (network === "testnet") {
18
18
  return [
19
- fromHex("0xb35a7228d8cf224ad1e828c0217c95a5153bafc2906d6f9c178197dce26fbcf8"),
20
- fromHex("0x2d6cde8a9d9a65bde3b0a346566945a63b4bfb70e9a06c41bdb70807e2502b06")
19
+ "0xb35a7228d8cf224ad1e828c0217c95a5153bafc2906d6f9c178197dce26fbcf8",
20
+ "0x2d6cde8a9d9a65bde3b0a346566945a63b4bfb70e9a06c41bdb70807e2502b06"
21
21
  ];
22
22
  } else {
23
- throw new Error("Network not supported");
23
+ throw new UnsupportedNetworkError(`Unsupported network ${network}`);
24
24
  }
25
25
  }
26
26
  async function retrieveKeyServers({
@@ -30,20 +30,22 @@ async function retrieveKeyServers({
30
30
  return await Promise.all(
31
31
  objectIds.map(async (objectId) => {
32
32
  const res = await client.getObject({
33
- id: toHex(objectId),
33
+ id: objectId,
34
34
  options: {
35
35
  showBcs: true
36
36
  }
37
37
  });
38
38
  if (!res || res.error || !res.data) {
39
- throw new Error(`KeyServer ${objectId} not found; ${res.error}`);
39
+ throw new InvalidGetObjectError(`KeyServer ${objectId} not found; ${res.error}`);
40
40
  }
41
41
  if (!res.data.bcs || !("bcsBytes" in res.data.bcs)) {
42
- throw new Error(`Invalid KeyServer query: ${objectId}, expected object, got package`);
42
+ throw new InvalidGetObjectError(
43
+ `Invalid KeyServer query: ${objectId}, expected object, got package`
44
+ );
43
45
  }
44
46
  let ks = KeyServerMove.parse(fromBase64(res.data.bcs.bcsBytes));
45
- if (ks.key_type !== 0) {
46
- throw new Error("Unsupported key type");
47
+ if (ks.keyType !== 0) {
48
+ throw new UnsupportedFeatureError(`Unsupported key type ${ks.keyType}`);
47
49
  }
48
50
  return {
49
51
  objectId,
@@ -55,18 +57,24 @@ async function retrieveKeyServers({
55
57
  })
56
58
  );
57
59
  }
58
- async function verifyKeyServer(server) {
60
+ async function verifyKeyServer(server, timeout) {
61
+ const requestId = crypto.randomUUID();
59
62
  const response = await fetch(server.url + "/v1/service", {
60
63
  method: "GET",
61
64
  headers: {
62
- "Content-Type": "application/json"
63
- }
65
+ "Content-Type": "application/json",
66
+ "Request-Id": requestId,
67
+ "Client-Sdk-Type": "typescript",
68
+ "Client-Sdk-Version": PACKAGE_VERSION
69
+ },
70
+ signal: AbortSignal.timeout(timeout)
64
71
  });
72
+ await SealAPIError.assertResponse(response, requestId);
65
73
  const serviceResponse = await response.json();
66
74
  if (serviceResponse.service_id !== server.objectId) {
67
75
  return false;
68
76
  }
69
- const fullMsg = new Uint8Array([...DST_POP, ...server.pk, ...server.objectId]);
77
+ const fullMsg = new Uint8Array([...DST_POP, ...server.pk, ...fromHex(server.objectId)]);
70
78
  return bls12_381.verifyShortSignature(fromBase64(serviceResponse.pop), fullMsg, server.pk);
71
79
  }
72
80
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/key-server.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { fromBase64, fromHex, toHex } from '@mysten/bcs';\nimport { bcs } from '@mysten/sui/bcs';\nimport type { SuiClient } from '@mysten/sui/client';\nimport { bls12_381 } from '@noble/curves/bls12-381';\n\nimport { DST_POP } from './ibe.js';\n\nexport type KeyServer = {\n\tobjectId: Uint8Array;\n\tname: string;\n\turl: string;\n\tkeyType: KeyServerType;\n\tpk: Uint8Array;\n};\n\nexport enum KeyServerType {\n\tBonehFranklinBLS12381 = 0,\n}\n\n// The Move struct for the KeyServer object.\nconst KeyServerMove = bcs.struct('KeyServer', {\n\tid: bcs.Address,\n\tname: bcs.string(),\n\turl: bcs.string(),\n\tkey_type: bcs.u8(),\n\tpk: bcs.vector(bcs.u8()),\n});\n\n/**\n * Returns a static list of Seal key server object ids that the dapp can choose to use.\n * @param network - The network to use.\n * @returns The object id's of the key servers.\n */\nexport function getAllowlistedKeyServers(network: 'testnet' | 'mainnet'): Uint8Array[] {\n\tif (network === 'testnet') {\n\t\treturn [\n\t\t\tfromHex('0xb35a7228d8cf224ad1e828c0217c95a5153bafc2906d6f9c178197dce26fbcf8'),\n\t\t\tfromHex('0x2d6cde8a9d9a65bde3b0a346566945a63b4bfb70e9a06c41bdb70807e2502b06'),\n\t\t];\n\t} else {\n\t\tthrow new Error('Network not supported');\n\t}\n}\n\n/**\n * Given a list of key server object IDs, returns a list of SealKeyServer\n * from onchain state containing name, objectId, URL and pk.\n *\n * @param objectIds - The key server object IDs.\n * @param client - The SuiClient to use.\n * @returns - An array of SealKeyServer.\n */\nexport async function retrieveKeyServers({\n\tobjectIds,\n\tclient,\n}: {\n\tobjectIds: Uint8Array[];\n\tclient: SuiClient;\n}): Promise<KeyServer[]> {\n\treturn await Promise.all(\n\t\tobjectIds.map(async (objectId) => {\n\t\t\tconst res = await client.getObject({\n\t\t\t\tid: toHex(objectId),\n\t\t\t\toptions: {\n\t\t\t\t\tshowBcs: true,\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (!res || res.error || !res.data) {\n\t\t\t\tthrow new Error(`KeyServer ${objectId} not found; ${res.error}`);\n\t\t\t}\n\n\t\t\tif (!res.data.bcs || !('bcsBytes' in res.data.bcs)) {\n\t\t\t\tthrow new Error(`Invalid KeyServer query: ${objectId}, expected object, got package`);\n\t\t\t}\n\n\t\t\tlet ks = KeyServerMove.parse(fromBase64(res.data.bcs!.bcsBytes));\n\t\t\tif (ks.key_type !== 0) {\n\t\t\t\tthrow new Error('Unsupported key type');\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tobjectId,\n\t\t\t\tname: ks.name,\n\t\t\t\turl: ks.url,\n\t\t\t\tkeyType: KeyServerType.BonehFranklinBLS12381,\n\t\t\t\tpk: new Uint8Array(ks.pk),\n\t\t\t};\n\t\t}),\n\t);\n}\n\n/**\n * Given a KeyServer, fetch the proof of possesion (PoP) from the URL and verify it\n * against the pubkey. This should be used only rarely when the dapp uses a dynamic\n * set of key servers.\n *\n * @param server - The KeyServer to verify.\n * @returns - True if the key server is valid, false otherwise.\n */\nexport async function verifyKeyServer(server: KeyServer): Promise<boolean> {\n\tconst response = await fetch(server.url! + '/v1/service', {\n\t\tmethod: 'GET',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t},\n\t});\n\tconst serviceResponse = await response.json();\n\n\tif (serviceResponse.service_id !== server.objectId) {\n\t\treturn false;\n\t}\n\tconst fullMsg = new Uint8Array([...DST_POP, ...server.pk, ...server.objectId]);\n\treturn bls12_381.verifyShortSignature(fromBase64(serviceResponse.pop), fullMsg, server.pk);\n}\n"],
5
- "mappings": "AAEA,SAAS,YAAY,SAAS,aAAa;AAC3C,SAAS,WAAW;AAEpB,SAAS,iBAAiB;AAE1B,SAAS,eAAe;AAUjB,IAAK,gBAAL,kBAAKA,mBAAL;AACN,EAAAA,8BAAA,2BAAwB,KAAxB;AADW,SAAAA;AAAA,GAAA;AAKZ,MAAM,gBAAgB,IAAI,OAAO,aAAa;AAAA,EAC7C,IAAI,IAAI;AAAA,EACR,MAAM,IAAI,OAAO;AAAA,EACjB,KAAK,IAAI,OAAO;AAAA,EAChB,UAAU,IAAI,GAAG;AAAA,EACjB,IAAI,IAAI,OAAO,IAAI,GAAG,CAAC;AACxB,CAAC;AAOM,SAAS,yBAAyB,SAA8C;AACtF,MAAI,YAAY,WAAW;AAC1B,WAAO;AAAA,MACN,QAAQ,oEAAoE;AAAA,MAC5E,QAAQ,oEAAoE;AAAA,IAC7E;AAAA,EACD,OAAO;AACN,UAAM,IAAI,MAAM,uBAAuB;AAAA,EACxC;AACD;AAUA,eAAsB,mBAAmB;AAAA,EACxC;AAAA,EACA;AACD,GAGyB;AACxB,SAAO,MAAM,QAAQ;AAAA,IACpB,UAAU,IAAI,OAAO,aAAa;AACjC,YAAM,MAAM,MAAM,OAAO,UAAU;AAAA,QAClC,IAAI,MAAM,QAAQ;AAAA,QAClB,SAAS;AAAA,UACR,SAAS;AAAA,QACV;AAAA,MACD,CAAC;AACD,UAAI,CAAC,OAAO,IAAI,SAAS,CAAC,IAAI,MAAM;AACnC,cAAM,IAAI,MAAM,aAAa,QAAQ,eAAe,IAAI,KAAK,EAAE;AAAA,MAChE;AAEA,UAAI,CAAC,IAAI,KAAK,OAAO,EAAE,cAAc,IAAI,KAAK,MAAM;AACnD,cAAM,IAAI,MAAM,4BAA4B,QAAQ,gCAAgC;AAAA,MACrF;AAEA,UAAI,KAAK,cAAc,MAAM,WAAW,IAAI,KAAK,IAAK,QAAQ,CAAC;AAC/D,UAAI,GAAG,aAAa,GAAG;AACtB,cAAM,IAAI,MAAM,sBAAsB;AAAA,MACvC;AAEA,aAAO;AAAA,QACN;AAAA,QACA,MAAM,GAAG;AAAA,QACT,KAAK,GAAG;AAAA,QACR,SAAS;AAAA,QACT,IAAI,IAAI,WAAW,GAAG,EAAE;AAAA,MACzB;AAAA,IACD,CAAC;AAAA,EACF;AACD;AAUA,eAAsB,gBAAgB,QAAqC;AAC1E,QAAM,WAAW,MAAM,MAAM,OAAO,MAAO,eAAe;AAAA,IACzD,QAAQ;AAAA,IACR,SAAS;AAAA,MACR,gBAAgB;AAAA,IACjB;AAAA,EACD,CAAC;AACD,QAAM,kBAAkB,MAAM,SAAS,KAAK;AAE5C,MAAI,gBAAgB,eAAe,OAAO,UAAU;AACnD,WAAO;AAAA,EACR;AACA,QAAM,UAAU,IAAI,WAAW,CAAC,GAAG,SAAS,GAAG,OAAO,IAAI,GAAG,OAAO,QAAQ,CAAC;AAC7E,SAAO,UAAU,qBAAqB,WAAW,gBAAgB,GAAG,GAAG,SAAS,OAAO,EAAE;AAC1F;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { fromBase64, fromHex } from '@mysten/bcs';\nimport type { SuiClient } from '@mysten/sui/client';\nimport { bls12_381 } from '@noble/curves/bls12-381';\n\nimport { KeyServerMove } from './bcs.js';\nimport {\n\tInvalidGetObjectError,\n\tSealAPIError,\n\tUnsupportedFeatureError,\n\tUnsupportedNetworkError,\n} from './error.js';\nimport { DST_POP } from './ibe.js';\nimport { PACKAGE_VERSION } from './version.js';\n\nexport type KeyServer = {\n\tobjectId: string;\n\tname: string;\n\turl: string;\n\tkeyType: KeyServerType;\n\tpk: Uint8Array;\n};\n\nexport enum KeyServerType {\n\tBonehFranklinBLS12381 = 0,\n}\n\n/**\n * Returns a static list of Seal key server object ids that the dapp can choose to use.\n * @param network - The network to use.\n * @returns The object id's of the key servers.\n */\nexport function getAllowlistedKeyServers(network: 'testnet' | 'mainnet'): string[] {\n\tif (network === 'testnet') {\n\t\treturn [\n\t\t\t'0xb35a7228d8cf224ad1e828c0217c95a5153bafc2906d6f9c178197dce26fbcf8',\n\t\t\t'0x2d6cde8a9d9a65bde3b0a346566945a63b4bfb70e9a06c41bdb70807e2502b06',\n\t\t];\n\t} else {\n\t\tthrow new UnsupportedNetworkError(`Unsupported network ${network}`);\n\t}\n}\n\n/**\n * Given a list of key server object IDs, returns a list of SealKeyServer\n * from onchain state containing name, objectId, URL and pk.\n *\n * @param objectIds - The key server object IDs.\n * @param client - The SuiClient to use.\n * @returns - An array of SealKeyServer.\n */\nexport async function retrieveKeyServers({\n\tobjectIds,\n\tclient,\n}: {\n\tobjectIds: string[];\n\tclient: SuiClient;\n}): Promise<KeyServer[]> {\n\t// todo: do not fetch the same object ID if this is fetched before.\n\treturn await Promise.all(\n\t\tobjectIds.map(async (objectId) => {\n\t\t\tconst res = await client.getObject({\n\t\t\t\tid: objectId,\n\t\t\t\toptions: {\n\t\t\t\t\tshowBcs: true,\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (!res || res.error || !res.data) {\n\t\t\t\tthrow new InvalidGetObjectError(`KeyServer ${objectId} not found; ${res.error}`);\n\t\t\t}\n\n\t\t\tif (!res.data.bcs || !('bcsBytes' in res.data.bcs)) {\n\t\t\t\tthrow new InvalidGetObjectError(\n\t\t\t\t\t`Invalid KeyServer query: ${objectId}, expected object, got package`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet ks = KeyServerMove.parse(fromBase64(res.data.bcs!.bcsBytes));\n\t\t\tif (ks.keyType !== 0) {\n\t\t\t\tthrow new UnsupportedFeatureError(`Unsupported key type ${ks.keyType}`);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tobjectId,\n\t\t\t\tname: ks.name,\n\t\t\t\turl: ks.url,\n\t\t\t\tkeyType: KeyServerType.BonehFranklinBLS12381,\n\t\t\t\tpk: new Uint8Array(ks.pk),\n\t\t\t};\n\t\t}),\n\t);\n}\n\n/**\n * Given a KeyServer, fetch the proof of possession (PoP) from the URL and verify it\n * against the pubkey. This should be used only rarely when the dapp uses a dynamic\n * set of key servers.\n *\n * @param server - The KeyServer to verify.\n * @returns - True if the key server is valid, false otherwise.\n */\nexport async function verifyKeyServer(server: KeyServer, timeout: number): Promise<boolean> {\n\tconst requestId = crypto.randomUUID();\n\tconst response = await fetch(server.url! + '/v1/service', {\n\t\tmethod: 'GET',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\t'Request-Id': requestId,\n\t\t\t'Client-Sdk-Type': 'typescript',\n\t\t\t'Client-Sdk-Version': PACKAGE_VERSION,\n\t\t},\n\t\tsignal: AbortSignal.timeout(timeout),\n\t});\n\n\tawait SealAPIError.assertResponse(response, requestId);\n\tconst serviceResponse = await response.json();\n\n\tif (serviceResponse.service_id !== server.objectId) {\n\t\treturn false;\n\t}\n\tconst fullMsg = new Uint8Array([...DST_POP, ...server.pk, ...fromHex(server.objectId)]);\n\treturn bls12_381.verifyShortSignature(fromBase64(serviceResponse.pop), fullMsg, server.pk);\n}\n"],
5
+ "mappings": "AAEA,SAAS,YAAY,eAAe;AAEpC,SAAS,iBAAiB;AAE1B,SAAS,qBAAqB;AAC9B;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA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AM,WAAW,MAAM,MAAM,OAAO,MAAO,eAAe;AAAA,IACzD,QAAQ;AAAA,IACR,SAAS;AAAA,MACR,gBAAgB;AAAA,MAChB,cAAc;AAAA,MACd,mBAAmB;AAAA,MACnB,sBAAsB;AAAA,IACvB;AAAA,IACA,QAAQ,YAAY,QAAQ,OAAO;AAAA,EACpC,CAAC;AAED,QAAM,aAAa,eAAe,UAAU,SAAS;AACrD,QAAM,kBAAkB,MAAM,SAAS,KAAK;AAE5C,MAAI,gBAAgB,eAAe,OAAO,UAAU;AACnD,WAAO;AAAA,EACR;AACA,QAAM,UAAU,IAAI,WAAW,CAAC,GAAG,SAAS,GAAG,OAAO,IAAI,GAAG,QAAQ,OAAO,QAAQ,CAAC,CAAC;AACtF,SAAO,UAAU,qBAAqB,WAAW,gBAAgB,GAAG,GAAG,SAAS,OAAO,EAAE;AAC1F;",
6
6
  "names": ["KeyServerType"]
7
7
  }
@@ -0,0 +1,17 @@
1
+ import type { Certificate } from './session-key.js';
2
+ /**
3
+ * Helper function to request all keys from URL with requestSig, txBytes, ephemeral pubkey.
4
+ * Then decrypt the Seal key with ephemeral secret key. Returns a list decryption keys with
5
+ * their full IDs.
6
+ *
7
+ * @param url - The URL of the key server.
8
+ * @param requestSig - The Base64 string of request signature.
9
+ * @param txBytes - The transaction bytes.
10
+ * @param encKey - The ephemeral secret key.
11
+ * @param certificate - The certificate.
12
+ * @returns - A list of full ID and the decrypted key.
13
+ */
14
+ export declare function fetchKeysForAllIds(url: string, requestSig: string, txBytes: Uint8Array, encKey: Uint8Array, certificate: Certificate, timeout: number, signal?: AbortSignal): Promise<{
15
+ fullId: string;
16
+ key: Uint8Array;
17
+ }[]>;
@@ -0,0 +1,41 @@
1
+ import { fromBase64, toBase64, toHex } from "@mysten/bcs";
2
+ import { elgamalDecrypt, toPublicKey, toVerificationKey } from "./elgamal.js";
3
+ import { SealAPIError } from "./error.js";
4
+ import { PACKAGE_VERSION } from "./version.js";
5
+ async function fetchKeysForAllIds(url, requestSig, txBytes, encKey, certificate, timeout, signal) {
6
+ const encKeyPk = toPublicKey(encKey);
7
+ const encVerificationKey = toVerificationKey(encKey);
8
+ const body = {
9
+ ptb: toBase64(txBytes.slice(1)),
10
+ // removes the byte of the transaction type version
11
+ enc_key: toBase64(encKeyPk),
12
+ enc_verification_key: toBase64(encVerificationKey),
13
+ request_signature: requestSig,
14
+ // already b64
15
+ certificate
16
+ };
17
+ const timeoutSignal = AbortSignal.timeout(timeout);
18
+ const combinedSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
19
+ const requestId = crypto.randomUUID();
20
+ const response = await fetch(url + "/v1/fetch_key", {
21
+ method: "POST",
22
+ headers: {
23
+ "Content-Type": "application/json",
24
+ "Request-Id": requestId,
25
+ "Client-Sdk-Type": "typescript",
26
+ "Client-Sdk-Version": PACKAGE_VERSION
27
+ },
28
+ body: JSON.stringify(body),
29
+ signal: combinedSignal
30
+ });
31
+ await SealAPIError.assertResponse(response, requestId);
32
+ const resp = await response.json();
33
+ return resp.decryption_keys.map((dk) => ({
34
+ fullId: toHex(new Uint8Array(dk.id)),
35
+ key: elgamalDecrypt(encKey, dk.encrypted_key.map(fromBase64))
36
+ }));
37
+ }
38
+ export {
39
+ fetchKeysForAllIds
40
+ };
41
+ //# sourceMappingURL=keys.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/keys.ts"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromBase64, toBase64, toHex } from '@mysten/bcs';\n\nimport { elgamalDecrypt, toPublicKey, toVerificationKey } from './elgamal.js';\nimport { SealAPIError } from './error.js';\nimport type { Certificate } from './session-key.js';\nimport { PACKAGE_VERSION } from './version.js';\n\n/**\n * Helper function to request all keys from URL with requestSig, txBytes, ephemeral pubkey.\n * Then decrypt the Seal key with ephemeral secret key. Returns a list decryption keys with\n * their full IDs.\n *\n * @param url - The URL of the key server.\n * @param requestSig - The Base64 string of request signature.\n * @param txBytes - The transaction bytes.\n * @param encKey - The ephemeral secret key.\n * @param certificate - The certificate.\n * @returns - A list of full ID and the decrypted key.\n */\nexport async function fetchKeysForAllIds(\n\turl: string,\n\trequestSig: string,\n\ttxBytes: Uint8Array,\n\tencKey: Uint8Array,\n\tcertificate: Certificate,\n\ttimeout: number,\n\tsignal?: AbortSignal,\n): Promise<{ fullId: string; key: Uint8Array }[]> {\n\tconst encKeyPk = toPublicKey(encKey);\n\tconst encVerificationKey = toVerificationKey(encKey);\n\tconst body = {\n\t\tptb: toBase64(txBytes.slice(1)), // removes the byte of the transaction type version\n\t\tenc_key: toBase64(encKeyPk),\n\t\tenc_verification_key: toBase64(encVerificationKey),\n\t\trequest_signature: requestSig, // already b64\n\t\tcertificate,\n\t};\n\n\tconst timeoutSignal = AbortSignal.timeout(timeout);\n\tconst combinedSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;\n\n\tconst requestId = crypto.randomUUID();\n\tconst response = await fetch(url + '/v1/fetch_key', {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\t'Request-Id': requestId,\n\t\t\t'Client-Sdk-Type': 'typescript',\n\t\t\t'Client-Sdk-Version': PACKAGE_VERSION,\n\t\t},\n\t\tbody: JSON.stringify(body),\n\t\tsignal: combinedSignal,\n\t});\n\tawait SealAPIError.assertResponse(response, requestId);\n\n\tconst resp = await response.json();\n\treturn resp.decryption_keys.map((dk: { id: Uint8Array; encrypted_key: [string, string] }) => ({\n\t\tfullId: toHex(new Uint8Array(dk.id)),\n\t\tkey: elgamalDecrypt(encKey, dk.encrypted_key.map(fromBase64) as [Uint8Array, Uint8Array]),\n\t}));\n}\n"],
5
+ "mappings": "AAGA,SAAS,YAAY,UAAU,aAAa;AAE5C,SAAS,gBAAgB,aAAa,yBAAyB;AAC/D,SAAS,oBAAoB;AAE7B,SAAS,uBAAuB;AAchC,eAAsB,mBACrB,KACA,YACA,SACA,QACA,aACA,SACA,QACiD;AACjD,QAAM,WAAW,YAAY,MAAM;AACnC,QAAM,qBAAqB,kBAAkB,MAAM;AACnD,QAAM,OAAO;AAAA,IACZ,KAAK,SAAS,QAAQ,MAAM,CAAC,CAAC;AAAA;AAAA,IAC9B,SAAS,SAAS,QAAQ;AAAA,IAC1B,sBAAsB,SAAS,kBAAkB;AAAA,IACjD,mBAAmB;AAAA;AAAA,IACnB;AAAA,EACD;AAEA,QAAM,gBAAgB,YAAY,QAAQ,OAAO;AACjD,QAAM,iBAAiB,SAAS,YAAY,IAAI,CAAC,QAAQ,aAAa,CAAC,IAAI;AAE3E,QAAM,YAAY,OAAO,WAAW;AACpC,QAAM,WAAW,MAAM,MAAM,MAAM,iBAAiB;AAAA,IACnD,QAAQ;AAAA,IACR,SAAS;AAAA,MACR,gBAAgB;AAAA,MAChB,cAAc;AAAA,MACd,mBAAmB;AAAA,MACnB,sBAAsB;AAAA,IACvB;AAAA,IACA,MAAM,KAAK,UAAU,IAAI;AAAA,IACzB,QAAQ;AAAA,EACT,CAAC;AACD,QAAM,aAAa,eAAe,UAAU,SAAS;AAErD,QAAM,OAAO,MAAM,SAAS,KAAK;AACjC,SAAO,KAAK,gBAAgB,IAAI,CAAC,QAA6D;AAAA,IAC7F,QAAQ,MAAM,IAAI,WAAW,GAAG,EAAE,CAAC;AAAA,IACnC,KAAK,eAAe,QAAQ,GAAG,cAAc,IAAI,UAAU,CAA6B;AAAA,EACzF,EAAE;AACH;",
6
+ "names": []
7
+ }
@@ -1,36 +1,42 @@
1
+ import type { Signer } from '@mysten/sui/cryptography';
1
2
  export declare const RequestFormat: import("@mysten/bcs").BcsType<{
2
3
  ptb: number[];
3
- enc_key: number[];
4
- enc_verification_key: number[];
4
+ encKey: number[];
5
+ encVerificationKey: number[];
5
6
  }, {
6
7
  ptb: Iterable<number> & {
7
8
  length: number;
8
9
  };
9
- enc_key: Iterable<number> & {
10
+ encKey: Iterable<number> & {
10
11
  length: number;
11
12
  };
12
- enc_verification_key: Iterable<number> & {
13
+ encVerificationKey: Iterable<number> & {
13
14
  length: number;
14
15
  };
15
16
  }>;
16
17
  export type Certificate = {
18
+ user: string;
17
19
  session_vk: string;
18
20
  creation_time: number;
19
21
  ttl_min: number;
20
22
  signature: string;
21
23
  };
22
24
  export declare class SessionKey {
23
- private packageId;
24
- private creationTime;
25
- private ttlMin;
26
- private session_key;
27
- private personalMessageSignature;
28
- constructor(packageId: Uint8Array, ttlMin: number);
25
+ #private;
26
+ constructor({ address, packageId, ttlMin, signer, }: {
27
+ address: string;
28
+ packageId: string;
29
+ ttlMin: number;
30
+ signer?: Signer;
31
+ });
32
+ isExpired(): boolean;
33
+ getAddress(): string;
34
+ getPackageId(): string;
29
35
  getPersonalMessage(): Uint8Array;
30
- setPersonalMessageSignature(personalMessageSignature: string): void;
31
- getCertificate(): Certificate;
36
+ setPersonalMessageSignature(personalMessageSignature: string): Promise<void>;
37
+ getCertificate(): Promise<Certificate>;
32
38
  createRequestParams(txBytes: Uint8Array): Promise<{
33
- decryption_key: Uint8Array;
34
- request_signature: string;
39
+ decryptionKey: Uint8Array;
40
+ requestSignature: string;
35
41
  }>;
36
42
  }
@@ -1,51 +1,122 @@
1
- import { toBase64, toHex } from "@mysten/bcs";
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+ var _address, _packageId, _creationTimeMs, _ttlMin, _sessionKey, _personalMessageSignature, _signer;
9
+ import { toBase64 } from "@mysten/bcs";
2
10
  import { bcs } from "@mysten/sui/bcs";
11
+ import { SuiGraphQLClient } from "@mysten/sui/graphql";
3
12
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
13
+ import { isValidSuiAddress, isValidSuiObjectId } from "@mysten/sui/utils";
14
+ import { verifyPersonalMessageSignature } from "@mysten/sui/verify";
4
15
  import { generateSecretKey, toPublicKey, toVerificationKey } from "./elgamal.js";
16
+ import {
17
+ ExpiredSessionKeyError,
18
+ InvalidPersonalMessageSignatureError,
19
+ UserError
20
+ } from "./error.js";
5
21
  const RequestFormat = bcs.struct("RequestFormat", {
6
22
  ptb: bcs.vector(bcs.U8),
7
- enc_key: bcs.vector(bcs.U8),
8
- enc_verification_key: bcs.vector(bcs.U8)
23
+ encKey: bcs.vector(bcs.U8),
24
+ encVerificationKey: bcs.vector(bcs.U8)
9
25
  });
10
26
  class SessionKey {
11
- constructor(packageId, ttlMin) {
12
- this.packageId = packageId;
13
- this.creationTime = Date.now();
14
- this.ttlMin = ttlMin;
15
- this.session_key = Ed25519Keypair.generate();
16
- this.personalMessageSignature = "";
27
+ constructor({
28
+ address,
29
+ packageId,
30
+ ttlMin,
31
+ signer
32
+ }) {
33
+ __privateAdd(this, _address);
34
+ __privateAdd(this, _packageId);
35
+ __privateAdd(this, _creationTimeMs);
36
+ __privateAdd(this, _ttlMin);
37
+ __privateAdd(this, _sessionKey);
38
+ __privateAdd(this, _personalMessageSignature);
39
+ __privateAdd(this, _signer);
40
+ if (!isValidSuiObjectId(packageId) || !isValidSuiAddress(address)) {
41
+ throw new UserError(`Invalid package ID ${packageId} or address ${address}`);
42
+ }
43
+ if (ttlMin > 10 || ttlMin < 1) {
44
+ throw new UserError(`Invalid TTL ${ttlMin}, must be between 1 and 10`);
45
+ }
46
+ __privateSet(this, _address, address);
47
+ __privateSet(this, _packageId, packageId);
48
+ __privateSet(this, _creationTimeMs, Date.now());
49
+ __privateSet(this, _ttlMin, ttlMin);
50
+ __privateSet(this, _sessionKey, Ed25519Keypair.generate());
51
+ __privateSet(this, _signer, signer);
52
+ }
53
+ isExpired() {
54
+ return __privateGet(this, _creationTimeMs) + __privateGet(this, _ttlMin) * 60 * 1e3 - 1e4 < Date.now();
55
+ }
56
+ getAddress() {
57
+ return __privateGet(this, _address);
58
+ }
59
+ getPackageId() {
60
+ return __privateGet(this, _packageId);
17
61
  }
18
62
  getPersonalMessage() {
19
- const message = `Requesting access to keys of package ${toHex(this.packageId)} for ${this.ttlMin} mins, session key ${toBase64(this.session_key.getPublicKey().toRawBytes())}, created at ${this.creationTime}`;
63
+ const creationTimeUtc = new Date(__privateGet(this, _creationTimeMs)).toISOString().slice(0, 19).replace("T", " ") + " UTC";
64
+ const message = `Accessing keys of package ${__privateGet(this, _packageId)} for ${__privateGet(this, _ttlMin)} mins from ${creationTimeUtc}, session key ${toBase64(__privateGet(this, _sessionKey).getPublicKey().toRawBytes())}`;
20
65
  return new TextEncoder().encode(message);
21
66
  }
22
- setPersonalMessageSignature(personalMessageSignature) {
23
- this.personalMessageSignature = personalMessageSignature;
67
+ async setPersonalMessageSignature(personalMessageSignature) {
68
+ try {
69
+ await verifyPersonalMessageSignature(this.getPersonalMessage(), personalMessageSignature, {
70
+ address: __privateGet(this, _address),
71
+ client: new SuiGraphQLClient({
72
+ url: "https://sui-testnet.mystenlabs.com/graphql"
73
+ })
74
+ });
75
+ __privateSet(this, _personalMessageSignature, personalMessageSignature);
76
+ } catch (e) {
77
+ throw new InvalidPersonalMessageSignatureError("Not valid");
78
+ }
24
79
  }
25
- getCertificate() {
26
- if (this.personalMessageSignature === "") {
27
- throw new Error("Personal message signature is not set");
80
+ async getCertificate() {
81
+ if (!__privateGet(this, _personalMessageSignature)) {
82
+ if (__privateGet(this, _signer)) {
83
+ const { signature } = await __privateGet(this, _signer).signPersonalMessage(this.getPersonalMessage());
84
+ __privateSet(this, _personalMessageSignature, signature);
85
+ } else {
86
+ throw new InvalidPersonalMessageSignatureError("Personal message signature is not set");
87
+ }
28
88
  }
29
89
  return {
30
- session_vk: toBase64(this.session_key.getPublicKey().toRawBytes()),
31
- creation_time: this.creationTime,
32
- ttl_min: this.ttlMin,
33
- signature: this.personalMessageSignature
90
+ user: __privateGet(this, _address),
91
+ session_vk: toBase64(__privateGet(this, _sessionKey).getPublicKey().toRawBytes()),
92
+ creation_time: __privateGet(this, _creationTimeMs),
93
+ ttl_min: __privateGet(this, _ttlMin),
94
+ signature: __privateGet(this, _personalMessageSignature)
34
95
  };
35
96
  }
36
97
  async createRequestParams(txBytes) {
37
- let eg_sk = generateSecretKey();
98
+ if (this.isExpired()) {
99
+ throw new ExpiredSessionKeyError();
100
+ }
101
+ const egSk = generateSecretKey();
38
102
  const msgToSign = RequestFormat.serialize({
39
103
  ptb: txBytes.slice(1),
40
- enc_key: toPublicKey(eg_sk),
41
- enc_verification_key: toVerificationKey(eg_sk)
104
+ encKey: toPublicKey(egSk),
105
+ encVerificationKey: toVerificationKey(egSk)
42
106
  }).toBytes();
43
107
  return {
44
- decryption_key: eg_sk,
45
- request_signature: toBase64(await this.session_key.sign(msgToSign))
108
+ decryptionKey: egSk,
109
+ requestSignature: toBase64(await __privateGet(this, _sessionKey).sign(msgToSign))
46
110
  };
47
111
  }
48
112
  }
113
+ _address = new WeakMap();
114
+ _packageId = new WeakMap();
115
+ _creationTimeMs = new WeakMap();
116
+ _ttlMin = new WeakMap();
117
+ _sessionKey = new WeakMap();
118
+ _personalMessageSignature = new WeakMap();
119
+ _signer = new WeakMap();
49
120
  export {
50
121
  RequestFormat,
51
122
  SessionKey
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/session-key.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { toBase64, toHex } from '@mysten/bcs';\nimport { bcs } from '@mysten/sui/bcs';\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\n\nimport { generateSecretKey, toPublicKey, toVerificationKey } from './elgamal.js';\n\nexport const RequestFormat = bcs.struct('RequestFormat', {\n\tptb: bcs.vector(bcs.U8),\n\tenc_key: bcs.vector(bcs.U8),\n\tenc_verification_key: bcs.vector(bcs.U8),\n});\n\nexport type Certificate = {\n\tsession_vk: string;\n\tcreation_time: number;\n\tttl_min: number;\n\tsignature: string;\n};\n\nexport class SessionKey {\n\tprivate packageId: Uint8Array;\n\tprivate creationTime: number;\n\tprivate ttlMin: number;\n\tprivate session_key: Ed25519Keypair;\n\tprivate personalMessageSignature: string;\n\n\tconstructor(packageId: Uint8Array, ttlMin: number) {\n\t\tthis.packageId = packageId;\n\t\tthis.creationTime = Date.now();\n\t\tthis.ttlMin = ttlMin;\n\t\tthis.session_key = Ed25519Keypair.generate();\n\t\tthis.personalMessageSignature = '';\n\t}\n\n\tgetPersonalMessage(): Uint8Array {\n\t\t// TODO: decide if we want 0x on the server end\n\t\tconst message = `Requesting access to keys of package ${toHex(this.packageId)} for ${this.ttlMin} mins, session key ${toBase64(this.session_key.getPublicKey().toRawBytes())}, created at ${this.creationTime}`;\n\t\treturn new TextEncoder().encode(message);\n\t}\n\n\tsetPersonalMessageSignature(personalMessageSignature: string) {\n\t\tthis.personalMessageSignature = personalMessageSignature;\n\t}\n\n\tgetCertificate(): Certificate {\n\t\tif (this.personalMessageSignature === '') {\n\t\t\tthrow new Error('Personal message signature is not set');\n\t\t}\n\t\treturn {\n\t\t\tsession_vk: toBase64(this.session_key.getPublicKey().toRawBytes()),\n\t\t\tcreation_time: this.creationTime,\n\t\t\tttl_min: this.ttlMin,\n\t\t\tsignature: this.personalMessageSignature,\n\t\t};\n\t}\n\n\tasync createRequestParams(\n\t\ttxBytes: Uint8Array,\n\t): Promise<{ decryption_key: Uint8Array; request_signature: string }> {\n\t\tlet eg_sk = generateSecretKey();\n\t\tconst msgToSign = RequestFormat.serialize({\n\t\t\tptb: txBytes.slice(1),\n\t\t\tenc_key: toPublicKey(eg_sk),\n\t\t\tenc_verification_key: toVerificationKey(eg_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U;AAAA,MACzC,KAAK,QAAQ,MAAM,CAAC;AAAA,MACpB,SAAS,YAAY,KAAK;AAAA,MAC1B,sBAAsB,kBAAkB,KAAK;AAAA,IAC9C,CAAC,EAAE,QAAQ;AACX,WAAO;AAAA,MACN,gBAAgB;AAAA,MAChB,mBAAmB,SAAS,MAAM,KAAK,YAAY,KAAK,SAAS,CAAC;AAAA,IACnE;AAAA,EACD;AACD;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { toBase64 } from '@mysten/bcs';\nimport { bcs } from '@mysten/sui/bcs';\nimport type { Signer } from '@mysten/sui/cryptography';\nimport { SuiGraphQLClient } from '@mysten/sui/graphql';\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { isValidSuiAddress, isValidSuiObjectId } from '@mysten/sui/utils';\nimport { verifyPersonalMessageSignature } from '@mysten/sui/verify';\n\nimport { generateSecretKey, toPublicKey, toVerificationKey } from './elgamal.js';\nimport {\n\tExpiredSessionKeyError,\n\tInvalidPersonalMessageSignatureError,\n\tUserError,\n} from './error.js';\n\nexport const RequestFormat = bcs.struct('RequestFormat', {\n\tptb: bcs.vector(bcs.U8),\n\tencKey: bcs.vector(bcs.U8),\n\tencVerificationKey: bcs.vector(bcs.U8),\n});\n\nexport type Certificate = {\n\tuser: string;\n\tsession_vk: string;\n\tcreation_time: number;\n\tttl_min: number;\n\tsignature: string;\n};\n\nexport class SessionKey {\n\t#address: string;\n\t#packageId: string;\n\t#creationTimeMs: number;\n\t#ttlMin: number;\n\t#sessionKey: Ed25519Keypair;\n\t#personalMessageSignature?: string;\n\t#signer?: Signer;\n\n\tconstructor({\n\t\taddress,\n\t\tpackageId,\n\t\tttlMin,\n\t\tsigner,\n\t}: {\n\t\taddress: string;\n\t\tpackageId: string;\n\t\tttlMin: number;\n\t\tsigner?: Signer;\n\t}) {\n\t\tif (!isValidSuiObjectId(packageId) || !isValidSuiAddress(address)) {\n\t\t\tthrow new UserError(`Invalid package ID ${packageId} or address ${address}`);\n\t\t}\n\t\tif (ttlMin > 10 || ttlMin < 1) {\n\t\t\tthrow new UserError(`Invalid TTL ${ttlMin}, must be between 1 and 10`);\n\t\t}\n\n\t\tthis.#address = address;\n\t\tthis.#packageId = packageId;\n\t\tthis.#creationTimeMs = Date.now();\n\t\tthis.#ttlMin = ttlMin;\n\t\tthis.#sessionKey = Ed25519Keypair.generate();\n\t\tthis.#signer = signer;\n\t}\n\n\tisExpired(): boolean {\n\t\t// Allow 10 seconds for clock skew\n\t\treturn this.#creationTimeMs + this.#ttlMin * 60 * 1000 - 10_000 < Date.now();\n\t}\n\n\tgetAddress(): string {\n\t\treturn this.#address;\n\t}\n\n\tgetPackageId(): string {\n\t\treturn this.#packageId;\n\t}\n\n\tgetPersonalMessage(): Uint8Array {\n\t\tconst creationTimeUtc =\n\t\t\tnew Date(this.#creationTimeMs).toISOString().slice(0, 19).replace('T', ' ') + ' UTC';\n\t\tconst message = `Accessing keys of package ${this.#packageId} for ${this.#ttlMin} mins from ${creationTimeUtc}, session key ${toBase64(this.#sessionKey.getPublicKey().toRawBytes())}`;\n\t\treturn new TextEncoder().encode(message);\n\t}\n\n\tasync setPersonalMessageSignature(personalMessageSignature: string) {\n\t\ttry {\n\t\t\t// TODO: Fix this to work with any network\n\t\t\tawait verifyPersonalMessageSignature(this.getPersonalMessage(), personalMessageSignature, {\n\t\t\t\taddress: this.#address,\n\t\t\t\tclient: new SuiGraphQLClient({\n\t\t\t\t\turl: 'https://sui-testnet.mystenlabs.com/graphql',\n\t\t\t\t}),\n\t\t\t});\n\t\t\tthis.#personalMessageSignature = personalMessageSignature;\n\t\t} catch (e) {\n\t\t\tthrow new InvalidPersonalMessageSignatureError('Not valid');\n\t\t}\n\t}\n\n\tasync getCertificate(): Promise<Certificate> {\n\t\tif (!this.#personalMessageSignature) {\n\t\t\tif (this.#signer) {\n\t\t\t\tconst { signature } = await this.#signer.signPersonalMessage(this.getPersonalMessage());\n\t\t\t\tthis.#personalMessageSignature = signature;\n\t\t\t} else {\n\t\t\t\tthrow new InvalidPersonalMessageSignatureError('Personal message signature is not set');\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tuser: this.#address,\n\t\t\tsession_vk: toBase64(this.#sessionKey.getPublicKey().toRawBytes()),\n\t\t\tcreation_time: this.#creationTimeMs,\n\t\t\tttl_min: this.#ttlMin,\n\t\t\tsignature: this.#personalMessageSignature,\n\t\t};\n\t}\n\n\tasync createRequestParams(\n\t\ttxBytes: Uint8Array,\n\t): Promise<{ decryptionKey: Uint8Array; requestSignature: string }> {\n\t\tif (this.isExpired()) {\n\t\t\tthrow new ExpiredSessionKeyError();\n\t\t}\n\t\tconst egSk = generateSecretKey();\n\t\tconst msgToSign = RequestFormat.serialize({\n\t\t\tptb: txBytes.slice(1),\n\t\t\tencKey: toPublicKey(egSk),\n\t\t\tencVerificationKey: toVerificationKey(egSk),\n\t\t}).toBytes();\n\t\treturn {\n\t\t\tdecryptionKey: egSk,\n\t\t\trequestSignature: toBase64(await this.#sessionKey.sign(msgToSign)),\n\t\t};\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;AAAA;AAGA,SAAS,gBAAgB;AACzB,SAAS,WAAW;AAEpB,SAAS,wBAAwB;AACjC,SAAS,sBAAsB;AAC/B,SAAS,mBAAmB,0BAA0B;AACtD,SAAS,sCAAsC;AAE/C,SAAS,mBAAmB,aAAa,yBAAyB;AAClE;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAEA,MAAM,gBAAgB,IAAI,OAAO,iBAAiB;AAAA,EACxD,KAAK,IAAI,OAAO,IAAI,EAAE;AAAA,EACtB,QAAQ,IAAI,OAAO,IAAI,EAAE;AAAA,EACzB,oBAAoB,IAAI,OAAO,IAAI,EAAE;AACtC,CAAC;AAUM,MAAM,WAAW;AAAA,EASvB,YAAY;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD,GAKG;AAlBH;A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EACD;AAAA,EAEA,MAAM,iBAAuC;AAC5C,QAAI,CAAC,mBAAK,4BAA2B;AACpC,UAAI,mBAAK,UAAS;AACjB,cAAM,EAAE,UAAU,IAAI,MAAM,mBAAK,SAAQ,oBAAoB,KAAK,mBAAmB,CAAC;AACtF,2BAAK,2BAA4B;AAAA,MAClC,OAAO;AACN,cAAM,IAAI,qCAAqC,uCAAuC;AAAA,MACvF;AAAA,IACD;AACA,WAAO;AAAA,MACN,MAAM,mBAAK;AAAA,MACX,YAAY,SAAS,mBAAK,aAAY,aAAa,EAAE,WAAW,CAAC;AAAA,MACjE,eAAe,mBAAK;AAAA,MACpB,SAAS,mBAAK;AAAA,MACd,WAAW,mBAAK;AAAA,IACjB;AAAA,EACD;AAAA,EAEA,MAAM,oBACL,SACmE;AACnE,QAAI,KAAK,UAAU,GAAG;AACrB,YAAM,IAAI,uBAAuB;AAAA,IAClC;AACA,UAAM,OAAO,kBAAkB;AAC/B,UAAM,YAAY,cAAc,UAAU;AAAA,MACzC,KAAK,QAAQ,MAAM,CAAC;AAAA,MACpB,QAAQ,YAAY,IAAI;AAAA,MACxB,oBAAoB,kBAAkB,IAAI;AAAA,IAC3C,CAAC,EAAE,QAAQ;AACX,WAAO;AAAA,MACN,eAAe;AAAA,MACf,kBAAkB,SAAS,MAAM,mBAAK,aAAY,KAAK,SAAS,CAAC;AAAA,IAClE;AAAA,EACD;AACD;AAxGC;AACA;AACA;AACA;AACA;AACA;AACA;",
6
6
  "names": []
7
7
  }
@@ -1,86 +1 @@
1
- export declare const IBEEncryptions: import("@mysten/sui/bcs").BcsType<{
2
- BonehFranklinBLS12381: {
3
- encapsulation: Uint8Array<ArrayBufferLike>;
4
- shares: Uint8Array<ArrayBufferLike>[];
5
- };
6
- $kind: "BonehFranklinBLS12381";
7
- }, {
8
- BonehFranklinBLS12381: {
9
- encapsulation: Iterable<number>;
10
- shares: Iterable<Iterable<number>> & {
11
- length: number;
12
- };
13
- };
14
- }>;
15
- export type IBEEncryptionsType = typeof IBEEncryptions.$inferType;
16
- export declare const Ciphertext: import("@mysten/sui/bcs").BcsType<import("@mysten/bcs").EnumOutputShapeWithKeys<{
17
- Aes256Gcm: {
18
- blob: number[];
19
- aad: number[] | null;
20
- };
21
- Plain: {};
22
- }, "Aes256Gcm" | "Plain">, import("@mysten/bcs").EnumInputShape<{
23
- Aes256Gcm: {
24
- blob: Iterable<number> & {
25
- length: number;
26
- };
27
- aad: (Iterable<number> & {
28
- length: number;
29
- }) | null | undefined;
30
- };
31
- Plain: {};
32
- }>>;
33
- export type CiphertextType = typeof Ciphertext.$inferInput;
34
- /**
35
- * The encrypted object format. Should be aligned with the Rust implementation.
36
- */
37
- export declare const EncryptedObject: import("@mysten/sui/bcs").BcsType<{
38
- version: number;
39
- package_id: Uint8Array<ArrayBufferLike>;
40
- id: number[];
41
- services: [Uint8Array<ArrayBufferLike>, number][];
42
- threshold: number;
43
- encrypted_shares: {
44
- BonehFranklinBLS12381: {
45
- encapsulation: Uint8Array<ArrayBufferLike>;
46
- shares: Uint8Array<ArrayBufferLike>[];
47
- };
48
- $kind: "BonehFranklinBLS12381";
49
- };
50
- ciphertext: import("@mysten/bcs").EnumOutputShapeWithKeys<{
51
- Aes256Gcm: {
52
- blob: number[];
53
- aad: number[] | null;
54
- };
55
- Plain: {};
56
- }, "Aes256Gcm" | "Plain">;
57
- }, {
58
- version: number;
59
- package_id: Iterable<number>;
60
- id: Iterable<number> & {
61
- length: number;
62
- };
63
- services: Iterable<readonly [Iterable<number>, number]> & {
64
- length: number;
65
- };
66
- threshold: number;
67
- encrypted_shares: {
68
- BonehFranklinBLS12381: {
69
- encapsulation: Iterable<number>;
70
- shares: Iterable<Iterable<number>> & {
71
- length: number;
72
- };
73
- };
74
- };
75
- ciphertext: import("@mysten/bcs").EnumInputShape<{
76
- Aes256Gcm: {
77
- blob: Iterable<number> & {
78
- length: number;
79
- };
80
- aad: (Iterable<number> & {
81
- length: number;
82
- }) | null | undefined;
83
- };
84
- Plain: {};
85
- }>;
86
- }>;
1
+ export type KeyCacheKey = `${string}:${string}`;
package/dist/esm/types.js CHANGED
@@ -1,29 +1 @@
1
- import { bcs } from "@mysten/sui/bcs";
2
- const IBEEncryptions = bcs.enum("IBEEncryptions", {
3
- BonehFranklinBLS12381: bcs.struct("BonehFranklinBLS12381", {
4
- encapsulation: bcs.bytes(96),
5
- shares: bcs.vector(bcs.bytes(32))
6
- })
7
- });
8
- const Ciphertext = bcs.enum("Ciphertext", {
9
- Aes256Gcm: bcs.struct("Aes256Gcm", {
10
- blob: bcs.vector(bcs.U8),
11
- aad: bcs.option(bcs.vector(bcs.U8))
12
- }),
13
- Plain: bcs.struct("Plain", {})
14
- });
15
- const EncryptedObject = bcs.struct("EncryptedObject", {
16
- version: bcs.U8,
17
- package_id: bcs.bytes(32),
18
- id: bcs.vector(bcs.U8),
19
- services: bcs.vector(bcs.tuple([bcs.bytes(32), bcs.U8])),
20
- threshold: bcs.U8,
21
- encrypted_shares: IBEEncryptions,
22
- ciphertext: Ciphertext
23
- });
24
- export {
25
- Ciphertext,
26
- EncryptedObject,
27
- IBEEncryptions
28
- };
29
1
  //# sourceMappingURL=types.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../src/types.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { bcs } from '@mysten/sui/bcs';\n\nexport const IBEEncryptions = bcs.enum('IBEEncryptions', {\n\tBonehFranklinBLS12381: bcs.struct('BonehFranklinBLS12381', {\n\t\tencapsulation: bcs.bytes(96),\n\t\tshares: bcs.vector(bcs.bytes(32)),\n\t}),\n});\nexport type IBEEncryptionsType = typeof IBEEncryptions.$inferType;\n\nexport const Ciphertext = bcs.enum('Ciphertext', {\n\tAes256Gcm: bcs.struct('Aes256Gcm', {\n\t\tblob: bcs.vector(bcs.U8),\n\t\taad: bcs.option(bcs.vector(bcs.U8)),\n\t}),\n\tPlain: bcs.struct('Plain', {}),\n});\nexport type CiphertextType = typeof Ciphertext.$inferInput;\n\n/**\n * The encrypted object format. Should be aligned with the Rust implementation.\n */\nexport const EncryptedObject = bcs.struct('EncryptedObject', {\n\tversion: bcs.U8,\n\tpackage_id: bcs.bytes(32),\n\tid: bcs.vector(bcs.U8),\n\tservices: bcs.vector(bcs.tuple([bcs.bytes(32), bcs.U8])),\n\tthreshold: bcs.U8,\n\tencrypted_shares: IBEEncryptions,\n\tciphertext: Ciphertext,\n});\n"],
5
- "mappings": "AAGA,SAAS,WAAW;AAEb,MAAM,iBAAiB,IAAI,KAAK,kBAAkB;AAAA,EACxD,uBAAuB,IAAI,OAAO,yBAAyB;AAAA,IAC1D,eAAe,IAAI,MAAM,EAAE;AAAA,IAC3B,QAAQ,IAAI,OAAO,IAAI,MAAM,EAAE,CAAC;AAAA,EACjC,CAAC;AACF,CAAC;AAGM,MAAM,aAAa,IAAI,KAAK,cAAc;AAAA,EAChD,WAAW,IAAI,OAAO,aAAa;AAAA,IAClC,MAAM,IAAI,OAAO,IAAI,EAAE;AAAA,IACvB,KAAK,IAAI,OAAO,IAAI,OAAO,IAAI,EAAE,CAAC;AAAA,EACnC,CAAC;AAAA,EACD,OAAO,IAAI,OAAO,SAAS,CAAC,CAAC;AAC9B,CAAC;AAMM,MAAM,kBAAkB,IAAI,OAAO,mBAAmB;AAAA,EAC5D,SAAS,IAAI;AAAA,EACb,YAAY,IAAI,MAAM,EAAE;AAAA,EACxB,IAAI,IAAI,OAAO,IAAI,EAAE;AAAA,EACrB,UAAU,IAAI,OAAO,IAAI,MAAM,CAAC,IAAI,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;AAAA,EACvD,WAAW,IAAI;AAAA,EACf,kBAAkB;AAAA,EAClB,YAAY;AACb,CAAC;",
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,5 @@
1
1
  export declare function xor(a: Uint8Array, b: Uint8Array): Uint8Array;
2
+ export declare function xorUnchecked(a: Uint8Array, b: Uint8Array): Uint8Array;
2
3
  /**
3
4
  * Create a full ID concatenating DST || package ID || inner ID.
4
5
  * @param dst - The domain separation tag.
@@ -6,4 +7,4 @@ export declare function xor(a: Uint8Array, b: Uint8Array): Uint8Array;
6
7
  * @param innerId - The inner ID.
7
8
  * @returns The full ID.
8
9
  */
9
- export declare function createFullId(dst: Uint8Array, packageId: Uint8Array, innerId: Uint8Array): Uint8Array;
10
+ export declare function createFullId(dst: Uint8Array, packageId: string, innerId: string): string;
package/dist/esm/utils.js CHANGED
@@ -1,19 +1,31 @@
1
+ import { fromHex, toHex } from "@mysten/bcs";
2
+ import { isValidSuiObjectId } from "@mysten/sui/utils";
3
+ import { UserError } from "./error.js";
1
4
  function xor(a, b) {
2
5
  if (a.length !== b.length) {
3
6
  throw new Error("Invalid input");
4
7
  }
8
+ return xorUnchecked(a, b);
9
+ }
10
+ function xorUnchecked(a, b) {
5
11
  return a.map((ai, i) => ai ^ b[i]);
6
12
  }
7
13
  function createFullId(dst, packageId, innerId) {
8
- const fullId = new Uint8Array(1 + dst.length + packageId.length + innerId.length);
14
+ if (!isValidSuiObjectId(packageId)) {
15
+ throw new UserError(`Invalid package ID ${packageId}`);
16
+ }
17
+ const packageIdBytes = fromHex(packageId);
18
+ const innerIdBytes = fromHex(innerId);
19
+ const fullId = new Uint8Array(1 + dst.length + packageIdBytes.length + innerIdBytes.length);
9
20
  fullId.set([dst.length], 0);
10
21
  fullId.set(dst, 1);
11
- fullId.set(packageId, 1 + dst.length);
12
- fullId.set(innerId, 1 + dst.length + packageId.length);
13
- return fullId;
22
+ fullId.set(packageIdBytes, 1 + dst.length);
23
+ fullId.set(innerIdBytes, 1 + dst.length + packageIdBytes.length);
24
+ return toHex(fullId);
14
25
  }
15
26
  export {
16
27
  createFullId,
17
- xor
28
+ xor,
29
+ xorUnchecked
18
30
  };
19
31
  //# sourceMappingURL=utils.js.map