@tearleads/client-sdk 0.1.254 → 0.1.256

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 (46) hide show
  1. package/index.d.ts +1 -1
  2. package/index.js +1 -1
  3. package/index.js.map +1 -1
  4. package/internal/validators/containerSystemSlot.d.ts +6 -0
  5. package/internal/validators/containerSystemSlot.js +14 -6
  6. package/internal/validators/containerSystemSlot.js.map +1 -1
  7. package/package.json +1 -1
  8. package/stores/container-contents/hydration/remoteHydrationRequest.js +6 -5
  9. package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
  10. package/stores/container-contents/hydration/trackContainerHydration.js +35 -0
  11. package/stores/container-contents/hydration/trackContainerHydration.js.map +1 -0
  12. package/stores/container-contents/operations/index.js +4 -0
  13. package/stores/container-contents/operations/index.js.map +1 -1
  14. package/stores/container-contents/state.js +7 -2
  15. package/stores/container-contents/state.js.map +1 -1
  16. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +1 -0
  17. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  18. package/stores/container-contents/types.d.ts +2 -0
  19. package/stores/container-contents/types.js.map +1 -1
  20. package/workflows/container-contents/container-state/create/createChild.d.ts +30 -0
  21. package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -0
  22. package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
  23. package/workflows/container-contents/container-state/remote.js +1 -1
  24. package/workflows/container-contents/container-state/remote.js.map +1 -1
  25. package/workflows/container-contents/container-state/types.d.ts +141 -0
  26. package/workflows/container-contents/index.d.ts +1 -0
  27. package/workflows/container-contents/index.js +1 -0
  28. package/workflows/container-contents/index.js.map +1 -1
  29. package/workflows/container-contents/remoteHydration/destination/destinationSystemTopology.js +16 -0
  30. package/workflows/container-contents/remoteHydration/destination/destinationSystemTopology.js.map +1 -0
  31. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +8 -9
  32. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  33. package/workflows/registration/bootstrapRootContainer.d.ts +1 -0
  34. package/workflows/registration/bootstrapRootContainer.js +9 -0
  35. package/workflows/registration/bootstrapRootContainer.js.map +1 -1
  36. package/workflows/registration/index.d.ts +1 -1
  37. package/workflows/registration/index.js +1 -1
  38. package/workflows/registration/index.js.map +1 -1
  39. package/workflows/registration/organizationProvisioning.d.ts +3 -2
  40. package/workflows/registration/organizationProvisioning.js +1 -2
  41. package/workflows/registration/organizationProvisioning.js.map +1 -1
  42. package/workflows/registration/provisioningBootstrapBuilders.d.ts +3 -5
  43. package/workflows/registration/provisioningBootstrapBuilders.js +11 -5
  44. package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
  45. package/workflows/registration/registerIdentity.js +2 -0
  46. package/workflows/registration/registerIdentity.js.map +1 -1
