@tearleads/client-sdk 0.1.246 → 0.1.248

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 (71) hide show
  1. package/Tearleads.js +4 -2
  2. package/Tearleads.js.map +1 -1
  3. package/data/persistence/principalPolicy/heldOrganizationDirectories.js +53 -0
  4. package/data/persistence/principalPolicy/heldOrganizationDirectories.js.map +1 -0
  5. package/data/persistence/verifiedManifestBundlePersistence.d.ts +8 -3
  6. package/data/persistence/verifiedManifestBundlePersistence.js +34 -15
  7. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  8. package/internal/api-client/ApiClient.d.ts +2 -0
  9. package/internal/api-client/client/session.d.ts +2 -0
  10. package/internal/api-client/heldDirectoryCitations.d.ts +19 -0
  11. package/internal/api-client/heldDirectoryCitations.js +37 -0
  12. package/internal/api-client/heldDirectoryCitations.js.map +1 -0
  13. package/internal/api-client/index.d.ts +1 -1
  14. package/internal/api-client/index.js.map +1 -1
  15. package/internal/api-client/verifiedManifestCitations.d.ts +16 -6
  16. package/internal/api-client/verifiedManifestCitations.js +32 -13
  17. package/internal/api-client/verifiedManifestCitations.js.map +1 -1
  18. package/internal/api-client/writerProjectionRequests.js +5 -3
  19. package/internal/api-client/writerProjectionRequests.js.map +1 -1
  20. package/internal/validators/knownManifestsRefinements.js +1 -1
  21. package/internal/validators/knownManifestsRefinements.js.map +1 -1
  22. package/internal/validators/operation/auth.d.ts +14 -0
  23. package/internal/validators/operation/auth.js +2 -1
  24. package/internal/validators/operation/auth.js.map +1 -1
  25. package/internal/validators/operation/writerProjections.d.ts +11 -11
  26. package/internal/validators/operation/writerProjections.js +1 -1
  27. package/internal/validators/operation/writerProjections.js.map +1 -1
  28. package/internal/validators/response/areas/auth.d.ts +1 -1
  29. package/internal/validators/response/areas/auth.js +1 -1
  30. package/internal/validators/response/areas/auth.js.map +1 -1
  31. package/internal/validators/response/areas/principals.d.ts +2 -1
  32. package/internal/validators/response/areas/principals.js +1 -1
  33. package/internal/validators/response/areas/principals.js.map +1 -1
  34. package/internal/validators/response/container.d.ts +4 -4
  35. package/internal/validators/response/container.js +2 -2
  36. package/internal/validators/response/container.js.map +1 -1
  37. package/internal/validators/response/documentMutation.d.ts +4 -4
  38. package/internal/validators/response/documentMutation.js +2 -2
  39. package/internal/validators/response/documentMutation.js.map +1 -1
  40. package/internal/validators/response/documentSyncSchema.d.ts +5 -0
  41. package/internal/validators/response/documentSyncSchema.js +1 -1
  42. package/internal/validators/response/documentSyncSchema.js.map +1 -1
  43. package/internal/validators/response/policyEvidenceWire.d.ts +17 -0
  44. package/internal/validators/response/policyEvidenceWire.js +36 -0
  45. package/internal/validators/response/policyEvidenceWire.js.map +1 -0
  46. package/internal/validators/response/projectionPolicyEvidence.d.ts +175 -0
  47. package/internal/validators/response/projectionPolicyEvidence.js +13 -0
  48. package/internal/validators/response/projectionPolicyEvidence.js.map +1 -1
  49. package/internal/validators/response/registration.d.ts +17 -1
  50. package/internal/validators/response/registration.js +31 -2
  51. package/internal/validators/response/registration.js.map +1 -1
  52. package/internal/validators/response/writerProjectionWire.d.ts +11 -7
  53. package/internal/validators/response/writerProjectionWire.js +19 -10
  54. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  55. package/internal/validators/util/index.d.ts +1 -1
  56. package/internal/validators/util/index.js +1 -1
  57. package/internal/validators/util/index.js.map +1 -1
  58. package/internal/validators/util/knownManifestWire.d.ts +9 -3
  59. package/internal/validators/util/knownManifestWire.js +24 -8
  60. package/internal/validators/util/knownManifestWire.js.map +1 -1
  61. package/package.json +1 -1
  62. package/workflows/registration/organizationCreation/createOrganization.js +3 -0
  63. package/workflows/registration/organizationCreation/createOrganization.js.map +1 -1
  64. package/workflows/registration/organizationProvisioningPersistence.d.ts +7 -0
  65. package/workflows/registration/organizationProvisioningPersistence.js +1 -0
  66. package/workflows/registration/organizationProvisioningPersistence.js.map +1 -1
  67. package/workflows/registration/persistRegistrationBootstrap.d.ts +7 -0
  68. package/workflows/registration/persistRegistrationBootstrap.js +6 -2
  69. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  70. package/workflows/registration/registerIdentity.js +1 -0
  71. package/workflows/registration/registerIdentity.js.map +1 -1
package/Tearleads.js CHANGED
@@ -17,6 +17,7 @@ import { createRuntime, } from "./client/runtime/workflowRuntime.js";
17
17
  import { createSecurityIncidentService, } from "./client/securityIncidents/index.js";
18
18
  import { createSession } from "./client/session/index.js";
19
19
  import { resolveDocumentProjectorRegistry, } from "./data/documents/documentKinds.js";
20
+ import { heldDirectoryCitations } from "./data/persistence/principalPolicy/heldOrganizationDirectories.js";
20
21
  import { createVerifiedManifestCitations } from "./data/persistence/verifiedManifestBundlePersistence.js";
21
22
  import { createDomainScope } from "./data/shared/domainScope.js";
22
23
  import { createListenerSet } from "./data/shared/listenerSet.js";
@@ -171,8 +172,9 @@ export class Tearleads {
171
172
  this.boundUserId = (signingKeyFingerprint) => runtime.boundUserId(signingKeyFingerprint);
172
173
  }
