@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/browser.cjs CHANGED
@@ -5480,16 +5480,40 @@ async function updateDocuments(arbi, documents) {
5480
5480
  "Failed to update documents"
5481
5481
  );
5482
5482
  }
5483
- async function uploadUrl(arbi, urls, shared = false, configExtId) {
5484
- return requireData(
5483
+ async function uploadUrl(arbi, urls, options) {
5484
+ return requireUploadData(
5485
5485
  await arbi.fetch.POST("/v1/document/upload-url", {
5486
5486
  params: {
5487
- query: { urls, shared, ...configExtId ? { config_ext_id: configExtId } : {} }
5487
+ query: {
5488
+ urls,
5489
+ shared: options.shared ?? false,
5490
+ workspace_ext_id: options.workspaceExtId,
5491
+ ...options.configExtId ? { config_ext_id: options.configExtId } : {}
5492
+ }
5488
5493
  }
5489
5494
  }),
5490
5495
  "Failed to upload from URLs"
5491
5496
  );
5492
5497
  }
5498
+ var UPLOAD_WORKSPACE_CONFLICT_MESSAGES = {
5499
+ workspace_mismatch: "These files were prepared for another workspace, so they were not saved. Upload them again.",
5500
+ workspace_key_required: "The workspace couldn't be unlocked for this upload, so the files were not saved."
5501
+ };
5502
+ function requireUploadData(result, message) {
5503
+ const status = result.response?.status;
5504
+ const conflict = result.error && status === 409 ? workspaceConflictOf(result.error) : null;
5505
+ if (conflict) {
5506
+ throw new ArbiApiError(
5507
+ UPLOAD_WORKSPACE_CONFLICT_MESSAGES[conflict.code],
5508
+ result.error,
5509
+ status,
5510
+ {
5511
+ code: conflict.code
5512
+ }
5513
+ );
5514
+ }
5515
+ return requireData(result, message);
5516
+ }
5493
5517
  async function uploadDocuments(arbi, files, options = {}) {
5494
5518
  const query2 = {};
5495
5519
  if (options.shared !== void 0) query2.shared = options.shared;
@@ -5514,7 +5538,7 @@ async function uploadDocuments(arbi, files, options = {}) {
5514
5538
  return form;
5515
5539
  }
5516
5540
  });
5517
- return requireData(result, "Failed to upload documents");
5541
+ return requireUploadData(result, "Failed to upload documents");
5518
5542
  }