@@ -0,0 +1,141 @@
1
+ import type { ContainerSystemSlot } from "../../../internal/validators/containerSystemSlot.js";
2
+ import type { ContainerDeleteResponse, ContainerWriterProjectionResponse, ReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
3
+ import type { DocumentCreateApi } from "../../../data/documents/shared/types.js";
4
+ import type { ProjectionUserKeyResolver } from "../../../data/keyingProjectionVerification/index.js";
5
+ import type { DocumentRecord } from "../../../data/persistence/documents/records/index.js";
6
+ import type { ContainerMutationServiceApi } from "../../containers/index.js";
7
+ import type { shareRemoteContainerWithGroup } from "../../organizations/groupShare/index.js";
8
+ import type { CurrentPrincipalPolicyReader } from "../../principals/currentPrincipalPolicyReader.js";
9
+ import type { PrincipalPolicyHistoryReader } from "../../principals/principalPolicyHistoryReader.js";
10
+ import type { ContainerContentsPersistence, ContainerCreateIntentRecord, ContainerMoveIntentRecord } from "../containerPersistence.js";
11
+ import type { createInitializedContainerMetadataDocument } from "../metadata/containerMetadataDocument.js";
12
+ import type { ContainerState, RemoteContainer as HydratedRemoteContainer, RemoteContainerHydrationHost } from "../remoteHydration/types.js";
13
+ import type { ContainerContentsWorkflowRuntime } from "../runtime.js";
14
+ export type ContainerWorkflowApi = ContainerMutationServiceApi & Parameters<typeof shareRemoteContainerWithGroup>[0]["apiClient"] & DocumentCreateApi & Partial<PrincipalPolicyHistoryReader> & CurrentPrincipalPolicyReader & {
15
+ deleteContainerResult(containerId: string, options?: {
16
+ expectedPaymentRequiredOrganizationId?: string;
17
+ reportErrors?: boolean;
18
+ requiredAncestorId?: string | undefined;
19
+ }): Promise<{
20
+ data: ContainerDeleteResponse;
21
+ ok: true;
22
+ } | {
23
+ ok: false;
24
+ report: () => void;
25
+ status: number | null;
26
+ }>;
27
+ primeContainerWriterProjection(containerId: string, projection: ContainerWriterProjectionResponse): void;
28
+ };
29
+ export interface ContainerWorkflowRuntime extends Pick<ContainerContentsWorkflowRuntime, "auth" | "crypto" | "infra" | "organizations" | "principalPolicies" | "resolveTrustedUserIdentity" | "state" | "util"> {
30
+ readonly apiClient: ContainerWorkflowApi;
31
+ }
32
+ export interface CreatedRemoteContainerState {
33
+ accessManifestHash: string;
34
+ /**
35
+ * The metadata seed the create committed, settled by the caller instead of
36
+ * a first metadata sync. Absent when the create carried no seed or fell back
37
+ * to a plain create.
38
+ */
39
+ metadataSeed?: {
40
+ readonly commitLsn: string | null;
41
+ readonly updateId: string;
42
+ } | undefined;
43
+ /** The slot this client signed into the create; never the server's echo. */
44
+ systemSlot: ContainerSystemSlot | null;
45
+ containerId: string;
46
+ createdAt: string;
47
+ metadataDocumentId: string;
48
+ organizationId: string;
49
+ /** A created container is a child; the acknowledgement echoed this parent. */
50
+ parentId: string;
51
+ persistedMetadataState: Pick<DocumentRecord, "documentId" | "contentKeyBundle" | "documentKekTargets" | "documentManifestBundle">;
52
+ updatedAt: string;
53
+ }
54
+ export interface SharedRemoteContainerState {
55
+ accessEpoch: number;
56
+ accessManifestHash: string;
57
+ createdAt: string;
58
+ metadataDocumentId: string;
59
+ referencedPrincipalHeads: ReferencedPrincipalStateResponse[];
60
+ updatedAt: string;
61
+ writerProjection: ContainerWriterProjectionResponse | null;
62
+ }
63
+ export interface SharedContainerState {
64
+ container: ContainerState["container"];
65
+ record: ContainerState["record"];
66
+ }
67
+ export type SharedContainerStateResult = {
68
+ status: "missing";
69
+ } | {
70
+ status: "confirmed";
71
+ } | (SharedContainerState & {
72
+ status: "identity-superseded" | "persisted";
73
+ });
74
+ export type RemoteContainer = HydratedRemoteContainer;
75
+ export type ContainerMetadataDocumentState = Awaited<ReturnType<typeof createInitializedContainerMetadataDocument>>["doc"];
76
+ export interface CreatedChildContainerState {
77
+ containerState: ContainerState;
78
+ initialUpdate: Uint8Array;
79
+ shouldRequestSync: boolean;
80
+ }
81
+ export interface ContainerIntentSyncState {
82
+ containersById: ReadonlyMap<string, ContainerState>;
83
+ /**
84
+ * Metadata update ids this device sent, so their own update echoes are
85
+ * classified as self-authored (shared with the metadata sync).
86
+ */
87
+ locallyAcceptedMetadataUpdateIds?: Set<string> | undefined;
88
+ /** Metadata document ids of folder creates in flight (shared with hints). */
89
+ plannedMetadataDocumentIds?: Set<string> | undefined;
90
+ persistence: ContainerContentsPersistence;
91
+ resolveProjectionUserKey: ProjectionUserKeyResolver;
92
+ runtime: ContainerWorkflowRuntime;
93
+ /**
94
+ * Verifies that a listed container is this device's pending create before it
95
+ * is adopted and returns where it sits; `assertContainerCreateAdoptable`
96
+ * unless a test replaces it.
97
+ */
98
+ verifyCreateAdoption?: (input: {
99
+ readonly containerId: string;
100
+ readonly expectedOrganizationId: string;
101
+ }) => Promise<AdoptedContainerPlacement>;
102
+ }
103
+ /** Where a verified listed create committed, and where its container is now. */
104
+ export interface AdoptedContainerPlacement {
105
+ /** The parent its signed epoch-1 `container.create` named. */
106
+ readonly createdParentId: string;
107
+ /** The verified head's parent; another writer may have moved it since. */
108
+ readonly currentParentId: string;
109
+ }
110
+ export type ContainerCreateIntentSyncState = ContainerIntentSyncState;
111
+ export type ContainerCreateIntentSyncHost = Pick<RemoteContainerHydrationHost, "persistContainerState">;
112
+ export interface ContainerCreateIntentSyncInput {
113
+ host: ContainerCreateIntentSyncHost;
114
+ /** A parent whose own create has not settled takes no child create. */
115
+ isCreatePending: (containerId: string) => boolean;
116
+ isCurrent: () => boolean;
117
+ isRemoteSyncBlocked: (organizationId: string) => boolean;
118
+ intent: ContainerCreateIntentRecord;
119
+ requestRemoteReconciliation: (parentContainerId: string | null) => void;
120
+ state: ContainerCreateIntentSyncState;
121
+ }
122
+ export type ContainerMoveIntentSyncState = ContainerIntentSyncState;
123
+ export type ContainerMoveIntentSyncHost = Pick<RemoteContainerHydrationHost, "persistContainerState" | "updateSnapshot">;
124
+ /** Later passes for moves the server accepted but no pass settled. */
125
+ export interface AcceptedMoveRetry {
126
+ /** The server holds the move: schedule a replay to settle it. */
127
+ arm: (intentId: string) => void;
128
+ /** A replay failed; continue an accepted move's retries, if it has some. */
129
+ resume: (intentId: string) => void;
130
+ }
131
+ export interface ContainerMoveIntentSyncInput {
132
+ host: ContainerMoveIntentSyncHost;
133
+ isCurrent: () => boolean;
134
+ /** A folder whose create has not settled takes no structural writes. */
135
+ isCreatePending: (containerId: string) => boolean;
136
+ isRemoteSyncBlocked: (organizationId: string) => boolean;
137
+ intent: ContainerMoveIntentRecord;
138
+ requestRemoteReconciliation: (parentContainerId: string | null) => void;
139
+ acceptedMoveRetry: AcceptedMoveRetry;
140
+ state: ContainerMoveIntentSyncState;
141
+ }
@@ -1,6 +1,7 @@
1
1
  export { DocumentContainerProjectionRepository } from "../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
2
  export { didRegainSyncPrerequisites, isDatabaseUnavailableError, } from "../../data/sync/syncCoordinator.js";
3
3
  export { type DocumentAttributionRangesInput, type DocumentAttributionRangesPage, loadDocumentAttributionRanges, } from "./attribution/documentAttributionRanges.js";
4
+ export { deriveSystemContainerId } from "./container-state/create/createChild.js";
4
5
  export type { ContainerContentsOrganizationHost } from "./container-state/organizationHost.js";
5
6
  export { type ContainerSyncWatermarkLane, ContainerSyncWatermarkRepository, createContainerContentsSyncLane, createContainerParentSyncLane, defaultContainerContentsPersistence, } from "./containerPersistence.js";
6
7
  export { type ContainerDocumentLinkInput, type ContainerDocumentQueries, type ContainerDocumentSidebarRow, type ContainerDocumentTombstone, type ContainerItemRow, type ContainerItemSort, type ContainerItemSortDirection, type ContainerItemSortKey, createContainerDocumentQueriesFromRuntime, } from "./documentQueries/index.js";
@@ -1,6 +1,7 @@
1
1
  export { DocumentContainerProjectionRepository } from "../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
2
  export { didRegainSyncPrerequisites, isDatabaseUnavailableError, } from "../../data/sync/syncCoordinator.js";
3
3
  export { loadDocumentAttributionRanges, } from "./attribution/documentAttributionRanges.js";
4
+ export { deriveSystemContainerId } from "./container-state/create/createChild.js";
4
5
  export { ContainerSyncWatermarkRepository, createContainerContentsSyncLane, createContainerParentSyncLane, defaultContainerContentsPersistence, } from "./containerPersistence.js";
5
6
  export { createContainerDocumentQueriesFromRuntime, } from "./documentQueries/index.js";
6
7
  export { activateDocumentLink, addDocumentLink, canMutateDocumentLink, canMutateLocalDocumentLink, moveDocumentLink, moveLocalDocumentLink, removeDocumentLink, } from "./documentQueries/documentStructure.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,kFAAkF,CAAC;AACzI,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGL,6BAA6B,GAC9B,MAAM,yCAAyC,CAAC;AAEjD,OAAO,EAEL,gCAAgC,EAChC,+BAA+B,EAC/B,6BAA6B,EAC7B,mCAAmC,GACpC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EASL,yCAAyC,GAC1C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,0BAA0B,EAG1B,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,GAEnB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EASL,YAAY,GACb,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAQL,iBAAiB,GAClB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAQL,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,uCAAuC,EACvC,wCAAwC,EACxC,uCAAuC,EACvC,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,EAEL,0CAA0C,EAC1C,uBAAuB,EACvB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,iBAAiB,GAOlB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,wDAAwD,EACxD,gDAAgD,EAChD,8CAA8C,GAC/C,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAcL,uCAAuC,EACvC,2CAA2C,EAC3C,uDAAuD,EACvD,sCAAsC,EACtC,kDAAkD,GACnD,MAAM,WAAW,CAAC;AAKnB,OAAO,EACL,sCAAsC,EACtC,sCAAsC,GACvC,MAAM,aAAa,CAAC;AACrB,OAAO,EAEL,yBAAyB,GAC1B,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC","sourcesContent":["export { DocumentContainerProjectionRepository } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"./attribution/documentAttributionRanges\";\nexport type { ContainerContentsOrganizationHost } from \"./container-state/organizationHost\";\nexport {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n defaultContainerContentsPersistence,\n} from \"./containerPersistence\";\nexport {\n type ContainerDocumentLinkInput,\n type ContainerDocumentQueries,\n type ContainerDocumentSidebarRow,\n type ContainerDocumentTombstone,\n type ContainerItemRow,\n type ContainerItemSort,\n type ContainerItemSortDirection,\n type ContainerItemSortKey,\n createContainerDocumentQueriesFromRuntime,\n} from \"./documentQueries\";\nexport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n type MergeDocumentSummary,\n moveDocumentLink,\n moveLocalDocumentLink,\n removeDocumentLink,\n type SetLinkedContainerIdsForDocument,\n} from \"./documentQueries/documentStructure\";\nexport type { PendingDownloadQueueItem } from \"./documentQueries/pendingDownloads\";\nexport {\n type BlobInfo,\n type BlobInfoAttachmentKind,\n type BlobInfoDocumentReference,\n type BlobInfoInput,\n type BlobInfoList,\n type BlobInfoSort,\n type BlobInfoSortDirection,\n type BlobInfoSortKey,\n listBlobInfo,\n} from \"./info/blobInfo\";\nexport {\n type ContainerInfo,\n type ContainerInfoGrant,\n type ContainerInfoGrantRow,\n type ContainerInfoPathEntry,\n type ContainerInfoRemoteMode,\n type ContainerInfoSecurityDetails,\n type ContainerShareAccessLevel,\n loadContainerInfo,\n} from \"./info/containerInfo\";\nexport {\n type DocumentInfo,\n type DocumentInfoAttachment,\n type DocumentInfoAuthorizingContainerPath,\n type DocumentInfoLocalDetails,\n type DocumentInfoRemoteAttachmentBinding,\n type DocumentInfoRemoteDetails,\n type DocumentInfoRemoteMode,\n loadDocumentInfo,\n} from \"./info/documentInfo\";\nexport {\n type ContainerMetadataPatch,\n hasContainerMetadataDocumentUpdateEvent,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n syncContainerMetadataState,\n} from \"./metadata\";\nexport {\n type ContainerMetadataDocument,\n createInitializedContainerMetadataDocument,\n getDefaultContainerName,\n readContainerMetadataValue,\n writeContainerMetadataValue,\n} from \"./metadata/containerMetadataDocument\";\nexport {\n listPendingWrites,\n type PendingWriteQueueItem,\n type PendingWriteQueueItemStatus,\n type PendingWriteQueueObjectKind,\n type PendingWriteQueueOperation,\n type PendingWriteQueueOperationKind,\n type PendingWriteQueueOperationStatus,\n} from \"./pendingWrites\";\nexport {\n type ContainerContentsProjectionUserKeyResolver,\n createContainerContentsDocumentProjectionUserKeyResolver,\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport type { RecoveryFolder } from \"./recovery/folderRecovery\";\nexport {\n type ContainerContentsRootAdopter,\n type ContainerContentsRootAdoptionInput,\n type ContainerContentsStoreWorkflowRuntime,\n type ContainerContentsWorkflowRuntime,\n type ContainerContentsWorkflowRuntimeAuth,\n type ContainerContentsWorkflowRuntimeCrypto,\n type ContainerContentsWorkflowRuntimeGroups,\n type ContainerContentsWorkflowRuntimeInfra,\n type ContainerContentsWorkflowRuntimeInput,\n type ContainerContentsWorkflowRuntimeInputGroups,\n type ContainerContentsWorkflowRuntimeSnapshot,\n type ContainerContentsWorkflowRuntimeState,\n type ContainerContentsWorkflowRuntimeUtil,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsStoreWorkflowRuntimeFromSnapshot,\n createContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntimeFromSnapshot,\n} from \"./runtime\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"./syncState\";\nexport {\n createContainerDocumentObjectSyncState,\n syncedContainerDocumentObjectSyncState,\n} from \"./syncState\";\nexport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"./systemSlot\";\nexport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"./tombstones/documentPurge\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,kFAAkF,CAAC;AACzI,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iCAAi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istence/container-contents/documentContainerProjectionPersistence\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"./attribution/documentAttributionRanges\";\nexport { deriveSystemContainerId } from \"./container-state/create/createChild\";\nexport type { ContainerContentsOrganizationHost } from \"./container-state/organizationHost\";\nexport {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n defaultContainerContentsPersistence,\n} from \"./containerPersistence\";\nexport {\n type ContainerDocumentLinkInput,\n type ContainerDocumentQueries,\n type ContainerDocumentSidebarRow,\n type ContainerDocumentTombstone,\n type ContainerItemRow,\n type ContainerItemSort,\n type ContainerItemSortDirection,\n type ContainerItemSortKey,\n createContainerDocumentQueriesFromRuntime,\n} from \"./documentQueries\";\nexport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n type MergeDocumentSummary,\n moveDocumentLink,\n moveLocalDocumentLink,\n removeDocumentLink,\n type SetLinkedContainerIdsForDocument,\n} from \"./documentQueries/documentStructure\";\nexport type { PendingDownloadQueueItem } from \"./documentQueries/pendingDownloads\";\nexport {\n type BlobInfo,\n type BlobInfoAttachmentKind,\n type BlobInfoDocumentReference,\n type BlobInfoInput,\n type BlobInfoList,\n type BlobInfoSort,\n type BlobInfoSortDirection,\n type BlobInfoSortKey,\n listBlobInfo,\n} from \"./info/blobInfo\";\nexport {\n type ContainerInfo,\n type ContainerInfoGrant,\n type ContainerInfoGrantRow,\n type ContainerInfoPathEntry,\n type ContainerInfoRemoteMode,\n type ContainerInfoSecurityDetails,\n type ContainerShareAccessLevel,\n loadContainerInfo,\n} from \"./info/containerInfo\";\nexport {\n type DocumentInfo,\n type DocumentInfoAttachment,\n type DocumentInfoAuthorizingContainerPath,\n type DocumentInfoLocalDetails,\n type DocumentInfoRemoteAttachmentBinding,\n type DocumentInfoRemoteDetails,\n type DocumentInfoRemoteMode,\n loadDocumentInfo,\n} from \"./info/documentInfo\";\nexport {\n type ContainerMetadataPatch,\n hasContainerMetadataDocumentUpdateEvent,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n syncContainerMetadataState,\n} from \"./metadata\";\nexport {\n type ContainerMetadataDocument,\n createInitializedContainerMetadataDocument,\n getDefaultContainerName,\n readContainerMetadataValue,\n writeContainerMetadataValue,\n} from \"./metadata/containerMetadataDocument\";\nexport {\n listPendingWrites,\n type PendingWriteQueueItem,\n type PendingWriteQueueItemStatus,\n type PendingWriteQueueObjectKind,\n type PendingWriteQueueOperation,\n type PendingWriteQueueOperationKind,\n type PendingWriteQueueOperationStatus,\n} from \"./pendingWrites\";\nexport {\n type ContainerContentsProjectionUserKeyResolver,\n createContainerContentsDocumentProjectionUserKeyResolver,\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport type { RecoveryFolder } from \"./recovery/folderRecovery\";\nexport {\n type ContainerContentsRootAdopter,\n type ContainerContentsRootAdoptionInput,\n type ContainerContentsStoreWorkflowRuntime,\n type ContainerContentsWorkflowRuntime,\n type ContainerContentsWorkflowRuntimeAuth,\n type ContainerContentsWorkflowRuntimeCrypto,\n type ContainerContentsWorkflowRuntimeGroups,\n type ContainerContentsWorkflowRuntimeInfra,\n type ContainerContentsWorkflowRuntimeInput,\n type ContainerContentsWorkflowRuntimeInputGroups,\n type ContainerContentsWorkflowRuntimeSnapshot,\n type ContainerContentsWorkflowRuntimeState,\n type ContainerContentsWorkflowRuntimeUtil,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsStoreWorkflowRuntimeFromSnapshot,\n createContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntimeFromSnapshot,\n} from \"./runtime\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"./syncState\";\nexport {\n createContainerDocumentObjectSyncState,\n syncedContainerDocumentObjectSyncState,\n} from \"./syncState\";\nexport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"./systemSlot\";\nexport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"./tombstones/documentPurge\";\n"]}
