@arbidocs/sdk 0.5.68 → 0.5.70

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.cjs CHANGED
@@ -6022,16 +6022,40 @@ async function updateDocuments(arbi, documents) {
6022
6022
  "Failed to update documents"
6023
6023
  );
6024
6024
  }
6025
- async function uploadUrl(arbi, urls, shared = false, configExtId) {
6026
- return requireData(
6025
+ async function uploadUrl(arbi, urls, options) {
6026
+ return requireUploadData(
6027
6027
  await arbi.fetch.POST("/v1/document/upload-url", {
6028
6028
  params: {
6029
- query: { urls, shared, ...configExtId ? { config_ext_id: configExtId } : {} }
6029
+ query: {
6030
+ urls,
6031
+ shared: options.shared ?? false,
6032
+ workspace_ext_id: options.workspaceExtId,
6033
+ ...options.configExtId ? { config_ext_id: options.configExtId } : {}
6034
+ }
6030
6035
  }
6031
6036
  }),
6032
6037
  "Failed to upload from URLs"
6033
6038
  );
6034
6039
  }
6040
+ var UPLOAD_WORKSPACE_CONFLICT_MESSAGES = {
6041
+ workspace_mismatch: "These files were prepared for another workspace, so they were not saved. Upload them again.",
6042
+ workspace_key_required: "The workspace couldn't be unlocked for this upload, so the files were not saved."
6043
+ };
6044
+ function requireUploadData(result, message) {
6045
+ const status = result.response?.status;
6046
+ const conflict = result.error && status === 409 ? workspaceConflictOf(result.error) : null;
6047
+ if (conflict) {
6048
+ throw new ArbiApiError(
6049
+ UPLOAD_WORKSPACE_CONFLICT_MESSAGES[conflict.code],
6050
+ result.error,
6051
+ status,
6052
+ {
6053
+ code: conflict.code
6054
+ }
6055
+ );
6056
+ }
6057
+ return requireData(result, message);
6058
+ }
6035
6059
  async function uploadDocuments(arbi, files, options = {}) {
6036
6060
  const query2 = {};
6037
6061
  if (options.shared !== void 0) query2.shared = options.shared;
@@ -6056,7 +6080,7 @@ async function uploadDocuments(arbi, files, options = {}) {
6056
6080
  return form;
6057
6081
  }
6058
6082
  });
6059
- return requireData(result, "Failed to upload documents");
6083
+ return requireUploadData(result, "Failed to upload documents");
6060
6084
  }