5519
5543
  async function similarDocuments(arbi, options = {}) {
5520
5544
  return requireData(
@@ -5671,6 +5695,9 @@ async function presignedPut(url, body, onProgress, headers) {
5671
5695
  }
5672
5696
  }
5673
5697
  async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5698
+ if (!options?.workspaceExtId) {
5699
+ throw new ArbiError("uploadDocumentsDirect needs options.workspaceExtId (the key's workspace)");
5700
+ }
5674
5701
  if (files.length === 0) return { doc_ext_ids: [], skipped: [] };
5675
5702
  const SECRETBOX_ENVELOPE_OVERHEAD = 40;
5676
5703
  const declared = files.map((f2) => ({
@@ -5682,21 +5709,19 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5682
5709
  }));
5683
5710
  const initBody = {
5684
5711
  files: declared,
5685
- shared: options?.shared !== false,
5686
- config_ext_id: options?.configExtId ?? null,
5712
+ shared: options.shared !== false,
5713
+ config_ext_id: options.configExtId ?? null,
5687
5714
  // Only sent when set, so a plain upload is accepted by any server version.
5688
- ...options?.versionOf ? { version_of: options.versionOf } : {},
5689
- wp_type: options?.wpType ?? null,
5690
- tag_ext_id: options?.tagExtId ?? null,
5691
- folder: options?.folder ? sanitizeFolderPath(options.folder) : null,
5692
- presign_expires_in: options?.presignExpiresIn ?? 3600
5715
+ ...options.versionOf ? { version_of: options.versionOf } : {},
5716
+ wp_type: options.wpType ?? null,
5717
+ tag_ext_id: options.tagExtId ?? null,
5718
+ folder: options.folder ? sanitizeFolderPath(options.folder) : null,
5719
+ presign_expires_in: options.presignExpiresIn ?? 3600
5693
5720
  };
5694
- const guarded = options?.inWorkspace ?? ((send) => send());
5695
- const initResult = await guarded(
5696
- async () => requireData(
5697
- await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
5698
- "Failed to initialize direct upload"
5699
- )
5721
+ const query2 = { workspace_ext_id: options.workspaceExtId };
5722
+ const initResult = requireUploadData(
5723
+ await arbi.fetch.POST("/v1/document/upload-init", { params: { query: query2 }, body: initBody }),
5724
+ "Failed to initialize direct upload"
5700
5725
  );
5701
5726
  const items = initResult.items ?? [];
5702
5727
  const bytesByName = /* @__PURE__ */ new Map();
@@ -5730,7 +5755,7 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5730
5755
  const total = ciphertext.length;
5731
5756
  try {
5732
5757
  await presignedPut(item.upload_url, ciphertext, (loaded, putTotal) => {
5733
- options?.onBytesProgress?.({
5758
+ options.onBytesProgress?.({
5734
5759
  fileIndex,
5735
5760
  fileName: item.file_name,
5736
5761
  loaded,
@@ -5742,7 +5767,7 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5742
5767
  `Presigned PUT for ${item.doc_ext_id} failed: ${err instanceof Error ? err.message : String(err)}`
5743
5768
  );
5744
5769
  }
5745
- options?.onBytesProgress?.({
5770
+ options.onBytesProgress?.({
5746
5771
  fileIndex,
5747
5772
  fileName: item.file_name,
5748
5773
  loaded: total,
@@ -5753,16 +5778,15 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5753
5778
  if (toCommit.length === 0) {
5754
5779
  return { doc_ext_ids: [], skipped };
5755
5780
  }
5756
- const commitResult = await guarded(
5757
- async () => requireData(
5758
- await arbi.fetch.POST("/v1/document/upload-commit", {
5759
- body: {
5760
- doc_ext_ids: toCommit,
5761
- tag_ext_id: options?.tagExtId ?? null
5762
- }
5763
- }),
5764
- "Failed to commit direct upload"
5765
- )
5781
+ const commitResult = requireUploadData(
5782
+ await arbi.fetch.POST("/v1/document/upload-commit", {
5783
+ params: { query: query2 },
5784
+ body: {
5785
+ doc_ext_ids: toCommit,
5786
+ tag_ext_id: options.tagExtId ?? null
5787
+ }
5788
+ }),
5789
+ "Failed to commit direct upload"
5766
5790
  );
5767
5791
  return {
5768
5792
  doc_ext_ids: commitResult.doc_ext_ids ?? [],
@@ -5987,6 +6011,130 @@ async function unlockModelConnections(arbi, keys, onlyId) {
5987
6011
  }
5988
6012
  }
5989
6013
 
6014
+ // src/operations/secure-mail.ts
6015
+ var secure_mail_exports = {};
6016
+ __export(secure_mail_exports, {
6017
+ claimSecureMail: () => claimSecureMail,
6018
+ prepareSecureMail: () => prepareSecureMail,
6019
+ secureMime: () => secureMime
6020
+ });
6021
+ var MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
6022
+ var utf8 = new TextEncoder();
6023
+ var encodedWord = (value) => `=?UTF-8?B?${client.bytesToBase64(utf8.encode(value))}?=`;
6024
+ var folded = (value) => value.match(/.{1,76}/g)?.join("\r\n") ?? "";
6025
+ var safeHeader = (value) => {
6026
+ if (/[\r\n\0]/.test(value)) throw new Error("Email headers cannot contain newlines");
6027
+ return value;
6028
+ };
6029
+ function secureMime(compose, sender) {
6030
+ const address = (r2) => `${r2.name ? encodedWord(safeHeader(r2.name)) + " " : ""}<${safeHeader(r2.email)}>`;
6031
+ const boundary = "arbi-" + crypto.randomUUID();
6032
+ const headers = [
6033
+ `From: ${address({ email: sender.email, name: sender.display_name })}`,
6034
+ ...compose.to.length ? [`To: ${compose.to.map(address).join(", ")}`] : [],
6035
+ ...compose.cc.length ? [`Cc: ${compose.cc.map(address).join(", ")}`] : [],
6036
+ `Subject: ${encodedWord(safeHeader(compose.subject))}`,
6037
+ `Date: ${(/* @__PURE__ */ new Date()).toUTCString()}`,
6038
+ `Message-ID: <${crypto.randomUUID()}@${sender.email.split("@")[1]}>`,
6039
+ ...compose.in_reply_to ? [`In-Reply-To: ${safeHeader(compose.in_reply_to)}`] : [],
6040
+ ...compose.references?.length ? [`References: ${compose.references.map(safeHeader).join(" ")}`] : [],
6041
+ "MIME-Version: 1.0",
6042
+ "X-ARBI-Secure-Delivery: 1",
6043
+ `Content-Type: multipart/mixed; boundary="${boundary}"`
6044
+ ];
6045
+ const alternative = "alternative-" + crypto.randomUUID();
6046
+ const plainPart = `Content-Type: text/plain; charset="utf-8"\r
6047
+ Content-Transfer-Encoding: base64\r
6048
+ \r
6049
+ ${folded(client.bytesToBase64(utf8.encode(compose.text)))}`;
6050
+ const bodyPart = compose.html ? `Content-Type: multipart/alternative; boundary="${alternative}"\r
6051
+ \r
6052
+ --${alternative}\r
6053
+ ${plainPart}\r
6054
+ --${alternative}\r
6055
+ Content-Type: text/html; charset="utf-8"\r
6056
+ Content-Transfer-Encoding: base64\r
6057
+ \r
6058
+ ${folded(client.bytesToBase64(utf8.encode(compose.html)))}\r
6059
+ --${alternative}--\r
6060
+ ` : plainPart;
6061
+ const parts = [
6062
+ `--${boundary}\r
6063
+ ${bodyPart}`,
6064
+ ...compose.attachments.map((a2) => {
6065
+ if (!a2.content_base64) throw new Error("Attachment content is missing");
6066
+ const name = encodeURIComponent(safeHeader(a2.name)).replace(/'/g, "%27");
6067
+ return `--${boundary}\r
6068
+ Content-Type: ${safeHeader(a2.content_type || "application/octet-stream")}\r
6069
+ Content-Disposition: attachment; filename*=UTF-8''${name}\r
6070
+ Content-Transfer-Encoding: base64\r
6071
+ \r
6072
+ ${folded(a2.content_base64)}`;
6073
+ }),
6074
+ `--${boundary}--\r
6075
+ `
6076
+ ];
6077
+ return utf8.encode(headers.join("\r\n") + "\r\n\r\n" + parts.join("\r\n"));
6078
+ }
6079
+ async function prepareSecureMail(compose, sender, { requestId, senderPublicKey, frontendOrigin }) {
6080
+ const raw = secureMime(compose, sender);
6081
+ try {
6082
+ if (raw.length > MAX_MESSAGE_BYTES) throw new Error("Email exceeds the message size limit");
6083
+ const metadata = {
6084
+ secure_delivery: true,
6085
+ id: "",
6086
+ subject: compose.subject,
6087
+ sender: [{ email: sender.email, name: sender.display_name }],
6088
+ to: compose.to,
6089
+ cc: compose.cc,
6090
+ bcc: [],
6091
+ received_at: (/* @__PURE__ */ new Date()).toISOString(),
6092
+ preview: compose.text.slice(0, 220),
6093
+ unread: false,
6094
+ text: "",
6095
+ references: compose.references ?? [],
6096
+ attachments: compose.attachments.map((a2, i2) => ({
6097
+ ...a2,
6098
+ id: String(i2),
6099
+ content_base64: null
6100
+ }))
6101
+ };
6102
+ const recipients = [
6103
+ ...new Set([...compose.to, ...compose.cc, ...compose.bcc].map((r2) => r2.email.toLowerCase()))
6104
+ ];
6105
+ const sealed = await client.sealSecureMail(raw, metadata, senderPublicKey);
6106
+ return {
6107
+ request_id: requestId,
6108
+ draft_id: compose.draft_id,
6109
+ recipients: recipients.map((email) => ({
6110
+ id: crypto.randomUUID(),
6111
+ email,
6112
+ fragment_key: sealed.fragment_key
6113
+ })),
6114
+ ciphertext: sealed.ciphertext,
6115
+ metadata_ciphertext: sealed.metadata_ciphertext,
6116
+ sender_wrapped_key: sealed.sender_wrapped_key,
6117
+ frontend_origin: frontendOrigin
6118
+ };
6119
+ } finally {
6120
+ raw.fill(0);
6121
+ }
6122
+ }
6123
+ async function claimSecureMail(mail, id, fragmentKey, recipientPublicKey) {
6124
+ const key = client.decodeSecureMailKey(fragmentKey);
6125
+ try {
6126
+ const path2 = `/secure/${encodeURIComponent(id)}`;
6127
+ const response = await mail(path2);
6128
+ const { raw } = await client.openSecureMail(await response.json(), key);
6129
+ raw.fill(0);
6130
+ const claim = await client.secureMailClaim(key, recipientPublicKey);
6131
+ const claimed = await mail(`${path2}/claim`, { method: "POST", body: JSON.stringify(claim) });
6132
+ return await claimed.json();
6133
+ } finally {
6134
+ key.fill(0);
6135
+ }
6136
+ }
6137
+
5990
6138
  // src/operations/workspaces.ts
5991
6139
  var workspaces_exports = {};
5992
6140
  __export(workspaces_exports, {
@@ -9624,7 +9772,6 @@ __export(mail_exports, {
9624
9772
  NATIVE_ACCOUNT: () => NATIVE_ACCOUNT,
9625
9773
  attachmentFromBytes: () => attachmentFromBytes,
9626
9774
  claimNativeAlias: () => claimNativeAlias,
9627
- claimSecureMail: () => claimSecureMail,
9628
9775
  createMailFetch: () => createMailFetch,
9629
9776
  downloadAttachment: () => downloadAttachment,
9630
9777
  getMailPolicy: () => getMailPolicy,
@@ -9730,28 +9877,16 @@ async function unlockNativeMail(mail, keys) {
9730
9877
  secretKey.fill(0);
9731
9878
  }
9732
9879
  }
9733
- async function claimSecureMail(mail, id, fragmentKey, recipientPublicKey) {
9734
- const key = client.decodeSecureMailKey(fragmentKey);
9735
- try {
9736
- const path2 = `/secure/${encodeURIComponent(id)}`;
9737
- const { raw } = await client.openSecureMail(await json(mail(path2)), key);
9738
- raw.fill(0);
9739
- const claim = await client.secureMailClaim(key, recipientPublicKey);
9740
- return await json(mail(`${path2}/claim`, { method: "POST", body: JSON.stringify(claim) }));
9741
- } finally {
9742
- key.fill(0);
9743
- }
9744
- }
9745
9880
  function attachmentFromBytes(name, contentType, bytes) {
9746
9881
  return {
9747
9882
  id: "",
9748
9883
  name,
9749
9884
  content_type: contentType,
9750
9885
  size: bytes.length,
9751
- content_base64: bytesToBase643(bytes)
9886
+ content_base64: bytesToBase644(bytes)
9752
9887
  };
9753
9888
  }
9754
- function bytesToBase643(bytes) {
9889
+ function bytesToBase644(bytes) {
9755
9890
  let binary = "";
9756
9891
  for (let i2 = 0; i2 < bytes.length; i2 += 32768) {
9757
9892
  binary += String.fromCharCode(...bytes.subarray(i2, i2 + 32768));
@@ -11213,6 +11348,10 @@ var Arbi = class {
11213
11348
  if (target) await this.openWorkspace(target);
11214
11349
  return target;
11215
11350
  }
11351
+ /** {@link targetWorkspace} for a call that cannot go without one: throws when none is known. */
11352
+ async requireTargetWorkspace(workspaceId) {
11353
+ return await this.targetWorkspace(workspaceId) ?? this.requireWorkspace();
11354
+ }
11216
11355
  /**
11217
11356
  * Make a workspace the CURRENT one: decrypt its key, open it on the server (which makes it the
11218
11357
  * session's active workspace) and record it in the session. This is navigation: only the host's
@@ -11826,20 +11965,23 @@ var Arbi = class {
11826
11965
  finaliseTranslation: (docId) => finaliseTranslation(this.requireClient(), docId),
11827
11966
  delete: (externalIds) => deleteDocuments(this.requireClient(), externalIds),
11828
11967
  update: (documents) => updateDocuments(this.requireClient(), documents),
11829
- uploadUrl: (urls, options) => {
11830
- this.requireWorkspace();
11831
- return uploadUrl(
11832
- this.requireClient(),
11833
- urls,
11834
- options?.shared,
11835
- options?.configExtId
11836
- );
11968
+ /** Make documents from web addresses in the current workspace, or `options.workspaceId`. */
11969
+ uploadUrl: async (urls, options) => {
11970
+ const { workspaceId, ...rest } = options ?? {};
11971
+ return uploadUrl(this.requireClient(), urls, {
11972
+ workspaceExtId: await this.requireTargetWorkspace(workspaceId),
11973
+ ...rest
11974
+ });
11837
11975
  },
11838
11976
  /**
11839
- * Upload files in one request (the open workspace, or `options.workspaceExtId`): folder, tag,
11840
- * sharing, config, a new version of a document.
11977
+ * Upload files in one request into the current workspace, or `options.workspaceExtId`: folder,
11978
+ * tag, sharing, config, a new version of a document. The request names the workspace either
11979
+ * way, so a switch while it is in flight cannot move it.
11841
11980
  */
11842
- upload: (files, options) => uploadDocuments(this.requireClient(), files, options),
11981
+ upload: async (files, options) => uploadDocuments(this.requireClient(), files, {
11982
+ ...options,
11983
+ workspaceExtId: await this.requireTargetWorkspace(options?.workspaceExtId ?? void 0)
11984
+ }),
11843
11985
  /** Near-duplicate pairs at or above `threshold` (or one document's, `docId`). */
11844
11986
  similar: (options) => similarDocuments(this.requireClient(), options),
11845
11987
  /**
@@ -11864,19 +12006,15 @@ var Arbi = class {
11864
12006
  },
11865
12007
  /**
11866
12008
  * Upload files straight to storage, encrypted here with `workspaceKey` (`uploadDocumentsDirect`),
11867
- * into `workspaceId`, which must be the workspace open NOW. `upload-init` and `upload-commit`
11868
- * name no workspace yet (they act on the session's open one), so each runs under
11869
- * `readInWorkspace`: it is not sent, or its answer not kept, unless `workspaceId` is open when
11870
- * it is sent and still when it returns. A switch refuses the upload
11871
- * (`ArbiWorkspaceChangedError`) instead of storing files encrypted with one workspace's key in
11872
- * another. For any other workspace use `upload` with `workspaceExtId`, which names it.
12009
+ * into `workspaceId`, whose key it must be. `upload-init` and `upload-commit` name that
12010
+ * workspace (made usable for this session first, not switched to), so a switch while the
12011
+ * upload runs cannot move the files into another workspace.
11873
12012
  */
11874
- uploadDirect: (workspaceId, workspaceKey, files, options) => {
11875
- if (this.currentWorkspaceId !== workspaceId)
11876
- return Promise.reject(new ArbiWorkspaceChangedError(workspaceId, "uploading to"));
12013
+ uploadDirect: async (workspaceId, workspaceKey, files, options) => {
12014
+ const workspaceExtId = await this.requireTargetWorkspace(workspaceId);
11877
12015
  return uploadDocumentsDirect(this.requireClient(), workspaceKey, files, {
11878
12016
  ...options,
11879
- inWorkspace: (send) => this.readInWorkspace(workspaceId, send)
12017
+ workspaceExtId
11880
12018
  });
11881
12019
  },
11882
12020
  /** Download a document's original file — its current version, or `version`. */
@@ -12033,6 +12171,42 @@ var Arbi = class {
12033
12171
  });
12034
12172
  }
12035
12173
  };
12174
+ // ── Secure mail ─────────────────────────────────────────────────────
12175
+ /**
12176
+ * Mail to anyone, sealed in this browser under a key that travels only in the link's fragment
12177
+ * (see `operations/secure-mail`). Both sides use the signed-in user's encryption key: the
12178
+ * login's, or (a new tab not signed in to the server yet) the one kept on this device.
12179
+ */
12180
+ secureMail = {
12181
+ /**
12182
+ * The `/secure/send` payload for `compose` from `account`, shown with the user's own name.
12183
+ * Links open on `frontendOrigin` (default: this page's origin).
12184
+ */
12185
+ prepare: async (compose, account, requestId, frontendOrigin = globalThis.location?.origin ?? "") => {
12186
+ const user = this.client?.session.getState().user;
12187
+ const name = user ? [user.given_name, user.family_name] : [this.userProfile?.givenName, this.userProfile?.familyName];
12188
+ const senderName = name.filter(Boolean).join(" ");
12189
+ return prepareSecureMail(
12190
+ compose,
12191
+ { ...account, display_name: senderName || account.display_name },
12192
+ { requestId, senderPublicKey: await this.encryptionPublicKey(), frontendOrigin }
12193
+ );
12194
+ },
12195
+ /**
12196
+ * Claim the secure message `id` with the key from its link into the user's native inbox, over
12197
+ * `mail` (default: this session's mail transport). Resolves to the message's id there.
12198
+ */
12199
+ claim: async (id, fragmentKey, mail = this.mail.fetch) => claimSecureMail(mail, id, fragmentKey, await this.encryptionPublicKey())
12200
+ };
12201
+ /** The signed-in user's X25519 public key (from the identity key; its secret half is wiped). */
12202
+ async encryptionPublicKey() {
12203
+ const signingKey = this.loginResult?.signingPrivateKey ?? (await this.client?.storage.getSession().catch(() => null))?.signingPrivateKey;
12204
+ if (!signingKey) throw new ArbiError("Sign in again to unlock your encryption key");
12205
+ await client.initSodium();
12206
+ const pair = client.encryptionKeypairFromSigningKey(signingKey);
12207
+ pair.secretKey.fill(0);
12208
+ return pair.publicKey;
12209
+ }
12036
12210
  async openResponseHandle(open, options, id, bufferEvents = false) {
12037
12211
  const controller = new AbortController();
12038
12212
  const abort = () => controller.abort();
@@ -14007,6 +14181,7 @@ exports.resolveSummary = resolveSummary;
14007
14181
  exports.resolveWorkspace = resolveWorkspace;
14008
14182
  exports.responses = responses_exports;
14009
14183
  exports.searchChunks = searchChunks;
14184
+ exports.secureMail = secure_mail_exports;
14010
14185
  exports.selectFullContextDocument = selectFullContextDocument;
14011
14186
  exports.selectWorkspace = selectWorkspace;
14012
14187
  exports.selectWorkspaceById = selectWorkspaceById;