@tearleads/client-sdk 0.1.65 → 0.1.67
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/persistence/container-contents/documentPurgePlacement.js +13 -0
- package/data/persistence/container-contents/documentPurgePlacement.js.map +1 -1
- package/index.d.ts +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/stores/container-contents/containerContentsStore.js +3 -2
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/index.d.ts +1 -1
- package/stores/container-contents/index.js.map +1 -1
- package/stores/container-contents/operations/purgeMoveSettlementOperation.js +71 -0
- package/stores/container-contents/operations/purgeMoveSettlementOperation.js.map +1 -0
- package/stores/container-contents/syncAgent/acceptedMoveRetry.js +40 -0
- package/stores/container-contents/syncAgent/acceptedMoveRetry.js.map +1 -0
- package/stores/container-contents/syncAgent/syncLaneIteration.js +9 -2
- package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
- package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js +59 -0
- package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js.map +1 -0
- package/workflows/container-contents/container-state/{moveIntentSync.js → move/moveIntentSync.js} +77 -39
- package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -0
- package/workflows/container-contents/container-state/purge/purgeMoveSettlement.js +119 -0
- package/workflows/container-contents/container-state/purge/purgeMoveSettlement.js.map +1 -0
- package/workflows/container-contents/container-state/purge/purgeProgress.d.ts +8 -0
- package/workflows/container-contents/container-state/purge/purgeProgress.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +22 -18
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/types.js.map +1 -1
- package/workflows/container-contents/syncLane.d.ts +2 -0
- package/workflows/container-contents/syncLane.js +7 -0
- package/workflows/container-contents/syncLane.js.map +1 -1
- package/workflows/containers/child/move/index.d.ts +24 -2
- package/workflows/containers/child/move/index.js +62 -70
- package/workflows/containers/child/move/index.js.map +1 -1
- package/workflows/containers/child/move/moveRequest.js +47 -0
- package/workflows/containers/child/move/moveRequest.js.map +1 -0
- package/workflows/containers/child/mutationSubmit.js +1 -0
- package/workflows/containers/child/mutationSubmit.js.map +1 -1
- package/workflows/containers/index.d.ts +1 -1
- package/workflows/containers/index.js +1 -1
- package/workflows/containers/index.js.map +1 -1
- package/workflows/container-contents/container-state/moveIntentSync.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isContainerNotFoundFailure } from "../../../data/containers/shared/mutationFailures.js";
|
|
2
2
|
import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
|
|
3
|
-
import {
|
|
3
|
+
import { readContainerMutationMetadataDocumentId, referencedPrincipalHeadsFromContainerMutationResponse, replayRemoteContainerMove, shareRemoteContainer as shareRemoteContainerMutation, } from "../../containers/index.js";
|
|
4
4
|
import { createRuntimeCurrentGroupShare } from "../../containers/child/share/runtimeCurrentGroupShare.js";
|
|
5
5
|
import { resolveDocumentCreateAuthor } from "../../documents/index.js";
|
|
6
6
|
import { createRuntimeGroupMetadataAccess } from "../../organizations/groupMetadata/groupMetadataRuntime.js";
|
|
@@ -103,42 +103,46 @@ export async function shareRemoteContainerWithGroup(input) {
|
|
|
103
103
|
}
|
|
104
104
|
return sharedRemoteContainerStateFromMutation(input.previousProjection, shared.response);
|
|
105
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* Replays a queued move. `applied` carries the verified head when the server
|
|
108
|
+
* already holds the container under the destination, so nothing is posted.
|
|
109
|
+
*/
|
|
106
110
|
export async function moveRemoteContainer(input) {
|
|
107
111
|
const writer = resolveContainerWriterContext(input.runtime, "container move");
|
|
108
112
|
if (!writer) {
|
|
109
113
|
return null;
|
|
110
114
|
}
|
|
111
115
|
const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;
|
|
112
|
-
const
|
|
116
|
+
const replayed = await replayRemoteContainerMove({
|
|
113
117
|
reportSecurityIncident: input.runtime.util.reportSecurityIncident,
|
|
114
118
|
apiClient,
|
|
115
119
|
author,
|
|
116
120
|
containerId: input.containerId,
|
|
117
121
|
destinationParentContainerId: input.parentContainerId,
|
|
118
122
|
execSql,
|
|
123
|
+
onAccepted: input.onAccepted,
|
|
119
124
|
resolveProjectionUserKey: input.resolveProjectionUserKey,
|
|
120
125
|
stillCurrent: input.stillCurrent,
|
|
121
126
|
targetSecretKey,
|
|
122
127
|
warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.runtime),
|
|
123
128
|
});
|
|
124
|
-
if (!
|
|
125
|
-
return
|
|
129
|
+
if (!replayed || "applied" in replayed) {
|
|
130
|
+
return replayed;
|
|
126
131
|
}
|
|
132
|
+
const { response } = replayed;
|
|
127
133
|
return {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
}),
|
|
141
|
-
updatedAt: moved.response.updatedAt,
|
|
134
|
+
moved: {
|
|
135
|
+
createdAt: response.createdAt,
|
|
136
|
+
effectiveAccessLevel: "admin",
|
|
137
|
+
id: response.containerId,
|
|
138
|
+
organizationId: response.organizationId,
|
|
139
|
+
parentId: response.parentId,
|
|
140
|
+
metadataDocumentId: readContainerMutationMetadataDocumentId({ response }),
|
|
141
|
+
metadataAccessEpoch: response.manifestHead.epoch,
|
|
142
|
+
metadataAccessStateHash: response.manifestHead.manifestHash,
|
|
143
|
+
metadataReferencedPrincipals: referencedPrincipalHeadsFromContainerMutationResponse({ response }),
|
|
144
|
+
updatedAt: response.updatedAt,
|
|
145
|
+
},
|
|
142
146
|
};
|
|
143
147
|
}
|
|
144
148
|
export async function deleteRemoteContainer(input) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote.js","sourceRoot":"","sources":["remote.ts"],"names":[],"mappings":"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D,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { isContainerNotFoundFailure } from \"../../../data/containers/shared/mutationFailures\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport {\n moveRemoteContainer as moveRemoteContainerMutation,\n readContainerMutationMetadataDocumentId,\n referencedPrincipalHeadsFromContainerMutationResponse,\n shareRemoteContainer as shareRemoteContainerMutation,\n} from \"../../containers\";\nimport { createRuntimeCurrentGroupShare } from \"../../containers/child/share/runtimeCurrentGroupShare\";\nimport { resolveDocumentCreateAuthor } from \"../../documents\";\nimport { createRuntimeGroupMetadataAccess } from \"../../organizations/groupMetadata/groupMetadataRuntime\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport {\n type ContainerAlreadyCommitted,\n createRemoteContainerWithMetadataDocument,\n} from \"./create/createWithMetadata\";\nimport type {\n ContainerWorkflowRuntime,\n CreatedRemoteContainerState,\n RemoteContainer,\n SharedRemoteContainerState,\n} from \"./types\";\n\n/**\n * Resolve the author, api client, executor, and encapsulation secret a remote\n * container mutation needs, logging a skip for the given operation when the\n * writer context is unavailable.\n */\nfunction resolveContainerWriterContext(\n runtime: ContainerWorkflowRuntime,\n operation:\n | \"container create\"\n | \"container group share\"\n | \"container move\"\n | \"container share\",\n) {\n const author = resolveDocumentCreateAuthor(runtime);\n const secretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!author || !secretKey) {\n runtime.util.log(\n `Container contents: skipped ${operation} because the writer context is unavailable.`,\n );\n return null;\n }\n\n return {\n apiClient: runtime.apiClient,\n author,\n execSql: runtime.infra.execSql,\n secretKey,\n };\n}\n\nexport async function createRemoteContainer(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n containerId: string;\n parentContainerId: string;\n parentProjection?: ContainerWriterProjectionResponse | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedRemoteContainerState | ContainerAlreadyCommitted | null> {\n return createRemoteContainerWithMetadataDocument(input);\n}\n\nfunction sharedRemoteContainerStateFromMutation(\n previousProjection: ContainerWriterProjectionResponse,\n response: ContainerMutationResponse,\n): SharedRemoteContainerState {\n if (\n response.containerId !== previousProjection.containerId ||\n response.organizationId !== previousProjection.organizationId\n )\n throw new Error(\"Container mutation response projection mismatch\");\n return {\n accessManifestHash: response.manifestHead.manifestHash,\n accessEpoch: response.manifestHead.epoch,\n createdAt: response.createdAt,\n metadataDocumentId: readContainerMutationMetadataDocumentId({ response }),\n referencedPrincipalHeads:\n referencedPrincipalHeadsFromContainerMutationResponse({ response }),\n updatedAt: response.updatedAt,\n // The next read obtains the post-commit proof. A failed read cannot undo\n // acknowledgement of this successful mutation.\n writerProjection: null,\n };\n}\n\nexport async function shareRemoteContainer(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n previousProjection: ContainerWriterProjectionResponse;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container share\",\n );\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const shared = await shareRemoteContainerMutation({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n accessLevel: input.accessLevel,\n apiClient,\n author,\n containerId: input.containerId,\n execSql,\n previousProjection: input.previousProjection,\n recipientUserId: input.recipientUserId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared.response,\n );\n}\n\nexport async function shareRemoteContainerWithGroup(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n expectedGroupName?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container group share\",\n );\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const shareWithGroup = createRuntimeCurrentGroupShare(input.runtime);\n if (!shareWithGroup)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n const shared = await shareWithGroup({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n accessLevel: input.accessLevel,\n apiClient,\n author,\n containerId: input.containerId,\n execSql,\n expectedGroupName: input.expectedGroupName ?? null,\n readEncryptedName: (bundle) =>\n createRuntimeGroupMetadataAccess(\n input.runtime,\n author.organizationId,\n input.stillCurrent,\n ).readName(bundle),\n knownContainerKeks: input.knownContainerKeks,\n previousProjection: input.previousProjection,\n recipientGroupId: input.recipientGroupId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n signingKeyPair: input.runtime.crypto.signingKeyPair,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared.response,\n );\n}\n\nexport async function moveRemoteContainer(input: {\n containerId: string;\n parentContainerId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<RemoteContainer | null> {\n const writer = resolveContainerWriterContext(input.runtime, \"container move\");\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const moved = await moveRemoteContainerMutation({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n apiClient,\n author,\n containerId: input.containerId,\n destinationParentContainerId: input.parentContainerId,\n execSql,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!moved) {\n return null;\n }\n\n return {\n createdAt: moved.response.createdAt,\n effectiveAccessLevel: \"admin\",\n id: moved.response.containerId,\n organizationId: moved.response.organizationId,\n parentId: moved.response.parentId,\n metadataDocumentId: readContainerMutationMetadataDocumentId({\n response: moved.response,\n }),\n metadataAccessEpoch: moved.response.manifestHead.epoch,\n metadataAccessStateHash: moved.response.manifestHead.manifestHash,\n metadataReferencedPrincipals:\n referencedPrincipalHeadsFromContainerMutationResponse({\n response: moved.response,\n }),\n updatedAt: moved.response.updatedAt,\n };\n}\n\nexport async function deleteRemoteContainer(input: {\n containerId: string;\n organizationId: string;\n requiredAncestorId?: string | undefined;\n runtime: ContainerWorkflowRuntime;\n}): Promise<{ deletedAt: string } | null> {\n const deleteResult = await input.runtime.apiClient.deleteContainerResult(\n input.containerId,\n {\n expectedPaymentRequiredOrganizationId: input.organizationId,\n reportErrors: false,\n requiredAncestorId: input.requiredAncestorId,\n },\n );\n if (!deleteResult.ok && !isContainerNotFoundFailure(deleteResult)) {\n deleteResult.report();\n return null;\n }\n\n if (!deleteResult.ok) {\n // A 404 proves this immutable id is permanently absent, but it does not\n // carry the server deletion time. A maximal fence prevents an older\n // in-flight listing page from resurrecting it.\n return { deletedAt: \"9999-12-31T23:59:59.999Z\" };\n }\n\n return { deletedAt: deleteResult.data.deletedAt };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"remote.js","sourceRoot":"","sources":["remote.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,0BAA0B,EAAE,MAAM,kDAAkD,CAAC;AAE9F,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAEL,uCAAuC,EACvC,qDAAqD,EACrD,yBAAyB,EACzB,oBAAoB,IAAI,4BAA4B,GACrD,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,8BAA8B,EAAE,MAAM,uDAAuD,CAAC;AACvG,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,gCAAgC,EAAE,MAAM,wDAAwD,CAAC;AAC1G,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EAEL,yCAAyC,GAC1C,MAAM,6BAA6B,CAAC;AAQrC;;;;GAIG;AACH,SAAS,6BAA6B,CACpC,OAAiC,EACjC,SAIqB;IAErB,MAAM,MAAM,GAAG,2BAA2B,CAAC,OAAO,CAAC,CAAC;IACpD,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,SAAS,CAAC;IACjE,IAAI,CAAC,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QAC1B,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,+BAA+B,SAAS,6CAA6C,CACtF,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,MAAM;QACN,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,SAAS;KACV,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,KAQ3C;IACC,OAAO,yC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,CAAC;QACrB,wEAAwE;QACxE,oEAAoE;QACpE,+CAA+C;QAC/C,OAAO,EAAE,SAAS,EAAE,0BAA0B,EAAE,CAAC;IACnD,CAAC;IAED,OAAO,EAAE,SAAS,EAAE,YAAY,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { isContainerNotFoundFailure } from \"../../../data/containers/shared/mutationFailures\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport {\n type AppliedContainerMove,\n readContainerMutationMetadataDocumentId,\n referencedPrincipalHeadsFromContainerMutationResponse,\n replayRemoteContainerMove,\n shareRemoteContainer as shareRemoteContainerMutation,\n} from \"../../containers\";\nimport { createRuntimeCurrentGroupShare } from \"../../containers/child/share/runtimeCurrentGroupShare\";\nimport { resolveDocumentCreateAuthor } from \"../../documents\";\nimport { createRuntimeGroupMetadataAccess } from \"../../organizations/groupMetadata/groupMetadataRuntime\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport {\n type ContainerAlreadyCommitted,\n createRemoteContainerWithMetadataDocument,\n} from \"./create/createWithMetadata\";\nimport type {\n ContainerWorkflowRuntime,\n CreatedRemoteContainerState,\n RemoteContainer,\n SharedRemoteContainerState,\n} from \"./types\";\n\n/**\n * Resolve the author, api client, executor, and encapsulation secret a remote\n * container mutation needs, logging a skip for the given operation when the\n * writer context is unavailable.\n */\nfunction resolveContainerWriterContext(\n runtime: ContainerWorkflowRuntime,\n operation:\n | \"container create\"\n | \"container group share\"\n | \"container move\"\n | \"container share\",\n) {\n const author = resolveDocumentCreateAuthor(runtime);\n const secretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!author || !secretKey) {\n runtime.util.log(\n `Container contents: skipped ${operation} because the writer context is unavailable.`,\n );\n return null;\n }\n\n return {\n apiClient: runtime.apiClient,\n author,\n execSql: runtime.infra.execSql,\n secretKey,\n };\n}\n\nexport async function createRemoteContainer(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n containerId: string;\n parentContainerId: string;\n parentProjection?: ContainerWriterProjectionResponse | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedRemoteContainerState | ContainerAlreadyCommitted | null> {\n return createRemoteContainerWithMetadataDocument(input);\n}\n\nfunction sharedRemoteContainerStateFromMutation(\n previousProjection: ContainerWriterProjectionResponse,\n response: ContainerMutationResponse,\n): SharedRemoteContainerState {\n if (\n response.containerId !== previousProjection.containerId ||\n response.organizationId !== previousProjection.organizationId\n )\n throw new Error(\"Container mutation response projection mismatch\");\n return {\n accessManifestHash: response.manifestHead.manifestHash,\n accessEpoch: response.manifestHead.epoch,\n createdAt: response.createdAt,\n metadataDocumentId: readContainerMutationMetadataDocumentId({ response }),\n referencedPrincipalHeads:\n referencedPrincipalHeadsFromContainerMutationResponse({ response }),\n updatedAt: response.updatedAt,\n // The next read obtains the post-commit proof. A failed read cannot undo\n // acknowledgement of this successful mutation.\n writerProjection: null,\n };\n}\n\nexport async function shareRemoteContainer(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n previousProjection: ContainerWriterProjectionResponse;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container share\",\n );\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const shared = await shareRemoteContainerMutation({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n accessLevel: input.accessLevel,\n apiClient,\n author,\n containerId: input.containerId,\n execSql,\n previousProjection: input.previousProjection,\n recipientUserId: input.recipientUserId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared.response,\n );\n}\n\nexport async function shareRemoteContainerWithGroup(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n expectedGroupName?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container group share\",\n );\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const shareWithGroup = createRuntimeCurrentGroupShare(input.runtime);\n if (!shareWithGroup)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n const shared = await shareWithGroup({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n accessLevel: input.accessLevel,\n apiClient,\n author,\n containerId: input.containerId,\n execSql,\n expectedGroupName: input.expectedGroupName ?? null,\n readEncryptedName: (bundle) =>\n createRuntimeGroupMetadataAccess(\n input.runtime,\n author.organizationId,\n input.stillCurrent,\n ).readName(bundle),\n knownContainerKeks: input.knownContainerKeks,\n previousProjection: input.previousProjection,\n recipientGroupId: input.recipientGroupId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n signingKeyPair: input.runtime.crypto.signingKeyPair,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared.response,\n );\n}\n\n/**\n * Replays a queued move. `applied` carries the verified head when the server\n * already holds the container under the destination, so nothing is posted.\n */\nexport async function moveRemoteContainer(input: {\n containerId: string;\n onAccepted?: (() => void) | undefined;\n parentContainerId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n { applied: AppliedContainerMove } | { moved: RemoteContainer } | null\n> {\n const writer = resolveContainerWriterContext(input.runtime, \"container move\");\n if (!writer) {\n return null;\n }\n const { apiClient, author, execSql, secretKey: targetSecretKey } = writer;\n\n const replayed = await replayRemoteContainerMove({\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n apiClient,\n author,\n containerId: input.containerId,\n destinationParentContainerId: input.parentContainerId,\n execSql,\n onAccepted: input.onAccepted,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (!replayed || \"applied\" in replayed) {\n return replayed;\n }\n\n const { response } = replayed;\n return {\n moved: {\n createdAt: response.createdAt,\n effectiveAccessLevel: \"admin\",\n id: response.containerId,\n organizationId: response.organizationId,\n parentId: response.parentId,\n metadataDocumentId: readContainerMutationMetadataDocumentId({ response }),\n metadataAccessEpoch: response.manifestHead.epoch,\n metadataAccessStateHash: response.manifestHead.manifestHash,\n metadataReferencedPrincipals:\n referencedPrincipalHeadsFromContainerMutationResponse({ response }),\n updatedAt: response.updatedAt,\n },\n };\n}\n\nexport async function deleteRemoteContainer(input: {\n containerId: string;\n organizationId: string;\n requiredAncestorId?: string | undefined;\n runtime: ContainerWorkflowRuntime;\n}): Promise<{ deletedAt: string } | null> {\n const deleteResult = await input.runtime.apiClient.deleteContainerResult(\n input.containerId,\n {\n expectedPaymentRequiredOrganizationId: input.organizationId,\n reportErrors: false,\n requiredAncestorId: input.requiredAncestorId,\n },\n );\n if (!deleteResult.ok && !isContainerNotFoundFailure(deleteResult)) {\n deleteResult.report();\n return null;\n }\n\n if (!deleteResult.ok) {\n // A 404 proves this immutable id is permanently absent, but it does not\n // carry the server deletion time. A maximal fence prevents an older\n // in-flight listing page from resurrecting it.\n return { deletedAt: \"9999-12-31T23:59:59.999Z\" };\n }\n\n return { deletedAt: deleteResult.data.deletedAt };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerDeleteResponse,\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { createInitializedContainerMetadataDocument } from \"../../../data/containers/containerMetadataDocument\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { DocumentRecord } from \"../../../data/sqlite/documentPersistence\";\nimport type {\n createRemoteContainer,\n moveRemoteContainer,\n shareRemoteContainer,\n shareRemoteContainerWithGroup,\n} from \"../../containers\";\nimport type { createRemoteDocument } from \"../../documents\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerMoveIntentRecord,\n} from \"../containerPersistence\";\nimport type {\n ContainerState,\n RemoteContainer as HydratedRemoteContainer,\n RemoteContainerHydrationHost,\n} from \"../remoteHydration\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ContainerWorkflowApi = Parameters<\n typeof createRemoteContainer\n>[0][\"apiClient\"] &\n Parameters<typeof shareRemoteContainer>[0][\"apiClient\"] &\n Parameters<typeof shareRemoteContainerWithGroup>[0][\"apiClient\"] &\n Parameters<typeof moveRemoteContainer>[0][\"apiClient\"] &\n Parameters<typeof createRemoteDocument>[0][\"apiClient\"] &\n Partial<PrincipalPolicyHistoryReader> &\n CurrentPrincipalPolicyReader & {\n deleteContainerResult(\n containerId: string,\n options?: {\n expectedPaymentRequiredOrganizationId?: string;\n reportErrors?: boolean;\n requiredAncestorId?: string | undefined;\n },\n ): Promise<\n | { data: ContainerDeleteResponse; ok: true }\n | {\n ok: false;\n report: () => void;\n status: number | null;\n }\n >;\n primeContainerWriterProjection(\n containerId: string,\n projection: ContainerWriterProjectionResponse,\n ): void;\n };\n\nexport interface ContainerWorkflowRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n readonly apiClient: ContainerWorkflowApi;\n}\n\nexport interface CreatedRemoteContainerState {\n accessManifestHash: string;\n /** The slot this client signed into the create; never the server's echo. */\n systemSlot: ContainerSystemSlot | null;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n organizationId: string;\n /** A created container is a child; the acknowledgement echoed this parent. */\n parentId: string;\n persistedMetadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n updatedAt: string;\n}\n\nexport interface SharedRemoteContainerState {\n accessEpoch: number;\n accessManifestHash: string;\n createdAt: string;\n metadataDocumentId: string;\n referencedPrincipalHeads: ReferencedPrincipalStateResponse[];\n updatedAt: string;\n writerProjection: ContainerWriterProjectionResponse | null;\n}\n\nexport interface SharedContainerState {\n container: ContainerState[\"container\"];\n record: ContainerState[\"record\"];\n}\n\nexport type SharedContainerStateResult =\n | { status: \"missing\" }\n | { status: \"confirmed\" }\n | (SharedContainerState & {\n status: \"identity-superseded\" | \"persisted\";\n });\n\nexport type RemoteContainer = HydratedRemoteContainer;\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createInitializedContainerMetadataDocument>\n>[\"doc\"];\n\nexport interface CreatedChildContainerState {\n containerState: ContainerState;\n initialUpdate: Uint8Array;\n shouldRequestSync: boolean;\n}\n\nexport interface ContainerIntentSyncState {\n containersById: ReadonlyMap<string, ContainerState>;\n persistence: ContainerContentsPersistence;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n /**\n * Verifies that a listed container is this device's pending create before it\n * is adopted and returns where it sits; `assertContainerCreateAdoptable`\n * unless a test replaces it.\n */\n verifyCreateAdoption?: (input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n }) => Promise<AdoptedContainerPlacement>;\n}\n\n/** Where a verified listed create committed, and where its container is now. */\nexport interface AdoptedContainerPlacement {\n /** The parent its signed epoch-1 `container.create` named. */\n readonly createdParentId: string;\n /** The verified head's parent; another writer may have moved it since. */\n readonly currentParentId: string;\n}\n\nexport type ContainerCreateIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerCreateIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\"\n>;\n\nexport interface ContainerCreateIntentSyncInput {\n host: ContainerCreateIntentSyncHost;\n /** A parent whose own create has not settled takes no child create. */\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerCreateIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerCreateIntentSyncState;\n}\n\nexport type ContainerMoveIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerMoveIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\" | \"updateSnapshot\"\n>;\n\nexport interface ContainerMoveIntentSyncInput {\n host: ContainerMoveIntentSyncHost;\n isCurrent: () => boolean;\n /** A folder whose create has not settled takes no structural writes. */\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerMoveIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerMoveIntentSyncState;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerDeleteResponse,\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { createInitializedContainerMetadataDocument } from \"../../../data/containers/containerMetadataDocument\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { DocumentRecord } from \"../../../data/sqlite/documentPersistence\";\nimport type {\n createRemoteContainer,\n moveRemoteContainer,\n shareRemoteContainer,\n shareRemoteContainerWithGroup,\n} from \"../../containers\";\nimport type { createRemoteDocument } from \"../../documents\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerMoveIntentRecord,\n} from \"../containerPersistence\";\nimport type {\n ContainerState,\n RemoteContainer as HydratedRemoteContainer,\n RemoteContainerHydrationHost,\n} from \"../remoteHydration\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ContainerWorkflowApi = Parameters<\n typeof createRemoteContainer\n>[0][\"apiClient\"] &\n Parameters<typeof shareRemoteContainer>[0][\"apiClient\"] &\n Parameters<typeof shareRemoteContainerWithGroup>[0][\"apiClient\"] &\n Parameters<typeof moveRemoteContainer>[0][\"apiClient\"] &\n Parameters<typeof createRemoteDocument>[0][\"apiClient\"] &\n Partial<PrincipalPolicyHistoryReader> &\n CurrentPrincipalPolicyReader & {\n deleteContainerResult(\n containerId: string,\n options?: {\n expectedPaymentRequiredOrganizationId?: string;\n reportErrors?: boolean;\n requiredAncestorId?: string | undefined;\n },\n ): Promise<\n | { data: ContainerDeleteResponse; ok: true }\n | {\n ok: false;\n report: () => void;\n status: number | null;\n }\n >;\n primeContainerWriterProjection(\n containerId: string,\n projection: ContainerWriterProjectionResponse,\n ): void;\n };\n\nexport interface ContainerWorkflowRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n readonly apiClient: ContainerWorkflowApi;\n}\n\nexport interface CreatedRemoteContainerState {\n accessManifestHash: string;\n /** The slot this client signed into the create; never the server's echo. */\n systemSlot: ContainerSystemSlot | null;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n organizationId: string;\n /** A created container is a child; the acknowledgement echoed this parent. */\n parentId: string;\n persistedMetadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n updatedAt: string;\n}\n\nexport interface SharedRemoteContainerState {\n accessEpoch: number;\n accessManifestHash: string;\n createdAt: string;\n metadataDocumentId: string;\n referencedPrincipalHeads: ReferencedPrincipalStateResponse[];\n updatedAt: string;\n writerProjection: ContainerWriterProjectionResponse | null;\n}\n\nexport interface SharedContainerState {\n container: ContainerState[\"container\"];\n record: ContainerState[\"record\"];\n}\n\nexport type SharedContainerStateResult =\n | { status: \"missing\" }\n | { status: \"confirmed\" }\n | (SharedContainerState & {\n status: \"identity-superseded\" | \"persisted\";\n });\n\nexport type RemoteContainer = HydratedRemoteContainer;\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createInitializedContainerMetadataDocument>\n>[\"doc\"];\n\nexport interface CreatedChildContainerState {\n containerState: ContainerState;\n initialUpdate: Uint8Array;\n shouldRequestSync: boolean;\n}\n\nexport interface ContainerIntentSyncState {\n containersById: ReadonlyMap<string, ContainerState>;\n persistence: ContainerContentsPersistence;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n /**\n * Verifies that a listed container is this device's pending create before it\n * is adopted and returns where it sits; `assertContainerCreateAdoptable`\n * unless a test replaces it.\n */\n verifyCreateAdoption?: (input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n }) => Promise<AdoptedContainerPlacement>;\n}\n\n/** Where a verified listed create committed, and where its container is now. */\nexport interface AdoptedContainerPlacement {\n /** The parent its signed epoch-1 `container.create` named. */\n readonly createdParentId: string;\n /** The verified head's parent; another writer may have moved it since. */\n readonly currentParentId: string;\n}\n\nexport type ContainerCreateIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerCreateIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\"\n>;\n\nexport interface ContainerCreateIntentSyncInput {\n host: ContainerCreateIntentSyncHost;\n /** A parent whose own create has not settled takes no child create. */\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerCreateIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerCreateIntentSyncState;\n}\n\nexport type ContainerMoveIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerMoveIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\" | \"updateSnapshot\"\n>;\n\n/** Later passes for moves the server accepted but no pass settled. */\nexport interface AcceptedMoveRetry {\n /** The server holds the move: schedule a replay to settle it. */\n arm: (intentId: string) => void;\n /** A replay failed; continue an accepted move's retries, if it has some. */\n resume: (intentId: string) => void;\n}\n\nexport interface ContainerMoveIntentSyncInput {\n host: ContainerMoveIntentSyncHost;\n isCurrent: () => boolean;\n /** A folder whose create has not settled takes no structural writes. */\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerMoveIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n acceptedMoveRetry: AcceptedMoveRetry;\n state: ContainerMoveIntentSyncState;\n}\n"]}
|
|
@@ -10,3 +10,5 @@ export declare function registerContainerContentsSyncLane(input: {
|
|
|
10
10
|
readonly logError?: ((message: string, error: unknown) => void) | undefined;
|
|
11
11
|
readonly run: () => Promise<void>;
|
|
12
12
|
}): ContainerContentsSyncLane;
|
|
13
|
+
/** The lane's run counters, for work that waits on a pass it requested. */
|
|
14
|
+
export declare function readContainerContentsSyncLane(domainScope: DomainScope): import("../sync/index.js").SyncLaneSnapshot | null;
|
|
@@ -17,4 +17,11 @@ export function registerContainerContentsSyncLane(input) {
|
|
|
17
17
|
shouldIgnoreError: isDatabaseUnavailableError,
|
|
18
18
|
});
|
|
19
19
|
}
|
|
20
|
+
/** The lane's run counters, for work that waits on a pass it requested. */
|
|
21
|
+
export function readContainerContentsSyncLane(domainScope) {
|
|
22
|
+
return (getOrCreateDomainSyncCoordinator(domainScope)
|
|
23
|
+
.getSnapshot()
|
|
24
|
+
.lanes.find((lane) => lane.key === CONTAINER_CONTENTS_SYNC_LANE_KEY) ??
|
|
25
|
+
null);
|
|
26
|
+
}
|
|
20
27
|
//# sourceMappingURL=syncLane.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncLane.js","sourceRoot":"","sources":["syncLane.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAE3B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,4EAA4E;AAC5E,+EAA+E;AAC/E,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AAGzC,MAAM,CAAC,MAAM,gCAAgC,GAAG,oBAAoB,CAAC;AAErE,MAAM,UAAU,iCAAiC,CAAC,KAKjD;IACC,OAAO,gCAAgC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,YAAY,CACrE,gCAAgC,EAChC;QACE,KAAK,EAAE,oBAAoB;QAC3B,KAAK,EAAE,YAAY;QACnB,qEAAqE;QACrE,sEAAsE;QACtE,yEAAyE;QACzE,mDAAmD;QACnD,qBAAqB,EAAE,CAAC,KAAK,EAAE,EAAE,CAC/B,KAAK,CAAC,QAAQ,EAAE,CAAC,sCAAsC,EAAE,KAAK,CAAC;QACjE,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,iBAAiB,EAAE,0BAA0B;KAC9C,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n type SyncLane,\n} from \"../../data/sync/syncCoordinator\";\n\nexport { sequenceUnchanged } from \"../../data/sync/sequence\";\n// Facade re-exports: container-contents stores must reach these shared sync\n// helpers through this workflow boundary, not by importing data/sync directly.\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\n\nexport type ContainerContentsSyncLane = SyncLane;\nexport const CONTAINER_CONTENTS_SYNC_LANE_KEY = \"container-contents\";\n\nexport function registerContainerContentsSyncLane(input: {\n readonly domainScope: DomainScope;\n /** Host diagnostics sink; bare runtimes do not structure errors. */\n readonly logError?: ((message: string, error: unknown) => void) | undefined;\n readonly run: () => Promise<void>;\n}): ContainerContentsSyncLane {\n return getOrCreateDomainSyncCoordinator(input.domainScope).registerLane(\n CONTAINER_CONTENTS_SYNC_LANE_KEY,\n {\n label: \"Container contents\",\n phase: \"structural\",\n // Fixed literal: no container or identity id may reach a report. The\n // mapped stack identifies which lane body threw. Returning the host's\n // result hands a rejection to the lane reporter's wrapper; discarding it\n // would surface as an unhandled rejection instead.\n reportUnexpectedError: (error) =>\n input.logError?.(\"Container contents: sync lane failed\", error),\n run: input.run,\n shouldIgnoreError: isDatabaseUnavailableError,\n },\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncLane.js","sourceRoot":"","sources":["syncLane.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAE3B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,4EAA4E;AAC5E,+EAA+E;AAC/E,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AAGzC,MAAM,CAAC,MAAM,gCAAgC,GAAG,oBAAoB,CAAC;AAErE,MAAM,UAAU,iCAAiC,CAAC,KAKjD;IACC,OAAO,gCAAgC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,YAAY,CACrE,gCAAgC,EAChC;QACE,KAAK,EAAE,oBAAoB;QAC3B,KAAK,EAAE,YAAY;QACnB,qEAAqE;QACrE,sEAAsE;QACtE,yEAAyE;QACzE,mDAAmD;QACnD,qBAAqB,EAAE,CAAC,KAAK,EAAE,EAAE,CAC/B,KAAK,CAAC,QAAQ,EAAE,CAAC,sCAAsC,EAAE,KAAK,CAAC;QACjE,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,iBAAiB,EAAE,0BAA0B;KAC9C,CACF,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,6BAA6B,CAAC,WAAwB;IACpE,OAAO,CACL,gCAAgC,CAAC,WAAW,CAAC;SAC1C,WAAW,EAAE;SACb,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,KAAK,gCAAgC,CAAC;QACtE,IAAI,CACL,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n type SyncLane,\n} from \"../../data/sync/syncCoordinator\";\n\nexport { sequenceUnchanged } from \"../../data/sync/sequence\";\n// Facade re-exports: container-contents stores must reach these shared sync\n// helpers through this workflow boundary, not by importing data/sync directly.\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\n\nexport type ContainerContentsSyncLane = SyncLane;\nexport const CONTAINER_CONTENTS_SYNC_LANE_KEY = \"container-contents\";\n\nexport function registerContainerContentsSyncLane(input: {\n readonly domainScope: DomainScope;\n /** Host diagnostics sink; bare runtimes do not structure errors. */\n readonly logError?: ((message: string, error: unknown) => void) | undefined;\n readonly run: () => Promise<void>;\n}): ContainerContentsSyncLane {\n return getOrCreateDomainSyncCoordinator(input.domainScope).registerLane(\n CONTAINER_CONTENTS_SYNC_LANE_KEY,\n {\n label: \"Container contents\",\n phase: \"structural\",\n // Fixed literal: no container or identity id may reach a report. The\n // mapped stack identifies which lane body threw. Returning the host's\n // result hands a rejection to the lane reporter's wrapper; discarding it\n // would surface as an unhandled rejection instead.\n reportUnexpectedError: (error) =>\n input.logError?.(\"Container contents: sync lane failed\", error),\n run: input.run,\n shouldIgnoreError: isDatabaseUnavailableError,\n },\n );\n}\n\n/** The lane's run counters, for work that waits on a pass it requested. */\nexport function readContainerContentsSyncLane(domainScope: DomainScope) {\n return (\n getOrCreateDomainSyncCoordinator(domainScope)\n .getSnapshot()\n .lanes.find((lane) => lane.key === CONTAINER_CONTENTS_SYNC_LANE_KEY) ??\n null\n );\n}\n"]}
|
|
@@ -1,9 +1,18 @@
|
|
|
1
|
+
import type { ContainerAccessManifestState } from "../../../../internal/crypto/index.js";
|
|
1
2
|
import type { ContainerRotationResponse } from "../../../../internal/validators/response/index.js";
|
|
2
3
|
import type { ContainerMoveApi, ContainerMovePlan, ContainerMutationAuthor } from "../../../../data/containers/shared/types.js";
|
|
3
4
|
import { type ProjectionUserKeyResolver, type ReferencedPrincipalPolicyWarmer } from "../../../../data/keyingProjectionVerification/index.js";
|
|
4
5
|
import type { SecurityIncidentReporter } from "../../../../data/shared/securityIncidents.js";
|
|
5
6
|
import type { ExecSql } from "../../../../data/sqlite/sqlSchema.js";
|
|
6
|
-
|
|
7
|
+
/**
|
|
8
|
+
* The source's verified head already sits under the destination: a move the
|
|
9
|
+
* server accepted but this device never settled, or one another writer made.
|
|
10
|
+
*/
|
|
11
|
+
export interface AppliedContainerMove {
|
|
12
|
+
readonly manifestHash: string;
|
|
13
|
+
readonly state: ContainerAccessManifestState;
|
|
14
|
+
}
|
|
15
|
+
interface MoveRemoteContainerInput {
|
|
7
16
|
reportSecurityIncident: SecurityIncidentReporter;
|
|
8
17
|
apiClient: ContainerMoveApi;
|
|
9
18
|
author: ContainerMutationAuthor;
|
|
@@ -11,13 +20,26 @@ export declare function moveRemoteContainer(input: {
|
|
|
11
20
|
destinationParentContainerId: string;
|
|
12
21
|
eventId?: string | undefined;
|
|
13
22
|
execSql: ExecSql;
|
|
23
|
+
onAccepted?: (() => void) | undefined;
|
|
14
24
|
resolveProjectionUserKey: ProjectionUserKeyResolver;
|
|
15
25
|
signedAt?: string | undefined;
|
|
16
26
|
stillCurrent?: (() => boolean) | undefined;
|
|
17
27
|
targetSecretKey: Uint8Array;
|
|
18
28
|
warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
|
|
19
|
-
}
|
|
29
|
+
}
|
|
30
|
+
interface SubmittedContainerMove {
|
|
20
31
|
containerKey: Uint8Array;
|
|
21
32
|
plan: ContainerMovePlan;
|
|
22
33
|
response: ContainerRotationResponse;
|
|
34
|
+
}
|
|
35
|
+
/** Signs and submits a move; `null` when it was refused or abandoned. */
|
|
36
|
+
export declare function moveRemoteContainer(input: MoveRemoteContainerInput): Promise<SubmittedContainerMove | null>;
|
|
37
|
+
/**
|
|
38
|
+
* Replays a queued move. When the verified source head already sits under
|
|
39
|
+
* the destination it signs nothing and returns that head, so a lost response
|
|
40
|
+
* settles without a second rotation.
|
|
41
|
+
*/
|
|
42
|
+
export declare function replayRemoteContainerMove(input: MoveRemoteContainerInput): Promise<SubmittedContainerMove | {
|
|
43
|
+
applied: AppliedContainerMove;
|
|
23
44
|
} | null>;
|
|
45
|
+
export {};
|
|
@@ -1,26 +1,15 @@
|
|
|
1
1
|
import { assertContainerAuthorAccess } from "../../../../data/containers/shared/authorAccess.js";
|
|
2
2
|
import { assertContainerChildPathFits } from "../../../../data/containers/shared/containerPathLimits.js";
|
|
3
|
-
import { asContainerManifestBundle,
|
|
3
|
+
import { asContainerManifestBundle, getTargetContainerContext, readContainerState, uniqueSortedManifestHashes, } from "../../../../data/containers/shared/projection.js";
|
|
4
4
|
import { unwrapContainerKekPath } from "../../../../data/documents/shared/projection/index.js";
|
|
5
5
|
import { projectionVerificationOptions } from "../../../../data/documents/shared/types.js";
|
|
6
|
-
import { readCanonicalRecord } from "../../../../data/keying/canonicalJson.js";
|
|
7
6
|
import { nullOnProjectionVerificationCancellation, requireProjectionUserKeyResolver, } from "../../../../data/keyingProjectionVerification/index.js";
|
|
8
|
-
import { containerMutationRequestCore, previousPathRequestFields, } from "../mutationRequestCore.js";
|
|
9
7
|
import { submitAcknowledgedContainerMutation, submitContainerRotation, } from "../mutationSubmit.js";
|
|
10
8
|
import { containerWriterProjectionFromRotationPlan } from "../rekey/rekeyProjection.js";
|
|
11
9
|
import { requireUnwrappedKek, signedRotationTarget, } from "../rotation/rotationContext.js";
|
|
12
10
|
import { buildMoveRotationWithBody, deriveMoveManifestArtifacts, } from "./moveArtifacts.js";
|
|
11
|
+
import { buildContainerMovePlanResult } from "./moveRequest.js";
|
|
13
12
|
import { buildContainerMoveWraps, collectContainerMovePrincipalPolicies, } from "./moveWraps.js";
|
|
14
|
-
function buildContainerMoveRequest(input) {
|
|
15
|
-
return {
|
|
16
|
-
...containerMutationRequestCore("move", input),
|
|
17
|
-
...previousPathRequestFields(input.previousManifest, input.previousProjection),
|
|
18
|
-
destinationParentContainerPathRefs: input.destinationParentProjection.path.map(containerManifestRef),
|
|
19
|
-
predecessorBridge: readCanonicalRecord(input.predecessorBridge, "Container move predecessor bridge"),
|
|
20
|
-
keyring: readCanonicalRecord(input.keyring, "Container move keyring"),
|
|
21
|
-
parentKekState: readCanonicalRecord(input.destinationParentKek, "Container move destination parent KEK state"),
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
13
|
async function unwrapMoveContainerKeys(input) {
|
|
25
14
|
const verifiedByHash = new Map();
|
|
26
15
|
const keksByEpochId = await unwrapContainerKekPath({
|
|
@@ -66,39 +55,6 @@ function containerMoveDependencyManifestHashes(input) {
|
|
|
66
55
|
...uniqueSortedManifestHashes(input.destinationParentProjection.path),
|
|
67
56
|
];
|
|
68
57
|
}
|
|
69
|
-
function buildContainerMovePlanResult(input) {
|
|
70
|
-
const plan = {
|
|
71
|
-
body: input.body,
|
|
72
|
-
containerId: input.containerId,
|
|
73
|
-
containerKeyEpochId: input.containerKeyEpochId,
|
|
74
|
-
event: input.event,
|
|
75
|
-
eventHash: input.eventHash,
|
|
76
|
-
keyEpoch: input.keyEpoch,
|
|
77
|
-
keyring: input.keyring,
|
|
78
|
-
manifest: input.manifest,
|
|
79
|
-
manifestHash: input.manifestHash,
|
|
80
|
-
previousManifest: input.previousManifest,
|
|
81
|
-
request: buildContainerMoveRequest({
|
|
82
|
-
body: input.body,
|
|
83
|
-
destinationParentKek: input.destinationParentKek,
|
|
84
|
-
destinationParentProjection: input.destinationParentProjection,
|
|
85
|
-
event: input.event,
|
|
86
|
-
keyEpoch: input.keyEpoch,
|
|
87
|
-
keyring: input.keyring,
|
|
88
|
-
manifest: input.manifest,
|
|
89
|
-
manifestHash: input.manifestHash,
|
|
90
|
-
previousManifest: input.previousManifest,
|
|
91
|
-
previousProjection: input.previousProjection,
|
|
92
|
-
predecessorBridge: input.predecessorBridge,
|
|
93
|
-
principalPolicies: input.principalPolicies,
|
|
94
|
-
userRecipientKeys: input.userRecipientKeys,
|
|
95
|
-
wraps: input.wraps,
|
|
96
|
-
}),
|
|
97
|
-
state: input.state,
|
|
98
|
-
wraps: input.wraps,
|
|
99
|
-
};
|
|
100
|
-
return { containerKey: input.containerKey, plan };
|
|
101
|
-
}
|
|
102
58
|
async function collectAuthorizedMovePolicies(input) {
|
|
103
59
|
const principalPolicies = await collectContainerMovePrincipalPolicies({
|
|
104
60
|
...input,
|
|
@@ -118,8 +74,9 @@ async function collectAuthorizedMovePolicies(input) {
|
|
|
118
74
|
});
|
|
119
75
|
return principalPolicies;
|
|
120
76
|
}
|
|
121
|
-
|
|
122
|
-
|
|
77
|
+
/** Verifies both projections and reads the states a move rotates between. */
|
|
78
|
+
async function verifyContainerMoveSources(input) {
|
|
79
|
+
const unwrapped = await unwrapMoveContainerKeys({
|
|
123
80
|
destinationParentProjection: input.destinationParentProjection,
|
|
124
81
|
execSql: input.execSql,
|
|
125
82
|
previousProjection: input.previousProjection,
|
|
@@ -131,11 +88,25 @@ async function buildMaterializedContainerMovePlan(input) {
|
|
|
131
88
|
// Only a verified path is a final depth refusal; a padded unverified path
|
|
132
89
|
// must fail verification (an incident), never look like an honest refusal.
|
|
133
90
|
assertContainerChildPathFits(input.destinationParentProjection.path);
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
91
|
+
return {
|
|
92
|
+
...unwrapped,
|
|
93
|
+
...readContainerMoveStates({
|
|
94
|
+
authorOrganizationId: input.author.organizationId,
|
|
95
|
+
destinationParent: unwrapped.destinationParent,
|
|
96
|
+
source: unwrapped.source,
|
|
97
|
+
}),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
async function buildMaterializedContainerMovePlan(input) {
|
|
101
|
+
const { containerKey: predecessorContainerKey, destinationParent, destinationState, previousState, source, } = await verifyContainerMoveSources(input);
|
|
102
|
+
if (input.adoptAppliedMove &&
|
|
103
|
+
previousState.parentContainerId === destinationState.containerId)
|
|
104
|
+
return {
|
|
105
|
+
applied: {
|
|
106
|
+
manifestHash: source.manifest.manifestHash,
|
|
107
|
+
state: previousState,
|
|
108
|
+
},
|
|
109
|
+
};
|
|
139
110
|
const principalPolicies = await collectAuthorizedMovePolicies(input);
|
|
140
111
|
const { body, containerKey, containerKeyEpochId, keyring, predecessorBridge, } = await buildMoveRotationWithBody({
|
|
141
112
|
destinationParent,
|
|
@@ -194,7 +165,22 @@ async function buildMaterializedContainerMovePlan(input) {
|
|
|
194
165
|
wraps,
|
|
195
166
|
});
|
|
196
167
|
}
|
|
168
|
+
/** Signs and submits a move; `null` when it was refused or abandoned. */
|
|
197
169
|
export async function moveRemoteContainer(input) {
|
|
170
|
+
const moved = await submitRemoteContainerMove(input, false);
|
|
171
|
+
if (moved && "applied" in moved)
|
|
172
|
+
throw new Error("A move that adopts nothing cannot report one applied");
|
|
173
|
+
return moved;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Replays a queued move. When the verified source head already sits under
|
|
177
|
+
* the destination it signs nothing and returns that head, so a lost response
|
|
178
|
+
* settles without a second rotation.
|
|
179
|
+
*/
|
|
180
|
+
export function replayRemoteContainerMove(input) {
|
|
181
|
+
return submitRemoteContainerMove(input, true);
|
|
182
|
+
}
|
|
183
|
+
async function submitRemoteContainerMove(input, adoptAppliedMove) {
|
|
198
184
|
const resolveProjectionUserKey = requireProjectionUserKeyResolver(input.resolveProjectionUserKey, "Remote container move");
|
|
199
185
|
const [previousProjection, destinationParentProjection] = await Promise.all([
|
|
200
186
|
input.apiClient.getContainerWriterProjection(input.containerId),
|
|
@@ -204,6 +190,7 @@ export async function moveRemoteContainer(input) {
|
|
|
204
190
|
return null;
|
|
205
191
|
}
|
|
206
192
|
const materializedPlan = await nullOnProjectionVerificationCancellation(() => buildMaterializedContainerMovePlan({
|
|
193
|
+
adoptAppliedMove,
|
|
207
194
|
author: input.author,
|
|
208
195
|
eventId: input.eventId,
|
|
209
196
|
execSql: input.execSql,
|
|
@@ -215,8 +202,8 @@ export async function moveRemoteContainer(input) {
|
|
|
215
202
|
targetSecretKey: input.targetSecretKey,
|
|
216
203
|
warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,
|
|
217
204
|
}));
|
|
218
|
-
if (!materializedPlan)
|
|
219
|
-
return
|
|
205
|
+
if (!materializedPlan || "applied" in materializedPlan)
|
|
206
|
+
return materializedPlan;
|
|
220
207
|
return submitAcknowledgedContainerMutation({
|
|
221
208
|
reportSecurityIncident: input.reportSecurityIncident,
|
|
222
209
|
recitationPolicies: [],
|
|
@@ -246,23 +233,28 @@ export async function moveRemoteContainer(input) {
|
|
|
246
233
|
},
|
|
247
234
|
containerKey: materializedPlan.containerKey,
|
|
248
235
|
execSql: input.execSql,
|
|
236
|
+
onAccepted: input.onAccepted,
|
|
249
237
|
plan: materializedPlan.plan,
|
|
250
238
|
stillCurrent: input.stillCurrent,
|
|
251
|
-
submit: (carried) => {
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
239
|
+
submit: (carried) => submitContainerMoveRequest(input, {
|
|
240
|
+
...materializedPlan.plan.request,
|
|
241
|
+
...(carried.length ? { containerRekeys: [...carried] } : {}),
|
|
242
|
+
}),
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
function submitContainerMoveRequest(input, request) {
|
|
246
|
+
const options = {
|
|
247
|
+
expectedPaymentRequiredOrganizationId: input.author.organizationId,
|
|
248
|
+
};
|
|
249
|
+
const { moveContainerResult } = input.apiClient;
|
|
250
|
+
return submitContainerRotation({
|
|
251
|
+
plain: () => input.apiClient.moveContainer(input.containerId, request, options),
|
|
252
|
+
result: moveContainerResult
|
|
253
|
+
? () => moveContainerResult.call(input.apiClient, input.containerId, request, {
|
|
254
|
+
...options,
|
|
255
|
+
reportErrors: false,
|
|
256
|
+
})
|
|
257
|
+
: undefined,
|
|
266
258
|
});
|
|
267
259
|
}
|
|
268
260
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAqBA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BAA+B;aACvE;YACD,OAAO,EAAE,GAAG,EAAE,CACZ,yCAAyC,CAAC;gBACxC,SAAS,EAAE,2BAA2B;gBACtC,IAAI,EAAE,gBAAgB,CAAC,IAAI;gBAC3B,kBAAkB;aACnB,CAAC;SACL;QACD,YAAY,EAAE,gBAAgB,CAAC,YAAY;QAC3C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,IAAI,EAAE,gBAAgB,CAAC,IAAI;QAC3B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,MAAM,EAAE,CAAC,OAAO,EAAE,EAAE;YAClB,MAAM,OAAO,GAAG,OAAO,CAAC,MAAM;gBAC5B,CAAC,CAAC,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC,OAAO,EAAE,eAAe,EAAE,CAAC,GAAG,OAAO,CAAC,EAAE;gBACrE,CAAC,CAAC,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC;YAClC,MAAM,OAAO,GAAG;gBACd,qCAAqC,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;aACnE,CAAC;YACF,MAAM,EAAE,mBAAmB,EAAE,GAAG,KAAK,CAAC,SAAS,CAAC;YAChD,OAAO,uBAAuB,CAAC;gBAC7B,KAAK,EAAE,GAAG,EAAE,CACV,KAAK,CAAC,SAAS,CAAC,aAAa,CAAC,KAAK,CAAC,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC;gBACpE,MAAM,EAAE,mBAAmB;oBACzB,CAAC,CAAC,GAAG,EAAE,CACH,mBAAmB,CAAC,IAAI,CACtB,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,WAAW,EACjB,OAAO,EACP,EAAE,GAAG,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,CACpC;oBACL,CAAC,CAAC,SAAS;aACd,CAAC,CAAC;QACL,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerAccessManifestState,\n ContainerKekKeyring,\n ContainerKekPredecessorBridge,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerMoveAccessEventBody,\n ContainerUserRecipientKey,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerMutationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerKekResponse,\n ContainerRotationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertContainerAuthorAccess } from \"../../../../data/containers/shared/authorAccess\";\nimport { assertContainerChildPathFits } from \"../../../../data/containers/shared/containerPathLimits\";\nimport {\n asContainerManifestBundle,\n containerManifestRef,\n getTargetContainerContext,\n readContainerState,\n uniqueSortedManifestHashes,\n} from \"../../../../data/containers/shared/projection\";\nimport type {\n BuildMaterializedContainerMovePlanInput,\n ContainerMoveApi,\n ContainerMovePlan,\n ContainerMutationAuthor,\n MaterializedContainerMovePlan,\n} from \"../../../../data/containers/shared/types\";\nimport { unwrapContainerKekPath } from \"../../../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../../../data/keying/canonicalJson\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../../data/keyingProjectionVerification\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../../data/principals/principalPolicyEvidence\";\nimport type { SecurityIncidentReporter } from \"../../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../../data/sqlite/sqlSchema\";\nimport {\n containerMutationRequestCore,\n previousPathRequestFields,\n} from \"../mutationRequestCore\";\nimport {\n submitAcknowledgedContainerMutation,\n submitContainerRotation,\n} from \"../mutationSubmit\";\nimport { containerWriterProjectionFromRotationPlan } from \"../rekey/rekeyProjection\";\nimport {\n requireUnwrappedKek,\n type SignedRotationTarget,\n signedRotationTarget,\n} from \"../rotation/rotationContext\";\nimport {\n buildMoveRotationWithBody,\n deriveMoveManifestArtifacts,\n} from \"./moveArtifacts\";\nimport {\n buildContainerMoveWraps,\n collectContainerMovePrincipalPolicies,\n} from \"./moveWraps\";\n\nfunction buildContainerMoveRequest(input: {\n body: ContainerMoveAccessEventBody;\n destinationParentKek: ContainerKekResponse;\n destinationParentProjection: ContainerWriterProjectionResponse;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n predecessorBridge: ContainerKekPredecessorBridge;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n ...containerMutationRequestCore(\"move\", input),\n ...previousPathRequestFields(\n input.previousManifest,\n input.previousProjection,\n ),\n destinationParentContainerPathRefs:\n input.destinationParentProjection.path.map(containerManifestRef),\n predecessorBridge: readCanonicalRecord(\n input.predecessorBridge,\n \"Container move predecessor bridge\",\n ),\n keyring: readCanonicalRecord(input.keyring, \"Container move keyring\"),\n parentKekState: readCanonicalRecord(\n input.destinationParentKek,\n \"Container move destination parent KEK state\",\n ),\n };\n}\n\nasync function unwrapMoveContainerKeys(input: {\n destinationParentProjection: ContainerWriterProjectionResponse;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n destinationParent: ReturnType<typeof getTargetContainerContext>;\n source: SignedRotationTarget;\n}> {\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const keksByEpochId = await unwrapContainerKekPath({\n execSql: input.execSql,\n projection: input.previousProjection,\n secretKey: input.targetSecretKey,\n verifiedByHash,\n ...projectionVerificationOptions(input),\n });\n const source = signedRotationTarget(input.previousProjection, verifiedByHash);\n const containerKey = requireUnwrappedKek(\n keksByEpochId,\n source.kek,\n \"Container move source\",\n );\n\n const destinationKeksByEpochId = await unwrapContainerKekPath({\n execSql: input.execSql,\n projection: input.destinationParentProjection,\n secretKey: input.targetSecretKey,\n ...projectionVerificationOptions(input),\n });\n const destinationParent = getTargetContainerContext(\n input.destinationParentProjection,\n );\n requireUnwrappedKek(\n destinationKeksByEpochId,\n destinationParent.kek,\n \"Container move destination parent\",\n );\n\n return { containerKey, destinationParent, source };\n}\n\nfunction assertContainerMoveOrganizations(input: {\n authorOrganizationId: string;\n destinationState: ContainerAccessManifestState;\n previousState: ContainerAccessManifestState;\n}): void {\n if (input.previousState.organizationId !== input.authorOrganizationId) {\n throw new Error(\"Container move author organization mismatch\");\n }\n if (input.destinationState.organizationId !== input.authorOrganizationId) {\n throw new Error(\"Container move destination organization mismatch\");\n }\n}\n\nfunction readContainerMoveStates(input: {\n authorOrganizationId: string;\n destinationParent: ReturnType<typeof getTargetContainerContext>;\n source: ReturnType<typeof getTargetContainerContext>;\n}) {\n const previousState = readContainerState(input.source.manifest);\n const destinationState = readContainerState(input.destinationParent.manifest);\n assertContainerMoveOrganizations({\n authorOrganizationId: input.authorOrganizationId,\n destinationState,\n previousState,\n });\n return { destinationState, previousState };\n}\n\nfunction containerMoveDependencyManifestHashes(input: {\n destinationParentProjection: ContainerWriterProjectionResponse;\n previousProjection: ContainerWriterProjectionResponse;\n}): string[] {\n return [\n ...uniqueSortedManifestHashes(input.previousProjection.path),\n ...uniqueSortedManifestHashes(input.destinationParentProjection.path),\n ];\n}\n\nfunction buildContainerMovePlanResult(input: {\n body: ContainerMoveAccessEventBody;\n containerId: string;\n containerKey: Uint8Array;\n containerKeyEpochId: string;\n destinationParentKek: ContainerKekResponse;\n destinationParentProjection: ContainerWriterProjectionResponse;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n predecessorBridge: ContainerKekPredecessorBridge;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}): MaterializedContainerMovePlan {\n const plan: ContainerMovePlan = {\n body: input.body,\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n event: input.event,\n eventHash: input.eventHash,\n keyEpoch: input.keyEpoch,\n keyring: input.keyring,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n previousManifest: input.previousManifest,\n request: buildContainerMoveRequest({\n body: input.body,\n destinationParentKek: input.destinationParentKek,\n destinationParentProjection: input.destinationParentProjection,\n event: input.event,\n keyEpoch: input.keyEpoch,\n keyring: input.keyring,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n previousManifest: input.previousManifest,\n previousProjection: input.previousProjection,\n predecessorBridge: input.predecessorBridge,\n principalPolicies: input.principalPolicies,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n }),\n state: input.state,\n wraps: input.wraps,\n };\n\n return { containerKey: input.containerKey, plan };\n}\n\ntype MaterializedContainerMoveInput =\n BuildMaterializedContainerMovePlanInput & {\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n };\n\nasync function collectAuthorizedMovePolicies(\n input: MaterializedContainerMoveInput,\n) {\n const principalPolicies = await collectContainerMovePrincipalPolicies({\n ...input,\n resolveUserKey: input.resolveProjectionUserKey,\n });\n assertContainerAuthorAccess({\n author: input.author,\n projection: input.previousProjection,\n principalPolicies,\n minimumAccess: \"admin\",\n });\n assertContainerAuthorAccess({\n author: input.author,\n projection: input.destinationParentProjection,\n principalPolicies,\n minimumAccess: \"write\",\n });\n return principalPolicies;\n}\n\nasync function buildMaterializedContainerMovePlan(\n input: MaterializedContainerMoveInput,\n): Promise<MaterializedContainerMovePlan> {\n const {\n containerKey: predecessorContainerKey,\n destinationParent,\n source,\n } = await unwrapMoveContainerKeys({\n destinationParentProjection: input.destinationParentProjection,\n execSql: input.execSql,\n previousProjection: input.previousProjection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // Only a verified path is a final depth refusal; a padded unverified path\n // must fail verification (an incident), never look like an honest refusal.\n assertContainerChildPathFits(input.destinationParentProjection.path);\n const { destinationState, previousState } = readContainerMoveStates({\n authorOrganizationId: input.author.organizationId,\n destinationParent,\n source,\n });\n const principalPolicies = await collectAuthorizedMovePolicies(input);\n const {\n body,\n containerKey,\n containerKeyEpochId,\n keyring,\n predecessorBridge,\n } = await buildMoveRotationWithBody({\n destinationParent,\n destinationState,\n override: input.containerKeyEpochId,\n predecessorContainerKey,\n previousState,\n source,\n });\n const { event, eventHash, keyEpoch, manifest, manifestHash, state } =\n await deriveMoveManifestArtifacts({\n body,\n containerKeyEpochId,\n destinationParent,\n previousState,\n signing: {\n author: input.author,\n dependencyManifestHashes: containerMoveDependencyManifestHashes(input),\n eventId: input.eventId,\n signedAt: input.signedAt,\n },\n source,\n });\n const { userRecipientKeys, wraps } = await buildContainerMoveWraps({\n principalPolicies,\n containerKey,\n containerKeyEpochId,\n destinationParentKek: destinationParent.kek,\n destinationParentProjection: input.destinationParentProjection,\n execSql: input.execSql,\n manifestHash,\n previousProjection: input.previousProjection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n state,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n\n return buildContainerMovePlanResult({\n body,\n containerKey,\n containerId: previousState.containerId,\n containerKeyEpochId,\n destinationParentKek: destinationParent.kek,\n destinationParentProjection: input.destinationParentProjection,\n event,\n eventHash,\n keyEpoch,\n keyring,\n manifest,\n manifestHash,\n previousManifest: asContainerManifestBundle(source.manifest),\n previousProjection: input.previousProjection,\n predecessorBridge,\n principalPolicies,\n state,\n userRecipientKeys,\n wraps,\n });\n}\n\nexport async function moveRemoteContainer(input: {\n reportSecurityIncident: SecurityIncidentReporter;\n apiClient: ContainerMoveApi;\n author: ContainerMutationAuthor;\n containerId: string;\n destinationParentContainerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n plan: ContainerMovePlan;\n response: ContainerRotationResponse;\n} | null> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container move\",\n );\n const [previousProjection, destinationParentProjection] = await Promise.all([\n input.apiClient.getContainerWriterProjection(input.containerId),\n input.apiClient.getContainerWriterProjection(\n input.destinationParentContainerId,\n ),\n ]);\n if (!previousProjection || !destinationParentProjection) {\n return null;\n }\n\n const materializedPlan = await nullOnProjectionVerificationCancellation(() =>\n buildMaterializedContainerMovePlan({\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n destinationParentProjection,\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }),\n );\n if (!materializedPlan) return null;\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n carriedRekeys: {\n planning: {\n apiClient: input.apiClient,\n author: input.author,\n execSql: input.execSql,\n knownContainerKeks: new Map([\n [\n materializedPlan.plan.containerKeyEpochId,\n materializedPlan.containerKey,\n ],\n ]),\n resolveProjectionUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n },\n rotated: () =>\n containerWriterProjectionFromRotationPlan({\n ancestors: destinationParentProjection,\n plan: materializedPlan.plan,\n previousProjection,\n }),\n },\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: (carried) => {\n const request = carried.length\n ? { ...materializedPlan.plan.request, containerRekeys: [...carried] }\n : materializedPlan.plan.request;\n const options = {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n };\n const { moveContainerResult } = input.apiClient;\n return submitContainerRotation({\n plain: () =>\n input.apiClient.moveContainer(input.containerId, request, options),\n result: moveContainerResult\n ? () =>\n moveContainerResult.call(\n input.apiClient,\n input.containerId,\n request,\n { ...options, reportErrors: false },\n )\n : undefined,\n });\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,2BAA2B,EAAE,MAAM,iDAAiD,CAAC;AAC9F,OAAO,EAAE,4BAA4B,EAAE,MAAM,wDAAwD,CAAC;AACtG,OAAO,EACL,yBAAyB,EACzB,yBAAyB,EACzB,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,+CAA+C,CAAC;AAQvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AACxF,OAAO,EACL,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,+CAA+C,CAAC;AAGvD,OAAO,EACL,mCAAmC,EACnC,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,yCAAyC,EAAE,MAAM,0BAA0B,CAAC;AACr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AC,YAAY;QAC3C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,IAAI,EAAE,gBAAgB,CAAC,IAAI;QAC3B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,MAAM,EAAE,CAAC,OAAO,EAAE,EAAE,CAClB,0BAA0B,CAAC,KAAK,EAAE;YAChC,GAAG,gBAAgB,CAAC,IAAI,CAAC,OAAO;YAChC,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,CAAC,GAAG,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC7D,CAAC;KACL,CAAC,CAAC;AACL,CAAC;AAED,SAAS,0BAA0B,CACjC,KAA+B,EAC/B,OAAiC;IAEjC,MAAM,OAAO,GAAG;QACd,qCAAqC,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;KACnE,CAAC;IACF,MAAM,EAAE,mBAAmB,EAAE,GAAG,KAAK,CAAC,SAAS,CAAC;IAChD,OAAO,uBAAuB,CAAC;QAC7B,KAAK,EAAE,GAAG,EAAE,CACV,KAAK,CAAC,SAAS,CAAC,aAAa,CAAC,KAAK,CAAC,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC;QACpE,MAAM,EAAE,mBAAmB;YACzB,CAAC,CAAC,GAAG,EAAE,CACH,mBAAmB,CAAC,IAAI,CACtB,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,WAAW,EACjB,OAAO,EACP;gBACE,GAAG,OAAO;gBACV,YAAY,EAAE,KAAK;aACpB,CACF;YACL,CAAC,CAAC,SAAS;KACd,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { ContainerMutationRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerRotationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertContainerAuthorAccess } from \"../../../../data/containers/shared/authorAccess\";\nimport { assertContainerChildPathFits } from \"../../../../data/containers/shared/containerPathLimits\";\nimport {\n asContainerManifestBundle,\n getTargetContainerContext,\n readContainerState,\n uniqueSortedManifestHashes,\n} from \"../../../../data/containers/shared/projection\";\nimport type {\n BuildMaterializedContainerMovePlanInput,\n ContainerMoveApi,\n ContainerMovePlan,\n ContainerMutationAuthor,\n MaterializedContainerMovePlan,\n} from \"../../../../data/containers/shared/types\";\nimport { unwrapContainerKekPath } from \"../../../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../../../data/documents/shared/types\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../../data/keyingProjectionVerification\";\nimport type { SecurityIncidentReporter } from \"../../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../../data/sqlite/sqlSchema\";\nimport {\n submitAcknowledgedContainerMutation,\n submitContainerRotation,\n} from \"../mutationSubmit\";\nimport { containerWriterProjectionFromRotationPlan } from \"../rekey/rekeyProjection\";\nimport {\n requireUnwrappedKek,\n type SignedRotationTarget,\n signedRotationTarget,\n} from \"../rotation/rotationContext\";\nimport {\n buildMoveRotationWithBody,\n deriveMoveManifestArtifacts,\n} from \"./moveArtifacts\";\nimport { buildContainerMovePlanResult } from \"./moveRequest\";\nimport {\n buildContainerMoveWraps,\n collectContainerMovePrincipalPolicies,\n} from \"./moveWraps\";\n\nasync function unwrapMoveContainerKeys(input: {\n destinationParentProjection: ContainerWriterProjectionResponse;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n destinationParent: ReturnType<typeof getTargetContainerContext>;\n source: SignedRotationTarget;\n}> {\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const keksByEpochId = await unwrapContainerKekPath({\n execSql: input.execSql,\n projection: input.previousProjection,\n secretKey: input.targetSecretKey,\n verifiedByHash,\n ...projectionVerificationOptions(input),\n });\n const source = signedRotationTarget(input.previousProjection, verifiedByHash);\n const containerKey = requireUnwrappedKek(\n keksByEpochId,\n source.kek,\n \"Container move source\",\n );\n\n const destinationKeksByEpochId = await unwrapContainerKekPath({\n execSql: input.execSql,\n projection: input.destinationParentProjection,\n secretKey: input.targetSecretKey,\n ...projectionVerificationOptions(input),\n });\n const destinationParent = getTargetContainerContext(\n input.destinationParentProjection,\n );\n requireUnwrappedKek(\n destinationKeksByEpochId,\n destinationParent.kek,\n \"Container move destination parent\",\n );\n\n return { containerKey, destinationParent, source };\n}\n\nfunction assertContainerMoveOrganizations(input: {\n authorOrganizationId: string;\n destinationState: ContainerAccessManifestState;\n previousState: ContainerAccessManifestState;\n}): void {\n if (input.previousState.organizationId !== input.authorOrganizationId) {\n throw new Error(\"Container move author organization mismatch\");\n }\n if (input.destinationState.organizationId !== input.authorOrganizationId) {\n throw new Error(\"Container move destination organization mismatch\");\n }\n}\n\nfunction readContainerMoveStates(input: {\n authorOrganizationId: string;\n destinationParent: ReturnType<typeof getTargetContainerContext>;\n source: ReturnType<typeof getTargetContainerContext>;\n}) {\n const previousState = readContainerState(input.source.manifest);\n const destinationState = readContainerState(input.destinationParent.manifest);\n assertContainerMoveOrganizations({\n authorOrganizationId: input.authorOrganizationId,\n destinationState,\n previousState,\n });\n return { destinationState, previousState };\n}\n\nfunction containerMoveDependencyManifestHashes(input: {\n destinationParentProjection: ContainerWriterProjectionResponse;\n previousProjection: ContainerWriterProjectionResponse;\n}): string[] {\n return [\n ...uniqueSortedManifestHashes(input.previousProjection.path),\n ...uniqueSortedManifestHashes(input.destinationParentProjection.path),\n ];\n}\n\ntype MaterializedContainerMoveInput =\n BuildMaterializedContainerMovePlanInput & {\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n };\n\nasync function collectAuthorizedMovePolicies(\n input: MaterializedContainerMoveInput,\n) {\n const principalPolicies = await collectContainerMovePrincipalPolicies({\n ...input,\n resolveUserKey: input.resolveProjectionUserKey,\n });\n assertContainerAuthorAccess({\n author: input.author,\n projection: input.previousProjection,\n principalPolicies,\n minimumAccess: \"admin\",\n });\n assertContainerAuthorAccess({\n author: input.author,\n projection: input.destinationParentProjection,\n principalPolicies,\n minimumAccess: \"write\",\n });\n return principalPolicies;\n}\n\n/**\n * The source's verified head already sits under the destination: a move the\n * server accepted but this device never settled, or one another writer made.\n */\nexport interface AppliedContainerMove {\n readonly manifestHash: string;\n readonly state: ContainerAccessManifestState;\n}\n\n/** Verifies both projections and reads the states a move rotates between. */\nasync function verifyContainerMoveSources(\n input: MaterializedContainerMoveInput,\n) {\n const unwrapped = await unwrapMoveContainerKeys({\n destinationParentProjection: input.destinationParentProjection,\n execSql: input.execSql,\n previousProjection: input.previousProjection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // Only a verified path is a final depth refusal; a padded unverified path\n // must fail verification (an incident), never look like an honest refusal.\n assertContainerChildPathFits(input.destinationParentProjection.path);\n return {\n ...unwrapped,\n ...readContainerMoveStates({\n authorOrganizationId: input.author.organizationId,\n destinationParent: unwrapped.destinationParent,\n source: unwrapped.source,\n }),\n };\n}\n\nasync function buildMaterializedContainerMovePlan(\n input: MaterializedContainerMoveInput & { adoptAppliedMove: boolean },\n): Promise<MaterializedContainerMovePlan | { applied: AppliedContainerMove }> {\n const {\n containerKey: predecessorContainerKey,\n destinationParent,\n destinationState,\n previousState,\n source,\n } = await verifyContainerMoveSources(input);\n if (\n input.adoptAppliedMove &&\n previousState.parentContainerId === destinationState.containerId\n )\n return {\n applied: {\n manifestHash: source.manifest.manifestHash,\n state: previousState,\n },\n };\n const principalPolicies = await collectAuthorizedMovePolicies(input);\n const {\n body,\n containerKey,\n containerKeyEpochId,\n keyring,\n predecessorBridge,\n } = await buildMoveRotationWithBody({\n destinationParent,\n destinationState,\n override: input.containerKeyEpochId,\n predecessorContainerKey,\n previousState,\n source,\n });\n const { event, eventHash, keyEpoch, manifest, manifestHash, state } =\n await deriveMoveManifestArtifacts({\n body,\n containerKeyEpochId,\n destinationParent,\n previousState,\n signing: {\n author: input.author,\n dependencyManifestHashes: containerMoveDependencyManifestHashes(input),\n eventId: input.eventId,\n signedAt: input.signedAt,\n },\n source,\n });\n const { userRecipientKeys, wraps } = await buildContainerMoveWraps({\n principalPolicies,\n containerKey,\n containerKeyEpochId,\n destinationParentKek: destinationParent.kek,\n destinationParentProjection: input.destinationParentProjection,\n execSql: input.execSql,\n manifestHash,\n previousProjection: input.previousProjection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n state,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n\n return buildContainerMovePlanResult({\n body,\n containerKey,\n containerId: previousState.containerId,\n containerKeyEpochId,\n destinationParentKek: destinationParent.kek,\n destinationParentProjection: input.destinationParentProjection,\n event,\n eventHash,\n keyEpoch,\n keyring,\n manifest,\n manifestHash,\n previousManifest: asContainerManifestBundle(source.manifest),\n previousProjection: input.previousProjection,\n predecessorBridge,\n principalPolicies,\n state,\n userRecipientKeys,\n wraps,\n });\n}\n\ninterface MoveRemoteContainerInput {\n reportSecurityIncident: SecurityIncidentReporter;\n apiClient: ContainerMoveApi;\n author: ContainerMutationAuthor;\n containerId: string;\n destinationParentContainerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n onAccepted?: (() => void) | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface SubmittedContainerMove {\n containerKey: Uint8Array;\n plan: ContainerMovePlan;\n response: ContainerRotationResponse;\n}\n\n/** Signs and submits a move; `null` when it was refused or abandoned. */\nexport async function moveRemoteContainer(\n input: MoveRemoteContainerInput,\n): Promise<SubmittedContainerMove | null> {\n const moved = await submitRemoteContainerMove(input, false);\n if (moved && \"applied\" in moved)\n throw new Error(\"A move that adopts nothing cannot report one applied\");\n return moved;\n}\n\n/**\n * Replays a queued move. When the verified source head already sits under\n * the destination it signs nothing and returns that head, so a lost response\n * settles without a second rotation.\n */\nexport function replayRemoteContainerMove(\n input: MoveRemoteContainerInput,\n): Promise<SubmittedContainerMove | { applied: AppliedContainerMove } | null> {\n return submitRemoteContainerMove(input, true);\n}\n\nasync function submitRemoteContainerMove(\n input: MoveRemoteContainerInput,\n adoptAppliedMove: boolean,\n): Promise<SubmittedContainerMove | { applied: AppliedContainerMove } | null> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container move\",\n );\n const [previousProjection, destinationParentProjection] = await Promise.all([\n input.apiClient.getContainerWriterProjection(input.containerId),\n input.apiClient.getContainerWriterProjection(\n input.destinationParentContainerId,\n ),\n ]);\n if (!previousProjection || !destinationParentProjection) {\n return null;\n }\n\n const materializedPlan = await nullOnProjectionVerificationCancellation(() =>\n buildMaterializedContainerMovePlan({\n adoptAppliedMove,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n destinationParentProjection,\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }),\n );\n if (!materializedPlan || \"applied\" in materializedPlan)\n return materializedPlan;\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n carriedRekeys: {\n planning: {\n apiClient: input.apiClient,\n author: input.author,\n execSql: input.execSql,\n knownContainerKeks: new Map([\n [\n materializedPlan.plan.containerKeyEpochId,\n materializedPlan.containerKey,\n ],\n ]),\n resolveProjectionUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n },\n rotated: () =>\n containerWriterProjectionFromRotationPlan({\n ancestors: destinationParentProjection,\n plan: materializedPlan.plan,\n previousProjection,\n }),\n },\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n onAccepted: input.onAccepted,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: (carried) =>\n submitContainerMoveRequest(input, {\n ...materializedPlan.plan.request,\n ...(carried.length ? { containerRekeys: [...carried] } : {}),\n }),\n });\n}\n\nfunction submitContainerMoveRequest(\n input: MoveRemoteContainerInput,\n request: ContainerMutationRequest,\n) {\n const options = {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n };\n const { moveContainerResult } = input.apiClient;\n return submitContainerRotation({\n plain: () =>\n input.apiClient.moveContainer(input.containerId, request, options),\n result: moveContainerResult\n ? () =>\n moveContainerResult.call(\n input.apiClient,\n input.containerId,\n request,\n {\n ...options,\n reportErrors: false,\n },\n )\n : undefined,\n });\n}\n"]}
|