173
174
  configureApiClientCallbacks() {
174
- // Projection reads cite bundles this identity's database already verified.
175
- this.apiClient.setVerifiedManifestCitations(createVerifiedManifestCitations(() => this.database.execSql));
175
+ // Projection reads cite bundles this identity's database already
176
+ // verified, and the organization directories its policy bundles hold.
177
+ this.apiClient.setVerifiedManifestCitations(createVerifiedManifestCitations(() => this.database.execSql, heldDirectoryCitations));
176
178
  this.apiClient.setOnError((message) => this.logError(message));
177
179
  // An authoritative host source owns connectivity. Without one, request
178
180
  // outcomes remain reachability hints. Browser and native app bindings both
package/Tearleads.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Tearleads.js","sourceRoot":"","sources":["Tearleads.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EAET,iBAAiB,EACjB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAEL,uBAAuB,GACxB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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 {\n ApiClient,\n type ApiNetworkFailureDetails,\n ApiRequestMetrics,\n createApiReachabilityProbe,\n openServerEventsSocket,\n} from \"@tearleads/api-client\";\nimport { Blobs } from \"./client/blobs\";\nimport {\n type ContainerContents,\n createContainerContents,\n} from \"./client/containerContents\";\nimport { createDeviceFirst, type DeviceFirst } from \"./client/deviceFirst\";\nimport { createDocuments, type Documents } from \"./client/documents\";\nimport { logErrorToConsole } from \"./client/host/logger\";\nimport { createIdentity, type Identity } from \"./client/identity\";\nimport {\n createUserIdentities,\n type UserIdentities,\n} from \"./client/identity/userIdentities\";\nimport {\n createOrganizations,\n type Organizations,\n} from \"./client/organizations\";\nimport { createRoot, type Root, rootRuntimeOf } from \"./client/root\";\nimport { ApiVersion } from \"./client/runtime/apiVersion\";\nimport { Database } from \"./client/runtime/database\";\nimport { Events } from \"./client/runtime/events\";\nimport { Network } from \"./client/runtime/network\";\nimport { SyncBillingGate } from \"./client/runtime/syncBillingGate\";\nimport {\n createRuntime,\n type InternalRuntime,\n type Runtime,\n} from \"./client/runtime/workflowRuntime\";\nimport {\n createSecurityIncidentService,\n type SecurityIncidents,\n} from \"./client/securityIncidents\";\nimport { createSession } from \"./client/session\";\nimport type { Session } from \"./client/session/sessionTypes\";\nimport {\n type DocumentProjectorRegistry,\n resolveDocumentProjectorRegistry,\n} from \"./data/documents/documentKinds\";\nimport { createVerifiedManifestCitations } from \"./data/persistence/verifiedManifestBundlePersistence\";\nimport { createDomainScope, type DomainScope } from \"./data/shared/domainScope\";\nimport { createListenerSet } from \"./data/shared/listenerSet\";\nimport type { SecurityIncidentReporter } from \"./data/shared/securityIncidents\";\nimport { disposeDomainSyncCoordinator } from \"./data/sync/syncCoordinator\";\nimport { resolveIdentityTrustDomain } from \"./data/trustedUserIdentity\";\nimport type { TearleadsOptions } from \"./TearleadsOptions\";\n\nexport class Tearleads {\n readonly apiVersion = new ApiVersion();\n private readonly apiNetworkFailures =\n createListenerSet<[ApiNetworkFailureDetails]>();\n /**\n * Every API request that got no response (plain cancellations excluded),\n * with the transport's secret-free details; hosts forward them to\n * diagnostics. Returns the unsubscribe handle.\n */\n readonly subscribeApiNetworkFailures = (\n listener: (details: ApiNetworkFailureDetails) => void,\n ): (() => void) => this.apiNetworkFailures.subscribe(listener);\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 primeProvisionedState: InternalRuntime[\"primeProvisionedState\"] =\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: TearleadsOptions = {}) {\n const apiBaseUrl = options.apiBaseUrl ?? \"\";\n this.apiRequests = options.apiRequestMetrics ?? new ApiRequestMetrics();\n this.apiClient = this.createApiClient(\n apiBaseUrl,\n options.probeApiNetworkFailures === true,\n );\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 identityTrustDomain = resolveIdentityTrustDomain({\n apiBaseUrl,\n identityTrustDomain: options.identityTrustDomain,\n });\n const security = this.createSecurityIncidents(identityTrustDomain, options);\n this.securityIncidents = security.incidents;\n this.disposeSecurityIncidents = security.dispose;\n this.network = new Network(options.online);\n this.syncBillingGate = new SyncBillingGate();\n let session: Session | null = null;\n this.identity = createIdentity(options.identity, this.blobs, this.log, {\n assertReadyForGeneration: () => {\n if (this.database.status !== \"ready\") {\n throw new Error(\n \"identity.generate requires a ready SQLite database.\",\n );\n }\n },\n bootstrapLocalRootContainer: async (isCurrent) => {\n if (!session) {\n throw new Error(\"identity.generate requires an initialized session.\");\n }\n\n return session.bootstrapLocalRootContainer(isCurrent);\n },\n getUserId: () => session?.userId ?? null,\n });\n session = this.createClientSession(\n options,\n security.report,\n identityTrustDomain,\n );\n this.session = session;\n const runtime = this.createWorkflowRuntime(\n identityTrustDomain,\n options,\n security.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(\n runtime,\n this.containerContents,\n () => this.deviceFirst.open().reconciler,\n );\n this.root = createRoot(rootRuntimeOf(runtime, this.session));\n this.userIdentities = createUserIdentities({\n getOrganizationId: () => this.session.organizationId,\n reportSecurityIncident: security.report,\n identityLinks: runtime.identityLinks,\n });\n\n this.configureApiClientCallbacks();\n\n if (options.identityProvisioning === \"auto\") {\n this.startAutomaticIdentityProvisioning();\n }\n }\n\n /** Durable incident records in this database, reported to the host's listener. */\n private createSecurityIncidents(\n trustDomain: string | null,\n options: TearleadsOptions,\n ) {\n return createSecurityIncidentService({\n database: this.database,\n logError: this.logError,\n onIncident: options.onSecurityIncident,\n trustDomain,\n });\n }\n\n /** Trust callbacks reach the workflow runtime, which is created later. */\n private createClientSession(\n options: TearleadsOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n identityTrustDomain: string | null,\n ): Session {\n return createSession({\n identityTrustDomain,\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 primeProvisionedState: (input) => this.primeProvisionedState(input),\n provisionedSystemContainers: options.provisionedSystemContainers,\n reportSecurityIncident,\n });\n }\n\n private createApiClient(\n apiBaseUrl: string,\n probeNetworkFailures: boolean,\n ): ApiClient {\n return new ApiClient(apiBaseUrl, {\n metrics: this.apiRequests,\n getIdentity: () => this.identity.signingFingerprint,\n // A native source beats a WebView's navigator.onLine (Android misreports it).\n isOnline: () => this.network.authoritativeOnline,\n networkFailureProbe: probeNetworkFailures\n ? createApiReachabilityProbe()\n : null,\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.primeProvisionedState = runtime.primeProvisionedState;\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.setOnNetworkFailure((error) =>\n this.apiNetworkFailures.notify(error.details),\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: TearleadsOptions,\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. Pass it to {@link openServerEventsSocket}.\n */\n requestWebSocketTicket(): Promise<string | null> {\n return this.apiClient.requestWebSocketTicket();\n }\n\n /** Opens the API's server-events socket for a ticket; the API client owns the URL shape. */\n openServerEventsSocket(wsUrl: string, ticket: string): WebSocket {\n return openServerEventsSocket(wsUrl, ticket);\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,EACL,SAAS,EAET,iBAA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FailureDetails,\n ApiRequestMetrics,\n createApiReachabilityProbe,\n openServerEventsSocket,\n} from \"@tearleads/api-client\";\nimport { Blobs } from \"./client/blobs\";\nimport {\n type ContainerContents,\n createContainerContents,\n} from \"./client/containerContents\";\nimport { createDeviceFirst, type DeviceFirst } from \"./client/deviceFirst\";\nimport { createDocuments, type Documents } from \"./client/documents\";\nimport { logErrorToConsole } from \"./client/host/logger\";\nimport { createIdentity, type Identity } from \"./client/identity\";\nimport {\n createUserIdentities,\n type UserIdentities,\n} from \"./client/identity/userIdentities\";\nimport {\n createOrganizations,\n type Organizations,\n} from \"./client/organizations\";\nimport { createRoot, type Root, rootRuntimeOf } from \"./client/root\";\nimport { ApiVersion } from \"./client/runtime/apiVersion\";\nimport { Database } from \"./client/runtime/database\";\nimport { Events } from \"./client/runtime/events\";\nimport { Network } from \"./client/runtime/network\";\nimport { SyncBillingGate } from \"./client/runtime/syncBillingGate\";\nimport {\n createRuntime,\n type InternalRuntime,\n type Runtime,\n} from \"./client/runtime/workflowRuntime\";\nimport {\n createSecurityIncidentService,\n type SecurityIncidents,\n} from \"./client/securityIncidents\";\nimport { createSession } from \"./client/session\";\nimport type { Session } from \"./client/session/sessionTypes\";\nimport {\n type DocumentProjectorRegistry,\n resolveDocumentProjectorRegistry,\n} from \"./data/documents/documentKinds\";\nimport { heldDirectoryCitations } from \"./data/persistence/principalPolicy/heldOrganizationDirectories\";\nimport { createVerifiedManifestCitations } from \"./data/persistence/verifiedManifestBundlePersistence\";\nimport { createDomainScope, type DomainScope } from \"./data/shared/domainScope\";\nimport { createListenerSet } from \"./data/shared/listenerSet\";\nimport type { SecurityIncidentReporter } from \"./data/shared/securityIncidents\";\nimport { disposeDomainSyncCoordinator } from \"./data/sync/syncCoordinator\";\nimport { resolveIdentityTrustDomain } from \"./data/trustedUserIdentity\";\nimport type { TearleadsOptions } from \"./TearleadsOptions\";\n\nexport class Tearleads {\n readonly apiVersion = new ApiVersion();\n private readonly apiNetworkFailures =\n createListenerSet<[ApiNetworkFailureDetails]>();\n /**\n * Every API request that got no response (plain cancellations excluded),\n * with the transport's secret-free details; hosts forward them to\n * diagnostics. Returns the unsubscribe handle.\n */\n readonly subscribeApiNetworkFailures = (\n listener: (details: ApiNetworkFailureDetails) => void,\n ): (() => void) => this.apiNetworkFailures.subscribe(listener);\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 primeProvisionedState: InternalRuntime[\"primeProvisionedState\"] =\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: TearleadsOptions = {}) {\n const apiBaseUrl = options.apiBaseUrl ?? \"\";\n this.apiRequests = options.apiRequestMetrics ?? new ApiRequestMetrics();\n this.apiClient = this.createApiClient(\n apiBaseUrl,\n options.probeApiNetworkFailures === true,\n );\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 identityTrustDomain = resolveIdentityTrustDomain({\n apiBaseUrl,\n identityTrustDomain: options.identityTrustDomain,\n });\n const security = this.createSecurityIncidents(identityTrustDomain, options);\n this.securityIncidents = security.incidents;\n this.disposeSecurityIncidents = security.dispose;\n this.network = new Network(options.online);\n this.syncBillingGate = new SyncBillingGate();\n let session: Session | null = null;\n this.identity = createIdentity(options.identity, this.blobs, this.log, {\n assertReadyForGeneration: () => {\n if (this.database.status !== \"ready\") {\n throw new Error(\n \"identity.generate requires a ready SQLite database.\",\n );\n }\n },\n bootstrapLocalRootContainer: async (isCurrent) => {\n if (!session) {\n throw new Error(\"identity.generate requires an initialized session.\");\n }\n\n return session.bootstrapLocalRootContainer(isCurrent);\n },\n getUserId: () => session?.userId ?? null,\n });\n session = this.createClientSession(\n options,\n security.report,\n identityTrustDomain,\n );\n this.session = session;\n const runtime = this.createWorkflowRuntime(\n identityTrustDomain,\n options,\n security.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(\n runtime,\n this.containerContents,\n () => this.deviceFirst.open().reconciler,\n );\n this.root = createRoot(rootRuntimeOf(runtime, this.session));\n this.userIdentities = createUserIdentities({\n getOrganizationId: () => this.session.organizationId,\n reportSecurityIncident: security.report,\n identityLinks: runtime.identityLinks,\n });\n\n this.configureApiClientCallbacks();\n\n if (options.identityProvisioning === \"auto\") {\n this.startAutomaticIdentityProvisioning();\n }\n }\n\n /** Durable incident records in this database, reported to the host's listener. */\n private createSecurityIncidents(\n trustDomain: string | null,\n options: TearleadsOptions,\n ) {\n return createSecurityIncidentService({\n database: this.database,\n logError: this.logError,\n onIncident: options.onSecurityIncident,\n trustDomain,\n });\n }\n\n /** Trust callbacks reach the workflow runtime, which is created later. */\n private createClientSession(\n options: TearleadsOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n identityTrustDomain: string | null,\n ): Session {\n return createSession({\n identityTrustDomain,\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 primeProvisionedState: (input) => this.primeProvisionedState(input),\n provisionedSystemContainers: options.provisionedSystemContainers,\n reportSecurityIncident,\n });\n }\n\n private createApiClient(\n apiBaseUrl: string,\n probeNetworkFailures: boolean,\n ): ApiClient {\n return new ApiClient(apiBaseUrl, {\n metrics: this.apiRequests,\n getIdentity: () => this.identity.signingFingerprint,\n // A native source beats a WebView's navigator.onLine (Android misreports it).\n isOnline: () => this.network.authoritativeOnline,\n networkFailureProbe: probeNetworkFailures\n ? createApiReachabilityProbe()\n : null,\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.primeProvisionedState = runtime.primeProvisionedState;\n this.boundUserId = (signingKeyFingerprint) =>\n runtime.boundUserId(signingKeyFingerprint);\n }\n\n private configureApiClientCallbacks(): void {\n // Projection reads cite bundles this identity's database already\n // verified, and the organization directories its policy bundles hold.\n this.apiClient.setVerifiedManifestCitations(\n createVerifiedManifestCitations(\n () => this.database.execSql,\n heldDirectoryCitations,\n ),\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.setOnNetworkFailure((error) =>\n this.apiNetworkFailures.notify(error.details),\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: TearleadsOptions,\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. Pass it to {@link openServerEventsSocket}.\n */\n requestWebSocketTicket(): Promise<string | null> {\n return this.apiClient.requestWebSocketTicket();\n }\n\n /** Opens the API's server-events socket for a ticket; the API client owns the URL shape. */\n openServerEventsSocket(wsUrl: string, ticket: string): WebSocket {\n return openServerEventsSocket(wsUrl, ticket);\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"]}
@@ -0,0 +1,53 @@
1
+ import { isPrincipalStatePayloadResponse, isPrincipalStateResponse, } from "../../../internal/validators/response/index.js";
2
+ import { KNOWN_DIRECTORY_HINT_LIMIT } from "../../../internal/validators/util/index.js";
3
+ import { and, asc, desc, eq } from "drizzle-orm";
4
+ import { principalPolicyBundles } from "../../sqlite/schema/principalPolicySchema.js";
5
+ import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
6
+ function parsed(json) {
7
+ try {
8
+ return JSON.parse(json);
9
+ }
10
+ catch {
11
+ return null;
12
+ }
13
+ }
14
+ /**
15
+ * The organization directory payloads this device holds in its verified
16
+ * policy bundles, its current state first, at most
17
+ * `KNOWN_DIRECTORY_HINT_LIMIT`. Each travels with its signed state: the
18
+ * request cites a payload only when its bytes hash to that state's
19
+ * `payloadCiphertextHash`, so a refill is exactly the bytes the server would
20
+ * send.
21
+ */
22
+ export async function heldDirectoryCitations(execSql, organizationId) {
23
+ // Citing only saves bytes: a device that has stored no policy bundle yet
24
+ // (so no table) or cannot read them cites no directory.
25
+ const rows = await heldDirectoryRows(getClientSQLitePersistenceRuntime(execSql).db, organizationId).catch(() => []);
26
+ const citations = [];
27
+ for (const row of rows) {
28
+ const directoryState = parsed(row.stateJson);
29
+ const directoryPayload = parsed(row.payloadJson);
30
+ // A row must name its own state of this organization, so a request
31
+ // never cites another organization's state hash.
32
+ if (isPrincipalStateResponse(directoryState) &&
33
+ isPrincipalStatePayloadResponse(directoryPayload) &&
34
+ directoryState.stateHash === row.stateHash &&
35
+ directoryState.principalType === "organization" &&
36
+ directoryState.principalId === organizationId)
37
+ citations.push({ directoryState, directoryPayload });
38
+ }
39
+ return citations;
40
+ }
41
+ function heldDirectoryRows(db, organizationId) {
42
+ return db
43
+ .select({
44
+ stateHash: principalPolicyBundles.stateHash,
45
+ stateJson: principalPolicyBundles.currentStateJson,
46
+ payloadJson: principalPolicyBundles.currentPayloadJson,
47
+ })
48
+ .from(principalPolicyBundles)
49
+ .where(and(eq(principalPolicyBundles.principalType, "organization"), eq(principalPolicyBundles.principalId, organizationId)))
50
+ .orderBy(desc(principalPolicyBundles.isCurrent), desc(principalPolicyBundles.updatedAt), asc(principalPolicyBundles.stateHash))
51
+ .limit(KNOWN_DIRECTORY_HINT_LIMIT);
52
+ }
53
+ //# sourceMappingURL=heldOrganizationDirectories.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"heldOrganizationDirectories.js","sourceRoot":"","sources":["heldOrganizationDirectories.ts"],"names":[],"mappings":"AACA,OAAO,EACL,+BAA+B,EAC/B,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,sBAAsB,EAAE,MAAM,2CAA2C,CAAC;AACnF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAG/C,SAAS,MAAM,CAAC,IAAY;IAC1B,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,OAAgB,EAChB,cAAsB;IAEtB,yEAAyE;IACzE,wDAAwD;IACxD,MAAM,IAAI,GAAG,MAAM,iBAAiB,CAClC,iCAAiC,CAAC,OAAO,CAAC,CAAC,EAA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C","sourcesContent":["import type { HeldDirectoryCitation } from \"@tearleads/api-client\";\nimport {\n isPrincipalStatePayloadResponse,\n isPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { KNOWN_DIRECTORY_HINT_LIMIT } from \"@tearleads/validators/util\";\nimport { and, asc, desc, eq } from \"drizzle-orm\";\nimport { principalPolicyBundles } from \"../../sqlite/schema/principalPolicySchema\";\nimport {\n type ClientSQLiteDatabase,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\nfunction parsed(json: string): unknown {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\n/**\n * The organization directory payloads this device holds in its verified\n * policy bundles, its current state first, at most\n * `KNOWN_DIRECTORY_HINT_LIMIT`. Each travels with its signed state: the\n * request cites a payload only when its bytes hash to that state's\n * `payloadCiphertextHash`, so a refill is exactly the bytes the server would\n * send.\n */\nexport async function heldDirectoryCitations(\n execSql: ExecSql,\n organizationId: string,\n): Promise<HeldDirectoryCitation[]> {\n // Citing only saves bytes: a device that has stored no policy bundle yet\n // (so no table) or cannot read them cites no directory.\n const rows = await heldDirectoryRows(\n getClientSQLitePersistenceRuntime(execSql).db,\n organizationId,\n ).catch(() => []);\n const citations: HeldDirectoryCitation[] = [];\n for (const row of rows) {\n const directoryState = parsed(row.stateJson);\n const directoryPayload = parsed(row.payloadJson);\n // A row must name its own state of this organization, so a request\n // never cites another organization's state hash.\n if (\n isPrincipalStateResponse(directoryState) &&\n isPrincipalStatePayloadResponse(directoryPayload) &&\n directoryState.stateHash === row.stateHash &&\n directoryState.principalType === \"organization\" &&\n directoryState.principalId === organizationId\n )\n citations.push({ directoryState, directoryPayload });\n }\n return citations;\n}\n\nfunction heldDirectoryRows(db: ClientSQLiteDatabase, organizationId: string) {\n return db\n .select({\n stateHash: principalPolicyBundles.stateHash,\n stateJson: principalPolicyBundles.currentStateJson,\n payloadJson: principalPolicyBundles.currentPayloadJson,\n })\n .from(principalPolicyBundles)\n .where(\n and(\n eq(principalPolicyBundles.principalType, \"organization\"),\n eq(principalPolicyBundles.principalId, organizationId),\n ),\n )\n .orderBy(\n desc(principalPolicyBundles.isCurrent),\n desc(principalPolicyBundles.updatedAt),\n asc(principalPolicyBundles.stateHash),\n )\n .limit(KNOWN_DIRECTORY_HINT_LIMIT);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { HeldProjectionCitation, VerifiedManifestCitations, WriterProjectionTarget } from "../../internal/api-client/index.js";
1
+ import type { HeldDirectoryCitation, HeldProjectionCitation, VerifiedManifestCitations, WriterProjectionTarget } from "../../internal/api-client/index.js";
2
2
  import { type ServedAccessManifestBundleWireResponse } from "../../internal/validators/util/index.js";