6061
6085
  async function similarDocuments(arbi, options = {}) {
6062
6086
  return requireData(
@@ -6213,6 +6237,9 @@ async function presignedPut(url, body, onProgress, headers) {
6213
6237
  }
6214
6238
  }
6215
6239
  async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6240
+ if (!options?.workspaceExtId) {
6241
+ throw new ArbiError("uploadDocumentsDirect needs options.workspaceExtId (the key's workspace)");
6242
+ }
6216
6243
  if (files.length === 0) return { doc_ext_ids: [], skipped: [] };
6217
6244
  const SECRETBOX_ENVELOPE_OVERHEAD = 40;
6218
6245
  const declared = files.map((f2) => ({
@@ -6224,21 +6251,19 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6224
6251
  }));
6225
6252
  const initBody = {
6226
6253
  files: declared,
6227
- shared: options?.shared !== false,
6228
- config_ext_id: options?.configExtId ?? null,
6254
+ shared: options.shared !== false,
6255
+ config_ext_id: options.configExtId ?? null,
6229
6256
  // Only sent when set, so a plain upload is accepted by any server version.
6230
- ...options?.versionOf ? { version_of: options.versionOf } : {},
6231
- wp_type: options?.wpType ?? null,
6232
- tag_ext_id: options?.tagExtId ?? null,
6233
- folder: options?.folder ? sanitizeFolderPath(options.folder) : null,
6234
- presign_expires_in: options?.presignExpiresIn ?? 3600
6257
+ ...options.versionOf ? { version_of: options.versionOf } : {},
6258
+ wp_type: options.wpType ?? null,
6259
+ tag_ext_id: options.tagExtId ?? null,
6260
+ folder: options.folder ? sanitizeFolderPath(options.folder) : null,
6261
+ presign_expires_in: options.presignExpiresIn ?? 3600
6235
6262
  };
6236
- const guarded = options?.inWorkspace ?? ((send) => send());
6237
- const initResult = await guarded(
6238
- async () => requireData(
6239
- await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
6240
- "Failed to initialize direct upload"
6241
- )
6263
+ const query2 = { workspace_ext_id: options.workspaceExtId };
6264
+ const initResult = requireUploadData(
6265
+ await arbi.fetch.POST("/v1/document/upload-init", { params: { query: query2 }, body: initBody }),
6266
+ "Failed to initialize direct upload"
6242
6267
  );
6243
6268
  const items = initResult.items ?? [];
6244
6269
  const bytesByName = /* @__PURE__ */ new Map();
@@ -6272,7 +6297,7 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6272
6297
  const total = ciphertext.length;
6273
6298
  try {
6274
6299
  await presignedPut(item.upload_url, ciphertext, (loaded, putTotal) => {
6275
- options?.onBytesProgress?.({
6300
+ options.onBytesProgress?.({
6276
6301
  fileIndex,
6277
6302
  fileName: item.file_name,
6278
6303
  loaded,
@@ -6284,7 +6309,7 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6284
6309
  `Presigned PUT for ${item.doc_ext_id} failed: ${err instanceof Error ? err.message : String(err)}`
6285
6310
  );
6286
6311
  }
6287
- options?.onBytesProgress?.({
6312
+ options.onBytesProgress?.({
6288
6313
  fileIndex,
6289
6314
  fileName: item.file_name,
6290
6315
  loaded: total,
@@ -6295,16 +6320,15 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6295
6320
  if (toCommit.length === 0) {
6296
6321
  return { doc_ext_ids: [], skipped };
6297
6322
  }
6298
- const commitResult = await guarded(
6299
- async () => requireData(
6300
- await arbi.fetch.POST("/v1/document/upload-commit", {
6301
- body: {
6302
- doc_ext_ids: toCommit,
6303
- tag_ext_id: options?.tagExtId ?? null
6304
- }
6305
- }),
6306
- "Failed to commit direct upload"
6307
- )
6323
+ const commitResult = requireUploadData(
6324
+ await arbi.fetch.POST("/v1/document/upload-commit", {
6325
+ params: { query: query2 },
6326
+ body: {
6327
+ doc_ext_ids: toCommit,
6328
+ tag_ext_id: options.tagExtId ?? null
6329
+ }
6330
+ }),
6331
+ "Failed to commit direct upload"
6308
6332
  );
6309
6333
  return {
6310
6334
  doc_ext_ids: commitResult.doc_ext_ids ?? [],
@@ -6552,6 +6576,130 @@ async function unlockModelConnections(arbi, keys, onlyId) {
6552
6576
  }
6553
6577
  }
6554
6578
 
6579
+ // src/operations/secure-mail.ts
6580
+ var secure_mail_exports = {};
6581
+ __export(secure_mail_exports, {
6582
+ claimSecureMail: () => claimSecureMail,
6583
+ prepareSecureMail: () => prepareSecureMail,
6584
+ secureMime: () => secureMime
6585
+ });
6586
+ var MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
6587
+ var utf8 = new TextEncoder();
6588
+ var encodedWord = (value) => `=?UTF-8?B?${client.bytesToBase64(utf8.encode(value))}?=`;
6589
+ var folded = (value) => value.match(/.{1,76}/g)?.join("\r\n") ?? "";
6590
+ var safeHeader = (value) => {
6591
+ if (/[\r\n\0]/.test(value)) throw new Error("Email headers cannot contain newlines");
6592
+ return value;
6593
+ };
6594
+ function secureMime(compose, sender) {
6595
+ const address = (r2) => `${r2.name ? encodedWord(safeHeader(r2.name)) + " " : ""}<${safeHeader(r2.email)}>`;
6596
+ const boundary = "arbi-" + crypto.randomUUID();
6597
+ const headers = [
6598
+ `From: ${address({ email: sender.email, name: sender.display_name })}`,
6599
+ ...compose.to.length ? [`To: ${compose.to.map(address).join(", ")}`] : [],
6600
+ ...compose.cc.length ? [`Cc: ${compose.cc.map(address).join(", ")}`] : [],
6601
+ `Subject: ${encodedWord(safeHeader(compose.subject))}`,
6602
+ `Date: ${(/* @__PURE__ */ new Date()).toUTCString()}`,
6603
+ `Message-ID: <${crypto.randomUUID()}@${sender.email.split("@")[1]}>`,
6604
+ ...compose.in_reply_to ? [`In-Reply-To: ${safeHeader(compose.in_reply_to)}`] : [],
6605
+ ...compose.references?.length ? [`References: ${compose.references.map(safeHeader).join(" ")}`] : [],
6606
+ "MIME-Version: 1.0",
6607
+ "X-ARBI-Secure-Delivery: 1",
6608
+ `Content-Type: multipart/mixed; boundary="${boundary}"`
6609
+ ];
6610
+ const alternative = "alternative-" + crypto.randomUUID();
6611
+ const plainPart = `Content-Type: text/plain; charset="utf-8"\r
6612
+ Content-Transfer-Encoding: base64\r
6613
+ \r
6614
+ ${folded(client.bytesToBase64(utf8.encode(compose.text)))}`;
6615
+ const bodyPart = compose.html ? `Content-Type: multipart/alternative; boundary="${alternative}"\r
6616
+ \r
6617
+ --${alternative}\r
6618
+ ${plainPart}\r
6619
+ --${alternative}\r
6620
+ Content-Type: text/html; charset="utf-8"\r
6621
+ Content-Transfer-Encoding: base64\r
6622
+ \r
6623
+ ${folded(client.bytesToBase64(utf8.encode(compose.html)))}\r
6624
+ --${alternative}--\r
6625
+ ` : plainPart;
6626
+ const parts = [
6627
+ `--${boundary}\r
6628
+ ${bodyPart}`,
6629
+ ...compose.attachments.map((a2) => {
6630
+ if (!a2.content_base64) throw new Error("Attachment content is missing");
6631
+ const name = encodeURIComponent(safeHeader(a2.name)).replace(/'/g, "%27");
6632
+ return `--${boundary}\r
6633
+ Content-Type: ${safeHeader(a2.content_type || "application/octet-stream")}\r
6634
+ Content-Disposition: attachment; filename*=UTF-8''${name}\r
6635
+ Content-Transfer-Encoding: base64\r
6636
+ \r
6637
+ ${folded(a2.content_base64)}`;
6638
+ }),
6639
+ `--${boundary}--\r
6640
+ `
6641
+ ];
6642
+ return utf8.encode(headers.join("\r\n") + "\r\n\r\n" + parts.join("\r\n"));
6643
+ }
6644
+ async function prepareSecureMail(compose, sender, { requestId, senderPublicKey, frontendOrigin }) {
6645
+ const raw = secureMime(compose, sender);
6646
+ try {
6647
+ if (raw.length > MAX_MESSAGE_BYTES) throw new Error("Email exceeds the message size limit");
6648
+ const metadata = {
6649
+ secure_delivery: true,
6650
+ id: "",
6651
+ subject: compose.subject,
6652
+ sender: [{ email: sender.email, name: sender.display_name }],
6653
+ to: compose.to,
6654
+ cc: compose.cc,
6655
+ bcc: [],
6656
+ received_at: (/* @__PURE__ */ new Date()).toISOString(),
6657
+ preview: compose.text.slice(0, 220),
6658
+ unread: false,
6659
+ text: "",
6660
+ references: compose.references ?? [],
6661
+ attachments: compose.attachments.map((a2, i2) => ({
6662
+ ...a2,
6663
+ id: String(i2),
6664
+ content_base64: null
6665
+ }))
6666
+ };
6667
+ const recipients = [
6668
+ ...new Set([...compose.to, ...compose.cc, ...compose.bcc].map((r2) => r2.email.toLowerCase()))
6669
+ ];
6670
+ const sealed = await client.sealSecureMail(raw, metadata, senderPublicKey);
6671
+ return {
6672
+ request_id: requestId,
6673
+ draft_id: compose.draft_id,
6674
+ recipients: recipients.map((email) => ({
6675
+ id: crypto.randomUUID(),
6676
+ email,
6677
+ fragment_key: sealed.fragment_key
6678
+ })),
6679
+ ciphertext: sealed.ciphertext,
6680
+ metadata_ciphertext: sealed.metadata_ciphertext,
6681
+ sender_wrapped_key: sealed.sender_wrapped_key,
6682
+ frontend_origin: frontendOrigin
6683
+ };
6684
+ } finally {
6685
+ raw.fill(0);
6686
+ }
6687
+ }
6688
+ async function claimSecureMail(mail, id, fragmentKey, recipientPublicKey) {
6689
+ const key = client.decodeSecureMailKey(fragmentKey);
6690
+ try {
6691
+ const path5 = `/secure/${encodeURIComponent(id)}`;
6692
+ const response = await mail(path5);
6693
+ const { raw } = await client.openSecureMail(await response.json(), key);
6694
+ raw.fill(0);
6695
+ const claim = await client.secureMailClaim(key, recipientPublicKey);
6696
+ const claimed = await mail(`${path5}/claim`, { method: "POST", body: JSON.stringify(claim) });
6697
+ return await claimed.json();
6698
+ } finally {
6699
+ key.fill(0);
6700
+ }
6701
+ }
6702
+
6555
6703
  // src/operations/workspaces.ts
6556
6704
  var workspaces_exports = {};
6557
6705
  __export(workspaces_exports, {
@@ -10210,7 +10358,6 @@ __export(mail_exports, {
10210
10358
  NATIVE_ACCOUNT: () => NATIVE_ACCOUNT,
10211
10359
  attachmentFromBytes: () => attachmentFromBytes,
10212
10360
  claimNativeAlias: () => claimNativeAlias,
10213
- claimSecureMail: () => claimSecureMail,
10214
10361
  createMailFetch: () => createMailFetch,
10215
10362
  downloadAttachment: () => downloadAttachment,
10216
10363
  getMailPolicy: () => getMailPolicy,
@@ -10316,28 +10463,16 @@ async function unlockNativeMail(mail, keys) {
10316
10463
  secretKey.fill(0);
10317
10464
  }
10318
10465
  }
10319
- async function claimSecureMail(mail, id, fragmentKey, recipientPublicKey) {
10320
- const key = client.decodeSecureMailKey(fragmentKey);
10321
- try {
10322
- const path5 = `/secure/${encodeURIComponent(id)}`;
10323
- const { raw } = await client.openSecureMail(await json(mail(path5)), key);
10324
- raw.fill(0);
10325
- const claim = await client.secureMailClaim(key, recipientPublicKey);
10326
- return await json(mail(`${path5}/claim`, { method: "POST", body: JSON.stringify(claim) }));
10327
- } finally {
10328
- key.fill(0);
10329
- }
10330
- }
10331
10466
  function attachmentFromBytes(name, contentType, bytes) {
10332
10467
  return {
10333
10468
  id: "",
10334
10469
  name,
10335
10470
  content_type: contentType,
10336
10471
  size: bytes.length,
10337
- content_base64: bytesToBase643(bytes)
10472
+ content_base64: bytesToBase644(bytes)
10338
10473
  };
10339
10474
  }
10340
- function bytesToBase643(bytes) {
10475
+ function bytesToBase644(bytes) {
10341
10476
  let binary = "";
10342
10477
  for (let i2 = 0; i2 < bytes.length; i2 += 32768) {
10343
10478
  binary += String.fromCharCode(...bytes.subarray(i2, i2 + 32768));
@@ -11799,6 +11934,10 @@ var Arbi = class {
11799
11934
  if (target) await this.openWorkspace(target);
11800
11935
  return target;
11801
11936
  }
11937
+ /** {@link targetWorkspace} for a call that cannot go without one: throws when none is known. */
11938
+ async requireTargetWorkspace(workspaceId) {
11939
+ return await this.targetWorkspace(workspaceId) ?? this.requireWorkspace();
11940
+ }
11802
11941
  /**
11803
11942
  * Make a workspace the CURRENT one: decrypt its key, open it on the server (which makes it the
11804
11943
  * session's active workspace) and record it in the session. This is navigation: only the host's
@@ -12412,20 +12551,23 @@ var Arbi = class {
12412
12551
  finaliseTranslation: (docId) => finaliseTranslation(this.requireClient(), docId),
12413
12552
  delete: (externalIds) => deleteDocuments(this.requireClient(), externalIds),
12414
12553
  update: (documents) => updateDocuments(this.requireClient(), documents),
12415
- uploadUrl: (urls, options) => {
12416
- this.requireWorkspace();
12417
- return uploadUrl(
12418
- this.requireClient(),
12419
- urls,
12420
- options?.shared,
12421
- options?.configExtId
12422
- );
12554
+ /** Make documents from web addresses in the current workspace, or `options.workspaceId`. */
12555
+ uploadUrl: async (urls, options) => {
12556
+ const { workspaceId, ...rest } = options ?? {};
12557
+ return uploadUrl(this.requireClient(), urls, {
12558
+ workspaceExtId: await this.requireTargetWorkspace(workspaceId),
12559
+ ...rest
12560
+ });
12423
12561
  },
12424
12562
  /**
12425
- * Upload files in one request (the open workspace, or `options.workspaceExtId`): folder, tag,
12426
- * sharing, config, a new version of a document.
12563
+ * Upload files in one request into the current workspace, or `options.workspaceExtId`: folder,
12564
+ * tag, sharing, config, a new version of a document. The request names the workspace either
12565
+ * way, so a switch while it is in flight cannot move it.
12427
12566
  */
12428
- upload: (files, options) => uploadDocuments(this.requireClient(), files, options),
12567
+ upload: async (files, options) => uploadDocuments(this.requireClient(), files, {
12568
+ ...options,
12569
+ workspaceExtId: await this.requireTargetWorkspace(options?.workspaceExtId ?? void 0)
12570
+ }),
12429
12571
  /** Near-duplicate pairs at or above `threshold` (or one document's, `docId`). */
12430
12572
  similar: (options) => similarDocuments(this.requireClient(), options),
12431
12573
  /**
@@ -12450,19 +12592,15 @@ var Arbi = class {
12450
12592
  },
12451
12593
  /**
12452
12594
  * Upload files straight to storage, encrypted here with `workspaceKey` (`uploadDocumentsDirect`),
12453
- * into `workspaceId`, which must be the workspace open NOW. `upload-init` and `upload-commit`
12454
- * name no workspace yet (they act on the session's open one), so each runs under
12455
- * `readInWorkspace`: it is not sent, or its answer not kept, unless `workspaceId` is open when
12456
- * it is sent and still when it returns. A switch refuses the upload
12457
- * (`ArbiWorkspaceChangedError`) instead of storing files encrypted with one workspace's key in
12458
- * another. For any other workspace use `upload` with `workspaceExtId`, which names it.
12595
+ * into `workspaceId`, whose key it must be. `upload-init` and `upload-commit` name that
12596
+ * workspace (made usable for this session first, not switched to), so a switch while the
12597
+ * upload runs cannot move the files into another workspace.
12459
12598
  */
12460
- uploadDirect: (workspaceId, workspaceKey, files, options) => {
12461
- if (this.currentWorkspaceId !== workspaceId)
12462
- return Promise.reject(new ArbiWorkspaceChangedError(workspaceId, "uploading to"));
12599
+ uploadDirect: async (workspaceId, workspaceKey, files, options) => {
12600
+ const workspaceExtId = await this.requireTargetWorkspace(workspaceId);
12463
12601
  return uploadDocumentsDirect(this.requireClient(), workspaceKey, files, {
12464
12602
  ...options,
12465
- inWorkspace: (send) => this.readInWorkspace(workspaceId, send)
12603
+ workspaceExtId
12466
12604
  });
12467
12605
  },
12468
12606
  /** Download a document's original file — its current version, or `version`. */
@@ -12619,6 +12757,42 @@ var Arbi = class {
12619
12757
  });
12620
12758
  }
12621
12759
  };
12760
+ // ── Secure mail ─────────────────────────────────────────────────────
12761
+ /**
12762
+ * Mail to anyone, sealed in this browser under a key that travels only in the link's fragment
12763
+ * (see `operations/secure-mail`). Both sides use the signed-in user's encryption key: the
12764
+ * login's, or (a new tab not signed in to the server yet) the one kept on this device.
12765
+ */
12766
+ secureMail = {
12767
+ /**
12768
+ * The `/secure/send` payload for `compose` from `account`, shown with the user's own name.
12769
+ * Links open on `frontendOrigin` (default: this page's origin).
12770
+ */
12771
+ prepare: async (compose, account, requestId, frontendOrigin = globalThis.location?.origin ?? "") => {
12772
+ const user = this.client?.session.getState().user;
12773
+ const name = user ? [user.given_name, user.family_name] : [this.userProfile?.givenName, this.userProfile?.familyName];
12774
+ const senderName = name.filter(Boolean).join(" ");
12775
+ return prepareSecureMail(
12776
+ compose,
12777
+ { ...account, display_name: senderName || account.display_name },
12778
+ { requestId, senderPublicKey: await this.encryptionPublicKey(), frontendOrigin }
12779
+ );
12780
+ },
12781
+ /**
12782
+ * Claim the secure message `id` with the key from its link into the user's native inbox, over
12783
+ * `mail` (default: this session's mail transport). Resolves to the message's id there.
12784
+ */
12785
+ claim: async (id, fragmentKey, mail = this.mail.fetch) => claimSecureMail(mail, id, fragmentKey, await this.encryptionPublicKey())
12786
+ };
12787
+ /** The signed-in user's X25519 public key (from the identity key; its secret half is wiped). */
12788
+ async encryptionPublicKey() {
12789
+ const signingKey = this.loginResult?.signingPrivateKey ?? (await this.client?.storage.getSession().catch(() => null))?.signingPrivateKey;
12790
+ if (!signingKey) throw new ArbiError("Sign in again to unlock your encryption key");
12791
+ await client.initSodium();
12792
+ const pair = client.encryptionKeypairFromSigningKey(signingKey);
12793
+ pair.secretKey.fill(0);
12794
+ return pair.publicKey;
12795
+ }
12622
12796
  async openResponseHandle(open, options, id, bufferEvents = false) {
12623
12797
  const controller = new AbortController();
12624
12798
  const abort = () => controller.abort();
@@ -13829,7 +14003,8 @@ async function runGroupedDirectUpload(arbi, workspaceKey, groups, options) {
13829
14003
  options?.onBatchStart?.(progress);
13830
14004
  const result = await uploadDocumentsDirect(arbi, workspaceKey, group.files, {
13831
14005
  folder: group.folder || void 0,
13832
- configExtId: options?.configExtId
14006
+ configExtId: options.configExtId,
14007
+ workspaceExtId: options.workspaceExtId
13833
14008
  });
13834
14009
  const skipped = result.skipped ?? [];
13835
14010
  allDocIds.push(...result.doc_ext_ids);
@@ -15685,6 +15860,7 @@ exports.resolveSummary = resolveSummary;
15685
15860
  exports.resolveWorkspace = resolveWorkspace;
15686
15861
  exports.responses = responses_exports;
15687
15862
  exports.searchChunks = searchChunks;
15863
+ exports.secureMail = secure_mail_exports;
15688
15864
  exports.selectFullContextDocument = selectFullContextDocument;
15689
15865
  exports.selectWorkspace = selectWorkspace;
15690
15866
  exports.selectWorkspaceById = selectWorkspaceById;