@tearleads/client-sdk 0.1.40 → 0.1.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/client/Tearleads.js +3 -0
  2. package/client/Tearleads.js.map +1 -1
  3. package/data/documents/shared/syncResponses.js +5 -7
  4. package/data/documents/shared/syncResponses.js.map +1 -1
  5. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js +2 -0
  6. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
  7. package/data/keyingProjectionVerification/checkpointContext.d.ts +12 -0
  8. package/data/keyingProjectionVerification/checkpointContext.js +16 -0
  9. package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
  10. package/data/keyingProjectionVerification/containerDestinationVerification.js +3 -1
  11. package/data/keyingProjectionVerification/containerDestinationVerification.js.map +1 -1
  12. package/data/keyingProjectionVerification/containerProjectionVerification.js +12 -6
  13. package/data/keyingProjectionVerification/containerProjectionVerification.js.map +1 -1
  14. package/data/keyingProjectionVerification/documentProjectionVerification.js +10 -4
  15. package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
  16. package/data/persistence/keyingCheckpointAdvancePersistence.js +27 -8
  17. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +1 -1
  18. package/data/persistence/verifiedManifestBundlePersistence.d.ts +45 -0
  19. package/data/persistence/verifiedManifestBundlePersistence.js +282 -0
  20. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -0
  21. package/data/sqlite/schema.d.ts +157 -0
  22. package/data/sqlite/schema.js +3 -0
  23. package/data/sqlite/schema.js.map +1 -1
  24. package/data/sqlite/verifiedManifestBundleSchema.d.ts +174 -0
  25. package/data/sqlite/verifiedManifestBundleSchema.js +36 -0
  26. package/data/sqlite/verifiedManifestBundleSchema.js.map +1 -0
  27. package/internal/api-client/ApiClient.d.ts +4 -11
  28. package/internal/api-client/ApiClient.js +8 -6
  29. package/internal/api-client/ApiClient.js.map +1 -1
  30. package/internal/api-client/index.d.ts +1 -1
  31. package/internal/api-client/index.js +0 -1
  32. package/internal/api-client/index.js.map +1 -1
  33. package/internal/api-client/principalHistoryRequest.js +8 -2
  34. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  35. package/internal/api-client/principalHistoryRequestContext.js +15 -5
  36. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  37. package/internal/api-client/routes/writerProjections.js +6 -3
  38. package/internal/api-client/routes/writerProjections.js.map +1 -1
  39. package/internal/api-client/verifiedManifestCitations.d.ts +23 -0
  40. package/internal/api-client/verifiedManifestCitations.js +60 -0
  41. package/internal/api-client/verifiedManifestCitations.js.map +1 -0
  42. package/internal/api-client/writerProjectionRequests.js +75 -14
  43. package/internal/api-client/writerProjectionRequests.js.map +1 -1
  44. package/internal/crypto/index.d.ts +0 -1
  45. package/internal/crypto/index.js +0 -1
  46. package/internal/crypto/index.js.map +1 -1
  47. package/internal/validators/documentSyncRefinements.js +5 -0
  48. package/internal/validators/documentSyncRefinements.js.map +1 -1
  49. package/internal/validators/knownManifestsRefinements.js +5 -0
  50. package/internal/validators/knownManifestsRefinements.js.map +1 -0
  51. package/internal/validators/operation/documentSync.d.ts +3 -0
  52. package/internal/validators/operation/writerProjections.d.ts +85 -319
  53. package/internal/validators/operation/writerProjections.js +11 -11
  54. package/internal/validators/operation/writerProjections.js.map +1 -1
  55. package/internal/validators/response/container.d.ts +429 -20
  56. package/internal/validators/response/container.js +40 -5
  57. package/internal/validators/response/container.js.map +1 -1
  58. package/internal/validators/response/documentMutation.d.ts +440 -20
  59. package/internal/validators/response/documentMutation.js +33 -3
  60. package/internal/validators/response/documentMutation.js.map +1 -1
  61. package/internal/validators/response/documentSyncSchema.js +35 -1
  62. package/internal/validators/response/documentSyncSchema.js.map +1 -1
  63. package/internal/validators/response/index.d.ts +3 -2
  64. package/internal/validators/response/index.js +3 -2
  65. package/internal/validators/response/index.js.map +1 -1
  66. package/internal/validators/response/manifestBundleReferences.js +79 -0
  67. package/internal/validators/response/manifestBundleReferences.js.map +1 -0
  68. package/internal/validators/response/writerProjectionWire.d.ts +19 -0
  69. package/internal/validators/response/writerProjectionWire.js +132 -0
  70. package/internal/validators/response/writerProjectionWire.js.map +1 -0
  71. package/internal/validators/schema.js +20 -0
  72. package/internal/validators/schema.js.map +1 -1
  73. package/internal/validators/util/index.d.ts +1 -1
  74. package/internal/validators/util/index.js +1 -1
  75. package/internal/validators/util/index.js.map +1 -1
  76. package/internal/validators/util/knownManifestWire.d.ts +11 -0
  77. package/internal/validators/util/knownManifestWire.js +28 -0
  78. package/internal/validators/util/knownManifestWire.js.map +1 -0
  79. package/internal/validators/writerProjectionRefinements.js +5 -0
  80. package/internal/validators/writerProjectionRefinements.js.map +1 -1
  81. package/package.json +1 -1
  82. package/workflows/documents/syncContentKeys.js +4 -9
  83. package/workflows/documents/syncContentKeys.js.map +1 -1
  84. package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -5
  85. package/workflows/sync/remoteReset.js +2 -0
  86. package/workflows/sync/remoteReset.js.map +1 -1
  87. package/internal/api-client/projectionHistoryTransport.js +0 -107
  88. package/internal/api-client/projectionHistoryTransport.js.map +0 -1
  89. package/internal/api-client/verifiedProjectionHistory.d.ts +0 -4
  90. package/internal/api-client/verifiedProjectionHistory.js +0 -12
  91. package/internal/api-client/verifiedProjectionHistory.js.map +0 -1
  92. package/internal/crypto/projectionHistory.d.ts +0 -14
  93. package/internal/crypto/projectionHistory.js +0 -90
  94. package/internal/crypto/projectionHistory.js.map +0 -1
  95. package/internal/crypto/projectionHistorySlots.d.ts +0 -13
  96. package/internal/crypto/projectionHistorySlots.js +0 -81
  97. package/internal/crypto/projectionHistorySlots.js.map +0 -1
  98. package/internal/validators/projectionHistoryRefinements.js +0 -5
  99. package/internal/validators/projectionHistoryRefinements.js.map +0 -1
  100. package/internal/validators/util/projectionHistoryWire.d.ts +0 -23
  101. package/internal/validators/util/projectionHistoryWire.js +0 -33
  102. package/internal/validators/util/projectionHistoryWire.js.map +0 -1
@@ -1,6 +1,7 @@
1
1
  import { ApiClient, ApiRequestMetrics } from "../internal/api-client/index.js";
2
2
  import { resolveDocumentProjectorRegistry, } from "../data/documents/documentKinds.js";
3
3
  import { createDomainScope } from "../data/domainScope.js";
4
+ import { createVerifiedManifestCitations } from "../data/persistence/verifiedManifestBundlePersistence.js";
4
5
  import { disposeDomainSyncCoordinator } from "../data/sync/syncCoordinator.js";
5
6
  import { resolveIdentityTrustDomain } from "../data/trustedUserIdentity/index.js";
6
7
  import { ApiVersion } from "./apiVersion.js";
@@ -161,6 +162,8 @@ export class Tearleads {
161
162
  this.boundUserId = (signingKeyFingerprint) => runtime.boundUserId(signingKeyFingerprint);
162
163
  }
