@nexys/zk-store 0.1.12 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -98,6 +98,9 @@ function apiError(what, response, error) {
98
98
  return new Error(error?.error ? `${what}: ${error.error}` : `${what}: ${response.status}`);
99
99
  }
100
100
  var vaultToken = null;
101
+ function currentVaultToken() {
102
+ return vaultToken;
103
+ }
101
104
  function vaultAuth() {
102
105
  if (!vaultToken)
103
106
  throw new Error("No vault session");
@@ -541,6 +544,13 @@ var sharePath = (id) => ({ params: { path: { id } }, headers: vaultAuth() });
541
544
  async function ownedShareKey(share, userKey) {
542
545
  return importKey(await unwrapKey(fromBase642(share.wrappedShareKey), userKey));
543
546
  }
547
+ async function shareKeyFor(userKey, tree, shareId) {
548
+ const owned = tree.shares?.[shareId];
549
+ if (owned)
550
+ return ownedShareKey(owned, userKey);
551
+ const joined = tree.sharedWithMe?.[shareId];
552
+ return joined ? joinedShareKey(joined, userKey) : null;
553
+ }
544
554
  async function joinedShareKey(share, userKey) {
545
555
  return importKey(await unwrapKey(fromBase642(share.wrappedShareKey), userKey));
546
556
  }
@@ -551,7 +561,7 @@ function findShare(tree, kind, target) {
551
561
  }
552
562
  return null;
553
563
  }
554
- async function createShare(userKey, kind, target) {
564
+ async function createShare(userKey, kind, target, linkRole = "viewer") {
555
565
  const tree = await loadTree(userKey);
556
566
  const existing = findShare(tree, kind, target);
557
567
  if (existing)
@@ -569,7 +579,8 @@ async function createShare(userKey, kind, target) {
569
579
  linkProof: proof,
570
580
  linkWrappedKey: toBase642(await wrapKey(shareKeyRaw, linkWrap)),
571
581
  manifest: await sealJson(built.manifest, shareKey),
572
- blobIds: built.blobIds
582
+ blobIds: built.blobIds,
583
+ linkRole
573
584
  }
574
585
  }), "Share");
575
586
  const entry = {
@@ -596,7 +607,7 @@ async function openMembers(raw, shareKey) {
596
607
  try {
597
608
  name = new TextDecoder().decode(await decrypt(fromBase642(m.name), shareKey));
598
609
  } catch {}
599
- return { memberId: m.memberId, name, joinedAt: m.joinedAt * 1000 };
610
+ return { memberId: m.memberId, name, joinedAt: m.joinedAt * 1000, role: m.role };
600
611
  }));
601
612
  }
602
613
  async function fetchShare(shareId, shareKey) {
@@ -608,7 +619,9 @@ async function fetchShare(shareId, shareKey) {
608
619
  role: raw.role,
609
620
  manifest: await openJson(raw.manifest, shareKey),
610
621
  members: await openMembers(raw.members, shareKey),
611
- linkActive: raw.linkActive
622
+ linkActive: raw.linkActive,
623
+ linkRole: raw.linkRole,
624
+ canEdit: raw.canEdit
612
625
  };
613
626
  }
614
627
  async function getOwnedShare(userKey, tree, shareId) {
@@ -631,7 +644,14 @@ async function removeMember(shareId, memberId) {
631
644
  headers: vaultAuth()
632
645
  }), "Remove");
633
646
  }
