@tearleads/client-sdk 0.1.250 → 0.1.252
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Tearleads.d.ts +0 -2
- package/Tearleads.js +14 -25
- package/Tearleads.js.map +1 -1
- package/client/organizations/organizationReadModelPresentation.js +7 -4
- package/client/organizations/organizationReadModelPresentation.js.map +1 -1
- package/client/organizations/organizationReadModels.js +6 -5
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/client/organizations/organizationWorkflowRuntime.js +1 -1
- package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
- package/client/runtime/principalMutationApi.d.ts +4 -0
- package/client/runtime/principalMutationApi.js +9 -5
- package/client/runtime/principalMutationApi.js.map +1 -1
- package/client/runtime/runtimeIdentityResolution.js +23 -0
- package/client/runtime/runtimeIdentityResolution.js.map +1 -1
- package/client/runtime/runtimeSubscription.js +68 -0
- package/client/runtime/runtimeSubscription.js.map +1 -0
- package/client/runtime/workflowRuntime.d.ts +1 -1
- package/client/runtime/workflowRuntime.js +20 -77
- package/client/runtime/workflowRuntime.js.map +1 -1
- package/client/session/authenticationMachine.js +47 -0
- package/client/session/authenticationMachine.js.map +1 -0
- package/client/session/index.js +75 -93
- package/client/session/index.js.map +1 -1
- package/client/session/sessionBlobStore.js +39 -0
- package/client/session/sessionBlobStore.js.map +1 -0
- package/client/session/sessionContext.js +11 -0
- package/client/session/sessionContext.js.map +1 -1
- package/client/session/sessionIdentityTrust.d.ts +2 -1
- package/client/session/sessionIdentityTrust.js +8 -4
- package/client/session/sessionIdentityTrust.js.map +1 -1
- package/client/session/sessionLifetime.js +87 -0
- package/client/session/sessionLifetime.js.map +1 -0
- package/client/session/sessionLogin.js +114 -0
- package/client/session/sessionLogin.js.map +1 -0
- package/client/session/sessionOrganizationCreation.js +3 -2
- package/client/session/sessionOrganizationCreation.js.map +1 -1
- package/client/session/sessionPurgeRecovery.js +11 -3
- package/client/session/sessionPurgeRecovery.js.map +1 -1
- package/client/session/sessionTypes.d.ts +6 -2
- package/client/session/sessionTypes.js.map +1 -1
- package/data/blobs/blobContracts.d.ts +4 -3
- package/data/blobs/blobContracts.js.map +1 -1
- package/data/blobs/createBlobStore.js +1 -8
- package/data/blobs/createBlobStore.js.map +1 -1
- package/data/blobs/encryptedBlobStore.js +17 -12
- package/data/blobs/encryptedBlobStore.js.map +1 -1
- package/data/blobs/memoryBlobStore.js +8 -5
- package/data/blobs/memoryBlobStore.js.map +1 -1
- package/data/blobs/opfsBlobFile.js +36 -0
- package/data/blobs/opfsBlobFile.js.map +1 -0
- package/data/blobs/opfsBlobStore.d.ts +1 -1
- package/data/blobs/opfsBlobStore.js +91 -21
- package/data/blobs/opfsBlobStore.js.map +1 -1
- package/data/documents/shared/events.js +2 -1
- package/data/documents/shared/events.js.map +1 -1
- package/data/principals/principalPolicyCoordinator.js +8 -17
- package/data/principals/principalPolicyCoordinator.js.map +1 -1
- package/data/shared/domainScope.d.ts +2 -0
- package/data/shared/domainScope.js +2 -1
- package/data/shared/domainScope.js.map +1 -1
- package/data/shared/keyedQueue.js +15 -0
- package/data/shared/keyedQueue.js.map +1 -0
- package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
- package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
- package/data/sqlite/sqlExec.d.ts +6 -0
- package/data/sqlite/sqlExec.js +64 -13
- package/data/sqlite/sqlExec.js.map +1 -1
- package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
- package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
- package/data/trustedUserIdentity/service.js +2 -1
- package/data/trustedUserIdentity/service.js.map +1 -1
- package/data/trustedUserIdentity/types.d.ts +1 -1
- package/data/trustedUserIdentity/types.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +4 -1
- package/internal/api-client/apiRequestRuntime.d.ts +6 -3
- package/internal/api-client/apiRequestRuntime.js +86 -101
- package/internal/api-client/apiRequestRuntime.js.map +1 -1
- package/internal/api-client/binaryRequestOperationTransport.js +2 -1
- package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
- package/internal/api-client/binaryResponseOperationTransport.js +6 -2
- package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
- package/internal/api-client/client/blobs.d.ts +1 -0
- package/internal/api-client/client/blobs.js +12 -3
- package/internal/api-client/client/blobs.js.map +1 -1
- package/internal/api-client/client/laneListingRequest.js +4 -0
- package/internal/api-client/client/laneListingRequest.js.map +1 -1
- package/internal/api-client/client/session.d.ts +5 -1
- package/internal/api-client/client/session.js +12 -4
- package/internal/api-client/client/session.js.map +1 -1
- package/internal/api-client/client/writerProjections.js +12 -13
- package/internal/api-client/client/writerProjections.js.map +1 -1
- package/internal/api-client/operationResponse.d.ts +1 -1
- package/internal/api-client/operationResponse.js +10 -23
- package/internal/api-client/operationResponse.js.map +1 -1
- package/internal/api-client/operationTransport.js +2 -1
- package/internal/api-client/operationTransport.js.map +1 -1
- package/internal/api-client/principalHistoryRequest.js +25 -20
- package/internal/api-client/principalHistoryRequest.js.map +1 -1
- package/internal/api-client/principalHistoryRequestContext.js +30 -6
- package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
- package/internal/api-client/principalPolicyPages.d.ts +4 -1
- package/internal/api-client/principalPolicyPages.js +4 -2
- package/internal/api-client/principalPolicyPages.js.map +1 -1
- package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
- package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
- package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
- package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
- package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
- package/internal/api-client/routes/blobs/get.js +9 -67
- package/internal/api-client/routes/blobs/get.js.map +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
- package/internal/api-client/sessionRefresh.js +1 -1
- package/internal/api-client/sessionRefresh.js.map +1 -1
- package/internal/api-client/sessionRenewal.d.ts +31 -0
- package/internal/api-client/sessionRenewal.js +91 -6
- package/internal/api-client/sessionRenewal.js.map +1 -1
- package/internal/api-client/sessionRequestInit.js +22 -0
- package/internal/api-client/sessionRequestInit.js.map +1 -0
- package/internal/api-client/sessionResponse.js +39 -0
- package/internal/api-client/sessionResponse.js.map +1 -0
- package/internal/api-client/types.d.ts +1 -0
- package/internal/api-client/types.js.map +1 -1
- package/internal/api-client/webSocketTickets.d.ts +1 -0
- package/internal/api-client/webSocketTickets.js +4 -0
- package/internal/api-client/webSocketTickets.js.map +1 -1
- package/internal/sqlite-worker/client.d.ts +1 -1
- package/internal/sqlite-worker/client.js +6 -1
- package/internal/sqlite-worker/client.js.map +1 -1
- package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
- package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
- package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
- package/internal/sqlite-worker/types.d.ts +4 -0
- package/internal/sqlite-worker/types.js.map +1 -1
- package/internal/validators/documentCreateSeedRefinements.js +2 -2
- package/internal/validators/documentCreateSeedRefinements.js.map +1 -1
- package/internal/validators/operation/auth.d.ts +50 -1703
- package/internal/validators/operation/auth.js +2 -2
- package/internal/validators/operation/auth.js.map +1 -1
- package/internal/validators/operation/containerMutations.d.ts +1 -294
- package/internal/validators/operation/containerMutations.js +2 -2
- package/internal/validators/operation/containerMutations.js.map +1 -1
- package/internal/validators/operation/documentMutations.d.ts +1 -294
- package/internal/validators/operation/documentMutations.js +2 -2
- package/internal/validators/operation/documentMutations.js.map +1 -1
- package/internal/validators/operation/organizations.d.ts +50 -1703
- package/internal/validators/operation/organizations.js +2 -2
- package/internal/validators/operation/organizations.js.map +1 -1
- package/internal/validators/organizationProvisioningRefinements.js +2 -2
- package/internal/validators/organizationProvisioningRefinements.js.map +1 -1
- package/internal/validators/request/containerMetadata.d.ts +0 -276
- package/internal/validators/request/containerMetadata.js +5 -4
- package/internal/validators/request/containerMetadata.js.map +1 -1
- package/internal/validators/request/document.d.ts +0 -277
- package/internal/validators/request/document.js +8 -4
- package/internal/validators/request/document.js.map +1 -1
- package/internal/validators/request/documentCreateSeed.d.ts +99 -0
- package/internal/validators/request/documentCreateSeed.js +132 -9
- package/internal/validators/request/documentCreateSeed.js.map +1 -1
- package/internal/validators/request/documentSyncSchema.d.ts +41 -0
- package/internal/validators/request/documentSyncSchema.js +1 -1
- package/internal/validators/request/documentSyncSchema.js.map +1 -1
- package/internal/validators/request/index.d.ts +1 -0
- package/internal/validators/request/index.js +1 -0
- package/internal/validators/request/index.js.map +1 -1
- package/internal/validators/request/organizationProvisioning.d.ts +263 -5567
- package/internal/validators/request/organizationProvisioning.js +10 -4
- package/internal/validators/request/organizationProvisioning.js.map +1 -1
- package/internal/validators/request/registration.d.ts +71 -1703
- package/package.json +1 -1
- package/sqlite/worker.js +1 -1
- package/workflows/container-contents/container-state/create/createWithMetadata.js +6 -3
- package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
- package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
- package/workflows/documents/attachments/blobMutationLock.js +2 -2
- package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
- package/workflows/documents/create/index.js +4 -4
- package/workflows/documents/create/index.js.map +1 -1
- package/workflows/documents/sync/initialSync.d.ts +26 -11
- package/workflows/documents/sync/initialSync.js +32 -12
- package/workflows/documents/sync/initialSync.js.map +1 -1
- package/workflows/organizations/readModel/readModelProjection.js +2 -0
- package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
- package/workflows/registration/provisionedProfileDocument.js +2 -2
- package/workflows/registration/provisionedProfileDocument.js.map +1 -1
- package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -68
- package/workflows/registration/provisioningBootstrapBuilders.js +3 -3
- package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
- package/workflows/registration/registerIdentity.js +2 -0
- package/workflows/registration/registerIdentity.js.map +1 -1
|
@@ -1 +1 @@
|
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KAAK,MAAM,EAAE,CAAC;YAC5B,OAAO,OAAO,CAAC,KAAK,CAAC;QACvB,CAAC;QACD,IAAI,OAAO,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAChC,SAAS;QACX,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;QACzE,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC5B,OAAO,OAAO,CAAC,KAAK,CAAC;QACvB,CAAC;IACH,CAAC;IAED,KAAK,CAAC,QAAQ,EAAE,CACd,4DAA4D,CAC7D,CAAC;IACF,MAAM,QAAQ,GAAG,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,OAAO,QAAQ,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,CAAC","sourcesContent":["import type {\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n ORGANIZATION_READ_MODEL_ERROR_CODES,\n type OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport type { OrganizationReadModelGroupMembers } from \"../../../data/persistence/organizations/organizationReadModelMemberLoad\";\nimport { OrganizationReadModelBindingError } from \"../../../data/persistence/organizations/organizationReadModelMembershipPersistence\";\nimport type {\n ApplyOrganizationReadModelResponseResult,\n OrganizationReadModelProjection,\n} from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationDirectoryAndGroups } from \"./index\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n denyOrganizationPresentationAccess,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n type OrganizationPresentationAccessAttempt,\n type OrganizationPresentationAccessInput,\n restoreOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n runOrganizationPresentationRead,\n} from \"./organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"./organizationPresentationFailures\";\n\nconst MAX_READ_MODEL_PAGES = 100;\nconst MAX_STALE_RETRIES = 1;\n\ninterface OrganizationReadModelApi {\n getOrganizationReadModelResult(\n organizationId: string,\n cursor?: string,\n options?: RequestResultOptions,\n ): Promise<RequestResult<OrganizationReadModelResponse>>;\n}\n\ninterface OrganizationReadModelProjectionInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\n/** Applying a page needs no API; `stillCurrent` is rechecked in the write. */\ninterface ApplyReadModelPageInput extends OrganizationReadModelProjectionInput {\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ReconcileOrganizationDirectoryAndGroupsInput\n extends ApplyReadModelPageInput {\n readonly apiClient: OrganizationReadModelApi;\n}\n\nfunction toDirectoryAndGroups(\n projection: OrganizationReadModelProjection | null,\n): OrganizationDirectoryAndGroups | null {\n if (!projection?.requester) {\n return null;\n }\n\n return {\n directory: {\n ...projection.directory,\n currentUser: projection.requester,\n },\n // Hydration decides whether a name is unreadable; a stored blank name may\n // only mean the group has not been hydrated yet.\n groups: projection.groups.groups.map((group) => ({\n ...group,\n nameUnreadable: false,\n })),\n memberGroupId: projection.groups.memberGroupId,\n readModelCursor: projection.cursor,\n };\n}\n\nasync function loadProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () => loadRawProjection(input),\n );\n}\n\nfunction loadRawProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n}\n\nfunction organizationPresentationAccessInput(\n input: OrganizationReadModelProjectionInput,\n): OrganizationPresentationAccessInput {\n return {\n execSql: input.execSql,\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n };\n}\n\ninterface ReconciliationState {\n readonly accessAttempt: OrganizationPresentationAccessAttempt;\n expectedLocalCursor: string | null;\n preparedDeniedProjection: boolean;\n projection: OrganizationReadModelProjection | null;\n requestCursor: string | undefined;\n retriedBindingFailure: boolean;\n retriedInvalidCursor: boolean;\n staleRetries: number;\n}\n\ntype ReconciliationStep =\n | { readonly kind: \"continue\" }\n | {\n readonly kind: \"done\";\n readonly value: OrganizationDirectoryAndGroups | null | undefined;\n };\n\ntype PageRequestStep =\n | ReconciliationStep\n | {\n readonly kind: \"response\";\n readonly response: OrganizationReadModelResponse;\n };\n\nfunction localResult(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n outcome: { readonly failed: boolean },\n): ReconciliationStep {\n const accessInput = organizationPresentationAccessInput(input);\n const readable =\n isOrganizationPresentationAccessAttemptCurrent(\n accessInput,\n state.accessAttempt,\n ) && isOrganizationPresentationAccessReadable(accessInput, \"readModel\");\n if (!readable) {\n return { kind: \"done\", value: null };\n }\n // Retained rows are available through the local loader, but are not proof\n // that this pass caught up. Returning them after a failed post-commit read\n // makes mutation callers skip their retry and repaint pre-mutation status.\n if (outcome.failed) {\n return { kind: \"done\", value: undefined };\n }\n return { kind: \"done\", value: toDirectoryAndGroups(state.projection) };\n}\n\nfunction resetRequestCursor(state: ReconciliationState): void {\n state.expectedLocalCursor = state.projection?.cursor ?? null;\n state.requestCursor = state.projection?.cursor ?? undefined;\n}\n\n/** Replays a page that applied stale, up to the retry budget. */\nfunction retryStaleApply(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): ReconciliationStep {\n if (state.staleRetries >= MAX_STALE_RETRIES) {\n return localResult(input, state, { failed: true });\n }\n state.staleRetries += 1;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n}\n\nfunction isInvalidReadModelCursorFailure(\n result: RequestResult<OrganizationReadModelResponse>,\n): boolean {\n return (\n !result.ok &&\n result.kind === \"http\" &&\n result.status === 400 &&\n result.code === ORGANIZATION_READ_MODEL_ERROR_CODES.cursorInvalid\n );\n}\n\nasync function requestReadModelPage(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): Promise<PageRequestStep> {\n const result = await input.apiClient.getOrganizationReadModelResult(\n input.organizationId,\n state.requestCursor,\n { reportErrors: false },\n );\n if (result.ok) {\n return { kind: \"response\", response: result.data };\n }\n if (isOrganizationPresentationAccessDeniedFailure(result)) {\n const accessInput = organizationPresentationAccessInput(input);\n denyOrganizationPresentationAccess(accessInput, [\"readModel\", \"usage\"]);\n const repository = new OrganizationReadModelRepository(input.execSql);\n // The durable marker lands before the purge attempt: if the purge fails,\n // an offline restart must still refuse to serve the revoked projection.\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.recordOrganizationPresentationDenials(accessInput, [\n \"readModel\",\n \"usage\",\n ]),\n );\n } catch (error) {\n input.logError?.(\"Failed to record denied organization access\", error);\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.purgeOrganizationAccessProjection({\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n }),\n );\n } catch (error) {\n input.logError?.(\"Failed to purge denied organization access\", error);\n }\n return { kind: \"done\", value: null };\n }\n if (\n isInvalidReadModelCursorFailure(result) &&\n state.requestCursor !== undefined &&\n !state.retriedInvalidCursor\n ) {\n state.requestCursor = undefined;\n state.retriedInvalidCursor = true;\n return { kind: \"continue\" };\n }\n\n result.report();\n return localResult(input, state, { failed: true });\n}\n\nfunction responseMatchesRequest(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): boolean {\n if (response.organizationId !== input.organizationId) {\n input.logError?.(\n `Organization read-model response scope does not match ${input.organizationId}`,\n );\n return false;\n }\n if (response.hasMore && response.nextCursor === state.expectedLocalCursor) {\n input.logError?.(\"Organization read-model page did not advance its cursor\");\n return false;\n }\n return true;\n}\n\nfunction reconciliationIsCurrent(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): boolean {\n return isOrganizationPresentationAccessAttemptCurrent(\n organizationPresentationAccessInput(input),\n state.accessAttempt,\n );\n}\n\ntype ApplyResponseStep =\n | ReconciliationStep\n | {\n readonly kind: \"applied\";\n readonly result: ApplyOrganizationReadModelResponseResult;\n };\n\nasync function applyResponse(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ApplyResponseStep> {\n const repository = new OrganizationReadModelRepository(input.execSql);\n try {\n return {\n kind: \"applied\",\n result: await repository.applyOrganizationReadModelResponse({\n canCommit: input.stillCurrent,\n currentUserId: input.currentUserId,\n requestedCursor: state.expectedLocalCursor,\n response,\n }),\n };\n } catch (error) {\n input.logError?.(\"Failed to apply organization read-model response\", error);\n if (\n !(error instanceof OrganizationReadModelBindingError) ||\n state.retriedBindingFailure\n ) {\n return localResult(input, state, { failed: true });\n }\n state.retriedBindingFailure = true;\n await repository.purgeOrganizationReadModelProjection(input.organizationId);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.projection = null;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n }\n}\n\nasync function prepareDeniedProjectionForApply(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): Promise<ReconciliationStep | null> {\n if (state.preparedDeniedProjection) {\n return null;\n }\n try {\n // The apply that follows replaces the shared rows authoritatively, so\n // only this requester's row is dropped: another local identity sharing\n // the database keeps its access and reads the replacement.\n await new OrganizationReadModelRepository(\n input.execSql,\n ).purgeOrganizationReadModelProjection(input.organizationId, {\n onlyRequesterUserId: input.currentUserId,\n });\n } catch (error) {\n input.logError?.(\"Failed to replace denied organization read model\", error);\n return { kind: \"done\", value: null };\n }\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.expectedLocalCursor = null;\n state.preparedDeniedProjection = true;\n state.projection = null;\n return null;\n}\n\n/** The last page settles only if presentation access is still restorable. */\nfunction finalPageStep(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n accessInput: OrganizationPresentationAccessInput,\n): ReconciliationStep {\n return restoreOrganizationPresentationAccess(accessInput, state.accessAttempt)\n ? localResult(input, state, { failed: false })\n : { kind: \"done\", value: null };\n}\n\nasync function applyReadModelPage(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ReconciliationStep> {\n if (!responseMatchesRequest(input, state, response)) {\n return localResult(input, state, { failed: true });\n }\n\n const accessInput = organizationPresentationAccessInput(input);\n return runOrganizationPresentationMutation(input.execSql, async () => {\n if (\n !reconciliationIsCurrent(input, state) ||\n input.stillCurrent?.() === false\n )\n return { kind: \"done\", value: null };\n const preparation = await prepareDeniedProjectionForApply(input, state);\n if (preparation) return preparation;\n const applied = await applyResponse(input, state, response);\n if (applied.kind !== \"applied\") {\n return applied;\n }\n\n state.projection = await loadRawProjection(input);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n if (applied.result === \"stale\") {\n return retryStaleApply(input, state);\n }\n\n state.expectedLocalCursor = state.projection?.cursor ?? response.nextCursor;\n if (!response.hasMore) {\n return finalPageStep(input, state, accessInput);\n }\n state.requestCursor = response.nextCursor;\n return { kind: \"continue\" };\n });\n}\n\nexport async function loadLocalOrganizationDirectoryAndGroups(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationDirectoryAndGroups | null> {\n return toDirectoryAndGroups(await loadProjection(input));\n}\n\nexport async function loadLocalOrganizationGroupMembers(\n input: OrganizationReadModelProjectionInput & { readonly groupId: string },\n): Promise<OrganizationReadModelGroupMembers | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () =>\n new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelGroupMembers(\n input.organizationId,\n input.groupId,\n input.currentUserId,\n ),\n );\n}\n\n/**\n * Apply one page as a feed read from `requestedCursor` returns it, with no\n * request, while the projection still holds that cursor. Resolves `undefined`\n * when it is not applied; it is never retried.\n */\nexport async function applyOrganizationReadModelPageAt(\n input: ApplyReadModelPageInput & {\n readonly requestedCursor: string;\n readonly response: OrganizationReadModelResponse;\n },\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n organizationPresentationAccessInput(input),\n \"readModel\",\n );\n const projection = await loadProjection(input);\n if (projection?.cursor !== input.requestedCursor) return undefined;\n const applied = await applyReadModelPage(\n input,\n {\n accessAttempt,\n expectedLocalCursor: projection.cursor,\n preparedDeniedProjection: true,\n projection,\n requestCursor: projection.cursor,\n retriedBindingFailure: true,\n retriedInvalidCursor: true,\n staleRetries: MAX_STALE_RETRIES,\n },\n input.response,\n );\n return applied.kind === \"done\" ? applied.value : undefined;\n}\n\n/**\n * Resolves the reconciled projection, `null` when the pass completed\n * authoritatively with nothing presentable (including a denial that purged\n * the projection), or `undefined` when the feed failed — even when local\n * rows remain available. A failed pass must not count as caught up.\n */\nexport async function reconcileOrganizationDirectoryAndGroups(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessInput = organizationPresentationAccessInput(input);\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n accessInput,\n \"readModel\",\n );\n const state: ReconciliationState = {\n accessAttempt,\n expectedLocalCursor: null,\n preparedDeniedProjection: !accessAttempt.startedDenied,\n projection: await loadProjection(input),\n requestCursor: undefined,\n retriedBindingFailure: false,\n retriedInvalidCursor: false,\n staleRetries: 0,\n };\n resetRequestCursor(state);\n\n for (let page = 0; page < MAX_READ_MODEL_PAGES; page += 1) {\n const request = await requestReadModelPage(input, state);\n if (request.kind === \"done\") {\n return request.value;\n }\n if (request.kind === \"continue\") {\n continue;\n }\n const applied = await applyReadModelPage(input, state, request.response);\n if (applied.kind === \"done\") {\n return applied.value;\n }\n }\n\n input.logError?.(\n \"Organization read-model reconciliation exceeded page limit\",\n );\n const retained = localResult(input, state, { failed: true });\n return retained.kind === \"done\" ? retained.value : null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"readModelProjection.js","sourceRoot":"","sources":["readModelProjection.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,mCAAmC,GAEpC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,iCAAiC,EAAE,MAAM,oFAAoF,CAAC;AAKvI,OAAO,EAAE,+BAA+B,EAAE,MAAM,yEAAyE,CAAC;AAG1H,OAAO,EACL,4CAA4C,EAC5C,kCAAkC,EAClC,8CAA8C,EAC9C,wCAAwC,EAGxC,qCAAqC,EACrC,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,6CAA6C,EAAE,MAAM,oCAAoC,CAAC;AAEnG,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,MAAM,iBAAiB,GAAG,CAAC,CAAC;AA6B5B,SAAS,oBAAoB,CAC3B,UAAkD;IAElD,IAAI,CAAC,UAAU,EAAE,SAAS,EAAE,CAAC;QAC3B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,SAAS,EAAE;YACT,GAAG,UAAU,CAAC,SAAS;YACvB,WAAW,EAAE,UAAU,CAAC,SAAS;SAClC;QACD,0EAA0E;QAC1E,iDAAiD;QACjD,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YAC/C,GAAG,KAAK;YACR,cAAc,EAAE,KAAK;SACtB,CAAC,CAAC;QACH,aAAa,EAAE,UAAU,CAAC,MAAM,CAAC,aAAa;QAC9C,eAAe,EAAE,UAAU,CAAC,MAAM;KACnC,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,cAAc,CAC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oBAAoB,EAAE,KAAK;QAC3B,YAAY,EAAE,CAAC;KAChB,CAAC;IACF,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAE1B,KAAK,IAAI,IAAI,GAAG,CAAC,EAAE,IAAI,GAAG,oBAAoB,EAAE,IAAI,IAAI,CAAC,EAAE,CAAC;QAC1D,MAAM,OAAO,GAAG,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QACzD,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC5B,OAAO,OAAO,CAAC,KAAK,CAAC;QACvB,CAAC;QACD,IAAI,OAAO,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAChC,SAAS;QACX,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;QACzE,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC5B,OAAO,OAAO,CAAC,KAAK,CAAC;QACvB,CAAC;IACH,CAAC;IAED,KAAK,CAAC,QAAQ,EAAE,CACd,4DAA4D,CAC7D,CAAC;IACF,MAAM,QAAQ,GAAG,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,OAAO,QAAQ,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,CAAC","sourcesContent":["import type {\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n ORGANIZATION_READ_MODEL_ERROR_CODES,\n type OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport type { OrganizationReadModelGroupMembers } from \"../../../data/persistence/organizations/organizationReadModelMemberLoad\";\nimport { OrganizationReadModelBindingError } from \"../../../data/persistence/organizations/organizationReadModelMembershipPersistence\";\nimport type {\n ApplyOrganizationReadModelResponseResult,\n OrganizationReadModelProjection,\n} from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationDirectoryAndGroups } from \"./index\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n denyOrganizationPresentationAccess,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n type OrganizationPresentationAccessAttempt,\n type OrganizationPresentationAccessInput,\n restoreOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n runOrganizationPresentationRead,\n} from \"./organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"./organizationPresentationFailures\";\n\nconst MAX_READ_MODEL_PAGES = 100;\nconst MAX_STALE_RETRIES = 1;\n\ninterface OrganizationReadModelApi {\n getOrganizationReadModelResult(\n organizationId: string,\n cursor?: string,\n options?: RequestResultOptions,\n ): Promise<RequestResult<OrganizationReadModelResponse>>;\n}\n\ninterface OrganizationReadModelProjectionInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\n/** Applying a page needs no API; `stillCurrent` is rechecked in the write. */\ninterface ApplyReadModelPageInput extends OrganizationReadModelProjectionInput {\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ReconcileOrganizationDirectoryAndGroupsInput\n extends ApplyReadModelPageInput {\n readonly apiClient: OrganizationReadModelApi;\n}\n\nfunction toDirectoryAndGroups(\n projection: OrganizationReadModelProjection | null,\n): OrganizationDirectoryAndGroups | null {\n if (!projection?.requester) {\n return null;\n }\n\n return {\n directory: {\n ...projection.directory,\n currentUser: projection.requester,\n },\n // Hydration decides whether a name is unreadable; a stored blank name may\n // only mean the group has not been hydrated yet.\n groups: projection.groups.groups.map((group) => ({\n ...group,\n nameUnreadable: false,\n })),\n memberGroupId: projection.groups.memberGroupId,\n readModelCursor: projection.cursor,\n };\n}\n\nasync function loadProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () => loadRawProjection(input),\n );\n}\n\nfunction loadRawProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n}\n\nfunction organizationPresentationAccessInput(\n input: OrganizationReadModelProjectionInput,\n): OrganizationPresentationAccessInput {\n return {\n execSql: input.execSql,\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n };\n}\n\ninterface ReconciliationState {\n readonly accessAttempt: OrganizationPresentationAccessAttempt;\n expectedLocalCursor: string | null;\n preparedDeniedProjection: boolean;\n projection: OrganizationReadModelProjection | null;\n requestCursor: string | undefined;\n retriedBindingFailure: boolean;\n retriedInvalidCursor: boolean;\n staleRetries: number;\n}\n\ntype ReconciliationStep =\n | { readonly kind: \"continue\" }\n | {\n readonly kind: \"done\";\n readonly value: OrganizationDirectoryAndGroups | null | undefined;\n };\n\ntype PageRequestStep =\n | ReconciliationStep\n | {\n readonly kind: \"response\";\n readonly response: OrganizationReadModelResponse;\n };\n\nfunction localResult(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n outcome: { readonly failed: boolean },\n): ReconciliationStep {\n const accessInput = organizationPresentationAccessInput(input);\n const readable =\n isOrganizationPresentationAccessAttemptCurrent(\n accessInput,\n state.accessAttempt,\n ) && isOrganizationPresentationAccessReadable(accessInput, \"readModel\");\n if (!readable) {\n return { kind: \"done\", value: null };\n }\n // Retained rows are available through the local loader, but are not proof\n // that this pass caught up. Returning them after a failed post-commit read\n // makes mutation callers skip their retry and repaint pre-mutation status.\n if (outcome.failed) {\n return { kind: \"done\", value: undefined };\n }\n return { kind: \"done\", value: toDirectoryAndGroups(state.projection) };\n}\n\nfunction resetRequestCursor(state: ReconciliationState): void {\n state.expectedLocalCursor = state.projection?.cursor ?? null;\n state.requestCursor = state.projection?.cursor ?? undefined;\n}\n\n/** Replays a page that applied stale, up to the retry budget. */\nfunction retryStaleApply(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): ReconciliationStep {\n if (state.staleRetries >= MAX_STALE_RETRIES) {\n return localResult(input, state, { failed: true });\n }\n state.staleRetries += 1;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n}\n\nfunction isInvalidReadModelCursorFailure(\n result: RequestResult<OrganizationReadModelResponse>,\n): boolean {\n return (\n !result.ok &&\n result.kind === \"http\" &&\n result.status === 400 &&\n result.code === ORGANIZATION_READ_MODEL_ERROR_CODES.cursorInvalid\n );\n}\n\nasync function requestReadModelPage(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): Promise<PageRequestStep> {\n const result = await input.apiClient.getOrganizationReadModelResult(\n input.organizationId,\n state.requestCursor,\n { reportErrors: false },\n );\n if (input.stillCurrent?.() === false)\n return { kind: \"done\", value: undefined };\n if (result.ok) {\n return { kind: \"response\", response: result.data };\n }\n if (isOrganizationPresentationAccessDeniedFailure(result)) {\n const accessInput = organizationPresentationAccessInput(input);\n denyOrganizationPresentationAccess(accessInput, [\"readModel\", \"usage\"]);\n const repository = new OrganizationReadModelRepository(input.execSql);\n // The durable marker lands before the purge attempt: if the purge fails,\n // an offline restart must still refuse to serve the revoked projection.\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.recordOrganizationPresentationDenials(accessInput, [\n \"readModel\",\n \"usage\",\n ]),\n );\n } catch (error) {\n input.logError?.(\"Failed to record denied organization access\", error);\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.purgeOrganizationAccessProjection({\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n }),\n );\n } catch (error) {\n input.logError?.(\"Failed to purge denied organization access\", error);\n }\n return { kind: \"done\", value: null };\n }\n if (\n isInvalidReadModelCursorFailure(result) &&\n state.requestCursor !== undefined &&\n !state.retriedInvalidCursor\n ) {\n state.requestCursor = undefined;\n state.retriedInvalidCursor = true;\n return { kind: \"continue\" };\n }\n\n result.report();\n return localResult(input, state, { failed: true });\n}\n\nfunction responseMatchesRequest(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): boolean {\n if (response.organizationId !== input.organizationId) {\n input.logError?.(\n `Organization read-model response scope does not match ${input.organizationId}`,\n );\n return false;\n }\n if (response.hasMore && response.nextCursor === state.expectedLocalCursor) {\n input.logError?.(\"Organization read-model page did not advance its cursor\");\n return false;\n }\n return true;\n}\n\nfunction reconciliationIsCurrent(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): boolean {\n return isOrganizationPresentationAccessAttemptCurrent(\n organizationPresentationAccessInput(input),\n state.accessAttempt,\n );\n}\n\ntype ApplyResponseStep =\n | ReconciliationStep\n | {\n readonly kind: \"applied\";\n readonly result: ApplyOrganizationReadModelResponseResult;\n };\n\nasync function applyResponse(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ApplyResponseStep> {\n const repository = new OrganizationReadModelRepository(input.execSql);\n try {\n return {\n kind: \"applied\",\n result: await repository.applyOrganizationReadModelResponse({\n canCommit: input.stillCurrent,\n currentUserId: input.currentUserId,\n requestedCursor: state.expectedLocalCursor,\n response,\n }),\n };\n } catch (error) {\n input.logError?.(\"Failed to apply organization read-model response\", error);\n if (\n !(error instanceof OrganizationReadModelBindingError) ||\n state.retriedBindingFailure\n ) {\n return localResult(input, state, { failed: true });\n }\n state.retriedBindingFailure = true;\n await repository.purgeOrganizationReadModelProjection(input.organizationId);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.projection = null;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n }\n}\n\nasync function prepareDeniedProjectionForApply(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): Promise<ReconciliationStep | null> {\n if (state.preparedDeniedProjection) {\n return null;\n }\n try {\n // The apply that follows replaces the shared rows authoritatively, so\n // only this requester's row is dropped: another local identity sharing\n // the database keeps its access and reads the replacement.\n await new OrganizationReadModelRepository(\n input.execSql,\n ).purgeOrganizationReadModelProjection(input.organizationId, {\n onlyRequesterUserId: input.currentUserId,\n });\n } catch (error) {\n input.logError?.(\"Failed to replace denied organization read model\", error);\n return { kind: \"done\", value: null };\n }\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.expectedLocalCursor = null;\n state.preparedDeniedProjection = true;\n state.projection = null;\n return null;\n}\n\n/** The last page settles only if presentation access is still restorable. */\nfunction finalPageStep(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n accessInput: OrganizationPresentationAccessInput,\n): ReconciliationStep {\n return restoreOrganizationPresentationAccess(accessInput, state.accessAttempt)\n ? localResult(input, state, { failed: false })\n : { kind: \"done\", value: null };\n}\n\nasync function applyReadModelPage(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ReconciliationStep> {\n if (!responseMatchesRequest(input, state, response)) {\n return localResult(input, state, { failed: true });\n }\n\n const accessInput = organizationPresentationAccessInput(input);\n return runOrganizationPresentationMutation(input.execSql, async () => {\n if (\n !reconciliationIsCurrent(input, state) ||\n input.stillCurrent?.() === false\n )\n return { kind: \"done\", value: null };\n const preparation = await prepareDeniedProjectionForApply(input, state);\n if (preparation) return preparation;\n const applied = await applyResponse(input, state, response);\n if (applied.kind !== \"applied\") {\n return applied;\n }\n\n state.projection = await loadRawProjection(input);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n if (applied.result === \"stale\") {\n return retryStaleApply(input, state);\n }\n\n state.expectedLocalCursor = state.projection?.cursor ?? response.nextCursor;\n if (!response.hasMore) {\n return finalPageStep(input, state, accessInput);\n }\n state.requestCursor = response.nextCursor;\n return { kind: \"continue\" };\n });\n}\n\nexport async function loadLocalOrganizationDirectoryAndGroups(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationDirectoryAndGroups | null> {\n return toDirectoryAndGroups(await loadProjection(input));\n}\n\nexport async function loadLocalOrganizationGroupMembers(\n input: OrganizationReadModelProjectionInput & { readonly groupId: string },\n): Promise<OrganizationReadModelGroupMembers | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () =>\n new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelGroupMembers(\n input.organizationId,\n input.groupId,\n input.currentUserId,\n ),\n );\n}\n\n/**\n * Apply one page as a feed read from `requestedCursor` returns it, with no\n * request, while the projection still holds that cursor. Resolves `undefined`\n * when it is not applied; it is never retried.\n */\nexport async function applyOrganizationReadModelPageAt(\n input: ApplyReadModelPageInput & {\n readonly requestedCursor: string;\n readonly response: OrganizationReadModelResponse;\n },\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n organizationPresentationAccessInput(input),\n \"readModel\",\n );\n const projection = await loadProjection(input);\n if (projection?.cursor !== input.requestedCursor) return undefined;\n const applied = await applyReadModelPage(\n input,\n {\n accessAttempt,\n expectedLocalCursor: projection.cursor,\n preparedDeniedProjection: true,\n projection,\n requestCursor: projection.cursor,\n retriedBindingFailure: true,\n retriedInvalidCursor: true,\n staleRetries: MAX_STALE_RETRIES,\n },\n input.response,\n );\n return applied.kind === \"done\" ? applied.value : undefined;\n}\n\n/**\n * Resolves the reconciled projection, `null` when the pass completed\n * authoritatively with nothing presentable (including a denial that purged\n * the projection), or `undefined` when the feed failed — even when local\n * rows remain available. A failed pass must not count as caught up.\n */\nexport async function reconcileOrganizationDirectoryAndGroups(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessInput = organizationPresentationAccessInput(input);\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n accessInput,\n \"readModel\",\n );\n const state: ReconciliationState = {\n accessAttempt,\n expectedLocalCursor: null,\n preparedDeniedProjection: !accessAttempt.startedDenied,\n projection: await loadProjection(input),\n requestCursor: undefined,\n retriedBindingFailure: false,\n retriedInvalidCursor: false,\n staleRetries: 0,\n };\n resetRequestCursor(state);\n\n for (let page = 0; page < MAX_READ_MODEL_PAGES; page += 1) {\n const request = await requestReadModelPage(input, state);\n if (request.kind === \"done\") {\n return request.value;\n }\n if (request.kind === \"continue\") {\n continue;\n }\n const applied = await applyReadModelPage(input, state, request.response);\n if (applied.kind === \"done\") {\n return applied.value;\n }\n }\n\n input.logError?.(\n \"Organization read-model reconciliation exceeded page limit\",\n );\n const retained = localResult(input, state, { failed: true });\n return retained.kind === \"done\" ? retained.value : null;\n}\n"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { bytesToBase64 } from "../../internal/encoding/index.js";
|
|
2
|
-
import {
|
|
2
|
+
import { buildInitialDocumentCreateSeed } from "../documents/sync/initialSync.js";
|
|
3
3
|
import { createInitializedOrganizationProfileDocument, DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME, } from "../organizations/organizationProfile.js";
|
|
4
4
|
import { createInitializedRosterProfileDocument, DEFAULT_ROSTER_PROFILE_SELF_NICKNAME, } from "../organizations/rosterProfileContainer.js";
|
|
5
5
|
async function buildProvisionedDocumentRequest(input) {
|
|
6
6
|
return {
|
|
7
7
|
...input.materializedDocument.plan.request,
|
|
8
|
-
initialSync: await
|
|
8
|
+
initialSync: await buildInitialDocumentCreateSeed(input),
|
|
9
9
|
};
|
|
10
10
|
}
|
|
11
11
|
export async function buildProvisionedOrganizationProfile(input) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provisionedProfileDocument.js","sourceRoot":"","sources":["provisionedProfileDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAOpD,OA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aAAa,EAAE,WAAW,CAAC,aAAa;KACzC,CAAC,CAAC;IACH,OAAO,EAAE,GAAG,WAAW,EAAE,OAAO,EAAE,CAAC;AACrC,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { ProvisionedDocumentRequest } from \"@tearleads/validators/request\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type {\n DocumentCreateAuthor,\n MaterializedDocumentCreatePlan,\n} from \"../../data/documents/shared/types\";\nimport { buildInitialDocumentCreateSeed } from \"../documents/sync/initialSync\";\nimport {\n createInitializedOrganizationProfileDocument,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n} from \"../organizations/organizationProfile\";\nimport {\n createInitializedRosterProfileDocument,\n DEFAULT_ROSTER_PROFILE_SELF_NICKNAME,\n} from \"../organizations/rosterProfileContainer\";\n\ninterface ProvisionedProfileInput {\n author: DocumentCreateAuthor;\n containerProjection: ContainerWriterProjectionResponse;\n materializedDocument: MaterializedDocumentCreatePlan;\n}\n\nasync function buildProvisionedDocumentRequest(\n input: ProvisionedProfileInput & { initialUpdate: Uint8Array },\n): Promise<ProvisionedDocumentRequest> {\n return {\n ...input.materializedDocument.plan.request,\n initialSync: await buildInitialDocumentCreateSeed(input),\n };\n}\n\nexport async function buildProvisionedOrganizationProfile(\n input: ProvisionedProfileInput & { name?: string | undefined },\n) {\n const initialized = await createInitializedOrganizationProfileDocument({\n name: input.name ?? DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n });\n const request = await buildProvisionedDocumentRequest({\n ...input,\n initialUpdate: initialized.initialUpdate,\n });\n return { ...initialized, request };\n}\n\nexport async function buildProvisionedRosterProfile(\n input: ProvisionedProfileInput & {\n encapsulationPublicKey: Uint8Array;\n nickname?: string | undefined;\n },\n) {\n const initialized = await createInitializedRosterProfileDocument({\n encapsulationPublicKey: bytesToBase64(input.encapsulationPublicKey),\n isSelf: true,\n nickname: input.nickname ?? DEFAULT_ROSTER_PROFILE_SELF_NICKNAME,\n userId: input.author.signerUserId,\n });\n const request = await buildProvisionedDocumentRequest({\n ...input,\n initialUpdate: initialized.initialUpdate,\n });\n return { ...initialized, request };\n}\n"]}
|
|
@@ -147,10 +147,6 @@ export declare function buildInitialRootProvisioning(input: {
|
|
|
147
147
|
rootMetadataDocument: import("../../data/documents/shared/types.js").MaterializedDocumentCreatePlan;
|
|
148
148
|
rootMetadataDocumentRequest: {
|
|
149
149
|
initialSync: {
|
|
150
|
-
contentKeyEpoch: number;
|
|
151
|
-
expectedLinkSetManifestHash: string;
|
|
152
|
-
expectedTargetHash: string;
|
|
153
|
-
localVersionVector: string | null;
|
|
154
150
|
outgoingUpdates: {
|
|
155
151
|
encryptedData: string;
|
|
156
152
|
id: string;
|
|
@@ -162,69 +158,6 @@ export declare function buildInitialRootProvisioning(input: {
|
|
|
162
158
|
checkpointPayloadKind?: "full_history_snapshot" | undefined;
|
|
163
159
|
sourceVersionVector?: string | undefined;
|
|
164
160
|
}[];
|
|
165
|
-
supportsPullPagination: true;
|
|
166
|
-
authorizingContainerPathRefs?: {
|
|
167
|
-
containerId: string;
|
|
168
|
-
manifestHash: string;
|
|
169
|
-
}[][] | undefined;
|
|
170
|
-
containerRekeys?: {
|
|
171
|
-
body: unknown;
|
|
172
|
-
event: Record<string, unknown>;
|
|
173
|
-
expectedManifestHash: string;
|
|
174
|
-
keyEpoch: Record<string, unknown>;
|
|
175
|
-
keyring: Record<string, unknown> | null;
|
|
176
|
-
predecessorBridge: Record<string, unknown> | null;
|
|
177
|
-
principalPolicyRefs: {
|
|
178
|
-
principalType: "group" | "organization";
|
|
179
|
-
principalId: string;
|
|
180
|
-
version: number;
|
|
181
|
-
stateHash: string;
|
|
182
|
-
}[];
|
|
183
|
-
wraps: Record<string, unknown>[];
|
|
184
|
-
containerManifestHistoryRefs?: {
|
|
185
|
-
containerId: string;
|
|
186
|
-
manifestHash: string;
|
|
187
|
-
}[] | undefined;
|
|
188
|
-
destinationParentContainerPathRefs?: {
|
|
189
|
-
containerId: string;
|
|
190
|
-
manifestHash: string;
|
|
191
|
-
}[] | undefined;
|
|
192
|
-
parentContainerPathRefs?: {
|
|
193
|
-
containerId: string;
|
|
194
|
-
manifestHash: string;
|
|
195
|
-
}[] | undefined;
|
|
196
|
-
parentKekRef?: {
|
|
197
|
-
containerId: string;
|
|
198
|
-
containerKeyEpochId: string;
|
|
199
|
-
keyEpochHash: string;
|
|
200
|
-
} | null | undefined;
|
|
201
|
-
previousContainerPathRefs?: {
|
|
202
|
-
containerId: string;
|
|
203
|
-
manifestHash: string;
|
|
204
|
-
}[] | undefined;
|
|
205
|
-
previousManifestRef?: {
|
|
206
|
-
containerId: string;
|
|
207
|
-
manifestHash: string;
|
|
208
|
-
} | null | undefined;
|
|
209
|
-
userRecipientKeys?: Record<string, unknown>[] | undefined;
|
|
210
|
-
}[] | undefined;
|
|
211
|
-
contentKeyBundle?: {
|
|
212
|
-
contentKeyEpoch: number;
|
|
213
|
-
linkSetManifestHash: string;
|
|
214
|
-
targetHash: string;
|
|
215
|
-
targets: {
|
|
216
|
-
containerId: string;
|
|
217
|
-
containerKeyEpoch: number;
|
|
218
|
-
containerKeyEpochId: string;
|
|
219
|
-
containerManifestHash: string;
|
|
220
|
-
wrappedKey: string;
|
|
221
|
-
wrappingMetadata: Record<string, unknown>;
|
|
222
|
-
}[];
|
|
223
|
-
} | undefined;
|
|
224
|
-
historyMode?: "raw" | undefined;
|
|
225
|
-
inlineRekeyCommitId?: string | undefined;
|
|
226
|
-
minLsn?: string | undefined;
|
|
227
|
-
pullCursor?: string | undefined;
|
|
228
161
|
};
|
|
229
162
|
body: unknown;
|
|
230
163
|
contentKeyBundle: {
|
|
@@ -242,7 +175,6 @@ export declare function buildInitialRootProvisioning(input: {
|
|
|
242
175
|
};
|
|
243
176
|
event: Record<string, unknown>;
|
|
244
177
|
expectedManifestHash: string;
|
|
245
|
-
manifest: Record<string, unknown>;
|
|
246
178
|
authorizingContainerPathRefs?: {
|
|
247
179
|
containerId: string;
|
|
248
180
|
manifestHash: string;
|
|
@@ -4,7 +4,7 @@ import { deriveContainerSystemSlot, } from "../container-contents/index.js";
|
|
|
4
4
|
import { createInitializedContainerMetadataDocument } from "../container-contents/metadata/containerMetadataDocument.js";
|
|
5
5
|
import { buildContainerCreatePlan, buildRootContainerCreatePlan, childContainerWriterProjectionFromCreatePlan, rootContainerWriterProjectionFromCreatePlan, } from "../containers/index.js";
|
|
6
6
|
import { buildMaterializedDocumentCreatePlan } from "../documents/index.js";
|
|
7
|
-
import {
|
|
7
|
+
import { buildInitialDocumentCreateSeed } from "../documents/sync/initialSync.js";
|
|
8
8
|
import { getOrganizationProfileDocumentLocalId } from "../organizations/organizationProfile.js";
|
|
9
9
|
import { deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationRosterProfileContainerSystemSlot, getRosterProfileDocumentLocalId, ORGANIZATION_METADATA_CONTAINER_NAME, ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME, } from "../organizations/rosterProfileContainer.js";
|
|
10
10
|
import { buildProvisionedOrganizationProfile, buildProvisionedRosterProfile, } from "./provisionedProfileDocument.js";
|
|
@@ -66,7 +66,7 @@ async function buildProvisionedChildContainerCore(input) {
|
|
|
66
66
|
targetSecretKey: input.targetSecretKey,
|
|
67
67
|
trustedLocalProjection: true,
|
|
68
68
|
});
|
|
69
|
-
const initialMetadataSync = await
|
|
69
|
+
const initialMetadataSync = await buildInitialDocumentCreateSeed({
|
|
70
70
|
author: input.author,
|
|
71
71
|
containerProjection,
|
|
72
72
|
initialUpdate,
|
|
@@ -262,7 +262,7 @@ export async function buildInitialRootProvisioning(input) {
|
|
|
262
262
|
rootMetadataDocument,
|
|
263
263
|
rootMetadataDocumentRequest: {
|
|
264
264
|
...rootMetadataDocument.plan.request,
|
|
265
|
-
initialSync: await
|
|
265
|
+
initialSync: await buildInitialDocumentCreateSeed({
|
|
266
266
|
author: input.author,
|
|
267
267
|
containerProjection: rootContainerProjection,
|
|
268
268
|
initialUpdate: input.bootstrap.initialUpdate,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provisioningBootstrapBuilders.js","sourceRoot":"","sources":["provisioningBootstrapBuilders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EAEL,yBAAyB,GAC1B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,0CAA0C,EAAE,MAAM,0DAA0D,CAAC;AACtH,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,4CAA4C,EAC5C,2CAA2C,GAC5C,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,mCAAmC,EAAE,MAAM,cAAc,CAAC;AACnE,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAAE,qCAAqC,EAAE,MAAM,sCAAsC,CAAC;AAC7F,OAAO,EACL,6CAA6C,EAC7C,kDAAkD,EAClD,+BAA+B,EAC/B,oCAAoC,EACpC,0CAA0C,GAC3C,MAAM,yCAAyC,CAAC;AAQjD,OAAO,EACL,mCAAmC,EACnC,6BAA6B,GAC9B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,8CAA8C,EAAE,MAAM,0CAA0C,CAAC;AAqE1G;;;;;;GAMG;AACH,KAAK,UAAU,kCAAkC,CAAC,KAmBjD;IACC,MAAM,WAAW,GAAG,KAAK,CAAC,WAAW,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;IAC7D,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,0CAA0C,CACxE,WAAW,EACX;QACE,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,IAAI,EAAE,KAAK,CAAC,IAAI;KACjB,CACF,CAAC;IACF,MAAM,YAAY,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IACh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AC;QACrE,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,mBAAmB,EAAE,uBAAuB;QAC5C,UAAU,EAAE,KAAK,CAAC,SAAS,CAAC,kBAAkB;QAC9C,kBAAkB,EAAE,IAAI,GAAG,CAAC;YAC1B,CAAC,aAAa,CAAC,IAAI,CAAC,mBAAmB,EAAE,aAAa,CAAC,YAAY,CAAC;SACrE,CAAC;QACF,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,sBAAsB,EAAE,IAAI;KAC7B,CAAC,CAAC;IACH,OAAO;QACL,aAAa;QACb,uBAAuB;QACvB,oBAAoB;QACpB,2BAA2B,EAAE;YAC3B,GAAG,oBAAoB,CAAC,IAAI,CAAC,OAAO;YACpC,WAAW,EAAE,MAAM,+BAA+B,CAAC;gBACjD,MAAM,EAAE,KAAK,CAAC,MAAM;gBACpB,mBAAmB,EAAE,uBAAuB;gBAC5C,aAAa,EAAE,KAAK,CAAC,SAAS,CAAC,aAAa;gBAC5C,oBAAoB,EAAE,oBAAoB;aAC3C,CAAC;SACH;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { CreateOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport { deriveStableDocumentId } from \"../../data/documents/shared/stableDocumentId\";\nimport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"../container-contents\";\nimport { createInitializedContainerMetadataDocument } from \"../container-contents/metadata/containerMetadataDocument\";\nimport {\n buildContainerCreatePlan,\n buildRootContainerCreatePlan,\n childContainerWriterProjectionFromCreatePlan,\n rootContainerWriterProjectionFromCreatePlan,\n} from \"../containers\";\nimport type { resolveDocumentCreateAuthor } from \"../documents\";\nimport { buildMaterializedDocumentCreatePlan } from \"../documents\";\nimport { buildInitialDocumentSyncRequest } from \"../documents/sync/initialSync\";\nimport { getOrganizationProfileDocumentLocalId } from \"../organizations/organizationProfile\";\nimport {\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n getRosterProfileDocumentLocalId,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n} from \"../organizations/rosterProfileContainer\";\nimport type {\n InitialOrganizationMetadataBootstrap,\n InitialRootContainerCreatePlan,\n InitialRosterProfileBootstrap,\n InitialSystemContainerBootstrap,\n InitialSystemContainerCreatePlan,\n} from \"./organizationProvisioningArtifacts\";\nimport {\n buildProvisionedOrganizationProfile,\n buildProvisionedRosterProfile,\n} from \"./provisionedProfileDocument\";\nimport { verifiedPrincipalPolicyFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nimport type { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\ntype InitialRootContainerProjection = ReturnType<\n typeof rootContainerWriterProjectionFromCreatePlan\n>;\n\n/**\n * An app-owned system container to provision atomically with a new organization\n * (e.g. a trash bin). The client-sdk is agnostic to what these are:\n * the caller (the app, which owns the mini-app slot namespaces) declares each\n * one, and the provisioning path derives its per-user system slot, builds a\n * signed Admins-scoped child of root, and links it into the same transaction as\n * the rest of the organization bootstrap. The behavioral rules that govern a\n * system container are resolved client-side by slot, so provisioning needs only\n * the slot definition, display name, and icon — no rules travel to the server.\n */\nexport interface ProvisionedSystemContainerSpec {\n readonly slotDefinition: ContainerSystemSlotDefinition;\n readonly name: string;\n readonly icon: string | null;\n}\n\ninterface InitialOrganizationMetadataBootstrapInput {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId: string;\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n organizationProfileName?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}\n\ninterface InitialRosterProfileInput {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n encapsulationPublicKey: Uint8Array;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n rosterProfileNickname?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\ninterface ProvisionedChildContainerCore {\n containerId: string;\n containerMetadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >;\n containerMetadataInitialUpdate: Uint8Array;\n containerPlan: InitialSystemContainerCreatePlan;\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n containerRequest: {\n systemSlot: ContainerSystemSlot;\n container: InitialSystemContainerCreatePlan[\"plan\"][\"request\"];\n initialMetadataSync: Awaited<\n ReturnType<typeof buildInitialDocumentSyncRequest>\n >;\n metadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >[\"plan\"][\"request\"];\n };\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n systemSlot: ContainerSystemSlot;\n}\n\n/**\n * The shared spine of every provisioned system child container: mint the\n * container and its metadata document under root, project the writer view,\n * and assemble the create request. Callers differ only in slot derivation,\n * display metadata, authorizing policies, an optional managed read grant, and\n * what they attach afterwards (roster/org profile documents).\n */\nasync function buildProvisionedChildContainerCore(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId?: string | undefined;\n icon: string | null;\n managedPrincipalGrant?: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"managedPrincipalGrant\"];\n name: string;\n principalPolicies: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"principalPolicies\"];\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n systemSlot: ContainerSystemSlot;\n targetSecretKey: Uint8Array;\n independentMetadataGroups?: {\n adminGroup: CreateOrganizationGroupRequest;\n memberGroup: CreateOrganizationGroupRequest;\n };\n}): Promise<ProvisionedChildContainerCore> {\n const containerId = input.containerId ?? crypto.randomUUID();\n const { initialUpdate } = await createInitializedContainerMetadataDocument(\n containerId,\n {\n icon: input.icon,\n name: input.name,\n },\n );\n const containerKey = crypto.getRandomValues(new Uint8Array(32));\n const containerPlan: InitialSystemContainerCreatePlan = {\n containerKey,\n plan: input.independentMetadataGroups\n ? (\n await buildRootContainerCreatePlan({\n ...input.independentMetadataGroups,\n author: input.author,\n containerId,\n containerKey,\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n recipientEncapsulationPublicKey: base64ToBytes(\n input.independentMetadataGroups.adminGroup.initialGroupPolicy\n .state.encapsulationPublicKey,\n ),\n })\n ).plan\n : await buildContainerCreatePlan({\n author: input.author,\n containerId,\n containerKey,\n ...(input.managedPrincipalGrant\n ? { managedPrincipalGrant: input.managedPrincipalGrant }\n : {}),\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n parentProjection: input.rootContainerProjection,\n principalPolicies: input.principalPolicies,\n }),\n };\n const containerProjection = input.independentMetadataGroups\n ? rootContainerWriterProjectionFromCreatePlan(containerPlan.plan)\n : childContainerWriterProjectionFromCreatePlan({\n materializedPlan: containerPlan,\n parentProjection: input.rootContainerProjection,\n });\n const knownContainerKeks = new Map([\n [containerPlan.plan.containerKeyEpochId, containerPlan.containerKey],\n ]);\n const containerMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection,\n documentId: containerPlan.plan.metadataDocumentId,\n knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const initialMetadataSync = await buildInitialDocumentSyncRequest({\n author: input.author,\n containerProjection,\n initialUpdate,\n materializedDocument: containerMetadataDocument,\n });\n return {\n containerId,\n containerMetadataDocument,\n containerMetadataInitialUpdate: initialUpdate,\n containerPlan,\n containerProjection,\n containerRequest: {\n systemSlot: input.systemSlot,\n container: containerPlan.plan.request,\n initialMetadataSync,\n metadataDocument: containerMetadataDocument.plan.request,\n },\n knownContainerKeks,\n systemSlot: input.systemSlot,\n };\n}\n\nexport async function buildInitialRosterProfileBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n encapsulationPublicKey: Uint8Array;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rosterProfileNickname?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}): Promise<InitialRosterProfileBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: null,\n name: ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationRosterProfileContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { profile, rosterProfileDocument } = await buildInitialRosterProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n knownContainerKeks: core.knownContainerKeks,\n rosterProfileNickname: input.rosterProfileNickname,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n profileDocument: rosterProfileDocument,\n profileDocumentInitialUpdate: profile.initialUpdate,\n profileDocumentRequest: profile.request,\n systemSlot: core.systemSlot,\n };\n}\n\nasync function buildInitialRosterProfile(input: InitialRosterProfileInput) {\n const rosterProfileDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await deriveStableDocumentId(\n getRosterProfileDocumentLocalId({\n organizationId: input.author.organizationId,\n userId: input.author.signerUserId,\n }),\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const profile = await buildProvisionedRosterProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n materializedDocument: rosterProfileDocument,\n nickname: input.rosterProfileNickname,\n });\n return { profile, rosterProfileDocument };\n}\n\nexport async function buildInitialSystemContainerBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n signingPrivateKey: Uint8Array;\n spec: ProvisionedSystemContainerSpec;\n targetSecretKey: Uint8Array;\n}): Promise<InitialSystemContainerBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: input.spec.icon,\n name: input.spec.name,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveContainerSystemSlot({\n definition: input.spec.slotDefinition,\n secretKey: input.signingPrivateKey,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n icon: input.spec.icon,\n name: input.spec.name,\n systemSlot: core.systemSlot,\n };\n}\n\nfunction stableOrganizationProfileId(organizationId: string): Promise<string> {\n return deriveStableDocumentId(\n getOrganizationProfileDocumentLocalId({ organizationId }),\n );\n}\n\nasync function buildInitialOrganizationProfile(input: {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n organizationProfileName?: string | undefined;\n targetSecretKey: Uint8Array;\n}) {\n const organizationProfileDocument = await buildMaterializedDocumentCreatePlan(\n {\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await stableOrganizationProfileId(\n input.author.organizationId,\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n },\n );\n const profile = await buildProvisionedOrganizationProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n materializedDocument: organizationProfileDocument,\n name: input.organizationProfileName,\n });\n return { organizationProfileDocument, profile };\n}\n\n/**\n * Organization labels use an independent system root with Admins/admin and\n * Members/read grants. Personal root shares and rotations cannot expose or\n * strand organization metadata; Members changes still rotate its own KEK.\n */\nexport async function buildInitialOrganizationMetadataBootstrap(\n input: InitialOrganizationMetadataBootstrapInput,\n): Promise<InitialOrganizationMetadataBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n containerId: input.containerId,\n icon: null,\n independentMetadataGroups: {\n adminGroup: input.initialAdminGroup,\n memberGroup: input.initialMemberGroup,\n },\n name: ORGANIZATION_METADATA_CONTAINER_NAME,\n // Both reserved groups receive explicit grants on the independent root.\n principalPolicies: await Promise.all([\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialAdminGroup),\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialMemberGroup),\n ]),\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { organizationProfileDocument, profile } =\n await buildInitialOrganizationProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n knownContainerKeks: core.knownContainerKeks,\n organizationProfileName: input.organizationProfileName,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n organizationProfileDocument,\n organizationProfileDocumentRequest: profile.request,\n organizationProfileSnapshot: profile.snapshot,\n systemSlot: core.systemSlot,\n };\n}\n\nexport async function buildInitialRootProvisioning(input: {\n adminGroup: CreateOrganizationGroupRequest;\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n bootstrap: Awaited<ReturnType<typeof createInitialRootMetadataBootstrap>>;\n recipientEncapsulationPublicKey: Uint8Array;\n rootContainerId: string;\n targetSecretKey: Uint8Array;\n}) {\n const rootContainer = await buildRootContainerCreatePlan({\n adminGroup: input.adminGroup,\n author: input.author,\n containerId: input.rootContainerId,\n metadataDocumentId: input.bootstrap.metadataDocumentId,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n });\n const rootContainerProjection = rootContainerWriterProjectionFromCreatePlan(\n rootContainer.plan,\n );\n const rootMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: rootContainerProjection,\n documentId: input.bootstrap.metadataDocumentId,\n knownContainerKeks: new Map([\n [rootContainer.plan.containerKeyEpochId, rootContainer.containerKey],\n ]),\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n return {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest: {\n ...rootMetadataDocument.plan.request,\n initialSync: await buildInitialDocumentSyncRequest({\n author: input.author,\n containerProjection: rootContainerProjection,\n initialUpdate: input.bootstrap.initialUpdate,\n materializedDocument: rootMetadataDocument,\n }),\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provisioningBootstrapBuilders.js","sourceRoot":"","sources":["provisioningBootstrapBuilders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EAEL,yBAAyB,GAC1B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,0CAA0C,EAAE,MAAM,0DAA0D,CAAC;AACtH,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,4CAA4C,EAC5C,2CAA2C,GAC5C,M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AAC,OAAO;YACpC,WAAW,EAAE,MAAM,8BAA8B,CAAC;gBAChD,MAAM,EAAE,KAAK,CAAC,MAAM;gBACpB,mBAAmB,EAAE,uBAAuB;gBAC5C,aAAa,EAAE,KAAK,CAAC,SAAS,CAAC,aAAa;gBAC5C,oBAAoB,EAAE,oBAAoB;aAC3C,CAAC;SACH;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { CreateOrganizationGroupRequest } from \"@tearleads/validators/request\";\nimport { deriveStableDocumentId } from \"../../data/documents/shared/stableDocumentId\";\nimport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"../container-contents\";\nimport { createInitializedContainerMetadataDocument } from \"../container-contents/metadata/containerMetadataDocument\";\nimport {\n buildContainerCreatePlan,\n buildRootContainerCreatePlan,\n childContainerWriterProjectionFromCreatePlan,\n rootContainerWriterProjectionFromCreatePlan,\n} from \"../containers\";\nimport type { resolveDocumentCreateAuthor } from \"../documents\";\nimport { buildMaterializedDocumentCreatePlan } from \"../documents\";\nimport { buildInitialDocumentCreateSeed } from \"../documents/sync/initialSync\";\nimport { getOrganizationProfileDocumentLocalId } from \"../organizations/organizationProfile\";\nimport {\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n getRosterProfileDocumentLocalId,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n} from \"../organizations/rosterProfileContainer\";\nimport type {\n InitialOrganizationMetadataBootstrap,\n InitialRootContainerCreatePlan,\n InitialRosterProfileBootstrap,\n InitialSystemContainerBootstrap,\n InitialSystemContainerCreatePlan,\n} from \"./organizationProvisioningArtifacts\";\nimport {\n buildProvisionedOrganizationProfile,\n buildProvisionedRosterProfile,\n} from \"./provisionedProfileDocument\";\nimport { verifiedPrincipalPolicyFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nimport type { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\ntype InitialRootContainerProjection = ReturnType<\n typeof rootContainerWriterProjectionFromCreatePlan\n>;\n\n/**\n * An app-owned system container to provision atomically with a new organization\n * (e.g. a trash bin). The client-sdk is agnostic to what these are:\n * the caller (the app, which owns the mini-app slot namespaces) declares each\n * one, and the provisioning path derives its per-user system slot, builds a\n * signed Admins-scoped child of root, and links it into the same transaction as\n * the rest of the organization bootstrap. The behavioral rules that govern a\n * system container are resolved client-side by slot, so provisioning needs only\n * the slot definition, display name, and icon — no rules travel to the server.\n */\nexport interface ProvisionedSystemContainerSpec {\n readonly slotDefinition: ContainerSystemSlotDefinition;\n readonly name: string;\n readonly icon: string | null;\n}\n\ninterface InitialOrganizationMetadataBootstrapInput {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId: string;\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n organizationProfileName?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}\n\ninterface InitialRosterProfileInput {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n encapsulationPublicKey: Uint8Array;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n rosterProfileNickname?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\ninterface ProvisionedChildContainerCore {\n containerId: string;\n containerMetadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >;\n containerMetadataInitialUpdate: Uint8Array;\n containerPlan: InitialSystemContainerCreatePlan;\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n containerRequest: {\n systemSlot: ContainerSystemSlot;\n container: InitialSystemContainerCreatePlan[\"plan\"][\"request\"];\n initialMetadataSync: Awaited<\n ReturnType<typeof buildInitialDocumentCreateSeed>\n >;\n metadataDocument: Awaited<\n ReturnType<typeof buildMaterializedDocumentCreatePlan>\n >[\"plan\"][\"request\"];\n };\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n systemSlot: ContainerSystemSlot;\n}\n\n/**\n * The shared spine of every provisioned system child container: mint the\n * container and its metadata document under root, project the writer view,\n * and assemble the create request. Callers differ only in slot derivation,\n * display metadata, authorizing policies, an optional managed read grant, and\n * what they attach afterwards (roster/org profile documents).\n */\nasync function buildProvisionedChildContainerCore(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n containerId?: string | undefined;\n icon: string | null;\n managedPrincipalGrant?: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"managedPrincipalGrant\"];\n name: string;\n principalPolicies: Parameters<\n typeof buildContainerCreatePlan\n >[0][\"principalPolicies\"];\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n systemSlot: ContainerSystemSlot;\n targetSecretKey: Uint8Array;\n independentMetadataGroups?: {\n adminGroup: CreateOrganizationGroupRequest;\n memberGroup: CreateOrganizationGroupRequest;\n };\n}): Promise<ProvisionedChildContainerCore> {\n const containerId = input.containerId ?? crypto.randomUUID();\n const { initialUpdate } = await createInitializedContainerMetadataDocument(\n containerId,\n {\n icon: input.icon,\n name: input.name,\n },\n );\n const containerKey = crypto.getRandomValues(new Uint8Array(32));\n const containerPlan: InitialSystemContainerCreatePlan = {\n containerKey,\n plan: input.independentMetadataGroups\n ? (\n await buildRootContainerCreatePlan({\n ...input.independentMetadataGroups,\n author: input.author,\n containerId,\n containerKey,\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n recipientEncapsulationPublicKey: base64ToBytes(\n input.independentMetadataGroups.adminGroup.initialGroupPolicy\n .state.encapsulationPublicKey,\n ),\n })\n ).plan\n : await buildContainerCreatePlan({\n author: input.author,\n containerId,\n containerKey,\n ...(input.managedPrincipalGrant\n ? { managedPrincipalGrant: input.managedPrincipalGrant }\n : {}),\n metadataDocumentId: containerId,\n systemSlot: input.systemSlot,\n parentProjection: input.rootContainerProjection,\n principalPolicies: input.principalPolicies,\n }),\n };\n const containerProjection = input.independentMetadataGroups\n ? rootContainerWriterProjectionFromCreatePlan(containerPlan.plan)\n : childContainerWriterProjectionFromCreatePlan({\n materializedPlan: containerPlan,\n parentProjection: input.rootContainerProjection,\n });\n const knownContainerKeks = new Map([\n [containerPlan.plan.containerKeyEpochId, containerPlan.containerKey],\n ]);\n const containerMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection,\n documentId: containerPlan.plan.metadataDocumentId,\n knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const initialMetadataSync = await buildInitialDocumentCreateSeed({\n author: input.author,\n containerProjection,\n initialUpdate,\n materializedDocument: containerMetadataDocument,\n });\n return {\n containerId,\n containerMetadataDocument,\n containerMetadataInitialUpdate: initialUpdate,\n containerPlan,\n containerProjection,\n containerRequest: {\n systemSlot: input.systemSlot,\n container: containerPlan.plan.request,\n initialMetadataSync,\n metadataDocument: containerMetadataDocument.plan.request,\n },\n knownContainerKeks,\n systemSlot: input.systemSlot,\n };\n}\n\nexport async function buildInitialRosterProfileBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n encapsulationPublicKey: Uint8Array;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rosterProfileNickname?: string | undefined;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n targetSecretKey: Uint8Array;\n}): Promise<InitialRosterProfileBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: null,\n name: ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationRosterProfileContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { profile, rosterProfileDocument } = await buildInitialRosterProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n knownContainerKeks: core.knownContainerKeks,\n rosterProfileNickname: input.rosterProfileNickname,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n profileDocument: rosterProfileDocument,\n profileDocumentInitialUpdate: profile.initialUpdate,\n profileDocumentRequest: profile.request,\n systemSlot: core.systemSlot,\n };\n}\n\nasync function buildInitialRosterProfile(input: InitialRosterProfileInput) {\n const rosterProfileDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await deriveStableDocumentId(\n getRosterProfileDocumentLocalId({\n organizationId: input.author.organizationId,\n userId: input.author.signerUserId,\n }),\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n const profile = await buildProvisionedRosterProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n encapsulationPublicKey: input.encapsulationPublicKey,\n materializedDocument: rosterProfileDocument,\n nickname: input.rosterProfileNickname,\n });\n return { profile, rosterProfileDocument };\n}\n\nexport async function buildInitialSystemContainerBootstrap(input: {\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n initialAdminGroup: CreateOrganizationGroupRequest;\n rootContainer: InitialRootContainerCreatePlan;\n rootContainerProjection: InitialRootContainerProjection;\n signingPrivateKey: Uint8Array;\n spec: ProvisionedSystemContainerSpec;\n targetSecretKey: Uint8Array;\n}): Promise<InitialSystemContainerBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n icon: input.spec.icon,\n name: input.spec.name,\n principalPolicies: [\n await verifiedPrincipalPolicyFromInitialGroupRequest(\n input.initialAdminGroup,\n ),\n ],\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveContainerSystemSlot({\n definition: input.spec.slotDefinition,\n secretKey: input.signingPrivateKey,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n icon: input.spec.icon,\n name: input.spec.name,\n systemSlot: core.systemSlot,\n };\n}\n\nfunction stableOrganizationProfileId(organizationId: string): Promise<string> {\n return deriveStableDocumentId(\n getOrganizationProfileDocumentLocalId({ organizationId }),\n );\n}\n\nasync function buildInitialOrganizationProfile(input: {\n author: InitialOrganizationMetadataBootstrapInput[\"author\"];\n containerProjection: ReturnType<\n typeof childContainerWriterProjectionFromCreatePlan\n >;\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n organizationProfileName?: string | undefined;\n targetSecretKey: Uint8Array;\n}) {\n const organizationProfileDocument = await buildMaterializedDocumentCreatePlan(\n {\n author: input.author,\n containerProjection: input.containerProjection,\n documentId: await stableOrganizationProfileId(\n input.author.organizationId,\n ),\n knownContainerKeks: input.knownContainerKeks,\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n },\n );\n const profile = await buildProvisionedOrganizationProfile({\n author: input.author,\n containerProjection: input.containerProjection,\n materializedDocument: organizationProfileDocument,\n name: input.organizationProfileName,\n });\n return { organizationProfileDocument, profile };\n}\n\n/**\n * Organization labels use an independent system root with Admins/admin and\n * Members/read grants. Personal root shares and rotations cannot expose or\n * strand organization metadata; Members changes still rotate its own KEK.\n */\nexport async function buildInitialOrganizationMetadataBootstrap(\n input: InitialOrganizationMetadataBootstrapInput,\n): Promise<InitialOrganizationMetadataBootstrap> {\n const core = await buildProvisionedChildContainerCore({\n author: input.author,\n containerId: input.containerId,\n icon: null,\n independentMetadataGroups: {\n adminGroup: input.initialAdminGroup,\n memberGroup: input.initialMemberGroup,\n },\n name: ORGANIZATION_METADATA_CONTAINER_NAME,\n // Both reserved groups receive explicit grants on the independent root.\n principalPolicies: await Promise.all([\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialAdminGroup),\n verifiedPrincipalPolicyFromInitialGroupRequest(input.initialMemberGroup),\n ]),\n rootContainer: input.rootContainer,\n rootContainerProjection: input.rootContainerProjection,\n systemSlot: await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: input.author.organizationId,\n }),\n targetSecretKey: input.targetSecretKey,\n });\n const { organizationProfileDocument, profile } =\n await buildInitialOrganizationProfile({\n author: input.author,\n containerProjection: core.containerProjection,\n knownContainerKeks: core.knownContainerKeks,\n organizationProfileName: input.organizationProfileName,\n targetSecretKey: input.targetSecretKey,\n });\n return {\n containerId: core.containerId,\n containerMetadataDocument: core.containerMetadataDocument,\n containerMetadataInitialUpdate: core.containerMetadataInitialUpdate,\n containerPlan: core.containerPlan,\n containerRequest: core.containerRequest,\n organizationProfileDocument,\n organizationProfileDocumentRequest: profile.request,\n organizationProfileSnapshot: profile.snapshot,\n systemSlot: core.systemSlot,\n };\n}\n\nexport async function buildInitialRootProvisioning(input: {\n adminGroup: CreateOrganizationGroupRequest;\n author: NonNullable<ReturnType<typeof resolveDocumentCreateAuthor>>;\n bootstrap: Awaited<ReturnType<typeof createInitialRootMetadataBootstrap>>;\n recipientEncapsulationPublicKey: Uint8Array;\n rootContainerId: string;\n targetSecretKey: Uint8Array;\n}) {\n const rootContainer = await buildRootContainerCreatePlan({\n adminGroup: input.adminGroup,\n author: input.author,\n containerId: input.rootContainerId,\n metadataDocumentId: input.bootstrap.metadataDocumentId,\n recipientEncapsulationPublicKey: input.recipientEncapsulationPublicKey,\n });\n const rootContainerProjection = rootContainerWriterProjectionFromCreatePlan(\n rootContainer.plan,\n );\n const rootMetadataDocument = await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection: rootContainerProjection,\n documentId: input.bootstrap.metadataDocumentId,\n knownContainerKeks: new Map([\n [rootContainer.plan.containerKeyEpochId, rootContainer.containerKey],\n ]),\n targetSecretKey: input.targetSecretKey,\n trustedLocalProjection: true,\n });\n return {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest: {\n ...rootMetadataDocument.plan.request,\n initialSync: await buildInitialDocumentCreateSeed({\n author: input.author,\n containerProjection: rootContainerProjection,\n initialUpdate: input.bootstrap.initialUpdate,\n materializedDocument: rootMetadataDocument,\n }),\n },\n };\n}\n"]}
|
|
@@ -22,6 +22,8 @@ export async function registerIdentity(input) {
|
|
|
22
22
|
signingKeyPair: input.signingKeyPair,
|
|
23
23
|
userId: newUserId,
|
|
24
24
|
});
|
|
25
|
+
if (input.isIdentityCurrent?.() === false)
|
|
26
|
+
return null;
|
|
25
27
|
const response = await input.apiClient.registerUser(newUserId, artifacts.organizationId, input.containerId, input.signingKeyPair.signingPublicKey, input.encapsulationKeyPair.publicKey, artifacts.initialAdminGroup, artifacts.initialMemberGroup, artifacts.initialOrganizationPolicy, artifacts.initialRootContainer, artifacts.rootMetadataDocumentRequest, artifacts.rosterProfileBootstrap.containerRequest, artifacts.rosterProfileBootstrap.profileDocumentRequest, artifacts.organizationMetadataBootstrap.containerRequest, artifacts.organizationMetadataBootstrap.organizationProfileDocumentRequest, artifacts.systemContainerBootstraps.map((systemContainer) => systemContainer.containerRequest));
|
|
26
28
|
if (!response) {
|
|
27
29
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registerIdentity.js","sourceRoot":"","sources":["registerIdentity.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAU3B,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,sCAAsC,EAAE,MAAM,4B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EAAE,SAAS,CAAC,yBAAyB;QAC9D,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,6BAA6B,EAAE,SAAS,CAAC,6BAA6B;QACtE,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,QAAQ;QACR,aAAa,EAAE,SAAS,CAAC,aAAa;QACtC,oBAAoB,EAAE,SAAS,CAAC,oBAAoB;QACpD,2BAA2B,EAAE,SAAS,CAAC,2BAA2B;QAClE,sBAAsB,EAAE,SAAS,CAAC,sBAAsB;QACxD,yBAAyB,EAAE,SAAS,CAAC,yBAAyB;KAC/D,CAAC,CAAC;IAEH,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n type EncapsulationKeyPair,\n KeyingVerificationError,\n type SigningKeyPair,\n} from \"@tearleads/crypto\";\nimport type {\n ProvisionedDocumentRequest,\n ProvisionedSystemContainerRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { RegistrationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport type { ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type { LocalUserIdentityCandidate } from \"../../data/trustedUserIdentity\";\nimport { validateUserIdentityKeys } from \"../../data/trustedUserIdentity\";\nimport { buildOrganizationProvisioningArtifacts } from \"./organizationProvisioning\";\nimport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nimport type { ProvisionedStatePrimer } from \"./provisionedStatePrimer\";\nimport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\nexport interface RegistrationApi {\n registerUser(\n userId: string,\n organizationId: string,\n rootContainerId: string,\n signingPublicKey: Uint8Array,\n encapsulationPublicKey: Uint8Array,\n initialAdminGroup: RegistrationRequest[\"initialAdminGroup\"],\n initialMemberGroup: RegistrationRequest[\"initialMemberGroup\"],\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"],\n initialRootContainer: RegistrationRequest[\"initialRootContainer\"],\n initialRootMetadataDocument: ProvisionedDocumentRequest,\n initialRosterProfileContainer: RegistrationRequest[\"initialRosterProfileContainer\"],\n initialRosterProfileDocument: ProvisionedDocumentRequest | undefined,\n initialOrganizationMetadataContainer: ProvisionedSystemContainerRequest,\n initialOrganizationProfileDocument?: ProvisionedDocumentRequest | undefined,\n initialSystemContainers?: ProvisionedSystemContainerRequest[] | undefined,\n ): Promise<RegistrationResponse | null>;\n}\n\nexport interface RegisterIdentityInput {\n identityTrustDomain: string;\n apiClient: RegistrationApi;\n containerId: string;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n /**\n * Reports whether the identity that started this registration is still\n * current. Forwarded to the bootstrap persist's in-mutex currency check,\n * so an identity replaced while the persist waits for the mutation queue\n * cannot write its bootstrap through a client the replacement owns.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /**\n * Overrides the seeded personal-org profile name; defaults to \"Personal Org\".\n */\n organizationProfileName?: string | undefined;\n pinLocalUserIdentity: (\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ) => Promise<void>;\n /** Seeds what the committed bootstrap already proves. */\n primeProvisionedState?: ProvisionedStatePrimer | undefined;\n /**\n * App-owned system containers to provision atomically with the personal\n * organization (e.g. a trash bin). See {@link ProvisionedSystemContainerSpec}.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /**\n * Overrides the seeded self roster-profile nickname; defaults to \"You\". The\n * demo host passes each pane's peer-labeled self name (\"Peer 1 (You)\").\n */\n rosterProfileNickname?: string | undefined;\n signingKeyFingerprint?: string | null | undefined;\n signingKeyPair: SigningKeyPair;\n}\n\nexport async function registerIdentity(\n input: RegisterIdentityInput,\n): Promise<RegistrationResponse | null> {\n input.log?.(\"Registering identity...\");\n await validateUserIdentityKeys({\n candidate: {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingKeyFingerprint: input.signingKeyFingerprint,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n },\n });\n\n const newUserId = crypto.randomUUID();\n const artifacts = await buildOrganizationProvisioningArtifacts({\n identityTrustDomain: input.identityTrustDomain,\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId: input.containerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: newUserId,\n });\n\n const response = await input.apiClient.registerUser(\n newUserId,\n artifacts.organizationId,\n input.containerId,\n input.signingKeyPair.signingPublicKey,\n input.encapsulationKeyPair.publicKey,\n artifacts.initialAdminGroup,\n artifacts.initialMemberGroup,\n artifacts.initialOrganizationPolicy,\n artifacts.initialRootContainer,\n artifacts.rootMetadataDocumentRequest,\n artifacts.rosterProfileBootstrap.containerRequest,\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n artifacts.organizationMetadataBootstrap.containerRequest,\n artifacts.organizationMetadataBootstrap.organizationProfileDocumentRequest,\n artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n );\n if (!response) {\n return null;\n }\n if (response.userId !== newUserId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Registration response user does not match the requested identity\",\n );\n }\n // Pinned only once the server has confirmed this user, and before anything\n // is persisted under it. The trust store binds each signing key to one user,\n // so a pin for an id the server never accepted — a retry after a lost\n // response, or a restored key that is already registered — would later\n // refuse the key's real user at login. Like the persistence below, it is a\n // durable write, so it is skipped once the registering identity has been\n // replaced: the caller discards this result.\n if (input.isIdentityCurrent?.() ?? true) {\n await input.pinLocalUserIdentity(newUserId, {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n }\n\n input.log?.(`Key registered (${response.userId})`);\n await persistOrganizationProvisioningState({\n bootstrap: artifacts.bootstrap,\n canStartDurableMutation: input.isIdentityCurrent,\n commitLsn: response.commitLsn,\n onPersistQueued: input.onPersistQueued,\n containerId: input.containerId,\n dbClient: input.dbClient,\n documentProjectors: input.documentProjectors,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n log: input.log,\n logError: input.logError,\n organizationMetadataBootstrap: artifacts.organizationMetadataBootstrap,\n primeProvisionedState: input.primeProvisionedState,\n response,\n rootContainer: artifacts.rootContainer,\n rootMetadataDocument: artifacts.rootMetadataDocument,\n rootMetadataDocumentRequest: artifacts.rootMetadataDocumentRequest,\n rosterProfileBootstrap: artifacts.rosterProfileBootstrap,\n systemContainerBootstraps: artifacts.systemContainerBootstraps,\n });\n\n return response;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"registerIdentity.js","sourceRoot":"","sources":["registerIdentity.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAU3B,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,sCAAsC,EAAE,MAAM,4BAA4B,CAAC;AACpF,OAAO,EAAE,oCAAoC,EAAE,MAAM,uCAAuC,CAAC;AAoE7F,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,KAA4B;IAE5B,KAAK,CAAC,GAAG,EAAE,CAAC,yBAAyB,CAAC,CAAC;IACvC,MAAM,wBAAwB,CAAC;QAC7B,SAAS,EAAE;YACT,sBAAsB,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;YAC5D,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;YAClD,gBAAgB,EAAE,KAAK,CAAC,cAAc,CAAC,gBAA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,EAAE,SAAS,CAAC,2BAA2B;QAClE,sBAAsB,EAAE,SAAS,CAAC,sBAAsB;QACxD,yBAAyB,EAAE,SAAS,CAAC,yBAAyB;KAC/D,CAAC,CAAC;IAEH,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n type EncapsulationKeyPair,\n KeyingVerificationError,\n type SigningKeyPair,\n} from \"@tearleads/crypto\";\nimport type {\n ProvisionedDocumentRequest,\n ProvisionedSystemContainerRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { RegistrationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport type { ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type { LocalUserIdentityCandidate } from \"../../data/trustedUserIdentity\";\nimport { validateUserIdentityKeys } from \"../../data/trustedUserIdentity\";\nimport { buildOrganizationProvisioningArtifacts } from \"./organizationProvisioning\";\nimport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nimport type { ProvisionedStatePrimer } from \"./provisionedStatePrimer\";\nimport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\nexport interface RegistrationApi {\n registerUser(\n userId: string,\n organizationId: string,\n rootContainerId: string,\n signingPublicKey: Uint8Array,\n encapsulationPublicKey: Uint8Array,\n initialAdminGroup: RegistrationRequest[\"initialAdminGroup\"],\n initialMemberGroup: RegistrationRequest[\"initialMemberGroup\"],\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"],\n initialRootContainer: RegistrationRequest[\"initialRootContainer\"],\n initialRootMetadataDocument: ProvisionedDocumentRequest,\n initialRosterProfileContainer: RegistrationRequest[\"initialRosterProfileContainer\"],\n initialRosterProfileDocument: ProvisionedDocumentRequest | undefined,\n initialOrganizationMetadataContainer: ProvisionedSystemContainerRequest,\n initialOrganizationProfileDocument?: ProvisionedDocumentRequest | undefined,\n initialSystemContainers?: ProvisionedSystemContainerRequest[] | undefined,\n ): Promise<RegistrationResponse | null>;\n}\n\nexport interface RegisterIdentityInput {\n identityTrustDomain: string;\n apiClient: RegistrationApi;\n containerId: string;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n /**\n * Reports whether the identity that started this registration is still\n * current. Forwarded to the bootstrap persist's in-mutex currency check,\n * so an identity replaced while the persist waits for the mutation queue\n * cannot write its bootstrap through a client the replacement owns.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /**\n * Overrides the seeded personal-org profile name; defaults to \"Personal Org\".\n */\n organizationProfileName?: string | undefined;\n pinLocalUserIdentity: (\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ) => Promise<void>;\n /** Seeds what the committed bootstrap already proves. */\n primeProvisionedState?: ProvisionedStatePrimer | undefined;\n /**\n * App-owned system containers to provision atomically with the personal\n * organization (e.g. a trash bin). See {@link ProvisionedSystemContainerSpec}.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /**\n * Overrides the seeded self roster-profile nickname; defaults to \"You\". The\n * demo host passes each pane's peer-labeled self name (\"Peer 1 (You)\").\n */\n rosterProfileNickname?: string | undefined;\n signingKeyFingerprint?: string | null | undefined;\n signingKeyPair: SigningKeyPair;\n}\n\nexport async function registerIdentity(\n input: RegisterIdentityInput,\n): Promise<RegistrationResponse | null> {\n input.log?.(\"Registering identity...\");\n await validateUserIdentityKeys({\n candidate: {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingKeyFingerprint: input.signingKeyFingerprint,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n },\n });\n\n const newUserId = crypto.randomUUID();\n const artifacts = await buildOrganizationProvisioningArtifacts({\n identityTrustDomain: input.identityTrustDomain,\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId: input.containerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: newUserId,\n });\n\n if (input.isIdentityCurrent?.() === false) return null;\n const response = await input.apiClient.registerUser(\n newUserId,\n artifacts.organizationId,\n input.containerId,\n input.signingKeyPair.signingPublicKey,\n input.encapsulationKeyPair.publicKey,\n artifacts.initialAdminGroup,\n artifacts.initialMemberGroup,\n artifacts.initialOrganizationPolicy,\n artifacts.initialRootContainer,\n artifacts.rootMetadataDocumentRequest,\n artifacts.rosterProfileBootstrap.containerRequest,\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n artifacts.organizationMetadataBootstrap.containerRequest,\n artifacts.organizationMetadataBootstrap.organizationProfileDocumentRequest,\n artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n );\n if (!response) {\n return null;\n }\n if (response.userId !== newUserId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Registration response user does not match the requested identity\",\n );\n }\n // Pinned only once the server has confirmed this user, and before anything\n // is persisted under it. The trust store binds each signing key to one user,\n // so a pin for an id the server never accepted — a retry after a lost\n // response, or a restored key that is already registered — would later\n // refuse the key's real user at login. Like the persistence below, it is a\n // durable write, so it is skipped once the registering identity has been\n // replaced: the caller discards this result.\n if (input.isIdentityCurrent?.() ?? true) {\n await input.pinLocalUserIdentity(newUserId, {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n }\n\n input.log?.(`Key registered (${response.userId})`);\n await persistOrganizationProvisioningState({\n bootstrap: artifacts.bootstrap,\n canStartDurableMutation: input.isIdentityCurrent,\n commitLsn: response.commitLsn,\n onPersistQueued: input.onPersistQueued,\n containerId: input.containerId,\n dbClient: input.dbClient,\n documentProjectors: input.documentProjectors,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n log: input.log,\n logError: input.logError,\n organizationMetadataBootstrap: artifacts.organizationMetadataBootstrap,\n primeProvisionedState: input.primeProvisionedState,\n response,\n rootContainer: artifacts.rootContainer,\n rootMetadataDocument: artifacts.rootMetadataDocument,\n rootMetadataDocumentRequest: artifacts.rootMetadataDocumentRequest,\n rosterProfileBootstrap: artifacts.rosterProfileBootstrap,\n systemContainerBootstraps: artifacts.systemContainerBootstraps,\n });\n\n return response;\n}\n"]}
|