@tearleads/client-sdk 0.1.68 → 0.1.71

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.
Files changed (123) hide show
  1. package/data/containers/shared/principalPolicies.js +8 -12
  2. package/data/containers/shared/principalPolicies.js.map +1 -1
  3. package/internal/api-client/ApiClient.d.ts +73 -3
  4. package/internal/api-client/apiRequestMetrics.d.ts +18 -4
  5. package/internal/api-client/apiRequestMetrics.js +55 -5
  6. package/internal/api-client/apiRequestMetrics.js.map +1 -1
  7. package/internal/api-client/durationSampleWindow.d.ts +26 -0
  8. package/internal/api-client/durationSampleWindow.js +42 -0
  9. package/internal/api-client/durationSampleWindow.js.map +1 -0
  10. package/internal/api-client/measureApiRequest.js +9 -4
  11. package/internal/api-client/measureApiRequest.js.map +1 -1
  12. package/internal/api-client/serverTiming.d.ts +12 -0
  13. package/internal/api-client/serverTiming.js +49 -0
  14. package/internal/api-client/serverTiming.js.map +1 -0
  15. package/internal/validators/documentCreateSeedRefinements.js +9 -0
  16. package/internal/validators/documentCreateSeedRefinements.js.map +1 -0
  17. package/internal/validators/operation/attachments.d.ts +48 -8
  18. package/internal/validators/operation/auth.d.ts +576 -76
  19. package/internal/validators/operation/containerMutations.d.ts +619 -44
  20. package/internal/validators/operation/containerMutations.js +7 -1
  21. package/internal/validators/operation/containerMutations.js.map +1 -1
  22. package/internal/validators/operation/documentMutations.d.ts +428 -12
  23. package/internal/validators/operation/documentMutations.js +6 -1
  24. package/internal/validators/operation/documentMutations.js.map +1 -1
  25. package/internal/validators/operation/documentSync.d.ts +33 -13
  26. package/internal/validators/operation/organizations.d.ts +648 -88
  27. package/internal/validators/operation/principals.d.ts +96 -16
  28. package/internal/validators/request/blob.d.ts +48 -8
  29. package/internal/validators/request/container.d.ts +96 -16
  30. package/internal/validators/request/container.js +5 -2
  31. package/internal/validators/request/container.js.map +1 -1
  32. package/internal/validators/request/containerMetadata.d.ts +409 -16
  33. package/internal/validators/request/containerMetadata.js +20 -3
  34. package/internal/validators/request/containerMetadata.js.map +1 -1
  35. package/internal/validators/request/document.d.ts +631 -10
  36. package/internal/validators/request/document.js +19 -1
  37. package/internal/validators/request/document.js.map +1 -1
  38. package/internal/validators/request/documentCreateSeed.js +35 -0
  39. package/internal/validators/request/documentCreateSeed.js.map +1 -0
  40. package/internal/validators/request/documentSyncSchema.d.ts +24 -4
  41. package/internal/validators/request/documentSyncSchema.js +2 -1
  42. package/internal/validators/request/documentSyncSchema.js.map +1 -1
  43. package/internal/validators/request/index.d.ts +1 -0
  44. package/internal/validators/request/index.js +1 -0
  45. package/internal/validators/request/index.js.map +1 -1
  46. package/internal/validators/request/organization.d.ts +96 -16
  47. package/internal/validators/request/organizationProvisioning.d.ts +1456 -246
  48. package/internal/validators/request/organizationProvisioning.js +9 -22
  49. package/internal/validators/request/organizationProvisioning.js.map +1 -1
  50. package/internal/validators/request/principal.d.ts +120 -20
  51. package/internal/validators/request/principalPolicyRef.d.ts +42 -0
  52. package/internal/validators/request/principalPolicyRef.js +19 -0
  53. package/internal/validators/request/principalPolicyRef.js.map +1 -0
  54. package/internal/validators/request/registration.d.ts +456 -76
  55. package/internal/validators/response/containerMetadata.d.ts +20 -0
  56. package/internal/validators/response/documentMutation.d.ts +43 -0
  57. package/internal/validators/response/documentMutation.js +12 -1
  58. package/internal/validators/response/documentMutation.js.map +1 -1
  59. package/internal/validators/response/documentSyncSchema.d.ts +13 -9
  60. package/internal/validators/response/documentSyncSchema.js +23 -18
  61. package/internal/validators/response/documentSyncSchema.js.map +1 -1
  62. package/internal/validators/response/index.d.ts +1 -1
  63. package/internal/validators/response/index.js.map +1 -1
  64. package/internal/validators/response/organizationProvisioning.d.ts +350 -0
  65. package/internal/validators/response/registration.d.ts +120 -0
  66. package/internal/validators/util/containerLimits.d.ts +8 -0
  67. package/internal/validators/util/containerLimits.js +8 -0
  68. package/internal/validators/util/containerLimits.js.map +1 -1
  69. package/package.json +1 -1
  70. package/stores/container-contents/containerState/containerStatePersistence.js +2 -0
  71. package/stores/container-contents/containerState/containerStatePersistence.js.map +1 -1
  72. package/stores/container-contents/remoteEvents/remoteEventSync.js +1 -1
  73. package/stores/container-contents/remoteEvents/remoteEventSync.js.map +1 -1
  74. package/stores/container-contents/state.js +2 -0
  75. package/stores/container-contents/state.js.map +1 -1
  76. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +5 -0
  77. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  78. package/stores/documents/documentStore/sync/createdDocumentPersistence.js +71 -0
  79. package/stores/documents/documentStore/sync/createdDocumentPersistence.js.map +1 -0
  80. package/stores/documents/documentStore/sync/index.js +13 -2
  81. package/stores/documents/documentStore/sync/index.js.map +1 -1
  82. package/stores/documents/documentStore/sync/syncRemoteSignals.js +21 -3
  83. package/stores/documents/documentStore/sync/syncRemoteSignals.js.map +1 -1
  84. package/stores/documents/documentStore/sync/syncSeededCreate.js +50 -0
  85. package/stores/documents/documentStore/sync/syncSeededCreate.js.map +1 -0
  86. package/stores/documents/documentStore/sync/syncShared.js +16 -8
  87. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  88. package/workflows/container-contents/container-state/create/createIntentSeed.js +60 -0
  89. package/workflows/container-contents/container-state/create/createIntentSeed.js.map +1 -0
  90. package/workflows/container-contents/container-state/create/createIntentSync.js +18 -19
  91. package/workflows/container-contents/container-state/create/createIntentSync.js.map +1 -1
  92. package/workflows/container-contents/container-state/create/createWithMetadata.js +43 -6
  93. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  94. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +5 -1
  95. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
  96. package/workflows/container-contents/container-state/remote.js +15 -0
  97. package/workflows/container-contents/container-state/remote.js.map +1 -1
  98. package/workflows/container-contents/container-state/types.js.map +1 -1
  99. package/workflows/container-contents/metadata/metadataEvents.d.ts +7 -1
  100. package/workflows/container-contents/metadata/metadataEvents.js +8 -2
  101. package/workflows/container-contents/metadata/metadataEvents.js.map +1 -1
  102. package/workflows/container-contents/remoteHydration/types.d.ts +3 -0
  103. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  104. package/workflows/containers/child/mutationRequestCore.js +2 -2
  105. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  106. package/workflows/containers/child/recitePlan.js +2 -2
  107. package/workflows/containers/child/recitePlan.js.map +1 -1
  108. package/workflows/containers/root/create.js +17 -28
  109. package/workflows/containers/root/create.js.map +1 -1
  110. package/workflows/containers/root/initialGroupPolicy.js +0 -23
  111. package/workflows/containers/root/initialGroupPolicy.js.map +1 -1
  112. package/workflows/documents/create/index.d.ts +7 -0
  113. package/workflows/documents/create/index.js +40 -2
  114. package/workflows/documents/create/index.js.map +1 -1
  115. package/workflows/documents/index.d.ts +1 -0
  116. package/workflows/documents/index.js +1 -0
  117. package/workflows/documents/index.js.map +1 -1
  118. package/workflows/documents/sync/initialSync.d.ts +39 -0
  119. package/workflows/documents/sync/initialSync.js +39 -6
  120. package/workflows/documents/sync/initialSync.js.map +1 -1
  121. package/workflows/documents/syncFailures/syncPolicyRepair.js +2 -8
  122. package/workflows/documents/syncFailures/syncPolicyRepair.js.map +1 -1
  123. package/workflows/registration/provisioningBootstrapBuilders.d.ts +12 -2