@@ -0,0 +1,16 @@
1
+ import { KeyingVerificationError } from "../../../../internal/crypto/index.js";
2
+ import { deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationTrashSystemSlot, } from "../../../../internal/validators/containerSystemSlot.js";
3
+ /** All fields come from the verified path, including parents absent from the local tree. */
4
+ export async function assertSystemDestinationTopology(input) {
5
+ if (input.systemSlot === null)
6
+ return;
7
+ const metadataSlot = await deriveOrganizationMetadataContainerSystemSlot(input);
8
+ if (input.rootSystemSlot !== null &&
9
+ input.systemSlot === deriveOrganizationTrashSystemSlot(input.organizationId)) {
10
+ throw new KeyingVerificationError("invalid_shape", "Trash must be a child of the organization's data root");
11
+ }
12
+ if (input.pathLength !== (input.systemSlot === metadataSlot ? 1 : 2)) {
13
+ throw new KeyingVerificationError("invalid_shape", "system destination has the wrong signed topology");
14
+ }
15
+ }
16
+ //# sourceMappingURL=destinationSystemTopology.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"destinationSystemTopology.js","sourceRoot":"","sources":["destinationSystemTopology.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,6CAA6C,EAC7C,iCAAiC,GAClC,MAAM,2CAA2C,CAAC;AAEnD,4FAA4F;AAC5F,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAKrD;IACC,IAAI,KAAK,CAAC,UAAU,KAAK,IAAI;QAAE,OAAO;IACtC,MAAM,YAAY,GAChB,MAAM,6CAA6C,CAAC,KAAK,CAAC,CAAC;IAC7D,IACE,KAAK,CAAC,cAAc,KAAK,IAAI;QAC7B,KAAK,CAAC,UAAU,KAAK,iCAAiC,CAAC,KAAK,CAAC,cAAc,CAAC,EAC5E,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,uDAAuD,CACxD,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,UAAU,KAAK,CAAC,KAAK,CAAC,UAAU,KAAK,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACrE,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,kDAAkD,CACnD,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationTrashSystemSlot,\n} from \"@tearleads/validators/containerSystemSlot\";\n\n/** All fields come from the verified path, including parents absent from the local tree. */\nexport async function assertSystemDestinationTopology(input: {\n organizationId: string;\n pathLength: number;\n rootSystemSlot: string | null;\n systemSlot: string | null;\n}) {\n if (input.systemSlot === null) return;\n const metadataSlot =\n await deriveOrganizationMetadataContainerSystemSlot(input);\n if (\n input.rootSystemSlot !== null &&\n input.systemSlot === deriveOrganizationTrashSystemSlot(input.organizationId)\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Trash must be a child of the organization's data root\",\n );\n }\n if (input.pathLength !== (input.systemSlot === metadataSlot ? 1 : 2)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"system destination has the wrong signed topology\",\n );\n }\n}\n"]}
@@ -1,11 +1,11 @@
1
1
  import { KeyingVerificationError, } from "../../../../internal/crypto/index.js";
2
- import { deriveOrganizationMetadataContainerSystemSlot } from "../../../../internal/validators/containerSystemSlot.js";
3
2
  import { verifiedContainerCreateManifest, verifyContainerDestinationProjection, verifyContainerWriterProjection, } from "../../../../data/keyingProjectionVerification/index.js";
4
3
  import { listingRepeatsHeldOrdinaryBinding, } from "../../../../data/persistence/container-contents/containerBinding.js";
5
4
  import { openPrincipalPolicyBundleReader } from "../../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
6
5
  import { isKeyingVerificationError, reportKeyingVerificationErrorInCauseChain, runWithSecurityIncidentReporting, } from "../../../../data/shared/securityIncidents.js";
7
6
  import { cachedDestinationRole, rememberDestinationRole, } from "./destinationRoleCache.js";
8
7
  import { resolveWithMetadataRootReload } from "./destinationRootReload.js";
8
+ import { assertSystemDestinationTopology } from "./destinationSystemTopology.js";
9
9
  import { assertPermittedDestinationBinding } from "./replacementBinding.js";