163
164
  configureApiClientCallbacks() {
165
+ // Projection reads cite bundles this identity's database already verified.
166
+ this.apiClient.setVerifiedManifestCitations(createVerifiedManifestCitations(() => this.database.execSql));
164
167
  this.apiClient.setOnError((message) => this.logError(message));
165
168
  // An authoritative host source owns connectivity. Without one, request
166
169
  // outcomes remain reachability hints. Browser and native app bindings both
@@ -1 +1 @@
1
- {"version":3,"file":"Tearleads.js","sourceRoot":"","sources":["Tearleads.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAErE,OAAO,EAGL,gCAAgC,GACjC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAoB,MAAM,qBAAqB,CAAC;AAE1E,OAAO,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAEzE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAyB,KAAK,EAAE,MAAM,SAAS,CAAC;AACvD,OAAO,EAEL,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAwB,MAAM,YAAY,CAAC;A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C,WAAW,EAAE,EAAE,CAAC;YAChB,WAAW,GAAG,IAAI,CAAC;QACrB,CAAC,CAAC;QACF,MAAM,sBAAsB,GAAG,GAAG,EAAE;YAClC,IAAI,IAAI,CAAC,uBAAuB,IAAI,IAAI,CAAC,QAAQ,CAAC,cAAc,EAAE,CAAC;gBACjE,wBAAwB,EAAE,CAAC;gBAC3B,OAAO;YACT,CAAC;YAED,IACE,IAAI,CAAC,+BAA+B;gBACpC,IAAI,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO,EAChC,CAAC;gBACD,OAAO;YACT,CAAC;YAED,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC,QAAQ;iBACjD,QAAQ,EAAE;iBACV,IAAI,CAAC,GAAG,EAAE;gBACT,IAAI,CAAC,uBAAuB,GAAG,IAAI,CAAC;gBACpC,wBAAwB,EAAE,CAAC;YAC7B,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACxB,IAAI,CAAC;oBACH,IAAI,CAAC,QAAQ,CAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;gBACjE,CAAC;gBAAC,MAAM,CAAC;oBACP,gFAAgF;gBAClF,CAAC;YACH,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACZ,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC;YAC9C,CAAC,CAAC,CAAC;QACP,CAAC,CAAC;QAEF,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;QAC9D,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACtD,CAAC;CACF","sourcesContent":["import { ApiClient, ApiRequestMetrics } from \"@tearleads/api-client\";\nimport type { BlobStore } from \"../data/blobContracts\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../data/documents/documentKinds\";\nimport { createDomainScope, type DomainScope } from \"../data/domainScope\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { disposeDomainSyncCoordinator } from \"../data/sync/syncCoordinator\";\nimport { resolveIdentityTrustDomain } from \"../data/trustedUserIdentity\";\nimport type { ProvisionedSystemContainerSpec } from \"../workflows/registration\";\nimport { ApiVersion } from \"./apiVersion\";\nimport { type BlobStoreFactory, Blobs } from \"./blobs\";\nimport {\n type ContainerContents,\n createContainerContents,\n} from \"./containerContents\";\nimport { Database, type DatabaseOptions } from \"./database\";\nimport { createDeviceFirst, type DeviceFirst } from \"./deviceFirst\";\nimport { createDocuments, type Documents } from \"./documents\";\nimport { Events } from \"./events\";\nimport {\n createIdentity,\n type Identity,\n type IdentityOptions,\n} from \"./identity\";\nimport { type Logger, logErrorToConsole } from \"./logger\";\nimport { Network } from \"./network\";\nimport { createOrganizations, type Organizations } from \"./organizations\";\nimport type { PrincipalHistoryKeyProvider } from \"./principalHistoryProtection\";\nimport { createRoot, type Root, rootRuntimeOf } from \"./root\";\nimport {\n createSecurityIncidentService,\n type SecurityIncidentListener,\n type SecurityIncidents,\n} from \"./securityIncidents\";\nimport { createSession } from \"./session\";\nimport type { Session } from \"./session/sessionTypes\";\nimport { SyncBillingGate } from \"./syncBillingGate\";\nimport { createUserIdentities, type UserIdentities } from \"./userIdentities\";\nimport {\n createRuntime,\n type InternalRuntime,\n type Runtime,\n} from \"./workflowRuntime\";\n\nfunction createClientSecurityIncidentService(input: {\n readonly apiBaseUrl: string;\n readonly database: Database;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly options: ClientOptions;\n}) {\n const identityTrustDomain = resolveIdentityTrustDomain({\n apiBaseUrl: input.apiBaseUrl,\n identityTrustDomain: input.options.identityTrustDomain,\n });\n return {\n identityTrustDomain,\n service: createSecurityIncidentService({\n database: input.database,\n logError: input.logError,\n onIncident: input.options.onSecurityIncident,\n trustDomain: identityTrustDomain,\n }),\n };\n}\n\nexport type ClientDatabaseOptions = Omit<DatabaseOptions, \"status\">;\n\nexport interface ClientOptions {\n apiBaseUrl?: string | undefined;\n /** Reuse a memory-only request counter across client lifetimes. */\n apiRequestMetrics?: ApiRequestMetrics | undefined;\n blobStore?: BlobStore | undefined;\n blobStoreFactory?: BlobStoreFactory | undefined;\n database?: ClientDatabaseOptions | undefined;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n events?: ReadonlyArray<unknown> | undefined;\n identity?: IdentityOptions | undefined;\n /**\n * Absolute, host-controlled API namespace for durable user-identity pins.\n * Required only when apiBaseUrl is relative and no browser origin exists.\n */\n identityTrustDomain?: string | undefined;\n identityProvisioning?: \"auto\" | \"manual\" | undefined;\n logger?: Logger | undefined;\n online?: boolean | undefined;\n /** Called after a trust-boundary verification failure is durably recorded. */\n onSecurityIncident?: SecurityIncidentListener | undefined;\n /**\n * Per-pane discriminator so documents in distinct panes derive distinct Loro\n * peer ids (e.g. the pane's local identity namespace). Omit for single-pane.\n */\n peerScope?: string | undefined;\n /** Private host key for durable history progress; omitted uses disposable session keys. */\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n /** Compound policy dispatch/recovery deadline in milliseconds; defaults to 60 seconds. */\n principalMutationTimeoutMs?: number | undefined;\n /**\n * App-owned system containers born with every new organization (both\n * registration and additional-org creation provision them atomically in the\n * same server call), e.g. a trash bin. The app owns these because their slot\n * namespaces are app concepts the SDK stays agnostic to.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n}\n\nexport class Tearleads {\n readonly apiVersion = new ApiVersion();\n readonly apiRequests: ApiRequestMetrics;\n readonly blobs: Blobs;\n readonly database: Database;\n readonly deviceFirst: DeviceFirst;\n readonly documents: Documents;\n readonly events: Events;\n readonly containerContents: ContainerContents;\n readonly identity: Identity;\n readonly network: Network;\n readonly organizations: Organizations;\n readonly root: Root;\n readonly runtime: Runtime;\n readonly securityIncidents: SecurityIncidents;\n readonly session: Session;\n readonly syncBillingGate: SyncBillingGate;\n readonly userIdentities: UserIdentities;\n\n private readonly apiClient: ApiClient;\n private readonly documentProjectors: DocumentProjectorRegistry;\n private readonly disposeSecurityIncidents: () => void;\n private retirePrincipalHistoryProtection = () => {};\n // Tracks the storage/identity pair that owns domain-scoped runtime state.\n private domainScopeKey: string | null = null;\n // Recreated when the storage database or signing identity changes.\n private domainScopeValue: DomainScope = createDomainScope();\n private readonly logErrorHandler: (\n message: string | Error,\n cause?: unknown,\n ) => void;\n private readonly logHandler: (message: string) => void;\n private autoIdentityProvisioned = false;\n private autoIdentityProvisioningPromise: Promise<void> | null = null;\n private expiredSessionLoginPromise: Promise<boolean> | null = null;\n // Rebound to the workflow runtime once it exists; the session is created first.\n private pinLocalUserIdentity: InternalRuntime[\"pinLocalUserIdentity\"] =\n async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n private primeProvisionedPrincipalHistory: InternalRuntime[\"primeProvisionedPrincipalHistory\"] =\n async () => undefined;\n private boundUserId: InternalRuntime[\"boundUserId\"] = async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n\n constructor(options: ClientOptions = {}) {\n const apiBaseUrl = options.apiBaseUrl ?? \"\";\n this.apiRequests = options.apiRequestMetrics ?? new ApiRequestMetrics();\n this.apiClient = this.createApiClient(apiBaseUrl);\n this.blobs = new Blobs(options.blobStore, options.blobStoreFactory);\n this.database = new Database(options.database);\n this.documentProjectors = resolveDocumentProjectorRegistry(\n options.documentProjectors,\n );\n this.events = new Events(options.events, () =>\n this.apiClient.clearWriterProjectionCaches(),\n );\n this.logHandler = options.logger?.log ?? (() => undefined);\n this.logErrorHandler = options.logger?.logError ?? logErrorToConsole;\n const security = createClientSecurityIncidentService({\n apiBaseUrl,\n database: this.database,\n logError: this.logError,\n options,\n });\n this.securityIncidents = security.service.incidents;\n this.disposeSecurityIncidents = security.service.dispose;\n this.network = new Network(options.online);\n this.syncBillingGate = new SyncBillingGate();\n let session: Session | null = null;\n this.identity = createIdentity(\n options.identity,\n (signingFingerprint) =>\n this.blobs.updateIdentityNamespace(signingFingerprint),\n this.log,\n {\n bootstrapLocalRootContainer: async () => {\n if (this.database.status !== \"ready\") {\n throw new Error(\n \"identity.generate requires a ready SQLite database.\",\n );\n }\n if (!session) {\n throw new Error(\n \"identity.generate requires an initialized session.\",\n );\n }\n\n return session.bootstrapLocalRootContainer();\n },\n getUserId: () => session?.userId ?? null,\n },\n );\n session = this.createClientSession(options, security.service.report);\n this.session = session;\n const runtime = this.createWorkflowRuntime(\n security.identityTrustDomain,\n options,\n security.service.report,\n );\n this.bindTrustedIdentityRuntime(runtime);\n this.runtime = runtime.publicRuntime;\n this.documents = createDocuments({\n getDefaultContainerId: () => this.session.containerId,\n runtime,\n });\n this.containerContents = createContainerContents(runtime);\n this.deviceFirst = createDeviceFirst(runtime, this.containerContents);\n this.organizations = createOrganizations(runtime, this.containerContents);\n this.root = createRoot(rootRuntimeOf(runtime, this.session));\n this.userIdentities = createUserIdentities({\n log: this.log,\n resolveTrustedUserIdentity: (userId) =>\n runtime.workflowInput().resolveTrustedUserIdentity(userId),\n });\n\n this.configureApiClientCallbacks();\n\n if (options.identityProvisioning === \"auto\") {\n this.startAutomaticIdentityProvisioning();\n }\n }\n\n /** Trust callbacks reach the workflow runtime, which is created later. */\n private createClientSession(\n options: ClientOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): Session {\n return createSession({\n api: this.apiClient,\n database: this.database,\n documentProjectors: this.documentProjectors,\n identity: this.identity,\n log: this.log,\n logError: this.logError,\n boundUserIdForSigningKey: (signingKeyFingerprint) =>\n this.boundUserId(signingKeyFingerprint),\n onUserIdentityAvailable: (userId, candidate) =>\n this.pinLocalUserIdentity(userId, candidate),\n primeProvisionedPrincipalHistory: (input) =>\n this.primeProvisionedPrincipalHistory(input),\n provisionedSystemContainers: options.provisionedSystemContainers,\n reportSecurityIncident,\n });\n }\n\n private createApiClient(apiBaseUrl: string): ApiClient {\n return new ApiClient(apiBaseUrl, {\n metrics: this.apiRequests,\n getIdentity: () => this.identity.signingFingerprint,\n });\n }\n\n /** Rebinds the session's trust callbacks once the runtime exists. */\n private bindTrustedIdentityRuntime(runtime: InternalRuntime): void {\n this.retirePrincipalHistoryProtection =\n runtime.retirePrincipalHistoryProtection;\n this.pinLocalUserIdentity = (userId, candidate) =>\n runtime.pinLocalUserIdentity(userId, candidate);\n this.primeProvisionedPrincipalHistory =\n runtime.primeProvisionedPrincipalHistory;\n this.boundUserId = (signingKeyFingerprint) =>\n runtime.boundUserId(signingKeyFingerprint);\n }\n\n private configureApiClientCallbacks(): void {\n this.apiClient.setOnError((message) => this.logError(message));\n // An authoritative host source owns connectivity. Without one, request\n // outcomes remain reachability hints. Browser and native app bindings both\n // install authoritative sources so a backend outage cannot stop retries.\n this.apiClient.setOnNetworkError(() =>\n this.network.reportReachability(false),\n );\n this.apiClient.setOnNetworkSuccess(() =>\n this.network.reportReachability(true),\n );\n this.apiClient.setOnApiVersion((version) =>\n this.apiVersion.observe(version),\n );\n this.apiClient.setOnSessionExpired(() => this.loginAfterSessionExpired());\n this.apiClient.setOnPaymentRequired((organizationId) =>\n this.syncBillingGate.notifyPaymentRequired(organizationId),\n );\n }\n\n private createWorkflowRuntime(\n identityTrustDomain: string | null,\n options: ClientOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): InternalRuntime {\n return createRuntime({\n api: this.apiClient,\n blobs: this.blobs,\n database: this.database,\n documentProjectors: this.documentProjectors,\n events: this.events,\n getDomainScope: () => this.domainScope,\n identity: this.identity,\n identityTrustDomain,\n log: this.log,\n logError: this.logError,\n network: this.network,\n peerScope: options.peerScope ?? null,\n principalHistoryKeyProvider: options.principalHistoryKeyProvider,\n principalMutationTimeoutMs: options.principalMutationTimeoutMs,\n reportSecurityIncident,\n session: this.session,\n syncBillingGate: this.syncBillingGate,\n });\n }\n\n log = (message: string): void => {\n this.logHandler(message);\n };\n\n // Preserve the host's return value so best-effort callers can also catch\n // rejected promises from async loggers accepted by the void callback type.\n logError = (message: string | Error, cause?: unknown): void =>\n this.logErrorHandler(message, cause);\n\n /**\n * A single-use ticket to authenticate the server-events websocket handshake\n * (which cannot carry the bearer header): the one login returned for the\n * first connect of that session, otherwise a freshly minted one. Returns\n * null when no session is active. The caller appends it to the websocket URL.\n */\n requestWebSocketTicket(): Promise<string | null> {\n return this.apiClient.requestWebSocketTicket();\n }\n\n get domainScope(): DomainScope {\n const nextScopeKey = JSON.stringify([\n this.database.id,\n this.identity.signingFingerprint,\n ]);\n if (this.domainScopeKey !== nextScopeKey) {\n this.domainScopeKey = nextScopeKey;\n this.domainScopeValue = createDomainScope();\n }\n\n return this.domainScopeValue;\n }\n\n /**\n * Tear down background work for the active domain scope: stop the reconciler\n * and force-stop the sync coordinator pump, then drop the coordinator from\n * its registry. Hosts call this from unmount/cleanup so a pump cannot outlive\n * the React tree that created it. A later access for the same scope rebuilds\n * fresh state.\n */\n dispose(): void {\n const domainScope = this.domainScope;\n this.disposeSecurityIncidents();\n this.retirePrincipalHistoryProtection();\n this.deviceFirst.dispose();\n disposeDomainSyncCoordinator(domainScope);\n }\n\n private loginAfterSessionExpired(): Promise<boolean> {\n if (!this.session.authToken || !this.identity.signingKeyPair) {\n this.session.logout();\n return Promise.resolve(false);\n }\n\n // The API client replays requests the expired session sent, so a login is\n // their renewal only when the loaded keys authenticate that known user.\n const expiredUserId = this.session.userId;\n this.expiredSessionLoginPromise ??= this.session\n .login()\n .then(\n (renewed) =>\n renewed &&\n expiredUserId !== null &&\n this.session.userId === expiredUserId,\n )\n .finally(() => {\n this.expiredSessionLoginPromise = null;\n });\n return this.expiredSessionLoginPromise;\n }\n\n private startAutomaticIdentityProvisioning(): void {\n let unsubscribe: (() => void) | null = null;\n const stopProvisioningListener = () => {\n unsubscribe?.();\n unsubscribe = null;\n };\n const maybeProvisionIdentity = () => {\n if (this.autoIdentityProvisioned || this.identity.signingKeyPair) {\n stopProvisioningListener();\n return;\n }\n\n if (\n this.autoIdentityProvisioningPromise ||\n this.database.status !== \"ready\"\n ) {\n return;\n }\n\n this.autoIdentityProvisioningPromise = this.identity\n .generate()\n .then(() => {\n this.autoIdentityProvisioned = true;\n stopProvisioningListener();\n })\n .catch((error: unknown) => {\n try {\n this.logError(\"Automatic identity provisioning failed\", error);\n } catch {\n // Keep background provisioning failures from surfacing as unhandled rejections.\n }\n })\n .finally(() => {\n this.autoIdentityProvisioningPromise = null;\n });\n };\n\n unsubscribe = this.database.subscribe(maybeProvisionIdentity);\n void Promise.resolve().then(maybeProvisionIdentity);\n }\n}\n"]}
1
+ {"version":3,"file":"Tearleads.js","sourceRoot":"","sources":["Tearleads.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAErE,OAAO,EAGL,gCAAgC,GACjC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAoB,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EAAE,+BAA+B,EAAE,MAAM,uDAAuD,CAAC;AAExG,OAAO,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAEzE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAyB,KAAK,EAAE,MAAM,SAAS,CAAC;AACvD,OAAO,EAEL,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAwB,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAoB,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,eAAe,EAAkB,MAAM,aAAa,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EACL,cAAc,GAGf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAe,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAA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AQ,CAAC,cAAc,EAAE,CAAC;gBACjE,wBAAwB,EAAE,CAAC;gBAC3B,OAAO;YACT,CAAC;YAED,IACE,IAAI,CAAC,+BAA+B;gBACpC,IAAI,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO,EAChC,CAAC;gBACD,OAAO;YACT,CAAC;YAED,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC,QAAQ;iBACjD,QAAQ,EAAE;iBACV,IAAI,CAAC,GAAG,EAAE;gBACT,IAAI,CAAC,uBAAuB,GAAG,IAAI,CAAC;gBACpC,wBAAwB,EAAE,CAAC;YAC7B,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACxB,IAAI,CAAC;oBACH,IAAI,CAAC,QAAQ,CAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;gBACjE,CAAC;gBAAC,MAAM,CAAC;oBACP,gFAAgF;gBAClF,CAAC;YACH,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACZ,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC;YAC9C,CAAC,CAAC,CAAC;QACP,CAAC,CAAC;QAEF,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;QAC9D,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACtD,CAAC;CACF","sourcesContent":["import { ApiClient, ApiRequestMetrics } from \"@tearleads/api-client\";\nimport type { BlobStore } from \"../data/blobContracts\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../data/documents/documentKinds\";\nimport { createDomainScope, type DomainScope } from \"../data/domainScope\";\nimport { createVerifiedManifestCitations } from \"../data/persistence/verifiedManifestBundlePersistence\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { disposeDomainSyncCoordinator } from \"../data/sync/syncCoordinator\";\nimport { resolveIdentityTrustDomain } from \"../data/trustedUserIdentity\";\nimport type { ProvisionedSystemContainerSpec } from \"../workflows/registration\";\nimport { ApiVersion } from \"./apiVersion\";\nimport { type BlobStoreFactory, Blobs } from \"./blobs\";\nimport {\n type ContainerContents,\n createContainerContents,\n} from \"./containerContents\";\nimport { Database, type DatabaseOptions } from \"./database\";\nimport { createDeviceFirst, type DeviceFirst } from \"./deviceFirst\";\nimport { createDocuments, type Documents } from \"./documents\";\nimport { Events } from \"./events\";\nimport {\n createIdentity,\n type Identity,\n type IdentityOptions,\n} from \"./identity\";\nimport { type Logger, logErrorToConsole } from \"./logger\";\nimport { Network } from \"./network\";\nimport { createOrganizations, type Organizations } from \"./organizations\";\nimport type { PrincipalHistoryKeyProvider } from \"./principalHistoryProtection\";\nimport { createRoot, type Root, rootRuntimeOf } from \"./root\";\nimport {\n createSecurityIncidentService,\n type SecurityIncidentListener,\n type SecurityIncidents,\n} from \"./securityIncidents\";\nimport { createSession } from \"./session\";\nimport type { Session } from \"./session/sessionTypes\";\nimport { SyncBillingGate } from \"./syncBillingGate\";\nimport { createUserIdentities, type UserIdentities } from \"./userIdentities\";\nimport {\n createRuntime,\n type InternalRuntime,\n type Runtime,\n} from \"./workflowRuntime\";\n\nfunction createClientSecurityIncidentService(input: {\n readonly apiBaseUrl: string;\n readonly database: Database;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly options: ClientOptions;\n}) {\n const identityTrustDomain = resolveIdentityTrustDomain({\n apiBaseUrl: input.apiBaseUrl,\n identityTrustDomain: input.options.identityTrustDomain,\n });\n return {\n identityTrustDomain,\n service: createSecurityIncidentService({\n database: input.database,\n logError: input.logError,\n onIncident: input.options.onSecurityIncident,\n trustDomain: identityTrustDomain,\n }),\n };\n}\n\nexport type ClientDatabaseOptions = Omit<DatabaseOptions, \"status\">;\n\nexport interface ClientOptions {\n apiBaseUrl?: string | undefined;\n /** Reuse a memory-only request counter across client lifetimes. */\n apiRequestMetrics?: ApiRequestMetrics | undefined;\n blobStore?: BlobStore | undefined;\n blobStoreFactory?: BlobStoreFactory | undefined;\n database?: ClientDatabaseOptions | undefined;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n events?: ReadonlyArray<unknown> | undefined;\n identity?: IdentityOptions | undefined;\n /**\n * Absolute, host-controlled API namespace for durable user-identity pins.\n * Required only when apiBaseUrl is relative and no browser origin exists.\n */\n identityTrustDomain?: string | undefined;\n identityProvisioning?: \"auto\" | \"manual\" | undefined;\n logger?: Logger | undefined;\n online?: boolean | undefined;\n /** Called after a trust-boundary verification failure is durably recorded. */\n onSecurityIncident?: SecurityIncidentListener | undefined;\n /**\n * Per-pane discriminator so documents in distinct panes derive distinct Loro\n * peer ids (e.g. the pane's local identity namespace). Omit for single-pane.\n */\n peerScope?: string | undefined;\n /** Private host key for durable history progress; omitted uses disposable session keys. */\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n /** Compound policy dispatch/recovery deadline in milliseconds; defaults to 60 seconds. */\n principalMutationTimeoutMs?: number | undefined;\n /**\n * App-owned system containers born with every new organization (both\n * registration and additional-org creation provision them atomically in the\n * same server call), e.g. a trash bin. The app owns these because their slot\n * namespaces are app concepts the SDK stays agnostic to.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n}\n\nexport class Tearleads {\n readonly apiVersion = new ApiVersion();\n readonly apiRequests: ApiRequestMetrics;\n readonly blobs: Blobs;\n readonly database: Database;\n readonly deviceFirst: DeviceFirst;\n readonly documents: Documents;\n readonly events: Events;\n readonly containerContents: ContainerContents;\n readonly identity: Identity;\n readonly network: Network;\n readonly organizations: Organizations;\n readonly root: Root;\n readonly runtime: Runtime;\n readonly securityIncidents: SecurityIncidents;\n readonly session: Session;\n readonly syncBillingGate: SyncBillingGate;\n readonly userIdentities: UserIdentities;\n\n private readonly apiClient: ApiClient;\n private readonly documentProjectors: DocumentProjectorRegistry;\n private readonly disposeSecurityIncidents: () => void;\n private retirePrincipalHistoryProtection = () => {};\n // Tracks the storage/identity pair that owns domain-scoped runtime state.\n private domainScopeKey: string | null = null;\n // Recreated when the storage database or signing identity changes.\n private domainScopeValue: DomainScope = createDomainScope();\n private readonly logErrorHandler: (\n message: string | Error,\n cause?: unknown,\n ) => void;\n private readonly logHandler: (message: string) => void;\n private autoIdentityProvisioned = false;\n private autoIdentityProvisioningPromise: Promise<void> | null = null;\n private expiredSessionLoginPromise: Promise<boolean> | null = null;\n // Rebound to the workflow runtime once it exists; the session is created first.\n private pinLocalUserIdentity: InternalRuntime[\"pinLocalUserIdentity\"] =\n async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n private primeProvisionedPrincipalHistory: InternalRuntime[\"primeProvisionedPrincipalHistory\"] =\n async () => undefined;\n private boundUserId: InternalRuntime[\"boundUserId\"] = async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n\n constructor(options: ClientOptions = {}) {\n const apiBaseUrl = options.apiBaseUrl ?? \"\";\n this.apiRequests = options.apiRequestMetrics ?? new ApiRequestMetrics();\n this.apiClient = this.createApiClient(apiBaseUrl);\n this.blobs = new Blobs(options.blobStore, options.blobStoreFactory);\n this.database = new Database(options.database);\n this.documentProjectors = resolveDocumentProjectorRegistry(\n options.documentProjectors,\n );\n this.events = new Events(options.events, () =>\n this.apiClient.clearWriterProjectionCaches(),\n );\n this.logHandler = options.logger?.log ?? (() => undefined);\n this.logErrorHandler = options.logger?.logError ?? logErrorToConsole;\n const security = createClientSecurityIncidentService({\n apiBaseUrl,\n database: this.database,\n logError: this.logError,\n options,\n });\n this.securityIncidents = security.service.incidents;\n this.disposeSecurityIncidents = security.service.dispose;\n this.network = new Network(options.online);\n this.syncBillingGate = new SyncBillingGate();\n let session: Session | null = null;\n this.identity = createIdentity(\n options.identity,\n (signingFingerprint) =>\n this.blobs.updateIdentityNamespace(signingFingerprint),\n this.log,\n {\n bootstrapLocalRootContainer: async () => {\n if (this.database.status !== \"ready\") {\n throw new Error(\n \"identity.generate requires a ready SQLite database.\",\n );\n }\n if (!session) {\n throw new Error(\n \"identity.generate requires an initialized session.\",\n );\n }\n\n return session.bootstrapLocalRootContainer();\n },\n getUserId: () => session?.userId ?? null,\n },\n );\n session = this.createClientSession(options, security.service.report);\n this.session = session;\n const runtime = this.createWorkflowRuntime(\n security.identityTrustDomain,\n options,\n security.service.report,\n );\n this.bindTrustedIdentityRuntime(runtime);\n this.runtime = runtime.publicRuntime;\n this.documents = createDocuments({\n getDefaultContainerId: () => this.session.containerId,\n runtime,\n });\n this.containerContents = createContainerContents(runtime);\n this.deviceFirst = createDeviceFirst(runtime, this.containerContents);\n this.organizations = createOrganizations(runtime, this.containerContents);\n this.root = createRoot(rootRuntimeOf(runtime, this.session));\n this.userIdentities = createUserIdentities({\n log: this.log,\n resolveTrustedUserIdentity: (userId) =>\n runtime.workflowInput().resolveTrustedUserIdentity(userId),\n });\n\n this.configureApiClientCallbacks();\n\n if (options.identityProvisioning === \"auto\") {\n this.startAutomaticIdentityProvisioning();\n }\n }\n\n /** Trust callbacks reach the workflow runtime, which is created later. */\n private createClientSession(\n options: ClientOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): Session {\n return createSession({\n api: this.apiClient,\n database: this.database,\n documentProjectors: this.documentProjectors,\n identity: this.identity,\n log: this.log,\n logError: this.logError,\n boundUserIdForSigningKey: (signingKeyFingerprint) =>\n this.boundUserId(signingKeyFingerprint),\n onUserIdentityAvailable: (userId, candidate) =>\n this.pinLocalUserIdentity(userId, candidate),\n primeProvisionedPrincipalHistory: (input) =>\n this.primeProvisionedPrincipalHistory(input),\n provisionedSystemContainers: options.provisionedSystemContainers,\n reportSecurityIncident,\n });\n }\n\n private createApiClient(apiBaseUrl: string): ApiClient {\n return new ApiClient(apiBaseUrl, {\n metrics: this.apiRequests,\n getIdentity: () => this.identity.signingFingerprint,\n });\n }\n\n /** Rebinds the session's trust callbacks once the runtime exists. */\n private bindTrustedIdentityRuntime(runtime: InternalRuntime): void {\n this.retirePrincipalHistoryProtection =\n runtime.retirePrincipalHistoryProtection;\n this.pinLocalUserIdentity = (userId, candidate) =>\n runtime.pinLocalUserIdentity(userId, candidate);\n this.primeProvisionedPrincipalHistory =\n runtime.primeProvisionedPrincipalHistory;\n this.boundUserId = (signingKeyFingerprint) =>\n runtime.boundUserId(signingKeyFingerprint);\n }\n\n private configureApiClientCallbacks(): void {\n // Projection reads cite bundles this identity's database already verified.\n this.apiClient.setVerifiedManifestCitations(\n createVerifiedManifestCitations(() => this.database.execSql),\n );\n this.apiClient.setOnError((message) => this.logError(message));\n // An authoritative host source owns connectivity. Without one, request\n // outcomes remain reachability hints. Browser and native app bindings both\n // install authoritative sources so a backend outage cannot stop retries.\n this.apiClient.setOnNetworkError(() =>\n this.network.reportReachability(false),\n );\n this.apiClient.setOnNetworkSuccess(() =>\n this.network.reportReachability(true),\n );\n this.apiClient.setOnApiVersion((version) =>\n this.apiVersion.observe(version),\n );\n this.apiClient.setOnSessionExpired(() => this.loginAfterSessionExpired());\n this.apiClient.setOnPaymentRequired((organizationId) =>\n this.syncBillingGate.notifyPaymentRequired(organizationId),\n );\n }\n\n private createWorkflowRuntime(\n identityTrustDomain: string | null,\n options: ClientOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): InternalRuntime {\n return createRuntime({\n api: this.apiClient,\n blobs: this.blobs,\n database: this.database,\n documentProjectors: this.documentProjectors,\n events: this.events,\n getDomainScope: () => this.domainScope,\n identity: this.identity,\n identityTrustDomain,\n log: this.log,\n logError: this.logError,\n network: this.network,\n peerScope: options.peerScope ?? null,\n principalHistoryKeyProvider: options.principalHistoryKeyProvider,\n principalMutationTimeoutMs: options.principalMutationTimeoutMs,\n reportSecurityIncident,\n session: this.session,\n syncBillingGate: this.syncBillingGate,\n });\n }\n\n log = (message: string): void => {\n this.logHandler(message);\n };\n\n // Preserve the host's return value so best-effort callers can also catch\n // rejected promises from async loggers accepted by the void callback type.\n logError = (message: string | Error, cause?: unknown): void =>\n this.logErrorHandler(message, cause);\n\n /**\n * A single-use ticket to authenticate the server-events websocket handshake\n * (which cannot carry the bearer header): the one login returned for the\n * first connect of that session, otherwise a freshly minted one. Returns\n * null when no session is active. The caller appends it to the websocket URL.\n */\n requestWebSocketTicket(): Promise<string | null> {\n return this.apiClient.requestWebSocketTicket();\n }\n\n get domainScope(): DomainScope {\n const nextScopeKey = JSON.stringify([\n this.database.id,\n this.identity.signingFingerprint,\n ]);\n if (this.domainScopeKey !== nextScopeKey) {\n this.domainScopeKey = nextScopeKey;\n this.domainScopeValue = createDomainScope();\n }\n\n return this.domainScopeValue;\n }\n\n /**\n * Tear down background work for the active domain scope: stop the reconciler\n * and force-stop the sync coordinator pump, then drop the coordinator from\n * its registry. Hosts call this from unmount/cleanup so a pump cannot outlive\n * the React tree that created it. A later access for the same scope rebuilds\n * fresh state.\n */\n dispose(): void {\n const domainScope = this.domainScope;\n this.disposeSecurityIncidents();\n this.retirePrincipalHistoryProtection();\n this.deviceFirst.dispose();\n disposeDomainSyncCoordinator(domainScope);\n }\n\n private loginAfterSessionExpired(): Promise<boolean> {\n if (!this.session.authToken || !this.identity.signingKeyPair) {\n this.session.logout();\n return Promise.resolve(false);\n }\n\n // The API client replays requests the expired session sent, so a login is\n // their renewal only when the loaded keys authenticate that known user.\n const expiredUserId = this.session.userId;\n this.expiredSessionLoginPromise ??= this.session\n .login()\n .then(\n (renewed) =>\n renewed &&\n expiredUserId !== null &&\n this.session.userId === expiredUserId,\n )\n .finally(() => {\n this.expiredSessionLoginPromise = null;\n });\n return this.expiredSessionLoginPromise;\n }\n\n private startAutomaticIdentityProvisioning(): void {\n let unsubscribe: (() => void) | null = null;\n const stopProvisioningListener = () => {\n unsubscribe?.();\n unsubscribe = null;\n };\n const maybeProvisionIdentity = () => {\n if (this.autoIdentityProvisioned || this.identity.signingKeyPair) {\n stopProvisioningListener();\n return;\n }\n\n if (\n this.autoIdentityProvisioningPromise ||\n this.database.status !== \"ready\"\n ) {\n return;\n }\n\n this.autoIdentityProvisioningPromise = this.identity\n .generate()\n .then(() => {\n this.autoIdentityProvisioned = true;\n stopProvisioningListener();\n })\n .catch((error: unknown) => {\n try {\n this.logError(\"Automatic identity provisioning failed\", error);\n } catch {\n // Keep background provisioning failures from surfacing as unhandled rejections.\n }\n })\n .finally(() => {\n this.autoIdentityProvisioningPromise = null;\n });\n };\n\n unsubscribe = this.database.subscribe(maybeProvisionIdentity);\n void Promise.resolve().then(maybeProvisionIdentity);\n }\n}\n"]}
@@ -227,14 +227,12 @@ function documentSyncContentKeyBundlesByEpoch(plan, response) {
227
227
  bundle.contentKeyEpoch <= 0) {
228
228
  throw new Error("Document sync response content-key bundle epoch mismatch");
229
229
  }
230
- const existing = bundleByEpoch.get(bundle.contentKeyEpoch);
231
- if (!existing) {
232
- bundleByEpoch.set(bundle.contentKeyEpoch, bundle);
233
- continue;
234
- }
235
- if (contentKeyBundleCanonical(existing) !== contentKeyBundleCanonical(bundle)) {
236
- throw new Error("Document sync response content-key bundle conflict");
230
+ // The current epoch travels only as contentKeyBundle; the array carries
231
+ // each older epoch once.
232
+ if (bundleByEpoch.has(bundle.contentKeyEpoch)) {
233
+ throw new Error("Document sync response repeats a content-key epoch");
237
234
  }
235
+ bundleByEpoch.set(bundle.contentKeyEpoch, bundle);
238
236
  }
239
237
  return bundleByEpoch;
240
238
  }
@@ -1 +1 @@
1
- {"version":3,"file":"syncResponses.js","sourceRoot":"","sources":["syncResponses.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,mCAAmC,EACnC,0CAA0C,EAC1C,wCAAwC,EACxC,iBAAiB,GAElB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACrF,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,GAE1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAE,mCAAmC,EAAE,MAAM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,IAAI,KAAK,6BAA6B,CACzE,CAAC;AACJ,CAAC","sourcesContent":["import {\n CONTENT_RECORD_ENCRYPTION_SUITE,\n computeContentRecordNonceDomainHash,\n computeDocumentContentRecordCiphertextHash,\n computeDocumentContentRecordMetadataHash,\n verifyWriteHeader,\n type WriteHeader,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n DOCUMENT_SYNC_ERROR_CODES,\n type DocumentSyncResponse,\n} from \"@tearleads/validators/response\";\nimport { parseWalLsn } from \"@tearleads/validators/util\";\nimport { throwKeyingVerificationShapeFailure } from \"../../keyingProjectionVerification/error\";\nimport {\n readRecordPositiveInteger,\n readRecordString,\n readWriteHeader,\n serializeCanonical,\n serializedPersistedDocumentState,\n} from \"./readers\";\n\nexport { submitDocumentSync } from \"./syncPagination\";\n\nimport { documentWriteAuthorizationForHeader } from \"./syncResponseAuthorization\";\nimport type {\n DocumentSyncPlan,\n DocumentSyncSubmitFailure,\n DocumentWriterPublicKeyResolver,\n PersistedDocumentSyncState,\n} from \"./types\";\n\n// Remote-primary databases without a portable WAL position use the zero LSN\n// as an explicit \"checkpoint not tracked\" sentinel. It is accepted only when\n// the response declares that mode, letting a local record carrying a checkpoint\n// from another backend move to that primary without weakening tracked checks.\n// This protects against replica lag, not a server that falsely declares its own\n// consistency capability; the authenticated server remains the source of data.\nconst UNTRACKED_COMMIT_LSN = \"0/0\";\n\nexport class DocumentSyncResponseUpdateContentKeyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DocumentSyncResponseUpdateContentKeyError\";\n }\n}\n\nfunction assertAcceptedOutgoingUpdateIdsMatchPlan(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n const expected = plan.request.outgoingUpdates.map((update) => update.id);\n const accepted = response.acceptedOutgoingUpdateIds;\n const expectedSorted = [...expected].sort();\n const acceptedSorted = [...accepted].sort();\n if (\n expectedSorted.length !== acceptedSorted.length ||\n expectedSorted.some((id, index) => id !== acceptedSorted[index])\n ) {\n throw new Error(\"Document sync response accepted update mismatch\");\n }\n}\n\nasync function assertDocumentSyncResponseUpdateMatchesPlan(input: {\n contentKeyBundlesByEpoch: ReadonlyMap<\n number,\n DocumentSyncResponse[\"contentKeyBundle\"]\n >;\n plan: DocumentSyncPlan;\n update: DocumentSyncResponse[\"updates\"][number];\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n}): Promise<void> {\n const { plan, update } = input;\n if (update.documentId !== plan.documentId) {\n throw new Error(\"Document sync response update document mismatch\");\n }\n const header = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n );\n await assertDocumentSyncResponseUpdateHashes({ update });\n const contentKeyBundle = assertDocumentSyncResponseUpdateContentKeyBundle({\n contentKeyBundlesByEpoch: input.contentKeyBundlesByEpoch,\n header,\n plan,\n });\n assertDocumentSyncResponseWriteHeaderFields({ header, plan, update });\n await assertDocumentSyncResponseNonceDomain({ header, plan });\n await assertDocumentSyncResponseWriteHeaderSignature({\n header,\n contentKeyBundle,\n plan,\n resolveWriterPublicKey: input.resolveWriterPublicKey,\n update,\n });\n}\n\nfunction assertDocumentSyncResponseUpdateContentKeyBundle(input: {\n contentKeyBundlesByEpoch: ReadonlyMap<\n number,\n DocumentSyncResponse[\"contentKeyBundle\"]\n >;\n header: WriteHeader;\n plan: DocumentSyncPlan;\n}): DocumentSyncResponse[\"contentKeyBundle\"] {\n const { header, plan } = input;\n if (header.contentKeyEpoch > plan.contentKeyEpoch) {\n throw new DocumentSyncResponseUpdateContentKeyError(\n \"Document sync response includes a future content-key epoch\",\n );\n }\n\n const bundle = input.contentKeyBundlesByEpoch.get(header.contentKeyEpoch);\n if (!bundle) {\n throw new DocumentSyncResponseUpdateContentKeyError(\n \"Document sync response content-key bundle missing\",\n );\n }\n if (\n bundle.documentId !== plan.documentId ||\n bundle.contentKeyEpoch !== header.contentKeyEpoch\n ) {\n throw new Error(\"Document sync response content-key bundle mismatch\");\n }\n return bundle;\n}\n\nasync function assertDocumentSyncResponseUpdateHashes(input: {\n update: DocumentSyncResponse[\"updates\"][number];\n}): Promise<void> {\n const { update } = input;\n const ciphertextHash = await computeDocumentContentRecordCiphertextHash(\n update.encryptedData,\n );\n if (\n ciphertextHash !==\n readRecordString(update.writeHeader, \"ciphertextHash\", \"write header\")\n ) {\n throw new Error(\"Document sync response ciphertext hash mismatch\");\n }\n const metadataHash = await computeDocumentContentRecordMetadataHash({\n ...(update.checkpointKind === undefined\n ? {}\n : { checkpointKind: update.checkpointKind }),\n ...(update.checkpointPayloadKind === undefined\n ? {}\n : { checkpointPayloadKind: update.checkpointPayloadKind }),\n documentId: update.documentId,\n partialEndVersionVector: update.partialEndVersionVector,\n partialStartVersionVector: update.partialStartVersionVector,\n plaintextHash: update.plaintextHash,\n ...(update.sourceVersionVector === undefined\n ? {}\n : { sourceVersionVector: update.sourceVersionVector }),\n updateId: update.id,\n });\n if (\n metadataHash !==\n readRecordString(update.writeHeader, \"metadataHash\", \"write header\")\n ) {\n throw new Error(\"Document sync response metadata hash mismatch\");\n }\n}\n\nfunction assertDocumentSyncResponseWriteHeaderFields(input: {\n header: WriteHeader;\n plan: DocumentSyncPlan;\n update: DocumentSyncResponse[\"updates\"][number];\n}): void {\n const { header, plan, update } = input;\n const mustMatchCurrentBoundary = isAcceptedOutgoingSyncUpdate(plan, update);\n\n if (\n header.version !== 1 ||\n header.objectKind !== \"document\" ||\n header.objectId !== plan.documentId ||\n header.organizationId !== plan.organizationId ||\n header.encryptionSuite !== CONTENT_RECORD_ENCRYPTION_SUITE ||\n header.writerKeyFingerprint !== update.authorFingerprint ||\n (mustMatchCurrentBoundary &&\n (header.contentKeyEpoch !== plan.contentKeyEpoch ||\n header.accessManifestHash !== plan.expectedLinkSetManifestHash ||\n header.targetHash !== plan.expectedTargetHash))\n ) {\n throw new Error(\"Document sync response write header mismatch\");\n }\n}\n\nfunction isAcceptedOutgoingSyncUpdate(\n plan: DocumentSyncPlan,\n update: DocumentSyncResponse[\"updates\"][number],\n): boolean {\n return plan.request.outgoingUpdates.some(\n (outgoingUpdate) => outgoingUpdate.id === update.id,\n );\n}\n\nasync function assertDocumentSyncResponseNonceDomain(input: {\n header: WriteHeader;\n plan: DocumentSyncPlan;\n}): Promise<void> {\n const { header, plan } = input;\n const nonceDomainHash = await computeContentRecordNonceDomainHash({\n version: 1,\n organizationId: plan.organizationId,\n objectKind: \"document\",\n objectId: plan.documentId,\n contentKeyEpoch: header.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: header.contentRecordId,\n });\n if (nonceDomainHash !== header.nonceDomainHash) {\n throw new Error(\"Document sync response nonce domain mismatch\");\n }\n}\n\nasync function assertDocumentSyncResponseWriteHeaderSignature(input: {\n contentKeyBundle: DocumentSyncResponse[\"contentKeyBundle\"];\n header: WriteHeader;\n plan: DocumentSyncPlan;\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n update: DocumentSyncResponse[\"updates\"][number];\n}): Promise<void> {\n const { header, plan, update } = input;\n const writerPublicKey = await input.resolveWriterPublicKey({\n writerSigningKeyFingerprint: header.writerKeyFingerprint,\n writerUserId: header.writerUserId,\n });\n if (!writerPublicKey) {\n throw new Error(\"Document sync response writer public key missing\");\n }\n\n const documentAuthorization = await documentWriteAuthorizationForHeader({\n allowMissingAuthorization: isAcceptedOutgoingSyncUpdate(plan, update),\n authorizationTargets: update.authorizationTargets,\n dependencyManifestHashes: header.dependencyManifestHashes,\n contentKeyBundle: input.contentKeyBundle,\n manifestHash: header.accessManifestHash,\n plan,\n targetHash: header.targetHash,\n });\n const verified = await verifyWriteHeader({\n authorizationMembership: \"referenced\",\n expectedAccessManifestHash: documentAuthorization\n ? header.accessManifestHash\n : plan.expectedLinkSetManifestHash,\n expectedObject: {\n objectKind: \"document\",\n objectId: plan.documentId,\n organizationId: plan.organizationId,\n },\n header,\n ...(documentAuthorization ? { documentAuthorization } : {}),\n expectedTargetHash: documentAuthorization\n ? header.targetHash\n : plan.expectedTargetHash,\n writerPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n}\n\nfunction assertDocumentSyncCommitCheckpointMatchesPlan(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n if (\n response.commitLsnMode === \"untracked\" &&\n response.commitLsn !== UNTRACKED_COMMIT_LSN\n ) {\n throw new Error(\n \"Document sync response untracked commit LSN must use the 0/0 sentinel\",\n );\n }\n if (\n response.commitLsn === UNTRACKED_COMMIT_LSN &&\n response.commitLsnMode !== \"untracked\"\n ) {\n throw new Error(\n \"Document sync response 0/0 commit LSN must be declared untracked\",\n );\n }\n if (response.commitLsn !== null) {\n parseWalLsn(response.commitLsn, \"Document sync response commit LSN\");\n }\n if (plan.minLsn === undefined) {\n return;\n }\n const minLsn = parseWalLsn(\n plan.minLsn,\n \"Document sync requested minimum LSN\",\n );\n if (response.commitLsn === null) {\n throw new Error(\"Document sync response commit LSN is missing\");\n }\n if (\n !(\n response.commitLsn === UNTRACKED_COMMIT_LSN &&\n response.commitLsnMode === \"untracked\"\n ) &&\n parseWalLsn(response.commitLsn, \"Document sync response commit LSN\") <\n minLsn\n ) {\n throw new Error(\"Document sync response commit LSN is stale\");\n }\n}\n\nfunction documentSyncManifestEpoch(plan: DocumentSyncPlan): number {\n if (!isPlainRecord(plan.documentManifest.state)) {\n throw new Error(\"Document sync manifest state is invalid\");\n }\n\n return readRecordPositiveInteger(\n plan.documentManifest.state,\n \"epoch\",\n \"Document sync manifest state\",\n );\n}\n\n// The one load-bearing epoch check: no returned update may claim an\n// accessEpoch newer than the current manifest epoch.\nfunction assertDocumentSyncAccessEpochsNotInFuture(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n const currentAccessEpoch = documentSyncManifestEpoch(plan);\n for (const update of response.updates) {\n if (update.accessEpoch > currentAccessEpoch) {\n throw new Error(\"Document sync response includes a future access epoch\");\n }\n }\n}\n\nfunction contentKeyBundleCanonical(\n bundle: DocumentSyncResponse[\"contentKeyBundle\"],\n): string {\n return serializeCanonical(bundle, \"content-key bundle\");\n}\n\nfunction documentSyncContentKeyBundlesByEpoch(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): ReadonlyMap<number, DocumentSyncResponse[\"contentKeyBundle\"]> {\n if (\n contentKeyBundleCanonical(response.contentKeyBundle) !==\n contentKeyBundleCanonical(plan.sourceContentKeyBundle)\n ) {\n throw new Error(\"Document sync response content-key bundle mismatch\");\n }\n\n const bundleByEpoch = new Map<\n number,\n DocumentSyncResponse[\"contentKeyBundle\"]\n >();\n const bundles = [response.contentKeyBundle, ...response.contentKeyBundles];\n\n for (const bundle of bundles) {\n if (bundle.documentId !== plan.documentId) {\n throw new Error(\n \"Document sync response content-key bundle document mismatch\",\n );\n }\n if (\n !Number.isInteger(bundle.contentKeyEpoch) ||\n bundle.contentKeyEpoch <= 0\n ) {\n throw new Error(\n \"Document sync response content-key bundle epoch mismatch\",\n );\n }\n\n const existing = bundleByEpoch.get(bundle.contentKeyEpoch);\n if (!existing) {\n bundleByEpoch.set(bundle.contentKeyEpoch, bundle);\n continue;\n }\n if (\n contentKeyBundleCanonical(existing) !== contentKeyBundleCanonical(bundle)\n ) {\n throw new Error(\"Document sync response content-key bundle conflict\");\n }\n }\n\n return bundleByEpoch;\n}\n\nasync function persistedDocumentSyncStateFromResponseInternal(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n options: {\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n },\n): Promise<PersistedDocumentSyncState> {\n if (response.documentId !== plan.documentId) {\n throw new Error(\"Document sync response document id mismatch\");\n }\n const contentKeyBundlesByEpoch = documentSyncContentKeyBundlesByEpoch(\n plan,\n response,\n );\n if (\n serializeCanonical(response.documentKekTargets, \"KEK targets\") !==\n serializeCanonical(plan.documentKekTargets, \"KEK targets\")\n ) {\n throw new Error(\"Document sync response KEK target mismatch\");\n }\n assertAcceptedOutgoingUpdateIdsMatchPlan(plan, response);\n assertDocumentSyncCommitCheckpointMatchesPlan(plan, response);\n assertDocumentSyncAccessEpochsNotInFuture(plan, response);\n\n await Promise.all(\n response.updates.map((update) =>\n assertDocumentSyncResponseUpdateMatchesPlan({\n contentKeyBundlesByEpoch,\n plan,\n resolveWriterPublicKey: options.resolveWriterPublicKey,\n update,\n }),\n ),\n );\n\n return serializedPersistedDocumentState({\n contentKeyBundle: response.contentKeyBundle,\n documentId: plan.documentId,\n documentKekTargets: response.documentKekTargets,\n documentManifestBundle: plan.documentManifest,\n });\n}\n\nexport async function persistedDocumentSyncStateFromResponse(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n options: {\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n },\n): Promise<PersistedDocumentSyncState> {\n try {\n return await persistedDocumentSyncStateFromResponseInternal(\n plan,\n response,\n options,\n );\n } catch (error) {\n if (error instanceof DocumentSyncResponseUpdateContentKeyError) throw error;\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function isRetryableDocumentSyncConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.stateStale\n );\n}\n\n// The wipe gate is deliberately strict — coded 404s only, which is the right\n// failure mode for a destructive action. A bare 404 proves nothing about the\n// document: proxy/tunnel error pages, deploy-skew route misses, and\n// container-level lookups all produce one.\nexport function isUpstreamDeletedDocumentSyncFailure(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE\n );\n}\n"]}
1
+ {"version":3,"file":"syncResponses.js","sourceRoot":"","sources":["syncResponses.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,mCAAmC,EACnC,0CAA0C,EAC1C,wCAAwC,EACxC,iBAAiB,GAElB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,IAAI,aAAa,EAA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ElC,OAAO,CACL,OAAO,CAAC,MAAM,KAAK,GAAG,IAAI,OAAO,CAAC,IAAI,KAAK,6BAA6B,CACzE,CAAC;AACJ,CAAC","sourcesContent":["import {\n CONTENT_RECORD_ENCRYPTION_SUITE,\n computeContentRecordNonceDomainHash,\n computeDocumentContentRecordCiphertextHash,\n computeDocumentContentRecordMetadataHash,\n verifyWriteHeader,\n type WriteHeader,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n DOCUMENT_SYNC_ERROR_CODES,\n type DocumentSyncResponse,\n} from \"@tearleads/validators/response\";\nimport { parseWalLsn } from \"@tearleads/validators/util\";\nimport { throwKeyingVerificationShapeFailure } from \"../../keyingProjectionVerification/error\";\nimport {\n readRecordPositiveInteger,\n readRecordString,\n readWriteHeader,\n serializeCanonical,\n serializedPersistedDocumentState,\n} from \"./readers\";\n\nexport { submitDocumentSync } from \"./syncPagination\";\n\nimport { documentWriteAuthorizationForHeader } from \"./syncResponseAuthorization\";\nimport type {\n DocumentSyncPlan,\n DocumentSyncSubmitFailure,\n DocumentWriterPublicKeyResolver,\n PersistedDocumentSyncState,\n} from \"./types\";\n\n// Remote-primary databases without a portable WAL position use the zero LSN\n// as an explicit \"checkpoint not tracked\" sentinel. It is accepted only when\n// the response declares that mode, letting a local record carrying a checkpoint\n// from another backend move to that primary without weakening tracked checks.\n// This protects against replica lag, not a server that falsely declares its own\n// consistency capability; the authenticated server remains the source of data.\nconst UNTRACKED_COMMIT_LSN = \"0/0\";\n\nexport class DocumentSyncResponseUpdateContentKeyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DocumentSyncResponseUpdateContentKeyError\";\n }\n}\n\nfunction assertAcceptedOutgoingUpdateIdsMatchPlan(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n const expected = plan.request.outgoingUpdates.map((update) => update.id);\n const accepted = response.acceptedOutgoingUpdateIds;\n const expectedSorted = [...expected].sort();\n const acceptedSorted = [...accepted].sort();\n if (\n expectedSorted.length !== acceptedSorted.length ||\n expectedSorted.some((id, index) => id !== acceptedSorted[index])\n ) {\n throw new Error(\"Document sync response accepted update mismatch\");\n }\n}\n\nasync function assertDocumentSyncResponseUpdateMatchesPlan(input: {\n contentKeyBundlesByEpoch: ReadonlyMap<\n number,\n DocumentSyncResponse[\"contentKeyBundle\"]\n >;\n plan: DocumentSyncPlan;\n update: DocumentSyncResponse[\"updates\"][number];\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n}): Promise<void> {\n const { plan, update } = input;\n if (update.documentId !== plan.documentId) {\n throw new Error(\"Document sync response update document mismatch\");\n }\n const header = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n );\n await assertDocumentSyncResponseUpdateHashes({ update });\n const contentKeyBundle = assertDocumentSyncResponseUpdateContentKeyBundle({\n contentKeyBundlesByEpoch: input.contentKeyBundlesByEpoch,\n header,\n plan,\n });\n assertDocumentSyncResponseWriteHeaderFields({ header, plan, update });\n await assertDocumentSyncResponseNonceDomain({ header, plan });\n await assertDocumentSyncResponseWriteHeaderSignature({\n header,\n contentKeyBundle,\n plan,\n resolveWriterPublicKey: input.resolveWriterPublicKey,\n update,\n });\n}\n\nfunction assertDocumentSyncResponseUpdateContentKeyBundle(input: {\n contentKeyBundlesByEpoch: ReadonlyMap<\n number,\n DocumentSyncResponse[\"contentKeyBundle\"]\n >;\n header: WriteHeader;\n plan: DocumentSyncPlan;\n}): DocumentSyncResponse[\"contentKeyBundle\"] {\n const { header, plan } = input;\n if (header.contentKeyEpoch > plan.contentKeyEpoch) {\n throw new DocumentSyncResponseUpdateContentKeyError(\n \"Document sync response includes a future content-key epoch\",\n );\n }\n\n const bundle = input.contentKeyBundlesByEpoch.get(header.contentKeyEpoch);\n if (!bundle) {\n throw new DocumentSyncResponseUpdateContentKeyError(\n \"Document sync response content-key bundle missing\",\n );\n }\n if (\n bundle.documentId !== plan.documentId ||\n bundle.contentKeyEpoch !== header.contentKeyEpoch\n ) {\n throw new Error(\"Document sync response content-key bundle mismatch\");\n }\n return bundle;\n}\n\nasync function assertDocumentSyncResponseUpdateHashes(input: {\n update: DocumentSyncResponse[\"updates\"][number];\n}): Promise<void> {\n const { update } = input;\n const ciphertextHash = await computeDocumentContentRecordCiphertextHash(\n update.encryptedData,\n );\n if (\n ciphertextHash !==\n readRecordString(update.writeHeader, \"ciphertextHash\", \"write header\")\n ) {\n throw new Error(\"Document sync response ciphertext hash mismatch\");\n }\n const metadataHash = await computeDocumentContentRecordMetadataHash({\n ...(update.checkpointKind === undefined\n ? {}\n : { checkpointKind: update.checkpointKind }),\n ...(update.checkpointPayloadKind === undefined\n ? {}\n : { checkpointPayloadKind: update.checkpointPayloadKind }),\n documentId: update.documentId,\n partialEndVersionVector: update.partialEndVersionVector,\n partialStartVersionVector: update.partialStartVersionVector,\n plaintextHash: update.plaintextHash,\n ...(update.sourceVersionVector === undefined\n ? {}\n : { sourceVersionVector: update.sourceVersionVector }),\n updateId: update.id,\n });\n if (\n metadataHash !==\n readRecordString(update.writeHeader, \"metadataHash\", \"write header\")\n ) {\n throw new Error(\"Document sync response metadata hash mismatch\");\n }\n}\n\nfunction assertDocumentSyncResponseWriteHeaderFields(input: {\n header: WriteHeader;\n plan: DocumentSyncPlan;\n update: DocumentSyncResponse[\"updates\"][number];\n}): void {\n const { header, plan, update } = input;\n const mustMatchCurrentBoundary = isAcceptedOutgoingSyncUpdate(plan, update);\n\n if (\n header.version !== 1 ||\n header.objectKind !== \"document\" ||\n header.objectId !== plan.documentId ||\n header.organizationId !== plan.organizationId ||\n header.encryptionSuite !== CONTENT_RECORD_ENCRYPTION_SUITE ||\n header.writerKeyFingerprint !== update.authorFingerprint ||\n (mustMatchCurrentBoundary &&\n (header.contentKeyEpoch !== plan.contentKeyEpoch ||\n header.accessManifestHash !== plan.expectedLinkSetManifestHash ||\n header.targetHash !== plan.expectedTargetHash))\n ) {\n throw new Error(\"Document sync response write header mismatch\");\n }\n}\n\nfunction isAcceptedOutgoingSyncUpdate(\n plan: DocumentSyncPlan,\n update: DocumentSyncResponse[\"updates\"][number],\n): boolean {\n return plan.request.outgoingUpdates.some(\n (outgoingUpdate) => outgoingUpdate.id === update.id,\n );\n}\n\nasync function assertDocumentSyncResponseNonceDomain(input: {\n header: WriteHeader;\n plan: DocumentSyncPlan;\n}): Promise<void> {\n const { header, plan } = input;\n const nonceDomainHash = await computeContentRecordNonceDomainHash({\n version: 1,\n organizationId: plan.organizationId,\n objectKind: \"document\",\n objectId: plan.documentId,\n contentKeyEpoch: header.contentKeyEpoch,\n encryptionSuite: CONTENT_RECORD_ENCRYPTION_SUITE,\n contentRecordId: header.contentRecordId,\n });\n if (nonceDomainHash !== header.nonceDomainHash) {\n throw new Error(\"Document sync response nonce domain mismatch\");\n }\n}\n\nasync function assertDocumentSyncResponseWriteHeaderSignature(input: {\n contentKeyBundle: DocumentSyncResponse[\"contentKeyBundle\"];\n header: WriteHeader;\n plan: DocumentSyncPlan;\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n update: DocumentSyncResponse[\"updates\"][number];\n}): Promise<void> {\n const { header, plan, update } = input;\n const writerPublicKey = await input.resolveWriterPublicKey({\n writerSigningKeyFingerprint: header.writerKeyFingerprint,\n writerUserId: header.writerUserId,\n });\n if (!writerPublicKey) {\n throw new Error(\"Document sync response writer public key missing\");\n }\n\n const documentAuthorization = await documentWriteAuthorizationForHeader({\n allowMissingAuthorization: isAcceptedOutgoingSyncUpdate(plan, update),\n authorizationTargets: update.authorizationTargets,\n dependencyManifestHashes: header.dependencyManifestHashes,\n contentKeyBundle: input.contentKeyBundle,\n manifestHash: header.accessManifestHash,\n plan,\n targetHash: header.targetHash,\n });\n const verified = await verifyWriteHeader({\n authorizationMembership: \"referenced\",\n expectedAccessManifestHash: documentAuthorization\n ? header.accessManifestHash\n : plan.expectedLinkSetManifestHash,\n expectedObject: {\n objectKind: \"document\",\n objectId: plan.documentId,\n organizationId: plan.organizationId,\n },\n header,\n ...(documentAuthorization ? { documentAuthorization } : {}),\n expectedTargetHash: documentAuthorization\n ? header.targetHash\n : plan.expectedTargetHash,\n writerPublicKey,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n}\n\nfunction assertDocumentSyncCommitCheckpointMatchesPlan(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n if (\n response.commitLsnMode === \"untracked\" &&\n response.commitLsn !== UNTRACKED_COMMIT_LSN\n ) {\n throw new Error(\n \"Document sync response untracked commit LSN must use the 0/0 sentinel\",\n );\n }\n if (\n response.commitLsn === UNTRACKED_COMMIT_LSN &&\n response.commitLsnMode !== \"untracked\"\n ) {\n throw new Error(\n \"Document sync response 0/0 commit LSN must be declared untracked\",\n );\n }\n if (response.commitLsn !== null) {\n parseWalLsn(response.commitLsn, \"Document sync response commit LSN\");\n }\n if (plan.minLsn === undefined) {\n return;\n }\n const minLsn = parseWalLsn(\n plan.minLsn,\n \"Document sync requested minimum LSN\",\n );\n if (response.commitLsn === null) {\n throw new Error(\"Document sync response commit LSN is missing\");\n }\n if (\n !(\n response.commitLsn === UNTRACKED_COMMIT_LSN &&\n response.commitLsnMode === \"untracked\"\n ) &&\n parseWalLsn(response.commitLsn, \"Document sync response commit LSN\") <\n minLsn\n ) {\n throw new Error(\"Document sync response commit LSN is stale\");\n }\n}\n\nfunction documentSyncManifestEpoch(plan: DocumentSyncPlan): number {\n if (!isPlainRecord(plan.documentManifest.state)) {\n throw new Error(\"Document sync manifest state is invalid\");\n }\n\n return readRecordPositiveInteger(\n plan.documentManifest.state,\n \"epoch\",\n \"Document sync manifest state\",\n );\n}\n\n// The one load-bearing epoch check: no returned update may claim an\n// accessEpoch newer than the current manifest epoch.\nfunction assertDocumentSyncAccessEpochsNotInFuture(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): void {\n const currentAccessEpoch = documentSyncManifestEpoch(plan);\n for (const update of response.updates) {\n if (update.accessEpoch > currentAccessEpoch) {\n throw new Error(\"Document sync response includes a future access epoch\");\n }\n }\n}\n\nfunction contentKeyBundleCanonical(\n bundle: DocumentSyncResponse[\"contentKeyBundle\"],\n): string {\n return serializeCanonical(bundle, \"content-key bundle\");\n}\n\nfunction documentSyncContentKeyBundlesByEpoch(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n): ReadonlyMap<number, DocumentSyncResponse[\"contentKeyBundle\"]> {\n if (\n contentKeyBundleCanonical(response.contentKeyBundle) !==\n contentKeyBundleCanonical(plan.sourceContentKeyBundle)\n ) {\n throw new Error(\"Document sync response content-key bundle mismatch\");\n }\n\n const bundleByEpoch = new Map<\n number,\n DocumentSyncResponse[\"contentKeyBundle\"]\n >();\n const bundles = [response.contentKeyBundle, ...response.contentKeyBundles];\n\n for (const bundle of bundles) {\n if (bundle.documentId !== plan.documentId) {\n throw new Error(\n \"Document sync response content-key bundle document mismatch\",\n );\n }\n if (\n !Number.isInteger(bundle.contentKeyEpoch) ||\n bundle.contentKeyEpoch <= 0\n ) {\n throw new Error(\n \"Document sync response content-key bundle epoch mismatch\",\n );\n }\n\n // The current epoch travels only as contentKeyBundle; the array carries\n // each older epoch once.\n if (bundleByEpoch.has(bundle.contentKeyEpoch)) {\n throw new Error(\"Document sync response repeats a content-key epoch\");\n }\n bundleByEpoch.set(bundle.contentKeyEpoch, bundle);\n }\n\n return bundleByEpoch;\n}\n\nasync function persistedDocumentSyncStateFromResponseInternal(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n options: {\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n },\n): Promise<PersistedDocumentSyncState> {\n if (response.documentId !== plan.documentId) {\n throw new Error(\"Document sync response document id mismatch\");\n }\n const contentKeyBundlesByEpoch = documentSyncContentKeyBundlesByEpoch(\n plan,\n response,\n );\n if (\n serializeCanonical(response.documentKekTargets, \"KEK targets\") !==\n serializeCanonical(plan.documentKekTargets, \"KEK targets\")\n ) {\n throw new Error(\"Document sync response KEK target mismatch\");\n }\n assertAcceptedOutgoingUpdateIdsMatchPlan(plan, response);\n assertDocumentSyncCommitCheckpointMatchesPlan(plan, response);\n assertDocumentSyncAccessEpochsNotInFuture(plan, response);\n\n await Promise.all(\n response.updates.map((update) =>\n assertDocumentSyncResponseUpdateMatchesPlan({\n contentKeyBundlesByEpoch,\n plan,\n resolveWriterPublicKey: options.resolveWriterPublicKey,\n update,\n }),\n ),\n );\n\n return serializedPersistedDocumentState({\n contentKeyBundle: response.contentKeyBundle,\n documentId: plan.documentId,\n documentKekTargets: response.documentKekTargets,\n documentManifestBundle: plan.documentManifest,\n });\n}\n\nexport async function persistedDocumentSyncStateFromResponse(\n plan: DocumentSyncPlan,\n response: DocumentSyncResponse,\n options: {\n resolveWriterPublicKey: DocumentWriterPublicKeyResolver;\n },\n): Promise<PersistedDocumentSyncState> {\n try {\n return await persistedDocumentSyncStateFromResponseInternal(\n plan,\n response,\n options,\n );\n } catch (error) {\n if (error instanceof DocumentSyncResponseUpdateContentKeyError) throw error;\n throwKeyingVerificationShapeFailure(error);\n }\n}\n\nexport function isRetryableDocumentSyncConflict(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 409 &&\n failure.code === DOCUMENT_SYNC_ERROR_CODES.stateStale\n );\n}\n\n// The wipe gate is deliberately strict — coded 404s only, which is the right\n// failure mode for a destructive action. A bare 404 proves nothing about the\n// document: proxy/tunnel error pages, deploy-skew route misses, and\n// container-level lookups all produce one.\nexport function isUpstreamDeletedDocumentSyncFailure(\n failure: DocumentSyncSubmitFailure,\n): boolean {\n return (\n failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE\n );\n}\n"]}
@@ -43,6 +43,7 @@ export async function validateAccessManifestCheckpoints(input) {
43
43
  policies: input.policies,
44
44
  authorizationPolicies: input.authorizationPolicies,
45
45
  stillCurrent: input.stillCurrent,
46
+ verifiedBundles: input.verifiedBundles,
46
47
  });
47
48
  }
48
49
  export async function enforceAccessManifestCheckpoints(input) {
@@ -54,6 +55,7 @@ export async function enforceAccessManifestCheckpoints(input) {
54
55
  policies: input.policies,
55
56
  authorizationPolicies: input.authorizationPolicies,
56
57
  stillCurrent: input.stillCurrent,
58
+ verifiedBundles: input.verifiedBundles,
57
59
  });
58
60
  }
59
61
  //# sourceMappingURL=accessManifestCheckpointEnforcement.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"accessManifestCheckpointEnforcement.js","sourceRoot":"","sources":["accessManifestCheckpointEnforcement.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAEL,kCAAkC,EAClC,mCAAmC,GACpC,MAAM,mDAAmD,CAAC;AAI3D,SAAS,SAAS,CAAC,QAAkD;IACnE,MAAM,EAAE,UAAU,EAAE,cAAc,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC,UAAU,CAAC;IACrE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,iBAAiB,CACxB,SAA8D;IAE9D,MAAM,QAAQ,GAAG,IAAI,GAAG,EAGrB,CAAC;IACJ,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;QACjC,MAAM,GAAG,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;QAChC,IAAI,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,GAAG,IAAI,GAAG,EAAE,CAAC;YACnB,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC5B,CAAC;QACD,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,SAAS,gCAAgC,CAAC,KAGzC;I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,KAWtD;IACC,MAAM,kCAAkC,CAAC;QACvC,MAAM,EAAE,gCAAgC,CAAC,KAAK,CAAC;QAC/C,uBAAuB,EAAE,KAAK,CAAC,uBAAuB;QACtD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeCheckpoint } from \"../persistence/documentPurgeCheckpointPersistence\";\nimport {\n type AccessManifestCheckpointAdvance,\n advanceKeyingCheckpointsAtomically,\n validateKeyingCheckpointsAtomically,\n} from \"../persistence/keyingCheckpointAdvancePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\n\nfunction objectKey(manifest: VerifiedAccessManifestCheckpointEvidence): string {\n const { objectKind, organizationId, objectId } = manifest.checkpoint;\n return JSON.stringify([objectKind, organizationId, objectId]);\n}\n\nfunction manifestsByObject(\n manifests: readonly VerifiedAccessManifestCheckpointEvidence[],\n): Map<string, Map<string, VerifiedAccessManifestCheckpointEvidence>> {\n const byObject = new Map<\n string,\n Map<string, VerifiedAccessManifestCheckpointEvidence>\n >();\n for (const manifest of manifests) {\n const key = objectKey(manifest);\n let byHash = byObject.get(key);\n if (!byHash) {\n byHash = new Map();\n byObject.set(key, byHash);\n }\n byHash.set(manifest.manifestHash, manifest);\n }\n return byObject;\n}\n\nfunction accessManifestCheckpointAdvances(input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): AccessManifestCheckpointAdvance[] {\n const evidenceByObject = manifestsByObject(input.verifiedManifests);\n const headsByObject = manifestsByObject(input.verifiedHeads);\n const advances: AccessManifestCheckpointAdvance[] = [];\n\n for (const [key, headsByHash] of headsByObject) {\n if (headsByHash.size !== 1) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares conflicting access manifest heads for ${key}`,\n );\n }\n const head = headsByHash.values().next().value;\n if (!head) {\n continue;\n }\n const predecessors = [\n ...(evidenceByObject.get(key)?.values() ?? []),\n ].filter((manifest) => manifest.manifestHash !== head.manifestHash);\n advances.push({ head, predecessors });\n }\n\n return advances;\n}\n\nexport async function validateAccessManifestCheckpoints(input: {\n readonly execSql: ExecSql;\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): Promise<void> {\n await validateKeyingCheckpointsAtomically({\n access: accessManifestCheckpointAdvances(input),\n execSql: input.execSql,\n policies: input.policies,\n authorizationPolicies: input.authorizationPolicies,\n stillCurrent: input.stillCurrent,\n });\n}\n\nexport async function enforceAccessManifestCheckpoints(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): Promise<void> {\n await advanceKeyingCheckpointsAtomically({\n access: accessManifestCheckpointAdvances(input),\n documentPurgeCheckpoint: input.documentPurgeCheckpoint,\n execSql: input.execSql,\n organizationId: input.organizationId,\n policies: input.policies,\n authorizationPolicies: input.authorizationPolicies,\n stillCurrent: input.stillCurrent,\n });\n}\n"]}
1
+ {"version":3,"file":"accessManifestCheckpointEnforcement.js","sourceRoot":"","sources":["accessManifestCheckpointEnforcement.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAEL,kCAAkC,EAClC,mCAAmC,GACpC,MAAM,mDAAmD,CAAC;AAK3D,SAAS,SAAS,CAAC,QAAkD;IACnE,MAAM,EAAE,UAAU,EAAE,cAAc,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC,UAAU,CAAC;IACrE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,iBAAiB,CACxB,SAA8D;IAE9D,MAAM,QAAQ,GAAG,IAAI,GAAG,EAGrB,CAAC;IACJ,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;QACjC,MAAM,GAAG,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;QAChC,IAAI,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,GAAG,IAAI,GAAG,EAAE,CAAC;YACnB,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC5B,CAAC;QACD,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,SAAS,gCAAgC,CAAC,KAGzC;IACC,MAAM,gBAAgB,GAAG,iBAAiB,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;IACpE,MAAM,aAAa,GAAG,iBAAiB,CAAC,KAAK,CAAC,aAAa,CAAC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AAE,KAAK,CAAC,uBAAuB;QACtD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,eAAe,EAAE,KAAK,CAAC,eAAe;KACvC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeCheckpoint } from \"../persistence/documentPurgeCheckpointPersistence\";\nimport {\n type AccessManifestCheckpointAdvance,\n advanceKeyingCheckpointsAtomically,\n validateKeyingCheckpointsAtomically,\n} from \"../persistence/keyingCheckpointAdvancePersistence\";\nimport type { VerifiedManifestBundle } from \"../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\n\nfunction objectKey(manifest: VerifiedAccessManifestCheckpointEvidence): string {\n const { objectKind, organizationId, objectId } = manifest.checkpoint;\n return JSON.stringify([objectKind, organizationId, objectId]);\n}\n\nfunction manifestsByObject(\n manifests: readonly VerifiedAccessManifestCheckpointEvidence[],\n): Map<string, Map<string, VerifiedAccessManifestCheckpointEvidence>> {\n const byObject = new Map<\n string,\n Map<string, VerifiedAccessManifestCheckpointEvidence>\n >();\n for (const manifest of manifests) {\n const key = objectKey(manifest);\n let byHash = byObject.get(key);\n if (!byHash) {\n byHash = new Map();\n byObject.set(key, byHash);\n }\n byHash.set(manifest.manifestHash, manifest);\n }\n return byObject;\n}\n\nfunction accessManifestCheckpointAdvances(input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): AccessManifestCheckpointAdvance[] {\n const evidenceByObject = manifestsByObject(input.verifiedManifests);\n const headsByObject = manifestsByObject(input.verifiedHeads);\n const advances: AccessManifestCheckpointAdvance[] = [];\n\n for (const [key, headsByHash] of headsByObject) {\n if (headsByHash.size !== 1) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares conflicting access manifest heads for ${key}`,\n );\n }\n const head = headsByHash.values().next().value;\n if (!head) {\n continue;\n }\n const predecessors = [\n ...(evidenceByObject.get(key)?.values() ?? []),\n ].filter((manifest) => manifest.manifestHash !== head.manifestHash);\n advances.push({ head, predecessors });\n }\n\n return advances;\n}\n\nexport async function validateAccessManifestCheckpoints(input: {\n readonly execSql: ExecSql;\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): Promise<void> {\n await validateKeyingCheckpointsAtomically({\n access: accessManifestCheckpointAdvances(input),\n execSql: input.execSql,\n policies: input.policies,\n authorizationPolicies: input.authorizationPolicies,\n stillCurrent: input.stillCurrent,\n verifiedBundles: input.verifiedBundles,\n });\n}\n\nexport async function enforceAccessManifestCheckpoints(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): Promise<void> {\n await advanceKeyingCheckpointsAtomically({\n access: accessManifestCheckpointAdvances(input),\n documentPurgeCheckpoint: input.documentPurgeCheckpoint,\n execSql: input.execSql,\n organizationId: input.organizationId,\n policies: input.policies,\n authorizationPolicies: input.authorizationPolicies,\n stillCurrent: input.stillCurrent,\n verifiedBundles: input.verifiedBundles,\n });\n}\n"]}
@@ -1,5 +1,7 @@
1
1
  import { type AccessManifestCheckpoint, type VerifiedAccessManifestCheckpointEvidence, type VerifiedContainerAccessManifest, type VerifiedPrincipalPolicySelection } from "../../internal/crypto/index.js";
2
+ import type { AccessManifestBundleWireResponse } from "../../internal/validators/response/index.js";
2
3
  import type { DocumentPurgeCheckpoint } from "../persistence/documentPurgeCheckpointPersistence.js";
4
+ import type { VerifiedManifestBundle } from "../persistence/verifiedManifestBundlePersistence.js";
3
5
  import type { PrincipalPolicyCheckpointEvidence } from "../principals/principalPolicyEvidence.js";
4
6
  import type { ExecSql } from "../sqlite/sqlSchema.js";
5
7
  export interface ProjectionCheckpointContext {
@@ -9,6 +11,7 @@ export interface ProjectionCheckpointContext {
9
11
  organizationId?: string | undefined;
10
12
  readonly policies: PrincipalPolicyCheckpointEvidence[];
11
13
  readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];
14
+ readonly verifiedBundles: VerifiedManifestBundle[];
12
15
  readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];
13
16
  readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];