3
3
  import { verifiedAccessManifestBundles as bundles } from "../sqlite/schema/verifiedManifestBundleSchema.js";
4
4
  import { type ClientSQLiteTransactionScope } from "../sqlite/sqlitePersistenceRuntime.js";
@@ -47,7 +47,12 @@ export declare function writeVerifiedManifestBundlesInTransaction(tx: ClientSQLi
47
47
  * organization the device cannot place cites nothing. Damaged rows are
48
48
  * dropped.
49
49
  */
50
- export declare function loadVerifiedManifestCitations(execSql: ExecSql, target: WriterProjectionTarget, requestedLimit?: number): Promise<HeldProjectionCitation[]>;
50
+ /**
51
+ * The organization directory payloads a device holds, from the subsystem
52
+ * that stores policy bundles; the composition root wires it.
53
+ */
54
+ export type HeldDirectorySource = (execSql: ExecSql, organizationId: string) => Promise<readonly HeldDirectoryCitation[]>;
55
+ export declare function loadVerifiedManifestCitations(execSql: ExecSql, target: WriterProjectionTarget, requestedLimit?: number, heldDirectories?: HeldDirectorySource): Promise<HeldProjectionCitation[]>;
51
56
  /** Keeps these held bundles out of citations until the release runs. */
52
57
  export declare function suppressHeldCitations(manifestHashes: readonly string[]): () => void;
53
58
  /**
@@ -59,7 +64,7 @@ export declare function suppressHeldCitations(manifestHashes: readonly string[])
59
64
  */
60
65
  export declare function dropHeldManifestBundles(execSql: ExecSql, heldBundles: readonly ServedAccessManifestBundleWireResponse[], stillCurrent?: () => boolean): Promise<boolean>;
61
66
  /** Cites from whichever database the signed-in identity currently uses. */
62
- export declare function createVerifiedManifestCitations(resolveExecSql: () => ExecSql | null): VerifiedManifestCitations;
67
+ export declare function createVerifiedManifestCitations(resolveExecSql: () => ExecSql | null, heldDirectories?: HeldDirectorySource): VerifiedManifestCitations;
63
68
  /** Drops an organization's verified bundles when a remote reset forgets it. */
64
69
  export declare function deleteVerifiedManifestBundlesForOrganization(tx: ClientSQLiteTransactionScope, organizationId: string): Promise<void>;
65
70
  export {};
@@ -153,24 +153,35 @@ async function touchStoredDigests(tx, manifestHashes, verifiedAt) {
153
153
  return digests;
154
154
  }
155
155
  /**
156
- * The latest verified KEK level of each container the target's projection
157
- * walks (supplemented by organization-recency levels for a pending move,
158
- * or when the lineage has no stored level); then verified bundles of those
159
- * objects, newest epochs first; then
160
- * the most recently verified bundles of its organization, since a
161
- * just-verified parent is the likeliest part of a new child's projection.
162
- * Citations never leave the target's organization: an object whose
163
- * organization the device cannot place cites nothing. Damaged rows are
164
- * dropped.
156
+ * How long after the citation load began the directory read may still run.
157
+ * Directory citations are an extra: the load collects the manifest and
158
+ * KEK-level citations first, then reads directories only with the time left
159
+ * before this point, which stays inside the API client's 250 ms citation
160
+ * deadline with room for its own preparation. A slow or stalled directory
161
+ * read therefore never delays or discards the manifest hints.
165
162
  */
166
- export async function loadVerifiedManifestCitations(execSql, target, requestedLimit = KNOWN_MANIFEST_HINT_LIMIT) {
163
+ const DIRECTORY_CITATION_DEADLINE_MS = 150;
164
+ async function directoriesBeforeDeadline(source, execSql, organizationId, startedAt) {
165
+ const remaining = startedAt + DIRECTORY_CITATION_DEADLINE_MS - performance.now();
166
+ if (!source || remaining <= 0)
167
+ return [];
168
+ let timer;
169
+ const deadline = new Promise((resolve) => {
170
+ timer = setTimeout(() => resolve([]), remaining);
171
+ });
172
+ return Promise.race([
173
+ source(execSql, organizationId).catch(() => []),
174
+ deadline,
175
+ ]).finally(() => clearTimeout(timer));
176
+ }
177
+ export async function loadVerifiedManifestCitations(execSql, target, requestedLimit = KNOWN_MANIFEST_HINT_LIMIT, heldDirectories) {
167
178
  const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));
168
179
  if (!(limit > 0))
169
180
  return [];
170
181
  const loadGeneration = evictionGeneration;
171
182
  citationLoadsInFlight += 1;
172
183
  try {
173
- return await loadCitableManifestCitations(execSql, target, limit).then((cited) => cited.filter((citation) => citable(citation, loadGeneration)));
184
+ return await loadCitableManifestCitations(execSql, target, limit, heldDirectories).then((cited) => cited.filter((citation) => citable(citation, loadGeneration)));
174
185
  }
175
186
  finally {
176
187
  citationLoadsInFlight -= 1;
@@ -178,7 +189,8 @@ export async function loadVerifiedManifestCitations(execSql, target, requestedLi
178
189
  evictedInGeneration.clear();
179
190
  }
180
191
  }
181
- async function loadCitableManifestCitations(execSql, target, limit) {
192
+ async function loadCitableManifestCitations(execSql, target, limit, heldDirectories) {
193
+ const startedAt = performance.now();
182
194
  await ensureSqlTables(execSql, [
183
195
  ...verifiedManifestBundleTables,
184
196
  ...containerTables,
@@ -194,7 +206,12 @@ async function loadCitableManifestCitations(execSql, target, limit) {
194
206
  const { cited, damaged } = await collectVerifiedManifestCitations(db, organizationId, objects, target, limit);
195
207
  if (damaged.length > 0)
196
208
  await dropVerifiedManifestBundles(execSql, damaged).catch(() => undefined);
197
- return cited;
209
+ // Directories are cited beside the manifest quota, never in its place,
210
+ // and read only after the manifest citations, with the time left.
211
+ return [
212
+ ...cited,
213
+ ...(await directoriesBeforeDeadline(heldDirectories, execSql, organizationId, startedAt)),
214
+ ];
198
215
  }
199
216
  // Manifest hashes whose held rows a refused read is dropping: no read cites
200
217
  // them meanwhile, so none can be rebuilt from the bytes being dropped. Each
@@ -279,11 +296,13 @@ async function dropVerifiedManifestBundles(execSql, manifestHashes) {
279
296
  });
280
297
  }
281
298
  /** Cites from whichever database the signed-in identity currently uses. */
282
- export function createVerifiedManifestCitations(resolveExecSql) {
299
+ export function createVerifiedManifestCitations(resolveExecSql, heldDirectories) {
283
300
  return {
284
301
  cite: async (target) => {
285
302
  const execSql = resolveExecSql();
286
- return execSql ? loadVerifiedManifestCitations(execSql, target) : [];
303
+ return execSql
304
+ ? loadVerifiedManifestCitations(execSql, target, KNOWN_MANIFEST_HINT_LIMIT, heldDirectories)
305
+ : [];
287
306
  },
288
307
  };
289
308
  }
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedManifestBundlePersistence.js","sourceRoot":"","sources":["verifiedManifestBundlePersistence.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EACL,yBAAyB,GAE1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EACL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,6BAA6B,IAAI,OAAO,EACxC,4BAA4B,GAC7B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAE,gCAAgC,EAAE,MAAM,wCAAwC,CAAC;AAC1F,OAAO,EACL,YAAY,EACZ,kBAAkB,GACnB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,qBAAqB,EACrB,WAAW,GAEZ,MAAM,uCAAuC,CAAC;AAE/C;;;GAGG;AACH,MAAM,CAAC,M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M,OAAO,GAAG,cAAc,EAAE,CAAC;YACjC,OAAO,OAAO,CAAC,CAAC,CAAC,6BAA6B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACvE,CAAC;KACF,CAAC;AACJ,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAChE,EAAgC,EAChC,cAAsB;IAEtB,MAAM,EAAE;SACL,MAAM,CAAC,OAAO,CAAC;SACf,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;SACjD,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import type {\n HeldProjectionCitation,\n VerifiedManifestCitations,\n WriterProjectionTarget,\n} from \"@tearleads/api-client\";\nimport { toFingerprint } from \"@tearleads/crypto\";\nimport {\n KNOWN_MANIFEST_HINT_LIMIT,\n type ServedAccessManifestBundleWireResponse,\n} from \"@tearleads/validators/util\";\nimport { and, asc, eq, inArray, notInArray, sql } from \"drizzle-orm\";\nimport { containerTables, localIntentTables } from \"../sqlite/schema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../sqlite/schema/documentProjectionSchema\";\nimport {\n verifiedAccessManifestBundles as bundles,\n verifiedManifestBundleTables,\n} from \"../sqlite/schema/verifiedManifestBundleSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../sqlite/sqliteUpsert\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { collectVerifiedManifestCitations } from \"./verifiedCitations/citationCollection\";\nimport {\n citedObjects,\n targetOrganization,\n} from \"./verifiedCitations/citationScope\";\nimport {\n KEK_LEVEL_OBJECT_KIND,\n kekLevelRow,\n type VerifiedKekLevel,\n} from \"./verifiedCitations/kekLevelCitations\";\n\n/**\n * Bounds local bytes (a bundle is ~10–20 KB). Evicting the least recently\n * verified rows only makes a later read carry those bundles again.\n */\nexport const MAX_VERIFIED_MANIFEST_BUNDLES = 1024;\nconst STATEMENT_BATCH = 200;\n\ninterface VerifiedBundle {\n /** The served bytes; the decoded state is rebuilt from them on refill. */\n readonly bundle: ServedAccessManifestBundleWireResponse;\n readonly checkpoint: {\n readonly objectKind: string;\n readonly organizationId: string;\n readonly objectId: string;\n readonly epoch: number;\n };\n}\n\n/** Bytes a projection verification accepted: a bundle or a KEK level. */\nexport type VerifiedManifestBundle = VerifiedBundle | VerifiedKekLevel;\n\nfunction sha256Hex(text: string): Promise<string> {\n return toFingerprint(new TextEncoder().encode(text));\n}\n\nconst BUNDLE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(bundles);\n\nfunction slices<T>(values: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < values.length; index += size)\n result.push(values.slice(index, index + size));\n return result;\n}\n\nfunction batches<T>(values: readonly T[]): T[][] {\n return slices(values, STATEMENT_BATCH);\n}\n\nasync function pruneInTransaction(\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n const [row] = await tx.select({ count: sql<number>`count(*)` }).from(bundles);\n const excess = (row?.count ?? 0) - MAX_VERIFIED_MANIFEST_BUNDLES;\n if (excess <= 0) return;\n const evicted = await tx\n .select({ manifestHash: bundles.manifestHash })\n .from(bundles)\n .orderBy(asc(bundles.verifiedAt), asc(bundles.manifestHash))\n .limit(excess);\n for (const batch of batches(evicted.map((entry) => entry.manifestHash)))\n await tx.delete(bundles).where(inArray(bundles.manifestHash, batch)).run();\n}\n\n/** A verified bundle's exact JSON and that JSON's digest. */\nexport type VerifiedManifestBundleRow = Omit<\n typeof bundles.$inferInsert,\n \"verifiedAt\"\n>;\n\n/**\n * Prepares rows for bundles and KEK levels that just passed projection\n * verification. The digests are computed here, before the checkpoint\n * transaction that writes them begins.\n */\nexport async function verifiedManifestBundleRows(\n entries: readonly VerifiedManifestBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleEntries: VerifiedBundle[] = [];\n const levelEntries: VerifiedKekLevel[] = [];\n for (const entry of entries)\n if (\"kekLevel\" in entry) levelEntries.push(entry);\n else bundleEntries.push(entry);\n // One level per container: its newest epoch, the last one seen on a tie.\n const levelRows = new Map<string, VerifiedManifestBundleRow>();\n for (const level of levelEntries) {\n const row = await kekLevelRow(level);\n const held = row && levelRows.get(row.objectId);\n if (row && (!held || held.epoch <= row.epoch))\n levelRows.set(row.objectId, row);\n }\n return [...(await bundleRows(bundleEntries)), ...levelRows.values()];\n}\n\nfunction bundleRows(\n entries: readonly VerifiedBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const unique = new Map(\n entries.map((entry) => [entry.bundle.manifestHash, entry]),\n );\n return Promise.all(\n [...unique.values()].map(async ({ bundle, checkpoint }) => {\n const bundleJson = JSON.stringify(bundle);\n return {\n manifestHash: bundle.manifestHash,\n organizationId: checkpoint.organizationId,\n objectKind: checkpoint.objectKind,\n objectId: checkpoint.objectId,\n epoch: checkpoint.epoch,\n bundleJson,\n bundleDigest: await sha256Hex(bundleJson),\n };\n }),\n );\n}\n\n/**\n * Records verified bundles inside the transaction that finalizes their\n * projection's checkpoints, so they commit or roll back with it and no cache\n * work outlives the verification. Freshly verified bytes replace any stored\n * copy.\n */\nexport async function writeVerifiedManifestBundlesInTransaction(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n verifiedAt: string,\n): Promise<void> {\n if (rows.length === 0) return;\n const stored = await touchStoredDigests(\n tx,\n rows.map((row) => row.manifestHash),\n verifiedAt,\n );\n // A repeated hash keeps its last changed row, as sequential upserts would.\n const changed = new Map(\n rows\n .filter((row) => stored.get(row.manifestHash) !== row.bundleDigest)\n .map((row) => [row.manifestHash, { ...row, verifiedAt }]),\n );\n for (const batch of slices([...changed.values()], BUNDLE_WRITE_BATCH_SIZE))\n await tx\n .insert(bundles)\n .values(batch)\n .onConflictDoUpdate({\n target: bundles.manifestHash,\n set: {\n organizationId: excludedValue(bundles.organizationId),\n objectKind: excludedValue(bundles.objectKind),\n objectId: excludedValue(bundles.objectId),\n epoch: excludedValue(bundles.epoch),\n bundleJson: excludedValue(bundles.bundleJson),\n bundleDigest: excludedValue(bundles.bundleDigest),\n verifiedAt: excludedValue(bundles.verifiedAt),\n },\n })\n .run();\n // All incremental SDK level writes pass here. Both checkpoint callers\n // prepare them with verifiedManifestBundleRows (one level per container),\n // then write and drop siblings in the same serialized transaction. Thus an\n // unchanged level already removed its siblings; eviction/reset only delete.\n // Restored caches must preserve that invariant too: this fast path does not\n // repair externally injected stale siblings.\n await dropSupersededKekLevels(tx, [...changed.values()]);\n // Replacing or touching existing rows cannot grow the bounded cache.\n if (rows.some((row) => !stored.has(row.manifestHash))) {\n await pruneInTransaction(tx);\n }\n}\n\n/**\n * A container keeps only its latest verified level: the API serves its\n * current level, so an older one can never be cited usefully again.\n */\nasync function dropSupersededKekLevels(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n): Promise<void> {\n const levels = rows.filter((row) => row.objectKind === KEK_LEVEL_OBJECT_KIND);\n for (const batch of batches(levels))\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.objectKind, KEK_LEVEL_OBJECT_KIND),\n inArray(\n bundles.objectId,\n batch.map((row) => row.objectId),\n ),\n notInArray(\n bundles.manifestHash,\n batch.map((row) => row.manifestHash),\n ),\n ),\n )\n .run();\n}\n\nasync function touchStoredDigests(\n tx: ClientSQLiteTransactionScope,\n manifestHashes: readonly string[],\n verifiedAt: string,\n): Promise<Map<string, string>> {\n const digests = new Map<string, string>();\n for (const batch of batches(manifestHashes)) {\n const rows = await tx\n .update(bundles)\n .set({ verifiedAt })\n .where(inArray(bundles.manifestHash, batch))\n .returning({\n bundleDigest: bundles.bundleDigest,\n manifestHash: bundles.manifestHash,\n });\n for (const row of rows) digests.set(row.manifestHash, row.bundleDigest);\n }\n return digests;\n}\n\n/**\n * The latest verified KEK level of each container the target's projection\n * walks (supplemented by organization-recency levels for a pending move,\n * or when the lineage has no stored level); then verified bundles of those\n * objects, newest epochs first; then\n * the most recently verified bundles of its organization, since a\n * just-verified parent is the likeliest part of a new child's projection.\n * Citations never leave the target's organization: an object whose\n * organization the device cannot place cites nothing. Damaged rows are\n * dropped.\n */\nexport async function loadVerifiedManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n requestedLimit = KNOWN_MANIFEST_HINT_LIMIT,\n): Promise<HeldProjectionCitation[]> {\n const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));\n if (!(limit > 0)) return [];\n const loadGeneration = evictionGeneration;\n citationLoadsInFlight += 1;\n try {\n return await loadCitableManifestCitations(execSql, target, limit).then(\n (cited) => cited.filter((citation) => citable(citation, loadGeneration)),\n );\n } finally {\n citationLoadsInFlight -= 1;\n if (citationLoadsInFlight === 0) evictedInGeneration.clear();\n }\n}\n\nasync function loadCitableManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n limit: number,\n): Promise<HeldProjectionCitation[]> {\n await ensureSqlTables(execSql, [\n ...verifiedManifestBundleTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...localIntentTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const objects = await citedObjects(db, target);\n const organizationId = await targetOrganization(db, target, objects);\n if (organizationId === null) return [];\n const { cited, damaged } = await collectVerifiedManifestCitations(\n db,\n organizationId,\n objects,\n target,\n limit,\n );\n if (damaged.length > 0)\n await dropVerifiedManifestBundles(execSql, damaged).catch(() => undefined);\n return cited;\n}\n\n// Manifest hashes whose held rows a refused read is dropping: no read cites\n// them meanwhile, so none can be rebuilt from the bytes being dropped. Each\n// eviction also advances a generation, so a citation load that started\n// before it never returns the rows it read: they may already be gone.\nconst suppressedCitations = new Map<string, number>();\nconst evictedInGeneration = new Map<string, number>();\nlet evictionGeneration = 0;\n// Loads in flight; once none overlap, the eviction log has nothing to guard.\nlet citationLoadsInFlight = 0;\n\n/** Keeps these held bundles out of citations until the release runs. */\nexport function suppressHeldCitations(\n manifestHashes: readonly string[],\n): () => void {\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n suppressedCitations.set(hash, (suppressedCitations.get(hash) ?? 0) + 1);\n evictedInGeneration.set(hash, evictionGeneration);\n }\n return () => {\n // The drop is complete: a load that started before now may hold the\n // dropped bytes, so it is newer than none of them.\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n evictedInGeneration.set(hash, evictionGeneration);\n const count = (suppressedCitations.get(hash) ?? 1) - 1;\n if (count > 0) suppressedCitations.set(hash, count);\n else suppressedCitations.delete(hash);\n }\n };\n}\n\nfunction citable(\n citation: HeldProjectionCitation,\n loadGeneration: number,\n): boolean {\n if (!(\"manifestHash\" in citation)) return true;\n const { manifestHash } = citation;\n return (\n !suppressedCitations.has(manifestHash) &&\n (evictedInGeneration.get(manifestHash) ?? 0) <= loadGeneration\n );\n}\n\n/**\n * Drops the stored rows of held bundles a projection that cited them failed\n * to verify with, so the next read fetches them from the server. Only a row\n * still holding the exact bytes cited goes, so a newer verified copy written\n * meanwhile stays; nothing is dropped once `stillCurrent` turns false.\n * Resolves whether the drop committed.\n */\nexport async function dropHeldManifestBundles(\n execSql: ExecSql,\n heldBundles: readonly ServedAccessManifestBundleWireResponse[],\n stillCurrent?: () => boolean,\n): Promise<boolean> {\n if (heldBundles.length === 0) return true;\n const cited = await Promise.all(\n heldBundles.map(async (bundle) => ({\n manifestHash: bundle.manifestHash,\n bundleDigest: await sha256Hex(JSON.stringify(bundle)),\n })),\n );\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const drop = async (tx: ClientSQLiteTransactionScope) => {\n for (const row of cited)\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.manifestHash, row.manifestHash),\n eq(bundles.bundleDigest, row.bundleDigest),\n ),\n )\n .run();\n };\n if (!stillCurrent) {\n await runtime.transaction(drop, { behavior: \"immediate\" });\n return true;\n }\n const { committed } = await runtime.guardedTransaction(drop, stillCurrent, {\n behavior: \"immediate\",\n });\n return committed;\n}\n\n/** Drops damaged stored rows so no later read cites them. */\nasync function dropVerifiedManifestBundles(\n execSql: ExecSql,\n manifestHashes: readonly string[],\n): Promise<void> {\n if (manifestHashes.length === 0) return;\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n await getClientSQLitePersistenceRuntime(execSql).runMutation(\n async (handle) => {\n for (const batch of batches([...new Set(manifestHashes)]))\n await handle\n .delete(bundles)\n .where(inArray(bundles.manifestHash, batch))\n .run();\n },\n );\n}\n\n/** Cites from whichever database the signed-in identity currently uses. */\nexport function createVerifiedManifestCitations(\n resolveExecSql: () => ExecSql | null,\n): VerifiedManifestCitations {\n return {\n cite: async (target) => {\n const execSql = resolveExecSql();\n return execSql ? loadVerifiedManifestCitations(execSql, target) : [];\n },\n };\n}\n\n/** Drops an organization's verified bundles when a remote reset forgets it. */\nexport async function deleteVerifiedManifestBundlesForOrganization(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n await tx\n .delete(bundles)\n .where(eq(bundles.organizationId, organizationId))\n .run();\n}\n"]}
1
+ {"version":3,"file":"verifiedManifestBundlePersistence.js","sourceRoot":"","sources":["verifiedManifestBundlePersistence.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EACL,yBAAyB,GAE1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EACL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,2CAA2C,CAAC;AACnD,OAAO,E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AK,CAAC,CAAC;iBAC3C,GAAG,EAAE,CAAC;IACb,CAAC,CACF,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,+BAA+B,CAC7C,cAAoC,EACpC,eAAqC;IAErC,OAAO;QACL,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;YACrB,MAAM,OAAO,GAAG,cAAc,EAAE,CAAC;YACjC,OAAO,OAAO;gBACZ,CAAC,CAAC,6BAA6B,CAC3B,OAAO,EACP,MAAM,EACN,yBAAyB,EACzB,eAAe,CAChB;gBACH,CAAC,CAAC,EAAE,CAAC;QACT,CAAC;KACF,CAAC;AACJ,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAChE,EAAgC,EAChC,cAAsB;IAEtB,MAAM,EAAE;SACL,MAAM,CAAC,OAAO,CAAC;SACf,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;SACjD,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import type {\n HeldDirectoryCitation,\n HeldProjectionCitation,\n VerifiedManifestCitations,\n WriterProjectionTarget,\n} from \"@tearleads/api-client\";\nimport { toFingerprint } from \"@tearleads/crypto\";\nimport {\n KNOWN_MANIFEST_HINT_LIMIT,\n type ServedAccessManifestBundleWireResponse,\n} from \"@tearleads/validators/util\";\nimport { and, asc, eq, inArray, notInArray, sql } from \"drizzle-orm\";\nimport { containerTables, localIntentTables } from \"../sqlite/schema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../sqlite/schema/documentProjectionSchema\";\nimport {\n verifiedAccessManifestBundles as bundles,\n verifiedManifestBundleTables,\n} from \"../sqlite/schema/verifiedManifestBundleSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../sqlite/sqliteUpsert\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { collectVerifiedManifestCitations } from \"./verifiedCitations/citationCollection\";\nimport {\n citedObjects,\n targetOrganization,\n} from \"./verifiedCitations/citationScope\";\nimport {\n KEK_LEVEL_OBJECT_KIND,\n kekLevelRow,\n type VerifiedKekLevel,\n} from \"./verifiedCitations/kekLevelCitations\";\n\n/**\n * Bounds local bytes (a bundle is ~10–20 KB). Evicting the least recently\n * verified rows only makes a later read carry those bundles again.\n */\nexport const MAX_VERIFIED_MANIFEST_BUNDLES = 1024;\nconst STATEMENT_BATCH = 200;\n\ninterface VerifiedBundle {\n /** The served bytes; the decoded state is rebuilt from them on refill. */\n readonly bundle: ServedAccessManifestBundleWireResponse;\n readonly checkpoint: {\n readonly objectKind: string;\n readonly organizationId: string;\n readonly objectId: string;\n readonly epoch: number;\n };\n}\n\n/** Bytes a projection verification accepted: a bundle or a KEK level. */\nexport type VerifiedManifestBundle = VerifiedBundle | VerifiedKekLevel;\n\nfunction sha256Hex(text: string): Promise<string> {\n return toFingerprint(new TextEncoder().encode(text));\n}\n\nconst BUNDLE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(bundles);\n\nfunction slices<T>(values: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < values.length; index += size)\n result.push(values.slice(index, index + size));\n return result;\n}\n\nfunction batches<T>(values: readonly T[]): T[][] {\n return slices(values, STATEMENT_BATCH);\n}\n\nasync function pruneInTransaction(\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n const [row] = await tx.select({ count: sql<number>`count(*)` }).from(bundles);\n const excess = (row?.count ?? 0) - MAX_VERIFIED_MANIFEST_BUNDLES;\n if (excess <= 0) return;\n const evicted = await tx\n .select({ manifestHash: bundles.manifestHash })\n .from(bundles)\n .orderBy(asc(bundles.verifiedAt), asc(bundles.manifestHash))\n .limit(excess);\n for (const batch of batches(evicted.map((entry) => entry.manifestHash)))\n await tx.delete(bundles).where(inArray(bundles.manifestHash, batch)).run();\n}\n\n/** A verified bundle's exact JSON and that JSON's digest. */\nexport type VerifiedManifestBundleRow = Omit<\n typeof bundles.$inferInsert,\n \"verifiedAt\"\n>;\n\n/**\n * Prepares rows for bundles and KEK levels that just passed projection\n * verification. The digests are computed here, before the checkpoint\n * transaction that writes them begins.\n */\nexport async function verifiedManifestBundleRows(\n entries: readonly VerifiedManifestBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleEntries: VerifiedBundle[] = [];\n const levelEntries: VerifiedKekLevel[] = [];\n for (const entry of entries)\n if (\"kekLevel\" in entry) levelEntries.push(entry);\n else bundleEntries.push(entry);\n // One level per container: its newest epoch, the last one seen on a tie.\n const levelRows = new Map<string, VerifiedManifestBundleRow>();\n for (const level of levelEntries) {\n const row = await kekLevelRow(level);\n const held = row && levelRows.get(row.objectId);\n if (row && (!held || held.epoch <= row.epoch))\n levelRows.set(row.objectId, row);\n }\n return [...(await bundleRows(bundleEntries)), ...levelRows.values()];\n}\n\nfunction bundleRows(\n entries: readonly VerifiedBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const unique = new Map(\n entries.map((entry) => [entry.bundle.manifestHash, entry]),\n );\n return Promise.all(\n [...unique.values()].map(async ({ bundle, checkpoint }) => {\n const bundleJson = JSON.stringify(bundle);\n return {\n manifestHash: bundle.manifestHash,\n organizationId: checkpoint.organizationId,\n objectKind: checkpoint.objectKind,\n objectId: checkpoint.objectId,\n epoch: checkpoint.epoch,\n bundleJson,\n bundleDigest: await sha256Hex(bundleJson),\n };\n }),\n );\n}\n\n/**\n * Records verified bundles inside the transaction that finalizes their\n * projection's checkpoints, so they commit or roll back with it and no cache\n * work outlives the verification. Freshly verified bytes replace any stored\n * copy.\n */\nexport async function writeVerifiedManifestBundlesInTransaction(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n verifiedAt: string,\n): Promise<void> {\n if (rows.length === 0) return;\n const stored = await touchStoredDigests(\n tx,\n rows.map((row) => row.manifestHash),\n verifiedAt,\n );\n // A repeated hash keeps its last changed row, as sequential upserts would.\n const changed = new Map(\n rows\n .filter((row) => stored.get(row.manifestHash) !== row.bundleDigest)\n .map((row) => [row.manifestHash, { ...row, verifiedAt }]),\n );\n for (const batch of slices([...changed.values()], BUNDLE_WRITE_BATCH_SIZE))\n await tx\n .insert(bundles)\n .values(batch)\n .onConflictDoUpdate({\n target: bundles.manifestHash,\n set: {\n organizationId: excludedValue(bundles.organizationId),\n objectKind: excludedValue(bundles.objectKind),\n objectId: excludedValue(bundles.objectId),\n epoch: excludedValue(bundles.epoch),\n bundleJson: excludedValue(bundles.bundleJson),\n bundleDigest: excludedValue(bundles.bundleDigest),\n verifiedAt: excludedValue(bundles.verifiedAt),\n },\n })\n .run();\n // All incremental SDK level writes pass here. Both checkpoint callers\n // prepare them with verifiedManifestBundleRows (one level per container),\n // then write and drop siblings in the same serialized transaction. Thus an\n // unchanged level already removed its siblings; eviction/reset only delete.\n // Restored caches must preserve that invariant too: this fast path does not\n // repair externally injected stale siblings.\n await dropSupersededKekLevels(tx, [...changed.values()]);\n // Replacing or touching existing rows cannot grow the bounded cache.\n if (rows.some((row) => !stored.has(row.manifestHash))) {\n await pruneInTransaction(tx);\n }\n}\n\n/**\n * A container keeps only its latest verified level: the API serves its\n * current level, so an older one can never be cited usefully again.\n */\nasync function dropSupersededKekLevels(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n): Promise<void> {\n const levels = rows.filter((row) => row.objectKind === KEK_LEVEL_OBJECT_KIND);\n for (const batch of batches(levels))\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.objectKind, KEK_LEVEL_OBJECT_KIND),\n inArray(\n bundles.objectId,\n batch.map((row) => row.objectId),\n ),\n notInArray(\n bundles.manifestHash,\n batch.map((row) => row.manifestHash),\n ),\n ),\n )\n .run();\n}\n\nasync function touchStoredDigests(\n tx: ClientSQLiteTransactionScope,\n manifestHashes: readonly string[],\n verifiedAt: string,\n): Promise<Map<string, string>> {\n const digests = new Map<string, string>();\n for (const batch of batches(manifestHashes)) {\n const rows = await tx\n .update(bundles)\n .set({ verifiedAt })\n .where(inArray(bundles.manifestHash, batch))\n .returning({\n bundleDigest: bundles.bundleDigest,\n manifestHash: bundles.manifestHash,\n });\n for (const row of rows) digests.set(row.manifestHash, row.bundleDigest);\n }\n return digests;\n}\n\n/**\n * The latest verified KEK level of each container the target's projection\n * walks (supplemented by organization-recency levels for a pending move,\n * or when the lineage has no stored level); then verified bundles of those\n * objects, newest epochs first; then\n * the most recently verified bundles of its organization, since a\n * just-verified parent is the likeliest part of a new child's projection.\n * Citations never leave the target's organization: an object whose\n * organization the device cannot place cites nothing. Damaged rows are\n * dropped.\n */\n/**\n * The organization directory payloads a device holds, from the subsystem\n * that stores policy bundles; the composition root wires it.\n */\nexport type HeldDirectorySource = (\n execSql: ExecSql,\n organizationId: string,\n) => Promise<readonly HeldDirectoryCitation[]>;\n\n/**\n * How long after the citation load began the directory read may still run.\n * Directory citations are an extra: the load collects the manifest and\n * KEK-level citations first, then reads directories only with the time left\n * before this point, which stays inside the API client's 250 ms citation\n * deadline with room for its own preparation. A slow or stalled directory\n * read therefore never delays or discards the manifest hints.\n */\nconst DIRECTORY_CITATION_DEADLINE_MS = 150;\n\nasync function directoriesBeforeDeadline(\n source: HeldDirectorySource | undefined,\n execSql: ExecSql,\n organizationId: string,\n startedAt: number,\n): Promise<readonly HeldDirectoryCitation[]> {\n const remaining =\n startedAt + DIRECTORY_CITATION_DEADLINE_MS - performance.now();\n if (!source || remaining <= 0) return [];\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<readonly HeldDirectoryCitation[]>((resolve) => {\n timer = setTimeout(() => resolve([]), remaining);\n });\n return Promise.race([\n source(execSql, organizationId).catch(() => []),\n deadline,\n ]).finally(() => clearTimeout(timer));\n}\n\nexport async function loadVerifiedManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n requestedLimit = KNOWN_MANIFEST_HINT_LIMIT,\n heldDirectories?: HeldDirectorySource,\n): Promise<HeldProjectionCitation[]> {\n const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));\n if (!(limit > 0)) return [];\n const loadGeneration = evictionGeneration;\n citationLoadsInFlight += 1;\n try {\n return await loadCitableManifestCitations(\n execSql,\n target,\n limit,\n heldDirectories,\n ).then((cited) =>\n cited.filter((citation) => citable(citation, loadGeneration)),\n );\n } finally {\n citationLoadsInFlight -= 1;\n if (citationLoadsInFlight === 0) evictedInGeneration.clear();\n }\n}\n\nasync function loadCitableManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n limit: number,\n heldDirectories: HeldDirectorySource | undefined,\n): Promise<HeldProjectionCitation[]> {\n const startedAt = performance.now();\n await ensureSqlTables(execSql, [\n ...verifiedManifestBundleTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...localIntentTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const objects = await citedObjects(db, target);\n const organizationId = await targetOrganization(db, target, objects);\n if (organizationId === null) return [];\n const { cited, damaged } = await collectVerifiedManifestCitations(\n db,\n organizationId,\n objects,\n target,\n limit,\n );\n if (damaged.length > 0)\n await dropVerifiedManifestBundles(execSql, damaged).catch(() => undefined);\n // Directories are cited beside the manifest quota, never in its place,\n // and read only after the manifest citations, with the time left.\n return [\n ...cited,\n ...(await directoriesBeforeDeadline(\n heldDirectories,\n execSql,\n organizationId,\n startedAt,\n )),\n ];\n}\n\n// Manifest hashes whose held rows a refused read is dropping: no read cites\n// them meanwhile, so none can be rebuilt from the bytes being dropped. Each\n// eviction also advances a generation, so a citation load that started\n// before it never returns the rows it read: they may already be gone.\nconst suppressedCitations = new Map<string, number>();\nconst evictedInGeneration = new Map<string, number>();\nlet evictionGeneration = 0;\n// Loads in flight; once none overlap, the eviction log has nothing to guard.\nlet citationLoadsInFlight = 0;\n\n/** Keeps these held bundles out of citations until the release runs. */\nexport function suppressHeldCitations(\n manifestHashes: readonly string[],\n): () => void {\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n suppressedCitations.set(hash, (suppressedCitations.get(hash) ?? 0) + 1);\n evictedInGeneration.set(hash, evictionGeneration);\n }\n return () => {\n // The drop is complete: a load that started before now may hold the\n // dropped bytes, so it is newer than none of them.\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n evictedInGeneration.set(hash, evictionGeneration);\n const count = (suppressedCitations.get(hash) ?? 1) - 1;\n if (count > 0) suppressedCitations.set(hash, count);\n else suppressedCitations.delete(hash);\n }\n };\n}\n\nfunction citable(\n citation: HeldProjectionCitation,\n loadGeneration: number,\n): boolean {\n if (!(\"manifestHash\" in citation)) return true;\n const { manifestHash } = citation;\n return (\n !suppressedCitations.has(manifestHash) &&\n (evictedInGeneration.get(manifestHash) ?? 0) <= loadGeneration\n );\n}\n\n/**\n * Drops the stored rows of held bundles a projection that cited them failed\n * to verify with, so the next read fetches them from the server. Only a row\n * still holding the exact bytes cited goes, so a newer verified copy written\n * meanwhile stays; nothing is dropped once `stillCurrent` turns false.\n * Resolves whether the drop committed.\n */\nexport async function dropHeldManifestBundles(\n execSql: ExecSql,\n heldBundles: readonly ServedAccessManifestBundleWireResponse[],\n stillCurrent?: () => boolean,\n): Promise<boolean> {\n if (heldBundles.length === 0) return true;\n const cited = await Promise.all(\n heldBundles.map(async (bundle) => ({\n manifestHash: bundle.manifestHash,\n bundleDigest: await sha256Hex(JSON.stringify(bundle)),\n })),\n );\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const drop = async (tx: ClientSQLiteTransactionScope) => {\n for (const row of cited)\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.manifestHash, row.manifestHash),\n eq(bundles.bundleDigest, row.bundleDigest),\n ),\n )\n .run();\n };\n if (!stillCurrent) {\n await runtime.transaction(drop, { behavior: \"immediate\" });\n return true;\n }\n const { committed } = await runtime.guardedTransaction(drop, stillCurrent, {\n behavior: \"immediate\",\n });\n return committed;\n}\n\n/** Drops damaged stored rows so no later read cites them. */\nasync function dropVerifiedManifestBundles(\n execSql: ExecSql,\n manifestHashes: readonly string[],\n): Promise<void> {\n if (manifestHashes.length === 0) return;\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n await getClientSQLitePersistenceRuntime(execSql).runMutation(\n async (handle) => {\n for (const batch of batches([...new Set(manifestHashes)]))\n await handle\n .delete(bundles)\n .where(inArray(bundles.manifestHash, batch))\n .run();\n },\n );\n}\n\n/** Cites from whichever database the signed-in identity currently uses. */\nexport function createVerifiedManifestCitations(\n resolveExecSql: () => ExecSql | null,\n heldDirectories?: HeldDirectorySource,\n): VerifiedManifestCitations {\n return {\n cite: async (target) => {\n const execSql = resolveExecSql();\n return execSql\n ? loadVerifiedManifestCitations(\n execSql,\n target,\n KNOWN_MANIFEST_HINT_LIMIT,\n heldDirectories,\n )\n : [];\n },\n };\n}\n\n/** Drops an organization's verified bundles when a remote reset forgets it. */\nexport async function deleteVerifiedManifestBundlesForOrganization(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n await tx\n .delete(bundles)\n .where(eq(bundles.organizationId, organizationId))\n .run();\n}\n"]}
@@ -26,6 +26,8 @@ export declare class ApiClient extends ApiClientAreas {
26
26
  } | null>;
27
27
  registerUser: (userId: string, organizationId: string, rootContainerId: string, signingPublicKey: Uint8Array, encapsulationPublicKey: Uint8Array, initialAdminGroup: import("../validators/request/index.js").RegistrationRequest["initialAdminGroup"], initialMemberGroup: import("../validators/request/index.js").RegistrationRequest["initialMemberGroup"], initialOrganizationPolicy: import("../validators/request/index.js").RegistrationRequest["initialOrganizationPolicy"], initialRootContainer: import("../validators/request/index.js").RegistrationRequest["initialRootContainer"], initialRootMetadataDocument: import("../validators/request/index.js").RegistrationRequest["initialRootMetadataDocument"], initialRosterProfileContainer: import("../validators/request/index.js").RegistrationRequest["initialRosterProfileContainer"], initialRosterProfileDocument: import("../validators/request/index.js").RegistrationRequest["initialRosterProfileDocument"], initialOrganizationMetadataContainer: import("../validators/request/index.js").RegistrationRequest["initialOrganizationMetadataContainer"], initialOrganizationProfileDocument?: import("../validators/request/index.js").RegistrationRequest["initialOrganizationProfileDocument"], initialSystemContainers?: import("../validators/request/index.js").RegistrationRequest["initialSystemContainers"]) => Promise<{
28
28
  challenge: string;
29
+ commitLsn: string | null;
30
+ commitLsnMode: "tracked" | "untracked";
29
31
  committedCoreMetadataUpdateIds: string[];
30
32
  committedProfileUpdateIds: string[];
31
33
  organizationId: string;
@@ -35,6 +35,8 @@ export declare class SessionArea {
35
35
  } | null>;
36
36
  registerUser(userId: string, organizationId: string, rootContainerId: string, signingPublicKey: Uint8Array, encapsulationPublicKey: Uint8Array, initialAdminGroup: RegistrationRequest["initialAdminGroup"], initialMemberGroup: RegistrationRequest["initialMemberGroup"], initialOrganizationPolicy: RegistrationRequest["initialOrganizationPolicy"], initialRootContainer: RegistrationRequest["initialRootContainer"], initialRootMetadataDocument: RegistrationRequest["initialRootMetadataDocument"], initialRosterProfileContainer: RegistrationRequest["initialRosterProfileContainer"], initialRosterProfileDocument: RegistrationRequest["initialRosterProfileDocument"], initialOrganizationMetadataContainer: RegistrationRequest["initialOrganizationMetadataContainer"], initialOrganizationProfileDocument?: RegistrationRequest["initialOrganizationProfileDocument"], initialSystemContainers?: RegistrationRequest["initialSystemContainers"]): Promise<{
37
37
  challenge: string;
38
+ commitLsn: string | null;
39
+ commitLsnMode: "tracked" | "untracked";
38
40
  committedCoreMetadataUpdateIds: string[];
39
41
  committedProfileUpdateIds: string[];
40
42
  organizationId: string;
@@ -0,0 +1,19 @@
1
+ import { type PrincipalStatePayloadResponse, type PrincipalStateResponse } from "../validators/response/index.js";
2
+ /**
3
+ * An organization directory payload a device holds, beside the signed state
4
+ * that commits its hash. Writer projections serve directory payloads as
5
+ * policy evidence; a request may cite a held one by state hash instead.
6
+ */
7
+ export interface HeldDirectoryCitation {
8
+ readonly directoryState: PrincipalStateResponse;
9
+ readonly directoryPayload: PrincipalStatePayloadResponse;
10
+ }
11
+ export declare function isHeldDirectoryCitation(value: unknown): value is HeldDirectoryCitation;
12
+ /**
13
+ * The payload when its organization state recomputes to its own hash and its
14
+ * bytes hash to the `payloadCiphertextHash` that state signs; null otherwise.
15
+ * The state hash commits that payload hash, so a cited payload is exactly the
16
+ * bytes the server would serve for that state, and verification of the
17
+ * rebuilt evidence decides as if they had travelled.
18
+ */
19
+ export declare function signedDirectoryPayload(citation: HeldDirectoryCitation): Promise<PrincipalStatePayloadResponse | null>;
@@ -0,0 +1,37 @@
1
+ import { computePrincipalStateHash, computePrincipalStatePayloadCiphertextHash, } from "../crypto/index.js";
2
+ import { isPrincipalStatePayloadResponse, isPrincipalStateResponse, } from "../validators/response/index.js";
3
+ import { isSha256HexString } from "../validators/util/index.js";
4
+ export function isHeldDirectoryCitation(value) {
5
+ return (typeof value === "object" &&
6
+ value !== null &&
7
+ isPrincipalStateResponse(Reflect.get(value, "directoryState")) &&
8
+ isPrincipalStatePayloadResponse(Reflect.get(value, "directoryPayload")));
9
+ }
10
+ /**
11
+ * The payload when its organization state recomputes to its own hash and its
12
+ * bytes hash to the `payloadCiphertextHash` that state signs; null otherwise.
13
+ * The state hash commits that payload hash, so a cited payload is exactly the
14
+ * bytes the server would serve for that state, and verification of the
15
+ * rebuilt evidence decides as if they had travelled.
16
+ */
17
+ export async function signedDirectoryPayload(citation) {
18
+ const { directoryState: state, directoryPayload: payload } = citation;
19
+ try {
20
+ if (state.principalType !== "organization" ||
21
+ payload.principalType !== "organization" ||
22
+ payload.principalId !== state.principalId ||
23
+ payload.stateHash !== state.stateHash ||
24
+ !isSha256HexString(state.stateHash) ||
25
+ (await computePrincipalStateHash(state)) !== state.stateHash)
26
+ return null;
27
+ const hash = await computePrincipalStatePayloadCiphertextHash(payload.ciphertext);
28
+ return hash === state.payloadCiphertextHash &&
29
+ hash === payload.ciphertextHash
30
+ ? payload
31
+ : null;
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ //# sourceMappingURL=heldDirectoryCitations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"heldDirectoryCitations.js","sourceRoot":"","sources":["heldDirectoryCitations.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,0CAA0C,GAC3C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,+BAA+B,EAC/B,wBAAwB,GAGzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAY/D,MAAM,UAAU,uBAAuB,CACrC,KAAc;IAEd,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,wBAAwB,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;QAC9D,+BAA+B,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC,CACxE,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,QAA+B;IAE/B,MAAM,EAAE,cAAc,EAAE,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,GAAG,QAAQ,CAAC;IACtE,IAAI,CAAC;QACH,IACE,KAAK,CAAC,aAAa,KAAK,cAAc;YACtC,OAAO,CAAC,aAAa,KAAK,cAAc;YACxC,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,WAAW;YACzC,OAAO,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS;YACrC,CAAC,iBAAiB,CAAC,KAAK,CAAC,SAAS,CAAC;YACnC,CAAC,MAAM,yBAAyB,CAAC,KAAK,CAAC,CAAC,KAAK,KAAK,CAAC,SAAS;YAE5D,OAAO,IAAI,CAAC;QACd,MAAM,IAAI,GAAG,MAAM,0CAA0C,CAC3D,OAAO,CAAC,UAAU,CACnB,CAAC;QACF,OAAO,IAAI,KAAK,KAAK,CAAC,qBAAqB;YACzC,IAAI,KAAK,OAAO,CAAC,cAAc;YAC/B,CAAC,CAAC,OAAO;YACT,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n computePrincipalStateHash,\n computePrincipalStatePayloadCiphertextHash,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalStatePayloadResponse,\n isPrincipalStateResponse,\n type PrincipalStatePayloadResponse,\n type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isSha256HexString } from \"@tearleads/validators/util\";\n\n/**\n * An organization directory payload a device holds, beside the signed state\n * that commits its hash. Writer projections serve directory payloads as\n * policy evidence; a request may cite a held one by state hash instead.\n */\nexport interface HeldDirectoryCitation {\n readonly directoryState: PrincipalStateResponse;\n readonly directoryPayload: PrincipalStatePayloadResponse;\n}\n\nexport function isHeldDirectoryCitation(\n value: unknown,\n): value is HeldDirectoryCitation {\n return (\n typeof value === \"object\" &&\n value !== null &&\n isPrincipalStateResponse(Reflect.get(value, \"directoryState\")) &&\n isPrincipalStatePayloadResponse(Reflect.get(value, \"directoryPayload\"))\n );\n}\n\n/**\n * The payload when its organization state recomputes to its own hash and its\n * bytes hash to the `payloadCiphertextHash` that state signs; null otherwise.\n * The state hash commits that payload hash, so a cited payload is exactly the\n * bytes the server would serve for that state, and verification of the\n * rebuilt evidence decides as if they had travelled.\n */\nexport async function signedDirectoryPayload(\n citation: HeldDirectoryCitation,\n): Promise<PrincipalStatePayloadResponse | null> {\n const { directoryState: state, directoryPayload: payload } = citation;\n try {\n if (\n state.principalType !== \"organization\" ||\n payload.principalType !== \"organization\" ||\n payload.principalId !== state.principalId ||\n payload.stateHash !== state.stateHash ||\n !isSha256HexString(state.stateHash) ||\n (await computePrincipalStateHash(state)) !== state.stateHash\n )\n return null;\n const hash = await computePrincipalStatePayloadCiphertextHash(\n payload.ciphertext,\n );\n return hash === state.payloadCiphertextHash &&\n hash === payload.ciphertextHash\n ? payload\n : null;\n } catch {\n return null;\n }\n}\n"]}
@@ -8,5 +8,5 @@ export type { ProjectionPolicyHistoryReadOptions } from "./projectionPolicyHisto
8
8
  export type { BlobBytesResponse, UploadMultipartBlobPartBytesRequest, } from "./routes/blobs/get.js";
9
9
  export { describeMultipartBlobPart } from "./routes/blobs/multipartUpload.js";
10
10
  export type { HttpMethod, ListDocumentEditAttributionRangesOptions, RequestFailure, RequestFailureKind, RequestResult, RequestResultOptions, RequestSuccess, } from "./types.js";
11
- export type { HeldProjectionCitation, VerifiedManifestCitations, WriterProjectionListing, WriterProjectionTarget, } from "./verifiedManifestCitations.js";
11
+ export type { HeldDirectoryCitation, HeldProjectionCitation, VerifiedManifestCitations, WriterProjectionListing, WriterProjectionTarget, } from "./verifiedManifestCitations.js";
12
12
  export { openServerEventsSocket } from "./webSocketTickets.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAGL,0BAA0B,GAC3B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAGL,iBAAiB,GAElB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,eAAe,GAGhB,MAAM,kBAAkB,CAAC;AAa1B,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAgB3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["export { ApiClient } from \"./ApiClient\";\nexport { AccountSuspendedError } from \"./accountSuspension\";\nexport {\n type ApiReachability,\n type ApiReachabilityProbe,\n createApiReachabilityProbe,\n} from \"./apiReachabilityProbe\";\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"./apiRequestMetrics\";\nexport {\n ApiNetworkError,\n type ApiNetworkFailureClass,\n type ApiNetworkFailureDetails,\n} from \"./networkFailure\";\nexport type {\n PrincipalPolicyDiscoveryOptions,\n PrincipalPolicyHeldHead,\n PrincipalPolicyPageCurrent,\n PrincipalPolicyPageReadOptions,\n PrincipalPolicyPageResume,\n} from \"./principalPolicyPages\";\nexport type { ProjectionPolicyHistoryReadOptions } from \"./projectionPolicyHistoryPages\";\nexport type {\n BlobBytesResponse,\n UploadMultipartBlobPartBytesRequest,\n} from \"./routes/blobs/get\";\nexport { describeMultipartBlobPart } from \"./routes/blobs/multipartUpload\";\nexport type {\n HttpMethod,\n ListDocumentEditAttributionRangesOptions,\n RequestFailure,\n RequestFailureKind,\n RequestResult,\n RequestResultOptions,\n RequestSuccess,\n} from \"./types\";\nexport type {\n HeldProjectionCitation,\n VerifiedManifestCitations,\n WriterProjectionListing,\n WriterProjectionTarget,\n} from \"./verifiedManifestCitations\";\nexport { openServerEventsSocket } from \"./webSocketTickets\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAGL,0BAA0B,GAC3B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAGL,iBAAiB,GAElB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,eAAe,GAGhB,MAAM,kBAAkB,CAAC;AAa1B,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAiB3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["export { ApiClient } from \"./ApiClient\";\nexport { AccountSuspendedError } from \"./accountSuspension\";\nexport {\n type ApiReachability,\n type ApiReachabilityProbe,\n createApiReachabilityProbe,\n} from \"./apiReachabilityProbe\";\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"./apiRequestMetrics\";\nexport {\n ApiNetworkError,\n type ApiNetworkFailureClass,\n type ApiNetworkFailureDetails,\n} from \"./networkFailure\";\nexport type {\n PrincipalPolicyDiscoveryOptions,\n PrincipalPolicyHeldHead,\n PrincipalPolicyPageCurrent,\n PrincipalPolicyPageReadOptions,\n PrincipalPolicyPageResume,\n} from \"./principalPolicyPages\";\nexport type { ProjectionPolicyHistoryReadOptions } from \"./projectionPolicyHistoryPages\";\nexport type {\n BlobBytesResponse,\n UploadMultipartBlobPartBytesRequest,\n} from \"./routes/blobs/get\";\nexport { describeMultipartBlobPart } from \"./routes/blobs/multipartUpload\";\nexport type {\n HttpMethod,\n ListDocumentEditAttributionRangesOptions,\n RequestFailure,\n RequestFailureKind,\n RequestResult,\n RequestResultOptions,\n RequestSuccess,\n} from \"./types\";\nexport type {\n HeldDirectoryCitation,\n HeldProjectionCitation,\n VerifiedManifestCitations,\n WriterProjectionListing,\n WriterProjectionTarget,\n} from \"./verifiedManifestCitations\";\nexport { openServerEventsSocket } from \"./webSocketTickets\";\n"]}