@tearleads/client-sdk 0.1.239 → 0.1.241
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/data/documents/shared/sync/syncResponseAuthorization.js +12 -1
- package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -1
- package/data/documents/shared/sync/syncResponses.js +2 -2
- package/data/documents/shared/sync/syncResponses.js.map +1 -1
- package/data/documents/shared/types.d.ts +5 -1
- package/data/documents/shared/types.js.map +1 -1
- package/data/persistence/documents/documentAttachmentPresence.js +44 -0
- package/data/persistence/documents/documentAttachmentPresence.js.map +1 -0
- package/internal/api-client/ApiClient.d.ts +7 -7
- package/internal/api-client/client/apiClientContext.d.ts +1 -1
- package/internal/api-client/client/blobs.d.ts +1 -1
- package/internal/api-client/client/documents.d.ts +6 -6
- package/internal/validators/operation/attachments.d.ts +2 -2
- package/internal/validators/operation/containerMutations.d.ts +16 -16
- package/internal/validators/operation/documentMutations.d.ts +20 -20
- package/internal/validators/operation/documentSync.d.ts +24 -24
- package/internal/validators/response/blob.d.ts +6 -6
- package/internal/validators/response/blob.js +12 -2
- package/internal/validators/response/blob.js.map +1 -1
- package/internal/validators/response/containerMutationError.d.ts +2 -2
- package/internal/validators/response/documentMutationError.d.ts +3 -2
- package/internal/validators/response/documentMutationError.js +5 -0
- package/internal/validators/response/documentMutationError.js.map +1 -1
- package/internal/validators/response/documentSyncSchema.d.ts +48 -48
- package/internal/validators/response/documentSyncSchema.js +1 -1
- package/internal/validators/response/documentSyncSchema.js.map +1 -1
- package/package.json +1 -1
- package/workflows/blobs/hydration/decrypt.js +17 -1
- package/workflows/blobs/hydration/decrypt.js.map +1 -1
- package/workflows/documents/linkSet/linkSetBlobRewraps.d.ts +10 -4
- package/workflows/documents/linkSet/linkSetBlobRewraps.js +23 -11
- package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -1
- package/workflows/documents/linkSet/linkSetLegMachine.js +74 -0
- package/workflows/documents/linkSet/linkSetLegMachine.js.map +1 -0
- package/workflows/documents/linkSet/linkSetRemote.d.ts +4 -4
- package/workflows/documents/linkSet/linkSetRemote.js +96 -52
- package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
|
@@ -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
|
|
22
|
-
*
|
|
23
|
-
*
|
|
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
|
-
/**
|
|
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
|
|
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,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AAG,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, 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,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;;;;;;;;;GASG;AACH,MAAM,UAAU,yBAAyB,CAAC,KAIzC;IACC,MAAM,OAAO,GAAiB,EAAE,CAAC;IACjC,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;QACrC,MAAM,UAAU,GAAG;YACjB,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,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AC,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
|
+
{"version":3,"file":"lin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AyB,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
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
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
|
-
|
|
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
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
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
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
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 =
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
215
|
-
|
|
216
|
-
?
|
|
217
|
-
|
|
218
|
-
|
|
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
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
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,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkSetRemote.js","sourceRoot":"","sources":["linkSetRemote.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,mCAAmC,EACnC,yCAAyC,GAC1C,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,2BAA2B,EAAE,MAAM,6DAA6D,CAAC;AAU1G,OAAO,EACL,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,iCAAiC,EAAE,MAAM,wBAAwB,CAAC;AAG3E,OAAO,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,4CAA4C,EAAE,MAAM,SAAS,CAAC;AACvE,OAAO,EAEL,8BAA8B,EAC9B,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAEtE,KAAK,UAAU,qBAAqB,CAAC,KAQpC;IACC,IAAI,KAAK,CAAC,YA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AQ,EAAE,KAAK,CAAC,QAAQ;QACxB,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,yBAAyB;QACzB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,+BAA+B,EAC7B,KAAK,CAAC,+BAA+B;QACvC,gBAAgB;KACjB,CAAC,CACH,EACH,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type { DocumentLinkSetMutationRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n acknowledgedDocumentLinkSetMutation,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../data/documents/shared/responses\";\nimport { acknowledgeDocumentMutation } from \"../../../data/documents/shared/sync/mutationAcknowledgement\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationApi,\n DocumentLinkSetMutationFailure,\n DocumentLinkSetMutationOperation,\n RelinkRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { recordDocumentAuthorAccessFailure } from \"../authorAccessFailure\";\nimport type { SubtreePurgeRoot } from \"../purge/subtreePurgeScope\";\nimport type { RemoteDocumentCollaborators } from \"../remote/remoteDocumentCollaborators\";\nimport { completeLinkSetMutationRequest } from \"../rotationBaseline\";\nimport { buildMaterializedDocumentLinkSetMutationPlan } from \"./index\";\nimport {\n type LinkSetAttachmentReuse,\n prepareDocumentLinkBlobRewraps,\n reuseCommittedBlobRewraps,\n} from \"./linkSetBlobRewraps\";\nimport { seedLinkSetWriterProjection } from \"./linkSetProjectionSeed\";\n\nasync function submitLinkSetMutation(input: {\n apiClient: DocumentLinkSetMutationApi;\n documentId: string;\n expectedOrganizationId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<DocumentLinkSetMutationResponse | null> {\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input;\n // Preserve the HTTP failure for the durable move-intent queue.\n const resultFn =\n input.operation === \"link\"\n ? apiClient.linkDocumentResult.bind(apiClient)\n : apiClient.unlinkDocumentResult.bind(apiClient);\n const result = await resultFn(input.documentId, input.request, {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n });\n if (result.ok) {\n return result.data;\n }\n input.onFailure?.({\n code: result.code,\n message: result.message,\n status: result.status,\n });\n return null;\n}\n\ninterface LinkSetProjectionFetch<TProjection> {\n failure: DocumentLinkSetMutationFailure | null;\n projection: TProjection | null;\n}\n\n// Cold-cache projection fetches must keep their HTTP status: collapsing a\n// 403 to null would leave an access-denied link/unlink routinely retriable\n// instead of parking its move for the access-restored signal (row 7).\nasync function fetchLinkSetProjection<TProjection>(input: {\n fetchProjectionResult: () => Promise<\n | { readonly data: TProjection; readonly ok: true }\n | DocumentSyncSubmitFailure\n >;\n}): Promise<LinkSetProjectionFetch<TProjection>> {\n const result = await input.fetchProjectionResult();\n if (result.ok) {\n return { failure: null, projection: result.data };\n }\n result.report();\n return {\n failure: {\n code: result.code,\n message: result.message,\n status: result.status,\n },\n projection: null,\n };\n}\n\nfunction fetchLinkSetDocumentProjection(\n apiClient: DocumentLinkSetMutationApi,\n documentId: string,\n): Promise<LinkSetProjectionFetch<DocumentWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getDocumentWriterProjectionResult.bind(\n apiClient,\n documentId,\n { reportErrors: false },\n ),\n });\n}\n\nfunction fetchLinkSetContainerProjection(\n apiClient: DocumentLinkSetMutationApi,\n containerId: string,\n): Promise<LinkSetProjectionFetch<ContainerWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getContainerWriterProjectionResult.bind(\n apiClient,\n containerId,\n { reportErrors: false },\n ),\n });\n}\n\nasync function completeRemoteDocumentLinkSet(input: {\n completedPlan: Parameters<typeof acknowledgedDocumentLinkSetMutation>[0];\n execSql: ExecSql;\n materializedPlan: Awaited<\n ReturnType<typeof buildMaterializedDocumentLinkSetMutationPlan>\n >;\n operation: DocumentLinkSetMutationOperation;\n response: DocumentLinkSetMutationResponse;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n apiClient: DocumentLinkSetMutationApi;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const acknowledged = acknowledgedDocumentLinkSetMutation(\n input.completedPlan,\n input.response,\n );\n const persistedState =\n persistedDocumentStateFromAcknowledgement(acknowledged);\n await acknowledgeDocumentMutation({\n execSql: input.execSql,\n plan: input.completedPlan,\n stillCurrent: input.stillCurrent,\n });\n await seedLinkSetWriterProjection({\n apiClient: input.apiClient,\n execSql: input.execSql,\n operation: input.operation,\n priorProjection: input.writerProjection,\n response: acknowledged,\n targetContainerId: input.targetContainerId,\n targetContainerProjection: input.targetContainerProjection,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n return {\n contentKey: input.materializedPlan.contentKey,\n contentKeyRotated: input.materializedPlan.contentKeyRotated,\n documentId: input.response.id,\n linkedContainerIds: [\n ...input.materializedPlan.plan.state.linkedContainerIds,\n ],\n persistedState,\n plan: input.completedPlan,\n response: input.response,\n };\n}\n\n/** What varies per link or unlink leg; the collaborators bind the rest. */\nexport interface RelinkRemoteDocumentRequest {\n /** Shared by the legs of one move or trash workflow. */\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n author: DocumentCreateAuthor;\n contentKey?: Uint8Array | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n eventId?: string | undefined;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: DocumentLinkSetMutationOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RelinkRemoteDocumentInput extends RelinkRemoteDocumentRequest {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetSecretKey: Uint8Array;\n}\n\n/** What one leg signed, so the workflow can reuse or retry it. */\ninterface LinkSetLegAttempt {\n rewraps: DocumentLinkAccessEventBody[\"blobRewraps\"] | null;\n reused: boolean;\n}\n\n/**\n * A leg that re-cited the previous leg's envelopes and was refused with an\n * uncoded 409 (the attachment set or its key epoch moved) lists and retries\n * once, as a leg without reuse would have; that first failure is not\n * reported.\n */\nexport async function relinkRemoteDocument(\n remote: RemoteDocumentCollaborators,\n request: RelinkRemoteDocumentRequest,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (!remote.encapsulationSecretKey) {\n throw new Error(\n \"Remote document link-set mutation requires an encapsulation key\",\n );\n }\n const input: RelinkRemoteDocumentInput = {\n ...request,\n apiClient: remote.api,\n execSql: remote.execSql,\n targetSecretKey: remote.encapsulationSecretKey,\n };\n const reuse = input.attachmentReuse;\n const failures: DocumentLinkSetMutationFailure[] = [];\n const attempt: LinkSetLegAttempt = { reused: false, rewraps: null };\n const result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {\n if (attempt.reused) failures.push(failure);\n else input.onFailure?.(failure);\n }).catch((error: unknown) => {\n // A leg that threw may have committed before failing: list again next.\n if (reuse) reuse.committed = null;\n throw error;\n });\n if (reuse) reuse.committed = result ? attempt.rewraps : null;\n if (result || !attempt.reused) return result;\n // The attachment-set and key-epoch refusals are uncoded 409s; a coded one\n // (stale state, an unavailable container) keeps its own recovery path.\n if (\n !failures.some(\n (failure) => failure.status === 409 && failure.code === undefined,\n )\n ) {\n for (const failure of failures) input.onFailure?.(failure);\n return null;\n }\n const retry: LinkSetLegAttempt = { reused: false, rewraps: null };\n const retried = await relinkRemoteDocumentOnce(input, retry, (failure) =>\n input.onFailure?.(failure),\n );\n if (reuse) reuse.committed = retried ? retry.rewraps : null;\n return retried;\n}\n\nasync function relinkRemoteDocumentOnce(\n input: RelinkRemoteDocumentInput,\n attempt: LinkSetLegAttempt,\n onSubmitFailure: DocumentLinkSetFailureHandler,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (input.operation === \"unlink\" && !input.rotationSnapshot) {\n throw new Error(\n \"Document unlink requires a proven full-history rotation snapshot\",\n );\n }\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document link-set mutation\",\n );\n const [writerFetch, targetContainerFetch] = await Promise.all([\n fetchLinkSetDocumentProjection(input.apiClient, input.documentId),\n fetchLinkSetContainerProjection(input.apiClient, input.targetContainerId),\n ]);\n if (!writerFetch.projection || !targetContainerFetch.projection) {\n for (const failure of orderedProjectionFailures([\n writerFetch.failure,\n targetContainerFetch.failure,\n ])) {\n input.onFailure?.(failure);\n }\n return null;\n }\n const writerProjection = writerFetch.projection;\n const targetContainerProjection = targetContainerFetch.projection;\n if (input.stillCurrent?.() === false) return null;\n\n const signedAt = input.signedAt ?? new Date().toISOString();\n const materializedPlan = await prepareRemoteLinkSetMutation(\n { ...input, resolveProjectionUserKey, signedAt },\n writerProjection,\n targetContainerProjection,\n attempt,\n );\n if (!materializedPlan) return null;\n const request = await completeLinkSetMutationRequest({\n author: input.author,\n materializedPlan,\n operation: input.operation,\n rotationSnapshot: input.rotationSnapshot,\n signedAt,\n });\n const completedPlan = { ...materializedPlan.plan, request };\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n const response = await submitLinkSetMutation({\n apiClient: input.apiClient,\n documentId: completedPlan.documentId,\n expectedOrganizationId: completedPlan.state.organizationId,\n onFailure: onSubmitFailure,\n operation: input.operation,\n request: completedPlan.request,\n stillCurrent: input.stillCurrent,\n });\n if (!response) {\n return null;\n }\n if (input.stillCurrent?.() === false) return null;\n return completeRemoteDocumentLinkSet({\n apiClient: input.apiClient,\n completedPlan,\n execSql: input.execSql,\n materializedPlan,\n operation: input.operation,\n response,\n stillCurrent: input.stillCurrent,\n targetContainerId: input.targetContainerId,\n targetContainerProjection,\n writerProjection,\n });\n}\n\n// Every projection failure reaches the handler: the queued-move accumulator\n// classifies a vanished container from ANY coded container 404, so a document\n// fetch failure must not hide a container one (or vice versa). A 403 is\n// delivered last, so a single-slot consumer keeps the denial that parks the\n// move (row 7) while the accumulator still sees both.\nfunction orderedProjectionFailures(\n failures: readonly (DocumentLinkSetMutationFailure | null)[],\n): DocumentLinkSetMutationFailure[] {\n const present = failures.filter(\n (failure): failure is DocumentLinkSetMutationFailure => failure !== null,\n );\n return [\n ...present.filter((failure) => failure.status !== 403),\n ...present.filter((failure) => failure.status === 403),\n ];\n}\n\nfunction prepareRemoteLinkSetMutation(\n input: RelinkRemoteDocumentInput & {\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt: string;\n },\n writerProjection: DocumentWriterProjectionResponse,\n targetContainerProjection: ContainerWriterProjectionResponse,\n attempt: LinkSetLegAttempt,\n) {\n const prepareBlobRewraps = async (\n targets: readonly DocumentContentKeyTarget[],\n ) => {\n const committed = input.attachmentReuse?.committed;\n const reused = committed\n ? reuseCommittedBlobRewraps({\n committed,\n documentId: writerProjection.documentId,\n targets,\n })\n : null;\n attempt.reused = reused !== null;\n attempt.rewraps =\n reused ??\n (await prepareDocumentLinkBlobRewraps({\n ...input,\n targets,\n targetContainerProjection,\n writerProjection,\n }));\n return attempt.rewraps;\n };\n return recordDocumentAuthorAccessFailure(\n () =>\n nullOnProjectionVerificationCancellation(() =>\n buildMaterializedDocumentLinkSetMutationPlan({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n prepareBlobRewraps,\n contentKey: input.contentKey,\n eventId: input.eventId,\n execSql: input.execSql,\n operation: input.operation,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetContainerProjection,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n writerProjection,\n }),\n ),\n input.onFailure,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"linkSetRemote.js","sourceRoot":"","sources":["linkSetRemote.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,mCAAmC,EACnC,yCAAyC,GAC1C,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,2BAA2B,EAAE,MAAM,6DAA6D,CAAC;AAS1G,OAAO,EACL,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAE5G,OAAO,EAAE,iCAAiC,EAAE,MAAM,wBAAwB,CAAC;AAG3E,OAAO,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,4CAA4C,EAAE,MAAM,SAAS,CAAC;AACvE,OAAO,EAEL,8BAA8B,EAC9B,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,oBAAoB,EACpB,0BAA0B,EAG1B,mBAAmB,EAEnB,uBAAuB,EACvB,sBAAsB,EACtB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAEtE,KAAK,UAAU,qBAAqB,CAAC,KAQpC;IACC,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAA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ACtC,+BAA+B,EAC7B,KAAK,CAAC,+BAA+B;QACvC,gBAAgB;KACjB,CAAC,CACH,EACH,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type { DocumentLinkSetMutationRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n acknowledgedDocumentLinkSetMutation,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../data/documents/shared/responses\";\nimport { acknowledgeDocumentMutation } from \"../../../data/documents/shared/sync/mutationAcknowledgement\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationApi,\n DocumentLinkSetMutationOperation,\n RelinkRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { documentMayHaveAttachments } from \"../../../data/persistence/documents/documentAttachmentPresence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { recordDocumentAuthorAccessFailure } from \"../authorAccessFailure\";\nimport type { SubtreePurgeRoot } from \"../purge/subtreePurgeScope\";\nimport type { RemoteDocumentCollaborators } from \"../remote/remoteDocumentCollaborators\";\nimport { completeLinkSetMutationRequest } from \"../rotationBaseline\";\nimport { buildMaterializedDocumentLinkSetMutationPlan } from \"./index\";\nimport {\n type LinkSetAttachmentReuse,\n prepareDocumentLinkBlobRewraps,\n reuseCommittedBlobRewraps,\n} from \"./linkSetBlobRewraps\";\nimport {\n holdsLinkSetRefusals,\n INITIAL_LINK_SET_LEG_STATE,\n type LinkSetLegAttempt,\n type LinkSetSubmitFailure,\n linkSetAttemptEvent,\n type PreparedLinkSetRewraps,\n recordLinkSetLegRewraps,\n startLinkSetLegAttempt,\n transitionLinkSetLeg,\n} from \"./linkSetLegMachine\";\nimport { seedLinkSetWriterProjection } from \"./linkSetProjectionSeed\";\n\nasync function submitLinkSetMutation(input: {\n apiClient: DocumentLinkSetMutationApi;\n documentId: string;\n expectedOrganizationId: string;\n onFailure: (failure: LinkSetSubmitFailure) => void;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<DocumentLinkSetMutationResponse | null> {\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input;\n // Preserve the HTTP failure for the durable move-intent queue. Its host\n // report waits until the leg knows the refusal is not one it recovers from.\n const resultFn =\n input.operation === \"link\"\n ? apiClient.linkDocumentResult.bind(apiClient)\n : apiClient.unlinkDocumentResult.bind(apiClient);\n const result = await resultFn(input.documentId, input.request, {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n reportErrors: false,\n });\n if (result.ok) {\n return result.data;\n }\n // A refusal the operation no longer waits for is neither retried nor\n // reported.\n if (input.stillCurrent?.() === false) return null;\n input.onFailure({\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n });\n return null;\n}\n\n/** Hand a refusal the leg does not recover from to its host and caller. */\nfunction reportLinkSetFailure(\n input: Pick<RelinkRemoteDocumentInput, \"onFailure\">,\n failure: LinkSetSubmitFailure,\n): void {\n failure.report?.();\n input.onFailure?.({\n code: failure.code,\n message: failure.message,\n status: failure.status,\n });\n}\n\ninterface LinkSetProjectionFetch<TProjection> {\n failure: LinkSetSubmitFailure | null;\n projection: TProjection | null;\n}\n\n// Cold-cache projection fetches must keep their HTTP status: collapsing a\n// 403 to null would leave an access-denied link/unlink routinely retriable\n// instead of parking its move for the access-restored signal (row 7).\nasync function fetchLinkSetProjection<TProjection>(input: {\n fetchProjectionResult: () => Promise<\n | { readonly data: TProjection; readonly ok: true }\n | DocumentSyncSubmitFailure\n >;\n}): Promise<LinkSetProjectionFetch<TProjection>> {\n const result = await input.fetchProjectionResult();\n if (result.ok) {\n return { failure: null, projection: result.data };\n }\n return {\n failure: {\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n },\n projection: null,\n };\n}\n\nfunction fetchLinkSetDocumentProjection(\n apiClient: DocumentLinkSetMutationApi,\n documentId: string,\n): Promise<LinkSetProjectionFetch<DocumentWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getDocumentWriterProjectionResult.bind(\n apiClient,\n documentId,\n { reportErrors: false },\n ),\n });\n}\n\nfunction fetchLinkSetContainerProjection(\n apiClient: DocumentLinkSetMutationApi,\n containerId: string,\n): Promise<LinkSetProjectionFetch<ContainerWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getContainerWriterProjectionResult.bind(\n apiClient,\n containerId,\n { reportErrors: false },\n ),\n });\n}\n\nasync function completeRemoteDocumentLinkSet(input: {\n completedPlan: Parameters<typeof acknowledgedDocumentLinkSetMutation>[0];\n execSql: ExecSql;\n materializedPlan: Awaited<\n ReturnType<typeof buildMaterializedDocumentLinkSetMutationPlan>\n >;\n operation: DocumentLinkSetMutationOperation;\n response: DocumentLinkSetMutationResponse;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n apiClient: DocumentLinkSetMutationApi;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const acknowledged = acknowledgedDocumentLinkSetMutation(\n input.completedPlan,\n input.response,\n );\n const persistedState =\n persistedDocumentStateFromAcknowledgement(acknowledged);\n await acknowledgeDocumentMutation({\n execSql: input.execSql,\n plan: input.completedPlan,\n stillCurrent: input.stillCurrent,\n });\n await seedLinkSetWriterProjection({\n apiClient: input.apiClient,\n execSql: input.execSql,\n operation: input.operation,\n priorProjection: input.writerProjection,\n response: acknowledged,\n targetContainerId: input.targetContainerId,\n targetContainerProjection: input.targetContainerProjection,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n return {\n contentKey: input.materializedPlan.contentKey,\n contentKeyRotated: input.materializedPlan.contentKeyRotated,\n documentId: input.response.id,\n linkedContainerIds: [\n ...input.materializedPlan.plan.state.linkedContainerIds,\n ],\n persistedState,\n plan: input.completedPlan,\n response: input.response,\n };\n}\n\n/** What varies per link or unlink leg; the collaborators bind the rest. */\nexport interface RelinkRemoteDocumentRequest {\n /** Shared by the legs of one move or trash workflow. */\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n author: DocumentCreateAuthor;\n contentKey?: Uint8Array | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n eventId?: string | undefined;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: DocumentLinkSetMutationOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RelinkRemoteDocumentInput extends RelinkRemoteDocumentRequest {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetSecretKey: Uint8Array;\n}\n\n/**\n * A leg that cited rewraps without listing and was refused because the\n * attachment set (or a re-cited key epoch) moved lists and retries once, as a\n * leg that listed would have; that first refusal is neither reported nor\n * retried once the operation is no longer current (`transitionLinkSetLeg`).\n */\nexport async function relinkRemoteDocument(\n remote: RemoteDocumentCollaborators,\n request: RelinkRemoteDocumentRequest,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (!remote.encapsulationSecretKey) {\n throw new Error(\n \"Remote document link-set mutation requires an encapsulation key\",\n );\n }\n const input: RelinkRemoteDocumentInput = {\n ...request,\n apiClient: remote.api,\n execSql: remote.execSql,\n targetSecretKey: remote.encapsulationSecretKey,\n };\n const reuse = input.attachmentReuse;\n let leg = INITIAL_LINK_SET_LEG_STATE;\n let result: RelinkRemoteDocumentResult | null = null;\n while (leg.status === \"speculative\" || leg.status === \"fresh\") {\n const attempt = { current: startLinkSetLegAttempt(leg) };\n const heldFailures: LinkSetSubmitFailure[] = [];\n result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {\n if (holdsLinkSetRefusals(attempt.current)) heldFailures.push(failure);\n else reportLinkSetFailure(input, failure);\n }).catch((error: unknown) => {\n // A leg that threw may have committed before failing: list again next.\n if (reuse) reuse.committed = null;\n throw error;\n });\n const event = linkSetAttemptEvent({\n attempt: attempt.current,\n committed: result !== null,\n heldFailures,\n stillCurrent: input.stillCurrent?.() !== false,\n });\n if (reuse)\n reuse.committed =\n event.type === \"attemptCommitted\" ? event.rewraps : null;\n leg = transitionLinkSetLeg(leg, event);\n }\n if (leg.status === \"failed\") {\n for (const failure of leg.unreported) reportLinkSetFailure(input, failure);\n }\n return result;\n}\n\n/** The attempt in flight; preparation replaces it with what it signed. */\ninterface LinkSetAttemptSlot {\n current: LinkSetLegAttempt;\n}\n\nasync function relinkRemoteDocumentOnce(\n input: RelinkRemoteDocumentInput,\n attempt: LinkSetAttemptSlot,\n onSubmitFailure: (failure: LinkSetSubmitFailure) => void,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (input.operation === \"unlink\" && !input.rotationSnapshot) {\n throw new Error(\n \"Document unlink requires a proven full-history rotation snapshot\",\n );\n }\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document link-set mutation\",\n );\n const [writerFetch, targetContainerFetch] = await Promise.all([\n fetchLinkSetDocumentProjection(input.apiClient, input.documentId),\n fetchLinkSetContainerProjection(input.apiClient, input.targetContainerId),\n ]);\n if (!writerFetch.projection || !targetContainerFetch.projection) {\n // A failure the operation no longer waits for is not reported.\n if (input.stillCurrent?.() === false) return null;\n for (const failure of orderedProjectionFailures([\n writerFetch.failure,\n targetContainerFetch.failure,\n ])) {\n reportLinkSetFailure(input, failure);\n }\n return null;\n }\n const writerProjection = writerFetch.projection;\n const targetContainerProjection = targetContainerFetch.projection;\n if (input.stillCurrent?.() === false) return null;\n\n const signedAt = input.signedAt ?? new Date().toISOString();\n const materializedPlan = await prepareRemoteLinkSetMutation(\n { ...input, resolveProjectionUserKey, signedAt },\n writerProjection,\n targetContainerProjection,\n attempt,\n );\n if (!materializedPlan) return null;\n const request = await completeLinkSetMutationRequest({\n author: input.author,\n materializedPlan,\n operation: input.operation,\n rotationSnapshot: input.rotationSnapshot,\n signedAt,\n });\n const completedPlan = { ...materializedPlan.plan, request };\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n const response = await submitLinkSetMutation({\n apiClient: input.apiClient,\n documentId: completedPlan.documentId,\n expectedOrganizationId: completedPlan.state.organizationId,\n onFailure: onSubmitFailure,\n operation: input.operation,\n request: completedPlan.request,\n stillCurrent: input.stillCurrent,\n });\n if (!response) {\n return null;\n }\n if (input.stillCurrent?.() === false) return null;\n return completeRemoteDocumentLinkSet({\n apiClient: input.apiClient,\n completedPlan,\n execSql: input.execSql,\n materializedPlan,\n operation: input.operation,\n response,\n stillCurrent: input.stillCurrent,\n targetContainerId: input.targetContainerId,\n targetContainerProjection,\n writerProjection,\n });\n}\n\n// Every projection failure reaches the handler: the queued-move accumulator\n// classifies a vanished container from ANY coded container 404, so a document\n// fetch failure must not hide a container one (or vice versa). A 403 is\n// delivered last, so a single-slot consumer keeps the denial that parks the\n// move (row 7) while the accumulator still sees both.\nfunction orderedProjectionFailures(\n failures: readonly (LinkSetSubmitFailure | null)[],\n): LinkSetSubmitFailure[] {\n const present = failures.filter(\n (failure): failure is LinkSetSubmitFailure => failure !== null,\n );\n return [\n ...present.filter((failure) => failure.status !== 403),\n ...present.filter((failure) => failure.status === 403),\n ];\n}\n\n/**\n * Rewraps a first attempt may sign without listing: the previous leg's\n * envelopes, or none when the local view holds no attachment for the\n * document. The server's binding check at commit refuses either if stale.\n */\nasync function speculativeBlobRewraps(\n input: RelinkRemoteDocumentInput,\n writerProjection: DocumentWriterProjectionResponse,\n targets: readonly DocumentContentKeyTarget[],\n): Promise<{\n readonly rewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n readonly source: \"reused\" | \"skipped\";\n} | null> {\n const committed = input.attachmentReuse?.committed;\n if (committed) {\n const reused = reuseCommittedBlobRewraps({\n committed,\n documentId: writerProjection.documentId,\n targets,\n });\n if (reused) return { rewraps: reused, source: \"reused\" };\n // The previous leg cited attachments this leg cannot re-cite: list them.\n if (committed.length > 0) return null;\n }\n if (\n await documentMayHaveAttachments(input.execSql, writerProjection.documentId)\n )\n return null;\n return { rewraps: [], source: \"skipped\" };\n}\n\nfunction prepareRemoteLinkSetMutation(\n input: RelinkRemoteDocumentInput & {\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt: string;\n },\n writerProjection: DocumentWriterProjectionResponse,\n targetContainerProjection: ContainerWriterProjectionResponse,\n attempt: LinkSetAttemptSlot,\n) {\n const prepareBlobRewraps = async (\n targets: readonly DocumentContentKeyTarget[],\n ) => {\n const prepared: PreparedLinkSetRewraps = (attempt.current.listing ===\n \"speculative\"\n ? await speculativeBlobRewraps(input, writerProjection, targets)\n : null) ?? {\n rewraps: await prepareDocumentLinkBlobRewraps({\n ...input,\n refreshListing: attempt.current.listing === \"fresh\",\n targets,\n targetContainerProjection,\n writerProjection,\n }),\n source: \"listed\",\n };\n attempt.current = recordLinkSetLegRewraps(attempt.current, prepared);\n return prepared.rewraps;\n };\n return recordDocumentAuthorAccessFailure(\n () =>\n nullOnProjectionVerificationCancellation(() =>\n buildMaterializedDocumentLinkSetMutationPlan({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n prepareBlobRewraps,\n contentKey: input.contentKey,\n eventId: input.eventId,\n execSql: input.execSql,\n operation: input.operation,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetContainerProjection,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n writerProjection,\n }),\n ),\n input.onFailure,\n );\n}\n"]}
|