634
- async function resetLink(userKey, shareId) {
647
+ async function setMemberRole(shareId, memberId, role) {
648
+ check(await client.PUT("/share/{id}/members/{member}", {
649
+ params: { path: { id: shareId, member: memberId } },
650
+ headers: vaultAuth(),
651
+ body: { role }
652
+ }), "Change role");
653
+ }
654
+ async function resetLink(userKey, shareId, linkRole) {
635
655
  const tree = await loadTree(userKey);
636
656
  const share = tree.shares[shareId];
637
657
  const shareKeyRaw = await unwrapKey(fromBase642(share.wrappedShareKey), userKey);
@@ -639,7 +659,11 @@ async function resetLink(userKey, shareId) {
639
659
  const { proof, wrapKey: linkWrap } = await linkSecrets(linkKeyRaw);
640
660
  check(await client.PUT("/share/{id}/link", {
641
661
  ...sharePath(shareId),
642
- body: { linkProof: proof, linkWrappedKey: toBase642(await wrapKey(shareKeyRaw, linkWrap)) }
662
+ body: {
663
+ linkProof: proof,
664
+ linkWrappedKey: toBase642(await wrapKey(shareKeyRaw, linkWrap)),
665
+ ...linkRole ? { linkRole } : {}
666
+ }
643
667
  }), "Reset link");
644
668
  const wrappedLinkKey = toBase642(await wrapKey(linkKeyRaw, userKey));
645
669
  await updateTree(userKey, (t) => {
@@ -687,18 +711,23 @@ async function previewLink(shareId, linkKeyRaw) {
687
711
  const result = await client.GET("/share/{id}/link", {
688
712
  params: { path: { id: shareId }, header: { "X-Share-Proof": proof } }
689
713
  });
690
- const { linkWrappedKey, manifest } = result.response.status === 404 ? {} : check(result, "Open link");
714
+ const { linkWrappedKey, manifest, linkRole } = result.response.status === 404 ? {} : check(result, "Open link");
691
715
  if (!linkWrappedKey || !manifest)
692
716
  throw new Error("This link was turned off or replaced by a new one");
693
717
  const shareKeyRaw = await unwrapKey(fromBase642(linkWrappedKey), linkWrap);
694
718
  const shareKey = await importKey(shareKeyRaw);
695
- return { manifest: await openJson(manifest, shareKey), shareKeyRaw, proof };
719
+ return {
720
+ manifest: await openJson(manifest, shareKey),
721
+ shareKeyRaw,
722
+ proof,
723
+ linkRole: linkRole ?? "viewer"
724
+ };
696
725
  }
697
726
  async function joinShare(userKey, shareId, linkKeyRaw, name) {
698
727
  const { manifest, shareKeyRaw, proof } = await previewLink(shareId, linkKeyRaw);
699
728
  const shareKey = await importKey(shareKeyRaw);
700
729
  const sealedName = toBase642(await encrypt(new TextEncoder().encode(name).buffer, shareKey));
701
- const { memberId } = check(await client.POST("/share/{id}/join", {
730
+ const { memberId, role } = check(await client.POST("/share/{id}/join", {
702
731
  ...sharePath(shareId),
703
732
  body: { linkProof: proof, name: sealedName }
704
733
  }), "Join");
@@ -708,7 +737,8 @@ async function joinShare(userKey, shareId, linkKeyRaw, name) {
708
737
  ownerName: manifest.ownerName,
709
738
  wrappedShareKey: toBase642(await wrapKey(shareKeyRaw, userKey)),
710
739
  memberId,
711
- joinedAt: Date.now()
740
+ joinedAt: Date.now(),
741
+ role
712
742
  };
713
743
  await updateTree(userKey, (t) => {
714
744
  t.sharedWithMe = { ...t.sharedWithMe ?? {}, [shareId]: entry };
@@ -729,18 +759,44 @@ async function leaveShare(userKey, shareId, share) {
729
759
  delete t.sharedWithMe?.[shareId];
730
760
  });
731
761
  }
732
- async function downloadSharedFile(shareId, shareKey, uuid, manifest) {
762
+ async function sharedFileKey(shareKey, uuid, manifest) {
733
763
  const file = manifest.files[uuid];
734
764
  if (!file)
735
765
  throw new Error("File not in this share");
736
- const blob = check(await client.GET("/share/{id}/blob/{blob}", {
766
+ return importKey(await unwrapKey(fromBase642(file.wrappedFileKey), shareKey));
767
+ }
768
+ async function downloadSharedFile(shareId, shareKey, uuid, manifest) {
769
+ const fileKey = await sharedFileKey(shareKey, uuid, manifest);
770
+ const result = await client.GET("/share/{id}/blob/{blob}", {
737
771
  params: { path: { id: shareId, blob: `file_${uuid}` } },
738
772
  headers: vaultAuth(),
739
773
  parseAs: "arrayBuffer"
740
- }), "Download");
741
- const fileKey = await importKey(await unwrapKey(fromBase642(file.wrappedFileKey), shareKey));
774
+ });
775
+ const blob = check(result, "Download");
742
776
  const data = await decrypt(new Uint8Array(blob), fileKey);
743
- return { name: file.name, data };
777
+ return { name: manifest.files[uuid].name, data, etag: result.response.headers.get("ETag") ?? "" };
778
+ }
779
+ async function saveSharedFile(shareId, shareKey, uuid, manifest, data, etag) {
780
+ const fileKey = await sharedFileKey(shareKey, uuid, manifest);
781
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
782
+ const ciphertext = await encrypt(bytes.slice().buffer, fileKey);
783
+ const { error, response } = await client.PUT("/share/{id}/blob/{blob}", {
784
+ params: { path: { id: shareId, blob: `file_${uuid}` }, header: { "If-Match": etag } },
785
+ headers: { ...vaultAuth(), "Content-Type": "application/octet-stream" },
786
+ body: ciphertext,
787
+ bodySerializer: (b) => b
788
+ });
789
+ if (response.status === 412)
790
+ throw new ConflictError;
791
+ if (response.status === 403) {
792
+ const message = error?.error ?? "";
793
+ if (message.includes("only view"))
794
+ throw new Error("You can only view this share");
795
+ throw new AccessRemovedError;
796
+ }
797
+ if (!response.ok)
798
+ throw new Error(error?.error ?? `Save failed: ${response.status}`);
799
+ return response.headers.get("ETag") ?? "";
744
800
  }
745
801
  async function rewrapShareKeys(tree, oldKey, newKey) {
746
802
  const rewrap = async (b64) => toBase642(await wrapKey(await unwrapKey(fromBase642(b64), oldKey), newKey));
@@ -968,9 +1024,276 @@ async function connectAnswerUrl(request, answer) {
968
1024
  url.hash = ANSWER_PREFIX.slice(1) + encodeJson(body);
969
1025
  return url.toString();
970
1026
  }
1027
+ // src/live.ts
1028
+ var KEY_INFO = "zk-live-v1";
1029
+ var CHANNEL_INFO = "zk-live-channel-v1";
1030
+ var SALT2 = new TextEncoder().encode("zk-store-live");
1031
+ async function hkdfBits(key, info) {
1032
+ const raw = await crypto.subtle.exportKey("raw", key);
1033
+ const base = await crypto.subtle.importKey("raw", raw, "HKDF", false, ["deriveBits"]);
1034
+ return crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: SALT2, info: new TextEncoder().encode(info) }, base, 256);
1035
+ }
1036
+ async function liveChannelKeys(scopeKey, channel) {
1037
+ const key = await crypto.subtle.importKey("raw", await hkdfBits(scopeKey, KEY_INFO), "AES-GCM", false, [
1038
+ "encrypt",
1039
+ "decrypt"
1040
+ ]);
1041
+ const mac = await crypto.subtle.importKey("raw", await hkdfBits(scopeKey, CHANNEL_INFO), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
1042
+ const digest = new Uint8Array(await crypto.subtle.sign("HMAC", mac, new TextEncoder().encode(channel)));
1043
+ const channelId = toBase642(digest.slice(0, 16)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1044
+ return { key, channelId };
1045
+ }
1046
+ var opCounter = 0;
1047
+ var newOpId = () => `${Date.now().toString(36)}-${(opCounter++).toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
1048
+
1049
+ class LiveChannel {
1050
+ scope;
1051
+ options;
1052
+ self = null;
1053
+ role = null;
1054
+ status = "connecting";
1055
+ peers = [];
1056
+ ws = null;
1057
+ keys;
1058
+ token;
1059
+ unacked = [];
1060
+ seq = 0;
1061
+ replayUntil = 0;
1062
+ resendDue = false;
1063
+ epoch = null;
1064
+ retries = 0;
1065
+ retryTimer = null;
1066
+ pingTimer = null;
1067
+ queue = Promise.resolve();
1068
+ stopped = false;
1069
+ constructor(scope, options) {
1070
+ this.scope = scope;
1071
+ this.options = options;
1072
+ this.keys = liveChannelKeys(scope.key, options.channel);
1073
+ this.token = options.token ?? currentVaultToken();
1074
+ this.connect();
1075
+ }
1076
+ send(op) {
1077
+ const id = newOpId();
1078
+ const entry = { id, data: "" };
1079
+ this.unacked.push(entry);
1080
+ this.queueOut(async () => {
1081
+ entry.data = await this.seal(op);
1082
+ if (this.status === "live" && !this.resendDue)
1083
+ this.raw({ type: "op", id, data: entry.data });
1084
+ });
1085
+ return id;
1086
+ }
1087
+ signal(signal, to) {
1088
+ this.queueOut(async () => {
1089
+ if (this.status !== "live")
1090
+ return;
1091
+ this.raw({ type: "signal", data: await this.seal(signal), ...to ? { to } : {} });
1092
+ });
1093
+ }
1094
+ pending() {
1095
+ return this.unacked.map((u) => u.id);
1096
+ }
1097
+ close() {
1098
+ this.stop("closed");
1099
+ }
1100
+ outQueue = Promise.resolve();
1101
+ queueOut(work) {
1102
+ this.outQueue = this.outQueue.then(work).catch(() => {});
1103
+ }
1104
+ url(channelId) {
1105
+ const base = (this.options.baseUrl ?? getBaseUrl()).replace(/\/+$/, "").replace(/^http/, "ws");
1106
+ const path = "share" in this.scope ? `/share/${encodeURIComponent(this.scope.share)}/live` : "/vault/live";
1107
+ return `${base}${path}?channel=${channelId}`;
1108
+ }
1109
+ currentToken() {
1110
+ return typeof this.token === "function" ? this.token() : this.token;
1111
+ }
1112
+ async connect() {
1113
+ if (this.stopped)
1114
+ return;
1115
+ this.setStatus(this.retries ? "offline" : "connecting");
1116
+ const { channelId } = await this.keys;
1117
+ if (this.stopped)
1118
+ return;
1119
+ const token = this.currentToken();
1120
+ if (!token)
1121
+ return this.stop("unauthorized");
1122
+ const WS = this.options.WebSocket ?? globalThis.WebSocket;
1123
+ let ws;
1124
+ try {
1125
+ ws = new WS(this.url(channelId));
1126
+ } catch {
1127
+ return this.retry();
1128
+ }
1129
+ this.ws = ws;
1130
+ ws.onopen = () => {
1131
+ ws.send(JSON.stringify({
1132
+ type: "auth",
1133
+ token,
1134
+ ...this.epoch ? { since: this.seq, epoch: this.epoch } : {}
1135
+ }));
1136
+ };
1137
+ ws.onmessage = (e) => {
1138
+ const text = typeof e.data === "string" ? e.data : "";
1139
+ this.queue = this.queue.then(() => this.receive(ws, text)).catch(() => {});
1140
+ };
1141
+ ws.onclose = () => {
1142
+ if (this.ws !== ws)
1143
+ return;
1144
+ this.ws = null;
1145
+ this.clearPing();
1146
+ if (!this.stopped)
1147
+ this.retry();
1148
+ };
1149
+ ws.onerror = () => {};
1150
+ }
1151
+ retry() {
1152
+ if (this.stopped)
1153
+ return;
1154
+ this.setStatus("offline");
1155
+ const delay = Math.min(15000, 500 * 2 ** this.retries++) * (0.75 + Math.random() / 2);
1156
+ this.retryTimer = setTimeout(() => void this.connect(), delay);
1157
+ }
1158
+ stop(status) {
1159
+ this.stopped = true;
1160
+ if (this.retryTimer)
1161
+ clearTimeout(this.retryTimer);
1162
+ this.clearPing();
1163
+ const ws = this.ws;
1164
+ this.ws = null;
1165
+ try {
1166
+ ws?.close();
1167
+ } catch {}
1168
+ this.setStatus(status);
1169
+ }
1170
+ clearPing() {
1171
+ if (this.pingTimer)
1172
+ clearInterval(this.pingTimer);
1173
+ this.pingTimer = null;
1174
+ }
1175
+ setStatus(status) {
1176
+ if (this.status === status)
1177
+ return;
1178
+ this.status = status;
1179
+ this.options.onStatus?.(status);
1180
+ }
1181
+ raw(msg) {
1182
+ if (this.ws && this.ws.readyState === 1)
1183
+ this.ws.send(JSON.stringify(msg));
1184
+ }
1185
+ resendIfCaughtUp() {
1186
+ if (!this.resendDue || this.seq < this.replayUntil)
1187
+ return;
1188
+ this.resendDue = false;
1189
+ this.queueOut(async () => {
1190
+ for (const u of this.unacked)
1191
+ if (u.data)
1192
+ this.raw({ type: "op", id: u.id, data: u.data });
1193
+ });
1194
+ }
1195
+ setPeers(peers) {
1196
+ this.peers = peers;
1197
+ this.options.onPeers?.(peers);
1198
+ }
1199
+ async receive(ws, text) {
1200
+ if (ws !== this.ws)
1201
+ return;
1202
+ let msg;
1203
+ try {
1204
+ msg = JSON.parse(text);
1205
+ } catch {
1206
+ return;
1207
+ }
1208
+ switch (msg.type) {
1209
+ case "welcome": {
1210
+ const resumed = this.epoch === msg.epoch;
1211
+ this.self = msg.peer;
1212
+ this.role = msg.role;
1213
+ this.epoch = msg.epoch;
1214
+ if (!resumed)
1215
+ this.seq = 0;
1216
+ this.retries = 0;
1217
+ this.setPeers(msg.peers ?? []);
1218
+ if (msg.gap)
1219
+ this.options.onGap?.();
1220
+ this.setStatus("live");
1221
+ this.clearPing();
1222
+ this.pingTimer = setInterval(() => this.raw({ type: "ping" }), 25000);
1223
+ this.replayUntil = msg.seq;
1224
+ this.resendDue = true;
1225
+ this.resendIfCaughtUp();
1226
+ return;
1227
+ }
1228
+ case "op": {
1229
+ if (msg.seq <= this.seq)
1230
+ return;
1231
+ const caughtUp = msg.seq;
1232
+ const mine = msg.from === this.self || this.unacked.some((u) => u.id === msg.id);
1233
+ if (mine)
1234
+ this.unacked = this.unacked.filter((u) => u.id !== msg.id);
1235
+ let op;
1236
+ try {
1237
+ op = await this.open(msg.data);
1238
+ } catch {
1239
+ this.seq = caughtUp;
1240
+ this.resendIfCaughtUp();
1241
+ return;
1242
+ }
1243
+ this.seq = caughtUp;
1244
+ this.options.onOp?.(op, {
1245
+ seq: msg.seq,
1246
+ from: msg.from,
1247
+ mine,
1248
+ id: msg.id ?? null,
1249
+ replayed: msg.seq <= this.replayUntil
1250
+ });
1251
+ this.resendIfCaughtUp();
1252
+ return;
1253
+ }
1254
+ case "signal": {
1255
+ try {
1256
+ this.options.onSignal?.(await this.open(msg.data), { from: msg.from });
1257
+ } catch {}
1258
+ return;
1259
+ }
1260
+ case "peer-joined":
1261
+ case "peer-role":
1262
+ this.setPeers([...this.peers.filter((p) => p.peer !== msg.peer), { peer: msg.peer, role: msg.role }]);
1263
+ if (msg.type === "peer-role" && msg.peer === this.self)
1264
+ this.role = msg.role;
1265
+ return;
1266
+ case "peer-left":
1267
+ this.setPeers(this.peers.filter((p) => p.peer !== msg.peer));
1268
+ return;
1269
+ case "revoked":
1270
+ return this.stop("revoked");
1271
+ case "error":
1272
+ if (msg.code === "unauthorized" || msg.code === "forbidden")
1273
+ return this.stop(msg.code === "forbidden" ? "revoked" : "unauthorized");
1274
+ if (msg.code === "read_only") {
1275
+ this.unacked = [];
1276
+ }
1277
+ return;
1278
+ }
1279
+ }
1280
+ async seal(value) {
1281
+ const { key } = await this.keys;
1282
+ const bytes = new TextEncoder().encode(JSON.stringify(value));
1283
+ return toBase642(await encrypt(bytes.buffer, key));
1284
+ }
1285
+ async open(data) {
1286
+ const { key } = await this.keys;
1287
+ return JSON.parse(new TextDecoder().decode(await decrypt(fromBase642(data), key)));
1288
+ }
1289
+ }
1290
+ function openLiveChannel(scope, options) {
1291
+ return new LiveChannel(scope, options);
1292
+ }
971
1293
  export {
972
1294
  AccessRemovedError,
973
1295
  ConflictError,
1296
+ LiveChannel,
974
1297
  PRF_SALT,
975
1298
  RollbackError,
976
1299
  Vault,
@@ -990,6 +1313,7 @@ export {
990
1313
  createShare,
991
1314
  createTree,
992
1315
  createVault,
1316
+ currentVaultToken,
993
1317
  decrypt,
994
1318
  deleteBlob,
995
1319
  deleteRecoveryBlob,
@@ -1022,13 +1346,16 @@ export {
1022
1346
  joinShare,
1023
1347
  joinedShareKey,
1024
1348
  leaveShare,
1349
+ liveChannelKeys,
1025
1350
  loadFileList,
1026
1351
  loadTree,
1027
1352
  memberCounts,
1028
1353
  normalizeRecoveryKey2 as normalizeRecoveryKey,
1029
1354
  normalizeRecoveryPhrase,
1030
1355
  openJoinedShare,
1356
+ openLiveChannel,
1031
1357
  openVault,
1358
+ ownedShareKey,
1032
1359
  ownedShareUrl,
1033
1360
  parseConnectHash,
1034
1361
  parseShareHash,
@@ -1042,7 +1369,10 @@ export {
1042
1369
  revokeCredential,
1043
1370
  rewrapShareKeys,
1044
1371
  rotateVault,
1372
+ saveSharedFile,
1373
+ setMemberRole,
1045
1374
  setWrappedKey,
1375
+ shareKeyFor,
1046
1376
  shareUrl,
1047
1377
  signInWithZkStore,
1048
1378
  stopSharing,
@@ -1057,5 +1387,5 @@ export {
1057
1387
  wrapKey
1058
1388
  };
1059
1389
 
1060
- //# debugId=EA214C11CE99C4ED64756E2164756E21
1390
+ //# debugId=466B0D2268E5678964756E2164756E21
1061
1391
  //# sourceMappingURL=index.js.map