@@ -1 +1 @@
1
- {"version":3,"file":"metadataEvents.js","sourceRoot":"","sources":["metadataEvents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AAGpF,MAAM,UAAU,uCAAuC,CACrD,MAA8B,EAC9B,cAAwE,EACxE,wBAAsC;IAEtC,0EAA0E;IAC1E,mCAAmC;IACnC,OAAO,CACL,sCAAsC,CACpC,MAAM,EACN,cAAc,EACd,wBAAwB,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,wBAAwB,CAAC,CAAC,CAAC,CAAC,SAAS,CACzE,CAAC,MAAM,GAAG,CAAC,CACb,CAAC;AACJ,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,CAAC,KAAK,EAAE,wBAAwB,CAAC,EAAE,CAAC;YACnE,SAAS;QACX,CAAC;QACD,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACzC,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;AACtC,CAAC","sourcesContent":["import { isDocumentUpdateCreatedEvent } from \"../../../data/documents/documentSync\";\nimport type { DocumentRecord } from \"../../../data/sqlite/documentPersistence\";\n\nexport function hasContainerMetadataDocumentUpdateEvent(\n events: ReadonlyArray<unknown>,\n metadataStates: Iterable<{ record: Pick<DocumentRecord, \"documentId\"> }>,\n locallyAcceptedUpdateIds?: Set<string>,\n): boolean {\n // A boolean predicate must not consume self-echo ids before the real list\n // pass classifies the same events.\n return (\n listContainerMetadataDocumentUpdateIds(\n events,\n metadataStates,\n locallyAcceptedUpdateIds ? new Set(locallyAcceptedUpdateIds) : undefined,\n ).length > 0\n );\n}\n\n/** Consume local ids and report whether an event still contains a peer id. */\nfunction metadataEventHasRemoteUpdate(\n event: { updateIds?: readonly string[] | undefined },\n locallyAcceptedUpdateIds: Set<string> | undefined,\n): boolean {\n if (\n !locallyAcceptedUpdateIds ||\n !event.updateIds ||\n event.updateIds.length === 0\n ) {\n return true;\n }\n\n let remoteUpdateFound = false;\n for (const updateId of event.updateIds) {\n if (locallyAcceptedUpdateIds.has(updateId)) {\n locallyAcceptedUpdateIds.delete(updateId);\n } else {\n remoteUpdateFound = true;\n }\n }\n return remoteUpdateFound;\n}\n\nexport function listContainerMetadataDocumentUpdateIds(\n events: ReadonlyArray<unknown>,\n metadataStates: Iterable<{ record: Pick<DocumentRecord, \"documentId\"> }>,\n locallyAcceptedUpdateIds?: Set<string>,\n): string[] {\n const metadataDocumentIds = new Set<string>();\n for (const metadataState of metadataStates) {\n if (typeof metadataState.record.documentId === \"string\") {\n metadataDocumentIds.add(metadataState.record.documentId);\n }\n }\n if (metadataDocumentIds.size === 0) return [];\n\n const eventDocumentIds = new Set<string>();\n for (const event of events) {\n if (\n !isDocumentUpdateCreatedEvent(event) ||\n !metadataDocumentIds.has(event.documentId)\n ) {\n continue;\n }\n if (!metadataEventHasRemoteUpdate(event, locallyAcceptedUpdateIds)) {\n continue;\n }\n eventDocumentIds.add(event.documentId);\n }\n\n return Array.from(eventDocumentIds);\n}\n"]}
1
+ {"version":3,"file":"metadataEvents.js","sourceRoot":"","sources":["metadataEvents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AAGpF,MAAM,UAAU,uCAAuC,CACrD,MAA8B,EAC9B,cAAwE,EACxE,wBAAsC;IAEtC,0EAA0E;IAC1E,mCAAmC;IACnC,OAAO,CACL,sCAAsC,CACpC,MAAM,EACN,cAAc,EACd,wBAAwB,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,wBAAwB,CAAC,CAAC,CAAC,CAAC,SAAS,CACzE,CAAC,MAAM,GAAG,CAAC,CACb,CAAC;AACJ,CAAC;AAED,8EAA8E;AAC9E,SAAS,4BAA4B,CACnC,KAAoD,EACpD,wBAAiD;IAEjD,IACE,CAAC,wBAAwB;QACzB,CAAC,KAAK,CAAC,SAAS;QAChB,KAAK,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EAC5B,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,iBAAiB,GAAG,KAAK,CAAC;IAC9B,KAAK,MAAM,QAAQ,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;QACvC,IAAI,wBAAwB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC3C,wBAAwB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAC5C,CAAC;aAAM,CAAC;YACN,iBAAiB,GAAG,IAAI,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,OAAO,iBAAiB,CAAC;AAC3B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,sCAAsC,CACpD,MAA8B,EAC9B,cAAwE,EACxE,wBAAsC,EACtC,kBAAqC;IAErC,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAS,kBAAkB,CAAC,CAAC;IAChE,KAAK,MAAM,aAAa,IAAI,cAAc,EAAE,CAAC;QAC3C,IAAI,OAAO,aAAa,CAAC,MAAM,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;YACxD,mBAAmB,CAAC,GAAG,CAAC,aAAa,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;IACD,IAAI,mBAAmB,CAAC,IAAI,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAE9C,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;IAC3C,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,IACE,CAAC,4BAA4B,CAAC,KAAK,CAAC;YACpC,CAAC,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,EAC1C,CAAC;YACD,SAAS;QACX,CAAC;QACD,IAAI,CAAC,4BAA4B,CAAC,KAAK,EAAE,wBAAwB,CAAC,EAAE,CAAC;YACnE,SAAS;QACX,CAAC;QACD,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACzC,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;AACtC,CAAC","sourcesContent":["import { isDocumentUpdateCreatedEvent } from \"../../../data/documents/documentSync\";\nimport type { DocumentRecord } from \"../../../data/sqlite/documentPersistence\";\n\nexport function hasContainerMetadataDocumentUpdateEvent(\n events: ReadonlyArray<unknown>,\n metadataStates: Iterable<{ record: Pick<DocumentRecord, \"documentId\"> }>,\n locallyAcceptedUpdateIds?: Set<string>,\n): boolean {\n // A boolean predicate must not consume self-echo ids before the real list\n // pass classifies the same events.\n return (\n listContainerMetadataDocumentUpdateIds(\n events,\n metadataStates,\n locallyAcceptedUpdateIds ? new Set(locallyAcceptedUpdateIds) : undefined,\n ).length > 0\n );\n}\n\n/** Consume local ids and report whether an event still contains a peer id. */\nfunction metadataEventHasRemoteUpdate(\n event: { updateIds?: readonly string[] | undefined },\n locallyAcceptedUpdateIds: Set<string> | undefined,\n): boolean {\n if (\n !locallyAcceptedUpdateIds ||\n !event.updateIds ||\n event.updateIds.length === 0\n ) {\n return true;\n }\n\n let remoteUpdateFound = false;\n for (const updateId of event.updateIds) {\n if (locallyAcceptedUpdateIds.has(updateId)) {\n locallyAcceptedUpdateIds.delete(updateId);\n } else {\n remoteUpdateFound = true;\n }\n }\n return remoteUpdateFound;\n}\n\n/**\n * `plannedDocumentIds` names the metadata documents of folders whose create is\n * in flight. A peer can edit one after the create commits but before the\n * response installs its id, and a committed seed stands in for the folder's\n * first metadata sync, so that hint must still queue a read.\n */\nexport function listContainerMetadataDocumentUpdateIds(\n events: ReadonlyArray<unknown>,\n metadataStates: Iterable<{ record: Pick<DocumentRecord, \"documentId\"> }>,\n locallyAcceptedUpdateIds?: Set<string>,\n plannedDocumentIds?: Iterable<string>,\n): string[] {\n const metadataDocumentIds = new Set<string>(plannedDocumentIds);\n for (const metadataState of metadataStates) {\n if (typeof metadataState.record.documentId === \"string\") {\n metadataDocumentIds.add(metadataState.record.documentId);\n }\n }\n if (metadataDocumentIds.size === 0) return [];\n\n const eventDocumentIds = new Set<string>();\n for (const event of events) {\n if (\n !isDocumentUpdateCreatedEvent(event) ||\n !metadataDocumentIds.has(event.documentId)\n ) {\n continue;\n }\n if (!metadataEventHasRemoteUpdate(event, locallyAcceptedUpdateIds)) {\n continue;\n }\n eventDocumentIds.add(event.documentId);\n }\n\n return Array.from(eventDocumentIds);\n}\n"]}
@@ -64,6 +64,9 @@ export type PersistContainerStateResult = {
64
64
  };
65
65
  export interface RemoteContainerHydrationHost {
66
66
  persistContainerState: (containerState: ContainerState, patch?: Partial<ContainerMetadataPatch>, updateView?: boolean, saveOptions?: SaveContainerOptions, mutationOptions?: {
67
+ /** Queued metadata rows the server committed, settled in this write. */
68
+ acceptedPendingUpdateIds?: readonly string[] | undefined;
69
+ clearSyncFailure?: boolean | undefined;
67
70
  expectedStateWhenMissing?: ContainerState | undefined;
68
71
  isCurrent?: (() => boolean) | undefined;
69
72
  createIntentSettlement?: Parameters<ContainerContentsPersistence["commitMetadataMutation"]>[1]["createIntentSettlement"];
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { ContainerReplacementAuthorizationsResponse } from \"@tearleads/validators/operation\";\nimport type { ListContainerParentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n ListContainerParentLanesResponse,\n ListContainersResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { createContainerMetadataDocument } from \"../../../data/containers/containerMetadataDocument\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord,\n ContainerHydrationTombstone,\n ContainerRecord,\n createContainerParentSyncLane,\n} from \"../containerPersistence\";\nimport type { ContainerMetadataPatch } from \"../metadata\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ListedRemoteContainerPageItem =\n ListContainersResponse[\"items\"][number];\nexport type ContainerChildIndex = Map<string, Set<string>>;\nexport type QueueContainerParentLane = (parentId: string | null) => void;\nexport type RemoteContainerIngestQueue = Map<string, RemoteContainer>;\nexport type SaveContainerOptions = Parameters<\n ContainerContentsPersistence[\"saveContainer\"]\n>[3];\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createContainerMetadataDocument>\n>;\nexport type RemoteContainer = Pick<\n ContainerSummary,\n | \"createdAt\"\n | \"effectiveAccessLevel\"\n | \"systemSlot\"\n | \"id\"\n | \"metadataAccessEpoch\"\n | \"metadataAccessStateHash\"\n | \"metadataDocumentId\"\n | \"metadataReferencedPrincipals\"\n | \"organizationId\"\n | \"parentId\"\n | \"updatedAt\"\n>;\n\nexport interface ContainerState {\n containerWriterProjection?:\n | ContainerWriterProjectionResponse\n | null\n | undefined;\n /**\n * Bumped whenever a realtime hint drops this container's cached writer\n * projections (container and metadata document alike); an operation that\n * fetched or carried a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration?: number | undefined;\n metadataReferencedPrincipals?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n container: ContainerRecord;\n doc: ContainerMetadataDocumentState;\n metadataWriterProjection?:\n | DocumentWriterProjectionResponse\n | null\n | undefined;\n /** Durable pull progress mirrored from the metadata document record. */\n pullContinuation?: ContainerDocumentRecord[\"pullContinuation\"] | undefined;\n record: ContainerDocumentRecord;\n}\n\ninterface RemoteContainerHydrationApi\n extends Partial<PrincipalPolicyHistoryReader>,\n CurrentPrincipalPolicyReader {\n getContainerReplacementAuthorizationsResult(\n containerId: string,\n replacesOrganizationId: string,\n ): Promise<RequestResult<ContainerReplacementAuthorizationsResponse>>;\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n listContainerParentLanes(\n input: ListContainerParentLanesRequest,\n ): Promise<ListContainerParentLanesResponse | null>;\n}\n\ninterface RemoteContainerHydrationRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"adoptRootContainer\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: RemoteContainerHydrationApi;\n}\n\nexport interface RemoteContainerHydrationState {\n containersById: Map<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n persistence: ContainerContentsPersistence;\n rootLaneHydrated?: boolean | undefined;\n runtime: RemoteContainerHydrationRuntime;\n structuralGeneration?: number | undefined;\n}\n\nexport type PersistContainerStateResult =\n | { status: \"identity-superseded\"; record: ContainerDocumentRecord }\n | { status: \"missing\" }\n | {\n status: \"persisted\";\n record: ContainerDocumentRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | { status: \"stale-generation\" };\n\nexport interface RemoteContainerHydrationHost {\n persistContainerState: (\n containerState: ContainerState,\n patch?: Partial<ContainerMetadataPatch>,\n updateView?: boolean,\n saveOptions?: SaveContainerOptions,\n mutationOptions?: {\n expectedStateWhenMissing?: ContainerState | undefined;\n isCurrent?: (() => boolean) | undefined;\n createIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"createIntentSettlement\"];\n moveIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"moveIntentSettlement\"];\n preserveDurableStructureWhenPending?: boolean | undefined;\n },\n ) => Promise<PersistContainerStateResult>;\n requestDocumentPriming?: (() => void) | undefined;\n updateSnapshot: () => void;\n}\n\nexport interface ContainerParentHydrationLane {\n parentId: string | null;\n watermark?: ListContainersResponse[\"nextWatermark\"];\n}\n\nexport interface ExpectedContainerState {\n container: ContainerRecord;\n fingerprint: string;\n}\n\nexport interface FetchedContainerParentLanePage {\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n expectedHydrationTombstones: ReadonlyMap<string, ContainerHydrationTombstone>;\n lane: ContainerParentHydrationLane;\n response: ListContainersResponse;\n syncLane: ReturnType<typeof createContainerParentSyncLane>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { ContainerReplacementAuthorizationsResponse } from \"@tearleads/validators/operation\";\nimport type { ListContainerParentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n ListContainerParentLanesResponse,\n ListContainersResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { createContainerMetadataDocument } from \"../../../data/containers/containerMetadataDocument\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord,\n ContainerHydrationTombstone,\n ContainerRecord,\n createContainerParentSyncLane,\n} from \"../containerPersistence\";\nimport type { ContainerMetadataPatch } from \"../metadata\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ListedRemoteContainerPageItem =\n ListContainersResponse[\"items\"][number];\nexport type ContainerChildIndex = Map<string, Set<string>>;\nexport type QueueContainerParentLane = (parentId: string | null) => void;\nexport type RemoteContainerIngestQueue = Map<string, RemoteContainer>;\nexport type SaveContainerOptions = Parameters<\n ContainerContentsPersistence[\"saveContainer\"]\n>[3];\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createContainerMetadataDocument>\n>;\nexport type RemoteContainer = Pick<\n ContainerSummary,\n | \"createdAt\"\n | \"effectiveAccessLevel\"\n | \"systemSlot\"\n | \"id\"\n | \"metadataAccessEpoch\"\n | \"metadataAccessStateHash\"\n | \"metadataDocumentId\"\n | \"metadataReferencedPrincipals\"\n | \"organizationId\"\n | \"parentId\"\n | \"updatedAt\"\n>;\n\nexport interface ContainerState {\n containerWriterProjection?:\n | ContainerWriterProjectionResponse\n | null\n | undefined;\n /**\n * Bumped whenever a realtime hint drops this container's cached writer\n * projections (container and metadata document alike); an operation that\n * fetched or carried a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration?: number | undefined;\n metadataReferencedPrincipals?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n container: ContainerRecord;\n doc: ContainerMetadataDocumentState;\n metadataWriterProjection?:\n | DocumentWriterProjectionResponse\n | null\n | undefined;\n /** Durable pull progress mirrored from the metadata document record. */\n pullContinuation?: ContainerDocumentRecord[\"pullContinuation\"] | undefined;\n record: ContainerDocumentRecord;\n}\n\ninterface RemoteContainerHydrationApi\n extends Partial<PrincipalPolicyHistoryReader>,\n CurrentPrincipalPolicyReader {\n getContainerReplacementAuthorizationsResult(\n containerId: string,\n replacesOrganizationId: string,\n ): Promise<RequestResult<ContainerReplacementAuthorizationsResponse>>;\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n listContainerParentLanes(\n input: ListContainerParentLanesRequest,\n ): Promise<ListContainerParentLanesResponse | null>;\n}\n\ninterface RemoteContainerHydrationRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"adoptRootContainer\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: RemoteContainerHydrationApi;\n}\n\nexport interface RemoteContainerHydrationState {\n containersById: Map<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n persistence: ContainerContentsPersistence;\n rootLaneHydrated?: boolean | undefined;\n runtime: RemoteContainerHydrationRuntime;\n structuralGeneration?: number | undefined;\n}\n\nexport type PersistContainerStateResult =\n | { status: \"identity-superseded\"; record: ContainerDocumentRecord }\n | { status: \"missing\" }\n | {\n status: \"persisted\";\n record: ContainerDocumentRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | { status: \"stale-generation\" };\n\nexport interface RemoteContainerHydrationHost {\n persistContainerState: (\n containerState: ContainerState,\n patch?: Partial<ContainerMetadataPatch>,\n updateView?: boolean,\n saveOptions?: SaveContainerOptions,\n mutationOptions?: {\n /** Queued metadata rows the server committed, settled in this write. */\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedStateWhenMissing?: ContainerState | undefined;\n isCurrent?: (() => boolean) | undefined;\n createIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"createIntentSettlement\"];\n moveIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"moveIntentSettlement\"];\n preserveDurableStructureWhenPending?: boolean | undefined;\n },\n ) => Promise<PersistContainerStateResult>;\n requestDocumentPriming?: (() => void) | undefined;\n updateSnapshot: () => void;\n}\n\nexport interface ContainerParentHydrationLane {\n parentId: string | null;\n watermark?: ListContainersResponse[\"nextWatermark\"];\n}\n\nexport interface ExpectedContainerState {\n container: ContainerRecord;\n fingerprint: string;\n}\n\nexport interface FetchedContainerParentLanePage {\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n expectedHydrationTombstones: ReadonlyMap<string, ContainerHydrationTombstone>;\n lane: ContainerParentHydrationLane;\n response: ListContainersResponse;\n syncLane: ReturnType<typeof createContainerParentSyncLane>;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { principalPolicyRequestRecord } from "../../../data/containers/shared/principalPolicies.js";
1
+ import { principalPolicyRef } from "../../../data/containers/shared/principalPolicies.js";
2
2
  import { containerManifestRef } from "../../../data/containers/shared/projection.js";
3
3
  import { readCanonicalRecord, readCanonicalRecords, } from "../../../data/keying/canonicalJson.js";
4
4
  export function readCanonicalRecordOrNull(value, label) {
@@ -31,7 +31,7 @@ export function containerMutationRequestCore(operation, input) {
31
31
  body: readCanonicalRecord(input.body, `${label} body`),
32
32
  expectedManifestHash: input.manifestHash,
33
33
  manifest: readCanonicalRecord(input.manifest, `${label} manifest`),
34
- principalPolicies: readCanonicalRecords(input.principalPolicies.map((policy) => principalPolicyRequestRecord(policy)), `${label} principal policies`),
34
+ principalPolicyRefs: input.principalPolicies.map(principalPolicyRef),
35
35
  keyEpoch: readCanonicalRecord(input.keyEpoch, `${label} key epoch`),
36
36
  wraps: readCanonicalRecords(input.wraps, `${label} wraps`),
37
37
  userRecipientKeys: readCanonicalRecords(input.userRecipientKeys, `${label} user recipient keys`),
@@ -1 +1 @@
1
- {"version":3,"file":"mutationRequestCore.js","sourceRoot":"","sources":["mutationRequestCore.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,4BAA4B,EAAE,MAAM,mDAAmD,CAAC;AACjG,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAClF,OAAO,EACL,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,oCAAoC,CAAC;AAG5C,MAAM,UAAU,yBAAyB,CACvC,KAAc,EACd,KAAa;IAEb,OAAO,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;QAC1C,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AACxC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CACvC,gBAA0C,EAC1C,kBAAqD;IAKrD,OAAO;QACL,mBAAmB,EAAE,oBAAoB,CAAC,gBAAgB,CAAC;QAC3D,yBAAyB,EACvB,kBAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,oBAAoB,CAAC;KACpD,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,4BAA4B,CAC1C,SAAiB,EACjB,KASC;IAYD,MAAM,KAAK,GAAG,aAAa,SAAS,EAAE,CAAC;IACvC,OAAO;QACL,KAAK,EAAE,mBAAmB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK,QAAQ,CAAC;QACzD,IAAI,EAAE,mBAAmB,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC;QACtD,oBAAoB,EAAE,KAAK,CAAC,YAAY;QACxC,QAAQ,EAAE,mBAAmB,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,KAAK,WAAW,CAAC;QAClE,iBAAiB,EAAE,oBAAoB,CACrC,KAAK,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CACrC,4BAA4B,CAAC,MAAM,CAAC,CACrC,EACD,GAAG,KAAK,qBAAqB,CAC9B;QACD,QAAQ,EAAE,mBAAmB,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,KAAK,YAAY,CAAC;QACnE,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK,QAAQ,CAAC;QAC1D,iBAAiB,EAAE,oBAAoB,CACrC,KAAK,CAAC,iBAAiB,EACvB,GAAG,KAAK,sBAAsB,CAC/B;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerMutationRequest,\n} from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyRequestRecord } from \"../../../data/containers/shared/principalPolicies\";\nimport { containerManifestRef } from \"../../../data/containers/shared/projection\";\nimport {\n readCanonicalRecord,\n readCanonicalRecords,\n} from \"../../../data/keying/canonicalJson\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principals/principalPolicyEvidence\";\n\nexport function readCanonicalRecordOrNull(\n value: unknown,\n label: string,\n): Record<string, unknown> | null {\n return value === null || value === undefined\n ? null\n : readCanonicalRecord(value, label);\n}\n\n/**\n * The previous-manifest identity every non-create mutation\n * (share/rekey/revoke/move) sends alongside the core request fields: the\n * previous head and the current path, cited by hash rather than echoed.\n */\nexport function previousPathRequestFields(\n previousManifest: AccessManifestBundleWire,\n previousProjection: ContainerWriterProjectionResponse,\n): Pick<\n ContainerMutationRequest,\n \"previousManifestRef\" | \"previousContainerPathRefs\"\n> {\n return {\n previousManifestRef: containerManifestRef(previousManifest),\n previousContainerPathRefs:\n previousProjection.path.map(containerManifestRef),\n };\n}\n\n/**\n * The eight ContainerMutationRequest fields every child-container mutation\n * (create/share/rekey/revoke/move) assembles identically, labeled by\n * operation. The identity fields — previous manifest/path, manifest history,\n * predecessor bridge, keyring, and the parent KEK — genuinely differ per\n * operation and stay with each builder.\n */\nexport function containerMutationRequestCore(\n operation: string,\n input: {\n body: unknown;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n },\n): Pick<\n ContainerMutationRequest,\n | \"event\"\n | \"body\"\n | \"expectedManifestHash\"\n | \"manifest\"\n | \"principalPolicies\"\n | \"keyEpoch\"\n | \"wraps\"\n | \"userRecipientKeys\"\n> {\n const label = `Container ${operation}`;\n return {\n event: readCanonicalRecord(input.event, `${label} event`),\n body: readCanonicalRecord(input.body, `${label} body`),\n expectedManifestHash: input.manifestHash,\n manifest: readCanonicalRecord(input.manifest, `${label} manifest`),\n principalPolicies: readCanonicalRecords(\n input.principalPolicies.map((policy) =>\n principalPolicyRequestRecord(policy),\n ),\n `${label} principal policies`,\n ),\n keyEpoch: readCanonicalRecord(input.keyEpoch, `${label} key epoch`),\n wraps: readCanonicalRecords(input.wraps, `${label} wraps`),\n userRecipientKeys: readCanonicalRecords(\n input.userRecipientKeys,\n `${label} user recipient keys`,\n ),\n };\n}\n"]}
1
+ {"version":3,"file":"mutationRequestCore.js","sourceRoot":"","sources":["mutationRequestCore.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,kBAAkB,EAAE,MAAM,mDAAmD,CAAC;AACvF,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAClF,OAAO,EACL,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,oCAAoC,CAAC;AAG5C,MAAM,UAAU,yBAAyB,CACvC,KAAc,EACd,KAAa;IAEb,OAAO,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;QAC1C,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AACxC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CACvC,gBAA0C,EAC1C,kBAAqD;IAKrD,OAAO;QACL,mBAAmB,EAAE,oBAAoB,CAAC,gBAAgB,CAAC;QAC3D,yBAAyB,EACvB,kBAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,oBAAoB,CAAC;KACpD,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,4BAA4B,CAC1C,SAAiB,EACjB,KASC;IAYD,MAAM,KAAK,GAAG,aAAa,SAAS,EAAE,CAAC;IACvC,OAAO;QACL,KAAK,EAAE,mBAAmB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK,QAAQ,CAAC;QACzD,IAAI,EAAE,mBAAmB,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC;QACtD,oBAAoB,EAAE,KAAK,CAAC,YAAY;QACxC,QAAQ,EAAE,mBAAmB,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,KAAK,WAAW,CAAC;QAClE,mBAAmB,EAAE,KAAK,CAAC,iBAAiB,CAAC,GAAG,CAAC,kBAAkB,CAAC;QACpE,QAAQ,EAAE,mBAAmB,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,KAAK,YAAY,CAAC;QACnE,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,KAAK,QAAQ,CAAC;QAC1D,iBAAiB,EAAE,oBAAoB,CACrC,KAAK,CAAC,iBAAiB,EACvB,GAAG,KAAK,sBAAsB,CAC/B;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerMutationRequest,\n} from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyRef } from \"../../../data/containers/shared/principalPolicies\";\nimport { containerManifestRef } from \"../../../data/containers/shared/projection\";\nimport {\n readCanonicalRecord,\n readCanonicalRecords,\n} from \"../../../data/keying/canonicalJson\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principals/principalPolicyEvidence\";\n\nexport function readCanonicalRecordOrNull(\n value: unknown,\n label: string,\n): Record<string, unknown> | null {\n return value === null || value === undefined\n ? null\n : readCanonicalRecord(value, label);\n}\n\n/**\n * The previous-manifest identity every non-create mutation\n * (share/rekey/revoke/move) sends alongside the core request fields: the\n * previous head and the current path, cited by hash rather than echoed.\n */\nexport function previousPathRequestFields(\n previousManifest: AccessManifestBundleWire,\n previousProjection: ContainerWriterProjectionResponse,\n): Pick<\n ContainerMutationRequest,\n \"previousManifestRef\" | \"previousContainerPathRefs\"\n> {\n return {\n previousManifestRef: containerManifestRef(previousManifest),\n previousContainerPathRefs:\n previousProjection.path.map(containerManifestRef),\n };\n}\n\n/**\n * The eight ContainerMutationRequest fields every child-container mutation\n * (create/share/rekey/revoke/move) assembles identically, labeled by\n * operation. The identity fields — previous manifest/path, manifest history,\n * predecessor bridge, keyring, and the parent KEK — genuinely differ per\n * operation and stay with each builder.\n */\nexport function containerMutationRequestCore(\n operation: string,\n input: {\n body: unknown;\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n },\n): Pick<\n ContainerMutationRequest,\n | \"event\"\n | \"body\"\n | \"expectedManifestHash\"\n | \"manifest\"\n | \"principalPolicyRefs\"\n | \"keyEpoch\"\n | \"wraps\"\n | \"userRecipientKeys\"\n> {\n const label = `Container ${operation}`;\n return {\n event: readCanonicalRecord(input.event, `${label} event`),\n body: readCanonicalRecord(input.body, `${label} body`),\n expectedManifestHash: input.manifestHash,\n manifest: readCanonicalRecord(input.manifest, `${label} manifest`),\n principalPolicyRefs: input.principalPolicies.map(principalPolicyRef),\n keyEpoch: readCanonicalRecord(input.keyEpoch, `${label} key epoch`),\n wraps: readCanonicalRecords(input.wraps, `${label} wraps`),\n userRecipientKeys: readCanonicalRecords(\n input.userRecipientKeys,\n `${label} user recipient keys`,\n ),\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { computeAccessManifestHash, deriveContainerAccessManifest, KeyingVerificationError, MAX_CONTAINER_RECITATION_EPOCH, resolveContainerStatePathUserAccessLevel, } from "../../../internal/crypto/index.js";
2
2
  import { signContainerMutationEvent } from "../../../data/containers/shared/events.js";
3
- import { principalPolicyRequestRecord } from "../../../data/containers/shared/principalPolicies.js";
3
+ import { principalPolicyRef } from "../../../data/containers/shared/principalPolicies.js";
4
4
  import { containerManifestRef } from "../../../data/containers/shared/projection.js";
5
5
  import { canonicalKeyingJsonString, readCanonicalRecord, } from "../../../data/keying/canonicalJson.js";
6
6
  export function referencedRecitationPolicies(path, policies) {
@@ -53,7 +53,7 @@ export async function buildContainerRecitePlan(input) {
53
53
  expectedManifestHash: manifestHash,
54
54
  previousManifestRef: containerManifestRef(previous.bundle),
55
55
  previousContainerPathRefs: input.path.map((head) => containerManifestRef(head.bundle)),
56
- principalPolicies: referencedRecitationPolicies(input.path, input.policies).map((policy) => principalPolicyRequestRecord(policy)),
56
+ principalPolicyRefs: referencedRecitationPolicies(input.path, input.policies).map(principalPolicyRef),
57
57
  };
58
58
  return { body, event, eventHash, manifest, manifestHash, state, request };
59
59
  }
@@ -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,GACzC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,0BAA0B,EAAE,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AE,qBAAqB,CAAC;QACxD,yBAAyB,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CACzD,CAAC;IACF,IACE,QAAQ,CAAC,WAAW,KAAK,IAAI,CAAC,KAAK,CAAC,WAAW;QAC/C,QAAQ,CAAC,cAAc,KAAK,IAAI,CAAC,KAAK,CAAC,cAAc;QACrD,QAAQ,CAAC,QAAQ,KAAK,IAAI,CAAC,KAAK,CAAC,iBAAiB;QAClD,QAAQ,CAAC,YAAY,CAAC,KAAK,KAAK,IAAI,CAAC,KAAK,CAAC,KAAK;QAChD,QAAQ,CAAC,YAAY,CAAC,YAAY,KAAK,IAAI,CAAC,YAAY;QACxD,MAAM,CAAC,YAAY,KAAK,IAAI,CAAC,YAAY;QACzC,MAAM,CAAC,KAAK,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS;QACzC,CAAC,iBAAiB;QAClB,yBAAyB,CACvB,QAAQ,CAAC,wBAAwB,EACjC,uBAAuB,CACxB;YACC,yBAAyB,CACvB,IAAI,CAAC,QAAQ,CAAC,wBAAwB,EACtC,+BAA+B,CAChC;QAEH,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 type { HeldContainerHead } from \"../../../data/containers/shared/heldContainerHeads\";\nimport { principalPolicyRequestRecord } from \"../../../data/containers/shared/principalPolicies\";\nimport { containerManifestRef } from \"../../../data/containers/shared/projection\";\nimport type { ContainerMutationAuthor } from \"../../../data/containers/shared/types\";\nimport {\n canonicalKeyingJsonString,\n readCanonicalRecord,\n} from \"../../../data/keying/canonicalJson\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../../data/principals/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 manifest: readCanonicalRecord(manifest, \"Recitation manifest\"),\n expectedManifestHash: manifestHash,\n previousManifestRef: containerManifestRef(previous.bundle),\n previousContainerPathRefs: input.path.map((head) =>\n containerManifestRef(head.bundle),\n ),\n principalPolicies: referencedRecitationPolicies(\n input.path,\n input.policies,\n ).map((policy) => principalPolicyRequestRecord(policy)),\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 const bundle = response.accessManifest;\n const signedFieldsMatch = [\n [bundle.event.event, plan.event],\n [bundle.event.body, plan.body],\n [bundle.manifest, plan.manifest],\n [bundle.state, plan.state],\n ].every(\n ([actual, expected]) =>\n canonicalKeyingJsonString(actual, \"Recitation response\") ===\n canonicalKeyingJsonString(expected, \"Recitation plan\"),\n );\n if (\n response.containerId !== plan.state.containerId ||\n response.organizationId !== plan.state.organizationId ||\n response.parentId !== plan.state.parentContainerId ||\n response.manifestHead.epoch !== plan.state.epoch ||\n response.manifestHead.manifestHash !== plan.manifestHash ||\n bundle.manifestHash !== plan.manifestHash ||\n bundle.event.eventHash !== plan.eventHash ||\n !signedFieldsMatch ||\n canonicalKeyingJsonString(\n response.referencedPrincipalHeads,\n \"Recitation references\",\n ) !==\n canonicalKeyingJsonString(\n plan.manifest.referencedPrincipalHeads,\n \"Recitation planned references\",\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Container recitation response does not match the signed plan\",\n );\n}\n"]}
1
+ {"version":3,"file":"recitePlan.js","sourceRoot":"","sources":["recitePlan.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,6BAA6B,EAC7B,uBAAuB,EACvB,8BAA8B,EAC9B,wCAAwC,GACzC,MAAM,mBAAmB,CAA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,CAAC;QACxD,yBAAyB,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CACzD,CAAC;IACF,IACE,QAAQ,CAAC,WAAW,KAAK,IAAI,CAAC,KAAK,CAAC,WAAW;QAC/C,QAAQ,CAAC,cAAc,KAAK,IAAI,CAAC,KAAK,CAAC,cAAc;QACrD,QAAQ,CAAC,QAAQ,KAAK,IAAI,CAAC,KAAK,CAAC,iBAAiB;QAClD,QAAQ,CAAC,YAAY,CAAC,KAAK,KAAK,IAAI,CAAC,KAAK,CAAC,KAAK;QAChD,QAAQ,CAAC,YAAY,CAAC,YAAY,KAAK,IAAI,CAAC,YAAY;QACxD,MAAM,CAAC,YAAY,KAAK,IAAI,CAAC,YAAY;QACzC,MAAM,CAAC,KAAK,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS;QACzC,CAAC,iBAAiB;QAClB,yBAAyB,CACvB,QAAQ,CAAC,wBAAwB,EACjC,uBAAuB,CACxB;YACC,yBAAyB,CACvB,IAAI,CAAC,QAAQ,CAAC,wBAAwB,EACtC,+BAA+B,CAChC;QAEH,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 type { HeldContainerHead } from \"../../../data/containers/shared/heldContainerHeads\";\nimport { principalPolicyRef } from \"../../../data/containers/shared/principalPolicies\";\nimport { containerManifestRef } from \"../../../data/containers/shared/projection\";\nimport type { ContainerMutationAuthor } from \"../../../data/containers/shared/types\";\nimport {\n canonicalKeyingJsonString,\n readCanonicalRecord,\n} from \"../../../data/keying/canonicalJson\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../../data/principals/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 manifest: readCanonicalRecord(manifest, \"Recitation manifest\"),\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 const bundle = response.accessManifest;\n const signedFieldsMatch = [\n [bundle.event.event, plan.event],\n [bundle.event.body, plan.body],\n [bundle.manifest, plan.manifest],\n [bundle.state, plan.state],\n ].every(\n ([actual, expected]) =>\n canonicalKeyingJsonString(actual, \"Recitation response\") ===\n canonicalKeyingJsonString(expected, \"Recitation plan\"),\n );\n if (\n response.containerId !== plan.state.containerId ||\n response.organizationId !== plan.state.organizationId ||\n response.parentId !== plan.state.parentContainerId ||\n response.manifestHead.epoch !== plan.state.epoch ||\n response.manifestHead.manifestHash !== plan.manifestHash ||\n bundle.manifestHash !== plan.manifestHash ||\n bundle.event.eventHash !== plan.eventHash ||\n !signedFieldsMatch ||\n canonicalKeyingJsonString(\n response.referencedPrincipalHeads,\n \"Recitation references\",\n ) !==\n canonicalKeyingJsonString(\n plan.manifest.referencedPrincipalHeads,\n \"Recitation planned references\",\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Container recitation response does not match the signed plan\",\n );\n}\n"]}
@@ -1,8 +1,9 @@
1
1
  import { computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, deriveContainerKekWrappingPublicKey, normalizeContainerAccessEventBody, } from "../../../internal/crypto/index.js";
2
2
  import { buildContainerCreateBody, buildContainerCreateKeyEpoch, deriveContainerCreateManifest, resolveContainerKekEpochId, signContainerCreateEvent, } from "../../../data/containers/shared/events.js";
3
+ import { principalPolicyRef } from "../../../data/containers/shared/principalPolicies.js";
3
4
  import { wrapContainerKeyToManagedPrincipal, wrapContainerKeyToRootUser, } from "../../../data/containers/shared/projection.js";
4
5
  import { readCanonicalJson, readCanonicalRecord, readCanonicalRecords, } from "../../../data/keying/canonicalJson.js";
5
- import { principalHeadFromInitialGroupPolicy, principalPolicyRecordFromInitialGroupPolicy, } from "./initialGroupPolicy.js";
6
+ import { principalHeadFromInitialGroupPolicy } from "./initialGroupPolicy.js";
6
7
  function buildRootContainerCreateBody(input) {
7
8
  const baseBody = buildContainerCreateBody({
8
9
  systemSlot: input.systemSlot,
@@ -56,7 +57,7 @@ function buildRootContainerCreateRequest(input) {
56
57
  manifest: readCanonicalRecord(input.manifest, "Container root create manifest"),
57
58
  previousManifestRef: null,
58
59
  parentContainerPathRefs: [],
59
- principalPolicies: readCanonicalRecords(input.principalPolicies, "Container root create principal policies"),
60
+ principalPolicyRefs: input.principalPolicyRefs,
60
61
  keyEpoch: readCanonicalRecord(input.keyEpoch, "Container root create key epoch"),
61
62
  predecessorBridge: null,
62
63
  keyring: null,
@@ -64,26 +65,13 @@ function buildRootContainerCreateRequest(input) {
64
65
  userRecipientKeys: readCanonicalRecords(input.userRecipientKeys, "Container root create user recipient keys"),
65
66
  };
66
67
  }
67
- async function buildRootManagedPrincipalContext(adminGroup) {
68
- if (!adminGroup) {
69
- return {
70
- managedPrincipalHead: null,
71
- managedPrincipalPolicies: [],
72
- };
73
- }
74
- const managedPrincipalHead = await principalHeadFromInitialGroupPolicy({
75
- principalId: adminGroup.groupId,
76
- policy: adminGroup.initialGroupPolicy,
77
- });
78
- return {
79
- managedPrincipalHead,
80
- managedPrincipalPolicies: [
81
- principalPolicyRecordFromInitialGroupPolicy({
82
- head: managedPrincipalHead,
83
- policy: adminGroup.initialGroupPolicy,
84
- }),
85
- ],
86
- };
68
+ async function rootManagedPrincipalHead(group) {
69
+ return group
70
+ ? principalHeadFromInitialGroupPolicy({
71
+ principalId: group.groupId,
72
+ policy: group.initialGroupPolicy,
73
+ })
74
+ : null;
87
75
  }
88
76
  async function deriveRootCreateArtifacts(input) {
89
77
  if (!input.body.containerKeyPublicKey)
@@ -175,11 +163,10 @@ function normalizedRootCreateBody(input) {
175
163
  export async function buildRootContainerCreatePlan(input) {
176
164
  const containerKey = rootKeyMaterial(input.containerKey);
177
165
  const adminGroup = input.adminGroup ?? null;
178
- const { managedPrincipalHead, managedPrincipalPolicies } = await buildRootManagedPrincipalContext(adminGroup);
179
- const member = await buildRootManagedPrincipalContext(input.memberGroup ?? null);
166
+ const managedPrincipalHead = await rootManagedPrincipalHead(adminGroup);
167
+ const memberHead = await rootManagedPrincipalHead(input.memberGroup ?? null);
180
168
  if (input.memberGroup && !adminGroup)
181
169
  throw new Error("Members root grant requires Admins authority");
182
- managedPrincipalPolicies.push(...member.managedPrincipalPolicies);
183
170
  const containerKeyEpochId = await resolveContainerKekEpochId({
184
171
  containerId: input.containerId,
185
172
  keyEpoch: 1,
@@ -190,7 +177,7 @@ export async function buildRootContainerCreatePlan(input) {
190
177
  containerId: input.containerId,
191
178
  keyMaterial: containerKey,
192
179
  }),
193
- memberHead: member.managedPrincipalHead,
180
+ memberHead,
194
181
  systemSlot: input.systemSlot ?? null,
195
182
  author: input.author,
196
183
  containerKeyEpochId,
@@ -207,7 +194,7 @@ export async function buildRootContainerCreatePlan(input) {
207
194
  });
208
195
  const { recipientTargets, wraps, userRecipientKeys } = await wrapRootContainerRecipients({
209
196
  memberGroup: input.memberGroup ?? null,
210
- memberHead: member.managedPrincipalHead,
197
+ memberHead,
211
198
  adminGroup,
212
199
  containerKey,
213
200
  containerKeyEpochId,
@@ -239,7 +226,9 @@ export async function buildRootContainerCreatePlan(input) {
239
226
  keyEpoch,
240
227
  manifest,
241
228
  manifestHash,
242
- principalPolicies: managedPrincipalPolicies,
229
+ principalPolicyRefs: [managedPrincipalHead, memberHead]
230
+ .filter((head) => head !== null)
231
+ .map(principalPolicyRef),
243
232
  userRecipientKeys,
244
233
  wraps,
245
234
  }),
@@ -1 +1 @@
1
- {"version":3,"file":"create.js","sourceRoot":"","sources":["create.ts"],"names":[],"mappings":"AASA,OAAO,EACL,sCAAsC,EACtC,4BAA4B,EAC5B,mCAAmC,EACnC,iCAAiC,GAClC,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,6BAA6B,EAC7B,0BAA0B,EAC1B,wBAAwB,GACzB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,kCAAkC,EAClC,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AAMpD,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EACL,mCAAmC,EACnC,2CAA2C,GAC5C,MAAM,sBAAsB,CAAC;AAE9B,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,EAAE,KAAK,CAAC,UAAU,CAAC,WAAW;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AAC,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} 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 {\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 readCanonicalJson,\n readCanonicalRecord,\n readCanonicalRecords,\n} from \"../../../data/keying/canonicalJson\";\n\nimport {\n principalHeadFromInitialGroupPolicy,\n principalPolicyRecordFromInitialGroupPolicy,\n} 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 principalPolicies: readonly Record<string, unknown>[];\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 principalPolicies: readCanonicalRecords(\n input.principalPolicies,\n \"Container root create principal policies\",\n ),\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 buildRootManagedPrincipalContext(\n adminGroup: CreateOrganizationGroupRequest | null,\n): Promise<{\n managedPrincipalHead: ContainerGrantPrincipalHead | null;\n managedPrincipalPolicies: Record<string, unknown>[];\n}> {\n if (!adminGroup) {\n return {\n managedPrincipalHead: null,\n managedPrincipalPolicies: [],\n };\n }\n\n const managedPrincipalHead = await principalHeadFromInitialGroupPolicy({\n principalId: adminGroup.groupId,\n policy: adminGroup.initialGroupPolicy,\n });\n\n return {\n managedPrincipalHead,\n managedPrincipalPolicies: [\n principalPolicyRecordFromInitialGroupPolicy({\n head: managedPrincipalHead,\n policy: adminGroup.initialGroupPolicy,\n }),\n ],\n };\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 readCanonicalJson(buildRootContainerCreateBody(input), \"Root create body\"),\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, managedPrincipalPolicies } =\n await buildRootManagedPrincipalContext(adminGroup);\n\n const member = await buildRootManagedPrincipalContext(\n input.memberGroup ?? null,\n );\n if (input.memberGroup && !adminGroup)\n throw new Error(\"Members root grant requires Admins authority\");\n managedPrincipalPolicies.push(...member.managedPrincipalPolicies);\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: member.managedPrincipalHead,\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: member.managedPrincipalHead,\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 principalPolicies: managedPrincipalPolicies,\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","sour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BACL,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} 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 readCanonicalJson,\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 readCanonicalJson(buildRootContainerCreateBody(input), \"Root create body\"),\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,5 +1,4 @@
1
1
  import { computePrincipalStateHash } from "../../../internal/crypto/index.js";
2
- import { readCanonicalRecord } from "../../../data/keying/canonicalJson.js";
3
2
  export async function principalHeadFromInitialGroupPolicy(input) {
4
3
  return {
5
4
  principalType: "group",
@@ -10,26 +9,4 @@ export async function principalHeadFromInitialGroupPolicy(input) {
10
9
  keyFingerprint: input.policy.state.keyFingerprint,
11
10
  };
12
11
  }
13
- export function principalPolicyRecordFromInitialGroupPolicy(input) {
14
- const { head } = input;
15
- return readCanonicalRecord({
16
- principalType: head.principalType,
17
- principalId: head.principalId,
18
- version: head.version,
19
- keyEpoch: head.keyEpoch,
20
- stateHash: head.stateHash,
21
- state: {
22
- ...input.policy.state,
23
- stateHash: head.stateHash,
24
- },
25
- projection: input.policy.projection,
26
- grants: input.policy.grants,
27
- checkpoint: {
28
- principalType: head.principalType,
29
- principalId: head.principalId,
30
- version: head.version,
31
- stateHash: head.stateHash,
32
- },
33
- }, "Initial managed principal policy");
34
- }
35
12
  //# sourceMappingURL=initialGroupPolicy.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"initialGroupPolicy.js","sourceRoot":"","s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ACnC,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerGrantPrincipalHead,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { computePrincipalStateHash } from \"@tearleads/crypto\";\nimport type { CreateOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\n\ntype InitialManagedPrincipalPolicy =\n CreateOrganizationGroupRequest[\"initialGroupPolicy\"];\n\ninterface RootManagedPrincipalGrantInput {\n readonly principalId: string;\n readonly policy: InitialManagedPrincipalPolicy;\n}\n\nexport async function principalHeadFromInitialGroupPolicy(\n input: RootManagedPrincipalGrantInput,\n): Promise<ContainerGrantPrincipalHead> {\n return {\n principalType: \"group\",\n principalId: input.principalId,\n version: input.policy.state.version,\n keyEpoch: input.policy.state.keyEpoch,\n stateHash: await computePrincipalStateHash(input.policy.state),\n keyFingerprint: input.policy.state.keyFingerprint,\n };\n}\n\nexport function principalPolicyRecordFromInitialGroupPolicy(input: {\n readonly head: ReferencedPrincipalHead;\n readonly policy: InitialManagedPrincipalPolicy;\n}): Record<string, unknown> {\n const { head } = input;\n\n return readCanonicalRecord(\n {\n principalType: head.principalType,\n principalId: head.principalId,\n version: head.version,\n keyEpoch: head.keyEpoch,\n stateHash: head.stateHash,\n state: {\n ...input.policy.state,\n stateHash: head.stateHash,\n },\n projection: input.policy.projection,\n grants: input.policy.grants,\n checkpoint: {\n principalType: head.principalType,\n principalId: head.principalId,\n version: head.version,\n stateHash: head.stateHash,\n },\n },\n \"Initial managed principal policy\",\n );\n}\n"]}
1
+ {"version":3,"file":"initialGroupPolicy.js","sourceRoot":"","sources":["initialGroupPolicy.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAW9D,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,KAAqC;IAErC,OAAO;QACL,aAAa,EAAE,OAAO;QACtB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO;QACnC,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ;QACrC,SAAS,EAAE,MAAM,yBAAyB,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC;QAC9D,cAAc,EAAE,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,cAAc;KAClD,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerGrantPrincipalHead } from \"@tearleads/crypto\";\nimport { computePrincipalStateHash } from \"@tearleads/crypto\";\nimport type { CreateOrganizationGroupRequest } from \"@tearleads/validators/request\";\n\ntype InitialManagedPrincipalPolicy =\n CreateOrganizationGroupRequest[\"initialGroupPolicy\"];\n\ninterface RootManagedPrincipalGrantInput {\n readonly principalId: string;\n readonly policy: InitialManagedPrincipalPolicy;\n}\n\nexport async function principalHeadFromInitialGroupPolicy(\n input: RootManagedPrincipalGrantInput,\n): Promise<ContainerGrantPrincipalHead> {\n return {\n principalType: \"group\",\n principalId: input.principalId,\n version: input.policy.state.version,\n keyEpoch: input.policy.state.keyEpoch,\n stateHash: await computePrincipalStateHash(input.policy.state),\n keyFingerprint: input.policy.state.keyFingerprint,\n };\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { type ContainerWriterProjectionResponse, type DocumentCreateResponse } from "../../../internal/validators/response/index.js";
2
2
  import type { CreateRemoteDocumentResult, DocumentCreateApi, DocumentCreateAuthor, MaterializedDocumentCreatePlan, ProjectionVerificationOptions } from "../../../data/documents/shared/types.js";
3
3
  import type { ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../../../data/keyingProjectionVerification/index.js";
4
+ import type { PendingUpdateRecord } from "../../../data/sqlite/documentPersistence/index.js";
4
5
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
5
6
  import type { DocumentCreateTerminalFailureHandler } from "./createProjectionFetch.js";
6
7
  export declare function buildMaterializedDocumentCreatePlan(input: {
@@ -37,6 +38,12 @@ interface RemoteDocumentCreateInput {
37
38
  */
38
39
  onTerminalSubmitFailure?: DocumentCreateTerminalFailureHandler | undefined;
39
40
  resolveProjectionUserKey: ProjectionUserKeyResolver;
41
+ /**
42
+ * The queued row holding the new document's whole content (see
43
+ * `documentCreateSeedCandidate`). The create commits it as its seed, and the
44
+ * caller settles the row from the response instead of syncing it.
45
+ */
46
+ seedUpdate?: PendingUpdateRecord | undefined;
40
47
  signedAt?: string | undefined;
41
48
  stillCurrent?: (() => boolean) | undefined;
42
49
  targetSecretKey: Uint8Array;
@@ -6,6 +6,7 @@ import { projectionVerificationOptions } from "../../../data/documents/shared/ty
6
6
  import { collectContainerWriterProjectionPrincipalPolicies, nullOnProjectionVerificationCancellation, requireProjectionUserKeyResolver, } from "../../../data/keyingProjectionVerification/index.js";
7
7
  import { isContainerCreatePending } from "../../../data/persistence/container-contents/pendingContainerCreate.js";
8
8
  import { recordDocumentAuthorAccessFailure } from "../authorAccessFailure.js";
9
+ import { buildDocumentCreateSeedRequest, documentCreateSeedFits, } from "../sync/initialSync.js";
9
10
  import { isDocumentManifestAlreadyExistsConflict, shouldRetryWithFreshProjection, } from "../syncFailures/syncFailureClassification.js";
10
11
  import { adoptExistingRemoteDocument } from "./createAdoption.js";
11
12
  import { fetchContainerWriterProjectionForCreate } from "./createProjectionFetch.js";
@@ -119,6 +120,39 @@ async function buildMaterializedDocumentCreatePlanWithFreshProjection(input) {
119
120
  });
120
121
  return refreshedProjection ? buildWithProjection(refreshedProjection) : null;
121
122
  }
123
+ /**
124
+ * A seed only saves the first sync. A refusal of the seeded create falls back
125
+ * to the plain create once, so the row syncs as before and seeding adds no
126
+ * failure mode. A lost response is adopted, and a stale target is replanned
127
+ * with a fresh seed, exactly as for a plain create. Building the seed awaits
128
+ * its encryption, so each submission rechecks the caller is still current and
129
+ * returns null instead of creating a document whose response would be dropped.
130
+ */
131
+ async function submitPlannedDocumentCreateRequest(input, createPlan) {
132
+ const request = createPlan.materializedPlan.plan.request;
133
+ const organizationId = createPlan.containerProjection.organizationId;
134
+ const seed = input.seedUpdate
135
+ ? await buildDocumentCreateSeedRequest({
136
+ author: input.author,
137
+ containerProjection: createPlan.containerProjection,
138
+ materializedDocument: createPlan.materializedPlan,
139
+ pendingUpdate: input.seedUpdate,
140
+ })
141
+ : null;
142
+ if (seed && documentCreateSeedFits(seed)) {
143
+ if (input.stillCurrent?.() === false)
144
+ return null;
145
+ const seeded = await submitDocumentCreate(input.apiClient, { ...request, initialSync: seed }, organizationId);
146
+ if (seeded.ok ||
147
+ isDocumentManifestAlreadyExistsConflict(seeded) ||
148
+ isStaleDocumentCreateTargetConflict(seeded)) {
149
+ return seeded;
150
+ }
151
+ }
152
+ if (input.stillCurrent?.() === false)
153
+ return null;
154
+ return submitDocumentCreate(input.apiClient, request, organizationId);
155
+ }
122
156
  function isRemoteDocumentCreatePlanBlocked(input, createPlan) {
123
157
  const organizationId = createPlan.containerProjection.organizationId;
124
158
  return input.isRemoteSyncBlocked?.(organizationId) ?? false;
@@ -152,7 +186,9 @@ async function submitPlannedDocumentCreate(input, resolveProjectionUserKey) {
152
186
  return null;
153
187
  if (input.stillCurrent?.() === false)
154
188
  return null;
155
- let submission = await submitDocumentCreate(input.apiClient, createPlan.materializedPlan.plan.request, createPlan.containerProjection.organizationId);
189
+ let submission = await submitPlannedDocumentCreateRequest(input, createPlan);
190
+ if (!submission)
191
+ return null;
156
192
  if (isStaleDocumentCreateTargetConflict(submission)) {
157
193
  if (input.stillCurrent?.() === false) {
158
194
  return { createPlan, submission };
@@ -185,7 +221,9 @@ async function submitPlannedDocumentCreate(input, resolveProjectionUserKey) {
185
221
  createPlan = refreshedPlan;
186
222
  if (input.stillCurrent?.() === false)
187
223
  return null;
188
- submission = await submitDocumentCreate(input.apiClient, createPlan.materializedPlan.plan.request, createPlan.containerProjection.organizationId);
224
+ submission = await submitPlannedDocumentCreateRequest(input, createPlan);
225
+ if (!submission)
226
+ return null;
189
227
  }
190
228
  return { createPlan, submission };
191
229
  }