10
10
  async function destinationRoleFromPath(input) {
11
11
  const { listed, path } = input;
@@ -15,13 +15,15 @@ async function destinationRoleFromPath(input) {
15
15
  head.state.organizationId !== listed.organizationId) {
16
16
  throw new KeyingVerificationError("object_mismatch", "container destination manifest has the wrong identity");
17
17
  }
18
- const metadataSlot = await deriveOrganizationMetadataContainerSystemSlot({
18
+ const root = path[0];
19
+ if (!root)
20
+ throw new Error("Destination root is unavailable");
21
+ await assertSystemDestinationTopology({
19
22
  organizationId: listed.organizationId,
23
+ systemSlot: head.state.systemSlot,
24
+ pathLength: path.length,
25
+ rootSystemSlot: root.state.systemSlot,
20
26
  });
21
- if (head.state.systemSlot !== null &&
22
- path.length !== (head.state.systemSlot === metadataSlot ? 1 : 2)) {
23
- throw new KeyingVerificationError("invalid_shape", "system destination has the wrong signed topology");
24
- }
25
27
  // The head may be a later grant signed by any admin; only the epoch-1
26
28
  // create names the creator, and roots are always created by the org owner.
27
29
  const created = verifiedContainerCreateManifest({
@@ -29,9 +31,6 @@ async function destinationRoleFromPath(input) {
29
31
  label: "Container destination",
30
32
  verifiedByHash: input.verifiedByHash,
31
33
  });
32
- const root = path[0];
33
- if (!root)
34
- throw new Error("Destination root is unavailable");
35
34
  const rootCreated = verifiedContainerCreateManifest({
36
35
  head: root,
37
36
  label: "Destination root",
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedDestination.js","sourceRoot":"","sources":["verifi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,CAAC,kBAAkB,CAAC,eAAe,EAAE,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,IAAI,GAAG,qBAAqB,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IACrE,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAC;IACxB,IAAI,CAAC;QACH,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;YAC3B,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,2DAA2D,CAC5D,CAAC;QACJ,CAAC;QACD,8BAA8B,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,QAAQ,GAAG,MAAM,yCAAyC,CAC9D,KAAK,EACL,OAAO,CAAC,IAAI,CAAC,sBAAsB,EACnC;YACE,QAAQ,EAAE,SAAS,CAAC,EAAE;YACtB,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,0BAA0B;YACrC,cAAc,EAAE,SAAS,CAAC,cAAc;SACzC,CACF,CAAC;QACF,IAAI,CAAC,QAAQ;YAAE,MAAM,KAAK,CAAC;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport {\n verifiedContainerCreateManifest,\n verifyContainerDestinationProjection,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport {\n type HeldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../../data/persistence/container-contents/containerBinding\";\nimport { openPrincipalPolicyBundleReader } from \"../../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n runWithSecurityIncidentReporting,\n} from \"../../../../data/shared/securityIncidents\";\nimport type {\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport type { PrefetchedDestinationProjection } from \"./destinationPrefetch\";\nimport {\n cachedDestinationRole,\n type DestinationRole,\n rememberDestinationRole,\n} from \"./destinationRoleCache\";\nimport { resolveWithMetadataRootReload } from \"./destinationRootReload\";\nimport { assertPermittedDestinationBinding } from \"./replacementBinding\";\n\n/** The identity a role is verified and cached under. */\ntype DestinationIdentity = Pick<RemoteContainer, \"id\" | \"organizationId\">;\n\nasync function destinationRoleFromPath(input: {\n listed: DestinationIdentity;\n path: readonly VerifiedContainerAccessManifest[];\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): Promise<{ role: DestinationRole; parentId: string | null }> {\n const { listed, path } = input;\n const head = path.at(-1);\n if (\n !head ||\n head.state.containerId !== listed.id ||\n head.state.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination manifest has the wrong identity\",\n );\n }\n const metadataSlot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: listed.organizationId,\n });\n if (\n head.state.systemSlot !== null &&\n path.length !== (head.state.systemSlot === metadataSlot ? 1 : 2)\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"system destination has the wrong signed topology\",\n );\n }\n // The head may be a later grant signed by any admin; only the epoch-1\n // create names the creator, and roots are always created by the org owner.\n const created = verifiedContainerCreateManifest({\n head,\n label: \"Container destination\",\n verifiedByHash: input.verifiedByHash,\n });\n const root = path[0];\n if (!root) throw new Error(\"Destination root is unavailable\");\n const rootCreated = verifiedContainerCreateManifest({\n head: root,\n label: \"Destination root\",\n verifiedByHash: input.verifiedByHash,\n });\n return {\n parentId: head.state.parentContainerId,\n role: {\n createSignerUserId: created.event.event.signerUserId,\n rootContainerId: rootCreated.state.containerId,\n rootCreateManifestHash: rootCreated.manifestHash,\n rootMetadataDocumentId: rootCreated.state.metadataDocumentId,\n metadataDocumentId: head.state.metadataDocumentId,\n ...(head.state.parentContainerId === null ||\n head.state.systemSlot !== null\n ? { parentId: head.state.parentContainerId }\n : {}),\n systemSlot: head.state.systemSlot,\n },\n };\n}\n\n/**\n * The session's root id arrives in an unsigned login response, so the root it\n * names must prove it belongs to this user: every acknowledged organization was\n * created by the session user, whose device signed the root's `container.create`.\n * A verified root created by anyone else is a substitution, never the merge\n * target for pre-login local content, whatever grants it carries. The check\n * runs on cache reuse too, since the cache is not scoped to the session user.\n */\nfunction assertRootCreatedBySessionUser(\n role: DestinationRole,\n runtime: RemoteContainerHydrationState[\"runtime\"],\n): void {\n if (role.systemSlot !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"acknowledged session root cannot be a system container\",\n );\n }\n if (role.createSignerUserId !== runtime.auth.userId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"acknowledged session root was not created by the session user\",\n );\n }\n}\n\nfunction assertAcknowledgedRootSigner(input: {\n listed: DestinationIdentity;\n role: DestinationRole;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): void {\n const { listed, role, runtime } = input;\n if (role.parentId !== null || listed.id !== runtime.auth.rootContainerId) {\n return;\n }\n assertRootCreatedBySessionUser(role, runtime);\n}\n\n/**\n * Authenticate destination roles before admitting a binding or advancing any\n * placement pin. Shared rehomes additionally require signed replacement evidence.\n */\nfunction assertDestinationProjectionIdentity(\n projection: { readonly containerId: string; readonly organizationId: string },\n listed: DestinationIdentity,\n): void {\n if (\n projection.containerId !== listed.id ||\n projection.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination projection has the wrong identity\",\n );\n }\n}\n\nasync function verifyDestinationRole(input: {\n heldBinding: HeldContainerBinding | null;\n prefetched: PrefetchedDestinationProjection | undefined;\n verifyCurrentPlacement: boolean;\n onVerifiedCheckpoint:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n isCurrent?: (() => boolean) | undefined;\n listed: DestinationIdentity;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): Promise<{ role: DestinationRole; parentId: string | null } | null> {\n const { isCurrent, listed, runtime } = input;\n const projection = input.prefetched\n ? input.prefetched.projection\n : await runtime.apiClient.getContainerWriterProjection(listed.id);\n if (!projection || isCurrent?.() === false) return null;\n assertDestinationProjectionIdentity(projection, listed);\n const verificationInput = {\n execSql: runtime.infra.execSql,\n openPrincipalPolicyBundleReader,\n projection,\n resolveUserKey: runtime.resolveTrustedUserIdentity,\n stillCurrent: isCurrent,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer(),\n };\n const { path, verifiedByHash } =\n await verifyContainerDestinationProjection(verificationInput);\n if (isCurrent?.() === false) return null;\n const destination = await destinationRoleFromPath({\n listed,\n path,\n verifiedByHash,\n });\n const { role } = destination;\n // Refuse a rebinding before group checks or placement pins run for it.\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (role.parentId === null && role.systemSlot !== null) {\n const head = path.at(-1);\n if (!head) throw new Error(\"Metadata root manifest is unavailable\");\n await runtime.organizations.verifyGroupMetadataAuthority({\n runtime,\n organizationId: listed.organizationId,\n organizationReference: projection.policyEvidence.organization?.head,\n state: head.state,\n stillCurrent: isCurrent ?? (() => true),\n });\n }\n if (isCurrent?.() === false) return null;\n if (input.verifyCurrentPlacement) {\n // Check the immutable role before allowing current placement to advance pins.\n assertAcknowledgedRootSigner({ listed, role, runtime });\n const currentPath = await verifyContainerWriterProjection({\n ...verificationInput,\n stillCurrent: isCurrent,\n });\n const currentHead = currentPath.at(-1);\n if (!currentHead)\n throw new Error(\"Recovery placement manifest is unavailable\");\n input.onVerifiedCheckpoint?.(currentHead.checkpoint);\n }\n if (isCurrent?.() === false) return null;\n return destination;\n}\n\ntype VerifyRemoteContainerDestinationInput = {\n heldBinding: HeldContainerBinding | null;\n /** The held folder was re-homed away from the listed organization. */\n supersededListing?: boolean | undefined;\n /** Fetched ahead by page hydration; ignored when placement is refreshed. */\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n refresh?: boolean;\n onVerifiedCheckpoint?:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n isCurrent?: (() => boolean) | undefined;\n};\n\n/** A cached immutable role, or a freshly verified one with its signed parent. */\nasync function resolveDestinationRole(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<{\n freshlyVerified: boolean;\n parentId: string | null | undefined;\n role: DestinationRole;\n} | null> {\n const { remoteContainer: listed, isCurrent } = input;\n const runtime = input.state.runtime;\n const cached = input.refresh\n ? undefined\n : cachedDestinationRole(runtime.infra.execSql, listed);\n // Ordinary parent edges are not immutable. A refresh authenticates current\n // placement; a forged root hint must also be corrected from a signed path.\n if (cached && !(cached.parentId === undefined && listed.parentId === null)) {\n return { freshlyVerified: false, parentId: cached.parentId, role: cached };\n }\n const verified = await verifyDestinationRole({\n heldBinding: input.heldBinding,\n prefetched: input.refresh ? undefined : input.prefetchedProjection,\n isCurrent,\n listed,\n runtime,\n verifyCurrentPlacement: input.refresh === true,\n onVerifiedCheckpoint: input.onVerifiedCheckpoint,\n });\n if (!verified) return null;\n return {\n freshlyVerified: true,\n parentId:\n input.refresh || listed.parentId === null\n ? verified.parentId\n : verified.role.parentId,\n role: verified.role,\n };\n}\n\n/**\n * A held ordinary binding was verified (or signed by this device) when it was\n * stored; a listing that repeats it needs no second proof. A listing the\n * caller already found superseded is refused.\n */\nfunction heldOrdinaryBindingStands(\n input: VerifyRemoteContainerDestinationInput,\n): boolean {\n if (input.supersededListing) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container was re-homed away from the listed organization\",\n );\n }\n return (\n !input.refresh &&\n listingRepeatsHeldOrdinaryBinding(input.heldBinding, input.remoteContainer)\n );\n}\n\n/**\n * Listing hints never establish a metadata target or a system/root role, and a\n * held folder keeps its organization and metadata target unless its own user\n * re-created it or its pinned founder authorized a verified replacement.\n * A conflicting proof is refused before placement pins\n * advance or its role is cached.\n */\nexport async function verifyRemoteContainerDestination(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<RemoteContainer | null> {\n const { remoteContainer: listed, state, isCurrent } = input;\n const runtime = state.runtime;\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: listed.id,\n objectKind: \"container\",\n operation: \"container.destination.verify\",\n organizationId: listed.organizationId,\n },\n async () => {\n if (heldOrdinaryBindingStands(input)) {\n return { ...listed, systemSlot: null };\n }\n if (input.refresh)\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n // A metadata root read before a reserved-group commit is reloaded once.\n const resolved = await resolveWithMetadataRootReload(\n input,\n resolveDestinationRole,\n () => runtime.apiClient.evictContainerWriterProjection(listed.id),\n runtime.organizations.withMetadataRootReload,\n ).catch((error: unknown) => {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error))\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n throw error;\n });\n if (!resolved || isCurrent?.() === false) return null;\n const { role, parentId } = resolved;\n // Fresh verification checked this binding before any placement pins.\n // A cached role still needs the held binding and replacement proof checked.\n if (!resolved.freshlyVerified)\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (resolved.freshlyVerified)\n rememberDestinationRole(runtime.infra.execSql, listed, role);\n assertAcknowledgedRootSigner({ listed, role, runtime });\n return {\n ...listed,\n metadataDocumentId: role.metadataDocumentId,\n parentId: parentId === undefined ? listed.parentId : parentId,\n systemSlot: role.systemSlot,\n };\n },\n );\n}\n\n/** The root the unsigned login answer named, in the expected organization. */\nexport function isSessionRootState(\n remoteRootState: ContainerState,\n state: RemoteContainerHydrationState,\n): boolean {\n const { container } = remoteRootState;\n const { auth } = state.runtime;\n return (\n container.parentId === null &&\n !container.systemSlot &&\n container.id === auth.rootContainerId &&\n container.organizationId === auth.organizationId\n );\n}\n\n/**\n * Whether the session root may absorb the pre-login local roots. The unsigned\n * login answer only names the root; the merge target must also be the verified\n * root whose epoch-1 `container.create` the session user signed. A row persisted\n * earlier as an ordinary shared container (another user's root this device once\n * hydrated) never passed that check for this session, so the creator is checked\n * here, at the reconciliation boundary itself, before any local content is\n * re-parented. The role comes only from the cache remote hydration fills when\n * it verifies the destination: this gate never fetches, so a local refresh stays\n * independent of the network. Without a cached role the merge is left pending\n * (no incident) until hydration verifies the root and reconciles from the\n * cache. A different creator is a `signer_mismatch` incident and never a merge;\n * the refusal is the \"no merge\" outcome, so the refresh that carried it\n * completes with the local content left in place.\n */\nexport async function isVerifiedLocalRootReconciliationTarget(input: {\n remoteRootState: ContainerState;\n state: RemoteContainerHydrationState;\n}): Promise<boolean> {\n const { remoteRootState, state } = input;\n const { container } = remoteRootState;\n const runtime = state.runtime;\n if (!isSessionRootState(remoteRootState, state)) return false;\n const role = cachedDestinationRole(runtime.infra.execSql, container);\n if (!role) return false;\n try {\n if (role.parentId !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"session root reconciliation target is not a verified root\",\n );\n }\n assertRootCreatedBySessionUser(role, runtime);\n return true;\n } catch (error) {\n const reported = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: container.id,\n objectKind: \"container\",\n operation: \"container.root.reconcile\",\n organizationId: container.organizationId,\n },\n );\n if (!reported) throw error;\n return false;\n }\n}\n"]}
1
+ {"version":3,"file":"verifiedDestination.js","sourceRoot":"","sources":["verifiedDestination.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EACpC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAEL,iCAAiC,GAClC,MAA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QACJ,CAAC;QACD,8BAA8B,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,QAAQ,GAAG,MAAM,yCAAyC,CAC9D,KAAK,EACL,OAAO,CAAC,IAAI,CAAC,sBAAsB,EACnC;YACE,QAAQ,EAAE,SAAS,CAAC,EAAE;YACtB,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,0BAA0B;YACrC,cAAc,EAAE,SAAS,CAAC,cAAc;SACzC,CACF,CAAC;QACF,IAAI,CAAC,QAAQ;YAAE,MAAM,KAAK,CAAC;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport {\n verifiedContainerCreateManifest,\n verifyContainerDestinationProjection,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport {\n type HeldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../../data/persistence/container-contents/containerBinding\";\nimport { openPrincipalPolicyBundleReader } from \"../../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n runWithSecurityIncidentReporting,\n} from \"../../../../data/shared/securityIncidents\";\nimport type {\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport type { PrefetchedDestinationProjection } from \"./destinationPrefetch\";\nimport {\n cachedDestinationRole,\n type DestinationRole,\n rememberDestinationRole,\n} from \"./destinationRoleCache\";\nimport { resolveWithMetadataRootReload } from \"./destinationRootReload\";\nimport { assertSystemDestinationTopology } from \"./destinationSystemTopology\";\nimport { assertPermittedDestinationBinding } from \"./replacementBinding\";\n\n/** The identity a role is verified and cached under. */\ntype DestinationIdentity = Pick<RemoteContainer, \"id\" | \"organizationId\">;\n\nasync function destinationRoleFromPath(input: {\n listed: DestinationIdentity;\n path: readonly VerifiedContainerAccessManifest[];\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): Promise<{ role: DestinationRole; parentId: string | null }> {\n const { listed, path } = input;\n const head = path.at(-1);\n if (\n !head ||\n head.state.containerId !== listed.id ||\n head.state.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination manifest has the wrong identity\",\n );\n }\n const root = path[0];\n if (!root) throw new Error(\"Destination root is unavailable\");\n await assertSystemDestinationTopology({\n organizationId: listed.organizationId,\n systemSlot: head.state.systemSlot,\n pathLength: path.length,\n rootSystemSlot: root.state.systemSlot,\n });\n // The head may be a later grant signed by any admin; only the epoch-1\n // create names the creator, and roots are always created by the org owner.\n const created = verifiedContainerCreateManifest({\n head,\n label: \"Container destination\",\n verifiedByHash: input.verifiedByHash,\n });\n const rootCreated = verifiedContainerCreateManifest({\n head: root,\n label: \"Destination root\",\n verifiedByHash: input.verifiedByHash,\n });\n return {\n parentId: head.state.parentContainerId,\n role: {\n createSignerUserId: created.event.event.signerUserId,\n rootContainerId: rootCreated.state.containerId,\n rootCreateManifestHash: rootCreated.manifestHash,\n rootMetadataDocumentId: rootCreated.state.metadataDocumentId,\n metadataDocumentId: head.state.metadataDocumentId,\n ...(head.state.parentContainerId === null ||\n head.state.systemSlot !== null\n ? { parentId: head.state.parentContainerId }\n : {}),\n systemSlot: head.state.systemSlot,\n },\n };\n}\n\n/**\n * The session's root id arrives in an unsigned login response, so the root it\n * names must prove it belongs to this user: every acknowledged organization was\n * created by the session user, whose device signed the root's `container.create`.\n * A verified root created by anyone else is a substitution, never the merge\n * target for pre-login local content, whatever grants it carries. The check\n * runs on cache reuse too, since the cache is not scoped to the session user.\n */\nfunction assertRootCreatedBySessionUser(\n role: DestinationRole,\n runtime: RemoteContainerHydrationState[\"runtime\"],\n): void {\n if (role.systemSlot !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"acknowledged session root cannot be a system container\",\n );\n }\n if (role.createSignerUserId !== runtime.auth.userId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"acknowledged session root was not created by the session user\",\n );\n }\n}\n\nfunction assertAcknowledgedRootSigner(input: {\n listed: DestinationIdentity;\n role: DestinationRole;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): void {\n const { listed, role, runtime } = input;\n if (role.parentId !== null || listed.id !== runtime.auth.rootContainerId) {\n return;\n }\n assertRootCreatedBySessionUser(role, runtime);\n}\n\n/**\n * Authenticate destination roles before admitting a binding or advancing any\n * placement pin. Shared rehomes additionally require signed replacement evidence.\n */\nfunction assertDestinationProjectionIdentity(\n projection: { readonly containerId: string; readonly organizationId: string },\n listed: DestinationIdentity,\n): void {\n if (\n projection.containerId !== listed.id ||\n projection.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination projection has the wrong identity\",\n );\n }\n}\n\nasync function verifyDestinationRole(input: {\n heldBinding: HeldContainerBinding | null;\n prefetched: PrefetchedDestinationProjection | undefined;\n verifyCurrentPlacement: boolean;\n onVerifiedCheckpoint:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n isCurrent?: (() => boolean) | undefined;\n listed: DestinationIdentity;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): Promise<{ role: DestinationRole; parentId: string | null } | null> {\n const { isCurrent, listed, runtime } = input;\n const projection = input.prefetched\n ? input.prefetched.projection\n : await runtime.apiClient.getContainerWriterProjection(listed.id);\n if (!projection || isCurrent?.() === false) return null;\n assertDestinationProjectionIdentity(projection, listed);\n const verificationInput = {\n execSql: runtime.infra.execSql,\n openPrincipalPolicyBundleReader,\n projection,\n resolveUserKey: runtime.resolveTrustedUserIdentity,\n stillCurrent: isCurrent,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer(),\n };\n const { path, verifiedByHash } =\n await verifyContainerDestinationProjection(verificationInput);\n if (isCurrent?.() === false) return null;\n const destination = await destinationRoleFromPath({\n listed,\n path,\n verifiedByHash,\n });\n const { role } = destination;\n // Refuse a rebinding before group checks or placement pins run for it.\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (role.parentId === null && role.systemSlot !== null) {\n const head = path.at(-1);\n if (!head) throw new Error(\"Metadata root manifest is unavailable\");\n await runtime.organizations.verifyGroupMetadataAuthority({\n runtime,\n organizationId: listed.organizationId,\n organizationReference: projection.policyEvidence.organization?.head,\n state: head.state,\n stillCurrent: isCurrent ?? (() => true),\n });\n }\n if (isCurrent?.() === false) return null;\n if (input.verifyCurrentPlacement) {\n // Check the immutable role before allowing current placement to advance pins.\n assertAcknowledgedRootSigner({ listed, role, runtime });\n const currentPath = await verifyContainerWriterProjection({\n ...verificationInput,\n stillCurrent: isCurrent,\n });\n const currentHead = currentPath.at(-1);\n if (!currentHead)\n throw new Error(\"Recovery placement manifest is unavailable\");\n input.onVerifiedCheckpoint?.(currentHead.checkpoint);\n }\n if (isCurrent?.() === false) return null;\n return destination;\n}\n\ntype VerifyRemoteContainerDestinationInput = {\n heldBinding: HeldContainerBinding | null;\n /** The held folder was re-homed away from the listed organization. */\n supersededListing?: boolean | undefined;\n /** Fetched ahead by page hydration; ignored when placement is refreshed. */\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n refresh?: boolean;\n onVerifiedCheckpoint?:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n isCurrent?: (() => boolean) | undefined;\n};\n\n/** A cached immutable role, or a freshly verified one with its signed parent. */\nasync function resolveDestinationRole(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<{\n freshlyVerified: boolean;\n parentId: string | null | undefined;\n role: DestinationRole;\n} | null> {\n const { remoteContainer: listed, isCurrent } = input;\n const runtime = input.state.runtime;\n const cached = input.refresh\n ? undefined\n : cachedDestinationRole(runtime.infra.execSql, listed);\n // Ordinary parent edges are not immutable. A refresh authenticates current\n // placement; a forged root hint must also be corrected from a signed path.\n if (cached && !(cached.parentId === undefined && listed.parentId === null)) {\n return { freshlyVerified: false, parentId: cached.parentId, role: cached };\n }\n const verified = await verifyDestinationRole({\n heldBinding: input.heldBinding,\n prefetched: input.refresh ? undefined : input.prefetchedProjection,\n isCurrent,\n listed,\n runtime,\n verifyCurrentPlacement: input.refresh === true,\n onVerifiedCheckpoint: input.onVerifiedCheckpoint,\n });\n if (!verified) return null;\n return {\n freshlyVerified: true,\n parentId:\n input.refresh || listed.parentId === null\n ? verified.parentId\n : verified.role.parentId,\n role: verified.role,\n };\n}\n\n/**\n * A held ordinary binding was verified (or signed by this device) when it was\n * stored; a listing that repeats it needs no second proof. A listing the\n * caller already found superseded is refused.\n */\nfunction heldOrdinaryBindingStands(\n input: VerifyRemoteContainerDestinationInput,\n): boolean {\n if (input.supersededListing) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container was re-homed away from the listed organization\",\n );\n }\n return (\n !input.refresh &&\n listingRepeatsHeldOrdinaryBinding(input.heldBinding, input.remoteContainer)\n );\n}\n\n/**\n * Listing hints never establish a metadata target or a system/root role, and a\n * held folder keeps its organization and metadata target unless its own user\n * re-created it or its pinned founder authorized a verified replacement.\n * A conflicting proof is refused before placement pins\n * advance or its role is cached.\n */\nexport async function verifyRemoteContainerDestination(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<RemoteContainer | null> {\n const { remoteContainer: listed, state, isCurrent } = input;\n const runtime = state.runtime;\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: listed.id,\n objectKind: \"container\",\n operation: \"container.destination.verify\",\n organizationId: listed.organizationId,\n },\n async () => {\n if (heldOrdinaryBindingStands(input)) {\n return { ...listed, systemSlot: null };\n }\n if (input.refresh)\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n // A metadata root read before a reserved-group commit is reloaded once.\n const resolved = await resolveWithMetadataRootReload(\n input,\n resolveDestinationRole,\n () => runtime.apiClient.evictContainerWriterProjection(listed.id),\n runtime.organizations.withMetadataRootReload,\n ).catch((error: unknown) => {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error))\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n throw error;\n });\n if (!resolved || isCurrent?.() === false) return null;\n const { role, parentId } = resolved;\n // Fresh verification checked this binding before any placement pins.\n // A cached role still needs the held binding and replacement proof checked.\n if (!resolved.freshlyVerified)\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (resolved.freshlyVerified)\n rememberDestinationRole(runtime.infra.execSql, listed, role);\n assertAcknowledgedRootSigner({ listed, role, runtime });\n return {\n ...listed,\n metadataDocumentId: role.metadataDocumentId,\n parentId: parentId === undefined ? listed.parentId : parentId,\n systemSlot: role.systemSlot,\n };\n },\n );\n}\n\n/** The root the unsigned login answer named, in the expected organization. */\nexport function isSessionRootState(\n remoteRootState: ContainerState,\n state: RemoteContainerHydrationState,\n): boolean {\n const { container } = remoteRootState;\n const { auth } = state.runtime;\n return (\n container.parentId === null &&\n !container.systemSlot &&\n container.id === auth.rootContainerId &&\n container.organizationId === auth.organizationId\n );\n}\n\n/**\n * Whether the session root may absorb the pre-login local roots. The unsigned\n * login answer only names the root; the merge target must also be the verified\n * root whose epoch-1 `container.create` the session user signed. A row persisted\n * earlier as an ordinary shared container (another user's root this device once\n * hydrated) never passed that check for this session, so the creator is checked\n * here, at the reconciliation boundary itself, before any local content is\n * re-parented. The role comes only from the cache remote hydration fills when\n * it verifies the destination: this gate never fetches, so a local refresh stays\n * independent of the network. Without a cached role the merge is left pending\n * (no incident) until hydration verifies the root and reconciles from the\n * cache. A different creator is a `signer_mismatch` incident and never a merge;\n * the refusal is the \"no merge\" outcome, so the refresh that carried it\n * completes with the local content left in place.\n */\nexport async function isVerifiedLocalRootReconciliationTarget(input: {\n remoteRootState: ContainerState;\n state: RemoteContainerHydrationState;\n}): Promise<boolean> {\n const { remoteRootState, state } = input;\n const { container } = remoteRootState;\n const runtime = state.runtime;\n if (!isSessionRootState(remoteRootState, state)) return false;\n const role = cachedDestinationRole(runtime.infra.execSql, container);\n if (!role) return false;\n try {\n if (role.parentId !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"session root reconciliation target is not a verified root\",\n );\n }\n assertRootCreatedBySessionUser(role, runtime);\n return true;\n } catch (error) {\n const reported = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: container.id,\n objectKind: \"container\",\n operation: \"container.root.reconcile\",\n organizationId: container.organizationId,\n },\n );\n if (!reported) throw error;\n return false;\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { type ExecSql, type ExecSqlClientLike } from "../../data/sqlite/sqlSchema.js";
2
+ export declare function deriveRegistrationOrganizationId(rootContainerId: string): Promise<string>;
2
3
  interface RootContainerBootstrapResult {
3
4
  containerId: string;
4
5
  created: boolean;
@@ -1,5 +1,14 @@
1
+ import { deriveStableUuidV4Shaped } from "../../data/keying/stableUuid.js";
1
2
  import { ensureContainerTables, loadContainers, saveContainer, } from "../../data/persistence/container-contents/containerPersistence.js";
2
3
  import { createExecSql, runSerializedSqlMutation, } from "../../data/sqlite/sqlSchema.js";
4
+ // A device-first root can receive deleted items before its organization is registered.
5
+ const ORGANIZATION_ID_NAMESPACE = new Uint8Array([
6
+ 0x62, 0xb5, 0x73, 0xbf, 0x47, 0x2a, 0x4f, 0x93, 0x87, 0xcf, 0x07, 0x8e, 0x25,
7
+ 0xa1, 0xd2, 0x68,
8
+ ]);
9
+ export function deriveRegistrationOrganizationId(rootContainerId) {
10
+ return deriveStableUuidV4Shaped(ORGANIZATION_ID_NAMESPACE, rootContainerId);
11
+ }
3
12
  async function bootstrapRootContainerFromExecSql(execSql) {
4
13
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
5
14
  await ensureContainerTables(lockedExecSql);
@@ -1 +1 @@
1
- {"version":3,"file":"bootstrapRootContainer.js","sourceRoot":"","sources":["bootstrapRootContainer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,aAAa,GACd,MAAM,gEAAgE,CAAC;AACxE,OAAO,EACL,aAAa,EAGb,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AAOrC,KAAK,UAAU,iCAAiC,CAC9C,OAAgB;IAEhB,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAC/D,MAAM,qBAAqB,CAAC,aAAa,CAAC,CAAC;QAC3C,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,aAAa,CAAC,CAAC;QACvD,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAC1B,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,QAAQ,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,UAAU,CACpE,CAAC;QAEF,IAAI,IAAI,EAAE,CAAC;YACT,OAAO;gBACL,WAAW,EAAE,IAAI,CAAC,EAAE;gBACpB,OAAO,EAAE,KAAK;aACf,CAAC;QACJ,CAAC;QAED,MAAM,WAAW,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;QACxC,MAAM,aAAa,CAAC,aAAa,EAAE;YACjC,EAAE,EAAE,WAAW;YACf,oBAAoB,EAAE,OAAO;YAC7B,cAAc,EAAE,EAAE;YAClB,QAAQ,EAAE,IAAI;YACd,kBAAkB,EAAE,IAAI;YACxB,IAAI,EAAE,GAAG;YACT,IAAI,EAAE,IAAI;SACX,CAAC,CAAC;QAEH,OAAO;YACL,WAAW;YACX,OAAO,EAAE,IAAI;SACd,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAAkC;IAElC,OAAO,iCAAiC,CACtC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,aAAa,CAAC,KAAK,CAAC,CAC3D,CAAC;AACJ,CAAC","sourcesContent":["import {\n ensureContainerTables,\n loadContainers,\n saveContainer,\n} from \"../../data/persistence/container-contents/containerPersistence\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\n\ninterface RootContainerBootstrapResult {\n containerId: string;\n created: boolean;\n}\n\nasync function bootstrapRootContainerFromExecSql(\n execSql: ExecSql,\n): Promise<RootContainerBootstrapResult> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureContainerTables(lockedExecSql);\n const containers = await loadContainers(lockedExecSql);\n const root = containers.find(\n (container) => container.parentId === null && !container.systemSlot,\n );\n\n if (root) {\n return {\n containerId: root.id,\n created: false,\n };\n }\n\n const containerId = crypto.randomUUID();\n await saveContainer(lockedExecSql, {\n id: containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: \"\",\n parentId: null,\n metadataDocumentId: null,\n name: \"/\",\n icon: null,\n });\n\n return {\n containerId,\n created: true,\n };\n });\n}\n\nexport async function bootstrapRootContainer(\n input: ExecSql | ExecSqlClientLike,\n): Promise<RootContainerBootstrapResult> {\n return bootstrapRootContainerFromExecSql(\n typeof input === \"function\" ? input : createExecSql(input),\n );\n}\n"]}
1
+ {"version":3,"file":"bootstrapRootContainer.js","sourceRoot":"","sources":["bootstrapRootContainer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,aAAa,GACd,MAAM,gEAAgE,CAAC;AACxE,OAAO,EACL,aAAa,EAGb,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AAErC,uFAAuF;AACvF,MAAM,yBAAyB,GAAG,IAAI,UAAU,CAAC;IAC/C,IAAI,EAAE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OAAO,iCAAiC,CACtC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,aAAa,CAAC,KAAK,CAAC,CAC3D,CAAC;AACJ,CAAC","sourcesContent":["import { deriveStableUuidV4Shaped } from \"../../data/keying/stableUuid\";\nimport {\n ensureContainerTables,\n loadContainers,\n saveContainer,\n} from \"../../data/persistence/container-contents/containerPersistence\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\n\n// A device-first root can receive deleted items before its organization is registered.\nconst ORGANIZATION_ID_NAMESPACE = new Uint8Array([\n 0x62, 0xb5, 0x73, 0xbf, 0x47, 0x2a, 0x4f, 0x93, 0x87, 0xcf, 0x07, 0x8e, 0x25,\n 0xa1, 0xd2, 0x68,\n]);\n\nexport function deriveRegistrationOrganizationId(\n rootContainerId: string,\n): Promise<string> {\n return deriveStableUuidV4Shaped(ORGANIZATION_ID_NAMESPACE, rootContainerId);\n}\n\ninterface RootContainerBootstrapResult {\n containerId: string;\n created: boolean;\n}\n\nasync function bootstrapRootContainerFromExecSql(\n execSql: ExecSql,\n): Promise<RootContainerBootstrapResult> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureContainerTables(lockedExecSql);\n const containers = await loadContainers(lockedExecSql);\n const root = containers.find(\n (container) => container.parentId === null && !container.systemSlot,\n );\n\n if (root) {\n return {\n containerId: root.id,\n created: false,\n };\n }\n\n const containerId = crypto.randomUUID();\n await saveContainer(lockedExecSql, {\n id: containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: \"\",\n parentId: null,\n metadataDocumentId: null,\n name: \"/\",\n icon: null,\n });\n\n return {\n containerId,\n created: true,\n };\n });\n}\n\nexport async function bootstrapRootContainer(\n input: ExecSql | ExecSqlClientLike,\n): Promise<RootContainerBootstrapResult> {\n return bootstrapRootContainerFromExecSql(\n typeof input === \"function\" ? input : createExecSql(input),\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  export { buildInitialOrganizationPolicyRequest } from "../../data/principals/organizationPolicyRequest.js";
2
- export { bootstrapRootContainer } from "./bootstrapRootContainer.js";
2
+ export { bootstrapRootContainer, deriveRegistrationOrganizationId, } from "./bootstrapRootContainer.js";
3
3
  export { type CreateOrganizationApi, type CreateOrganizationInput, createOrganization, removeNativeSubscriptionRestoreProvisioningAttempt, } from "./organizationCreation/createOrganization.js";
4
4
  export { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, } from "./organizationCreation/organizationProvisioningAttempt.js";
5
5
  export { verifyOrganizationReplacementResponse } from "./organizationCreation/organizationReplacementVerification.js";
@@ -1,5 +1,5 @@
1
1
  export { buildInitialOrganizationPolicyRequest } from "../../data/principals/organizationPolicyRequest.js";
2
- export { bootstrapRootContainer } from "./bootstrapRootContainer.js";
2
+ export { bootstrapRootContainer, deriveRegistrationOrganizationId, } from "./bootstrapRootContainer.js";
3
3
  export { createOrganization, removeNativeSubscriptionRestoreProvisioningAttempt, } from "./organizationCreation/createOrganization.js";
4
4
  export { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, } from "./organizationCreation/organizationProvisioningAttempt.js";
5
5
  export { verifyOrganizationReplacementResponse } from "./organizationCreation/organizationReplacementVerification.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAGL,kBAAkB,EAClB,kDAAkD,GACnD,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,qCAAqC,EAAE,MAAM,4DAA4D,CAAC;AAEnH,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAGL,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,4CAA4C,EAAE,MAAM,0CAA0C,CAAC;AACxG,OAAO,EACL,kCAAkC,GAEnC,MAAM,yBAAyB,CAAC","sourcesContent":["export { buildInitialOrganizationPolicyRequest } from \"../../data/principals/organizationPolicyRequest\";\nexport { bootstrapRootContainer } from \"./bootstrapRootContainer\";\nexport {\n type CreateOrganizationApi,\n type CreateOrganizationInput,\n createOrganization,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationCreation/createOrganization\";\nexport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"./organizationCreation/organizationProvisioningAttempt\";\nexport { verifyOrganizationReplacementResponse } from \"./organizationCreation/organizationReplacementVerification\";\nexport type { ProvisionedSystemContainerSpec } from \"./organizationProvisioning\";\nexport { persistRegistrationBootstrap } from \"./persistRegistrationBootstrap\";\nexport {\n type RegisterIdentityInput,\n type RegistrationApi,\n registerIdentity,\n} from \"./registerIdentity\";\nexport { principalPolicyBundleFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nexport {\n createInitialRootMetadataBootstrap,\n type InitialRootMetadataBootstrap,\n} from \"./rootMetadataBootstrap\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EACL,sBAAsB,EACtB,gCAAgC,GACjC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAGL,kBAAkB,EAClB,kDAAkD,GACnD,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,qCAAqC,EAAE,MAAM,4DAA4D,CAAC;AAEnH,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAGL,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,4CAA4C,EAAE,MAAM,0CAA0C,CAAC;AACxG,OAAO,EACL,kCAAkC,GAEnC,MAAM,yBAAyB,CAAC","sourcesContent":["export { buildInitialOrganizationPolicyRequest } from \"../../data/principals/organizationPolicyRequest\";\nexport {\n bootstrapRootContainer,\n deriveRegistrationOrganizationId,\n} from \"./bootstrapRootContainer\";\nexport {\n type CreateOrganizationApi,\n type CreateOrganizationInput,\n createOrganization,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationCreation/createOrganization\";\nexport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"./organizationCreation/organizationProvisioningAttempt\";\nexport { verifyOrganizationReplacementResponse } from \"./organizationCreation/organizationReplacementVerification\";\nexport type { ProvisionedSystemContainerSpec } from \"./organizationProvisioning\";\nexport { persistRegistrationBootstrap } from \"./persistRegistrationBootstrap\";\nexport {\n type RegisterIdentityInput,\n type RegistrationApi,\n registerIdentity,\n} from \"./registerIdentity\";\nexport { principalPolicyBundleFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nexport {\n createInitialRootMetadataBootstrap,\n type InitialRootMetadataBootstrap,\n} from \"./rootMetadataBootstrap\";\n"]}
@@ -8,10 +8,11 @@ export type { ProvisionedSystemContainerSpec } from "./provisioningBootstrapBuil
8
8
  * The freshly built provisioning artifacts, shared by registration and
9
9
  * additional-organization creation. `registerIdentity` generates a new
10
10
  * `userId`; creating an additional organization reuses the caller's existing
11
- * one. Everything here is derived purely from the caller's key material, so it
12
- * is identical for both flows.
11
+ * one. Registration supplies the personal organization ID planned for the local
12
+ * root. An additional organization receives a fresh ID.
13
13
  */
14
14
  export interface OrganizationProvisioningArtifactsInput {
15
+ organizationId?: string;
15
16
  identityTrustDomain: string;
16
17
  encapsulationKeyPair: EncapsulationKeyPair;
17
18
  organizationProfileName?: string | undefined;
@@ -10,7 +10,7 @@ import { buildInitialOrganizationMetadataBootstrap, buildInitialRootProvisioning
10
10
  import { createInitialRootMetadataBootstrap } from "./rootMetadataBootstrap.js";
11
11
  export { persistOrganizationProvisioningState } from "./organizationProvisioningPersistence.js";
12
12
  async function createOrganizationPrincipalPolicies(input) {
13
- const organizationId = crypto.randomUUID();
13
+ const organizationId = input.organizationId ?? crypto.randomUUID();
14
14
  const signingFingerprint = await toFingerprint(input.signingKeyPair.signingPublicKey);
15
15
  const initialAdminGroup = await buildInitialGroupPolicyRequest({
16
16
  identityTrustDomain: input.identityTrustDomain,
@@ -123,7 +123,6 @@ export async function buildOrganizationProvisioningArtifacts(input) {
123
123
  initialAdminGroup,
124
124
  rootContainer,
125
125
  rootContainerProjection,
126
- signingPrivateKey: input.signingKeyPair.signingPrivateKey,
127
126
  spec,
128
127
  targetSecretKey: input.encapsulationKeyPair.secretKey,
129
128
  })));
@@ -1 +1 @@
1
- {"version":3,"file":"organizationProvisioning.js","sourceRoot":"","sources":["organizationProvisioning.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,uBAAuB;AACvB,OAAO,EAGL,aAAa,GACd,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,sDAAsD,CAAC;AAC/F,OAAO,EACL,8BAA8B,EAC9B,oCAAoC,GACrC,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EACL,yCAAyC,EACzC,4BAA4B,EAC5B,kCAAkC,EAClC,oCAAoC,GAErC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kCAAkC,EAAE,MAAM,yBAAyB,CAAC;AAG7E,OAAO,EAAE,oCAAoC,EAAE,MAAM,uCAAuC,CAAC;AAoC7F,KAAK,UAAU,mCAAmC,CAAC,KAOlD;IACC,MAAM,cAAc,GAAG,MAAM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S;KACtD,CAAC,CACH,CACF,CAAC;IAEF,OAAO;QACL,wBAAwB,EAAE,IAAI;QAC9B,SAAS;QACT,iBAAiB;QACjB,kBAAkB;QAClB,yBAAyB;QACzB,oBAAoB,EAAE,aAAa,CAAC,IAAI,CAAC,OAAO;QAChD,cAAc;QACd,6BAA6B;QAC7B,aAAa;QACb,oBAAoB;QACpB,2BAA2B;QAC3B,sBAAsB;QACtB,yBAAyB;KAC1B,CAAC;AACJ,CAAC","sourcesContent":["// Registration and additional-organization creation build and persist an\n// organization's founding policies, system containers, and profile documents\n// through this module.\nimport {\n type EncapsulationKeyPair,\n type SigningKeyPair,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport { buildInitialOrganizationPolicyRequest } from \"../../data/principals/organizationPolicyRequest\";\nimport { resolveDocumentCreateAuthor } from \"../documents\";\nimport { groupPolicyMutationHead } from \"../organizations/groupPolicy/groupPolicyMutationHead\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../organizations/principalPolicy\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport {\n buildInitialOrganizationMetadataBootstrap,\n buildInitialRootProvisioning,\n buildInitialRosterProfileBootstrap,\n buildInitialSystemContainerBootstrap,\n type ProvisionedSystemContainerSpec,\n} from \"./provisioningBootstrapBuilders\";\nimport { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\nexport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nexport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nexport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\ninterface OrganizationProvisioningPrincipalPolicies {\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"];\n organizationId: string;\n signingFingerprint: string;\n}\n\n/**\n * The freshly built provisioning artifacts, shared by registration and\n * additional-organization creation. `registerIdentity` generates a new\n * `userId`; creating an additional organization reuses the caller's existing\n * one. Everything here is derived purely from the caller's key material, so it\n * is identical for both flows.\n */\nexport interface OrganizationProvisioningArtifactsInput {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationProfileName?: string | undefined;\n /**\n * App-owned system containers to provision atomically with the organization\n * (e.g. a trash bin). Omitted/empty leaves the org with only the roster and\n * organization-metadata system containers.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n rootContainerId: string;\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}\n\nasync function createOrganizationPrincipalPolicies(input: {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationMetadataContainerId: string;\n rootContainerId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<OrganizationProvisioningPrincipalPolicies> {\n const organizationId = crypto.randomUUID();\n const signingFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const initialAdminGroup = await buildInitialGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n { containerId: input.rootContainerId, accessLevel: \"admin\" },\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"admin\",\n },\n ],\n name: \"Admins\",\n builtinRole: \"admins\",\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialMemberGroup = await buildInitialMemberGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"read\",\n },\n ],\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialOrganizationPolicy = await buildInitialOrganizationPolicyRequest(\n {\n identityTrustDomain: input.identityTrustDomain,\n adminGroupId: initialAdminGroup.groupId,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n groupHeads: await Promise.all([\n groupPolicyMutationHead(initialAdminGroup.initialGroupPolicy),\n groupPolicyMutationHead(initialMemberGroup.initialGroupPolicy),\n ]),\n memberGroupId: initialMemberGroup.groupId,\n organizationId,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n },\n );\n\n return {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n };\n}\n\nfunction requireOrganizationProvisioningAuthor(input: {\n readonly organizationId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}) {\n const author = resolveDocumentCreateAuthor({\n auth: { organizationId: input.organizationId, userId: input.userId },\n crypto: {\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n },\n });\n if (!author) {\n throw new Error(\n `Organization provisioning document author context is unavailable for user ${input.userId} in organization ${input.organizationId}.`,\n );\n }\n return author;\n}\n\n/** Builds the signed artifacts shared by registration and org creation. */\nexport async function buildOrganizationProvisioningArtifacts(\n input: OrganizationProvisioningArtifactsInput,\n): Promise<OrganizationProvisioningArtifacts> {\n const bootstrap = await createInitialRootMetadataBootstrap(\n input.rootContainerId,\n );\n const organizationMetadataContainerId = crypto.randomUUID();\n const {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n } = await createOrganizationPrincipalPolicies({\n ...input,\n organizationMetadataContainerId,\n });\n const author = requireOrganizationProvisioningAuthor({\n organizationId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n });\n\n const {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n } = await buildInitialRootProvisioning({\n adminGroup: initialAdminGroup,\n author,\n bootstrap,\n recipientEncapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n rootContainerId: input.rootContainerId,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const rosterProfileBootstrap = await buildInitialRosterProfileBootstrap({\n author,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n initialAdminGroup,\n rosterProfileNickname: input.rosterProfileNickname,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const organizationMetadataBootstrap =\n await buildInitialOrganizationMetadataBootstrap({\n author,\n containerId: organizationMetadataContainerId,\n initialAdminGroup,\n initialMemberGroup,\n organizationProfileName: input.organizationProfileName,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const systemContainerBootstraps = await Promise.all(\n (input.provisionedSystemContainers ?? []).map((spec) =>\n buildInitialSystemContainerBootstrap({\n author,\n initialAdminGroup,\n rootContainer,\n rootContainerProjection,\n signingPrivateKey: input.signingKeyPair.signingPrivateKey,\n spec,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n }),\n ),\n );\n\n return {\n replacementAuthorization: null,\n bootstrap,\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer: rootContainer.plan.request,\n organizationId,\n organizationMetadataBootstrap,\n rootContainer,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n rosterProfileBootstrap,\n systemContainerBootstraps,\n };\n}\n"]}
1
+ {"version":3,"file":"organizationProvisioning.js","sourceRoot":"","sources":["organizationProvisioning.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,uBAAuB;AACvB,OAAO,EAGL,aAAa,GACd,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,uBAAuB,E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B,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CAAC;IACL,MAAM,yBAAyB,GAAG,MAAM,OAAO,CAAC,GAAG,CACjD,CAAC,KAAK,CAAC,2BAA2B,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACrD,oCAAoC,CAAC;QACnC,MAAM;QACN,iBAAiB;QACjB,aAAa;QACb,uBAAuB;QACvB,IAAI;QACJ,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CACH,CACF,CAAC;IAEF,OAAO;QACL,wBAAwB,EAAE,IAAI;QAC9B,SAAS;QACT,iBAAiB;QACjB,kBAAkB;QAClB,yBAAyB;QACzB,oBAAoB,EAAE,aAAa,CAAC,IAAI,CAAC,OAAO;QAChD,cAAc;QACd,6BAA6B;QAC7B,aAAa;QACb,oBAAoB;QACpB,2BAA2B;QAC3B,sBAAsB;QACtB,yBAAyB;KAC1B,CAAC;AACJ,CAAC","sourcesContent":["// Registration and additional-organization creation build and persist an\n// organization's founding policies, system containers, and profile documents\n// through this module.\nimport {\n type EncapsulationKeyPair,\n type SigningKeyPair,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport { buildInitialOrganizationPolicyRequest } from \"../../data/principals/organizationPolicyRequest\";\nimport { resolveDocumentCreateAuthor } from \"../documents\";\nimport { groupPolicyMutationHead } from \"../organizations/groupPolicy/groupPolicyMutationHead\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../organizations/principalPolicy\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport {\n buildInitialOrganizationMetadataBootstrap,\n buildInitialRootProvisioning,\n buildInitialRosterProfileBootstrap,\n buildInitialSystemContainerBootstrap,\n type ProvisionedSystemContainerSpec,\n} from \"./provisioningBootstrapBuilders\";\nimport { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\nexport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nexport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nexport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\ninterface OrganizationProvisioningPrincipalPolicies {\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"];\n organizationId: string;\n signingFingerprint: string;\n}\n\n/**\n * The freshly built provisioning artifacts, shared by registration and\n * additional-organization creation. `registerIdentity` generates a new\n * `userId`; creating an additional organization reuses the caller's existing\n * one. Registration supplies the personal organization ID planned for the local\n * root. An additional organization receives a fresh ID.\n */\nexport interface OrganizationProvisioningArtifactsInput {\n organizationId?: string;\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationProfileName?: string | undefined;\n /**\n * App-owned system containers to provision atomically with the organization\n * (e.g. a trash bin). Omitted/empty leaves the org with only the roster and\n * organization-metadata system containers.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n rootContainerId: string;\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}\n\nasync function createOrganizationPrincipalPolicies(input: {\n organizationId?: string;\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationMetadataContainerId: string;\n rootContainerId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<OrganizationProvisioningPrincipalPolicies> {\n const organizationId = input.organizationId ?? crypto.randomUUID();\n const signingFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const initialAdminGroup = await buildInitialGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n { containerId: input.rootContainerId, accessLevel: \"admin\" },\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"admin\",\n },\n ],\n name: \"Admins\",\n builtinRole: \"admins\",\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialMemberGroup = await buildInitialMemberGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"read\",\n },\n ],\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialOrganizationPolicy = await buildInitialOrganizationPolicyRequest(\n {\n identityTrustDomain: input.identityTrustDomain,\n adminGroupId: initialAdminGroup.groupId,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n groupHeads: await Promise.all([\n groupPolicyMutationHead(initialAdminGroup.initialGroupPolicy),\n groupPolicyMutationHead(initialMemberGroup.initialGroupPolicy),\n ]),\n memberGroupId: initialMemberGroup.groupId,\n organizationId,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n },\n );\n\n return {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n };\n}\n\nfunction requireOrganizationProvisioningAuthor(input: {\n readonly organizationId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}) {\n const author = resolveDocumentCreateAuthor({\n auth: { organizationId: input.organizationId, userId: input.userId },\n crypto: {\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n },\n });\n if (!author) {\n throw new Error(\n `Organization provisioning document author context is unavailable for user ${input.userId} in organization ${input.organizationId}.`,\n );\n }\n return author;\n}\n\n/** Builds the signed artifacts shared by registration and org creation. */\nexport async function buildOrganizationProvisioningArtifacts(\n input: OrganizationProvisioningArtifactsInput,\n): Promise<OrganizationProvisioningArtifacts> {\n const bootstrap = await createInitialRootMetadataBootstrap(\n input.rootContainerId,\n );\n const organizationMetadataContainerId = crypto.randomUUID();\n const {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n } = await createOrganizationPrincipalPolicies({\n ...input,\n organizationMetadataContainerId,\n });\n const author = requireOrganizationProvisioningAuthor({\n organizationId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n });\n\n const {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n } = await buildInitialRootProvisioning({\n adminGroup: initialAdminGroup,\n author,\n bootstrap,\n recipientEncapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n rootContainerId: input.rootContainerId,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const rosterProfileBootstrap = await buildInitialRosterProfileBootstrap({\n author,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n initialAdminGroup,\n rosterProfileNickname: input.rosterProfileNickname,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const organizationMetadataBootstrap =\n await buildInitialOrganizationMetadataBootstrap({\n author,\n containerId: organizationMetadataContainerId,\n initialAdminGroup,\n initialMemberGroup,\n organizationProfileName: input.organizationProfileName,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const systemContainerBootstraps = await Promise.all(\n (input.provisionedSystemContainers ?? []).map((spec) =>\n buildInitialSystemContainerBootstrap({\n author,\n initialAdminGroup,\n rootContainer,\n rootContainerProjection,\n spec,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n }),\n ),\n );\n\n return {\n replacementAuthorization: null,\n bootstrap,\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer: rootContainer.plan.request,\n organizationId,\n organizationMetadataBootstrap,\n rootContainer,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n rosterProfileBootstrap,\n systemContainerBootstraps,\n };\n}\n"]}
@@ -1,5 +1,4 @@
1
1
  import type { CreateOrganizationGroupRequest } from "../../internal/validators/request/index.js";
2
- import { type ContainerSystemSlotDefinition } from "../container-contents/index.js";
3
2
  import { rootContainerWriterProjectionFromCreatePlan } from "../containers/index.js";
4
3
  import type { resolveDocumentCreateAuthor } from "../documents/index.js";
5
4
  import type { InitialOrganizationMetadataBootstrap, InitialRootContainerCreatePlan, InitialRosterProfileBootstrap, InitialSystemContainerBootstrap } from "./organizationProvisioningArtifacts.js";
@@ -9,14 +8,14 @@ type InitialRootContainerProjection = ReturnType<typeof rootContainerWriterProje
9
8
  * An app-owned system container to provision atomically with a new organization
10
9
  * (e.g. a trash bin). The client-sdk is agnostic to what these are:
11
10
  * the caller (the app, which owns the mini-app slot namespaces) declares each
12
- * one, and the provisioning path derives its per-user system slot, builds a
11
+ * one, and the provisioning path derives its organization system slot, builds a
13
12
  * signed Admins-scoped child of root, and links it into the same transaction as
14
13
  * the rest of the organization bootstrap. The behavioral rules that govern a
15
14
  * system container are resolved client-side by slot, so provisioning needs only
16
- * the slot definition, display name, and icon — no rules travel to the server.
15
+ * the slot namespace, display name, and icon — no rules travel to the server.
17
16
  */
18
17
  export interface ProvisionedSystemContainerSpec {
19
- readonly slotDefinition: ContainerSystemSlotDefinition;
18
+ readonly slotNamespace: string;
20
19
  readonly name: string;
21
20
  readonly icon: string | null;
22
21
  }
@@ -44,7 +43,6 @@ export declare function buildInitialSystemContainerBootstrap(input: {
44
43
  initialAdminGroup: CreateOrganizationGroupRequest;
45
44
  rootContainer: InitialRootContainerCreatePlan;
46
45
  rootContainerProjection: InitialRootContainerProjection;
47
- signingPrivateKey: Uint8Array;
48
46
  spec: ProvisionedSystemContainerSpec;
49
47
  targetSecretKey: Uint8Array;
50
48
  }): Promise<InitialSystemContainerBootstrap>;