@tearleads/client-sdk 0.1.239 → 0.1.240

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.
@@ -19,19 +19,25 @@ export declare function createLinkSetAttachmentReuse(): LinkSetAttachmentReuse;
19
19
  * was authenticated or wrapped by this device before that leg signed it, so a
20
20
  * reuse propagates no key to a new scope; any target the previous leg did not
21
21
  * wrap returns null and the leg lists and authenticates as usual. A bind or
22
- * detach in between, a content-key epoch change, or a re-entered retired
23
- * target (the API keeps its stored wrap over the fresh one) makes the API
24
- * refuse with an uncoded 409, and the caller re-lists once.
22
+ * detach in between makes the API refuse with a coded 409
23
+ * (`document_link_attachments_changed`); a content-key epoch change or a
24
+ * re-entered retired target (the API keeps its stored wrap over the fresh one)
25
+ * with an uncoded one. The caller re-lists once.
25
26
  */
26
27
  export declare function reuseCommittedBlobRewraps(input: {
27
28
  committed: BlobRewraps;
28
29
  documentId: string;
29
30
  targets: readonly DocumentContentKeyTarget[];
30
31
  }): BlobRewraps | null;
31
- /** Authenticate the existing bytes before propagating their DEK to a new scope. */
32
+ /**
33
+ * Authenticate the existing bytes before propagating their DEK to a new scope.
34
+ * `refreshListing` bypasses a cached listing, after the server refused a leg
35
+ * because its attachments changed.
36
+ */
32
37
  export declare function prepareDocumentLinkBlobRewraps(input: {
33
38
  apiClient: DocumentLinkSetMutationApi;
34
39
  execSql: ExecSql;
40
+ refreshListing?: boolean | undefined;
35
41
  targetContainerProjection: ContainerWriterProjectionResponse;
36
42
  targetSecretKey: Uint8Array;
37
43
  targets: readonly DocumentContentKeyTarget[];
@@ -18,9 +18,10 @@ export function createLinkSetAttachmentReuse() {
18
18
  * was authenticated or wrapped by this device before that leg signed it, so a
19
19
  * reuse propagates no key to a new scope; any target the previous leg did not
20
20
  * wrap returns null and the leg lists and authenticates as usual. A bind or
21
- * detach in between, a content-key epoch change, or a re-entered retired
22
- * target (the API keeps its stored wrap over the fresh one) makes the API
23
- * refuse with an uncoded 409, and the caller re-lists once.
21
+ * detach in between makes the API refuse with a coded 409
22
+ * (`document_link_attachments_changed`); a content-key epoch change or a
23
+ * re-entered retired target (the API keeps its stored wrap over the fresh one)
24
+ * with an uncoded one. The caller re-lists once.
24
25
  */
25
26
  export function reuseCommittedBlobRewraps(input) {
26
27
  const rewraps = [];
@@ -52,16 +53,14 @@ export function reuseCommittedBlobRewraps(input) {
52
53
  }
53
54
  return rewraps.sort(compareBlobIds);
54
55
  }
55
- /** Authenticate the existing bytes before propagating their DEK to a new scope. */
56
+ /**
57
+ * Authenticate the existing bytes before propagating their DEK to a new scope.
58
+ * `refreshListing` bypasses a cached listing, after the server refused a leg
59
+ * because its attachments changed.
60
+ */
56
61
  export async function prepareDocumentLinkBlobRewraps(input) {
57
62
  const documentId = input.writerProjection.documentId;
58
- const bindings = await input.apiClient.listDocumentAttachments(documentId);
59
- // The API refuses the link unless every active binding is rewrapped, so an
60
- // unavailable listing (offline, or a 409 while a bind is mid-flight) is a
61
- // retryable availability failure of this mutation, not integrity evidence.
62
- if (!bindings)
63
- throw new ProjectionDependencyUnavailableError("Document attachments are unavailable for relinking");
64
- assertProjectionVerificationCurrent(input.stillCurrent);
63
+ const bindings = await listRelinkBindings(input, documentId);
65
64
  if (bindings.length === 0)
66
65
  return [];
67
66
  const keks = await collectRelinkKeks(input);
@@ -118,6 +117,19 @@ export async function prepareDocumentLinkBlobRewraps(input) {
118
117
  }
119
118
  return [...rewrapByBlob.values()].sort(compareBlobIds);
120
119
  }
120
+ async function listRelinkBindings(input, documentId) {
121
+ // An operation that ended before or while listing cancels instead of
122
+ // failing. The shared listing still reports its own failed request.
123
+ assertProjectionVerificationCurrent(input.stillCurrent);
124
+ const bindings = await input.apiClient.listDocumentAttachments(documentId, input.refreshListing ? { refresh: true } : undefined);
125
+ assertProjectionVerificationCurrent(input.stillCurrent);
126
+ // The API refuses the link unless every active binding is rewrapped, so an
127
+ // unavailable listing (offline, or a 409 while a bind is mid-flight) is a
128
+ // retryable availability failure of this mutation, not integrity evidence.
129
+ if (!bindings)
130
+ throw new ProjectionDependencyUnavailableError("Document attachments are unavailable for relinking");
131
+ return bindings;
132
+ }
121
133
  async function wrapBlobKeyForTarget(input) {
122
134
  const { binding, target } = input;
123
135
  const wrapped = await wrapContentKey(input.contentKey, input.kek, {
@@ -1 +1 @@
1
- {"version":3,"file":"linkSetBlobRewraps.js","sourceRoot":"","sources":["linkSetBlobRewraps.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAG3B,uBAAuB,EACvB,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EACL,kCAAkC,EAClC,sBAAsB,GACvB,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EACL,gBAAgB,EAChB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAC9F,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,OAAO,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAC3F,OAAO,EAAE,gCAAgC,EAAE,MAAM,qDAAqD,CAAC;AACvG,OAAO,EAAE,wBAAwB,EAAE,MAAM,yDAAyD,CAAC;AAoBnG,MAAM,UAAU,4BAA4B;IAC1C,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AAC7B,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,yBAAyB,CAAC,KAIzC;IACC,MAAM,OAAO,GAAiB,EAAE,CAAC;IACjC,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;QACrC,MAAM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AAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,cAAc,CAAC,CAAqB,EAAE,CAAqB;IAClE,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n BLOB_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkAccessEventBody,\n readKeyingCanonicalJson,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n BlobAttachmentSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n deriveDocumentTargetFromProjection,\n unwrapContainerKekPath,\n} from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n assertEqualBytes,\n targetKey,\n} from \"../../../data/documents/shared/readers\";\nimport type { DocumentLinkSetMutationApi } from \"../../../data/documents/shared/types\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { createAttachmentProofReader } from \"../../blobs/verification/attachmentDecryptor\";\nimport { createAttachmentKeyAuthenticator } from \"../../blobs/verification/attachmentKeyAuthenticator\";\nimport { verifyRetainedAttachment } from \"../../blobs/verification/retainedAttachmentVerification\";\n\ninterface BlobRewrap {\n blobId: string;\n contentKeyEpoch: number;\n targets: DocumentLinkAccessEventBody[\"blobRewraps\"][number][\"targets\"][number][];\n}\n\ntype BlobRewraps = DocumentLinkAccessEventBody[\"blobRewraps\"];\n\n/**\n * One move or trash workflow lists a document's attachments once. After a leg\n * commits, `committed` holds the document-scoped envelopes it signed, which\n * are exactly what the server now stores for this document; the next leg\n * starts from them instead of listing again.\n */\nexport interface LinkSetAttachmentReuse {\n committed: BlobRewraps | null;\n}\n\nexport function createLinkSetAttachmentReuse(): LinkSetAttachmentReuse {\n return { committed: null };\n}\n\n/**\n * Re-cite the previous leg's envelopes for this leg's targets. Every envelope\n * was authenticated or wrapped by this device before that leg signed it, so a\n * reuse propagates no key to a new scope; any target the previous leg did not\n * wrap returns null and the leg lists and authenticates as usual. A bind or\n * detach in between, a content-key epoch change, or a re-entered retired\n * target (the API keeps its stored wrap over the fresh one) makes the API\n * refuse with an uncoded 409, and the caller re-lists once.\n */\nexport function reuseCommittedBlobRewraps(input: {\n committed: BlobRewraps;\n documentId: string;\n targets: readonly DocumentContentKeyTarget[];\n}): BlobRewraps | null {\n const rewraps: BlobRewrap[] = [];\n for (const rewrap of input.committed) {\n const bindingIds = [\n ...new Set(rewrap.targets.map((target) => target.bindingId)),\n ];\n const targets: BlobRewrap[\"targets\"] = [];\n for (const bindingId of bindingIds) {\n for (const target of input.targets) {\n const previous = rewrap.targets.find(\n (candidate) =>\n candidate.bindingId === bindingId &&\n candidate.documentId === input.documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n if (!previous) return null;\n targets.push({\n ...previous,\n ...target,\n wrappingMetadata: readKeyingCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n });\n }\n }\n rewraps.push({\n blobId: rewrap.blobId,\n contentKeyEpoch: rewrap.contentKeyEpoch,\n targets,\n });\n }\n return rewraps.sort(compareBlobIds);\n}\n\n/** Authenticate the existing bytes before propagating their DEK to a new scope. */\nexport async function prepareDocumentLinkBlobRewraps(\n input: {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<DocumentLinkAccessEventBody[\"blobRewraps\"]> {\n const documentId = input.writerProjection.documentId;\n const bindings = await input.apiClient.listDocumentAttachments(documentId);\n // The API refuses the link unless every active binding is rewrapped, so an\n // unavailable listing (offline, or a 409 while a bind is mid-flight) is a\n // retryable availability failure of this mutation, not integrity evidence.\n if (!bindings)\n throw new ProjectionDependencyUnavailableError(\n \"Document attachments are unavailable for relinking\",\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (bindings.length === 0) return [];\n const keks = await collectRelinkKeks(input);\n const authenticateKey = createAttachmentKeyAuthenticator(\n input.apiClient,\n documentId,\n );\n const verifyRetained = createAttachmentProofReader(\n input.apiClient,\n documentId,\n verifyRetainedAttachment,\n );\n const rewrapByBlob = new Map<string, BlobRewrap>();\n for (const binding of bindings) {\n const verification = {\n binding,\n expectedDocumentId: documentId,\n expectedSlotId: binding.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Attachment relink\",\n ),\n targetSecretKey: input.targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n writerProjection: input.writerProjection,\n };\n const needsKey = input.targets.some(\n (target) => !retainedTarget(binding, target, documentId),\n );\n const contentKey = needsKey ? await authenticateKey(verification) : null;\n if (!needsKey) await verifyRetained(verification);\n const targets = await Promise.all(\n input.targets.map(async (target) => {\n const previous = retainedTarget(binding, target, documentId);\n if (previous)\n return {\n ...previous,\n ...target,\n wrappingMetadata: readKeyingCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n };\n const kek = keks.get(targetKey(target));\n if (!kek)\n throw new Error(\n \"Attachment destination is not a verified current container head\",\n );\n if (!contentKey)\n throw new Error(\"Attachment content key is unavailable\");\n return wrapBlobKeyForTarget({\n binding,\n contentKey,\n documentId,\n kek,\n target,\n });\n }),\n );\n const rewrap = rewrapByBlob.get(binding.blobId) ?? {\n blobId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n targets: [],\n };\n if (rewrap.contentKeyEpoch !== binding.contentKeyBundle.contentKeyEpoch)\n throw new Error(\"Attachment content epoch changed during relinking\");\n rewrap.targets.push(...targets);\n rewrapByBlob.set(binding.blobId, rewrap);\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n return [...rewrapByBlob.values()].sort(compareBlobIds);\n}\n\nasync function wrapBlobKeyForTarget(input: {\n binding: BlobAttachmentSummary;\n contentKey: Uint8Array;\n documentId: string;\n kek: Uint8Array;\n target: DocumentContentKeyTarget;\n}) {\n const { binding, target } = input;\n const wrapped = await wrapContentKey(input.contentKey, input.kek, {\n kind: \"Blob\",\n objectId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n bindingId: binding.bindingId,\n documentId: input.documentId,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: BLOB_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n}\n\nfunction retainedTarget(\n binding: BlobAttachmentSummary,\n target: DocumentContentKeyTarget,\n documentId: string,\n) {\n return binding.contentKeyBundle.targets.find(\n (candidate) =>\n candidate.bindingId === binding.bindingId &&\n candidate.documentId === documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n}\n\nasync function collectRelinkKeks(\n input: Parameters<typeof prepareDocumentLinkBlobRewraps>[0],\n): Promise<Map<string, Uint8Array>> {\n const keks = new Map<string, Uint8Array>();\n for (const projection of [\n ...documentContainerProjections(input.writerProjection),\n input.targetContainerProjection,\n ]) {\n const keys = await unwrapContainerKekPath({\n projection,\n secretKey: input.targetSecretKey,\n execSql: input.execSql,\n ...projectionVerificationOptions(input),\n });\n // Every node of this verified path has a current signed head. Historical\n // keyring entries may open source bytes, but never enter the destination map.\n for (const [index, head] of projection.containerKeks.entries()) {\n const target = deriveDocumentTargetFromProjection({\n ...projection,\n containerId: head.containerId,\n path: projection.path.slice(0, index + 1),\n containerKeks: projection.containerKeks.slice(0, index + 1),\n });\n const key = keys.get(target.containerKeyEpochId);\n // A direct child grantee need not possess any ancestor secret.\n if (!key) continue;\n const id = targetKey(target);\n const previous = keks.get(id);\n if (previous)\n assertEqualBytes(\n previous,\n key,\n \"Attachment link projections contain conflicting KEKs\",\n );\n keks.set(id, key);\n }\n }\n return keks;\n}\n\nfunction compareBlobIds(a: { blobId: string }, b: { blobId: string }): number {\n return a.blobId < b.blobId ? -1 : a.blobId > b.blobId ? 1 : 0;\n}\n"]}
1
+ {"version":3,"file":"linkSetBlobRewraps.js","sourceRoot":"","sources":["linkSetBlobRewraps.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAG3B,uBAAuB,EACvB,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EACL,kCAAkC,EAClC,sBAAsB,GACvB,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EACL,gBAAgB,EAChB,SAAS,GACV,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAC9F,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAA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AK,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,UAAU,CAAC,aAAa,CAAC,OAAO,EAAE,EAAE,CAAC;YAC/D,MAAM,MAAM,GAAG,kCAAkC,CAAC;gBAChD,GAAG,UAAU;gBACb,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,IAAI,EAAE,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC;gBACzC,aAAa,EAAE,UAAU,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC;aAC5D,CAAC,CAAC;YACH,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;YACjD,+DAA+D;YAC/D,IAAI,CAAC,GAAG;gBAAE,SAAS;YACnB,MAAM,EAAE,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;YAC7B,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC9B,IAAI,QAAQ;gBACV,gBAAgB,CACd,QAAQ,EACR,GAAG,EACH,sDAAsD,CACvD,CAAC;YACJ,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;QACpB,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,cAAc,CAAC,CAAqB,EAAE,CAAqB;IAClE,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n BLOB_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkAccessEventBody,\n readKeyingCanonicalJson,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n BlobAttachmentSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n deriveDocumentTargetFromProjection,\n unwrapContainerKekPath,\n} from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n assertEqualBytes,\n targetKey,\n} from \"../../../data/documents/shared/readers\";\nimport type { DocumentLinkSetMutationApi } from \"../../../data/documents/shared/types\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { createAttachmentProofReader } from \"../../blobs/verification/attachmentDecryptor\";\nimport { createAttachmentKeyAuthenticator } from \"../../blobs/verification/attachmentKeyAuthenticator\";\nimport { verifyRetainedAttachment } from \"../../blobs/verification/retainedAttachmentVerification\";\n\ninterface BlobRewrap {\n blobId: string;\n contentKeyEpoch: number;\n targets: DocumentLinkAccessEventBody[\"blobRewraps\"][number][\"targets\"][number][];\n}\n\ntype BlobRewraps = DocumentLinkAccessEventBody[\"blobRewraps\"];\n\n/**\n * One move or trash workflow lists a document's attachments once. After a leg\n * commits, `committed` holds the document-scoped envelopes it signed, which\n * are exactly what the server now stores for this document; the next leg\n * starts from them instead of listing again.\n */\nexport interface LinkSetAttachmentReuse {\n committed: BlobRewraps | null;\n}\n\nexport function createLinkSetAttachmentReuse(): LinkSetAttachmentReuse {\n return { committed: null };\n}\n\n/**\n * Re-cite the previous leg's envelopes for this leg's targets. Every envelope\n * was authenticated or wrapped by this device before that leg signed it, so a\n * reuse propagates no key to a new scope; any target the previous leg did not\n * wrap returns null and the leg lists and authenticates as usual. A bind or\n * detach in between makes the API refuse with a coded 409\n * (`document_link_attachments_changed`); a content-key epoch change or a\n * re-entered retired target (the API keeps its stored wrap over the fresh one)\n * with an uncoded one. The caller re-lists once.\n */\nexport function reuseCommittedBlobRewraps(input: {\n committed: BlobRewraps;\n documentId: string;\n targets: readonly DocumentContentKeyTarget[];\n}): BlobRewraps | null {\n const rewraps: BlobRewrap[] = [];\n for (const rewrap of input.committed) {\n const bindingIds = [\n ...new Set(rewrap.targets.map((target) => target.bindingId)),\n ];\n const targets: BlobRewrap[\"targets\"] = [];\n for (const bindingId of bindingIds) {\n for (const target of input.targets) {\n const previous = rewrap.targets.find(\n (candidate) =>\n candidate.bindingId === bindingId &&\n candidate.documentId === input.documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n if (!previous) return null;\n targets.push({\n ...previous,\n ...target,\n wrappingMetadata: readKeyingCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n });\n }\n }\n rewraps.push({\n blobId: rewrap.blobId,\n contentKeyEpoch: rewrap.contentKeyEpoch,\n targets,\n });\n }\n return rewraps.sort(compareBlobIds);\n}\n\n/**\n * Authenticate the existing bytes before propagating their DEK to a new scope.\n * `refreshListing` bypasses a cached listing, after the server refused a leg\n * because its attachments changed.\n */\nexport async function prepareDocumentLinkBlobRewraps(\n input: {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n refreshListing?: boolean | undefined;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<DocumentLinkAccessEventBody[\"blobRewraps\"]> {\n const documentId = input.writerProjection.documentId;\n const bindings = await listRelinkBindings(input, documentId);\n if (bindings.length === 0) return [];\n const keks = await collectRelinkKeks(input);\n const authenticateKey = createAttachmentKeyAuthenticator(\n input.apiClient,\n documentId,\n );\n const verifyRetained = createAttachmentProofReader(\n input.apiClient,\n documentId,\n verifyRetainedAttachment,\n );\n const rewrapByBlob = new Map<string, BlobRewrap>();\n for (const binding of bindings) {\n const verification = {\n binding,\n expectedDocumentId: documentId,\n expectedSlotId: binding.slotId,\n execSql: input.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Attachment relink\",\n ),\n targetSecretKey: input.targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n writerProjection: input.writerProjection,\n };\n const needsKey = input.targets.some(\n (target) => !retainedTarget(binding, target, documentId),\n );\n const contentKey = needsKey ? await authenticateKey(verification) : null;\n if (!needsKey) await verifyRetained(verification);\n const targets = await Promise.all(\n input.targets.map(async (target) => {\n const previous = retainedTarget(binding, target, documentId);\n if (previous)\n return {\n ...previous,\n ...target,\n wrappingMetadata: readKeyingCanonicalJson(\n previous.wrappingMetadata,\n \"Attachment wrap metadata\",\n ),\n };\n const kek = keks.get(targetKey(target));\n if (!kek)\n throw new Error(\n \"Attachment destination is not a verified current container head\",\n );\n if (!contentKey)\n throw new Error(\"Attachment content key is unavailable\");\n return wrapBlobKeyForTarget({\n binding,\n contentKey,\n documentId,\n kek,\n target,\n });\n }),\n );\n const rewrap = rewrapByBlob.get(binding.blobId) ?? {\n blobId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n targets: [],\n };\n if (rewrap.contentKeyEpoch !== binding.contentKeyBundle.contentKeyEpoch)\n throw new Error(\"Attachment content epoch changed during relinking\");\n rewrap.targets.push(...targets);\n rewrapByBlob.set(binding.blobId, rewrap);\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n return [...rewrapByBlob.values()].sort(compareBlobIds);\n}\n\nasync function listRelinkBindings(\n input: Pick<\n Parameters<typeof prepareDocumentLinkBlobRewraps>[0],\n \"apiClient\" | \"refreshListing\" | \"stillCurrent\"\n >,\n documentId: string,\n): Promise<BlobAttachmentSummary[]> {\n // An operation that ended before or while listing cancels instead of\n // failing. The shared listing still reports its own failed request.\n assertProjectionVerificationCurrent(input.stillCurrent);\n const bindings = await input.apiClient.listDocumentAttachments(\n documentId,\n input.refreshListing ? { refresh: true } : undefined,\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n // The API refuses the link unless every active binding is rewrapped, so an\n // unavailable listing (offline, or a 409 while a bind is mid-flight) is a\n // retryable availability failure of this mutation, not integrity evidence.\n if (!bindings)\n throw new ProjectionDependencyUnavailableError(\n \"Document attachments are unavailable for relinking\",\n );\n return bindings;\n}\n\nasync function wrapBlobKeyForTarget(input: {\n binding: BlobAttachmentSummary;\n contentKey: Uint8Array;\n documentId: string;\n kek: Uint8Array;\n target: DocumentContentKeyTarget;\n}) {\n const { binding, target } = input;\n const wrapped = await wrapContentKey(input.contentKey, input.kek, {\n kind: \"Blob\",\n objectId: binding.blobId,\n contentKeyEpoch: binding.contentKeyBundle.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n bindingId: binding.bindingId,\n documentId: input.documentId,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: BLOB_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n}\n\nfunction retainedTarget(\n binding: BlobAttachmentSummary,\n target: DocumentContentKeyTarget,\n documentId: string,\n) {\n return binding.contentKeyBundle.targets.find(\n (candidate) =>\n candidate.bindingId === binding.bindingId &&\n candidate.documentId === documentId &&\n candidate.containerId === target.containerId &&\n candidate.containerKeyEpochId === target.containerKeyEpochId,\n );\n}\n\nasync function collectRelinkKeks(\n input: Parameters<typeof prepareDocumentLinkBlobRewraps>[0],\n): Promise<Map<string, Uint8Array>> {\n const keks = new Map<string, Uint8Array>();\n for (const projection of [\n ...documentContainerProjections(input.writerProjection),\n input.targetContainerProjection,\n ]) {\n const keys = await unwrapContainerKekPath({\n projection,\n secretKey: input.targetSecretKey,\n execSql: input.execSql,\n ...projectionVerificationOptions(input),\n });\n // Every node of this verified path has a current signed head. Historical\n // keyring entries may open source bytes, but never enter the destination map.\n for (const [index, head] of projection.containerKeks.entries()) {\n const target = deriveDocumentTargetFromProjection({\n ...projection,\n containerId: head.containerId,\n path: projection.path.slice(0, index + 1),\n containerKeks: projection.containerKeks.slice(0, index + 1),\n });\n const key = keys.get(target.containerKeyEpochId);\n // A direct child grantee need not possess any ancestor secret.\n if (!key) continue;\n const id = targetKey(target);\n const previous = keks.get(id);\n if (previous)\n assertEqualBytes(\n previous,\n key,\n \"Attachment link projections contain conflicting KEKs\",\n );\n keks.set(id, key);\n }\n }\n return keks;\n}\n\nfunction compareBlobIds(a: { blobId: string }, b: { blobId: string }): number {\n return a.blobId < b.blobId ? -1 : a.blobId > b.blobId ? 1 : 0;\n}\n"]}
@@ -0,0 +1,74 @@
1
+ import { DOCUMENT_MUTATION_ERROR_CODES } from "../../../internal/validators/response/index.js";
2
+ export const INITIAL_LINK_SET_LEG_STATE = {
3
+ status: "speculative",
4
+ };
5
+ export function startLinkSetLegAttempt(state) {
6
+ return { listing: state.status, status: "unprepared" };
7
+ }
8
+ /**
9
+ * Record what an attempt signed, replacing an earlier preparation; a fresh
10
+ * attempt can only have listed.
11
+ */
12
+ export function recordLinkSetLegRewraps(attempt, prepared) {
13
+ if (attempt.listing === "speculative")
14
+ return { ...prepared, listing: "speculative", status: "prepared" };
15
+ if (prepared.source !== "listed")
16
+ throw new Error("A fresh link-set attempt must list its attachments");
17
+ return { ...prepared, listing: "fresh", status: "prepared" };
18
+ }
19
+ function attemptSource(attempt) {
20
+ return attempt.status === "prepared" ? attempt.source : null;
21
+ }
22
+ /** Whether a refusal of this attempt is held back until the leg decides. */
23
+ export function holdsLinkSetRefusals(attempt) {
24
+ return isSpeculativeRewrapSource(attemptSource(attempt));
25
+ }
26
+ /** The event an attempt's result raises. */
27
+ export function linkSetAttemptEvent(input) {
28
+ const rewraps = input.attempt.status === "prepared" ? input.attempt.rewraps : null;
29
+ return input.committed
30
+ ? { rewraps, type: "attemptCommitted" }
31
+ : {
32
+ heldFailures: input.heldFailures,
33
+ source: attemptSource(input.attempt),
34
+ stillCurrent: input.stillCurrent,
35
+ type: "attemptFailed",
36
+ };
37
+ }
38
+ function isSpeculativeRewrapSource(source) {
39
+ return source === "reused" || source === "skipped";
40
+ }
41
+ /**
42
+ * The server's binding check refused rewraps cited without listing: the coded
43
+ * attachment-set refusal (`lockDocumentLinkBlobRewraps`), or for re-cited
44
+ * envelopes the uncoded content-key epoch refusal the current server returns
45
+ * per cited blob (`rewrapDocumentBlobContentKeyInTransaction`). A skipped
46
+ * attempt cites no blob, so only the coded refusal can answer it.
47
+ */
48
+ function refusedSpeculativeRewraps(source, failure) {
49
+ if (failure.status !== 409 || !isSpeculativeRewrapSource(source))
50
+ return false;
51
+ if (failure.code === DOCUMENT_MUTATION_ERROR_CODES.linkAttachmentsChanged)
52
+ return true;
53
+ return source === "reused" && failure.code === undefined;
54
+ }
55
+ /**
56
+ * Only a speculative attempt the binding check refused retries, and only
57
+ * once: the fresh attempt lists, so it cannot be refused for the same stale
58
+ * view again. Any other refusal keeps its own recovery path.
59
+ */
60
+ export function transitionLinkSetLeg(state, event) {
61
+ if (state.status !== "speculative" && state.status !== "fresh")
62
+ return state;
63
+ if (event.type === "attemptCommitted")
64
+ return { rewraps: event.rewraps, status: "committed" };
65
+ // Nothing an ended operation held back is retried or reported.
66
+ if (!event.stillCurrent)
67
+ return { status: "abandoned" };
68
+ const retryable = state.status === "speculative" &&
69
+ event.heldFailures.some((failure) => refusedSpeculativeRewraps(event.source, failure));
70
+ return retryable
71
+ ? { status: "fresh" }
72
+ : { status: "failed", unreported: event.heldFailures };
73
+ }
74
+ //# sourceMappingURL=linkSetLegMachine.js.map
@@ -0,0 +1 @@
1
+ {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E,CAClC,yBAAyB,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CACjD,CAAC;IACJ,OAAO,SAAS;QACd,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE;QACrB,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,CAAC,YAAY,EAAE,CAAC;AAC3D,CAAC","sourcesContent":["import type { DocumentLinkAccessEventBody } from \"@tearleads/crypto\";\nimport { DOCUMENT_MUTATION_ERROR_CODES } from \"@tearleads/validators/response\";\nimport type { DocumentLinkSetMutationFailure } from \"../../../data/documents/shared/types\";\n\ntype BlobRewraps = DocumentLinkAccessEventBody[\"blobRewraps\"];\n\n/**\n * Where an attempt's signed rewraps came from. `reused` re-cites the previous\n * leg's envelopes and `skipped` cites none because the local view holds no\n * attachment; neither listed, so the server's binding check may refuse them.\n */\nexport type LinkSetRewrapSource = \"listed\" | \"reused\" | \"skipped\";\n\n/** A submit refusal, with the deferred host report the API client withheld. */\nexport interface LinkSetSubmitFailure extends DocumentLinkSetMutationFailure {\n readonly report?: (() => void) | undefined;\n}\n\n/**\n * One link or unlink leg. The first attempt (`speculative`) may cite rewraps\n * without listing; a refusal of those starts one `fresh` attempt, which lists.\n * A leg ends `committed`, `failed` with the refusals still to report, or\n * `abandoned` when the operation stopped being current, dropping what it held.\n */\nexport type LinkSetLegState =\n | { readonly status: \"speculative\" }\n | { readonly status: \"fresh\" }\n | { readonly status: \"committed\"; readonly rewraps: BlobRewraps | null }\n | {\n readonly status: \"failed\";\n readonly unreported: readonly LinkSetSubmitFailure[];\n }\n | { readonly status: \"abandoned\" };\n\nexport type LinkSetLegEvent =\n | { readonly type: \"attemptCommitted\"; readonly rewraps: BlobRewraps | null }\n | {\n readonly type: \"attemptFailed\";\n /** Refusals of a speculative attempt, held back from the caller. */\n readonly heldFailures: readonly LinkSetSubmitFailure[];\n readonly source: LinkSetRewrapSource | null;\n readonly stillCurrent: boolean;\n };\n\nexport const INITIAL_LINK_SET_LEG_STATE: LinkSetLegState = {\n status: \"speculative\",\n};\n\n/**\n * One attempt of a leg: what it may cite before it prepares, then the source\n * and rewraps it signed. Only a speculative attempt can skip or reuse; a fresh\n * one always lists.\n */\nexport type LinkSetLegAttempt =\n | {\n readonly listing: \"speculative\" | \"fresh\";\n readonly status: \"unprepared\";\n }\n | {\n readonly listing: \"speculative\";\n readonly rewraps: BlobRewraps;\n readonly source: LinkSetRewrapSource;\n readonly status: \"prepared\";\n }\n | {\n readonly listing: \"fresh\";\n readonly rewraps: BlobRewraps;\n readonly source: \"listed\";\n readonly status: \"prepared\";\n };\n\nexport type PreparedLinkSetRewraps =\n | { readonly rewraps: BlobRewraps; readonly source: \"listed\" }\n | {\n readonly rewraps: BlobRewraps;\n readonly source: \"reused\" | \"skipped\";\n };\n\nexport function startLinkSetLegAttempt(\n state: Extract<LinkSetLegState, { status: \"speculative\" | \"fresh\" }>,\n): LinkSetLegAttempt {\n return { listing: state.status, status: \"unprepared\" };\n}\n\n/**\n * Record what an attempt signed, replacing an earlier preparation; a fresh\n * attempt can only have listed.\n */\nexport function recordLinkSetLegRewraps(\n attempt: LinkSetLegAttempt,\n prepared: PreparedLinkSetRewraps,\n): LinkSetLegAttempt {\n if (attempt.listing === \"speculative\")\n return { ...prepared, listing: \"speculative\", status: \"prepared\" };\n if (prepared.source !== \"listed\")\n throw new Error(\"A fresh link-set attempt must list its attachments\");\n return { ...prepared, listing: \"fresh\", status: \"prepared\" };\n}\n\nfunction attemptSource(attempt: LinkSetLegAttempt): LinkSetRewrapSource | null {\n return attempt.status === \"prepared\" ? attempt.source : null;\n}\n\n/** Whether a refusal of this attempt is held back until the leg decides. */\nexport function holdsLinkSetRefusals(attempt: LinkSetLegAttempt): boolean {\n return isSpeculativeRewrapSource(attemptSource(attempt));\n}\n\n/** The event an attempt's result raises. */\nexport function linkSetAttemptEvent(input: {\n readonly attempt: LinkSetLegAttempt;\n readonly committed: boolean;\n readonly heldFailures: readonly LinkSetSubmitFailure[];\n readonly stillCurrent: boolean;\n}): LinkSetLegEvent {\n const rewraps =\n input.attempt.status === \"prepared\" ? input.attempt.rewraps : null;\n return input.committed\n ? { rewraps, type: \"attemptCommitted\" }\n : {\n heldFailures: input.heldFailures,\n source: attemptSource(input.attempt),\n stillCurrent: input.stillCurrent,\n type: \"attemptFailed\",\n };\n}\n\nfunction isSpeculativeRewrapSource(\n source: LinkSetRewrapSource | null,\n): boolean {\n return source === \"reused\" || source === \"skipped\";\n}\n\n/**\n * The server's binding check refused rewraps cited without listing: the coded\n * attachment-set refusal (`lockDocumentLinkBlobRewraps`), or for re-cited\n * envelopes the uncoded content-key epoch refusal the current server returns\n * per cited blob (`rewrapDocumentBlobContentKeyInTransaction`). A skipped\n * attempt cites no blob, so only the coded refusal can answer it.\n */\nfunction refusedSpeculativeRewraps(\n source: LinkSetRewrapSource | null,\n failure: DocumentLinkSetMutationFailure,\n): boolean {\n if (failure.status !== 409 || !isSpeculativeRewrapSource(source))\n return false;\n if (failure.code === DOCUMENT_MUTATION_ERROR_CODES.linkAttachmentsChanged)\n return true;\n return source === \"reused\" && failure.code === undefined;\n}\n\n/**\n * Only a speculative attempt the binding check refused retries, and only\n * once: the fresh attempt lists, so it cannot be refused for the same stale\n * view again. Any other refusal keeps its own recovery path.\n */\nexport function transitionLinkSetLeg(\n state: LinkSetLegState,\n event: LinkSetLegEvent,\n): LinkSetLegState {\n if (state.status !== \"speculative\" && state.status !== \"fresh\") return state;\n if (event.type === \"attemptCommitted\")\n return { rewraps: event.rewraps, status: \"committed\" };\n // Nothing an ended operation held back is retried or reported.\n if (!event.stillCurrent) return { status: \"abandoned\" };\n const retryable =\n state.status === \"speculative\" &&\n event.heldFailures.some((failure) =>\n refusedSpeculativeRewraps(event.source, failure),\n );\n return retryable\n ? { status: \"fresh\" }\n : { status: \"failed\", unreported: event.heldFailures };\n}\n"]}
@@ -23,9 +23,9 @@ export interface RelinkRemoteDocumentRequest {
23
23
  warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
24
24
  }
25
25
  /**
26
- * A leg that re-cited the previous leg's envelopes and was refused with an
27
- * uncoded 409 (the attachment set or its key epoch moved) lists and retries
28
- * once, as a leg without reuse would have; that first failure is not
29
- * reported.
26
+ * A leg that cited rewraps without listing and was refused because the
27
+ * attachment set (or a re-cited key epoch) moved lists and retries once, as a
28
+ * leg that listed would have; that first refusal is neither reported nor
29
+ * retried once the operation is no longer current (`transitionLinkSetLeg`).
30
30
  */
31
31
  export declare function relinkRemoteDocument(remote: RemoteDocumentCollaborators, request: RelinkRemoteDocumentRequest): Promise<RelinkRemoteDocumentResult | null>;
@@ -1,32 +1,50 @@
1
1
  import { acknowledgedDocumentLinkSetMutation, persistedDocumentStateFromAcknowledgement, } from "../../../data/documents/shared/responses.js";
2
2
  import { acknowledgeDocumentMutation } from "../../../data/documents/shared/sync/mutationAcknowledgement.js";
3
3
  import { nullOnProjectionVerificationCancellation, requireProjectionUserKeyResolver, } from "../../../data/keyingProjectionVerification/index.js";
4
+ import { documentMayHaveAttachments } from "../../../data/persistence/documents/documentAttachmentPresence.js";
4
5
  import { recordDocumentAuthorAccessFailure } from "../authorAccessFailure.js";
5
6
  import { completeLinkSetMutationRequest } from "../rotationBaseline.js";
6
7
  import { buildMaterializedDocumentLinkSetMutationPlan } from "./index.js";
7
8
  import { prepareDocumentLinkBlobRewraps, reuseCommittedBlobRewraps, } from "./linkSetBlobRewraps.js";
9
+ import { holdsLinkSetRefusals, INITIAL_LINK_SET_LEG_STATE, linkSetAttemptEvent, recordLinkSetLegRewraps, startLinkSetLegAttempt, transitionLinkSetLeg, } from "./linkSetLegMachine.js";
8
10
  import { seedLinkSetWriterProjection } from "./linkSetProjectionSeed.js";
9
11
  async function submitLinkSetMutation(input) {
10
12
  if (input.stillCurrent?.() === false)
11
13
  return null;
12
14
  const { apiClient } = input;
13
- // Preserve the HTTP failure for the durable move-intent queue.
15
+ // Preserve the HTTP failure for the durable move-intent queue. Its host
16
+ // report waits until the leg knows the refusal is not one it recovers from.
14
17
  const resultFn = input.operation === "link"
15
18
  ? apiClient.linkDocumentResult.bind(apiClient)
16
19
  : apiClient.unlinkDocumentResult.bind(apiClient);
17
20
  const result = await resultFn(input.documentId, input.request, {
18
21
  expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,
22
+ reportErrors: false,
19
23
  });
20
24
  if (result.ok) {
21
25
  return result.data;
22
26
  }
23
- input.onFailure?.({
27
+ // A refusal the operation no longer waits for is neither retried nor
28
+ // reported.
29
+ if (input.stillCurrent?.() === false)
30
+ return null;
31
+ input.onFailure({
24
32
  code: result.code,
25
33
  message: result.message,
34
+ report: result.report,
26
35
  status: result.status,
27
36
  });
28
37
  return null;
29
38
  }
39
+ /** Hand a refusal the leg does not recover from to its host and caller. */
40
+ function reportLinkSetFailure(input, failure) {
41
+ failure.report?.();
42
+ input.onFailure?.({
43
+ code: failure.code,
44
+ message: failure.message,
45
+ status: failure.status,
46
+ });
47
+ }
30
48
  // Cold-cache projection fetches must keep their HTTP status: collapsing a
31
49
  // 403 to null would leave an access-denied link/unlink routinely retriable
32
50
  // instead of parking its move for the access-restored signal (row 7).
@@ -35,11 +53,11 @@ async function fetchLinkSetProjection(input) {
35
53
  if (result.ok) {
36
54
  return { failure: null, projection: result.data };
37
55
  }
38
- result.report();
39
56
  return {
40
57
  failure: {
41
58
  code: result.code,
42
59
  message: result.message,
60
+ report: result.report,
43
61
  status: result.status,
44
62
  },
45
63
  projection: null,
@@ -88,10 +106,10 @@ async function completeRemoteDocumentLinkSet(input) {
88
106
  };
89
107
  }
90
108
  /**
91
- * A leg that re-cited the previous leg's envelopes and was refused with an
92
- * uncoded 409 (the attachment set or its key epoch moved) lists and retries
93
- * once, as a leg without reuse would have; that first failure is not
94
- * reported.
109
+ * A leg that cited rewraps without listing and was refused because the
110
+ * attachment set (or a re-cited key epoch) moved lists and retries once, as a
111
+ * leg that listed would have; that first refusal is neither reported nor
112
+ * retried once the operation is no longer current (`transitionLinkSetLeg`).
95
113
  */
96
114
  export async function relinkRemoteDocument(remote, request) {
97
115
  if (!remote.encapsulationSecretKey) {
@@ -104,35 +122,38 @@ export async function relinkRemoteDocument(remote, request) {
104
122
  targetSecretKey: remote.encapsulationSecretKey,
105
123
  };
106
124
  const reuse = input.attachmentReuse;
107
- const failures = [];
108
- const attempt = { reused: false, rewraps: null };
109
- const result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {
110
- if (attempt.reused)
111
- failures.push(failure);
112
- else
113
- input.onFailure?.(failure);
114
- }).catch((error) => {
115
- // A leg that threw may have committed before failing: list again next.
125
+ let leg = INITIAL_LINK_SET_LEG_STATE;
126
+ let result = null;
127
+ while (leg.status === "speculative" || leg.status === "fresh") {
128
+ const attempt = { current: startLinkSetLegAttempt(leg) };
129
+ const heldFailures = [];
130
+ result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {
131
+ if (holdsLinkSetRefusals(attempt.current))
132
+ heldFailures.push(failure);
133
+ else
134
+ reportLinkSetFailure(input, failure);
135
+ }).catch((error) => {
136
+ // A leg that threw may have committed before failing: list again next.
137
+ if (reuse)
138
+ reuse.committed = null;
139
+ throw error;
140
+ });
141
+ const event = linkSetAttemptEvent({
142
+ attempt: attempt.current,
143
+ committed: result !== null,
144
+ heldFailures,
145
+ stillCurrent: input.stillCurrent?.() !== false,
146
+ });
116
147
  if (reuse)
117
- reuse.committed = null;
118
- throw error;
119
- });
120
- if (reuse)
121
- reuse.committed = result ? attempt.rewraps : null;
122
- if (result || !attempt.reused)
123
- return result;
124
- // The attachment-set and key-epoch refusals are uncoded 409s; a coded one
125
- // (stale state, an unavailable container) keeps its own recovery path.
126
- if (!failures.some((failure) => failure.status === 409 && failure.code === undefined)) {
127
- for (const failure of failures)
128
- input.onFailure?.(failure);
129
- return null;
148
+ reuse.committed =
149
+ event.type === "attemptCommitted" ? event.rewraps : null;
150
+ leg = transitionLinkSetLeg(leg, event);
151
+ }
152
+ if (leg.status === "failed") {
153
+ for (const failure of leg.unreported)
154
+ reportLinkSetFailure(input, failure);
130
155
  }
131
- const retry = { reused: false, rewraps: null };
132
- const retried = await relinkRemoteDocumentOnce(input, retry, (failure) => input.onFailure?.(failure));
133
- if (reuse)
134
- reuse.committed = retried ? retry.rewraps : null;
135
- return retried;
156
+ return result;
136
157
  }
137
158
  async function relinkRemoteDocumentOnce(input, attempt, onSubmitFailure) {
138
159
  if (input.operation === "unlink" && !input.rotationSnapshot) {
@@ -144,11 +165,14 @@ async function relinkRemoteDocumentOnce(input, attempt, onSubmitFailure) {
144
165
  fetchLinkSetContainerProjection(input.apiClient, input.targetContainerId),
145
166
  ]);
146
167
  if (!writerFetch.projection || !targetContainerFetch.projection) {
168
+ // A failure the operation no longer waits for is not reported.
169
+ if (input.stillCurrent?.() === false)
170
+ return null;
147
171
  for (const failure of orderedProjectionFailures([
148
172
  writerFetch.failure,
149
173
  targetContainerFetch.failure,
150
174
  ])) {
151
- input.onFailure?.(failure);
175
+ reportLinkSetFailure(input, failure);
152
176
  }
153
177
  return null;
154
178
  }
@@ -209,26 +233,46 @@ function orderedProjectionFailures(failures) {
209
233
  ...present.filter((failure) => failure.status === 403),
210
234
  ];
211
235
  }
236
+ /**
237
+ * Rewraps a first attempt may sign without listing: the previous leg's
238
+ * envelopes, or none when the local view holds no attachment for the
239
+ * document. The server's binding check at commit refuses either if stale.
240
+ */
241
+ async function speculativeBlobRewraps(input, writerProjection, targets) {
242
+ const committed = input.attachmentReuse?.committed;
243
+ if (committed) {
244
+ const reused = reuseCommittedBlobRewraps({
245
+ committed,
246
+ documentId: writerProjection.documentId,
247
+ targets,
248
+ });
249
+ if (reused)
250
+ return { rewraps: reused, source: "reused" };
251
+ // The previous leg cited attachments this leg cannot re-cite: list them.
252
+ if (committed.length > 0)
253
+ return null;
254
+ }
255
+ if (await documentMayHaveAttachments(input.execSql, writerProjection.documentId))
256
+ return null;
257
+ return { rewraps: [], source: "skipped" };
258
+ }
212
259
  function prepareRemoteLinkSetMutation(input, writerProjection, targetContainerProjection, attempt) {
213
260
  const prepareBlobRewraps = async (targets) => {
214
- const committed = input.attachmentReuse?.committed;
215
- const reused = committed
216
- ? reuseCommittedBlobRewraps({
217
- committed,
218
- documentId: writerProjection.documentId,
261
+ const prepared = (attempt.current.listing ===
262
+ "speculative"
263
+ ? await speculativeBlobRewraps(input, writerProjection, targets)
264
+ : null) ?? {
265
+ rewraps: await prepareDocumentLinkBlobRewraps({
266
+ ...input,
267
+ refreshListing: attempt.current.listing === "fresh",
219
268
  targets,
220
- })
221
- : null;
222
- attempt.reused = reused !== null;
223
- attempt.rewraps =
224
- reused ??
225
- (await prepareDocumentLinkBlobRewraps({
226
- ...input,
227
- targets,
228
- targetContainerProjection,
229
- writerProjection,
230
- }));
231
- return attempt.rewraps;
269
+ targetContainerProjection,
270
+ writerProjection,
271
+ }),
272
+ source: "listed",
273
+ };
274
+ attempt.current = recordLinkSetLegRewraps(attempt.current, prepared);
275
+ return prepared.rewraps;
232
276
  };
233
277
  return recordDocumentAuthorAccessFailure(() => nullOnProjectionVerificationCancellation(() => buildMaterializedDocumentLinkSetMutationPlan({
234
278
  author: input.author,