14
17
  }
@@ -20,6 +23,15 @@ export declare function observeAccessManifestCheckpoints(context: ProjectionChec
20
23
  readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];
21
24
  readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];
22
25
  }): void;
26
+ /**
27
+ * Records each served bundle whose manifest this verification produced, so
28
+ * the transaction finalizing the checkpoints also stores it for later
29
+ * citation. A bundle the projection carried but verification never reached
30
+ * is skipped.
31
+ */
32
+ export declare function observeVerifiedProjectionBundles(context: ProjectionCheckpointContext, bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>, verifiedByHash: ReadonlyMap<string, {
33
+ readonly checkpoint: AccessManifestCheckpoint;
34
+ }>): void;
23
35
  export declare function observePrincipalPolicy(context: ProjectionCheckpointContext, policy: PrincipalPolicyCheckpointEvidence, organizationId?: string | undefined): void;
24
36
  export declare function commitProjectionCheckpoints(context: ProjectionCheckpointContext, input?: {
25
37
  readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;
@@ -16,6 +16,7 @@ export function createProjectionCheckpointContext(input) {
16
16
  organizationId: input.organizationId,
17
17
  policies: [],
18
18
  authorizationPolicies: [],
19
+ verifiedBundles: [],
19
20
  verifiedHeads: [],
20
21
  verifiedManifests: [],
21
22
  };
@@ -24,6 +25,19 @@ export function observeAccessManifestCheckpoints(context, input) {
24
25
  context.verifiedHeads.push(...input.verifiedHeads);
25
26
  context.verifiedManifests.push(...input.verifiedManifests);
26
27
  }
28
+ /**
29
+ * Records each served bundle whose manifest this verification produced, so
30
+ * the transaction finalizing the checkpoints also stores it for later
31
+ * citation. A bundle the projection carried but verification never reached
32
+ * is skipped.
33
+ */
34
+ export function observeVerifiedProjectionBundles(context, bundlesByHash, verifiedByHash) {
35
+ for (const [manifestHash, bundle] of bundlesByHash) {
36
+ const verified = verifiedByHash.get(manifestHash);
37
+ if (verified)
38
+ context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });
39
+ }
40
+ }
27
41
  export function observePrincipalPolicy(context, policy, organizationId) {
28
42
  if (organizationId !== undefined &&
29
43
  context.organizationId !== undefined &&
@@ -46,6 +60,7 @@ export async function commitProjectionCheckpoints(context, input) {
46
60
  policies: context.policies,
47
61
  authorizationPolicies: context.authorizationPolicies,
48
62
  stillCurrent: input?.stillCurrent,
63
+ verifiedBundles: context.verifiedBundles,
49
64
  verifiedHeads: context.verifiedHeads,
50
65
  verifiedManifests: context.verifiedManifests,
51
66
  }).catch((error) => {
@@ -67,6 +82,7 @@ async function validateProjectionCheckpoints(context, input) {
67
82
  policies: context.policies,
68
83
  authorizationPolicies: context.authorizationPolicies,
69
84
  stillCurrent: input?.stillCurrent,
85
+ verifiedBundles: context.verifiedBundles,
70
86
  verifiedHeads: context.verifiedHeads,
71
87
  verifiedManifests: context.verifiedManifests,
72
88
  }).catch((error) => {
@@ -1 +1 @@
1
- {"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,8BAA8B,EAAE,MAAM,yCAAyC,CAAC;AAEzF,OAAO,EAAE,gDAAgD,EAAE,MAAM,kDAAkD,CAAC;AAGpH,OAAO,EACL,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,oCAAoC,EAAE,MAAM,yBAAyB,CAAC;AAC/E,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,mCAAmC,EAAE,MAAM,SAAS,CAAC;AAc9D,MAAM,UAAU,iCAAiC,CAAC,KAGjD;IACC,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACxC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,oEAAoE,CACrE,CAAC;IACJ,CAAC;IAED,OAAO;QACL,kBAAkB,EAAE,EAAE;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,gBAAgB,EAAE,IAAI,GAAG,EAAE;QAC3B,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,EAAE;QACZ,qBAAqB,EAAE,EAAE;QACzB,aAAa,EAAE,EAAE;QACjB,iBAAiB,EAAE,EAAE;KACtB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,OAAoC,EACpC,KAGC;IAED,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,KAA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AO,CAAC,cAAc;QACtB,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport { rememberVerifiedContainerHeads } from \"../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../persistence/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../persistence/principalAuthorizationCheckpoints\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { ProjectionDependencyUnavailableError } from \"./dependencyUnavailable\";\nimport { projectionLifetimeGuard } from \"./projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"./types\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
1
+ {"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,8BAA8B,EAAE,MAAM,yCAAyC,CAAC;AAEzF,OAAO,EAAE,gDAAgD,EAAE,MAAM,kDAAkD,CAAC;AAIpH,OAAO,EACL,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,oCAAoC,EAAE,MAAM,yBAAyB,CAAC;AAC/E,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,mCAAmC,EAAE,MAAM,SAAS,CAAC;AAgB9D,MAAM,UAAU,iCAAiC,CAAC,KAGjD;IACC,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACxC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,oEAAoE,CACrE,CAAC;IACJ,CAAC;IAED,OAAO;QACL,kBAAkB,EAAE,EAAE;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,gBAAgB,EAAE,IAAI,GAAG,EAAE;QAC3B,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,EAAE;QACZ,qBAAqB,EAAE,EAAE;QACzB,eAAe,EAAE,EAAE;QACnB,aAAa,EAAE,EAAE;QACjB,iBAAiB,EAAE,EAAE;KACtB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,OAAoC,EACpC,KAGC;IAED,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,aAAa,CAAC,CAAC;IACnD,OAAO,CAAC,iBAAiB,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,iBAAiB,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;GAKG;AAC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AAoC,EACpC,KAIC;IAED,IAAI,KAAK,CAAC,8BAA8B,KAAK,KAAK,EAAE,CAAC;QACnD,MAAM,6BAA6B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACpD,OAAO;IACT,CAAC;IACD,MAAM,2BAA2B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAClD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO;IAC7C,MAAM,cAAc,GAClB,OAAO,CAAC,cAAc;QACtB,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport { rememberVerifiedContainerHeads } from \"../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../persistence/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../persistence/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { ProjectionDependencyUnavailableError } from \"./dependencyUnavailable\";\nimport { projectionLifetimeGuard } from \"./projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"./types\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n if (verified)\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, } from "./checkpointContext.js";
1
+ import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeVerifiedProjectionBundles, } from "./checkpointContext.js";
2
2
  import { verifyContainerManifestPath } from "./containerPathVerification.js";
3
3
  import { addContainerWriterProjectionBundles } from "./containerProjectionVerification.js";
4
4
  import { verifyProjectionAuthorizationEvidence } from "./projectionAuthorizationEvidence.js";
@@ -39,6 +39,8 @@ export async function verifyContainerDestinationProjection(input) {
39
39
  verifiedByHash,
40
40
  });
41
41
  const current = projectionLifetimeGuard(checkpointContext, input.stillCurrent);
42
+ // Authenticated bytes, not authority: a later read may cite them.
43
+ observeVerifiedProjectionBundles(checkpointContext, bundlesByHash, verifiedByHash);
42
44
  await finalizeProjectionCheckpoints(checkpointContext, {
43
45
  stillCurrent: current,
44
46
  persistVerificationCheckpoints: false,
@@ -1 +1 @@
1
- {"version":3,"file":"containerDestinationVerification.js","sourceRoot":"","sources":["containerDestinationVerification.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,iCAAiC,EACjC,6BAA6B,GAC9B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AACxF,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAC1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAKhE,OAAO,EAAE,mCAAmC,EAAE,MAAM,SAAS,CAAC;AAE9D,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAQ1D;IAKC,MAAM,aAAa,GAAG,IAAI,GAAG,EAA4C,CAAC;IAC1E,mCAAmC,CACjC,aAAa,EACb,KAAK,CAAC,UAAU,EAChB,uBAAuB,CACxB,CAAC;IACF,MAAM,cAAc,GAAG,IAAI,GAAG,EAA2C,CAAC;IAC1E,MAAM,iBAAiB,GAAG,iCAAiC,CAAC;QAC1D,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,UAAU,CAAC,cAAc;KAChD,CAAC,CAAC;IACH,MAAM,oBAAoB,GAAG,IAAI,GAAG,EAAE,CAAC;IACvC,MAAM,qBAAqB,GAAG,MAAM,qCAAqC,CAAC;QACxE,OAAO,EAAE,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC;QACpC,iBAAiB;QACjB,cAAc,EAAE,KAAK,CAAC,UAAU,CAAC,cAAc;QAC/C,cAAc,EAAE,KAAK,CAAC,UAAU,CAAC,cAAc;QAC/C,oBAAoB;QACpB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,MAAM,2BAA2B,CAAC;QAC7C,qBAAqB;QACrB,4BAA4B,EAAE,IAAI;QAClC,uBAAuB,EAAE,YAAY;QACrC,aAAa;QACb,iBAAiB;QACjB,uBAAuB,EAAE,KAAK;QAC9B,eAAe,EAAE,KAAK;QACtB,KAAK,EAAE,uBAAuB;QAC9B,IAAI,EAAE,KAAK,CAAC,UAAU,CAAC,IAAI;QAC3B,oBAAoB;QACpB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,cAAc;KACf,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,uBAAuB,CACrC,iBAAiB,EACjB,KAAK,CAAC,YAAY,CACnB,CAAC;IACF,MAAM,6BAA6B,CAAC,iBAAiB,EAAE;QACrD,YAAY,EAAE,OAAO;QACrB,8BAA8B,EAAE,KAAK;KACtC,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAClC,CAAC","sourcesContent":["import type { VerifiedContainerAccessManifest } from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n} from \"./checkpointContext\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\nimport { addContainerWriterProjectionBundles } from \"./containerProjectionVerification\";\nimport { verifyProjectionAuthorizationEvidence } from \"./projectionAuthorizationEvidence\";\nimport { projectionLifetimeGuard } from \"./projectionLifetimes\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nimport { assertProjectionVerificationCurrent } from \"./types\";\n\n/** Authenticate immutable destination roles without advancing write-authority pins. */\nexport async function verifyContainerDestinationProjection(input: {\n readonly execSql: ExecSql;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<{\n readonly path: VerifiedContainerAccessManifest[];\n /** Every manifest verified on the way, including each head's lineage. */\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n input.projection,\n \"Container destination\",\n );\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const principalPolicyCache = new Map();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [...bundlesByHash.values()],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const path = await verifyContainerManifestPath({\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext,\n enforceLocalCheckpoints: false,\n servedAsCurrent: false,\n label: \"Container destination\",\n path: input.projection.path,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n });\n const current = projectionLifetimeGuard(\n checkpointContext,\n input.stillCurrent,\n );\n await finalizeProjectionCheckpoints(checkpointContext, {\n stillCurrent: current,\n persistVerificationCheckpoints: false,\n });\n assertProjectionVerificationCurrent(current);\n return { path, verifiedByHash };\n}\n"]}
1
+ {"version":3,"file":"containerDestinationVerification.js","sourceRoot":"","sources":["containerDestinationVerification.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,GACjC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AACxF,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAC1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAKhE,OAAO,EAAE,mCAAmC,EAAE,MAAM,SAAS,CAAC;AAE9D,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAQ1D;IAKC,MAAM,aAAa,GAAG,IAAI,GAAG,EAA4C,CAAC;IAC1E,mCAAmC,CACjC,aAAa,EACb,KAAK,CAAC,UAAU,EAChB,uBAAuB,CACxB,CAAC;IACF,MAAM,cAAc,GAAG,IAAI,GAAG,EAA2C,CAAC;IAC1E,MAAM,iBAAiB,GAAG,iCAAiC,CAAC;QAC1D,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,UAAU,CAAC,cAAc;KAChD,CAAC,CAAC;IACH,MAAM,oBAAoB,GAAG,IAAI,GAAG,EAAE,CAAC;IACvC,MAAM,qBAAqB,GAAG,MAAM,qCAAqC,CAAC;QACxE,OAAO,EAAE,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC;QACpC,iBAAiB;QACjB,cAAc,EAAE,KAAK,CAAC,UAAU,CAAC,cAAc;QAC/C,cAAc,EAAE,KAAK,CAAC,UAAU,CAAC,cAAc;QAC/C,oBAAoB;QACpB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,MAAM,2BAA2B,CAAC;QAC7C,qBAAqB;QACrB,4BAA4B,EAAE,IAAI;QAClC,uBAAuB,EAAE,YAAY;QACrC,aAAa;QACb,iBAAiB;QACjB,uBAAuB,EAAE,KAAK;QAC9B,eAAe,EAAE,KAAK;QACtB,KAAK,EAAE,uBAAuB;QAC9B,IAAI,EAAE,KAAK,CAAC,UAAU,CAAC,IAAI;QAC3B,oBAAoB;QACpB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,cAAc;KACf,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,uBAAuB,CACrC,iBAAiB,EACjB,KAAK,CAAC,YAAY,CACnB,CAAC;IACF,kEAAkE;IAClE,gCAAgC,CAC9B,iBAAiB,EACjB,aAAa,EACb,cAAc,CACf,CAAC;IACF,MAAM,6BAA6B,CAAC,iBAAiB,EAAE;QACrD,YAAY,EAAE,OAAO;QACrB,8BAA8B,EAAE,KAAK;KACtC,CAAC,CAAC;IACH,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;AAClC,CAAC","sourcesContent":["import type { VerifiedContainerAccessManifest } from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeVerifiedProjectionBundles,\n} from \"./checkpointContext\";\nimport { verifyContainerManifestPath } from \"./containerPathVerification\";\nimport { addContainerWriterProjectionBundles } from \"./containerProjectionVerification\";\nimport { verifyProjectionAuthorizationEvidence } from \"./projectionAuthorizationEvidence\";\nimport { projectionLifetimeGuard } from \"./projectionLifetimes\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nimport { assertProjectionVerificationCurrent } from \"./types\";\n\n/** Authenticate immutable destination roles without advancing write-authority pins. */\nexport async function verifyContainerDestinationProjection(input: {\n readonly execSql: ExecSql;\n readonly projection: ContainerWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<{\n readonly path: VerifiedContainerAccessManifest[];\n /** Every manifest verified on the way, including each head's lineage. */\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n addContainerWriterProjectionBundles(\n bundlesByHash,\n input.projection,\n \"Container destination\",\n );\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.projection.organizationId,\n });\n const principalPolicyCache = new Map();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [...bundlesByHash.values()],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: input.projection.organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const path = await verifyContainerManifestPath({\n authorizationEvidence,\n requireAuthorizationEvidence: true,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext,\n enforceLocalCheckpoints: false,\n servedAsCurrent: false,\n label: \"Container destination\",\n path: input.projection.path,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n });\n const current = projectionLifetimeGuard(\n checkpointContext,\n input.stillCurrent,\n );\n // Authenticated bytes, not authority: a later read may cite them.\n observeVerifiedProjectionBundles(\n checkpointContext,\n bundlesByHash,\n verifiedByHash,\n );\n await finalizeProjectionCheckpoints(checkpointContext, {\n stillCurrent: current,\n persistVerificationCheckpoints: false,\n });\n assertProjectionVerificationCurrent(current);\n return { path, verifiedByHash };\n}\n"]}
@@ -1,7 +1,6 @@
1
- import { retainVerifiedProjectionHistory } from "../../internal/api-client/index.js";
2
1
  import { computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, toFingerprint, verifyContainerKekState, } from "../../internal/crypto/index.js";
3
2
  import { addBundleByHash } from "./bundleVerification.js";
4
- import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeAccessManifestCheckpoints, } from "./checkpointContext.js";
3
+ import { createProjectionCheckpointContext, finalizeProjectionCheckpoints, observeAccessManifestCheckpoints, observeVerifiedProjectionBundles, } from "./checkpointContext.js";
5
4
  import { verifyContainerManifestBundle } from "./containerManifestVerification.js";
6
5
  import { verifyContainerManifestPath } from "./containerPathVerification.js";
7
6
  import { ProjectionDependencyUnavailableError } from "./dependencyUnavailable.js";
@@ -173,16 +172,21 @@ export async function verifyContainerWriterProjectionWithContext(input, checkpoi
173
172
  export async function verifyContainerWriterProjection(input) {
174
173
  try {
175
174
  assertProjectionVerificationCurrent(input.stillCurrent);
176
- const guardedInput = withGenerationGuardedPolicyWarmer(input);
175
+ const verifiedByHash = input.verifiedByHash ??
176
+ new Map();
177
+ const guardedInput = {
178
+ ...withGenerationGuardedPolicyWarmer(input),
179
+ verifiedByHash,
180
+ };
177
181
  const checkpointContext = createProjectionCheckpointContext({
178
182
  execSql: input.execSql,
179
183
  organizationId: input.projection.organizationId,
180
184
  });
181
185
  const verifiedPath = await verifyContainerWriterProjectionWithContext(guardedInput, checkpointContext);
182
186
  assertProjectionVerificationCurrent(input.stillCurrent);
187
+ observeVerifiedProjectionBundles(checkpointContext, collectContainerProjectionBundles(input.projection), verifiedByHash);
183
188
  await finalizeProjectionCheckpoints(checkpointContext, input);
184
189
  assertProjectionVerificationCurrent(input.stillCurrent);
185
- retainVerifiedProjectionHistory(input.projection);
186
190
  return verifiedPath;
187
191
  }
188
192
  catch (error) {
@@ -194,6 +198,8 @@ export async function collectContainerWriterProjectionPrincipalPolicies(input) {
194
198
  assertProjectionVerificationCurrent(input.stillCurrent);
195
199
  const warmReferencedPrincipalPolicies = generationGuardedPrincipalPolicyWarmer(input.warmReferencedPrincipalPolicies, input.stillCurrent);
196
200
  const principalPolicyCache = input.principalPolicyCache ?? new Map();
201
+ const verifiedByHash = input.verifiedByHash ??
202
+ new Map();
197
203
  const checkpointContext = createProjectionCheckpointContext({
198
204
  execSql: input.execSql,
199
205
  organizationId: input.projection.organizationId,
@@ -201,7 +207,7 @@ export async function collectContainerWriterProjectionPrincipalPolicies(input) {
201
207
  const verifiedPath = await verifyContainerWriterProjectionWithContext({
202
208
  principalPolicyCache,
203
209
  projection: input.projection,
204
- verifiedByHash: input.verifiedByHash,
210
+ verifiedByHash,
205
211
  resolveUserKey: input.resolveUserKey,
206
212
  warmReferencedPrincipalPolicies,
207
213
  }, checkpointContext);
@@ -215,9 +221,9 @@ export async function collectContainerWriterProjectionPrincipalPolicies(input) {
215
221
  warmReferencedPrincipalPolicies,
216
222
  });
217
223
  assertProjectionVerificationCurrent(input.stillCurrent);
224
+ observeVerifiedProjectionBundles(checkpointContext, collectContainerProjectionBundles(input.projection), verifiedByHash);
218
225
  await finalizeProjectionCheckpoints(checkpointContext, input);
219
226
  assertProjectionVerificationCurrent(input.stillCurrent);
220
- retainVerifiedProjectionHistory(input.projection);
221
227
  return policies;
222
228
  }
223
229
  catch (error) {