@tearleads/client-sdk 0.1.246 → 0.1.247
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/internal/api-client/ApiClient.d.ts +2 -0
- package/internal/api-client/client/session.d.ts +2 -0
- package/internal/validators/operation/auth.d.ts +14 -0
- package/internal/validators/operation/auth.js +2 -1
- package/internal/validators/operation/auth.js.map +1 -1
- package/internal/validators/response/areas/auth.d.ts +1 -1
- package/internal/validators/response/areas/auth.js +1 -1
- package/internal/validators/response/areas/auth.js.map +1 -1
- package/internal/validators/response/documentSyncSchema.d.ts +5 -0
- package/internal/validators/response/documentSyncSchema.js +1 -1
- package/internal/validators/response/documentSyncSchema.js.map +1 -1
- package/internal/validators/response/registration.d.ts +17 -1
- package/internal/validators/response/registration.js +31 -2
- package/internal/validators/response/registration.js.map +1 -1
- package/package.json +1 -1
- package/workflows/registration/organizationCreation/createOrganization.js +3 -0
- package/workflows/registration/organizationCreation/createOrganization.js.map +1 -1
- package/workflows/registration/organizationProvisioningPersistence.d.ts +7 -0
- package/workflows/registration/organizationProvisioningPersistence.js +1 -0
- package/workflows/registration/organizationProvisioningPersistence.js.map +1 -1
- package/workflows/registration/persistRegistrationBootstrap.d.ts +7 -0
- package/workflows/registration/persistRegistrationBootstrap.js +6 -2
- package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
- package/workflows/registration/registerIdentity.js +1 -0
- package/workflows/registration/registerIdentity.js.map +1 -1
|
@@ -26,6 +26,8 @@ export declare class ApiClient extends ApiClientAreas {
|
|
|
26
26
|
} | null>;
|
|
27
27
|
registerUser: (userId: string, organizationId: string, rootContainerId: string, signingPublicKey: Uint8Array, encapsulationPublicKey: Uint8Array, initialAdminGroup: import("../validators/request/index.js").RegistrationRequest["initialAdminGroup"], initialMemberGroup: import("../validators/request/index.js").RegistrationRequest["initialMemberGroup"], initialOrganizationPolicy: import("../validators/request/index.js").RegistrationRequest["initialOrganizationPolicy"], initialRootContainer: import("../validators/request/index.js").RegistrationRequest["initialRootContainer"], initialRootMetadataDocument: import("../validators/request/index.js").RegistrationRequest["initialRootMetadataDocument"], initialRosterProfileContainer: import("../validators/request/index.js").RegistrationRequest["initialRosterProfileContainer"], initialRosterProfileDocument: import("../validators/request/index.js").RegistrationRequest["initialRosterProfileDocument"], initialOrganizationMetadataContainer: import("../validators/request/index.js").RegistrationRequest["initialOrganizationMetadataContainer"], initialOrganizationProfileDocument?: import("../validators/request/index.js").RegistrationRequest["initialOrganizationProfileDocument"], initialSystemContainers?: import("../validators/request/index.js").RegistrationRequest["initialSystemContainers"]) => Promise<{
|
|
28
28
|
challenge: string;
|
|
29
|
+
commitLsn: string | null;
|
|
30
|
+
commitLsnMode: "tracked" | "untracked";
|
|
29
31
|
committedCoreMetadataUpdateIds: string[];
|
|
30
32
|
committedProfileUpdateIds: string[];
|
|
31
33
|
organizationId: string;
|
|
@@ -35,6 +35,8 @@ export declare class SessionArea {
|
|
|
35
35
|
} | null>;
|
|
36
36
|
registerUser(userId: string, organizationId: string, rootContainerId: string, signingPublicKey: Uint8Array, encapsulationPublicKey: Uint8Array, initialAdminGroup: RegistrationRequest["initialAdminGroup"], initialMemberGroup: RegistrationRequest["initialMemberGroup"], initialOrganizationPolicy: RegistrationRequest["initialOrganizationPolicy"], initialRootContainer: RegistrationRequest["initialRootContainer"], initialRootMetadataDocument: RegistrationRequest["initialRootMetadataDocument"], initialRosterProfileContainer: RegistrationRequest["initialRosterProfileContainer"], initialRosterProfileDocument: RegistrationRequest["initialRosterProfileDocument"], initialOrganizationMetadataContainer: RegistrationRequest["initialOrganizationMetadataContainer"], initialOrganizationProfileDocument?: RegistrationRequest["initialOrganizationProfileDocument"], initialSystemContainers?: RegistrationRequest["initialSystemContainers"]): Promise<{
|
|
37
37
|
challenge: string;
|
|
38
|
+
commitLsn: string | null;
|
|
39
|
+
commitLsnMode: "tracked" | "untracked";
|
|
38
40
|
committedCoreMetadataUpdateIds: string[];
|
|
39
41
|
committedProfileUpdateIds: string[];
|
|
40
42
|
organizationId: string;
|
|
@@ -5914,6 +5914,8 @@ export declare const registerOperation: Omit<{
|
|
|
5914
5914
|
readonly responses: {
|
|
5915
5915
|
readonly 200: z.ZodType<{
|
|
5916
5916
|
challenge: string;
|
|
5917
|
+
commitLsn: string | null;
|
|
5918
|
+
commitLsnMode: "tracked" | "untracked";
|
|
5917
5919
|
committedCoreMetadataUpdateIds: string[];
|
|
5918
5920
|
committedProfileUpdateIds: string[];
|
|
5919
5921
|
organizationId: string;
|
|
@@ -6085,6 +6087,8 @@ export declare const registerOperation: Omit<{
|
|
|
6085
6087
|
rosterProfileDocumentId?: string | undefined;
|
|
6086
6088
|
}, {
|
|
6087
6089
|
challenge: string;
|
|
6090
|
+
commitLsn: string | null;
|
|
6091
|
+
commitLsnMode: "tracked" | "untracked";
|
|
6088
6092
|
committedCoreMetadataUpdateIds: string[];
|
|
6089
6093
|
committedProfileUpdateIds: string[];
|
|
6090
6094
|
organizationId: string;
|
|
@@ -6256,6 +6260,8 @@ export declare const registerOperation: Omit<{
|
|
|
6256
6260
|
rosterProfileDocumentId?: string | undefined;
|
|
6257
6261
|
}, z.core.$ZodTypeInternals<{
|
|
6258
6262
|
challenge: string;
|
|
6263
|
+
commitLsn: string | null;
|
|
6264
|
+
commitLsnMode: "tracked" | "untracked";
|
|
6259
6265
|
committedCoreMetadataUpdateIds: string[];
|
|
6260
6266
|
committedProfileUpdateIds: string[];
|
|
6261
6267
|
organizationId: string;
|
|
@@ -6427,6 +6433,8 @@ export declare const registerOperation: Omit<{
|
|
|
6427
6433
|
rosterProfileDocumentId?: string | undefined;
|
|
6428
6434
|
}, {
|
|
6429
6435
|
challenge: string;
|
|
6436
|
+
commitLsn: string | null;
|
|
6437
|
+
commitLsnMode: "tracked" | "untracked";
|
|
6430
6438
|
committedCoreMetadataUpdateIds: string[];
|
|
6431
6439
|
committedProfileUpdateIds: string[];
|
|
6432
6440
|
organizationId: string;
|
|
@@ -6634,6 +6642,12 @@ export declare const registerOperation: Omit<{
|
|
|
6634
6642
|
}, {
|
|
6635
6643
|
readonly description: "a container response keyring is null exactly for container key epoch 1";
|
|
6636
6644
|
readonly id: "response.organization-provisioning-container-keyring";
|
|
6645
|
+
}, {
|
|
6646
|
+
readonly description: "commitLsnMode \"untracked\" requires the commitLsn \"0/0\" sentinel";
|
|
6647
|
+
readonly id: "response.untracked-commit-lsn-sentinel";
|
|
6648
|
+
}, {
|
|
6649
|
+
readonly description: "commitLsn \"0/0\" requires commitLsnMode \"untracked\" in the same response";
|
|
6650
|
+
readonly id: "response.untracked-commit-lsn-mode";
|
|
6637
6651
|
}];
|
|
6638
6652
|
}, "failureResponses" | "failureStatuses"> & {
|
|
6639
6653
|
readonly failureResponses: {
|
|
@@ -2,7 +2,7 @@ import { z } from "zod";
|
|
|
2
2
|
import { documentSyncRequestRuntimeRefinements } from "../documentSyncRefinements.js";
|
|
3
3
|
import { organizationProvisioningRequestRuntimeRefinements, organizationProvisioningResponseRuntimeRefinements, } from "../organizationProvisioningRefinements.js";
|
|
4
4
|
import { ChallengeRequestSchema, isChallengeRequest, isRegistrationRequest, isVerifyRequest, RegistrationRequestSchema, VerifyRequestSchema, } from "../request/index.js";
|
|
5
|
-
import { ChallengeErrorResponseSchema, ChallengeResponseSchema, DestroySessionResponseSchema, ErrorResponseSchema, isChallengeResponse, isDestroySessionResponse, isListSessionsResponse, isRegistrationResponse, isUserIdentityResponse, isVerifyResponse, isWebSocketTicketResponse, ListSessionsResponseSchema, RegistrationResponseSchema, SessionFailureResponseSchema, UserIdentityResponseSchema, VerifyFailureResponseSchema, VerifySuccessResponseSchema, WebSocketTicketResponseSchema, } from "../response/index.js";
|
|
5
|
+
import { ChallengeErrorResponseSchema, ChallengeResponseSchema, DestroySessionResponseSchema, ErrorResponseSchema, isChallengeResponse, isDestroySessionResponse, isListSessionsResponse, isRegistrationResponse, isUserIdentityResponse, isVerifyResponse, isWebSocketTicketResponse, ListSessionsResponseSchema, RegistrationResponseSchema, registrationCommitCheckpointRefinements, SessionFailureResponseSchema, UserIdentityResponseSchema, VerifyFailureResponseSchema, VerifySuccessResponseSchema, WebSocketTicketResponseSchema, } from "../response/index.js";
|
|
6
6
|
import { sha256HexStringSchema } from "../schema.js";
|
|
7
7
|
import { defineJsonOperation } from "./definition.js";
|
|
8
8
|
const AuthPathParamsSchema = z.strictObject({});
|
|
@@ -77,6 +77,7 @@ export const registerOperation = defineJsonOperation({
|
|
|
77
77
|
...documentSyncRequestRuntimeRefinements,
|
|
78
78
|
...organizationProvisioningRequestRuntimeRefinements,
|
|
79
79
|
...organizationProvisioningResponseRuntimeRefinements,
|
|
80
|
+
...registrationCommitCheckpointRefinements,
|
|
80
81
|
],
|
|
81
82
|
});
|
|
82
83
|
export const logoutOperation = defineJsonOperation({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","sourceRoot":"","sources":["auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,qCAAqC,EAAE,MAAM,4BAA4B,CAAC;AACnF,OAAO,EACL,iDAAiD,EACjD,kDAAkD,GACnD,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,sBAAsB,EACtB,kBAAkB,EAClB,qBAAqB,EACrB,eAAe,EACf,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,EACvB,4BAA4B,EAC5B,mBAAmB,EACnB,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,EACtB,sBAAsB,EACtB,sBAAsB,EACtB,gBAAgB,EAChB,yBAAyB,EACzB,0BAA0B,EAC1B,0BAA0B,EAC1B,4BAA4B,EAC5B,0BAA0B,EAC1B,2BAA2B,EAC3B,2BAA2B,EAC3B,6BAA6B,GAC9B,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAClD,OAAO,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ntimeRefinements } from \"../documentSyncRefinements\";\nimport {\n organizationProvisioningRequestRuntimeRefinements,\n organizationProvisioningResponseRuntimeRefinements,\n} from \"../organizationProvisioningRefinements\";\nimport {\n ChallengeRequestSchema,\n isChallengeRequest,\n isRegistrationRequest,\n isVerifyRequest,\n RegistrationRequestSchema,\n VerifyRequestSchema,\n} from \"../request\";\nimport {\n ChallengeErrorResponseSchema,\n ChallengeResponseSchema,\n DestroySessionResponseSchema,\n ErrorResponseSchema,\n isChallengeResponse,\n isDestroySessionResponse,\n isListSessionsResponse,\n isRegistrationResponse,\n isUserIdentityResponse,\n isVerifyResponse,\n isWebSocketTicketResponse,\n ListSessionsResponseSchema,\n RegistrationResponseSchema,\n SessionFailureResponseSchema,\n UserIdentityResponseSchema,\n VerifyFailureResponseSchema,\n VerifySuccessResponseSchema,\n WebSocketTicketResponseSchema,\n} from \"../response\";\nimport { sha256HexStringSchema } from \"../schema\";\nimport { defineJsonOperation } from \"./definition\";\n\nconst AuthPathParamsSchema = z.strictObject({});\nconst SessionPathParamsSchema = z.strictObject({\n sessionId: sha256HexStringSchema,\n});\nconst UserIdentityPathParamsSchema = z.strictObject({\n userId: z.string(),\n});\n\nexport const challengeOperation = defineJsonOperation({\n auth: \"none\",\n body: ChallengeRequestSchema,\n failureResponses: {\n 400: ChallengeErrorResponseSchema,\n 404: ChallengeErrorResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [400, 404, 500],\n id: \"auth.challenge\",\n summary: \"Request an auth challenge\",\n description:\n \"Starts sign-in for a registered identity: the server stores a short-lived random challenge for the signing key fingerprint, and the client signs it and sends the signature to `POST /auth/verify`. No session is needed; an unknown fingerprint returns 404.\",\n method: \"POST\",\n params: AuthPathParamsSchema,\n path: \"/auth/challenge\",\n responses: {\n 200: ChallengeResponseSchema,\n },\n});\n\nexport const verifyOperation = defineJsonOperation({\n auth: \"none\",\n body: VerifyRequestSchema,\n failureResponses: {\n 400: ChallengeErrorResponseSchema,\n 401: VerifyFailureResponseSchema,\n 403: VerifyFailureResponseSchema,\n 404: VerifyFailureResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [400, 401, 403, 404, 500],\n id: \"auth.verify\",\n summary: \"Verify an auth challenge\",\n description:\n \"Completes sign-in by checking the challenge signature, bound to the API origin, against the identity's registered signing key, then opens a session and returns its bearer token plus the first WebSocket ticket. Each challenge can be used once. A suspended identity's valid signature is refused with 403 and code `account_suspended`, which clients treat as terminal.\",\n method: \"POST\",\n params: AuthPathParamsSchema,\n path: \"/auth/verify\",\n responses: {\n 200: VerifySuccessResponseSchema,\n },\n});\n\nexport const registerOperation = defineJsonOperation({\n auth: \"none\",\n body: RegistrationRequestSchema,\n failureResponses: {\n 400: ErrorResponseSchema,\n 403: ErrorResponseSchema,\n 404: ErrorResponseSchema,\n 409: ErrorResponseSchema,\n 500: ErrorResponseSchema,\n 503: ErrorResponseSchema,\n },\n failureStatuses: [400, 403, 404, 409, 500, 503],\n id: \"auth.register\",\n summary: \"Register an identity and bootstrap its root state\",\n description:\n \"Creates a new identity from its signing and encapsulation public keys and, in one transaction, provisions its personal organization: the reserved `Admins` and `Members` groups, the root container, and their signed policies and metadata documents. The response carries a fresh login challenge, so the client signs in next with `POST /auth/verify`. A signing key that is already registered returns 409.\",\n method: \"POST\",\n params: AuthPathParamsSchema,\n path: \"/auth/register\",\n responses: {\n 200: RegistrationResponseSchema,\n },\n runtimeRefinements: [\n ...documentSyncRequestRuntimeRefinements,\n ...organizationProvisioningRequestRuntimeRefinements,\n ...organizationProvisioningResponseRuntimeRefinements,\n ],\n});\n\nexport const logoutOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n 401: SessionFailureResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [401, 500],\n id: \"auth.logout\",\n summary: \"Destroy the current session\",\n description:\n \"Ends the session that made the request, so its bearer token stops working. Any signed-in user may call it.\",\n method: \"POST\",\n params: AuthPathParamsSchema,\n path: \"/auth/logout\",\n responses: {\n 200: DestroySessionResponseSchema,\n },\n});\n\nexport const webSocketTicketOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n 401: SessionFailureResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [401, 500],\n id: \"auth.webSocketTicket\",\n summary: \"Mint a one-time WebSocket ticket\",\n description:\n \"Issues a single-use, short-lived ticket that authenticates one WebSocket upgrade to the realtime hint gateway, because browsers cannot attach an `Authorization` header to a WebSocket handshake. Clients call it before each reconnect; sign-in already returns the first ticket.\",\n method: \"POST\",\n params: AuthPathParamsSchema,\n path: \"/auth/ws-ticket\",\n responses: {\n 200: WebSocketTicketResponseSchema,\n },\n});\n\nexport const listSessionsOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n 401: SessionFailureResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [401, 500],\n id: \"auth.sessions.list\",\n summary: \"List auth sessions\",\n description:\n \"Lists the signed-in user's live sessions with their creation time, last activity, IP addresses, and signing key fingerprint, flagging the one that made the request. It only ever returns the caller's own sessions.\",\n method: \"GET\",\n params: AuthPathParamsSchema,\n path: \"/auth/sessions\",\n responses: {\n 200: ListSessionsResponseSchema,\n },\n});\n\nexport const destroySessionOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n 400: ErrorResponseSchema,\n 401: SessionFailureResponseSchema,\n 404: ErrorResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [400, 401, 404, 500],\n id: \"auth.sessions.destroy\",\n summary: \"Destroy a user session\",\n description:\n \"Signs out one of the caller's own sessions, for example a lost device. A session id that is unknown or belongs to another user returns 404.\",\n method: \"DELETE\",\n params: SessionPathParamsSchema,\n path: \"/auth/sessions/{sessionId}\",\n responses: {\n 200: DestroySessionResponseSchema,\n },\n});\n\nexport const userIdentityOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n 401: SessionFailureResponseSchema,\n 404: ErrorResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [401, 404, 500],\n id: \"auth.userIdentity\",\n summary: \"Get a complete user identity\",\n description:\n \"Returns a user's registered signing and encapsulation public keys and fingerprints. Clients never trust the answer alone: they compare it with an identity link or an existing identity pin before using the keys. Any signed-in user may call it; an unknown user returns 404.\",\n method: \"GET\",\n params: UserIdentityPathParamsSchema,\n path: \"/auth/user-identity/{userId}\",\n responses: {\n 200: UserIdentityResponseSchema,\n },\n});\n\nexport const isChallengeOperationRequest = isChallengeRequest;\nexport const isChallengeOperationResponse = isChallengeResponse;\nexport const isRegistrationOperationRequest = isRegistrationRequest;\nexport const isRegistrationOperationResponse = isRegistrationResponse;\nexport const isVerifyOperationRequest = isVerifyRequest;\nexport const isVerifyOperationResponse = isVerifyResponse;\nexport const isLogoutOperationResponse = isDestroySessionResponse;\nexport const isWebSocketTicketOperationResponse = isWebSocketTicketResponse;\nexport const isListSessionsOperationResponse = isListSessionsResponse;\nexport const isDestroySessionOperationResponse = isDestroySessionResponse;\nexport const isUserIdentityOperationResponse = isUserIdentityResponse;\n"]}
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"","sources":["auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,qCAAqC,EAAE,MAAM,4BAA4B,CAAC;AACnF,OAAO,EACL,iDAAiD,EACjD,kDAAkD,GACnD,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,sBAAsB,EACtB,kBAAkB,EAClB,qBAAqB,EACrB,eAAe,EACf,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,EACvB,4BAA4B,EAC5B,mBAAmB,EACnB,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,EACtB,sBAAsB,EACtB,sBAAsB,EACtB,gBAAgB,EAChB,yBAAyB,EACzB,0BAA0B,EAC1B,0BAA0B,EAC1B,uCAAuC,EACvC,4BAA4B,EAC5B,0B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sBAAsB,CAAC;AACtE,MAAM,CAAC,MAAM,iCAAiC,GAAG,wBAAwB,CAAC;AAC1E,MAAM,CAAC,MAAM,+BAA+B,GAAG,sBAAsB,CAAC","sourcesContent":["import { z } from \"zod\";\nimport { documentSyncRequestRuntimeRefinements } from \"../documentSyncRefinements\";\nimport {\n organizationProvisioningRequestRuntimeRefinements,\n organizationProvisioningResponseRuntimeRefinements,\n} from \"../organizationProvisioningRefinements\";\nimport {\n ChallengeRequestSchema,\n isChallengeRequest,\n isRegistrationRequest,\n isVerifyRequest,\n RegistrationRequestSchema,\n VerifyRequestSchema,\n} from \"../request\";\nimport {\n ChallengeErrorResponseSchema,\n ChallengeResponseSchema,\n DestroySessionResponseSchema,\n ErrorResponseSchema,\n isChallengeResponse,\n isDestroySessionResponse,\n isListSessionsResponse,\n isRegistrationResponse,\n isUserIdentityResponse,\n isVerifyResponse,\n isWebSocketTicketResponse,\n ListSessionsResponseSchema,\n RegistrationResponseSchema,\n registrationCommitCheckpointRefinements,\n SessionFailureResponseSchema,\n UserIdentityResponseSchema,\n VerifyFailureResponseSchema,\n VerifySuccessResponseSchema,\n WebSocketTicketResponseSchema,\n} from \"../response\";\nimport { sha256HexStringSchema } from \"../schema\";\nimport { defineJsonOperation } from \"./definition\";\n\nconst AuthPathParamsSchema = z.strictObject({});\nconst SessionPathParamsSchema = z.strictObject({\n sessionId: sha256HexStringSchema,\n});\nconst UserIdentityPathParamsSchema = z.strictObject({\n userId: z.string(),\n});\n\nexport const challengeOperation = defineJsonOperation({\n auth: \"none\",\n body: ChallengeRequestSchema,\n failureResponses: {\n 400: ChallengeErrorResponseSchema,\n 404: ChallengeErrorResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [400, 404, 500],\n id: \"auth.challenge\",\n summary: \"Request an auth challenge\",\n description:\n \"Starts sign-in for a registered identity: the server stores a short-lived random challenge for the signing key fingerprint, and the client signs it and sends the signature to `POST /auth/verify`. No session is needed; an unknown fingerprint returns 404.\",\n method: \"POST\",\n params: AuthPathParamsSchema,\n path: \"/auth/challenge\",\n responses: {\n 200: ChallengeResponseSchema,\n },\n});\n\nexport const verifyOperation = defineJsonOperation({\n auth: \"none\",\n body: VerifyRequestSchema,\n failureResponses: {\n 400: ChallengeErrorResponseSchema,\n 401: VerifyFailureResponseSchema,\n 403: VerifyFailureResponseSchema,\n 404: VerifyFailureResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [400, 401, 403, 404, 500],\n id: \"auth.verify\",\n summary: \"Verify an auth challenge\",\n description:\n \"Completes sign-in by checking the challenge signature, bound to the API origin, against the identity's registered signing key, then opens a session and returns its bearer token plus the first WebSocket ticket. Each challenge can be used once. A suspended identity's valid signature is refused with 403 and code `account_suspended`, which clients treat as terminal.\",\n method: \"POST\",\n params: AuthPathParamsSchema,\n path: \"/auth/verify\",\n responses: {\n 200: VerifySuccessResponseSchema,\n },\n});\n\nexport const registerOperation = defineJsonOperation({\n auth: \"none\",\n body: RegistrationRequestSchema,\n failureResponses: {\n 400: ErrorResponseSchema,\n 403: ErrorResponseSchema,\n 404: ErrorResponseSchema,\n 409: ErrorResponseSchema,\n 500: ErrorResponseSchema,\n 503: ErrorResponseSchema,\n },\n failureStatuses: [400, 403, 404, 409, 500, 503],\n id: \"auth.register\",\n summary: \"Register an identity and bootstrap its root state\",\n description:\n \"Creates a new identity from its signing and encapsulation public keys and, in one transaction, provisions its personal organization: the reserved `Admins` and `Members` groups, the root container, and their signed policies and metadata documents. The response carries a fresh login challenge, so the client signs in next with `POST /auth/verify`. A signing key that is already registered returns 409.\",\n method: \"POST\",\n params: AuthPathParamsSchema,\n path: \"/auth/register\",\n responses: {\n 200: RegistrationResponseSchema,\n },\n runtimeRefinements: [\n ...documentSyncRequestRuntimeRefinements,\n ...organizationProvisioningRequestRuntimeRefinements,\n ...organizationProvisioningResponseRuntimeRefinements,\n ...registrationCommitCheckpointRefinements,\n ],\n});\n\nexport const logoutOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n 401: SessionFailureResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [401, 500],\n id: \"auth.logout\",\n summary: \"Destroy the current session\",\n description:\n \"Ends the session that made the request, so its bearer token stops working. Any signed-in user may call it.\",\n method: \"POST\",\n params: AuthPathParamsSchema,\n path: \"/auth/logout\",\n responses: {\n 200: DestroySessionResponseSchema,\n },\n});\n\nexport const webSocketTicketOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n 401: SessionFailureResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [401, 500],\n id: \"auth.webSocketTicket\",\n summary: \"Mint a one-time WebSocket ticket\",\n description:\n \"Issues a single-use, short-lived ticket that authenticates one WebSocket upgrade to the realtime hint gateway, because browsers cannot attach an `Authorization` header to a WebSocket handshake. Clients call it before each reconnect; sign-in already returns the first ticket.\",\n method: \"POST\",\n params: AuthPathParamsSchema,\n path: \"/auth/ws-ticket\",\n responses: {\n 200: WebSocketTicketResponseSchema,\n },\n});\n\nexport const listSessionsOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n 401: SessionFailureResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [401, 500],\n id: \"auth.sessions.list\",\n summary: \"List auth sessions\",\n description:\n \"Lists the signed-in user's live sessions with their creation time, last activity, IP addresses, and signing key fingerprint, flagging the one that made the request. It only ever returns the caller's own sessions.\",\n method: \"GET\",\n params: AuthPathParamsSchema,\n path: \"/auth/sessions\",\n responses: {\n 200: ListSessionsResponseSchema,\n },\n});\n\nexport const destroySessionOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n 400: ErrorResponseSchema,\n 401: SessionFailureResponseSchema,\n 404: ErrorResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [400, 401, 404, 500],\n id: \"auth.sessions.destroy\",\n summary: \"Destroy a user session\",\n description:\n \"Signs out one of the caller's own sessions, for example a lost device. A session id that is unknown or belongs to another user returns 404.\",\n method: \"DELETE\",\n params: SessionPathParamsSchema,\n path: \"/auth/sessions/{sessionId}\",\n responses: {\n 200: DestroySessionResponseSchema,\n },\n});\n\nexport const userIdentityOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n 401: SessionFailureResponseSchema,\n 404: ErrorResponseSchema,\n 500: ErrorResponseSchema,\n },\n failureStatuses: [401, 404, 500],\n id: \"auth.userIdentity\",\n summary: \"Get a complete user identity\",\n description:\n \"Returns a user's registered signing and encapsulation public keys and fingerprints. Clients never trust the answer alone: they compare it with an identity link or an existing identity pin before using the keys. Any signed-in user may call it; an unknown user returns 404.\",\n method: \"GET\",\n params: UserIdentityPathParamsSchema,\n path: \"/auth/user-identity/{userId}\",\n responses: {\n 200: UserIdentityResponseSchema,\n },\n});\n\nexport const isChallengeOperationRequest = isChallengeRequest;\nexport const isChallengeOperationResponse = isChallengeResponse;\nexport const isRegistrationOperationRequest = isRegistrationRequest;\nexport const isRegistrationOperationResponse = isRegistrationResponse;\nexport const isVerifyOperationRequest = isVerifyRequest;\nexport const isVerifyOperationResponse = isVerifyResponse;\nexport const isLogoutOperationResponse = isDestroySessionResponse;\nexport const isWebSocketTicketOperationResponse = isWebSocketTicketResponse;\nexport const isListSessionsOperationResponse = isListSessionsResponse;\nexport const isDestroySessionOperationResponse = isDestroySessionResponse;\nexport const isUserIdentityOperationResponse = isUserIdentityResponse;\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { type ChallengeErrorResponse, ChallengeErrorResponseSchema, type ChallengeResponse, ChallengeResponseSchema, type DestroySessionResponse, DestroySessionResponseSchema, isChallengeErrorResponse, isChallengeResponse, isDestroySessionResponse, isListSessionsResponse, isSessionRefreshRequiredFailure, isUserIdentityResponse, isUserSessionResponse, isVerifyResponse, isWebSocketTicketResponse, type ListSessionsResponse, ListSessionsResponseSchema, SESSION_ERROR_CODES, type SessionErrorCode, SessionErrorCodeSchema, type SessionFailureResponse, SessionFailureResponseSchema, type UserIdentityResponse, UserIdentityResponseSchema, type UserSessionResponse, UserSessionResponseSchema, VERIFY_ERROR_CODES, type VerifyFailureResponse, VerifyFailureResponseSchema, type VerifyResponse, type VerifySuccessResponse, VerifySuccessResponseSchema, type WebSocketTicketResponse, WebSocketTicketResponseSchema, } from "../auth/index.js";
|
|
2
|
-
export { isRegistrationResponse, type RegistrationResponse, RegistrationResponseSchema, } from "../registration.js";
|
|
2
|
+
export { isRegistrationResponse, type RegistrationResponse, RegistrationResponseSchema, registrationCommitCheckpointRefinements, } from "../registration.js";
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { ChallengeErrorResponseSchema, ChallengeResponseSchema, DestroySessionResponseSchema, isChallengeErrorResponse, isChallengeResponse, isDestroySessionResponse, isListSessionsResponse, isSessionRefreshRequiredFailure, isUserIdentityResponse, isUserSessionResponse, isVerifyResponse, isWebSocketTicketResponse, ListSessionsResponseSchema, SESSION_ERROR_CODES, SessionErrorCodeSchema, SessionFailureResponseSchema, UserIdentityResponseSchema, UserSessionResponseSchema, VERIFY_ERROR_CODES, VerifyFailureResponseSchema, VerifySuccessResponseSchema, WebSocketTicketResponseSchema, } from "../auth/index.js";
|
|
2
|
-
export { isRegistrationResponse, RegistrationResponseSchema, } from "../registration.js";
|
|
2
|
+
export { isRegistrationResponse, RegistrationResponseSchema, registrationCommitCheckpointRefinements, } from "../registration.js";
|
|
3
3
|
//# sourceMappingURL=auth.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","sourceRoot":"","sources":["auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,4BAA4B,EAE5B,uBAAuB,EAEvB,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,EACtB,+BAA+B,EAC/B,sBAAsB,EACtB,qBAAqB,EACrB,gBAAgB,EAChB,yBAAyB,EAEzB,0BAA0B,EAC1B,mBAAmB,EAEnB,sBAAsB,EAEtB,4BAA4B,EAE5B,0BAA0B,EAE1B,yBAAyB,EACzB,kBAAkB,EAElB,2BAA2B,EAG3B,2BAA2B,EAE3B,6BAA6B,GAC9B,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,sBAAsB,EAEtB,0BAA0B,
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"","sources":["auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,4BAA4B,EAE5B,uBAAuB,EAEvB,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,EACtB,+BAA+B,EAC/B,sBAAsB,EACtB,qBAAqB,EACrB,gBAAgB,EAChB,yBAAyB,EAEzB,0BAA0B,EAC1B,mBAAmB,EAEnB,sBAAsB,EAEtB,4BAA4B,EAE5B,0BAA0B,EAE1B,yBAAyB,EACzB,kBAAkB,EAElB,2BAA2B,EAG3B,2BAA2B,EAE3B,6BAA6B,GAC9B,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,sBAAsB,EAEtB,0BAA0B,EAC1B,uCAAuC,GACxC,MAAM,iBAAiB,CAAC","sourcesContent":["export {\n type ChallengeErrorResponse,\n ChallengeErrorResponseSchema,\n type ChallengeResponse,\n ChallengeResponseSchema,\n type DestroySessionResponse,\n DestroySessionResponseSchema,\n isChallengeErrorResponse,\n isChallengeResponse,\n isDestroySessionResponse,\n isListSessionsResponse,\n isSessionRefreshRequiredFailure,\n isUserIdentityResponse,\n isUserSessionResponse,\n isVerifyResponse,\n isWebSocketTicketResponse,\n type ListSessionsResponse,\n ListSessionsResponseSchema,\n SESSION_ERROR_CODES,\n type SessionErrorCode,\n SessionErrorCodeSchema,\n type SessionFailureResponse,\n SessionFailureResponseSchema,\n type UserIdentityResponse,\n UserIdentityResponseSchema,\n type UserSessionResponse,\n UserSessionResponseSchema,\n VERIFY_ERROR_CODES,\n type VerifyFailureResponse,\n VerifyFailureResponseSchema,\n type VerifyResponse,\n type VerifySuccessResponse,\n VerifySuccessResponseSchema,\n type WebSocketTicketResponse,\n WebSocketTicketResponseSchema,\n} from \"../auth\";\nexport {\n isRegistrationResponse,\n type RegistrationResponse,\n RegistrationResponseSchema,\n registrationCommitCheckpointRefinements,\n} from \"../registration\";\n"]}
|
|
@@ -213,6 +213,11 @@ export declare const commitLsnResponseShape: {
|
|
|
213
213
|
commitLsn: z.ZodNullable<z.ZodString>;
|
|
214
214
|
commitLsnMode: z.ZodUnion<readonly [z.ZodLiteral<"tracked">, z.ZodLiteral<"untracked">]>;
|
|
215
215
|
};
|
|
216
|
+
/** The 0/0 sentinel and the untracked mode imply each other. */
|
|
217
|
+
export declare function addCommitLsnIssues(response: {
|
|
218
|
+
readonly commitLsn: string | null;
|
|
219
|
+
readonly commitLsnMode: "tracked" | "untracked";
|
|
220
|
+
}, context: z.RefinementCtx): void;
|
|
216
221
|
export declare const DocumentSyncResponseSchema: z.ZodType<{
|
|
217
222
|
contentKeyBundles: {
|
|
218
223
|
contentKeyEpoch: number;
|
|
@@ -100,7 +100,7 @@ export const commitLsnResponseShape = {
|
|
|
100
100
|
commitLsnMode: z.union([z.literal("tracked"), z.literal("untracked")]),
|
|
101
101
|
};
|
|
102
102
|
/** The 0/0 sentinel and the untracked mode imply each other. */
|
|
103
|
-
function addCommitLsnIssues(response, context) {
|
|
103
|
+
export function addCommitLsnIssues(response, context) {
|
|
104
104
|
if (response.commitLsnMode === "untracked" && response.commitLsn !== "0/0") {
|
|
105
105
|
context.addIssue({
|
|
106
106
|
code: "custom",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentSyncSchema.js","sourceRoot":"","sources":["documentSyncSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,oCAAoC,EACpC,gDAAgD,EAChD,sCAAsC,EACtC,8CAA8C,GAC/C,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,2CAA2C,EAC3C,+CAA+C,EAC/C,+CAA+C,EAC/C,sCAAsC,EACtC,sCAAsC,GACvC,MAAM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AO,EAAE,+CAA+C;YACxD,IAAI,EAAE,CAAC,UAAU,EAAE,YAAY,CAAC;SACjC,CAAC,CAAC;IACL,CAAC;IACD,kBAAkB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IACtC,mCAAmC,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACzD,CAAC,CAAC,EACF;IACE,2CAA2C;IAC3C,+CAA+C;IAC/C,sCAAsC;IACtC,+CAA+C;CAChD,CACF,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n classifyDocumentSyncCheckpointFields,\n DOCUMENT_SYNC_CHECKPOINT_FIELD_SET_ISSUE_MESSAGE,\n DOCUMENT_SYNC_ROTATION_CHECKPOINT_KIND,\n DOCUMENT_SYNC_ROTATION_CHECKPOINT_PAYLOAD_KIND,\n} from \"../documentSyncCheckpoint\";\nimport {\n documentSyncResponseCommitLsnModeRefinement,\n documentSyncResponseCommitLsnSentinelRefinement,\n documentSyncResponseHistoricalBundlesRefinement,\n documentSyncResponsePullPageRefinement,\n documentSyncResponseRotationRefinement,\n} from \"../documentSyncRefinements\";\nimport { registerJsonSchemaRuntimeRefinements } from \"../jsonSchema\";\nimport {\n arraySchema,\n boundedNonEmptyStringSchema,\n loosePlainObject,\n nonEmptyArraySchema,\n nonEmptyStringSchema,\n plainObjectSchema,\n positiveIntegerSchema,\n} from \"../schema\";\nimport {\n MAX_DOCUMENT_SYNC_OUTGOING_UPDATES,\n MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES,\n} from \"../util/documentSyncLimits\";\n\nexport const DocumentContentKeyTargetEnvelopeResponseSchema = loosePlainObject({\n containerId: nonEmptyStringSchema,\n containerKeyEpoch: positiveIntegerSchema,\n containerKeyEpochId: nonEmptyStringSchema,\n containerManifestHash: nonEmptyStringSchema,\n wrappedKey: nonEmptyStringSchema,\n wrappingMetadata: plainObjectSchema,\n});\n\nexport type DocumentContentKeyTargetEnvelopeResponse = z.infer<\n typeof DocumentContentKeyTargetEnvelopeResponseSchema\n>;\n\nconst DocumentContentKeyTargetResponseSchema = loosePlainObject({\n containerId: nonEmptyStringSchema,\n containerKeyEpoch: positiveIntegerSchema,\n containerKeyEpochId: nonEmptyStringSchema,\n containerManifestHash: nonEmptyStringSchema,\n});\n\nexport const DocumentKekTargetsResponseSchema = loosePlainObject({\n documentId: z.string(),\n documentKeyTargetHash: nonEmptyStringSchema,\n linkedContainerKeyEpochIds: nonEmptyArraySchema(nonEmptyStringSchema),\n linkedContainerManifestHashes: nonEmptyArraySchema(nonEmptyStringSchema),\n linkSetManifestHash: nonEmptyStringSchema,\n targets: nonEmptyArraySchema(plainObjectSchema),\n});\n\nexport type DocumentKekTargetsResponse = z.infer<\n typeof DocumentKekTargetsResponseSchema\n>;\n\nexport const DocumentContentKeyBundleResponseSchema = loosePlainObject({\n contentKeyEpoch: positiveIntegerSchema,\n documentId: z.string(),\n linkSetManifestHash: nonEmptyStringSchema,\n targetHash: nonEmptyStringSchema,\n targets: nonEmptyArraySchema(DocumentContentKeyTargetEnvelopeResponseSchema),\n});\n\nexport type DocumentContentKeyBundleResponse = z.infer<\n typeof DocumentContentKeyBundleResponseSchema\n>;\n\nexport const DocumentSyncUpdateResponseSchema =\n registerJsonSchemaRuntimeRefinements(\n loosePlainObject({\n accessEpoch: positiveIntegerSchema,\n authorizationTargets: nonEmptyArraySchema(\n DocumentContentKeyTargetResponseSchema,\n ).optional(),\n authorFingerprint: z.string(),\n checkpointKind: z\n .literal(DOCUMENT_SYNC_ROTATION_CHECKPOINT_KIND)\n .optional(),\n checkpointPayloadKind: z\n .literal(DOCUMENT_SYNC_ROTATION_CHECKPOINT_PAYLOAD_KIND)\n .optional(),\n createdAt: z.string(),\n documentId: z.string(),\n encryptedData: z.string(),\n id: z.string(),\n partialEndVersionVector: z.string(),\n partialStartVersionVector: z.string(),\n plaintextHash: nonEmptyStringSchema,\n sourceVersionVector: z.string().min(1).optional(),\n writeHeader: plainObjectSchema,\n }).superRefine((update, context) => {\n if (classifyDocumentSyncCheckpointFields(update) === \"invalid\") {\n context.addIssue({\n code: \"custom\",\n message: DOCUMENT_SYNC_CHECKPOINT_FIELD_SET_ISSUE_MESSAGE,\n });\n }\n }),\n [documentSyncResponseRotationRefinement],\n );\n\nexport type DocumentSyncUpdateResponse = z.infer<\n typeof DocumentSyncUpdateResponseSchema\n>;\n\nexport const DocumentSyncPullPageResponseSchema = loosePlainObject({\n hasMore: z.boolean(),\n nextCursor: boundedNonEmptyStringSchema(\n MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH,\n ).nullable(),\n});\n\nexport type DocumentSyncPullPageResponse = z.infer<\n typeof DocumentSyncPullPageResponseSchema\n>;\n\nfunction contentKeyEpochOf(bundle: unknown): number | null {\n if (typeof bundle !== \"object\" || bundle === null) return null;\n const contentKeyEpoch: unknown = Reflect.get(bundle, \"contentKeyEpoch\");\n return typeof contentKeyEpoch === \"number\" ? contentKeyEpoch : null;\n}\n\n/**\n * The client already holds the current epoch's bundle, so the array holds the\n * distinct older epochs that served updates cite; the client rejects any epoch\n * not older than the one it planned against. Field issues do not stop this\n * object refinement, so it judges only epochs that parsed.\n */\nfunction addHistoricalContentKeyBundleIssues(\n response: { readonly contentKeyBundles: unknown },\n context: z.RefinementCtx,\n): void {\n if (!Array.isArray(response.contentKeyBundles)) return;\n const seenEpochs = new Set<number>();\n // forEach skips holes exactly as arraySchema's item validation does.\n response.contentKeyBundles.forEach((bundle: unknown, index: number) => {\n const contentKeyEpoch = contentKeyEpochOf(bundle);\n if (contentKeyEpoch === null) return;\n if (seenEpochs.has(contentKeyEpoch)) {\n context.addIssue({\n code: \"custom\",\n message: \"content-key bundles must be distinct epochs\",\n path: [\"contentKeyBundles\", index, \"contentKeyEpoch\"],\n });\n }\n seenEpochs.add(contentKeyEpoch);\n });\n}\n\nexport const commitLsnResponseShape = {\n commitLsn: z.string().nullable(),\n commitLsnMode: z.union([z.literal(\"tracked\"), z.literal(\"untracked\")]),\n};\n\n/** The 0/0 sentinel and the untracked mode imply each other. */\nfunction addCommitLsnIssues(\n response: {\n readonly commitLsn: string | null;\n readonly commitLsnMode: \"tracked\" | \"untracked\";\n },\n context: z.RefinementCtx,\n): void {\n if (response.commitLsnMode === \"untracked\" && response.commitLsn !== \"0/0\") {\n context.addIssue({\n code: \"custom\",\n message: \"untracked commit LSN must use the 0/0 sentinel\",\n path: [\"commitLsn\"],\n });\n }\n if (response.commitLsn === \"0/0\" && response.commitLsnMode !== \"untracked\") {\n context.addIssue({\n code: \"custom\",\n message: \"0/0 commit LSN must be declared untracked\",\n path: [\"commitLsnMode\"],\n });\n }\n}\n\nexport const DocumentSyncResponseSchema = registerJsonSchemaRuntimeRefinements(\n loosePlainObject({\n acceptedOutgoingUpdateIds: arraySchema(\n z.string(),\n MAX_DOCUMENT_SYNC_OUTGOING_UPDATES,\n ),\n ...commitLsnResponseShape,\n contentKeyBundles: arraySchema(DocumentContentKeyBundleResponseSchema),\n documentId: z.string(),\n pullPage: DocumentSyncPullPageResponseSchema,\n updates: arraySchema(\n DocumentSyncUpdateResponseSchema,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES,\n ),\n }).superRefine((response, context) => {\n if (\n response.pullPage !== undefined &&\n response.pullPage.hasMore !== (response.pullPage.nextCursor !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"pull page continuation does not match hasMore\",\n path: [\"pullPage\", \"nextCursor\"],\n });\n }\n addCommitLsnIssues(response, context);\n addHistoricalContentKeyBundleIssues(response, context);\n }),\n [\n documentSyncResponseCommitLsnModeRefinement,\n documentSyncResponseCommitLsnSentinelRefinement,\n documentSyncResponsePullPageRefinement,\n documentSyncResponseHistoricalBundlesRefinement,\n ],\n);\n\nexport type DocumentSyncResponse = z.infer<typeof DocumentSyncResponseSchema>;\n"]}
|
|
1
|
+
{"version":3,"file":"documentSyncSchema.js","sourceRoot":"","sources":["documentSyncSchema.ts"],"names":[],"mappings":"AAAA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EAAE,OAAO,EAAE,EAAE;IACnC,IACE,QAAQ,CAAC,QAAQ,KAAK,SAAS;QAC/B,QAAQ,CAAC,QAAQ,CAAC,OAAO,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,UAAU,KAAK,IAAI,CAAC,EACrE,CAAC;QACD,OAAO,CAAC,QAAQ,CAAC;YACf,IAAI,EAAE,QAAQ;YACd,OAAO,EAAE,+CAA+C;YACxD,IAAI,EAAE,CAAC,UAAU,EAAE,YAAY,CAAC;SACjC,CAAC,CAAC;IACL,CAAC;IACD,kBAAkB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IACtC,mCAAmC,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACzD,CAAC,CAAC,EACF;IACE,2CAA2C;IAC3C,+CAA+C;IAC/C,sCAAsC;IACtC,+CAA+C;CAChD,CACF,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n classifyDocumentSyncCheckpointFields,\n DOCUMENT_SYNC_CHECKPOINT_FIELD_SET_ISSUE_MESSAGE,\n DOCUMENT_SYNC_ROTATION_CHECKPOINT_KIND,\n DOCUMENT_SYNC_ROTATION_CHECKPOINT_PAYLOAD_KIND,\n} from \"../documentSyncCheckpoint\";\nimport {\n documentSyncResponseCommitLsnModeRefinement,\n documentSyncResponseCommitLsnSentinelRefinement,\n documentSyncResponseHistoricalBundlesRefinement,\n documentSyncResponsePullPageRefinement,\n documentSyncResponseRotationRefinement,\n} from \"../documentSyncRefinements\";\nimport { registerJsonSchemaRuntimeRefinements } from \"../jsonSchema\";\nimport {\n arraySchema,\n boundedNonEmptyStringSchema,\n loosePlainObject,\n nonEmptyArraySchema,\n nonEmptyStringSchema,\n plainObjectSchema,\n positiveIntegerSchema,\n} from \"../schema\";\nimport {\n MAX_DOCUMENT_SYNC_OUTGOING_UPDATES,\n MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES,\n} from \"../util/documentSyncLimits\";\n\nexport const DocumentContentKeyTargetEnvelopeResponseSchema = loosePlainObject({\n containerId: nonEmptyStringSchema,\n containerKeyEpoch: positiveIntegerSchema,\n containerKeyEpochId: nonEmptyStringSchema,\n containerManifestHash: nonEmptyStringSchema,\n wrappedKey: nonEmptyStringSchema,\n wrappingMetadata: plainObjectSchema,\n});\n\nexport type DocumentContentKeyTargetEnvelopeResponse = z.infer<\n typeof DocumentContentKeyTargetEnvelopeResponseSchema\n>;\n\nconst DocumentContentKeyTargetResponseSchema = loosePlainObject({\n containerId: nonEmptyStringSchema,\n containerKeyEpoch: positiveIntegerSchema,\n containerKeyEpochId: nonEmptyStringSchema,\n containerManifestHash: nonEmptyStringSchema,\n});\n\nexport const DocumentKekTargetsResponseSchema = loosePlainObject({\n documentId: z.string(),\n documentKeyTargetHash: nonEmptyStringSchema,\n linkedContainerKeyEpochIds: nonEmptyArraySchema(nonEmptyStringSchema),\n linkedContainerManifestHashes: nonEmptyArraySchema(nonEmptyStringSchema),\n linkSetManifestHash: nonEmptyStringSchema,\n targets: nonEmptyArraySchema(plainObjectSchema),\n});\n\nexport type DocumentKekTargetsResponse = z.infer<\n typeof DocumentKekTargetsResponseSchema\n>;\n\nexport const DocumentContentKeyBundleResponseSchema = loosePlainObject({\n contentKeyEpoch: positiveIntegerSchema,\n documentId: z.string(),\n linkSetManifestHash: nonEmptyStringSchema,\n targetHash: nonEmptyStringSchema,\n targets: nonEmptyArraySchema(DocumentContentKeyTargetEnvelopeResponseSchema),\n});\n\nexport type DocumentContentKeyBundleResponse = z.infer<\n typeof DocumentContentKeyBundleResponseSchema\n>;\n\nexport const DocumentSyncUpdateResponseSchema =\n registerJsonSchemaRuntimeRefinements(\n loosePlainObject({\n accessEpoch: positiveIntegerSchema,\n authorizationTargets: nonEmptyArraySchema(\n DocumentContentKeyTargetResponseSchema,\n ).optional(),\n authorFingerprint: z.string(),\n checkpointKind: z\n .literal(DOCUMENT_SYNC_ROTATION_CHECKPOINT_KIND)\n .optional(),\n checkpointPayloadKind: z\n .literal(DOCUMENT_SYNC_ROTATION_CHECKPOINT_PAYLOAD_KIND)\n .optional(),\n createdAt: z.string(),\n documentId: z.string(),\n encryptedData: z.string(),\n id: z.string(),\n partialEndVersionVector: z.string(),\n partialStartVersionVector: z.string(),\n plaintextHash: nonEmptyStringSchema,\n sourceVersionVector: z.string().min(1).optional(),\n writeHeader: plainObjectSchema,\n }).superRefine((update, context) => {\n if (classifyDocumentSyncCheckpointFields(update) === \"invalid\") {\n context.addIssue({\n code: \"custom\",\n message: DOCUMENT_SYNC_CHECKPOINT_FIELD_SET_ISSUE_MESSAGE,\n });\n }\n }),\n [documentSyncResponseRotationRefinement],\n );\n\nexport type DocumentSyncUpdateResponse = z.infer<\n typeof DocumentSyncUpdateResponseSchema\n>;\n\nexport const DocumentSyncPullPageResponseSchema = loosePlainObject({\n hasMore: z.boolean(),\n nextCursor: boundedNonEmptyStringSchema(\n MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH,\n ).nullable(),\n});\n\nexport type DocumentSyncPullPageResponse = z.infer<\n typeof DocumentSyncPullPageResponseSchema\n>;\n\nfunction contentKeyEpochOf(bundle: unknown): number | null {\n if (typeof bundle !== \"object\" || bundle === null) return null;\n const contentKeyEpoch: unknown = Reflect.get(bundle, \"contentKeyEpoch\");\n return typeof contentKeyEpoch === \"number\" ? contentKeyEpoch : null;\n}\n\n/**\n * The client already holds the current epoch's bundle, so the array holds the\n * distinct older epochs that served updates cite; the client rejects any epoch\n * not older than the one it planned against. Field issues do not stop this\n * object refinement, so it judges only epochs that parsed.\n */\nfunction addHistoricalContentKeyBundleIssues(\n response: { readonly contentKeyBundles: unknown },\n context: z.RefinementCtx,\n): void {\n if (!Array.isArray(response.contentKeyBundles)) return;\n const seenEpochs = new Set<number>();\n // forEach skips holes exactly as arraySchema's item validation does.\n response.contentKeyBundles.forEach((bundle: unknown, index: number) => {\n const contentKeyEpoch = contentKeyEpochOf(bundle);\n if (contentKeyEpoch === null) return;\n if (seenEpochs.has(contentKeyEpoch)) {\n context.addIssue({\n code: \"custom\",\n message: \"content-key bundles must be distinct epochs\",\n path: [\"contentKeyBundles\", index, \"contentKeyEpoch\"],\n });\n }\n seenEpochs.add(contentKeyEpoch);\n });\n}\n\nexport const commitLsnResponseShape = {\n commitLsn: z.string().nullable(),\n commitLsnMode: z.union([z.literal(\"tracked\"), z.literal(\"untracked\")]),\n};\n\n/** The 0/0 sentinel and the untracked mode imply each other. */\nexport function addCommitLsnIssues(\n response: {\n readonly commitLsn: string | null;\n readonly commitLsnMode: \"tracked\" | \"untracked\";\n },\n context: z.RefinementCtx,\n): void {\n if (response.commitLsnMode === \"untracked\" && response.commitLsn !== \"0/0\") {\n context.addIssue({\n code: \"custom\",\n message: \"untracked commit LSN must use the 0/0 sentinel\",\n path: [\"commitLsn\"],\n });\n }\n if (response.commitLsn === \"0/0\" && response.commitLsnMode !== \"untracked\") {\n context.addIssue({\n code: \"custom\",\n message: \"0/0 commit LSN must be declared untracked\",\n path: [\"commitLsnMode\"],\n });\n }\n}\n\nexport const DocumentSyncResponseSchema = registerJsonSchemaRuntimeRefinements(\n loosePlainObject({\n acceptedOutgoingUpdateIds: arraySchema(\n z.string(),\n MAX_DOCUMENT_SYNC_OUTGOING_UPDATES,\n ),\n ...commitLsnResponseShape,\n contentKeyBundles: arraySchema(DocumentContentKeyBundleResponseSchema),\n documentId: z.string(),\n pullPage: DocumentSyncPullPageResponseSchema,\n updates: arraySchema(\n DocumentSyncUpdateResponseSchema,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES,\n ),\n }).superRefine((response, context) => {\n if (\n response.pullPage !== undefined &&\n response.pullPage.hasMore !== (response.pullPage.nextCursor !== null)\n ) {\n context.addIssue({\n code: \"custom\",\n message: \"pull page continuation does not match hasMore\",\n path: [\"pullPage\", \"nextCursor\"],\n });\n }\n addCommitLsnIssues(response, context);\n addHistoricalContentKeyBundleIssues(response, context);\n }),\n [\n documentSyncResponseCommitLsnModeRefinement,\n documentSyncResponseCommitLsnSentinelRefinement,\n documentSyncResponsePullPageRefinement,\n documentSyncResponseHistoricalBundlesRefinement,\n ],\n);\n\nexport type DocumentSyncResponse = z.infer<typeof DocumentSyncResponseSchema>;\n"]}
|
|
@@ -1,6 +1,16 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** Runtime refinements the registration response adds to provisioning's. */
|
|
3
|
+
export declare const registrationCommitCheckpointRefinements: readonly [{
|
|
4
|
+
readonly description: "commitLsnMode \"untracked\" requires the commitLsn \"0/0\" sentinel";
|
|
5
|
+
readonly id: "response.untracked-commit-lsn-sentinel";
|
|
6
|
+
}, {
|
|
7
|
+
readonly description: "commitLsn \"0/0\" requires commitLsnMode \"untracked\" in the same response";
|
|
8
|
+
readonly id: "response.untracked-commit-lsn-mode";
|
|
9
|
+
}];
|
|
2
10
|
export declare const RegistrationResponseSchema: z.ZodType<{
|
|
3
11
|
challenge: string;
|
|
12
|
+
commitLsn: string | null;
|
|
13
|
+
commitLsnMode: "tracked" | "untracked";
|
|
4
14
|
committedCoreMetadataUpdateIds: string[];
|
|
5
15
|
committedProfileUpdateIds: string[];
|
|
6
16
|
organizationId: string;
|
|
@@ -172,6 +182,8 @@ export declare const RegistrationResponseSchema: z.ZodType<{
|
|
|
172
182
|
rosterProfileDocumentId?: string | undefined;
|
|
173
183
|
}, {
|
|
174
184
|
challenge: string;
|
|
185
|
+
commitLsn: string | null;
|
|
186
|
+
commitLsnMode: "tracked" | "untracked";
|
|
175
187
|
committedCoreMetadataUpdateIds: string[];
|
|
176
188
|
committedProfileUpdateIds: string[];
|
|
177
189
|
organizationId: string;
|
|
@@ -343,6 +355,8 @@ export declare const RegistrationResponseSchema: z.ZodType<{
|
|
|
343
355
|
rosterProfileDocumentId?: string | undefined;
|
|
344
356
|
}, z.core.$ZodTypeInternals<{
|
|
345
357
|
challenge: string;
|
|
358
|
+
commitLsn: string | null;
|
|
359
|
+
commitLsnMode: "tracked" | "untracked";
|
|
346
360
|
committedCoreMetadataUpdateIds: string[];
|
|
347
361
|
committedProfileUpdateIds: string[];
|
|
348
362
|
organizationId: string;
|
|
@@ -514,6 +528,8 @@ export declare const RegistrationResponseSchema: z.ZodType<{
|
|
|
514
528
|
rosterProfileDocumentId?: string | undefined;
|
|
515
529
|
}, {
|
|
516
530
|
challenge: string;
|
|
531
|
+
commitLsn: string | null;
|
|
532
|
+
commitLsnMode: "tracked" | "untracked";
|
|
517
533
|
committedCoreMetadataUpdateIds: string[];
|
|
518
534
|
committedProfileUpdateIds: string[];
|
|
519
535
|
organizationId: string;
|
|
@@ -1,11 +1,40 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { documentSyncResponseCommitLsnModeRefinement, documentSyncResponseCommitLsnSentinelRefinement, } from "../documentSyncRefinements.js";
|
|
3
|
+
import { registerJsonSchemaFragment, registerJsonSchemaRuntimeRefinements, } from "../jsonSchema.js";
|
|
2
4
|
import { organizationProvisioningCommittedUpdateIdsRefinement } from "../organizationProvisioningRefinements.js";
|
|
3
5
|
import { authChallengeHexStringSchema, loosePlainObject } from "../schema.js";
|
|
6
|
+
import { isWalLsnString, WAL_LSN_PATTERN } from "../util/walLsn.js";
|
|
7
|
+
import { addCommitLsnIssues } from "./documentSyncSchema.js";
|
|
4
8
|
import { addCommittedUpdateIdIssues, organizationProvisioningResponseShape, } from "./organizationProvisioning.js";
|
|
9
|
+
/**
|
|
10
|
+
* The commit position read after the registration transaction, as a document
|
|
11
|
+
* create's seed reports it, so the client records it for every document the
|
|
12
|
+
* registration seeded: a WAL LSN, or null when it could not be read. Only
|
|
13
|
+
* registration reports one; see `docs/client-sync-ordering.md`.
|
|
14
|
+
*/
|
|
15
|
+
const registrationCommitCheckpointShape = {
|
|
16
|
+
commitLsn: registerJsonSchemaFragment(z.string().refine(isWalLsnString), {
|
|
17
|
+
pattern: WAL_LSN_PATTERN.source,
|
|
18
|
+
type: "string",
|
|
19
|
+
}).nullable(),
|
|
20
|
+
commitLsnMode: z.union([z.literal("tracked"), z.literal("untracked")]),
|
|
21
|
+
};
|
|
22
|
+
/** Runtime refinements the registration response adds to provisioning's. */
|
|
23
|
+
export const registrationCommitCheckpointRefinements = [
|
|
24
|
+
documentSyncResponseCommitLsnModeRefinement,
|
|
25
|
+
documentSyncResponseCommitLsnSentinelRefinement,
|
|
26
|
+
];
|
|
5
27
|
export const RegistrationResponseSchema = registerJsonSchemaRuntimeRefinements(loosePlainObject({
|
|
6
28
|
...organizationProvisioningResponseShape,
|
|
29
|
+
...registrationCommitCheckpointShape,
|
|
7
30
|
challenge: authChallengeHexStringSchema,
|
|
8
|
-
}).superRefine(
|
|
31
|
+
}).superRefine((value, context) => {
|
|
32
|
+
addCommittedUpdateIdIssues(value, context);
|
|
33
|
+
addCommitLsnIssues(value, context);
|
|
34
|
+
}), [
|
|
35
|
+
organizationProvisioningCommittedUpdateIdsRefinement,
|
|
36
|
+
...registrationCommitCheckpointRefinements,
|
|
37
|
+
]);
|
|
9
38
|
export function isRegistrationResponse(value) {
|
|
10
39
|
return RegistrationResponseSchema.safeParse(value).success;
|
|
11
40
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registration.js","sourceRoot":"","sources":["registration.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"registration.js","sourceRoot":"","sources":["registration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,2CAA2C,EAC3C,+CAA+C,GAChD,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,0BAA0B,EAC1B,oCAAoC,GACrC,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,oDAAoD,EAAE,MAAM,wCAAwC,CAAC;AAC9G,OAAO,EAAE,4BAA4B,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EACL,0BAA0B,EAC1B,qCAAqC,GACtC,MAAM,4BAA4B,CAAC;AAEpC;;;;;GAKG;AACH,MAAM,iCAAiC,GAAG;IACxC,SAAS,EAAE,0BAA0B,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC,EAAE;QACvE,OAAO,EAAE,eAAe,CAAC,MAAM;QAC/B,IAAI,EAAE,QAAQ;KACf,CAAC,CAAC,QAAQ,EAAE;IACb,aAAa,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC;CAC/C,CAAC;AAE1B,4EAA4E;AAC5E,MAAM,CAAC,MAAM,uCAAuC,GAAG;IACrD,2CAA2C;IAC3C,+CAA+C;CACvC,CAAC;AAEX,MAAM,CAAC,MAAM,0BAA0B,GAAG,oCAAoC,CAC5E,gBAAgB,CAAC;IACf,GAAG,qCAAqC;IACxC,GAAG,iCAAiC;IACpC,SAAS,EAAE,4BAA4B;CACxC,CAAC,CAAC,WAAW,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;IAChC,0BAA0B,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC3C,kBAAkB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;AACrC,CAAC,CAAC,EACF;IACE,oDAAoD;IACpD,GAAG,uCAAuC;CAC3C,CACF,CAAC;AAIF,MAAM,UAAU,sBAAsB,CACpC,KAAc;IAEd,OAAO,0BAA0B,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;AAC7D,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n documentSyncResponseCommitLsnModeRefinement,\n documentSyncResponseCommitLsnSentinelRefinement,\n} from \"../documentSyncRefinements\";\nimport {\n registerJsonSchemaFragment,\n registerJsonSchemaRuntimeRefinements,\n} from \"../jsonSchema\";\nimport { organizationProvisioningCommittedUpdateIdsRefinement } from \"../organizationProvisioningRefinements\";\nimport { authChallengeHexStringSchema, loosePlainObject } from \"../schema\";\nimport { isWalLsnString, WAL_LSN_PATTERN } from \"../util/walLsn\";\nimport { addCommitLsnIssues } from \"./documentSyncSchema\";\nimport {\n addCommittedUpdateIdIssues,\n organizationProvisioningResponseShape,\n} from \"./organizationProvisioning\";\n\n/**\n * The commit position read after the registration transaction, as a document\n * create's seed reports it, so the client records it for every document the\n * registration seeded: a WAL LSN, or null when it could not be read. Only\n * registration reports one; see `docs/client-sync-ordering.md`.\n */\nconst registrationCommitCheckpointShape = {\n commitLsn: registerJsonSchemaFragment(z.string().refine(isWalLsnString), {\n pattern: WAL_LSN_PATTERN.source,\n type: \"string\",\n }).nullable(),\n commitLsnMode: z.union([z.literal(\"tracked\"), z.literal(\"untracked\")]),\n} satisfies z.ZodRawShape;\n\n/** Runtime refinements the registration response adds to provisioning's. */\nexport const registrationCommitCheckpointRefinements = [\n documentSyncResponseCommitLsnModeRefinement,\n documentSyncResponseCommitLsnSentinelRefinement,\n] as const;\n\nexport const RegistrationResponseSchema = registerJsonSchemaRuntimeRefinements(\n loosePlainObject({\n ...organizationProvisioningResponseShape,\n ...registrationCommitCheckpointShape,\n challenge: authChallengeHexStringSchema,\n }).superRefine((value, context) => {\n addCommittedUpdateIdIssues(value, context);\n addCommitLsnIssues(value, context);\n }),\n [\n organizationProvisioningCommittedUpdateIdsRefinement,\n ...registrationCommitCheckpointRefinements,\n ],\n);\n\nexport type RegistrationResponse = z.infer<typeof RegistrationResponseSchema>;\n\nexport function isRegistrationResponse(\n value: unknown,\n): value is RegistrationResponse {\n return RegistrationResponseSchema.safeParse(value).success;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -108,6 +108,9 @@ export async function createOrganization(input) {
|
|
|
108
108
|
...artifacts,
|
|
109
109
|
completeProvisioningAttempt: organizationCreationCompletion(input, artifacts.organizationId),
|
|
110
110
|
canStartDurableMutation: input.isIdentityCurrent,
|
|
111
|
+
// No position: the seeded documents are read once, as another session of
|
|
112
|
+
// this user may already have edited them.
|
|
113
|
+
commitLsn: null,
|
|
111
114
|
onPersistQueued: input.onPersistQueued,
|
|
112
115
|
containerId: durableRootContainerId,
|
|
113
116
|
dbClient: input.dbClient,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createOrganization.js","sourceRoot":"","sources":["createOrganization.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EACL,sCAAsC,EAItC,oCAAoC,GACrC,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAEL,8BAA8B,EAC9B,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,0CAA0C,EAC1C,kDAAkD,GACnD,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,kCAAkC,EAAE,MAAM,uCAAuC,CAAC;AAG3F,OAAO,EAAE,kDAAkD,EAAE,CAAC;AA+C9D,SAAS,4BAA4B,CAAC,KAIrC;IACC,IACE,KAAK,CAAC,QAAQ,CAAC,cAAc,KAAK,KAAK,CAAC,OAAO,CAAC,cAAc;QAC9D,KAAK,CAAC,QAAQ,CAAC,eAAe,KAAK,KAAK,CAAC,OAAO,CAAC,eAAe,EAChE,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IACE,CAAC,KAAK,CAAC,QAAQ,CAAC,sBAAsB;QACtC,KAAK,CAAC,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,QAAQ,CAAC,MAAM,EAC/C,CAAC;QACD,MAAM,IAAI,KAAK,CACb,+DAA+D,CAChE,CAAC;IACJ,CAAC;IACD,KAAK,CAAC,QAAQ,CAAC,GAAG,EAAE,CAClB,qCA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AsB;YACpD,QAAQ;YACR,gBAAgB,EAAE,KAAK,CAAC,cAAc,CAAC,gBAAgB;YACvD,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC;YACtC,YAAY,EAAE,KAAK,CAAC,iBAAiB;SACtC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC;IAEd,IAAI,4BAA4B,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;QACzE,yEAAyE;QACzE,4DAA4D;QAC5D,yEAAyE;QACzE,0EAA0E;QAC1E,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,GAAG,EAAE,CAAC,yBAAyB,QAAQ,CAAC,cAAc,GAAG,CAAC,CAAC;IACjE,MAAM,oCAAoC,CAAC;QACzC,GAAG,SAAS;QACZ,2BAA2B,EAAE,8BAA8B,CACzD,KAAK,EACL,SAAS,CAAC,cAAc,CACzB;QACD,uBAAuB,EAAE,KAAK,CAAC,iBAAiB;QAChD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,WAAW,EAAE,sBAAsB;QACnC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,QAAQ;KACT,CAAC,CAAC;IAEH,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n type EncapsulationKeyPair,\n type SigningKeyPair,\n signOrganizationReplacementAuthorization,\n} from \"@tearleads/crypto\";\nimport type { CreateOrganizationRequest } from \"@tearleads/validators/request\";\nimport type { CreateOrganizationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../../data/documents/documentKinds\";\nimport type { ExecSqlClientLike } from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifactsInput,\n type ProvisionedSystemContainerSpec,\n persistOrganizationProvisioningState,\n} from \"../organizationProvisioning\";\nimport type { ProvisionedStatePrimer } from \"../provisionedStatePrimer\";\nimport {\n type CreateOrganizationApi,\n organizationCreationCompletion,\n organizationCreationIntent,\n requestOrganizationCreation,\n} from \"./organizationCreationIntent\";\nimport {\n makeOrganizationProvisioningAttemptDurable,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationProvisioningAttempt\";\nimport { pinOrganizationReplacementResponse } from \"./organizationReplacementVerification\";\n\nexport type { CreateOrganizationApi } from \"./organizationCreationIntent\";\nexport { removeNativeSubscriptionRestoreProvisioningAttempt };\n\nexport interface CreateOrganizationInput {\n identityTrustDomain: string;\n apiClient: CreateOrganizationApi;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n /**\n * Returns false once the identity that supplied the key pairs is no longer\n * active. Checked before the remote create (so a stale request is never\n * submitted) and again before local persistence: an identity switch closes\n * or renews the captured database client, so persisting would write another\n * identity's bootstrap — or throw — after the org already exists remotely.\n * The caller discards the result.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /** Overrides the seeded organization profile name; see registration. */\n organizationProfileName?: string | undefined;\n /** Seeds what the committed bootstrap already proves. */\n primeProvisionedState?: ProvisionedStatePrimer | undefined;\n /**\n * App-owned system containers to provision atomically with the new\n * organization (e.g. a trash bin). See registration.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /** Purged organization whose personal-org generation this replaces. */\n replacesOrganizationId?: string | undefined;\n /** Marks and durably replays a fresh native-subscription restore target. */\n nativeSubscriptionRestore?: boolean | undefined;\n /** Overrides the seeded self roster-profile nickname; see registration. */\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n /**\n * The already-registered user creating the organization; they become its\n * founding admin. The server independently requires this to match the\n * authenticated session.\n */\n userId: string;\n}\n\nfunction isAdoptedReplacementResponse(input: {\n creation: CreateOrganizationInput;\n request: CreateOrganizationRequest;\n response: CreateOrganizationResponse;\n}): boolean {\n if (\n input.response.organizationId === input.request.organizationId &&\n input.response.rootContainerId === input.request.rootContainerId\n ) {\n return false;\n }\n if (\n !input.creation.replacesOrganizationId ||\n input.response.userId !== input.creation.userId\n ) {\n throw new Error(\n \"Organization provisioning returned an unexpected organization\",\n );\n }\n input.creation.log?.(\n `Organization replacement adopted (${input.response.organizationId})`,\n );\n return true;\n}\n\nasync function buildOrganizationCandidate(\n input: CreateOrganizationInput,\n rootContainerId: string,\n): Promise<OrganizationProvisioningArtifacts | null> {\n const artifactsInput: OrganizationProvisioningArtifactsInput = {\n identityTrustDomain: input.identityTrustDomain,\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n };\n const artifacts: OrganizationProvisioningArtifacts =\n await buildOrganizationProvisioningArtifacts(artifactsInput);\n\n if (input.replacesOrganizationId) {\n artifacts.replacementAuthorization =\n await signOrganizationReplacementAuthorization(\n {\n ...artifacts,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n },\n input.signingKeyPair,\n );\n }\n\n if (\n input.replacesOrganizationId &&\n input.isIdentityCurrent &&\n !input.isIdentityCurrent()\n ) {\n input.log?.(\n \"Organization creation aborted: identity changed while building artifacts\",\n );\n return null;\n }\n\n return artifacts;\n}\n\n/**\n * Provisions an additional organization for an already-registered user, reusing\n * the exact artifact-build and local-persistence path as registration\n * ({@link buildOrganizationProvisioningArtifacts} /\n * {@link persistOrganizationProvisioningState}). Unlike registration it mints a\n * fresh root container id, signs with the caller's existing identity, and needs\n * no auth challenge — the user is already authenticated.\n */\nexport async function createOrganization(\n input: CreateOrganizationInput,\n): Promise<CreateOrganizationResponse | null> {\n input.log?.(\"Creating organization...\");\n\n const rootContainerId = crypto.randomUUID();\n const candidateArtifacts = await buildOrganizationCandidate(\n input,\n rootContainerId,\n );\n\n if (!candidateArtifacts) return null;\n\n const durableAttempt = await makeOrganizationProvisioningAttemptDurable({\n artifacts: candidateArtifacts,\n creationIntent: organizationCreationIntent(input),\n canStartDurableMutation: input.isIdentityCurrent,\n dbClient: input.dbClient,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n });\n if (!durableAttempt) {\n input.log?.(\n \"Organization creation aborted: identity changed before saving artifacts\",\n );\n return null;\n }\n const {\n artifacts,\n request,\n rootContainerId: durableRootContainerId,\n } = durableAttempt;\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation aborted: identity changed before provisioning\",\n );\n return null;\n }\n\n const response = await requestOrganizationCreation(input, request);\n if (!response) return null;\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation discarded: identity changed while provisioning\",\n );\n return null;\n }\n\n if (\n input.replacesOrganizationId &&\n !(await pinOrganizationReplacementResponse({\n replacesOrganizationId: input.replacesOrganizationId,\n response,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n userId: input.userId,\n execSql: createExecSql(input.dbClient),\n stillCurrent: input.isIdentityCurrent,\n }))\n )\n return null;\n\n if (isAdoptedReplacementResponse({ creation: input, request, response })) {\n // Another device authorized this winning genesis with the same identity.\n // Its encrypted bootstrap will hydrate normally; persisting\n // this device's losing candidate would instead create an unrelated local\n // root. The session reset rebinds retained local data to the winning ids.\n return response;\n }\n\n input.log?.(`Organization created (${response.organizationId})`);\n await persistOrganizationProvisioningState({\n ...artifacts,\n completeProvisioningAttempt: organizationCreationCompletion(\n input,\n artifacts.organizationId,\n ),\n canStartDurableMutation: input.isIdentityCurrent,\n onPersistQueued: input.onPersistQueued,\n containerId: durableRootContainerId,\n dbClient: input.dbClient,\n documentProjectors: input.documentProjectors,\n log: input.log,\n logError: input.logError,\n primeProvisionedState: input.primeProvisionedState,\n response,\n });\n\n return response;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"createOrganization.js","sourceRoot":"","sources":["createOrganization.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EACL,sCAAsC,EAItC,oCAAoC,GACrC,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAEL,8BAA8B,EAC9B,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,0CAA0C,EAC1C,kDAAkD,GACnD,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,kCAAkC,EAAE,MAAM,uCAAuC,CAAC;AAG3F,OAAO,EAAE,kDAAkD,EAAE,CAAC;AA+C9D,SAAS,4BAA4B,CAAC,KAIrC;IACC,IACE,KAAK,CAAC,QAAQ,CAAC,cAAc,KAAK,KAAK,CAAC,OAAO,CAAC,cAAc;QAC9D,KAAK,CAAC,QAAQ,CAAC,eAAe,KAAK,KAAK,CAAC,OAAO,CAAC,eAAe,EAChE,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IACE,CAAC,KAAK,CAAC,QAAQ,CAAC,sBAAsB;QACtC,KAAK,CAAC,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,QAAQ,CAAC,MAAM,EAC/C,CAAC;QAC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from \"@tearleads/crypto\";\nimport type { CreateOrganizationRequest } from \"@tearleads/validators/request\";\nimport type { CreateOrganizationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../../data/documents/documentKinds\";\nimport type { ExecSqlClientLike } from \"../../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n buildOrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifacts,\n type OrganizationProvisioningArtifactsInput,\n type ProvisionedSystemContainerSpec,\n persistOrganizationProvisioningState,\n} from \"../organizationProvisioning\";\nimport type { ProvisionedStatePrimer } from \"../provisionedStatePrimer\";\nimport {\n type CreateOrganizationApi,\n organizationCreationCompletion,\n organizationCreationIntent,\n requestOrganizationCreation,\n} from \"./organizationCreationIntent\";\nimport {\n makeOrganizationProvisioningAttemptDurable,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationProvisioningAttempt\";\nimport { pinOrganizationReplacementResponse } from \"./organizationReplacementVerification\";\n\nexport type { CreateOrganizationApi } from \"./organizationCreationIntent\";\nexport { removeNativeSubscriptionRestoreProvisioningAttempt };\n\nexport interface CreateOrganizationInput {\n identityTrustDomain: string;\n apiClient: CreateOrganizationApi;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n /**\n * Returns false once the identity that supplied the key pairs is no longer\n * active. Checked before the remote create (so a stale request is never\n * submitted) and again before local persistence: an identity switch closes\n * or renews the captured database client, so persisting would write another\n * identity's bootstrap — or throw — after the org already exists remotely.\n * The caller discards the result.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /** Overrides the seeded organization profile name; see registration. */\n organizationProfileName?: string | undefined;\n /** Seeds what the committed bootstrap already proves. */\n primeProvisionedState?: ProvisionedStatePrimer | undefined;\n /**\n * App-owned system containers to provision atomically with the new\n * organization (e.g. a trash bin). See registration.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /** Purged organization whose personal-org generation this replaces. */\n replacesOrganizationId?: string | undefined;\n /** Marks and durably replays a fresh native-subscription restore target. */\n nativeSubscriptionRestore?: boolean | undefined;\n /** Overrides the seeded self roster-profile nickname; see registration. */\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n /**\n * The already-registered user creating the organization; they become its\n * founding admin. The server independently requires this to match the\n * authenticated session.\n */\n userId: string;\n}\n\nfunction isAdoptedReplacementResponse(input: {\n creation: CreateOrganizationInput;\n request: CreateOrganizationRequest;\n response: CreateOrganizationResponse;\n}): boolean {\n if (\n input.response.organizationId === input.request.organizationId &&\n input.response.rootContainerId === input.request.rootContainerId\n ) {\n return false;\n }\n if (\n !input.creation.replacesOrganizationId ||\n input.response.userId !== input.creation.userId\n ) {\n throw new Error(\n \"Organization provisioning returned an unexpected organization\",\n );\n }\n input.creation.log?.(\n `Organization replacement adopted (${input.response.organizationId})`,\n );\n return true;\n}\n\nasync function buildOrganizationCandidate(\n input: CreateOrganizationInput,\n rootContainerId: string,\n): Promise<OrganizationProvisioningArtifacts | null> {\n const artifactsInput: OrganizationProvisioningArtifactsInput = {\n identityTrustDomain: input.identityTrustDomain,\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n };\n const artifacts: OrganizationProvisioningArtifacts =\n await buildOrganizationProvisioningArtifacts(artifactsInput);\n\n if (input.replacesOrganizationId) {\n artifacts.replacementAuthorization =\n await signOrganizationReplacementAuthorization(\n {\n ...artifacts,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n },\n input.signingKeyPair,\n );\n }\n\n if (\n input.replacesOrganizationId &&\n input.isIdentityCurrent &&\n !input.isIdentityCurrent()\n ) {\n input.log?.(\n \"Organization creation aborted: identity changed while building artifacts\",\n );\n return null;\n }\n\n return artifacts;\n}\n\n/**\n * Provisions an additional organization for an already-registered user, reusing\n * the exact artifact-build and local-persistence path as registration\n * ({@link buildOrganizationProvisioningArtifacts} /\n * {@link persistOrganizationProvisioningState}). Unlike registration it mints a\n * fresh root container id, signs with the caller's existing identity, and needs\n * no auth challenge — the user is already authenticated.\n */\nexport async function createOrganization(\n input: CreateOrganizationInput,\n): Promise<CreateOrganizationResponse | null> {\n input.log?.(\"Creating organization...\");\n\n const rootContainerId = crypto.randomUUID();\n const candidateArtifacts = await buildOrganizationCandidate(\n input,\n rootContainerId,\n );\n\n if (!candidateArtifacts) return null;\n\n const durableAttempt = await makeOrganizationProvisioningAttemptDurable({\n artifacts: candidateArtifacts,\n creationIntent: organizationCreationIntent(input),\n canStartDurableMutation: input.isIdentityCurrent,\n dbClient: input.dbClient,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n replacesOrganizationId: input.replacesOrganizationId,\n rootContainerId,\n userId: input.userId,\n });\n if (!durableAttempt) {\n input.log?.(\n \"Organization creation aborted: identity changed before saving artifacts\",\n );\n return null;\n }\n const {\n artifacts,\n request,\n rootContainerId: durableRootContainerId,\n } = durableAttempt;\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation aborted: identity changed before provisioning\",\n );\n return null;\n }\n\n const response = await requestOrganizationCreation(input, request);\n if (!response) return null;\n\n if (input.isIdentityCurrent && !input.isIdentityCurrent()) {\n input.log?.(\n \"Organization creation discarded: identity changed while provisioning\",\n );\n return null;\n }\n\n if (\n input.replacesOrganizationId &&\n !(await pinOrganizationReplacementResponse({\n replacesOrganizationId: input.replacesOrganizationId,\n response,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n userId: input.userId,\n execSql: createExecSql(input.dbClient),\n stillCurrent: input.isIdentityCurrent,\n }))\n )\n return null;\n\n if (isAdoptedReplacementResponse({ creation: input, request, response })) {\n // Another device authorized this winning genesis with the same identity.\n // Its encrypted bootstrap will hydrate normally; persisting\n // this device's losing candidate would instead create an unrelated local\n // root. The session reset rebinds retained local data to the winning ids.\n return response;\n }\n\n input.log?.(`Organization created (${response.organizationId})`);\n await persistOrganizationProvisioningState({\n ...artifacts,\n completeProvisioningAttempt: organizationCreationCompletion(\n input,\n artifacts.organizationId,\n ),\n canStartDurableMutation: input.isIdentityCurrent,\n // No position: the seeded documents are read once, as another session of\n // this user may already have edited them.\n commitLsn: null,\n onPersistQueued: input.onPersistQueued,\n containerId: durableRootContainerId,\n dbClient: input.dbClient,\n documentProjectors: input.documentProjectors,\n log: input.log,\n logError: input.logError,\n primeProvisionedState: input.primeProvisionedState,\n response,\n });\n\n return response;\n}\n"]}
|
|
@@ -10,6 +10,13 @@ type PersistOrganizationProvisioningStateInput = Pick<OrganizationProvisioningAr
|
|
|
10
10
|
readonly canStartDurableMutation?: (() => boolean) | undefined;
|
|
11
11
|
/** @internal Forwarded to the bootstrap persist; test-only seam. */
|
|
12
12
|
readonly onPersistQueued?: (() => void) | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* The commit position to record for every seeded document: registration's,
|
|
15
|
+
* or null for an additional organization, which reports none because
|
|
16
|
+
* another session of its creator can edit those documents before this
|
|
17
|
+
* device subscribes to them.
|
|
18
|
+
*/
|
|
19
|
+
readonly commitLsn: string | null;
|
|
13
20
|
readonly containerId: string;
|
|
14
21
|
readonly dbClient: ExecSqlClientLike;
|
|
15
22
|
readonly documentProjectors?: DocumentProjectorRegistryInput | undefined;
|
|
@@ -152,6 +152,7 @@ export async function persistOrganizationProvisioningState(input) {
|
|
|
152
152
|
acknowledgedAccessHeads: artifacts.acknowledgedAccessHeads,
|
|
153
153
|
authoredDiscoveryHeads: artifacts.authoredDiscoveryHeads,
|
|
154
154
|
canStartDurableMutation: input.canStartDurableMutation,
|
|
155
|
+
commitLsn: input.commitLsn,
|
|
155
156
|
completeProvisioningAttempt: input.completeProvisioningAttempt,
|
|
156
157
|
onPersistQueued: input.onPersistQueued,
|
|
157
158
|
containerId: input.containerId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationProvisioningPersistence.js","sourceRoot":"","sources":["organizationProvisioningPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,wCAAwC,EAAE,MAAM,uCAAuC,CAAC;AAEjG,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,OAAO,EAAE,uCAAuC,EAAE,MAAM,gCAAgC,CAAC;AACzF,OAAO,EACL,sCAAsC,EACtC,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAGvC,OAAO,EACL,mCAAmC,EACnC,0BAA0B,GAC3B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,4CAA4C,EAC5C,mDAAmD,GACpD,MAAM,0CAA0C,CAAC;AAuClD,SAAS,kCAAkC,CACzC,QAA0C,EAC1C,QAAiB;IAEjB,OAAO,CACL,QAAQ,KAAK,SAAS;QACtB,QAAQ,CAAC,8BAA8B,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAC3D,CAAC;AACJ,CAAC;AAED,SAAS,gCAAgC,CACvC,QAA0C,EAC1C,SAA4E,EAC5E,SAOC;IAED,OAAO;QACL,WAAW,EAAE,SAAS,CAAC,SAAS,CAAC,YAAY,CAAC,KAAK;QACnD,eAAe,EAAE,SAAS,CAAC,SAAS,CAAC,YAAY,CAAC,YAAY;QAC9D,WAAW,EAAE,SAAS,CAAC,WAAW;QAClC,SAAS,EAAE,SAAS,CAAC,SAAS,CAAC,SAAS;QACxC,kBAAkB,EAAE,SAAS,CAAC,gBAAgB,CAAC,EAAE;QACjD,qBAAqB,EAAE,SAAS,CAAC,8BAA8B;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AC;QACF,KAAK,CAAC,GAAG,EAAE,CACT,SAAS;YACP,CAAC,CAAC,wCAAwC;YAC1C,CAAC,CAAC,yDAAyD,CAC9D,CAAC;QACF,IAAI,SAAS;YACX,MAAM,KAAK,CAAC,qBAAqB,EAAE,CAAC;gBAClC,UAAU,EAAE,yBAAyB,CAAC,KAAK,CAAC;gBAC5C,QAAQ,EAAE,KAAK,CAAC,QAAQ;gBACxB,SAAS,EAAE,KAAK,CAAC,uBAAuB,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC;gBACxD,cAAc,EAAE,KAAK,CAAC,QAAQ,CAAC,cAAc;gBAC7C,QAAQ,EAAE;oBACR,UAAU,EAAE,SAAS,CAAC,uBAAuB;oBAC7C,WAAW,EAAE,SAAS,CAAC,wBAAwB;oBAC/C,YAAY,EAAE,SAAS,CAAC,yBAAyB;iBAClD;gBACD,eAAe,EAAE,KAAK,CAAC,QAAQ,CAAC,eAAe;gBAC/C,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,MAAM;aAC9B,CAAC,CAAC;IACP,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;YACnB,KAAK,CAAC,QAAQ,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAC/D,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,KAAK,CAAC,sCAAsC,EAAE,KAAK,CAAC,CAAC;QAC/D,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { OrganizationProvisioningResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { persistedDocumentCreateStateFromResponse } from \"../../data/documents/shared/responses\";\nimport type { ExecSql, ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport { persistRegistrationBootstrapFromExecSql } from \"./persistRegistrationBootstrap\";\nimport {\n buildOrganizationProfileBootstrapInput,\n buildRosterProfileBootstrapInput,\n} from \"./profileBootstrapPersistence\";\nimport type { ProvisionedContainerSeed } from \"./provisionedContainerSeeds\";\nimport type { ProvisionedStatePrimer } from \"./provisionedStatePrimer\";\nimport {\n provisioningAcknowledgedAccessHeads,\n provisioningDiscoveryHeads,\n} from \"./provisioningAcknowledgement\";\nimport {\n principalPolicyBundleFromInitialGroupRequest,\n principalPolicyBundleFromInitialOrganizationRequest,\n} from \"./registrationPrincipalPolicyPersistence\";\n\ntype PersistOrganizationProvisioningStateInput = Pick<\n OrganizationProvisioningArtifacts,\n | \"bootstrap\"\n | \"initialAdminGroup\"\n | \"initialMemberGroup\"\n | \"initialOrganizationPolicy\"\n | \"organizationMetadataBootstrap\"\n | \"rootContainer\"\n | \"rootMetadataDocument\"\n | \"rootMetadataDocumentRequest\"\n | \"rosterProfileBootstrap\"\n | \"systemContainerBootstraps\"\n> & {\n /** @internal Runs inside the guarded bootstrap transaction, never after commit. */\n readonly completeProvisioningAttempt?:\n | ((execSql: ExecSql) => Promise<void>)\n | undefined;\n /** Forwarded to the bootstrap persist's in-mutex currency check. */\n readonly canStartDurableMutation?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n readonly onPersistQueued?: (() => void) | undefined;\n readonly containerId: string;\n readonly dbClient: ExecSqlClientLike;\n readonly documentProjectors?: DocumentProjectorRegistryInput | undefined;\n readonly log?: ((message: string) => void) | undefined;\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n /** Seeds what the bootstrap proves once it commits. */\n readonly primeProvisionedState?: ProvisionedStatePrimer | undefined;\n readonly response: OrganizationProvisioningResponse;\n};\n\ntype PersistBootstrapInput = Parameters<\n typeof persistRegistrationBootstrapFromExecSql\n>[1];\n\nfunction coreMetadataInitialUpdateCommitted(\n response: OrganizationProvisioningResponse,\n updateId?: string,\n): boolean {\n return (\n updateId !== undefined &&\n response.committedCoreMetadataUpdateIds.includes(updateId)\n );\n}\n\nfunction buildCoreContainerBootstrapInput(\n response: OrganizationProvisioningResponse,\n container: OrganizationProvisioningResponse[\"organizationMetadataContainer\"],\n bootstrap: Pick<\n OrganizationProvisioningArtifacts[\"rosterProfileBootstrap\"],\n | \"containerId\"\n | \"containerMetadataDocument\"\n | \"containerMetadataInitialUpdate\"\n | \"containerRequest\"\n | \"systemSlot\"\n >,\n): NonNullable<PersistBootstrapInput[\"organizationMetadataContainer\"]> {\n return {\n accessEpoch: container.container.manifestHead.epoch,\n accessStateHash: container.container.manifestHead.manifestHash,\n containerId: bootstrap.containerId,\n createdAt: container.container.createdAt,\n metadataDocumentId: container.metadataDocument.id,\n metadataInitialUpdate: bootstrap.containerMetadataInitialUpdate,\n metadataInitialUpdateCommitted: coreMetadataInitialUpdateCommitted(\n response,\n bootstrap.containerRequest.initialMetadataSync.outgoingUpdates[0]?.id,\n ),\n metadataSnapshot: bytesToBase64(bootstrap.containerMetadataInitialUpdate),\n metadataState: persistedDocumentCreateStateFromResponse(\n bootstrap.containerMetadataDocument.plan,\n container.metadataDocument,\n ),\n systemSlot: bootstrap.systemSlot,\n updatedAt: container.container.updatedAt,\n };\n}\n\nfunction buildSystemContainersBootstrapInput(\n input: PersistOrganizationProvisioningStateInput,\n): PersistBootstrapInput[\"systemContainers\"] {\n const responses = input.response.systemContainers;\n if (responses.length === 0) {\n return;\n }\n const responseByContainerId = new Map(\n responses.map((response) => [response.container.containerId, response]),\n );\n const entries: NonNullable<PersistBootstrapInput[\"systemContainers\"]> = [];\n for (const bootstrap of input.systemContainerBootstraps) {\n const response = responseByContainerId.get(bootstrap.containerId);\n if (!response) {\n continue;\n }\n entries.push({\n accessEpoch: response.container.manifestHead.epoch,\n accessStateHash: response.container.manifestHead.manifestHash,\n containerId: bootstrap.containerId,\n createdAt: response.container.createdAt,\n icon: bootstrap.icon,\n metadataDocumentId: response.metadataDocument.id,\n metadataSnapshot: bytesToBase64(bootstrap.containerMetadataInitialUpdate),\n metadataState: persistedDocumentCreateStateFromResponse(\n bootstrap.containerMetadataDocument.plan,\n response.metadataDocument,\n ),\n name: bootstrap.name,\n systemSlot: bootstrap.systemSlot,\n updatedAt: response.container.updatedAt,\n });\n }\n return entries.length > 0 ? entries : undefined;\n}\n\n/** Every container the request created, with the head the response acknowledged. */\nfunction provisionedContainerSeeds(\n input: PersistOrganizationProvisioningStateInput,\n): ProvisionedContainerSeed[] {\n const { response } = input;\n const systemHeads = new Map(\n response.systemContainers.map(({ container }) => [\n container.containerId,\n container.manifestHead.manifestHash,\n ]),\n );\n return [\n {\n acknowledgedManifestHash: response.rootMetadataAccessStateHash,\n plan: input.rootContainer.plan,\n },\n {\n acknowledgedManifestHash:\n response.rosterProfileContainer?.container.manifestHead.manifestHash,\n plan: input.rosterProfileBootstrap.containerPlan.plan,\n },\n {\n acknowledgedManifestHash:\n response.organizationMetadataContainer.container.manifestHead\n .manifestHash,\n plan: input.organizationMetadataBootstrap.containerPlan.plan,\n },\n ...input.systemContainerBootstraps.map((bootstrap) => ({\n acknowledgedManifestHash: systemHeads.get(bootstrap.containerId),\n plan: bootstrap.containerPlan.plan,\n })),\n ];\n}\n\nasync function buildProvisioningPersistenceArtifacts(\n input: PersistOrganizationProvisioningStateInput,\n) {\n const acknowledgedAccessHeads = await provisioningAcknowledgedAccessHeads({\n expectedOrganizationId: input.rootContainer.plan.state.organizationId,\n expectedUserId: input.rootContainer.plan.event.signerUserId,\n organizationMetadata: {\n containerPlan: input.organizationMetadataBootstrap.containerPlan.plan,\n metadataDocumentPlan:\n input.organizationMetadataBootstrap.containerMetadataDocument.plan,\n },\n organizationProfileDocumentPlan:\n input.organizationMetadataBootstrap.organizationProfileDocument.plan,\n response: input.response,\n rootContainerPlan: input.rootContainer.plan,\n rootMetadataDocumentPlan: input.rootMetadataDocument.plan,\n rosterProfile: {\n containerPlan: input.rosterProfileBootstrap.containerPlan.plan,\n metadataDocumentPlan:\n input.rosterProfileBootstrap.containerMetadataDocument.plan,\n },\n rosterProfileDocumentPlan:\n input.rosterProfileBootstrap.profileDocument.plan,\n systemContainers: input.systemContainerBootstraps.map((bootstrap) => ({\n containerPlan: bootstrap.containerPlan.plan,\n metadataDocumentPlan: bootstrap.containerMetadataDocument.plan,\n })),\n });\n const [\n initialAdminGroupPolicy,\n initialMemberGroupPolicy,\n initialOrganizationPolicy,\n ] = await Promise.all([\n principalPolicyBundleFromInitialGroupRequest(input.initialAdminGroup),\n principalPolicyBundleFromInitialGroupRequest(input.initialMemberGroup),\n principalPolicyBundleFromInitialOrganizationRequest(\n input.initialOrganizationPolicy,\n ),\n ]);\n return {\n acknowledgedAccessHeads,\n // Discovery lists the seeded profile documents; their signed heads are the\n // ones this client just authored and the server acknowledged.\n authoredDiscoveryHeads: provisioningDiscoveryHeads([\n {\n plan: input.rosterProfileBootstrap.profileDocument.plan,\n response: input.response.rosterProfileDocument,\n },\n {\n plan: input.organizationMetadataBootstrap.organizationProfileDocument\n .plan,\n response: input.response.organizationProfileDocument,\n },\n ]),\n initialAdminGroupPolicy,\n initialMemberGroupPolicy,\n initialOrganizationPolicy,\n organizationMetadataContainer: buildCoreContainerBootstrapInput(\n input.response,\n input.response.organizationMetadataContainer,\n input.organizationMetadataBootstrap,\n ),\n organizationProfileDocument: buildOrganizationProfileBootstrapInput({\n containerId: input.organizationMetadataBootstrap.containerId,\n materializedDocument:\n input.organizationMetadataBootstrap.organizationProfileDocument,\n request:\n input.organizationMetadataBootstrap.organizationProfileDocumentRequest,\n response: input.response,\n snapshot: input.organizationMetadataBootstrap.organizationProfileSnapshot,\n }),\n rosterProfileContainer: input.response.rosterProfileContainer\n ? buildCoreContainerBootstrapInput(\n input.response,\n input.response.rosterProfileContainer,\n input.rosterProfileBootstrap,\n )\n : undefined,\n rosterProfileDocument: buildRosterProfileBootstrapInput({\n containerId: input.rosterProfileBootstrap.containerId,\n initialUpdate: input.rosterProfileBootstrap.profileDocumentInitialUpdate,\n materializedDocument: input.rosterProfileBootstrap.profileDocument,\n request: input.rosterProfileBootstrap.profileDocumentRequest,\n response: input.response,\n }),\n systemContainers: buildSystemContainersBootstrapInput(input),\n };\n}\n\nexport async function persistOrganizationProvisioningState(\n input: PersistOrganizationProvisioningStateInput,\n): Promise<void> {\n try {\n const artifacts = await buildProvisioningPersistenceArtifacts(input);\n const persisted = await persistRegistrationBootstrapFromExecSql(\n createExecSql(input.dbClient),\n {\n acknowledgedAccessHeads: artifacts.acknowledgedAccessHeads,\n authoredDiscoveryHeads: artifacts.authoredDiscoveryHeads,\n canStartDurableMutation: input.canStartDurableMutation,\n completeProvisioningAttempt: input.completeProvisioningAttempt,\n onPersistQueued: input.onPersistQueued,\n containerId: input.containerId,\n documentProjectors: input.documentProjectors,\n initialAdminGroupPolicy: artifacts.initialAdminGroupPolicy,\n initialMemberGroupPolicy: artifacts.initialMemberGroupPolicy,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n organizationId: input.response.organizationId,\n // The provisioning response does not expose the root container's own\n // timestamps. Its metadata document is created in the same transaction,\n // so its server timestamp is the acknowledged remote anchor for the\n // locally persisted root row.\n rootContainerServerTimestamp:\n input.response.rootMetadataDocument.createdAt,\n rootMetadataAccessEpoch: input.response.rootMetadataAccessEpoch,\n rootMetadataAccessStateHash: input.response.rootMetadataAccessStateHash,\n rootMetadataDocumentId: input.response.rootMetadataDocumentId,\n rootMetadataInitialUpdate: input.bootstrap.initialUpdate,\n rootMetadataInitialUpdateCommitted: coreMetadataInitialUpdateCommitted(\n input.response,\n input.rootMetadataDocumentRequest.initialSync.outgoingUpdates[0]?.id,\n ),\n rootMetadataSnapshot: bytesToBase64(input.bootstrap.initialUpdate),\n rootMetadataState: persistedDocumentCreateStateFromResponse(\n input.rootMetadataDocument.plan,\n input.response.rootMetadataDocument,\n ),\n ...(artifacts.rosterProfileContainer\n ? { rosterProfileContainer: artifacts.rosterProfileContainer }\n : {}),\n organizationMetadataContainer: artifacts.organizationMetadataContainer,\n ...(artifacts.organizationProfileDocument\n ? {\n organizationProfileDocument:\n artifacts.organizationProfileDocument,\n }\n : {}),\n ...(artifacts.rosterProfileDocument\n ? { rosterProfileDocument: artifacts.rosterProfileDocument }\n : {}),\n ...(artifacts.systemContainers\n ? { systemContainers: artifacts.systemContainers }\n : {}),\n userId: input.response.userId,\n },\n );\n input.log?.(\n persisted\n ? \"Local organization bootstrap persisted\"\n : \"Local organization bootstrap skipped: identity replaced\",\n );\n if (persisted)\n await input.primeProvisionedState?.({\n containers: provisionedContainerSeeds(input),\n database: input.dbClient,\n isCurrent: input.canStartDurableMutation ?? (() => true),\n organizationId: input.response.organizationId,\n policies: {\n adminGroup: artifacts.initialAdminGroupPolicy,\n memberGroup: artifacts.initialMemberGroupPolicy,\n organization: artifacts.initialOrganizationPolicy,\n },\n rootContainerId: input.response.rootContainerId,\n userId: input.response.userId,\n });\n } catch (error: unknown) {\n if (input.logError) {\n input.logError(\"Failed to persist registration data\", error);\n } else {\n console.error(\"Failed to persist registration data:\", error);\n }\n throw error;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"organizationProvisioningPersistence.js","sourceRoot":"","sources":["organizationProvisioningPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,wCAAwC,EAAE,MAAM,uCAAuC,CAAC;AAEjG,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,OAAO,EAAE,uCAAuC,EAAE,MAAM,gCAAgC,CAAC;AACzF,OAAO,EACL,sCAAsC,EACtC,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAGvC,OAAO,EACL,mCAAmC,EACnC,0BAA0B,GAC3B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,4CAA4C,EAC5C,mDAAmD,GACpD,MAAM,0CAA0C,CAAC;AA8ClD,SAAS,kCAAkC,CAC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AO,KAAc,EAAE,CAAC;QACxB,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;YACnB,KAAK,CAAC,QAAQ,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAC/D,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,KAAK,CAAC,sCAAsC,EAAE,KAAK,CAAC,CAAC;QAC/D,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { OrganizationProvisioningResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { persistedDocumentCreateStateFromResponse } from \"../../data/documents/shared/responses\";\nimport type { ExecSql, ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport { createExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport { persistRegistrationBootstrapFromExecSql } from \"./persistRegistrationBootstrap\";\nimport {\n buildOrganizationProfileBootstrapInput,\n buildRosterProfileBootstrapInput,\n} from \"./profileBootstrapPersistence\";\nimport type { ProvisionedContainerSeed } from \"./provisionedContainerSeeds\";\nimport type { ProvisionedStatePrimer } from \"./provisionedStatePrimer\";\nimport {\n provisioningAcknowledgedAccessHeads,\n provisioningDiscoveryHeads,\n} from \"./provisioningAcknowledgement\";\nimport {\n principalPolicyBundleFromInitialGroupRequest,\n principalPolicyBundleFromInitialOrganizationRequest,\n} from \"./registrationPrincipalPolicyPersistence\";\n\ntype PersistOrganizationProvisioningStateInput = Pick<\n OrganizationProvisioningArtifacts,\n | \"bootstrap\"\n | \"initialAdminGroup\"\n | \"initialMemberGroup\"\n | \"initialOrganizationPolicy\"\n | \"organizationMetadataBootstrap\"\n | \"rootContainer\"\n | \"rootMetadataDocument\"\n | \"rootMetadataDocumentRequest\"\n | \"rosterProfileBootstrap\"\n | \"systemContainerBootstraps\"\n> & {\n /** @internal Runs inside the guarded bootstrap transaction, never after commit. */\n readonly completeProvisioningAttempt?:\n | ((execSql: ExecSql) => Promise<void>)\n | undefined;\n /** Forwarded to the bootstrap persist's in-mutex currency check. */\n readonly canStartDurableMutation?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n readonly onPersistQueued?: (() => void) | undefined;\n /**\n * The commit position to record for every seeded document: registration's,\n * or null for an additional organization, which reports none because\n * another session of its creator can edit those documents before this\n * device subscribes to them.\n */\n readonly commitLsn: string | null;\n readonly containerId: string;\n readonly dbClient: ExecSqlClientLike;\n readonly documentProjectors?: DocumentProjectorRegistryInput | undefined;\n readonly log?: ((message: string) => void) | undefined;\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n /** Seeds what the bootstrap proves once it commits. */\n readonly primeProvisionedState?: ProvisionedStatePrimer | undefined;\n readonly response: OrganizationProvisioningResponse;\n};\n\ntype PersistBootstrapInput = Parameters<\n typeof persistRegistrationBootstrapFromExecSql\n>[1];\n\nfunction coreMetadataInitialUpdateCommitted(\n response: OrganizationProvisioningResponse,\n updateId?: string,\n): boolean {\n return (\n updateId !== undefined &&\n response.committedCoreMetadataUpdateIds.includes(updateId)\n );\n}\n\nfunction buildCoreContainerBootstrapInput(\n response: OrganizationProvisioningResponse,\n container: OrganizationProvisioningResponse[\"organizationMetadataContainer\"],\n bootstrap: Pick<\n OrganizationProvisioningArtifacts[\"rosterProfileBootstrap\"],\n | \"containerId\"\n | \"containerMetadataDocument\"\n | \"containerMetadataInitialUpdate\"\n | \"containerRequest\"\n | \"systemSlot\"\n >,\n): NonNullable<PersistBootstrapInput[\"organizationMetadataContainer\"]> {\n return {\n accessEpoch: container.container.manifestHead.epoch,\n accessStateHash: container.container.manifestHead.manifestHash,\n containerId: bootstrap.containerId,\n createdAt: container.container.createdAt,\n metadataDocumentId: container.metadataDocument.id,\n metadataInitialUpdate: bootstrap.containerMetadataInitialUpdate,\n metadataInitialUpdateCommitted: coreMetadataInitialUpdateCommitted(\n response,\n bootstrap.containerRequest.initialMetadataSync.outgoingUpdates[0]?.id,\n ),\n metadataSnapshot: bytesToBase64(bootstrap.containerMetadataInitialUpdate),\n metadataState: persistedDocumentCreateStateFromResponse(\n bootstrap.containerMetadataDocument.plan,\n container.metadataDocument,\n ),\n systemSlot: bootstrap.systemSlot,\n updatedAt: container.container.updatedAt,\n };\n}\n\nfunction buildSystemContainersBootstrapInput(\n input: PersistOrganizationProvisioningStateInput,\n): PersistBootstrapInput[\"systemContainers\"] {\n const responses = input.response.systemContainers;\n if (responses.length === 0) {\n return;\n }\n const responseByContainerId = new Map(\n responses.map((response) => [response.container.containerId, response]),\n );\n const entries: NonNullable<PersistBootstrapInput[\"systemContainers\"]> = [];\n for (const bootstrap of input.systemContainerBootstraps) {\n const response = responseByContainerId.get(bootstrap.containerId);\n if (!response) {\n continue;\n }\n entries.push({\n accessEpoch: response.container.manifestHead.epoch,\n accessStateHash: response.container.manifestHead.manifestHash,\n containerId: bootstrap.containerId,\n createdAt: response.container.createdAt,\n icon: bootstrap.icon,\n metadataDocumentId: response.metadataDocument.id,\n metadataSnapshot: bytesToBase64(bootstrap.containerMetadataInitialUpdate),\n metadataState: persistedDocumentCreateStateFromResponse(\n bootstrap.containerMetadataDocument.plan,\n response.metadataDocument,\n ),\n name: bootstrap.name,\n systemSlot: bootstrap.systemSlot,\n updatedAt: response.container.updatedAt,\n });\n }\n return entries.length > 0 ? entries : undefined;\n}\n\n/** Every container the request created, with the head the response acknowledged. */\nfunction provisionedContainerSeeds(\n input: PersistOrganizationProvisioningStateInput,\n): ProvisionedContainerSeed[] {\n const { response } = input;\n const systemHeads = new Map(\n response.systemContainers.map(({ container }) => [\n container.containerId,\n container.manifestHead.manifestHash,\n ]),\n );\n return [\n {\n acknowledgedManifestHash: response.rootMetadataAccessStateHash,\n plan: input.rootContainer.plan,\n },\n {\n acknowledgedManifestHash:\n response.rosterProfileContainer?.container.manifestHead.manifestHash,\n plan: input.rosterProfileBootstrap.containerPlan.plan,\n },\n {\n acknowledgedManifestHash:\n response.organizationMetadataContainer.container.manifestHead\n .manifestHash,\n plan: input.organizationMetadataBootstrap.containerPlan.plan,\n },\n ...input.systemContainerBootstraps.map((bootstrap) => ({\n acknowledgedManifestHash: systemHeads.get(bootstrap.containerId),\n plan: bootstrap.containerPlan.plan,\n })),\n ];\n}\n\nasync function buildProvisioningPersistenceArtifacts(\n input: PersistOrganizationProvisioningStateInput,\n) {\n const acknowledgedAccessHeads = await provisioningAcknowledgedAccessHeads({\n expectedOrganizationId: input.rootContainer.plan.state.organizationId,\n expectedUserId: input.rootContainer.plan.event.signerUserId,\n organizationMetadata: {\n containerPlan: input.organizationMetadataBootstrap.containerPlan.plan,\n metadataDocumentPlan:\n input.organizationMetadataBootstrap.containerMetadataDocument.plan,\n },\n organizationProfileDocumentPlan:\n input.organizationMetadataBootstrap.organizationProfileDocument.plan,\n response: input.response,\n rootContainerPlan: input.rootContainer.plan,\n rootMetadataDocumentPlan: input.rootMetadataDocument.plan,\n rosterProfile: {\n containerPlan: input.rosterProfileBootstrap.containerPlan.plan,\n metadataDocumentPlan:\n input.rosterProfileBootstrap.containerMetadataDocument.plan,\n },\n rosterProfileDocumentPlan:\n input.rosterProfileBootstrap.profileDocument.plan,\n systemContainers: input.systemContainerBootstraps.map((bootstrap) => ({\n containerPlan: bootstrap.containerPlan.plan,\n metadataDocumentPlan: bootstrap.containerMetadataDocument.plan,\n })),\n });\n const [\n initialAdminGroupPolicy,\n initialMemberGroupPolicy,\n initialOrganizationPolicy,\n ] = await Promise.all([\n principalPolicyBundleFromInitialGroupRequest(input.initialAdminGroup),\n principalPolicyBundleFromInitialGroupRequest(input.initialMemberGroup),\n principalPolicyBundleFromInitialOrganizationRequest(\n input.initialOrganizationPolicy,\n ),\n ]);\n return {\n acknowledgedAccessHeads,\n // Discovery lists the seeded profile documents; their signed heads are the\n // ones this client just authored and the server acknowledged.\n authoredDiscoveryHeads: provisioningDiscoveryHeads([\n {\n plan: input.rosterProfileBootstrap.profileDocument.plan,\n response: input.response.rosterProfileDocument,\n },\n {\n plan: input.organizationMetadataBootstrap.organizationProfileDocument\n .plan,\n response: input.response.organizationProfileDocument,\n },\n ]),\n initialAdminGroupPolicy,\n initialMemberGroupPolicy,\n initialOrganizationPolicy,\n organizationMetadataContainer: buildCoreContainerBootstrapInput(\n input.response,\n input.response.organizationMetadataContainer,\n input.organizationMetadataBootstrap,\n ),\n organizationProfileDocument: buildOrganizationProfileBootstrapInput({\n containerId: input.organizationMetadataBootstrap.containerId,\n materializedDocument:\n input.organizationMetadataBootstrap.organizationProfileDocument,\n request:\n input.organizationMetadataBootstrap.organizationProfileDocumentRequest,\n response: input.response,\n snapshot: input.organizationMetadataBootstrap.organizationProfileSnapshot,\n }),\n rosterProfileContainer: input.response.rosterProfileContainer\n ? buildCoreContainerBootstrapInput(\n input.response,\n input.response.rosterProfileContainer,\n input.rosterProfileBootstrap,\n )\n : undefined,\n rosterProfileDocument: buildRosterProfileBootstrapInput({\n containerId: input.rosterProfileBootstrap.containerId,\n initialUpdate: input.rosterProfileBootstrap.profileDocumentInitialUpdate,\n materializedDocument: input.rosterProfileBootstrap.profileDocument,\n request: input.rosterProfileBootstrap.profileDocumentRequest,\n response: input.response,\n }),\n systemContainers: buildSystemContainersBootstrapInput(input),\n };\n}\n\nexport async function persistOrganizationProvisioningState(\n input: PersistOrganizationProvisioningStateInput,\n): Promise<void> {\n try {\n const artifacts = await buildProvisioningPersistenceArtifacts(input);\n const persisted = await persistRegistrationBootstrapFromExecSql(\n createExecSql(input.dbClient),\n {\n acknowledgedAccessHeads: artifacts.acknowledgedAccessHeads,\n authoredDiscoveryHeads: artifacts.authoredDiscoveryHeads,\n canStartDurableMutation: input.canStartDurableMutation,\n commitLsn: input.commitLsn,\n completeProvisioningAttempt: input.completeProvisioningAttempt,\n onPersistQueued: input.onPersistQueued,\n containerId: input.containerId,\n documentProjectors: input.documentProjectors,\n initialAdminGroupPolicy: artifacts.initialAdminGroupPolicy,\n initialMemberGroupPolicy: artifacts.initialMemberGroupPolicy,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n organizationId: input.response.organizationId,\n // The provisioning response does not expose the root container's own\n // timestamps. Its metadata document is created in the same transaction,\n // so its server timestamp is the acknowledged remote anchor for the\n // locally persisted root row.\n rootContainerServerTimestamp:\n input.response.rootMetadataDocument.createdAt,\n rootMetadataAccessEpoch: input.response.rootMetadataAccessEpoch,\n rootMetadataAccessStateHash: input.response.rootMetadataAccessStateHash,\n rootMetadataDocumentId: input.response.rootMetadataDocumentId,\n rootMetadataInitialUpdate: input.bootstrap.initialUpdate,\n rootMetadataInitialUpdateCommitted: coreMetadataInitialUpdateCommitted(\n input.response,\n input.rootMetadataDocumentRequest.initialSync.outgoingUpdates[0]?.id,\n ),\n rootMetadataSnapshot: bytesToBase64(input.bootstrap.initialUpdate),\n rootMetadataState: persistedDocumentCreateStateFromResponse(\n input.rootMetadataDocument.plan,\n input.response.rootMetadataDocument,\n ),\n ...(artifacts.rosterProfileContainer\n ? { rosterProfileContainer: artifacts.rosterProfileContainer }\n : {}),\n organizationMetadataContainer: artifacts.organizationMetadataContainer,\n ...(artifacts.organizationProfileDocument\n ? {\n organizationProfileDocument:\n artifacts.organizationProfileDocument,\n }\n : {}),\n ...(artifacts.rosterProfileDocument\n ? { rosterProfileDocument: artifacts.rosterProfileDocument }\n : {}),\n ...(artifacts.systemContainers\n ? { systemContainers: artifacts.systemContainers }\n : {}),\n userId: input.response.userId,\n },\n );\n input.log?.(\n persisted\n ? \"Local organization bootstrap persisted\"\n : \"Local organization bootstrap skipped: identity replaced\",\n );\n if (persisted)\n await input.primeProvisionedState?.({\n containers: provisionedContainerSeeds(input),\n database: input.dbClient,\n isCurrent: input.canStartDurableMutation ?? (() => true),\n organizationId: input.response.organizationId,\n policies: {\n adminGroup: artifacts.initialAdminGroupPolicy,\n memberGroup: artifacts.initialMemberGroupPolicy,\n organization: artifacts.initialOrganizationPolicy,\n },\n rootContainerId: input.response.rootContainerId,\n userId: input.response.userId,\n });\n } catch (error: unknown) {\n if (input.logError) {\n input.logError(\"Failed to persist registration data\", error);\n } else {\n console.error(\"Failed to persist registration data:\", error);\n }\n throw error;\n }\n}\n"]}
|
|
@@ -34,6 +34,12 @@ export interface RegistrationBootstrapInput {
|
|
|
34
34
|
authoredDiscoveryHeads: readonly AuthoredDiscoveryHead[];
|
|
35
35
|
/** Checked inside the mutation queue claim; false skips every write. */
|
|
36
36
|
canStartDurableMutation?: (() => boolean) | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* The provisioning's commit position, read after its transaction. Every
|
|
39
|
+
* seeded document keeps it as its last commit, so its first read passes it
|
|
40
|
+
* as `minLsn` and a clean seed needs no read at all.
|
|
41
|
+
*/
|
|
42
|
+
commitLsn: string | null;
|
|
37
43
|
/**
|
|
38
44
|
* @internal Test-only synchronization seam. Invoked synchronously,
|
|
39
45
|
* immediately before this persist joins the serialized mutation queue —
|
|
@@ -82,6 +88,7 @@ export declare function persistInitialDocumentBootstrap(execSql: ExecSql, input:
|
|
|
82
88
|
documentState: Pick<DocumentRecord, "contentKeyBundle" | "documentKekTargets" | "documentManifestBundle">;
|
|
83
89
|
initialUpdate: Uint8Array;
|
|
84
90
|
initialUpdateCommitted: boolean;
|
|
91
|
+
lastCommitLsn: string | null;
|
|
85
92
|
localId: string;
|
|
86
93
|
}): Promise<void>;
|
|
87
94
|
/**
|
|
@@ -23,7 +23,7 @@ async function persistProvisionedContainerBootstrap(execSql, input) {
|
|
|
23
23
|
accessStateHash: container.accessStateHash,
|
|
24
24
|
documentId: container.metadataDocumentId,
|
|
25
25
|
id: container.containerId,
|
|
26
|
-
lastCommitLsn:
|
|
26
|
+
lastCommitLsn: input.lastCommitLsn,
|
|
27
27
|
metadataUpdates: container.metadataSnapshot,
|
|
28
28
|
snapshotEndVersion: "",
|
|
29
29
|
contentKeyBundle: metadataState.contentKeyBundle ?? null,
|
|
@@ -56,7 +56,7 @@ async function persistRootContainerBootstrap(execSql, input) {
|
|
|
56
56
|
accessStateHash: input.rootMetadataAccessStateHash,
|
|
57
57
|
documentId: input.rootMetadataDocumentId,
|
|
58
58
|
id: input.containerId,
|
|
59
|
-
lastCommitLsn:
|
|
59
|
+
lastCommitLsn: input.commitLsn,
|
|
60
60
|
metadataUpdates: input.rootMetadataSnapshot,
|
|
61
61
|
snapshotEndVersion: "",
|
|
62
62
|
contentKeyBundle: input.rootMetadataState.contentKeyBundle ?? null,
|
|
@@ -93,6 +93,7 @@ async function persistNamedChildContainerBootstrap(execSql, input, container, na
|
|
|
93
93
|
const seeded = await persistProvisionedContainerBootstrap(execSql, {
|
|
94
94
|
container,
|
|
95
95
|
icon: null,
|
|
96
|
+
lastCommitLsn: input.commitLsn,
|
|
96
97
|
name,
|
|
97
98
|
organizationId: input.organizationId,
|
|
98
99
|
parentId: container === input.organizationMetadataContainer
|
|
@@ -115,6 +116,7 @@ async function persistSystemContainersBootstrap(execSql, input) {
|
|
|
115
116
|
await persistProvisionedContainerBootstrap(execSql, {
|
|
116
117
|
container: systemContainer,
|
|
117
118
|
icon: systemContainer.icon,
|
|
119
|
+
lastCommitLsn: input.commitLsn,
|
|
118
120
|
name: systemContainer.name,
|
|
119
121
|
organizationId: input.organizationId,
|
|
120
122
|
parentId: input.containerId,
|
|
@@ -137,6 +139,7 @@ async function persistProfileDocumentBootstrap(execSql, input, profileDocument,
|
|
|
137
139
|
...profileDocument,
|
|
138
140
|
documentKind,
|
|
139
141
|
documentProjectors: input.documentProjectors,
|
|
142
|
+
lastCommitLsn: input.commitLsn,
|
|
140
143
|
});
|
|
141
144
|
}
|
|
142
145
|
export async function persistInitialDocumentBootstrap(execSql, input) {
|
|
@@ -164,6 +167,7 @@ export async function persistInitialDocumentBootstrap(execSql, input) {
|
|
|
164
167
|
documentKekTargets: input.documentState.documentKekTargets ?? null,
|
|
165
168
|
documentKind: input.documentKind,
|
|
166
169
|
documentManifestBundle: input.documentState.documentManifestBundle ?? null,
|
|
170
|
+
lastCommitLsn: input.lastCommitLsn,
|
|
167
171
|
// The create-only persistence primitive stores this frontier and the
|
|
168
172
|
// full-history checkpoint in one transaction.
|
|
169
173
|
snapshotEndVersion: encodeVersionVector(doc),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"persistRegistrationBootstrap.js","sourceRoot":"","sources":["persistRegistrationBootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,aAAa,GACd,MAAM,iBAAiB,CAAC;AAIzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAEL,+BAA+B,GAChC,MAAM,wEAAwE,CAAC;AAChF,OAAO,EAAE,wBAAwB,EAAE,MAAM,kFAAkF,CAAC;AAC5H,OAAO,EAEL,mCAAmC,GACpC,MAAM,uEAAuE,CAAC;AAC/E,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,uDAAuD,CAAC;AAG/D,OAAO,EAAE,iCAAiC,EAAE,MAAM,mDAAmD,CAAC;AACtG,OAAO,EAAE,iCAAiC,EAAE,MAAM,4CAA4C,CAAC;AAC/F,OAAO,EACL,aAAa,EAGb,eAAe,EACf,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EACL,oCAAoC,EACpC,0CAA0C,EAC1C,4BAA4B,GAC7B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,2BAA2B,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,EAAE,qCAAqC,EAAE,MAAM,uCAAuC,CAAC;AAC9F,OAAO,EAAE,gCAAgC,EAAE,MAAM,kCAAkC,CAAC;AACpF,OAAO,EAAE,oCAAoC,EAAE,MAAM,0CA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C;QAC3D,CAAC,EACD,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,uBAAuB,IAAI,KAAK,CAAC,uBAAuB,EAAE,CACxE,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAChD,MAAyB,EACzB,KAAiC;IAEjC,MAAM,uCAAuC,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import {\n createDocument,\n encodeVersionVector,\n importUpdates,\n} from \"@tearleads/loro\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { createPendingUpdateFields } from \"../../data/documents/documentSync\";\nimport {\n type ContainerMetadataRecord,\n sqlContainerContentsPersistence,\n} from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport { deleteDocumentPlacements } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport {\n type AuthoredDiscoveryHead,\n primeAuthoredDocumentDiscoveryHeads,\n} from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport {\n DOCUMENTS_APP_KIND,\n sqlDocumentsPersistence,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport type { DocumentRecord } from \"../../data/persistence/documents/records\";\nimport type { LocallyAcknowledgedAccessManifestHead } from \"../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport { documentContainerProjectionTables } from \"../../data/sqlite/schema/documentProjectionSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\nimport { getScopedPeerSeed } from \"../../data/sync/crdtPeerSeed\";\nimport { persistDocumentState } from \"../documents/persistence\";\nimport { ORGANIZATION_PROFILE_DOCUMENT_KIND } from \"../organizations/organizationProfile\";\nimport {\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n ROSTER_PROFILE_DOCUMENT_KIND,\n} from \"../organizations/rosterProfileContainer\";\nimport { seedRegistrationAccessHeads } from \"./registrationAccessHeadPersistence\";\nimport { enqueueInitialContainerMetadataUpdate } from \"./registrationBootstrapPendingUpdates\";\nimport { persistMissingContainerBootstrap } from \"./registrationContainerBootstrap\";\nimport { persistRegistrationPrincipalPolicies } from \"./registrationPrincipalPolicyPersistence\";\n\ninterface ProvisionedContainerBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n metadataSnapshot: string;\n metadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n systemSlot: ContainerSystemSlot;\n updatedAt: string;\n}\n\ninterface ProvisionedProfileDocumentBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n localId: string;\n}\n\nexport interface RegistrationBootstrapInput {\n /** @internal Completes the caller's journal inside the bootstrap transaction. */\n completeProvisioningAttempt?:\n | ((execSql: ExecSql) => Promise<void>)\n | undefined;\n acknowledgedAccessHeads: readonly LocallyAcknowledgedAccessManifestHead[];\n /** Seeded documents' acknowledged signed heads; see the discovery cache. */\n authoredDiscoveryHeads: readonly AuthoredDiscoveryHead[];\n /** Checked inside the mutation queue claim; false skips every write. */\n canStartDurableMutation?: (() => boolean) | undefined;\n /**\n * @internal Test-only synchronization seam. Invoked synchronously,\n * immediately before this persist joins the serialized mutation queue —\n * no interleaving can separate the two. Lets identity-race tests\n * deterministically place an identity replacement inside the queue-wait\n * window instead of sleeping.\n */\n onPersistQueued?: (() => void) | undefined;\n containerId: string;\n initialAdminGroupPolicy: PrincipalPolicyBundleResponse;\n initialMemberGroupPolicy: PrincipalPolicyBundleResponse;\n initialOrganizationPolicy: PrincipalPolicyBundleResponse;\n rootMetadataAccessEpoch: number;\n rootMetadataAccessStateHash: string;\n rootContainerServerTimestamp: string;\n rootMetadataDocumentId: string;\n rootMetadataInitialUpdate: Uint8Array;\n rootMetadataInitialUpdateCommitted?: boolean | undefined;\n rootMetadataSnapshot: string;\n rootMetadataState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n rosterProfileContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationMetadataContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n rosterProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n // Additional app-owned system containers provisioned with the organization\n // (e.g. a trash bin). Each carries its own display name and icon (unlike the\n // roster/organization-metadata containers, whose names are fixed), since the\n // caller declares them.\n systemContainers?: Array<\n ProvisionedContainerBootstrapInput & {\n icon: string | null;\n name: string;\n }\n >;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n organizationId: string;\n userId: string;\n}\ntype CurrentBootstrap = RegistrationBootstrapInput & {\n canSeed: Awaited<ReturnType<typeof seedRegistrationAccessHeads>>;\n};\nasync function persistProvisionedContainerBootstrap(\n execSql: ExecSql,\n input: {\n container: ProvisionedContainerBootstrapInput;\n icon: string | null;\n name: string;\n organizationId: string;\n parentId: string | null;\n },\n): Promise<boolean> {\n const { container } = input;\n const metadataState = container.metadataState;\n const record: ContainerMetadataRecord = {\n accessEpoch: container.accessEpoch,\n accessStateHash: container.accessStateHash,\n documentId: container.metadataDocumentId,\n id: container.containerId,\n lastCommitLsn: null,\n metadataUpdates: container.metadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: metadataState.contentKeyBundle ?? null,\n documentKekTargets: metadataState.documentKekTargets ?? null,\n documentManifestBundle: metadataState.documentManifestBundle ?? null,\n };\n return persistMissingContainerBootstrap(\n execSql,\n {\n id: container.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: input.parentId,\n metadataDocumentId: container.metadataDocumentId,\n systemSlot: container.systemSlot,\n name: input.name,\n icon: input.icon,\n },\n record,\n {\n localUpdatedAt: container.updatedAt,\n serverTimestamps: {\n createdAt: container.createdAt,\n updatedAt: container.updatedAt,\n },\n },\n );\n}\n\nasync function persistRootContainerBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n): Promise<void> {\n if (\n !input.canSeed(\"container\", input.containerId) ||\n !input.canSeed(\"document\", input.rootMetadataDocumentId)\n )\n return;\n const rootRecord: ContainerMetadataRecord = {\n accessEpoch: input.rootMetadataAccessEpoch,\n accessStateHash: input.rootMetadataAccessStateHash,\n documentId: input.rootMetadataDocumentId,\n id: input.containerId,\n lastCommitLsn: null,\n metadataUpdates: input.rootMetadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: input.rootMetadataState.contentKeyBundle ?? null,\n documentKekTargets: input.rootMetadataState.documentKekTargets ?? null,\n documentManifestBundle:\n input.rootMetadataState.documentManifestBundle ?? null,\n };\n const seeded = await persistMissingContainerBootstrap(\n execSql,\n {\n id: input.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: null,\n metadataDocumentId: input.rootMetadataDocumentId,\n name: \"/\",\n icon: null,\n },\n rootRecord,\n {\n localUpdatedAt: input.rootContainerServerTimestamp,\n serverTimestamps: {\n createdAt: input.rootContainerServerTimestamp,\n updatedAt: input.rootContainerServerTimestamp,\n },\n },\n );\n if (!seeded) return;\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n input.containerId,\n input.rootMetadataInitialUpdate,\n input.rootMetadataInitialUpdateCommitted,\n );\n}\n\n// Persist reserved profile containers using their fixed topology: roster profiles\n// inherit the personal root; shared organization metadata has an independent root.\nasync function persistNamedChildContainerBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n container: RegistrationBootstrapInput[\"rosterProfileContainer\"],\n name: string,\n): Promise<void> {\n if (\n !container ||\n !input.canSeed(\"container\", container.containerId) ||\n !input.canSeed(\"document\", container.metadataDocumentId)\n ) {\n return;\n }\n\n const seeded = await persistProvisionedContainerBootstrap(execSql, {\n container,\n icon: null,\n name,\n organizationId: input.organizationId,\n parentId:\n container === input.organizationMetadataContainer\n ? null\n : input.containerId,\n });\n if (!seeded) return;\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n container.containerId,\n container.metadataInitialUpdate,\n container.metadataInitialUpdateCommitted,\n );\n}\n\nasync function persistSystemContainersBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n): Promise<void> {\n const systemContainers = input.systemContainers;\n if (!systemContainers) {\n return;\n }\n\n for (const systemContainer of systemContainers) {\n if (\n !input.canSeed(\"container\", systemContainer.containerId) ||\n !input.canSeed(\"document\", systemContainer.metadataDocumentId)\n )\n continue;\n await persistProvisionedContainerBootstrap(execSql, {\n container: systemContainer,\n icon: systemContainer.icon,\n name: systemContainer.name,\n organizationId: input.organizationId,\n parentId: input.containerId,\n });\n // Provisioned system-container metadata is already committed remotely in\n // the organization transaction. Persist the initialized snapshot locally,\n // but do not queue a duplicate write with a second update id.\n }\n}\n\n// The ONE persist shape for the provisioned profile documents (organization\n// profile and roster profile): the input carries exactly the bootstrap\n// fields, so only the document kind and the host's projectors join it.\nasync function persistProfileDocumentBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n profileDocument: ProvisionedProfileDocumentBootstrapInput | undefined,\n documentKind: string,\n): Promise<void> {\n if (\n !profileDocument ||\n !input.canSeed(\"document\", profileDocument.documentId) ||\n !input.canSeed(\"container\", profileDocument.containerId)\n ) {\n return;\n }\n\n await persistInitialDocumentBootstrap(execSql, {\n ...profileDocument,\n documentKind,\n documentProjectors: input.documentProjectors,\n });\n}\n\nexport async function persistInitialDocumentBootstrap(\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentKind: string;\n documentProjectors: DocumentProjectorRegistryInput | undefined;\n documentState: Pick<\n DocumentRecord,\n \"contentKeyBundle\" | \"documentKekTargets\" | \"documentManifestBundle\"\n >;\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n localId: string;\n },\n): Promise<void> {\n const doc = await createDocument(await getScopedPeerSeed(DOCUMENTS_APP_KIND));\n importUpdates(doc, [input.initialUpdate]);\n const pendingUpdate = input.initialUpdateCommitted\n ? undefined\n : (createPendingUpdateFields(input.initialUpdate) ?? undefined);\n\n await persistDocumentState({\n currentDoc: doc,\n currentRecord: null,\n deleteDocumentPlacements,\n documentProjectors: input.documentProjectors ?? [],\n execSql,\n localId: input.localId,\n patch: {\n accessEpoch: input.accessEpoch,\n accessStateHash: input.accessStateHash,\n containerId: input.containerId,\n contentKeyBundle: input.documentState.contentKeyBundle ?? null,\n documentId: input.documentId,\n // Successful provisioning makes this device's user the founding admin.\n // Stores can open before discovery returns the same access level.\n effectiveAccessLevel: \"admin\",\n documentKekTargets: input.documentState.documentKekTargets ?? null,\n documentKind: input.documentKind,\n documentManifestBundle:\n input.documentState.documentManifestBundle ?? null,\n // The create-only persistence primitive stores this frontier and the\n // full-history checkpoint in one transaction.\n snapshotEndVersion: encodeVersionVector(doc),\n },\n pendingUpdate,\n persistence: sqlDocumentsPersistence,\n });\n}\n\n/**\n * Persists the local root-container bootstrap created during successful\n * registration so container contents can initialize from SQLite on first\n * login — atomically: every write lands inside ONE transaction whose last\n * act re-checks identity currency, so an identity replaced anywhere between\n * the queue claim and the commit rolls the entire bootstrap back instead of\n * leaving a partial one. Resolves false when either currency check rejected\n * the write, so callers do not report a bootstrap that was never persisted.\n */\nexport async function persistRegistrationBootstrapFromExecSql(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n): Promise<boolean> {\n input.onPersistQueued?.();\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n // In-mutex currency check, adjacent to the serialized-mutation claim\n // (see persistDocumentState): the identity can be replaced while this\n // persist waits for the queue, and its bootstrap must not be written\n // through a client the replacement closed or renewed.\n if (input.canStartDurableMutation && !input.canStartDurableMutation()) {\n return false;\n }\n // Idempotent DDL stays outside the atomic boundary.\n await sqlContainerContentsPersistence.ensureSchema(lockedExecSql);\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n await ensureSqlTables(lockedExecSql, documentContainerProjectionTables);\n // Pre-commit currency guard: the write sequence awaits real work, so\n // the identity can be replaced mid-sequence. The guard runs\n // synchronously with the COMMIT dispatch, so a refusal rolls the whole\n // write set back and a pass cannot go stale before the commit is sent —\n // the partial-persist window a single entry check leaves open.\n const { committed } = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async () => {\n const canSeed = await seedRegistrationAccessHeads({\n execSql: lockedExecSql,\n heads: input.acknowledgedAccessHeads,\n organizationId: input.organizationId,\n });\n const bootstrap = { ...input, canSeed };\n await persistRegistrationPrincipalPolicies({\n adminGroup: input.initialAdminGroupPolicy,\n execSql: lockedExecSql,\n memberGroup: input.initialMemberGroupPolicy,\n organization: input.initialOrganizationPolicy,\n });\n await persistRootContainerBootstrap(lockedExecSql, bootstrap);\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n bootstrap,\n input.rosterProfileContainer,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n bootstrap,\n input.rosterProfileDocument,\n ROSTER_PROFILE_DOCUMENT_KIND,\n );\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n bootstrap,\n input.organizationMetadataContainer,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n bootstrap,\n input.organizationProfileDocument,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n );\n await persistSystemContainersBootstrap(lockedExecSql, bootstrap);\n // After the checkpoints above: discovery reuses a cached head only\n // while its access-manifest checkpoint still matches.\n await primeAuthoredDocumentDiscoveryHeads(\n lockedExecSql,\n input.authoredDiscoveryHeads.filter((head) =>\n canSeed(\"document\", head.documentId),\n ),\n );\n await input.completeProvisioningAttempt?.(lockedExecSql);\n },\n () => !input.canStartDurableMutation || input.canStartDurableMutation(),\n );\n return committed;\n });\n}\n\nexport async function persistRegistrationBootstrap(\n client: ExecSqlClientLike,\n input: RegistrationBootstrapInput,\n): Promise<void> {\n await persistRegistrationBootstrapFromExecSql(createExecSql(client), input);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"persistRegistrationBootstrap.js","sourceRoot":"","sources":["persistRegistrationBootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,aAAa,GACd,MAAM,iBAAiB,CAAC;AAIzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAEL,+BAA+B,GAChC,MAAM,wEAAwE,CAAC;AAChF,OAAO,EAAE,wBAAwB,EAAE,MAAM,kFAAkF,CAAC;AAC5H,OAAO,EAEL,mCAAmC,GACpC,MAAM,uEAAuE,CAAC;AAC/E,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,uDAAuD,CAAC;AAG/D,OAAO,EAAE,iCAAiC,EAAE,MAAM,mDAAmD,CAAC;AACtG,OAAO,EAAE,iCAAiC,EAAE,MAAM,4CAA4C,CAAC;AAC/F,OAAO,EACL,aAAa,EAGb,eAAe,EACf,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,kCA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CAAmC,CACvC,aAAa,EACb,SAAS,EACT,KAAK,CAAC,6BAA6B,EACnC,oCAAoC,CACrC,CAAC;YACF,MAAM,+BAA+B,CACnC,aAAa,EACb,SAAS,EACT,KAAK,CAAC,2BAA2B,EACjC,kCAAkC,CACnC,CAAC;YACF,MAAM,gCAAgC,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;YACjE,mEAAmE;YACnE,sDAAsD;YACtD,MAAM,mCAAmC,CACvC,aAAa,EACb,KAAK,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAC3C,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,CACrC,CACF,CAAC;YACF,MAAM,KAAK,CAAC,2BAA2B,EAAE,CAAC,aAAa,CAAC,CAAC;QAC3D,CAAC,EACD,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,uBAAuB,IAAI,KAAK,CAAC,uBAAuB,EAAE,CACxE,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAChD,MAAyB,EACzB,KAAiC;IAEjC,MAAM,uCAAuC,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import {\n createDocument,\n encodeVersionVector,\n importUpdates,\n} from \"@tearleads/loro\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { createPendingUpdateFields } from \"../../data/documents/documentSync\";\nimport {\n type ContainerMetadataRecord,\n sqlContainerContentsPersistence,\n} from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport { deleteDocumentPlacements } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport {\n type AuthoredDiscoveryHead,\n primeAuthoredDocumentDiscoveryHeads,\n} from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport {\n DOCUMENTS_APP_KIND,\n sqlDocumentsPersistence,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport type { DocumentRecord } from \"../../data/persistence/documents/records\";\nimport type { LocallyAcknowledgedAccessManifestHead } from \"../../data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence\";\nimport { documentContainerProjectionTables } from \"../../data/sqlite/schema/documentProjectionSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\nimport { getScopedPeerSeed } from \"../../data/sync/crdtPeerSeed\";\nimport { persistDocumentState } from \"../documents/persistence\";\nimport { ORGANIZATION_PROFILE_DOCUMENT_KIND } from \"../organizations/organizationProfile\";\nimport {\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n ROSTER_PROFILE_DOCUMENT_KIND,\n} from \"../organizations/rosterProfileContainer\";\nimport { seedRegistrationAccessHeads } from \"./registrationAccessHeadPersistence\";\nimport { enqueueInitialContainerMetadataUpdate } from \"./registrationBootstrapPendingUpdates\";\nimport { persistMissingContainerBootstrap } from \"./registrationContainerBootstrap\";\nimport { persistRegistrationPrincipalPolicies } from \"./registrationPrincipalPolicyPersistence\";\n\ninterface ProvisionedContainerBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n metadataSnapshot: string;\n metadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n systemSlot: ContainerSystemSlot;\n updatedAt: string;\n}\n\ninterface ProvisionedProfileDocumentBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n localId: string;\n}\n\nexport interface RegistrationBootstrapInput {\n /** @internal Completes the caller's journal inside the bootstrap transaction. */\n completeProvisioningAttempt?:\n | ((execSql: ExecSql) => Promise<void>)\n | undefined;\n acknowledgedAccessHeads: readonly LocallyAcknowledgedAccessManifestHead[];\n /** Seeded documents' acknowledged signed heads; see the discovery cache. */\n authoredDiscoveryHeads: readonly AuthoredDiscoveryHead[];\n /** Checked inside the mutation queue claim; false skips every write. */\n canStartDurableMutation?: (() => boolean) | undefined;\n /**\n * The provisioning's commit position, read after its transaction. Every\n * seeded document keeps it as its last commit, so its first read passes it\n * as `minLsn` and a clean seed needs no read at all.\n */\n commitLsn: string | null;\n /**\n * @internal Test-only synchronization seam. Invoked synchronously,\n * immediately before this persist joins the serialized mutation queue —\n * no interleaving can separate the two. Lets identity-race tests\n * deterministically place an identity replacement inside the queue-wait\n * window instead of sleeping.\n */\n onPersistQueued?: (() => void) | undefined;\n containerId: string;\n initialAdminGroupPolicy: PrincipalPolicyBundleResponse;\n initialMemberGroupPolicy: PrincipalPolicyBundleResponse;\n initialOrganizationPolicy: PrincipalPolicyBundleResponse;\n rootMetadataAccessEpoch: number;\n rootMetadataAccessStateHash: string;\n rootContainerServerTimestamp: string;\n rootMetadataDocumentId: string;\n rootMetadataInitialUpdate: Uint8Array;\n rootMetadataInitialUpdateCommitted?: boolean | undefined;\n rootMetadataSnapshot: string;\n rootMetadataState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n rosterProfileContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationMetadataContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n rosterProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n // Additional app-owned system containers provisioned with the organization\n // (e.g. a trash bin). Each carries its own display name and icon (unlike the\n // roster/organization-metadata containers, whose names are fixed), since the\n // caller declares them.\n systemContainers?: Array<\n ProvisionedContainerBootstrapInput & {\n icon: string | null;\n name: string;\n }\n >;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n organizationId: string;\n userId: string;\n}\ntype CurrentBootstrap = RegistrationBootstrapInput & {\n canSeed: Awaited<ReturnType<typeof seedRegistrationAccessHeads>>;\n};\nasync function persistProvisionedContainerBootstrap(\n execSql: ExecSql,\n input: {\n container: ProvisionedContainerBootstrapInput;\n icon: string | null;\n lastCommitLsn: string | null;\n name: string;\n organizationId: string;\n parentId: string | null;\n },\n): Promise<boolean> {\n const { container } = input;\n const metadataState = container.metadataState;\n const record: ContainerMetadataRecord = {\n accessEpoch: container.accessEpoch,\n accessStateHash: container.accessStateHash,\n documentId: container.metadataDocumentId,\n id: container.containerId,\n lastCommitLsn: input.lastCommitLsn,\n metadataUpdates: container.metadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: metadataState.contentKeyBundle ?? null,\n documentKekTargets: metadataState.documentKekTargets ?? null,\n documentManifestBundle: metadataState.documentManifestBundle ?? null,\n };\n return persistMissingContainerBootstrap(\n execSql,\n {\n id: container.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: input.parentId,\n metadataDocumentId: container.metadataDocumentId,\n systemSlot: container.systemSlot,\n name: input.name,\n icon: input.icon,\n },\n record,\n {\n localUpdatedAt: container.updatedAt,\n serverTimestamps: {\n createdAt: container.createdAt,\n updatedAt: container.updatedAt,\n },\n },\n );\n}\n\nasync function persistRootContainerBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n): Promise<void> {\n if (\n !input.canSeed(\"container\", input.containerId) ||\n !input.canSeed(\"document\", input.rootMetadataDocumentId)\n )\n return;\n const rootRecord: ContainerMetadataRecord = {\n accessEpoch: input.rootMetadataAccessEpoch,\n accessStateHash: input.rootMetadataAccessStateHash,\n documentId: input.rootMetadataDocumentId,\n id: input.containerId,\n lastCommitLsn: input.commitLsn,\n metadataUpdates: input.rootMetadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: input.rootMetadataState.contentKeyBundle ?? null,\n documentKekTargets: input.rootMetadataState.documentKekTargets ?? null,\n documentManifestBundle:\n input.rootMetadataState.documentManifestBundle ?? null,\n };\n const seeded = await persistMissingContainerBootstrap(\n execSql,\n {\n id: input.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: null,\n metadataDocumentId: input.rootMetadataDocumentId,\n name: \"/\",\n icon: null,\n },\n rootRecord,\n {\n localUpdatedAt: input.rootContainerServerTimestamp,\n serverTimestamps: {\n createdAt: input.rootContainerServerTimestamp,\n updatedAt: input.rootContainerServerTimestamp,\n },\n },\n );\n if (!seeded) return;\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n input.containerId,\n input.rootMetadataInitialUpdate,\n input.rootMetadataInitialUpdateCommitted,\n );\n}\n\n// Persist reserved profile containers using their fixed topology: roster profiles\n// inherit the personal root; shared organization metadata has an independent root.\nasync function persistNamedChildContainerBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n container: RegistrationBootstrapInput[\"rosterProfileContainer\"],\n name: string,\n): Promise<void> {\n if (\n !container ||\n !input.canSeed(\"container\", container.containerId) ||\n !input.canSeed(\"document\", container.metadataDocumentId)\n ) {\n return;\n }\n\n const seeded = await persistProvisionedContainerBootstrap(execSql, {\n container,\n icon: null,\n lastCommitLsn: input.commitLsn,\n name,\n organizationId: input.organizationId,\n parentId:\n container === input.organizationMetadataContainer\n ? null\n : input.containerId,\n });\n if (!seeded) return;\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n container.containerId,\n container.metadataInitialUpdate,\n container.metadataInitialUpdateCommitted,\n );\n}\n\nasync function persistSystemContainersBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n): Promise<void> {\n const systemContainers = input.systemContainers;\n if (!systemContainers) {\n return;\n }\n\n for (const systemContainer of systemContainers) {\n if (\n !input.canSeed(\"container\", systemContainer.containerId) ||\n !input.canSeed(\"document\", systemContainer.metadataDocumentId)\n )\n continue;\n await persistProvisionedContainerBootstrap(execSql, {\n container: systemContainer,\n icon: systemContainer.icon,\n lastCommitLsn: input.commitLsn,\n name: systemContainer.name,\n organizationId: input.organizationId,\n parentId: input.containerId,\n });\n // Provisioned system-container metadata is already committed remotely in\n // the organization transaction. Persist the initialized snapshot locally,\n // but do not queue a duplicate write with a second update id.\n }\n}\n\n// The ONE persist shape for the provisioned profile documents (organization\n// profile and roster profile): the input carries exactly the bootstrap\n// fields, so only the document kind and the host's projectors join it.\nasync function persistProfileDocumentBootstrap(\n execSql: ExecSql,\n input: CurrentBootstrap,\n profileDocument: ProvisionedProfileDocumentBootstrapInput | undefined,\n documentKind: string,\n): Promise<void> {\n if (\n !profileDocument ||\n !input.canSeed(\"document\", profileDocument.documentId) ||\n !input.canSeed(\"container\", profileDocument.containerId)\n ) {\n return;\n }\n\n await persistInitialDocumentBootstrap(execSql, {\n ...profileDocument,\n documentKind,\n documentProjectors: input.documentProjectors,\n lastCommitLsn: input.commitLsn,\n });\n}\n\nexport async function persistInitialDocumentBootstrap(\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentKind: string;\n documentProjectors: DocumentProjectorRegistryInput | undefined;\n documentState: Pick<\n DocumentRecord,\n \"contentKeyBundle\" | \"documentKekTargets\" | \"documentManifestBundle\"\n >;\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n lastCommitLsn: string | null;\n localId: string;\n },\n): Promise<void> {\n const doc = await createDocument(await getScopedPeerSeed(DOCUMENTS_APP_KIND));\n importUpdates(doc, [input.initialUpdate]);\n const pendingUpdate = input.initialUpdateCommitted\n ? undefined\n : (createPendingUpdateFields(input.initialUpdate) ?? undefined);\n\n await persistDocumentState({\n currentDoc: doc,\n currentRecord: null,\n deleteDocumentPlacements,\n documentProjectors: input.documentProjectors ?? [],\n execSql,\n localId: input.localId,\n patch: {\n accessEpoch: input.accessEpoch,\n accessStateHash: input.accessStateHash,\n containerId: input.containerId,\n contentKeyBundle: input.documentState.contentKeyBundle ?? null,\n documentId: input.documentId,\n // Successful provisioning makes this device's user the founding admin.\n // Stores can open before discovery returns the same access level.\n effectiveAccessLevel: \"admin\",\n documentKekTargets: input.documentState.documentKekTargets ?? null,\n documentKind: input.documentKind,\n documentManifestBundle:\n input.documentState.documentManifestBundle ?? null,\n lastCommitLsn: input.lastCommitLsn,\n // The create-only persistence primitive stores this frontier and the\n // full-history checkpoint in one transaction.\n snapshotEndVersion: encodeVersionVector(doc),\n },\n pendingUpdate,\n persistence: sqlDocumentsPersistence,\n });\n}\n\n/**\n * Persists the local root-container bootstrap created during successful\n * registration so container contents can initialize from SQLite on first\n * login — atomically: every write lands inside ONE transaction whose last\n * act re-checks identity currency, so an identity replaced anywhere between\n * the queue claim and the commit rolls the entire bootstrap back instead of\n * leaving a partial one. Resolves false when either currency check rejected\n * the write, so callers do not report a bootstrap that was never persisted.\n */\nexport async function persistRegistrationBootstrapFromExecSql(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n): Promise<boolean> {\n input.onPersistQueued?.();\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n // In-mutex currency check, adjacent to the serialized-mutation claim\n // (see persistDocumentState): the identity can be replaced while this\n // persist waits for the queue, and its bootstrap must not be written\n // through a client the replacement closed or renewed.\n if (input.canStartDurableMutation && !input.canStartDurableMutation()) {\n return false;\n }\n // Idempotent DDL stays outside the atomic boundary.\n await sqlContainerContentsPersistence.ensureSchema(lockedExecSql);\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n await ensureSqlTables(lockedExecSql, documentContainerProjectionTables);\n // Pre-commit currency guard: the write sequence awaits real work, so\n // the identity can be replaced mid-sequence. The guard runs\n // synchronously with the COMMIT dispatch, so a refusal rolls the whole\n // write set back and a pass cannot go stale before the commit is sent —\n // the partial-persist window a single entry check leaves open.\n const { committed } = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async () => {\n const canSeed = await seedRegistrationAccessHeads({\n execSql: lockedExecSql,\n heads: input.acknowledgedAccessHeads,\n organizationId: input.organizationId,\n });\n const bootstrap = { ...input, canSeed };\n await persistRegistrationPrincipalPolicies({\n adminGroup: input.initialAdminGroupPolicy,\n execSql: lockedExecSql,\n memberGroup: input.initialMemberGroupPolicy,\n organization: input.initialOrganizationPolicy,\n });\n await persistRootContainerBootstrap(lockedExecSql, bootstrap);\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n bootstrap,\n input.rosterProfileContainer,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n bootstrap,\n input.rosterProfileDocument,\n ROSTER_PROFILE_DOCUMENT_KIND,\n );\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n bootstrap,\n input.organizationMetadataContainer,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n bootstrap,\n input.organizationProfileDocument,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n );\n await persistSystemContainersBootstrap(lockedExecSql, bootstrap);\n // After the checkpoints above: discovery reuses a cached head only\n // while its access-manifest checkpoint still matches.\n await primeAuthoredDocumentDiscoveryHeads(\n lockedExecSql,\n input.authoredDiscoveryHeads.filter((head) =>\n canSeed(\"document\", head.documentId),\n ),\n );\n await input.completeProvisioningAttempt?.(lockedExecSql);\n },\n () => !input.canStartDurableMutation || input.canStartDurableMutation(),\n );\n return committed;\n });\n}\n\nexport async function persistRegistrationBootstrap(\n client: ExecSqlClientLike,\n input: RegistrationBootstrapInput,\n): Promise<void> {\n await persistRegistrationBootstrapFromExecSql(createExecSql(client), input);\n}\n"]}
|
|
@@ -46,6 +46,7 @@ export async function registerIdentity(input) {
|
|
|
46
46
|
await persistOrganizationProvisioningState({
|
|
47
47
|
bootstrap: artifacts.bootstrap,
|
|
48
48
|
canStartDurableMutation: input.isIdentityCurrent,
|
|
49
|
+
commitLsn: response.commitLsn,
|
|
49
50
|
onPersistQueued: input.onPersistQueued,
|
|
50
51
|
containerId: input.containerId,
|
|
51
52
|
dbClient: input.dbClient,
|
|
@@ -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,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,gBAAgB;SACxD;KACF,CAAC,CAAC;IAEH,MAAM,SAAS,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IACtC,MAAM,SAAS,GAAG,MAAM,sCAAsC,CAAC;QAC7D,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,uBAAuB,EAAE,KAAK,CAAC,uBAAuB;QACtD,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;QAC9D,eAAe,EAAE,KAAK,CAAC,WAAW;QAClC,qBAAqB,EAAE,KAAK,CAAC,qBA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xD,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,GAAG,EAAE,CAAC,mBAAmB,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IACnD,MAAM,oCAAoC,CAAC;QACzC,SAAS,EAAE,SAAS,CAAC,SAAS;QAC9B,uBAAuB,EAAE,KAAK,CAAC,iBAAiB;QAChD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;QAC9C,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;QAChD,yBAAyB,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 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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,SAAS,CAAC,iBAAiB;QAC9C,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;QAChD,yBAAyB,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"]}
|