@tearleads/client-sdk 0.1.244 → 0.1.246
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/containerContentsPersistence.js +2 -0
- package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -1
- package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataRevalidations.d.ts +22 -0
- package/data/persistence/container-contents/containerMetadataRevalidations.js +52 -0
- package/data/persistence/container-contents/containerMetadataRevalidations.js.map +1 -0
- package/data/sqlite/schema/containerSchema.d.ts +173 -0
- package/data/sqlite/schema/containerSchema.js +18 -0
- package/data/sqlite/schema/containerSchema.js.map +1 -1
- package/data/sqlite/schema/index.d.ts +84 -1
- package/data/sqlite/schema/index.js +1 -1
- package/data/sqlite/schema/index.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +1 -8
- package/internal/api-client/client/apiClientContext.d.ts +1 -0
- package/internal/api-client/client/containerReads.d.ts +1 -0
- package/internal/crypto/keying/accessManifestVerificationTypes.d.ts +8 -2
- package/internal/crypto/keying/accessManifestVerificationTypes.js.map +1 -1
- package/internal/crypto/keying/containerAccess.js +1 -1
- package/internal/crypto/keying/containerAccess.js.map +1 -1
- package/internal/crypto/keying/documentAccess.js +1 -1
- package/internal/crypto/keying/documentAccess.js.map +1 -1
- package/internal/crypto/organizationReplacement.js +5 -6
- package/internal/crypto/organizationReplacement.js.map +1 -1
- package/internal/loro/document.d.ts +5 -0
- package/internal/loro/document.js +17 -0
- package/internal/loro/document.js.map +1 -1
- package/internal/loro/index.d.ts +1 -1
- package/internal/loro/index.js +1 -1
- package/internal/loro/index.js.map +1 -1
- package/internal/validators/operation/attachments.d.ts +0 -12
- package/internal/validators/operation/auth.d.ts +0 -76
- package/internal/validators/operation/containerMutations.d.ts +1 -49
- package/internal/validators/operation/containerMutations.js +1 -1
- package/internal/validators/operation/containerMutations.js.map +1 -1
- package/internal/validators/operation/containerReads.d.ts +2 -0
- package/internal/validators/operation/documentMutations.d.ts +0 -24
- package/internal/validators/operation/documentSync.d.ts +0 -4
- package/internal/validators/operation/organizations.d.ts +0 -88
- package/internal/validators/operation/principals.d.ts +0 -16
- package/internal/validators/request/blob.d.ts +0 -12
- package/internal/validators/request/container.d.ts +0 -16
- package/internal/validators/request/container.js +0 -2
- package/internal/validators/request/container.js.map +1 -1
- package/internal/validators/request/containerMetadata.d.ts +0 -20
- package/internal/validators/request/document.d.ts +0 -22
- package/internal/validators/request/document.js +0 -1
- package/internal/validators/request/document.js.map +1 -1
- package/internal/validators/request/documentSyncSchema.d.ts +0 -4
- package/internal/validators/request/documentSyncSchema.js +0 -1
- package/internal/validators/request/documentSyncSchema.js.map +1 -1
- package/internal/validators/request/organization.d.ts +0 -16
- package/internal/validators/request/organizationProvisioning.d.ts +0 -242
- package/internal/validators/request/principal.d.ts +0 -20
- package/internal/validators/request/registration.d.ts +0 -76
- package/internal/validators/response/container.d.ts +8 -0
- package/internal/validators/response/container.js +1 -0
- package/internal/validators/response/container.js.map +1 -1
- package/internal/validators/response/containerParentLanes.d.ts +2 -0
- package/package.json +1 -1
- package/stores/container-contents/containerContentsStore.js +2 -0
- package/stores/container-contents/containerContentsStore.js.map +1 -1
- package/stores/container-contents/hydration/startupHydration.js +6 -2
- package/stores/container-contents/hydration/startupHydration.js.map +1 -1
- package/stores/container-contents/state.js +5 -1
- package/stores/container-contents/state.js.map +1 -1
- package/stores/container-contents/syncAgent/metadataRevalidation.js +79 -0
- package/stores/container-contents/syncAgent/metadataRevalidation.js.map +1 -0
- package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +6 -0
- package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
- package/stores/container-contents/syncAgent/syncLaneIteration.js +110 -23
- package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
- package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js +3 -0
- package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js.map +1 -1
- package/workflows/container-contents/container-state/remote.js +3 -0
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/containerPersistence.d.ts +1 -0
- package/workflows/container-contents/containerPersistence.js.map +1 -1
- package/workflows/container-contents/metadata/index.js +4 -1
- package/workflows/container-contents/metadata/index.js.map +1 -1
- package/workflows/container-contents/metadata/metadataSyncFollowup.js +9 -0
- package/workflows/container-contents/metadata/metadataSyncFollowup.js.map +1 -1
- package/workflows/container-contents/metadata/metadataTypes.d.ts +2 -0
- package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
- package/workflows/container-contents/remoteHydration/index.js +9 -0
- package/workflows/container-contents/remoteHydration/index.js.map +1 -1
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +31 -0
- package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/types.d.ts +9 -1
- package/workflows/container-contents/remoteHydration/types.js.map +1 -1
- package/workflows/containers/child/mutationRequestCore.js +1 -1
- package/workflows/containers/child/mutationRequestCore.js.map +1 -1
- package/workflows/containers/child/recitePlan.js +0 -1
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/root/create.js +0 -1
- package/workflows/containers/root/create.js.map +1 -1
- package/workflows/documents/linkSet/index.js +0 -1
- package/workflows/documents/linkSet/index.js.map +1 -1
- package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +17 -10
- package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
- package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recitePlan.js","sourceRoot":"","sources":["recitePlan.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,6BAA6B,EAC7B,uBAAuB,EACvB,8BAA8B,EAC9B,wCAAwC,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AK,CAAC,cAAc;QACrD,QAAQ,CAAC,QAAQ,KAAK,IAAI,CAAC,KAAK,CAAC,iBAAiB;QAClD,CAAC,QAAQ,CAAC,UAAU,IAAI,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,UAAU;QACvD,QAAQ,CAAC,YAAY,CAAC,KAAK,KAAK,IAAI,CAAC,KAAK,CAAC,KAAK;QAChD,QAAQ,CAAC,YAAY,CAAC,YAAY,KAAK,IAAI,CAAC,YAAY;QACxD,QAAQ,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS;QAErC,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;AACN,CAAC","sourcesContent":["import {\n computeAccessManifestHash,\n deriveContainerAccessManifest,\n KeyingVerificationError,\n MAX_CONTAINER_RECITATION_EPOCH,\n resolveContainerStatePathUserAccessLevel,\n} from \"@tearleads/crypto\";\nimport type { ContainerReciteRequest } from \"@tearleads/validators/request\";\nimport type { ContainerReciteResponse } from \"@tearleads/validators/response\";\nimport { signContainerMutationEvent } from \"../../../data/containers/shared/events\";\nimport { principalPolicyRef } from \"../../../data/containers/shared/principalPolicies\";\nimport { containerManifestRef } from \"../../../data/containers/shared/projection\";\nimport type { ContainerMutationAuthor } from \"../../../data/containers/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport type { HeldContainerHead } from \"../../../data/keyingProjectionVerification/checkpoints/heldContainerHeads\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../../data/principalContracts/principalPolicyEvidence\";\n\nexport function referencedRecitationPolicies(\n path: readonly HeldContainerHead[],\n policies: readonly PrincipalPolicyCheckpointEvidence[],\n): readonly PrincipalPolicyCheckpointEvidence[] {\n const referencedIds = new Set(\n path.flatMap((head) =>\n head.state.referencedPrincipalHeads.map(\n (ref) => `${ref.principalType}:${ref.principalId}`,\n ),\n ),\n );\n return policies.filter((policy) =>\n referencedIds.has(`${policy.principalType}:${policy.principalId}`),\n );\n}\n\nexport async function buildContainerRecitePlan(input: {\n readonly author: ContainerMutationAuthor;\n readonly path: readonly HeldContainerHead[];\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n}) {\n const previous = input.path.at(-1);\n if (!previous) throw new Error(\"Recitation requires a held container path\");\n if (previous.state.epoch >= MAX_CONTAINER_RECITATION_EPOCH) {\n throw new Error(\"Container re-citation history budget is exhausted\");\n }\n if (\n input.path.some(\n (head) => head.state.organizationId !== input.author.organizationId,\n )\n ) {\n throw new Error(\"Recitation cannot cross organizations\");\n }\n if (\n resolveContainerStatePathUserAccessLevel({\n states: input.path.map((head) => head.state),\n principalPolicies: input.policies,\n userId: input.author.signerUserId,\n }) !== \"admin\"\n ) {\n throw new KeyingVerificationError(\n \"unauthorized\",\n \"Container re-citation signer lacks admin access on the held path\",\n );\n }\n const body = {\n eventType: \"container.recite\" as const,\n containerKeyEpochId: previous.state.containerKeyEpochId,\n containerKeyPublicKey: previous.state.containerKeyPublicKey,\n };\n const { event, eventHash } = await signContainerMutationEvent({\n author: input.author,\n body,\n containerId: previous.state.containerId,\n dependencyManifestHashes: input.path.map(\n (head) => head.bundle.manifestHash,\n ),\n eventId: crypto.randomUUID(),\n previousManifestHash: previous.bundle.manifestHash,\n signedAt: new Date().toISOString(),\n });\n const state = {\n ...previous.state,\n epoch: previous.state.epoch + 1,\n eventHash,\n previousManifestHash: previous.bundle.manifestHash,\n };\n const manifest = await deriveContainerAccessManifest(state);\n const manifestHash = await computeAccessManifestHash(manifest);\n const request: ContainerReciteRequest = {\n body,\n event: readCanonicalRecord(event, \"Recitation event\"),\n expectedManifestHash: manifestHash,\n previousManifestRef: containerManifestRef(previous.bundle),\n previousContainerPathRefs: input.path.map((head) =>\n containerManifestRef(head.bundle),\n ),\n principalPolicyRefs: referencedRecitationPolicies(\n input.path,\n input.policies,\n ).map(principalPolicyRef),\n };\n return { body, event, eventHash, manifest, manifestHash, state, request };\n}\n\nexport function assertContainerReciteAcknowledgement(\n plan: Awaited<ReturnType<typeof buildContainerRecitePlan>>,\n response: ContainerReciteResponse,\n): void {\n // The manifest hash commits to the signed event, the derived state, and\n // the cited principal heads, so equal hashes acknowledge exactly this plan.\n if (\n response.containerId !== plan.state.containerId ||\n response.organizationId !== plan.state.organizationId ||\n response.parentId !== plan.state.parentContainerId ||\n (response.systemSlot ?? null) !== plan.state.systemSlot ||\n response.manifestHead.epoch !== plan.state.epoch ||\n response.manifestHead.manifestHash !== plan.manifestHash ||\n response.eventHash !== plan.eventHash\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Container recitation response does not match the signed plan\",\n );\n}\n"]}
|
|
@@ -54,7 +54,6 @@ function buildRootContainerCreateRequest(input) {
|
|
|
54
54
|
event: readCanonicalRecord(input.event, "Container root create event"),
|
|
55
55
|
body: readCanonicalRecord(input.body, "Container root create body"),
|
|
56
56
|
expectedManifestHash: input.manifestHash,
|
|
57
|
-
manifest: readCanonicalRecord(input.manifest, "Container root create manifest"),
|
|
58
57
|
previousManifestRef: null,
|
|
59
58
|
parentContainerPathRefs: [],
|
|
60
59
|
principalPolicyRefs: input.principalPolicyRefs,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.js","sourceRoot":"","sources":["create.ts"],"names":[],"mappings":"AASA,OAAO,EACL,sCAAsC,EACtC,4BAA4B,EAC5B,mCAAmC,EACnC,iCAAiC,EACjC,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,6BAA6B,EAC7B,0BAA0B,EAC1B,wBAAwB,GACzB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mDAAmD,CAAC;AACvF,OAAO,EACL,kCAAkC,EAClC,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AAMpD,OAAO,EACL,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EAAE,mCAAmC,EAAE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AAY;gBACrC,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;gBAC7C,iBAAiB,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ;gBACzC,QAAQ,EAAE,mBAAmB,CAC3B,IAAI,CAAC,QAAQ,EACb,0BAA0B,CAC3B;gBACD,YAAY,EAAE,IAAI,CAAC,YAAY;gBAC/B,aAAa,EAAE,IAAI,CAAC,aAAa;gBACjC,wBAAwB,EAAE,EAAE;gBAC5B,yBAAyB,EAAE,IAAI;gBAC/B,OAAO,EAAE,IAAI;gBACb,gBAAgB,EAAE,oBAAoB,CACpC,IAAI,CAAC,gBAAgB,EACrB,kCAAkC,CACnC;gBACD,KAAK,EAAE,oBAAoB,CAAC,IAAI,CAAC,KAAK,EAAE,sBAAsB,CAAC;aAChE;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerCreateAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport {\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n deriveContainerKekWrappingPublicKey,\n normalizeContainerAccessEventBody,\n readKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationRequest,\n CreateOrganizationGroupRequest,\n} from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n buildContainerCreateBody,\n buildContainerCreateKeyEpoch,\n deriveContainerCreateManifest,\n resolveContainerKekEpochId,\n signContainerCreateEvent,\n} from \"../../../data/containers/shared/events\";\nimport { principalPolicyRef } from \"../../../data/containers/shared/principalPolicies\";\nimport {\n wrapContainerKeyToManagedPrincipal,\n wrapContainerKeyToRootUser,\n} from \"../../../data/containers/shared/projection\";\nimport type {\n ContainerCreatePlan,\n ContainerMutationAuthor,\n MaterializedContainerCreatePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n readCanonicalRecord,\n readCanonicalRecords,\n} from \"../../../data/keying/canonicalJson\";\n\nimport { principalHeadFromInitialGroupPolicy } from \"./initialGroupPolicy\";\n\nfunction buildRootContainerCreateBody(input: {\n author: ContainerMutationAuthor;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n containerKeyEpochId: string;\n containerKeyPublicKey: string;\n metadataDocumentId: string;\n memberHead: ContainerGrantPrincipalHead | null;\n systemSlot: ContainerSystemSlot | null;\n}): ContainerCreateAccessEventBody {\n const baseBody = buildContainerCreateBody({\n systemSlot: input.systemSlot,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.containerKeyPublicKey,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n });\n if (input.managedPrincipalHead) {\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.managedPrincipalHead.principalId,\n subjectType: input.managedPrincipalHead.principalType,\n },\n ...(input.memberHead\n ? [\n {\n accessLevel: \"read\" as const,\n subjectId: input.memberHead.principalId,\n subjectType: \"group\" as const,\n },\n ]\n : []),\n ],\n referencedPrincipalHeads: [\n input.managedPrincipalHead,\n ...(input.memberHead ? [input.memberHead] : []),\n ],\n };\n }\n\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.author.signerUserId,\n subjectType: \"user\",\n },\n ],\n };\n}\n\nfunction buildRootContainerCreateRequest(input: {\n body: ContainerCreateAccessEventBody;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n principalPolicyRefs: ContainerMutationRequest[\"principalPolicyRefs\"];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n event: readCanonicalRecord(input.event, \"Container root create event\"),\n body: readCanonicalRecord(input.body, \"Container root create body\"),\n expectedManifestHash: input.manifestHash,\n manifest: readCanonicalRecord(\n input.manifest,\n \"Container root create manifest\",\n ),\n previousManifestRef: null,\n parentContainerPathRefs: [],\n principalPolicyRefs: input.principalPolicyRefs,\n keyEpoch: readCanonicalRecord(\n input.keyEpoch,\n \"Container root create key epoch\",\n ),\n predecessorBridge: null,\n keyring: null,\n wraps: readCanonicalRecords(input.wraps, \"Container root create wraps\"),\n userRecipientKeys: readCanonicalRecords(\n input.userRecipientKeys,\n \"Container root create user recipient keys\",\n ),\n };\n}\n\nasync function rootManagedPrincipalHead(\n group: CreateOrganizationGroupRequest | null,\n): Promise<ContainerGrantPrincipalHead | null> {\n return group\n ? principalHeadFromInitialGroupPolicy({\n principalId: group.groupId,\n policy: group.initialGroupPolicy,\n })\n : null;\n}\n\nasync function deriveRootCreateArtifacts(input: {\n author: ContainerMutationAuthor;\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n metadataDocumentId: string;\n signedAt: string | undefined;\n}) {\n if (!input.body.containerKeyPublicKey)\n throw new Error(\"Root container public key is missing\");\n const { event, eventHash } = await signContainerCreateEvent({\n author: input.author,\n body: input.body,\n containerId: input.containerId,\n eventId: crypto.randomUUID(),\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentPath: [],\n signedAt: input.signedAt ?? new Date().toISOString(),\n });\n const { manifest, manifestHash, state } = await deriveContainerCreateManifest(\n {\n systemSlot: input.body.systemSlot,\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.body.containerKeyPublicKey,\n directGrants: input.body.directGrants,\n eventHash,\n metadataDocumentId: input.metadataDocumentId,\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentContainerId: null,\n parentManifestHash: null,\n referencedPrincipalHeads: input.body.referencedPrincipalHeads,\n },\n );\n const keyEpoch = buildContainerCreateKeyEpoch({\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n eventHash,\n manifestHash,\n parentContainerKeyEpochId: null,\n });\n return { event, eventHash, keyEpoch, manifest, manifestHash, state };\n}\n\nasync function wrapRootContainerKeyForPlan(input: {\n adminGroup: CreateOrganizationGroupRequest | null;\n containerKey: Uint8Array;\n containerKeyEpochId: string;\n manifestHash: string;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n recipientEncapsulationPublicKey: Uint8Array;\n userId: string;\n}) {\n if (input.adminGroup && input.managedPrincipalHead) {\n return {\n ...(await wrapContainerKeyToManagedPrincipal({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n principalEncapsulationPublicKey:\n input.adminGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.managedPrincipalHead,\n })),\n userRecipientKey: null,\n };\n }\n\n return wrapContainerKeyToRootUser({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.userId,\n });\n}\n\nasync function wrapRootContainerRecipients(\n input: Parameters<typeof wrapRootContainerKeyForPlan>[0] & {\n memberGroup: CreateOrganizationGroupRequest | null;\n memberHead: ContainerGrantPrincipalHead | null;\n },\n) {\n const root = await wrapRootContainerKeyForPlan(input);\n const member =\n input.memberGroup && input.memberHead\n ? await wrapContainerKeyToManagedPrincipal({\n ...input,\n principalEncapsulationPublicKey:\n input.memberGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.memberHead,\n })\n : null;\n return {\n recipientTargets: [\n root.recipientTarget,\n ...(member ? [member.recipientTarget] : []),\n ],\n wraps: [root.wrap, ...(member ? [member.wrap] : [])],\n userRecipientKeys: root.userRecipientKey ? [root.userRecipientKey] : [],\n };\n}\n\nfunction rootKeyMaterial(key?: Uint8Array): Uint8Array {\n const material = key ?? crypto.getRandomValues(new Uint8Array(32));\n if (material.byteLength !== 32)\n throw new Error(\"Container KEK material must be 32 bytes\");\n return material;\n}\n\nfunction normalizedRootCreateBody(\n input: Parameters<typeof buildRootContainerCreateBody>[0],\n): ContainerCreateAccessEventBody {\n const body = normalizeContainerAccessEventBody(\n readKeyingCanonicalJson(\n buildRootContainerCreateBody(input),\n \"Root create body\",\n ),\n );\n if (body.eventType !== \"container.create\")\n throw new Error(\"Expected root creation body\");\n return body;\n}\n\nexport async function buildRootContainerCreatePlan(input: {\n adminGroup?: CreateOrganizationGroupRequest | undefined;\n memberGroup?: CreateOrganizationGroupRequest | undefined;\n systemSlot?: ContainerSystemSlot | undefined;\n author: ContainerMutationAuthor;\n containerId: string;\n containerKey?: Uint8Array | undefined;\n metadataDocumentId: string;\n recipientEncapsulationPublicKey: Uint8Array;\n signedAt?: string | undefined;\n}): Promise<MaterializedContainerCreatePlan> {\n const containerKey = rootKeyMaterial(input.containerKey);\n const adminGroup = input.adminGroup ?? null;\n const managedPrincipalHead = await rootManagedPrincipalHead(adminGroup);\n const memberHead = await rootManagedPrincipalHead(input.memberGroup ?? null);\n if (input.memberGroup && !adminGroup)\n throw new Error(\"Members root grant requires Admins authority\");\n const containerKeyEpochId = await resolveContainerKekEpochId({\n containerId: input.containerId,\n keyEpoch: 1,\n keyMaterial: containerKey,\n });\n const body = normalizedRootCreateBody({\n containerKeyPublicKey: await deriveContainerKekWrappingPublicKey({\n containerId: input.containerId,\n keyMaterial: containerKey,\n }),\n memberHead,\n systemSlot: input.systemSlot ?? null,\n author: input.author,\n containerKeyEpochId,\n managedPrincipalHead,\n metadataDocumentId: input.metadataDocumentId,\n });\n const { event, eventHash, keyEpoch, manifest, manifestHash, state } =\n await deriveRootCreateArtifacts({\n author: input.author,\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n metadataDocumentId: input.metadataDocumentId,\n signedAt: input.signedAt,\n });\n const { recipientTargets, wraps, userRecipientKeys } =\n await wrapRootContainerRecipients({\n memberGroup: input.memberGroup ?? null,\n memberHead,\n adminGroup,\n containerKey,\n containerKeyEpochId,\n manifestHash,\n managedPrincipalHead,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.author.signerUserId,\n });\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n const plan: ContainerCreatePlan = {\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n event,\n eventHash,\n keyEpoch,\n keyEpochHash,\n keyTargetHash,\n manifest,\n manifestHash,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n recipientTargets,\n request: buildRootContainerCreateRequest({\n body,\n event,\n keyEpoch,\n manifest,\n manifestHash,\n principalPolicyRefs: [managedPrincipalHead, memberHead]\n .filter((head) => head !== null)\n .map(principalPolicyRef),\n userRecipientKeys,\n wraps,\n }),\n state,\n wraps,\n };\n\n return { containerKey, plan };\n}\n\nexport function rootContainerWriterProjectionFromCreatePlan(\n plan: ContainerCreatePlan,\n): ContainerWriterProjectionResponse {\n return {\n policyEvidence: {\n organization: null,\n organizationPayloads: [],\n groups: [],\n },\n containerId: plan.containerId,\n organizationId: plan.state.organizationId,\n path: [\n {\n event: {\n event: readCanonicalRecord(plan.event, \"Container root event\"),\n body: readCanonicalRecord(plan.body, \"Container root body\"),\n eventHash: plan.eventHash,\n },\n manifest: readCanonicalRecord(plan.manifest, \"Container root manifest\"),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord(plan.state, \"Container root state\"),\n },\n ],\n containerKeks: [\n {\n containerId: plan.containerId,\n accessManifestHash: plan.manifestHash,\n containerKeyEpochId: plan.containerKeyEpochId,\n containerKeyEpoch: plan.keyEpoch.keyEpoch,\n keyEpoch: readCanonicalRecord(\n plan.keyEpoch,\n \"Container root key epoch\",\n ),\n keyEpochHash: plan.keyEpochHash,\n keyTargetHash: plan.keyTargetHash,\n containerManifestHistory: [],\n parentContainerKeyEpochId: null,\n keyring: null,\n recipientTargets: readCanonicalRecords(\n plan.recipientTargets,\n \"Container root recipient targets\",\n ),\n wraps: readCanonicalRecords(plan.wraps, \"Container root wraps\"),\n },\n ],\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"create.js","sourceRoot":"","sources":["create.ts"],"names":[],"mappings":"AASA,OAAO,EACL,sCAAsC,EACtC,4BAA4B,EAC5B,mCAAmC,EACnC,iCAAiC,EACjC,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,6BAA6B,EAC7B,0BAA0B,EAC1B,wBAAwB,GACzB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mDAAmD,CAAC;AACvF,OAAO,EACL,kCAAkC,EAClC,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AAMpD,OAAO,EACL,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EAAE,mCAAmC,EAAE,MAAM,sBAAsB,CAAC;AAE3E,SAAS,4BAA4B,CAAC,KAQrC;IACC,MAAM,QAAQ,GAAG,wBAAwB,CAAC;QACxC,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,iBAAiB,EAAE,IAAI;QACvB,kBAAkB,EAAE,IAAI;KACzB,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,oBAAoB,EAAE,CAAC;QAC/B,OAAO;YACL,GAAG,QAAQ;YACX,YAAY,EAAE;gBACZ;oBACE,WAAW,EAAE,OAAO;oBACpB,SAAS,EAAE,KAAK,CAAC,oBAAoB,CAAC,WAAW;oBACjD,WAAW,EAAE,KAAK,CAAC,oBAAoB,CAAC,aAAa;iBACtD;gBACD,GAAG,CAAC,KAAK,CAAC,UAAU;oBAClB,CAAC,CAAC;wBACE;4BACE,WAAW,EAAE,MAAe;4BAC5B,SAAS,EAA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,KAAK,EAAE;oBACL,KAAK,EAAE,mBAAmB,CAAC,IAAI,CAAC,KAAK,EAAE,sBAAsB,CAAC;oBAC9D,IAAI,EAAE,mBAAmB,CAAC,IAAI,CAAC,IAAI,EAAE,qBAAqB,CAAC;oBAC3D,SAAS,EAAE,IAAI,CAAC,SAAS;iBAC1B;gBACD,QAAQ,EAAE,mBAAmB,CAAC,IAAI,CAAC,QAAQ,EAAE,yBAAyB,CAAC;gBACvE,YAAY,EAAE,IAAI,CAAC,YAAY;gBAC/B,KAAK,EAAE,mBAAmB,CAAC,IAAI,CAAC,KAAK,EAAE,sBAAsB,CAAC;aAC/D;SACF;QACD,aAAa,EAAE;YACb;gBACE,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,kBAAkB,EAAE,IAAI,CAAC,YAAY;gBACrC,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;gBAC7C,iBAAiB,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ;gBACzC,QAAQ,EAAE,mBAAmB,CAC3B,IAAI,CAAC,QAAQ,EACb,0BAA0B,CAC3B;gBACD,YAAY,EAAE,IAAI,CAAC,YAAY;gBAC/B,aAAa,EAAE,IAAI,CAAC,aAAa;gBACjC,wBAAwB,EAAE,EAAE;gBAC5B,yBAAyB,EAAE,IAAI;gBAC/B,OAAO,EAAE,IAAI;gBACb,gBAAgB,EAAE,oBAAoB,CACpC,IAAI,CAAC,gBAAgB,EACrB,kCAAkC,CACnC;gBACD,KAAK,EAAE,oBAAoB,CAAC,IAAI,CAAC,KAAK,EAAE,sBAAsB,CAAC;aAChE;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerCreateAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport {\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n deriveContainerKekWrappingPublicKey,\n normalizeContainerAccessEventBody,\n readKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationRequest,\n CreateOrganizationGroupRequest,\n} from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n buildContainerCreateBody,\n buildContainerCreateKeyEpoch,\n deriveContainerCreateManifest,\n resolveContainerKekEpochId,\n signContainerCreateEvent,\n} from \"../../../data/containers/shared/events\";\nimport { principalPolicyRef } from \"../../../data/containers/shared/principalPolicies\";\nimport {\n wrapContainerKeyToManagedPrincipal,\n wrapContainerKeyToRootUser,\n} from \"../../../data/containers/shared/projection\";\nimport type {\n ContainerCreatePlan,\n ContainerMutationAuthor,\n MaterializedContainerCreatePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n readCanonicalRecord,\n readCanonicalRecords,\n} from \"../../../data/keying/canonicalJson\";\n\nimport { principalHeadFromInitialGroupPolicy } from \"./initialGroupPolicy\";\n\nfunction buildRootContainerCreateBody(input: {\n author: ContainerMutationAuthor;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n containerKeyEpochId: string;\n containerKeyPublicKey: string;\n metadataDocumentId: string;\n memberHead: ContainerGrantPrincipalHead | null;\n systemSlot: ContainerSystemSlot | null;\n}): ContainerCreateAccessEventBody {\n const baseBody = buildContainerCreateBody({\n systemSlot: input.systemSlot,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.containerKeyPublicKey,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n });\n if (input.managedPrincipalHead) {\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.managedPrincipalHead.principalId,\n subjectType: input.managedPrincipalHead.principalType,\n },\n ...(input.memberHead\n ? [\n {\n accessLevel: \"read\" as const,\n subjectId: input.memberHead.principalId,\n subjectType: \"group\" as const,\n },\n ]\n : []),\n ],\n referencedPrincipalHeads: [\n input.managedPrincipalHead,\n ...(input.memberHead ? [input.memberHead] : []),\n ],\n };\n }\n\n return {\n ...baseBody,\n directGrants: [\n {\n accessLevel: \"admin\",\n subjectId: input.author.signerUserId,\n subjectType: \"user\",\n },\n ],\n };\n}\n\nfunction buildRootContainerCreateRequest(input: {\n body: ContainerCreateAccessEventBody;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n principalPolicyRefs: ContainerMutationRequest[\"principalPolicyRefs\"];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n event: readCanonicalRecord(input.event, \"Container root create event\"),\n body: readCanonicalRecord(input.body, \"Container root create body\"),\n expectedManifestHash: input.manifestHash,\n previousManifestRef: null,\n parentContainerPathRefs: [],\n principalPolicyRefs: input.principalPolicyRefs,\n keyEpoch: readCanonicalRecord(\n input.keyEpoch,\n \"Container root create key epoch\",\n ),\n predecessorBridge: null,\n keyring: null,\n wraps: readCanonicalRecords(input.wraps, \"Container root create wraps\"),\n userRecipientKeys: readCanonicalRecords(\n input.userRecipientKeys,\n \"Container root create user recipient keys\",\n ),\n };\n}\n\nasync function rootManagedPrincipalHead(\n group: CreateOrganizationGroupRequest | null,\n): Promise<ContainerGrantPrincipalHead | null> {\n return group\n ? principalHeadFromInitialGroupPolicy({\n principalId: group.groupId,\n policy: group.initialGroupPolicy,\n })\n : null;\n}\n\nasync function deriveRootCreateArtifacts(input: {\n author: ContainerMutationAuthor;\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n metadataDocumentId: string;\n signedAt: string | undefined;\n}) {\n if (!input.body.containerKeyPublicKey)\n throw new Error(\"Root container public key is missing\");\n const { event, eventHash } = await signContainerCreateEvent({\n author: input.author,\n body: input.body,\n containerId: input.containerId,\n eventId: crypto.randomUUID(),\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentPath: [],\n signedAt: input.signedAt ?? new Date().toISOString(),\n });\n const { manifest, manifestHash, state } = await deriveContainerCreateManifest(\n {\n systemSlot: input.body.systemSlot,\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n containerKeyPublicKey: input.body.containerKeyPublicKey,\n directGrants: input.body.directGrants,\n eventHash,\n metadataDocumentId: input.metadataDocumentId,\n // A root container belongs to the creator's own organization.\n organizationId: input.author.organizationId,\n parentContainerId: null,\n parentManifestHash: null,\n referencedPrincipalHeads: input.body.referencedPrincipalHeads,\n },\n );\n const keyEpoch = buildContainerCreateKeyEpoch({\n containerId: input.containerId,\n containerKeyEpochId: input.containerKeyEpochId,\n eventHash,\n manifestHash,\n parentContainerKeyEpochId: null,\n });\n return { event, eventHash, keyEpoch, manifest, manifestHash, state };\n}\n\nasync function wrapRootContainerKeyForPlan(input: {\n adminGroup: CreateOrganizationGroupRequest | null;\n containerKey: Uint8Array;\n containerKeyEpochId: string;\n manifestHash: string;\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n recipientEncapsulationPublicKey: Uint8Array;\n userId: string;\n}) {\n if (input.adminGroup && input.managedPrincipalHead) {\n return {\n ...(await wrapContainerKeyToManagedPrincipal({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n principalEncapsulationPublicKey:\n input.adminGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.managedPrincipalHead,\n })),\n userRecipientKey: null,\n };\n }\n\n return wrapContainerKeyToRootUser({\n containerKey: input.containerKey,\n containerKeyEpochId: input.containerKeyEpochId,\n manifestHash: input.manifestHash,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.userId,\n });\n}\n\nasync function wrapRootContainerRecipients(\n input: Parameters<typeof wrapRootContainerKeyForPlan>[0] & {\n memberGroup: CreateOrganizationGroupRequest | null;\n memberHead: ContainerGrantPrincipalHead | null;\n },\n) {\n const root = await wrapRootContainerKeyForPlan(input);\n const member =\n input.memberGroup && input.memberHead\n ? await wrapContainerKeyToManagedPrincipal({\n ...input,\n principalEncapsulationPublicKey:\n input.memberGroup.initialGroupPolicy.state.encapsulationPublicKey,\n principalHead: input.memberHead,\n })\n : null;\n return {\n recipientTargets: [\n root.recipientTarget,\n ...(member ? [member.recipientTarget] : []),\n ],\n wraps: [root.wrap, ...(member ? [member.wrap] : [])],\n userRecipientKeys: root.userRecipientKey ? [root.userRecipientKey] : [],\n };\n}\n\nfunction rootKeyMaterial(key?: Uint8Array): Uint8Array {\n const material = key ?? crypto.getRandomValues(new Uint8Array(32));\n if (material.byteLength !== 32)\n throw new Error(\"Container KEK material must be 32 bytes\");\n return material;\n}\n\nfunction normalizedRootCreateBody(\n input: Parameters<typeof buildRootContainerCreateBody>[0],\n): ContainerCreateAccessEventBody {\n const body = normalizeContainerAccessEventBody(\n readKeyingCanonicalJson(\n buildRootContainerCreateBody(input),\n \"Root create body\",\n ),\n );\n if (body.eventType !== \"container.create\")\n throw new Error(\"Expected root creation body\");\n return body;\n}\n\nexport async function buildRootContainerCreatePlan(input: {\n adminGroup?: CreateOrganizationGroupRequest | undefined;\n memberGroup?: CreateOrganizationGroupRequest | undefined;\n systemSlot?: ContainerSystemSlot | undefined;\n author: ContainerMutationAuthor;\n containerId: string;\n containerKey?: Uint8Array | undefined;\n metadataDocumentId: string;\n recipientEncapsulationPublicKey: Uint8Array;\n signedAt?: string | undefined;\n}): Promise<MaterializedContainerCreatePlan> {\n const containerKey = rootKeyMaterial(input.containerKey);\n const adminGroup = input.adminGroup ?? null;\n const managedPrincipalHead = await rootManagedPrincipalHead(adminGroup);\n const memberHead = await rootManagedPrincipalHead(input.memberGroup ?? null);\n if (input.memberGroup && !adminGroup)\n throw new Error(\"Members root grant requires Admins authority\");\n const containerKeyEpochId = await resolveContainerKekEpochId({\n containerId: input.containerId,\n keyEpoch: 1,\n keyMaterial: containerKey,\n });\n const body = normalizedRootCreateBody({\n containerKeyPublicKey: await deriveContainerKekWrappingPublicKey({\n containerId: input.containerId,\n keyMaterial: containerKey,\n }),\n memberHead,\n systemSlot: input.systemSlot ?? null,\n author: input.author,\n containerKeyEpochId,\n managedPrincipalHead,\n metadataDocumentId: input.metadataDocumentId,\n });\n const { event, eventHash, keyEpoch, manifest, manifestHash, state } =\n await deriveRootCreateArtifacts({\n author: input.author,\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n metadataDocumentId: input.metadataDocumentId,\n signedAt: input.signedAt,\n });\n const { recipientTargets, wraps, userRecipientKeys } =\n await wrapRootContainerRecipients({\n memberGroup: input.memberGroup ?? null,\n memberHead,\n adminGroup,\n containerKey,\n containerKeyEpochId,\n manifestHash,\n managedPrincipalHead,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n userId: input.author.signerUserId,\n });\n const keyTargetHash =\n await computeContainerKekRecipientTargetHash(recipientTargets);\n const keyEpochHash = await computeContainerKeyEpochHash(keyEpoch);\n const plan: ContainerCreatePlan = {\n body,\n containerId: input.containerId,\n containerKeyEpochId,\n event,\n eventHash,\n keyEpoch,\n keyEpochHash,\n keyTargetHash,\n manifest,\n manifestHash,\n metadataDocumentId: input.metadataDocumentId,\n parentContainerId: null,\n parentManifestHash: null,\n recipientTargets,\n request: buildRootContainerCreateRequest({\n body,\n event,\n keyEpoch,\n manifest,\n manifestHash,\n principalPolicyRefs: [managedPrincipalHead, memberHead]\n .filter((head) => head !== null)\n .map(principalPolicyRef),\n userRecipientKeys,\n wraps,\n }),\n state,\n wraps,\n };\n\n return { containerKey, plan };\n}\n\nexport function rootContainerWriterProjectionFromCreatePlan(\n plan: ContainerCreatePlan,\n): ContainerWriterProjectionResponse {\n return {\n policyEvidence: {\n organization: null,\n organizationPayloads: [],\n groups: [],\n },\n containerId: plan.containerId,\n organizationId: plan.state.organizationId,\n path: [\n {\n event: {\n event: readCanonicalRecord(plan.event, \"Container root event\"),\n body: readCanonicalRecord(plan.body, \"Container root body\"),\n eventHash: plan.eventHash,\n },\n manifest: readCanonicalRecord(plan.manifest, \"Container root manifest\"),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord(plan.state, \"Container root state\"),\n },\n ],\n containerKeks: [\n {\n containerId: plan.containerId,\n accessManifestHash: plan.manifestHash,\n containerKeyEpochId: plan.containerKeyEpochId,\n containerKeyEpoch: plan.keyEpoch.keyEpoch,\n keyEpoch: readCanonicalRecord(\n plan.keyEpoch,\n \"Container root key epoch\",\n ),\n keyEpochHash: plan.keyEpochHash,\n keyTargetHash: plan.keyTargetHash,\n containerManifestHistory: [],\n parentContainerKeyEpochId: null,\n keyring: null,\n recipientTargets: readCanonicalRecords(\n plan.recipientTargets,\n \"Container root recipient targets\",\n ),\n wraps: readCanonicalRecords(plan.wraps, \"Container root wraps\"),\n },\n ],\n };\n}\n"]}
|
|
@@ -160,7 +160,6 @@ async function buildDocumentLinkSetMutationPlan({ author, blobRewraps, contentKe
|
|
|
160
160
|
event: readCanonicalRecord(eventPlan.event, "Document link-set event"),
|
|
161
161
|
body: readCanonicalRecord(eventPlan.body, "Document link-set body"),
|
|
162
162
|
expectedManifestHash: manifestHash,
|
|
163
|
-
manifest: readCanonicalRecord(manifest, "Document link-set manifest"),
|
|
164
163
|
targetContainerPathRefs,
|
|
165
164
|
authorizingContainerPathRefs: eventPlan.authorizingContainerPathRefs,
|
|
166
165
|
contentKeyBundle: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,mCAAmC,EACnC,+BAA+B,EAG/B,6BAA6B,EAC7B,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAMrF,OAAO,EACL,yCAAyC,EACzC,qCAAqC,GACtC,MAAM,4BAA4B,CAAC;AACpC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YAChC,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;YACxC,GAAG,mBAAmB;SACvB,CAAC,CACH,CAAC,aAAa;QACf,mEAAmE;QACnE,+DAA+D;QAC/D,OAAO,EAAE,2BAA2B,CAAC;YACnC,kBAAkB,EAAE,IAAI,CAAC,WAAW,CAAC,kBAAkB;YACvD,aAAa,EAAE,IAAI,CAAC,WAAW,CAAC,OAAO;YACvC,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;SACzC,CAAC;KACH,CAAC,CAAC;AACL,CAAC;AAED,SAAS,6BAA6B,CACpC,KAGC,EACD,kBAAqC;IAErC,0FAA0F;IAC1F,6BAA6B,CAC3B,KAAK,CAAC,gBAAgB,EACtB,IAAI,GAAG,CAAC,kBAAkB,CAAC,CAC5B,CAAC;IACF,IAAI,KAAK,CAAC,SAAS,KAAK,MAAM,EAAE,CAAC;QAC/B,6BAA6B,CAC3B,KAAK,CAAC,yBAAyB,CAAC,aAAa,CAC9C,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n computeAccessManifestHash,\n computeDocumentContentKeyTargetHash,\n DOCUMENT_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkSetManifestState,\n deriveDocumentLinkSetManifest,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type { DocumentContentKeyTargetEnvelope } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS,\n MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS,\n} from \"@tearleads/validators/util\";\nimport {\n assertContainerKekPathCurrent,\n assertDocumentKekPathsCurrent,\n} from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { buildDocumentLinkSetEventPlan } from \"../../../data/documents/shared/events\";\nimport {\n assertDocumentWriterProjectionConsistent,\n collectContainerKeksForDocumentSync,\n containerPathRefs,\n currentDocumentTargets,\n deriveDocumentTargetFromProjection,\n mergeTargetEnvelopes,\n readLinkedContainerIdsFromDocumentManifest,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyFromWriterProjection,\n verifiedDocumentWrapTargets,\n} from \"../../../data/documents/shared/projection\";\nimport {\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n assertDocumentManifestBundleConsistent,\n describeDocumentTargetKek,\n sortDocumentTargets,\n targetKey,\n uniqueSortedStrings,\n} from \"../../../data/documents/shared/readers\";\nimport type {\n BuildDocumentLinkSetMutationPlanInput,\n DocumentCreateAuthor,\n DocumentLinkSetMutationOperation,\n DocumentLinkSetMutationPlan,\n DocumentLinkSetTargetState,\n MaterializedDocumentLinkSetMutationPlan,\n} from \"../../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport type { PrincipalPolicyCache } from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n assertSubtreePurgePath,\n type SubtreePurgeRoot,\n} from \"../purge/subtreePurgeScope\";\nimport {\n assertDocumentLinkAuthorAccess,\n verifyDocumentLinkSetCurrentPolicies,\n} from \"./linkSetAuthority\";\n\nfunction deriveDocumentLinkSetTargetState(input: {\n operation: DocumentLinkSetMutationOperation;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}): DocumentLinkSetTargetState {\n const currentTargets = currentDocumentTargets(input.writerProjection);\n const currentLinkedContainerIds = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n const target = deriveDocumentTargetFromProjection(\n input.targetContainerProjection,\n );\n const currentTarget = currentTargets.find(\n (candidate) => candidate.containerId === target.containerId,\n );\n\n if (input.operation === \"link\") {\n if (currentTarget) {\n throw new Error(\"Document link target is already linked\");\n }\n assertDocumentLinkTargetCapacity(currentTargets.length);\n assertDocumentLinkAuthorizationPathCapacity(\n input.writerProjection.authorizingContainerPaths.map(\n (projection) => projection.path.length,\n ),\n input.targetContainerProjection.path.length,\n );\n\n return {\n currentTargets,\n linkedContainerIds: uniqueSortedStrings([\n ...currentLinkedContainerIds,\n target.containerId,\n ]),\n target,\n targets: sortDocumentTargets([...currentTargets, target]),\n };\n }\n\n if (!currentTarget) {\n throw new Error(\"Document unlink target is not linked\");\n }\n if (targetKey(currentTarget) !== targetKey(target)) {\n throw new Error(\"Document unlink target projection is stale\");\n }\n\n const linkedContainerIds = currentLinkedContainerIds.filter(\n (containerId) => containerId !== target.containerId,\n );\n if (linkedContainerIds.length === 0) {\n throw new Error(\"Document unlink must leave a linked container\");\n }\n\n return {\n currentTargets,\n linkedContainerIds,\n target,\n targets: currentTargets.filter(\n (candidate) => candidate.containerId !== target.containerId,\n ),\n };\n}\n\nexport function assertDocumentLinkTargetCapacity(\n currentTargetCount: number,\n): void {\n if (currentTargetCount >= MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS) {\n throw new RangeError(\n `A document cannot be linked to more than ${MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS} containers`,\n );\n }\n}\n\nexport function assertDocumentLinkAuthorizationPathCapacity(\n currentPathLengths: readonly number[],\n targetPathLength: number,\n): void {\n const totalReferences = currentPathLengths.reduce(\n (total, length) => total + length,\n targetPathLength,\n );\n if (totalReferences > MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS) {\n throw new RangeError(\n `Document links cannot require more than ${MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS} authorization references`,\n );\n }\n}\n\nasync function wrapDocumentContentKeyForTargets(input: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n keksByEpochId: ReadonlyMap<string, Uint8Array>;\n targets: readonly DocumentContentKeyTarget[];\n}): Promise<DocumentContentKeyTargetEnvelope[]> {\n return Promise.all(\n sortDocumentTargets(input.targets).map(async (target) => {\n const targetKek = input.keksByEpochId.get(target.containerKeyEpochId);\n if (!targetKek) {\n throw new Error(\n `Document target KEK could not be unwrapped for ${describeDocumentTargetKek(target)}`,\n );\n }\n\n const wrapped = await wrapContentKey(input.contentKey, targetKek, {\n kind: \"Document\",\n objectId: input.documentId,\n contentKeyEpoch: input.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: DOCUMENT_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n }),\n );\n}\n\n// Resolve the organization a link/unlink mutation belongs to: the document's\n// own org (from its manifest), which must equal the target container's org —\n// both are owned by the same organization. The acting member's personal org is\n// intentionally not part of this check; a member may link documents within any\n// org they belong to. Returns the document org so the plan stamps it onto the\n// signed event and manifest rather than the author's org.\nasync function resolveDocumentLinkSetMutationOrganization(input: {\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<string> {\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document link-set manifest\",\n });\n if (\n manifestIdentity.organizationId !==\n input.targetContainerProjection.organizationId\n ) {\n throw new Error(\"Document target container organization mismatch\");\n }\n\n return manifestIdentity.organizationId;\n}\n\nfunction readDocumentLinkSetPreviousEpoch(\n writerProjection: DocumentWriterProjectionResponse,\n): number {\n const previousState = writerProjection.documentManifest.state;\n const previousEpoch = isPlainRecord(previousState)\n ? Reflect.get(previousState, \"epoch\")\n : undefined;\n if (\n typeof previousEpoch !== \"number\" ||\n !Number.isInteger(previousEpoch) ||\n previousEpoch <= 0\n ) {\n throw new Error(\"Document link-set previous epoch is invalid\");\n }\n\n return previousEpoch;\n}\n\nasync function buildDocumentLinkSetMutationPlan({\n author,\n blobRewraps,\n contentKeyEpoch,\n eventId = crypto.randomUUID(),\n operation,\n signedAt = new Date().toISOString(),\n targetContainerProjection,\n targetEnvelopes,\n writerProjection,\n}: BuildDocumentLinkSetMutationPlanInput): Promise<DocumentLinkSetMutationPlan> {\n const organizationId = await resolveDocumentLinkSetMutationOrganization({\n targetContainerProjection,\n writerProjection,\n });\n const targetState = deriveDocumentLinkSetTargetState({\n operation,\n targetContainerProjection,\n writerProjection,\n });\n const targetEnvelopesForRequest = mergeTargetEnvelopes(\n targetState.targets,\n targetEnvelopes,\n );\n const targetContainerPathRefs = containerPathRefs(\n targetContainerProjection.path,\n );\n const eventPlan = await buildDocumentLinkSetEventPlan({\n author,\n blobRewraps,\n eventId,\n operation,\n organizationId,\n signedAt,\n targetContainerPathRefs,\n targetState,\n writerProjection,\n });\n const previousEpoch = readDocumentLinkSetPreviousEpoch(writerProjection);\n\n const state: DocumentLinkSetManifestState = {\n version: 1,\n documentId: writerProjection.documentId,\n organizationId,\n epoch: previousEpoch + 1,\n previousManifestHash: writerProjection.documentManifest.manifestHash,\n eventHash: eventPlan.eventHash,\n linkedContainerIds: [...targetState.linkedContainerIds],\n };\n const manifest = await deriveDocumentLinkSetManifest(state);\n const manifestHash = await computeAccessManifestHash(manifest);\n const targetHash = await computeDocumentContentKeyTargetHash(\n targetState.targets,\n );\n\n return {\n body: eventPlan.body,\n contentKeyEpoch,\n documentId: writerProjection.documentId,\n event: eventPlan.event,\n eventHash: eventPlan.eventHash,\n manifest,\n manifestHash,\n operation,\n request: {\n event: readCanonicalRecord(eventPlan.event, \"Document link-set event\"),\n body: readCanonicalRecord(eventPlan.body, \"Document link-set body\"),\n expectedManifestHash: manifestHash,\n manifest: readCanonicalRecord(manifest, \"Document link-set manifest\"),\n targetContainerPathRefs,\n authorizingContainerPathRefs: eventPlan.authorizingContainerPathRefs,\n contentKeyBundle: {\n contentKeyEpoch,\n linkSetManifestHash: manifestHash,\n targetHash,\n targets: targetEnvelopesForRequest,\n },\n },\n state,\n targetHash,\n targets: sortDocumentTargets(targetState.targets),\n };\n}\n\nexport async function buildMaterializedDocumentLinkSetMutationPlan(\n input: {\n author: DocumentCreateAuthor;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n prepareBlobRewraps: (\n targets: readonly DocumentContentKeyTarget[],\n ) => Promise<BuildDocumentLinkSetMutationPlanInput[\"blobRewraps\"]>;\n contentKey?: Uint8Array | undefined;\n eventId?: string | undefined;\n execSql?: ExecSql | undefined;\n operation: DocumentLinkSetMutationOperation;\n signedAt?: string | undefined;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<MaterializedDocumentLinkSetMutationPlan> {\n const verificationOptions = projectionVerificationOptions(input);\n const principalPolicyCache: PrincipalPolicyCache = new Map();\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n execSql: input.execSql,\n principalPolicyCache,\n ...verificationOptions,\n });\n await verifyDocumentLinkSetCurrentPolicies({\n execSql: input.execSql,\n principalPolicyCache,\n targetContainerProjection: input.targetContainerProjection,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n });\n assertSubtreePurgePath(\n input.targetContainerProjection.path,\n input.expectedSubtreeRoot,\n );\n if (input.resolveProjectionUserKey)\n assertDocumentLinkAuthorAccess({\n ...input,\n principalPolicies: [...principalPolicyCache.values()],\n });\n const targetState = deriveDocumentLinkSetTargetState({\n operation: input.operation,\n targetContainerProjection: input.targetContainerProjection,\n writerProjection: input.writerProjection,\n });\n assertLinkSetWriteKeksCurrent(input, targetState.linkedContainerIds);\n const currentContentKey = await unwrapDocumentContentKeyFromWriterProjection({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n });\n const contentKeyRotated = input.operation === \"unlink\";\n const contentKey = contentKeyRotated\n ? (input.contentKey ?? crypto.getRandomValues(new Uint8Array(32)))\n : currentContentKey;\n if (contentKey.byteLength !== 32) {\n throw new Error(\"Document content key must be 32 bytes\");\n }\n // A link carries the existing envelopes forward at the same epoch; an\n // unlink rotates to a fresh key at the next one.\n const contentKeyEpoch =\n input.writerProjection.contentKeyBundle.contentKeyEpoch +\n (contentKeyRotated ? 1 : 0);\n const targetEnvelopes = await buildLinkSetTargetEnvelopes(input, {\n contentKey,\n contentKeyEpoch,\n targetState,\n });\n\n const plan = await buildDocumentLinkSetMutationPlan({\n author: input.author,\n blobRewraps: await input.prepareBlobRewraps(targetState.targets),\n contentKeyEpoch,\n eventId: input.eventId,\n operation: input.operation,\n signedAt: input.signedAt,\n targetContainerProjection: input.targetContainerProjection,\n targetEnvelopes,\n writerProjection: input.writerProjection,\n });\n\n return {\n contentKey,\n contentKeyRotated,\n plan,\n };\n}\n\nasync function buildLinkSetTargetEnvelopes(\n input: Parameters<typeof buildMaterializedDocumentLinkSetMutationPlan>[0],\n wrap: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n targetState: ReturnType<typeof deriveDocumentLinkSetTargetState>;\n },\n): Promise<DocumentContentKeyTargetEnvelope[]> {\n const verificationOptions = projectionVerificationOptions(input);\n const sealing = {\n contentKey: wrap.contentKey,\n contentKeyEpoch: wrap.contentKeyEpoch,\n documentId: input.writerProjection.documentId,\n };\n if (input.operation === \"link\") {\n return [\n ...input.writerProjection.contentKeyBundle.targets,\n ...(await wrapDocumentContentKeyForTargets({\n ...sealing,\n keksByEpochId: await unwrapContainerKekPath({\n execSql: input.execSql,\n projection: input.targetContainerProjection,\n secretKey: input.targetSecretKey,\n ...verificationOptions,\n }),\n targets: [wrap.targetState.target],\n })),\n ];\n }\n return wrapDocumentContentKeyForTargets({\n ...sealing,\n keksByEpochId: (\n await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n })\n ).keksByEpochId,\n // The rotated key is wrapped only to verified current heads of the\n // remaining linked containers, never to a server-listed epoch.\n targets: verifiedDocumentWrapTargets({\n linkedContainerIds: wrap.targetState.linkedContainerIds,\n serverTargets: wrap.targetState.targets,\n writerProjection: input.writerProjection,\n }),\n });\n}\n\nfunction assertLinkSetWriteKeksCurrent(\n input: Pick<\n Parameters<typeof buildMaterializedDocumentLinkSetMutationPlan>[0],\n \"writerProjection\" | \"targetContainerProjection\" | \"operation\"\n >,\n linkedContainerIds: readonly string[],\n): void {\n // Unlink can escape a stale branch; only recipients of the successor key must be current.\n assertDocumentKekPathsCurrent(\n input.writerProjection,\n new Set(linkedContainerIds),\n );\n if (input.operation === \"link\") {\n assertContainerKekPathCurrent(\n input.targetContainerProjection.containerKeks,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,mCAAmC,EACnC,+BAA+B,EAG/B,6BAA6B,EAC7B,cAAc,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAMrF,OAAO,EACL,yCAAyC,EACzC,qCAAqC,GACtC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,uCAAuC,CAAC;AACtF,OAAO,EACL,wCAAwC,EACxC,mCAAmC,EACnC,iBAAiB,EACjB,sBAAsB,EACtB,kCAAkC,EAClC,oBAAoB,EACpB,0CAA0C,EAC1C,sBAAsB,EACtB,4CAA4C,EAC5C,2BAA2B,GAC5B,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAEL,6BAA6B,GAC9B,MAAM,yEAAyE,CAAC;AACjF,OAAO,EACL,sCAAsC,EACtC,yBAAyB,EACzB,mBAAmB,EACnB,SAAS,EACT,mBAAmB,GACpB,M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AAC,SAAS,KAAK,MAAM,EAAE,CAAC;QAC/B,6BAA6B,CAC3B,KAAK,CAAC,yBAAyB,CAAC,aAAa,CAC9C,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n computeAccessManifestHash,\n computeDocumentContentKeyTargetHash,\n DOCUMENT_CONTENT_KEY_WRAP_SUITE,\n type DocumentContentKeyTarget,\n type DocumentLinkSetManifestState,\n deriveDocumentLinkSetManifest,\n wrapContentKey,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type { DocumentContentKeyTargetEnvelope } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS,\n MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS,\n} from \"@tearleads/validators/util\";\nimport {\n assertContainerKekPathCurrent,\n assertDocumentKekPathsCurrent,\n} from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { buildDocumentLinkSetEventPlan } from \"../../../data/documents/shared/events\";\nimport {\n assertDocumentWriterProjectionConsistent,\n collectContainerKeksForDocumentSync,\n containerPathRefs,\n currentDocumentTargets,\n deriveDocumentTargetFromProjection,\n mergeTargetEnvelopes,\n readLinkedContainerIdsFromDocumentManifest,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyFromWriterProjection,\n verifiedDocumentWrapTargets,\n} from \"../../../data/documents/shared/projection\";\nimport {\n type ProjectionVerificationOptions,\n projectionVerificationOptions,\n} from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n assertDocumentManifestBundleConsistent,\n describeDocumentTargetKek,\n sortDocumentTargets,\n targetKey,\n uniqueSortedStrings,\n} from \"../../../data/documents/shared/readers\";\nimport type {\n BuildDocumentLinkSetMutationPlanInput,\n DocumentCreateAuthor,\n DocumentLinkSetMutationOperation,\n DocumentLinkSetMutationPlan,\n DocumentLinkSetTargetState,\n MaterializedDocumentLinkSetMutationPlan,\n} from \"../../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport type { PrincipalPolicyCache } from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n assertSubtreePurgePath,\n type SubtreePurgeRoot,\n} from \"../purge/subtreePurgeScope\";\nimport {\n assertDocumentLinkAuthorAccess,\n verifyDocumentLinkSetCurrentPolicies,\n} from \"./linkSetAuthority\";\n\nfunction deriveDocumentLinkSetTargetState(input: {\n operation: DocumentLinkSetMutationOperation;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}): DocumentLinkSetTargetState {\n const currentTargets = currentDocumentTargets(input.writerProjection);\n const currentLinkedContainerIds = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n const target = deriveDocumentTargetFromProjection(\n input.targetContainerProjection,\n );\n const currentTarget = currentTargets.find(\n (candidate) => candidate.containerId === target.containerId,\n );\n\n if (input.operation === \"link\") {\n if (currentTarget) {\n throw new Error(\"Document link target is already linked\");\n }\n assertDocumentLinkTargetCapacity(currentTargets.length);\n assertDocumentLinkAuthorizationPathCapacity(\n input.writerProjection.authorizingContainerPaths.map(\n (projection) => projection.path.length,\n ),\n input.targetContainerProjection.path.length,\n );\n\n return {\n currentTargets,\n linkedContainerIds: uniqueSortedStrings([\n ...currentLinkedContainerIds,\n target.containerId,\n ]),\n target,\n targets: sortDocumentTargets([...currentTargets, target]),\n };\n }\n\n if (!currentTarget) {\n throw new Error(\"Document unlink target is not linked\");\n }\n if (targetKey(currentTarget) !== targetKey(target)) {\n throw new Error(\"Document unlink target projection is stale\");\n }\n\n const linkedContainerIds = currentLinkedContainerIds.filter(\n (containerId) => containerId !== target.containerId,\n );\n if (linkedContainerIds.length === 0) {\n throw new Error(\"Document unlink must leave a linked container\");\n }\n\n return {\n currentTargets,\n linkedContainerIds,\n target,\n targets: currentTargets.filter(\n (candidate) => candidate.containerId !== target.containerId,\n ),\n };\n}\n\nexport function assertDocumentLinkTargetCapacity(\n currentTargetCount: number,\n): void {\n if (currentTargetCount >= MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS) {\n throw new RangeError(\n `A document cannot be linked to more than ${MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS} containers`,\n );\n }\n}\n\nexport function assertDocumentLinkAuthorizationPathCapacity(\n currentPathLengths: readonly number[],\n targetPathLength: number,\n): void {\n const totalReferences = currentPathLengths.reduce(\n (total, length) => total + length,\n targetPathLength,\n );\n if (totalReferences > MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS) {\n throw new RangeError(\n `Document links cannot require more than ${MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS} authorization references`,\n );\n }\n}\n\nasync function wrapDocumentContentKeyForTargets(input: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n keksByEpochId: ReadonlyMap<string, Uint8Array>;\n targets: readonly DocumentContentKeyTarget[];\n}): Promise<DocumentContentKeyTargetEnvelope[]> {\n return Promise.all(\n sortDocumentTargets(input.targets).map(async (target) => {\n const targetKek = input.keksByEpochId.get(target.containerKeyEpochId);\n if (!targetKek) {\n throw new Error(\n `Document target KEK could not be unwrapped for ${describeDocumentTargetKek(target)}`,\n );\n }\n\n const wrapped = await wrapContentKey(input.contentKey, targetKek, {\n kind: \"Document\",\n objectId: input.documentId,\n contentKeyEpoch: input.contentKeyEpoch,\n containerId: target.containerId,\n containerKeyEpochId: target.containerKeyEpochId,\n });\n return {\n ...target,\n wrappedKey: bytesToBase64(wrapped.ciphertext),\n wrappingMetadata: {\n suite: DOCUMENT_CONTENT_KEY_WRAP_SUITE,\n iv: bytesToBase64(wrapped.iv),\n },\n };\n }),\n );\n}\n\n// Resolve the organization a link/unlink mutation belongs to: the document's\n// own org (from its manifest), which must equal the target container's org —\n// both are owned by the same organization. The acting member's personal org is\n// intentionally not part of this check; a member may link documents within any\n// org they belong to. Returns the document org so the plan stamps it onto the\n// signed event and manifest rather than the author's org.\nasync function resolveDocumentLinkSetMutationOrganization(input: {\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}): Promise<string> {\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document link-set manifest\",\n });\n if (\n manifestIdentity.organizationId !==\n input.targetContainerProjection.organizationId\n ) {\n throw new Error(\"Document target container organization mismatch\");\n }\n\n return manifestIdentity.organizationId;\n}\n\nfunction readDocumentLinkSetPreviousEpoch(\n writerProjection: DocumentWriterProjectionResponse,\n): number {\n const previousState = writerProjection.documentManifest.state;\n const previousEpoch = isPlainRecord(previousState)\n ? Reflect.get(previousState, \"epoch\")\n : undefined;\n if (\n typeof previousEpoch !== \"number\" ||\n !Number.isInteger(previousEpoch) ||\n previousEpoch <= 0\n ) {\n throw new Error(\"Document link-set previous epoch is invalid\");\n }\n\n return previousEpoch;\n}\n\nasync function buildDocumentLinkSetMutationPlan({\n author,\n blobRewraps,\n contentKeyEpoch,\n eventId = crypto.randomUUID(),\n operation,\n signedAt = new Date().toISOString(),\n targetContainerProjection,\n targetEnvelopes,\n writerProjection,\n}: BuildDocumentLinkSetMutationPlanInput): Promise<DocumentLinkSetMutationPlan> {\n const organizationId = await resolveDocumentLinkSetMutationOrganization({\n targetContainerProjection,\n writerProjection,\n });\n const targetState = deriveDocumentLinkSetTargetState({\n operation,\n targetContainerProjection,\n writerProjection,\n });\n const targetEnvelopesForRequest = mergeTargetEnvelopes(\n targetState.targets,\n targetEnvelopes,\n );\n const targetContainerPathRefs = containerPathRefs(\n targetContainerProjection.path,\n );\n const eventPlan = await buildDocumentLinkSetEventPlan({\n author,\n blobRewraps,\n eventId,\n operation,\n organizationId,\n signedAt,\n targetContainerPathRefs,\n targetState,\n writerProjection,\n });\n const previousEpoch = readDocumentLinkSetPreviousEpoch(writerProjection);\n\n const state: DocumentLinkSetManifestState = {\n version: 1,\n documentId: writerProjection.documentId,\n organizationId,\n epoch: previousEpoch + 1,\n previousManifestHash: writerProjection.documentManifest.manifestHash,\n eventHash: eventPlan.eventHash,\n linkedContainerIds: [...targetState.linkedContainerIds],\n };\n const manifest = await deriveDocumentLinkSetManifest(state);\n const manifestHash = await computeAccessManifestHash(manifest);\n const targetHash = await computeDocumentContentKeyTargetHash(\n targetState.targets,\n );\n\n return {\n body: eventPlan.body,\n contentKeyEpoch,\n documentId: writerProjection.documentId,\n event: eventPlan.event,\n eventHash: eventPlan.eventHash,\n manifest,\n manifestHash,\n operation,\n request: {\n event: readCanonicalRecord(eventPlan.event, \"Document link-set event\"),\n body: readCanonicalRecord(eventPlan.body, \"Document link-set body\"),\n expectedManifestHash: manifestHash,\n targetContainerPathRefs,\n authorizingContainerPathRefs: eventPlan.authorizingContainerPathRefs,\n contentKeyBundle: {\n contentKeyEpoch,\n linkSetManifestHash: manifestHash,\n targetHash,\n targets: targetEnvelopesForRequest,\n },\n },\n state,\n targetHash,\n targets: sortDocumentTargets(targetState.targets),\n };\n}\n\nexport async function buildMaterializedDocumentLinkSetMutationPlan(\n input: {\n author: DocumentCreateAuthor;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n prepareBlobRewraps: (\n targets: readonly DocumentContentKeyTarget[],\n ) => Promise<BuildDocumentLinkSetMutationPlanInput[\"blobRewraps\"]>;\n contentKey?: Uint8Array | undefined;\n eventId?: string | undefined;\n execSql?: ExecSql | undefined;\n operation: DocumentLinkSetMutationOperation;\n signedAt?: string | undefined;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<MaterializedDocumentLinkSetMutationPlan> {\n const verificationOptions = projectionVerificationOptions(input);\n const principalPolicyCache: PrincipalPolicyCache = new Map();\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n execSql: input.execSql,\n principalPolicyCache,\n ...verificationOptions,\n });\n await verifyDocumentLinkSetCurrentPolicies({\n execSql: input.execSql,\n principalPolicyCache,\n targetContainerProjection: input.targetContainerProjection,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n });\n assertSubtreePurgePath(\n input.targetContainerProjection.path,\n input.expectedSubtreeRoot,\n );\n if (input.resolveProjectionUserKey)\n assertDocumentLinkAuthorAccess({\n ...input,\n principalPolicies: [...principalPolicyCache.values()],\n });\n const targetState = deriveDocumentLinkSetTargetState({\n operation: input.operation,\n targetContainerProjection: input.targetContainerProjection,\n writerProjection: input.writerProjection,\n });\n assertLinkSetWriteKeksCurrent(input, targetState.linkedContainerIds);\n const currentContentKey = await unwrapDocumentContentKeyFromWriterProjection({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n });\n const contentKeyRotated = input.operation === \"unlink\";\n const contentKey = contentKeyRotated\n ? (input.contentKey ?? crypto.getRandomValues(new Uint8Array(32)))\n : currentContentKey;\n if (contentKey.byteLength !== 32) {\n throw new Error(\"Document content key must be 32 bytes\");\n }\n // A link carries the existing envelopes forward at the same epoch; an\n // unlink rotates to a fresh key at the next one.\n const contentKeyEpoch =\n input.writerProjection.contentKeyBundle.contentKeyEpoch +\n (contentKeyRotated ? 1 : 0);\n const targetEnvelopes = await buildLinkSetTargetEnvelopes(input, {\n contentKey,\n contentKeyEpoch,\n targetState,\n });\n\n const plan = await buildDocumentLinkSetMutationPlan({\n author: input.author,\n blobRewraps: await input.prepareBlobRewraps(targetState.targets),\n contentKeyEpoch,\n eventId: input.eventId,\n operation: input.operation,\n signedAt: input.signedAt,\n targetContainerProjection: input.targetContainerProjection,\n targetEnvelopes,\n writerProjection: input.writerProjection,\n });\n\n return {\n contentKey,\n contentKeyRotated,\n plan,\n };\n}\n\nasync function buildLinkSetTargetEnvelopes(\n input: Parameters<typeof buildMaterializedDocumentLinkSetMutationPlan>[0],\n wrap: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n targetState: ReturnType<typeof deriveDocumentLinkSetTargetState>;\n },\n): Promise<DocumentContentKeyTargetEnvelope[]> {\n const verificationOptions = projectionVerificationOptions(input);\n const sealing = {\n contentKey: wrap.contentKey,\n contentKeyEpoch: wrap.contentKeyEpoch,\n documentId: input.writerProjection.documentId,\n };\n if (input.operation === \"link\") {\n return [\n ...input.writerProjection.contentKeyBundle.targets,\n ...(await wrapDocumentContentKeyForTargets({\n ...sealing,\n keksByEpochId: await unwrapContainerKekPath({\n execSql: input.execSql,\n projection: input.targetContainerProjection,\n secretKey: input.targetSecretKey,\n ...verificationOptions,\n }),\n targets: [wrap.targetState.target],\n })),\n ];\n }\n return wrapDocumentContentKeyForTargets({\n ...sealing,\n keksByEpochId: (\n await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...verificationOptions,\n })\n ).keksByEpochId,\n // The rotated key is wrapped only to verified current heads of the\n // remaining linked containers, never to a server-listed epoch.\n targets: verifiedDocumentWrapTargets({\n linkedContainerIds: wrap.targetState.linkedContainerIds,\n serverTargets: wrap.targetState.targets,\n writerProjection: input.writerProjection,\n }),\n });\n}\n\nfunction assertLinkSetWriteKeksCurrent(\n input: Pick<\n Parameters<typeof buildMaterializedDocumentLinkSetMutationPlan>[0],\n \"writerProjection\" | \"targetContainerProjection\" | \"operation\"\n >,\n linkedContainerIds: readonly string[],\n): void {\n // Unlink can escape a stale branch; only recipients of the successor key must be current.\n assertDocumentKekPathsCurrent(\n input.writerProjection,\n new Set(linkedContainerIds),\n );\n if (input.operation === \"link\") {\n assertContainerKekPathCurrent(\n input.targetContainerProjection.containerKeks,\n );\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { compareCanonicalStrings, computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, computePrincipalStateHash, } from "../../../internal/crypto/index.js";
|
|
1
|
+
import { compareCanonicalStrings, computeAccessEventHash, computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, computePrincipalStateHash, } from "../../../internal/crypto/index.js";
|
|
2
2
|
import { canonicalKeyingJsonString } from "../../../data/keying/canonicalJson.js";
|
|
3
|
-
import { readContainerKeyEpoch, readContainerKeyWrap, } from "../../../data/keyingProjectionVerification/readers.js";
|
|
3
|
+
import { readAccessEvent, readContainerKeyEpoch, readContainerKeyWrap, } from "../../../data/keyingProjectionVerification/readers.js";
|
|
4
4
|
import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
|
|
5
5
|
function sortedCanonicalValues(values, label) {
|
|
6
6
|
return [...values].sort((left, right) => compareCanonicalStrings(canonicalKeyingJsonString(left, label), canonicalKeyingJsonString(right, label)));
|
|
@@ -39,16 +39,23 @@ async function assertContainerMutationAcknowledgements(input) {
|
|
|
39
39
|
recipientKind: wrap.recipientKind,
|
|
40
40
|
};
|
|
41
41
|
}), "authored recipient target");
|
|
42
|
-
// The request carries this client's own hash of the manifest it signed
|
|
43
|
-
// and
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
//
|
|
42
|
+
// The request carries this client's own hash of the manifest it signed
|
|
43
|
+
// and the signed event, whose hashes the acknowledgement must name. The
|
|
44
|
+
// manifest hash commits the epoch, but the request no longer names it,
|
|
45
|
+
// so the receipt's epoch label is not compared here: journal recovery
|
|
46
|
+
// discards the receipt after this check, and the in-process path stores
|
|
47
|
+
// a head only through the plan-based container acknowledgement, which
|
|
48
|
+
// requires the plan's epoch. Every field compared here is one the
|
|
49
|
+
// server received in the request, so this binds the receipt to the
|
|
50
|
+
// request; it never proved a commit, with or without the epoch. A
|
|
51
|
+
// rotation's signed body commits its keyring hash, so a substituted
|
|
52
|
+
// keyring must refuse here, before journal recovery clears the saved
|
|
53
|
+
// request. A grant that keeps its epoch commits none; the container
|
|
54
|
+
// acknowledgement checks the retained keyring against the epoch's own.
|
|
48
55
|
const committedKeyringHash = Reflect.get(Object(request.body), "keyringHash");
|
|
49
56
|
if (response.manifestHead.manifestHash !== request.expectedManifestHash ||
|
|
50
|
-
response.
|
|
51
|
-
|
|
57
|
+
response.eventHash !==
|
|
58
|
+
(await computeAccessEventHash(readAccessEvent(request.event, label))) ||
|
|
52
59
|
response.containerKek.containerKeyEpochId !== keyEpoch.id ||
|
|
53
60
|
response.containerKek.containerKeyEpoch !== keyEpoch.keyEpoch ||
|
|
54
61
|
response.containerKek.keyEpochHash !==
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyReceiptArtifacts.js","sourceRoot":"","sources":["principalPolicyReceiptArtifacts.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,sCAAsC,EACtC,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EACL,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAEjH,SAAS,qBAAqB,CAAI,MAAoB,EAAE,KAAa;IACnE,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACtC,uBAAuB,CACrB,yBAAyB,CAAC,IAAI,EAAE,KAAK,CAAC,EACtC,yBAAyB,CAAC,KAAK,EAAE,KAAK,CAAC,CACxC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8CAA8C,CAC5D,QAAiD,EACjD,QAAiD;IAEjD,MAAM,UAAU,GAAG,CAAC,KAA8C,EAAE,EAAE,CAAC,CAAC;QACtE,GAAG,KAAK;QACR,SAAS,EAAE,qBAAqB,CAC9B,KAAK,CAAC,SAAS,EACf,2BAA2B,CAC5B;KACF,CAAC,CAAC;IACH,IACE,y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6B,CAAC,QAAQ,CAAC,IAAI,EAAE;QAC5C,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,SAAS;QACT,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC;QAEF,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,MAAM,uCAAuC,CAAC;QAC5C,QAAQ,EAAE,OAAO,CAAC,kBAAkB,IAAI,EAAE;QAC1C,SAAS,EAAE,QAAQ,CAAC,kBAAkB;KACvC,CAAC,CAAC;IACH,MAAM,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC;IAC7C,MAAM,EAAE,SAAS,EAAE,GAAG,QAAQ,CAAC;IAC/B,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QAChD,cAAc,EAAE;YACd,aAAa;YACb,WAAW;YACX,SAAS;YACT,GAAG,OAAO,CAAC,gBAAgB;YAC3B,SAAS;SACV;QACD,iBAAiB,EAAE,OAAO,CAAC,UAAU;QACrC,aAAa,EAAE,OAAO,CAAC,MAAM;QAC7B,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,KAAK,CAAC,QAAQ;YACrB,SAAS,EAAE,OAAO,CAAC,eAAe;SACnC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n compareCanonicalStrings,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n computePrincipalStateHash,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport {\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../../../data/keyingProjectionVerification/readers\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\n\nfunction sortedCanonicalValues<T>(values: readonly T[], label: string): T[] {\n return [...values].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, label),\n canonicalKeyingJsonString(right, label),\n ),\n );\n}\n\nexport function assertGroupPolicyEnvelopesMatchAcknowledgement(\n expected: CurrentPrincipalMemberEnvelopesResponse,\n observed: CurrentPrincipalMemberEnvelopesResponse,\n): void {\n const normalized = (value: CurrentPrincipalMemberEnvelopesResponse) => ({\n ...value,\n envelopes: sortedCanonicalValues(\n value.envelopes,\n \"principal member envelope\",\n ),\n });\n if (\n canonicalKeyingJsonString(\n normalized(expected),\n \"acknowledged group member envelopes\",\n ) !==\n canonicalKeyingJsonString(\n normalized(observed),\n \"observed group member envelopes\",\n )\n ) {\n throw new Error(\"Group member envelopes changed after acknowledgement\");\n }\n}\n\n/**\n * Each rematerialized container's acknowledgement names its commit by hash;\n * match every hash against the request this client authored.\n */\nasync function assertContainerMutationAcknowledgements(input: {\n readonly requests: readonly NonNullable<\n PutPrincipalPolicyRequest[\"containerMutations\"]\n >[number][];\n readonly responses: readonly ContainerMutationResponse[] | undefined;\n}): Promise<void> {\n if (!input.responses || input.responses.length !== input.requests.length) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n for (const [index, request] of input.requests.entries()) {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n const label = \"authored group policy container mutation\";\n const keyEpoch = readContainerKeyEpoch(request.keyEpoch, label);\n const recipientTargets = sortedCanonicalValues(\n request.wraps.map((value) => {\n const wrap = readContainerKeyWrap(value, label);\n return {\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n };\n }),\n \"authored recipient target\",\n );\n // The request carries this client's own hash of the manifest it signed,\n // and that manifest names its epoch and event by hash. A rotation's signed\n // body commits its keyring hash, so a substituted keyring must refuse\n // here, before journal recovery clears the saved request. A grant that\n // keeps its epoch commits none; the container acknowledgement checks the\n // retained keyring against the epoch's own.\n const committedKeyringHash = Reflect.get(\n Object(request.body),\n \"keyringHash\",\n );\n if (\n response.manifestHead.manifestHash !== request.expectedManifestHash ||\n response.manifestHead.epoch !== Reflect.get(request.manifest, \"epoch\") ||\n response.eventHash !== Reflect.get(request.manifest, \"eventHash\") ||\n response.containerKek.containerKeyEpochId !== keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== keyEpoch.keyEpoch ||\n response.containerKek.keyEpochHash !==\n (await computeContainerKeyEpochHash(keyEpoch)) ||\n (typeof committedKeyringHash === \"string\" &&\n response.containerKek.keyringHash !== committedKeyringHash) ||\n response.containerKek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(recipientTargets))\n ) {\n throw new Error(\"Group policy container acknowledgement mismatch\");\n }\n }\n}\n\n/**\n * The current an acknowledgement commits, rebuilt from this client's own\n * signed request: the server returns only the head it stored, the insertion\n * time it assigned to the state and payload, and hash-form container\n * acknowledgements. A head other than the one the request commits to refuses.\n * Nothing here manufactures predecessor history or pins.\n */\nexport async function acknowledgedPrincipalPolicyCurrent(input: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): Promise<PrincipalPolicyPageCurrent> {\n const { request, response } = input;\n const { state } = request;\n const stateHash = await computePrincipalStateHash(state);\n if (\n !principalHeadMatchesReference(response.head, {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash,\n keyFingerprint: state.keyFingerprint,\n })\n )\n throw new Error(\"Principal policy acknowledgement names another head\");\n await assertContainerMutationAcknowledgements({\n requests: request.containerMutations ?? [],\n responses: response.containerMutations,\n });\n const { principalType, principalId } = state;\n const { createdAt } = response;\n return {\n currentState: { ...state, stateHash, createdAt },\n currentPayload: {\n principalType,\n principalId,\n stateHash,\n ...request.encryptedPayload,\n createdAt,\n },\n currentProjection: request.projection,\n currentGrants: request.grants,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: state.keyEpoch,\n envelopes: request.memberEnvelopes,\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalPolicyReceiptArtifacts.js","sourceRoot":"","sources":["principalPolicyReceiptArtifacts.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,sCAAsC,EACtC,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EACL,eAAe,EACf,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAEjH,SAAS,qBAAqB,CAAI,MAAoB,EAAE,KAAa;IACnE,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACtC,uBAAuB,CACrB,yBAAyB,CAAC,IAAI,EAAE,KAAK,CAAC,EACtC,yBAAyB,CAAC,KAAK,EAAE,KAAK,CAAC,CACxC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8CAA8C,CAC5D,QAAiD,EACjD,QAAiD;IAEjD,MAAM,UAAU,GAAG,CAAC,KAA8C,EAAE,EAAE,CAAC,CAAC;QACtE,GAAG,KAAK;QACR,SAAS,EAAE,qBAAqB,CAC9B,KAAK,CAAC,SAAS,EACf,2BAA2B,CAC5B;KACF,CAAC,CAAC;IACH,IACE,yBAAyB,CACvB,UAAU,CAAC,QAAQ,CAAC,EACp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,IAAI,EAAE;QAC5C,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,SAAS;QACT,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC;QAEF,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,MAAM,uCAAuC,CAAC;QAC5C,QAAQ,EAAE,OAAO,CAAC,kBAAkB,IAAI,EAAE;QAC1C,SAAS,EAAE,QAAQ,CAAC,kBAAkB;KACvC,CAAC,CAAC;IACH,MAAM,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC;IAC7C,MAAM,EAAE,SAAS,EAAE,GAAG,QAAQ,CAAC;IAC/B,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QAChD,cAAc,EAAE;YACd,aAAa;YACb,WAAW;YACX,SAAS;YACT,GAAG,OAAO,CAAC,gBAAgB;YAC3B,SAAS;SACV;QACD,iBAAiB,EAAE,OAAO,CAAC,UAAU;QACrC,aAAa,EAAE,OAAO,CAAC,MAAM;QAC7B,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,KAAK,CAAC,QAAQ;YACrB,SAAS,EAAE,OAAO,CAAC,eAAe;SACnC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n compareCanonicalStrings,\n computeAccessEventHash,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n computePrincipalStateHash,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport {\n readAccessEvent,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../../../data/keyingProjectionVerification/readers\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\n\nfunction sortedCanonicalValues<T>(values: readonly T[], label: string): T[] {\n return [...values].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, label),\n canonicalKeyingJsonString(right, label),\n ),\n );\n}\n\nexport function assertGroupPolicyEnvelopesMatchAcknowledgement(\n expected: CurrentPrincipalMemberEnvelopesResponse,\n observed: CurrentPrincipalMemberEnvelopesResponse,\n): void {\n const normalized = (value: CurrentPrincipalMemberEnvelopesResponse) => ({\n ...value,\n envelopes: sortedCanonicalValues(\n value.envelopes,\n \"principal member envelope\",\n ),\n });\n if (\n canonicalKeyingJsonString(\n normalized(expected),\n \"acknowledged group member envelopes\",\n ) !==\n canonicalKeyingJsonString(\n normalized(observed),\n \"observed group member envelopes\",\n )\n ) {\n throw new Error(\"Group member envelopes changed after acknowledgement\");\n }\n}\n\n/**\n * Each rematerialized container's acknowledgement names its commit by hash;\n * match every hash against the request this client authored.\n */\nasync function assertContainerMutationAcknowledgements(input: {\n readonly requests: readonly NonNullable<\n PutPrincipalPolicyRequest[\"containerMutations\"]\n >[number][];\n readonly responses: readonly ContainerMutationResponse[] | undefined;\n}): Promise<void> {\n if (!input.responses || input.responses.length !== input.requests.length) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n for (const [index, request] of input.requests.entries()) {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n const label = \"authored group policy container mutation\";\n const keyEpoch = readContainerKeyEpoch(request.keyEpoch, label);\n const recipientTargets = sortedCanonicalValues(\n request.wraps.map((value) => {\n const wrap = readContainerKeyWrap(value, label);\n return {\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n };\n }),\n \"authored recipient target\",\n );\n // The request carries this client's own hash of the manifest it signed\n // and the signed event, whose hashes the acknowledgement must name. The\n // manifest hash commits the epoch, but the request no longer names it,\n // so the receipt's epoch label is not compared here: journal recovery\n // discards the receipt after this check, and the in-process path stores\n // a head only through the plan-based container acknowledgement, which\n // requires the plan's epoch. Every field compared here is one the\n // server received in the request, so this binds the receipt to the\n // request; it never proved a commit, with or without the epoch. A\n // rotation's signed body commits its keyring hash, so a substituted\n // keyring must refuse here, before journal recovery clears the saved\n // request. A grant that keeps its epoch commits none; the container\n // acknowledgement checks the retained keyring against the epoch's own.\n const committedKeyringHash = Reflect.get(\n Object(request.body),\n \"keyringHash\",\n );\n if (\n response.manifestHead.manifestHash !== request.expectedManifestHash ||\n response.eventHash !==\n (await computeAccessEventHash(readAccessEvent(request.event, label))) ||\n response.containerKek.containerKeyEpochId !== keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== keyEpoch.keyEpoch ||\n response.containerKek.keyEpochHash !==\n (await computeContainerKeyEpochHash(keyEpoch)) ||\n (typeof committedKeyringHash === \"string\" &&\n response.containerKek.keyringHash !== committedKeyringHash) ||\n response.containerKek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(recipientTargets))\n ) {\n throw new Error(\"Group policy container acknowledgement mismatch\");\n }\n }\n}\n\n/**\n * The current an acknowledgement commits, rebuilt from this client's own\n * signed request: the server returns only the head it stored, the insertion\n * time it assigned to the state and payload, and hash-form container\n * acknowledgements. A head other than the one the request commits to refuses.\n * Nothing here manufactures predecessor history or pins.\n */\nexport async function acknowledgedPrincipalPolicyCurrent(input: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): Promise<PrincipalPolicyPageCurrent> {\n const { request, response } = input;\n const { state } = request;\n const stateHash = await computePrincipalStateHash(state);\n if (\n !principalHeadMatchesReference(response.head, {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash,\n keyFingerprint: state.keyFingerprint,\n })\n )\n throw new Error(\"Principal policy acknowledgement names another head\");\n await assertContainerMutationAcknowledgements({\n requests: request.containerMutations ?? [],\n responses: response.containerMutations,\n });\n const { principalType, principalId } = state;\n const { createdAt } = response;\n return {\n currentState: { ...state, stateHash, createdAt },\n currentPayload: {\n principalType,\n principalId,\n stateHash,\n ...request.encryptedPayload,\n createdAt,\n },\n currentProjection: request.projection,\n currentGrants: request.grants,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: state.keyEpoch,\n envelopes: request.memberEnvelopes,\n },\n };\n}\n"]}
|
|
@@ -179,7 +179,6 @@ export declare function buildInitialRootProvisioning(input: {
|
|
|
179
179
|
expectedManifestHash: string;
|
|
180
180
|
keyEpoch: Record<string, unknown>;
|
|
181
181
|
keyring: Record<string, unknown> | null;
|
|
182
|
-
manifest: Record<string, unknown>;
|
|
183
182
|
predecessorBridge: Record<string, unknown> | null;
|
|
184
183
|
principalPolicyRefs: {
|
|
185
184
|
principalType: "group" | "organization";
|
|
@@ -260,7 +259,6 @@ export declare function buildInitialRootProvisioning(input: {
|
|
|
260
259
|
expectedManifestHash: string;
|
|
261
260
|
keyEpoch: Record<string, unknown>;
|
|
262
261
|
keyring: Record<string, unknown> | null;
|
|
263
|
-
manifest: Record<string, unknown>;
|
|
264
262
|
predecessorBridge: Record<string, unknown> | null;
|
|
265
263
|
principalPolicyRefs: {
|
|
266
264
|
principalType: "group" | "organization";
|