@tearleads/client-sdk 0.1.11 → 0.1.13

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 (141) hide show
  1. package/README.md +18 -2
  2. package/client/Tearleads.d.ts +4 -0
  3. package/client/Tearleads.js +5 -0
  4. package/client/Tearleads.js.map +1 -1
  5. package/client/index.d.ts +1 -0
  6. package/client/index.js.map +1 -1
  7. package/client/principalHistoryProtection.d.ts +19 -0
  8. package/client/principalHistoryProtection.js +76 -0
  9. package/client/principalHistoryProtection.js.map +1 -0
  10. package/client/workflowRuntime.d.ts +5 -0
  11. package/client/workflowRuntime.js +34 -5
  12. package/client/workflowRuntime.js.map +1 -1
  13. package/data/containers/shared/authorAccess.d.ts +2 -2
  14. package/data/containers/shared/authorAccess.js.map +1 -1
  15. package/data/containers/shared/heldContainerHeads.js.map +1 -1
  16. package/data/containers/shared/principalPolicies.js.map +1 -1
  17. package/data/containers/shared/types.d.ts +3 -2
  18. package/data/containers/shared/types.js.map +1 -1
  19. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
  20. package/data/keyingProjectionVerification/checkpointContext.d.ts +4 -3
  21. package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
  22. package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
  23. package/data/keyingProjectionVerification/containerPathVerification.js.map +1 -1
  24. package/data/keyingProjectionVerification/containerProjectionVerification.d.ts +4 -3
  25. package/data/keyingProjectionVerification/containerProjectionVerification.js.map +1 -1
  26. package/data/keyingProjectionVerification/documentManifestPolicies.js.map +1 -1
  27. package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
  28. package/data/keyingProjectionVerification/documentProjectionVerification.d.ts +3 -2
  29. package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
  30. package/data/keyingProjectionVerification/organizationFounderBinding.js +9 -4
  31. package/data/keyingProjectionVerification/organizationFounderBinding.js.map +1 -1
  32. package/data/keyingProjectionVerification/principalPolicyCache.js +3 -4
  33. package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
  34. package/data/keyingProjectionVerification/principalPolicyVerification.js +12 -2
  35. package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
  36. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +1 -1
  37. package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js +70 -0
  38. package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js.map +1 -0
  39. package/data/keyingProjectionVerification/types.d.ts +17 -2
  40. package/data/keyingProjectionVerification/types.js +12 -0
  41. package/data/keyingProjectionVerification/types.js.map +1 -1
  42. package/data/persistence/organizationFounderPersistence.js +3 -2
  43. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  44. package/data/persistence/principalHistoryEvidencePersistence.js +91 -0
  45. package/data/persistence/principalHistoryEvidencePersistence.js.map +1 -0
  46. package/data/persistence/principalHistoryPrefixPersistence.js +52 -0
  47. package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -0
  48. package/data/persistence/principalHistoryStagePersistence.js +9 -2
  49. package/data/persistence/principalHistoryStagePersistence.js.map +1 -1
  50. package/data/persistence/principalKeyEnvelopeCandidates.js +67 -0
  51. package/data/persistence/principalKeyEnvelopeCandidates.js.map +1 -0
  52. package/data/principals/principalHistoryPrefixProtection.js +29 -0
  53. package/data/principals/principalHistoryPrefixProtection.js.map +1 -0
  54. package/data/principals/principalHistoryProtection.d.ts +10 -0
  55. package/data/principals/principalHistoryProtection.js +14 -0
  56. package/data/principals/principalHistoryProtection.js.map +1 -0
  57. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  58. package/data/principals/principalPolicyCrypto.js +11 -21
  59. package/data/principals/principalPolicyCrypto.js.map +1 -1
  60. package/data/principals/principalPolicyEvidence.d.ts +4 -0
  61. package/data/principals/principalPolicyEvidence.js +12 -0
  62. package/data/principals/principalPolicyEvidence.js.map +1 -0
  63. package/data/sqlite/principalHistoryEvidenceSchema.js +46 -0
  64. package/data/sqlite/principalHistoryEvidenceSchema.js.map +1 -0
  65. package/data/sqlite/principalKeyFingerprintJson.js +9 -0
  66. package/data/sqlite/principalKeyFingerprintJson.js.map +1 -0
  67. package/data/sqlite/principalPolicySchema.js +4 -0
  68. package/data/sqlite/principalPolicySchema.js.map +1 -1
  69. package/data/sqlite/schema.d.ts +304 -0
  70. package/data/sqlite/schema.js +5 -0
  71. package/data/sqlite/schema.js.map +1 -1
  72. package/data/sqlite/sqlTableSchema.js +1 -1
  73. package/data/sqlite/sqlTableSchema.js.map +1 -1
  74. package/index.d.ts +3 -3
  75. package/index.js +1 -1
  76. package/index.js.map +1 -1
  77. package/internal/api-client/principalPolicyPages.d.ts +2 -0
  78. package/internal/api-client/principalPolicyPages.js +11 -2
  79. package/internal/api-client/principalPolicyPages.js.map +1 -1
  80. package/internal/crypto/index.d.ts +1 -1
  81. package/internal/crypto/index.js +1 -1
  82. package/internal/crypto/index.js.map +1 -1
  83. package/internal/crypto/keying/index.d.ts +1 -1
  84. package/internal/crypto/keying/index.js +1 -1
  85. package/internal/crypto/keying/index.js.map +1 -1
  86. package/internal/crypto/keying/principalPolicyHistoryIndex.d.ts +6 -2
  87. package/internal/crypto/keying/principalPolicyHistoryIndex.js +11 -5
  88. package/internal/crypto/keying/principalPolicyHistoryIndex.js.map +1 -1
  89. package/internal/crypto/keying/principalPolicyHistoryReferences.d.ts +2 -0
  90. package/internal/crypto/keying/principalPolicyHistoryReferences.js +19 -2
  91. package/internal/crypto/keying/principalPolicyHistoryReferences.js.map +1 -1
  92. package/package.json +1 -1
  93. package/workflows/containers/child/create.js.map +1 -1
  94. package/workflows/containers/child/move.js.map +1 -1
  95. package/workflows/containers/child/moveWraps.js.map +1 -1
  96. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  97. package/workflows/containers/child/recitePlan.js.map +1 -1
  98. package/workflows/containers/child/rekey.d.ts +3 -2
  99. package/workflows/containers/child/rekey.js.map +1 -1
  100. package/workflows/containers/child/revoke.d.ts +2 -2
  101. package/workflows/containers/child/revoke.js.map +1 -1
  102. package/workflows/containers/child/rotationPrincipalPolicies.js.map +1 -1
  103. package/workflows/containers/child/rotationWraps.js.map +1 -1
  104. package/workflows/containers/child/sharePlanCore.d.ts +11 -10
  105. package/workflows/containers/child/sharePlanCore.js.map +1 -1
  106. package/workflows/documents/linkSetAuthority.js.map +1 -1
  107. package/workflows/principals/index.d.ts +1 -0
  108. package/workflows/principals/index.js +1 -0
  109. package/workflows/principals/index.js.map +1 -1
  110. package/workflows/principals/principalHistoryRecoveryPrefix.js +65 -0
  111. package/workflows/principals/principalHistoryRecoveryPrefix.js.map +1 -0
  112. package/workflows/principals/principalHistoryRecoveryReferences.js +60 -0
  113. package/workflows/principals/principalHistoryRecoveryReferences.js.map +1 -0
  114. package/workflows/principals/principalHistoryRecoveryStage.js +38 -2
  115. package/workflows/principals/principalHistoryRecoveryStage.js.map +1 -1
  116. package/workflows/principals/principalHistoryRecoveryTypes.d.ts +9 -1
  117. package/workflows/principals/principalHistoryRecoveryTypes.js +7 -0
  118. package/workflows/principals/principalHistoryRecoveryTypes.js.map +1 -1
  119. package/workflows/principals/principalHistoryRecoveryVerification.js +24 -0
  120. package/workflows/principals/principalHistoryRecoveryVerification.js.map +1 -0
  121. package/workflows/principals/principalRecoveryDirectory.d.ts +10 -0
  122. package/workflows/principals/principalRecoveryDirectory.js +107 -0
  123. package/workflows/principals/principalRecoveryDirectory.js.map +1 -0
  124. package/workflows/principals/principalRecoveryMemo.js +46 -0
  125. package/workflows/principals/principalRecoveryMemo.js.map +1 -0
  126. package/workflows/principals/principalRecoveryOutage.js +40 -0
  127. package/workflows/principals/principalRecoveryOutage.js.map +1 -0
  128. package/workflows/principals/principalRecoveryQueue.js +22 -0
  129. package/workflows/principals/principalRecoveryQueue.js.map +1 -0
  130. package/workflows/principals/recoverPrincipalPolicyHistory.d.ts +1 -0
  131. package/workflows/principals/recoverPrincipalPolicyHistory.js +108 -36
  132. package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
  133. package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +13 -0
  134. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +150 -0
  135. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -0
  136. package/workflows/principals/runtimePolicyRecovery.js +65 -0
  137. package/workflows/principals/runtimePolicyRecovery.js.map +1 -0
  138. package/workflows/principals/runtimePolicyWarmer.js +5 -1
  139. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  140. package/workflows/sync/remoteResetPrincipalScope.js +10 -0
  141. package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
package/README.md CHANGED
@@ -71,8 +71,24 @@ without it, failing on errors in the SDK's declarations and ignoring those in
71
71
  drizzle-orm's and loro-crdt's own. It needs the network to install the
72
72
  consumer's dependencies.
73
73
 
74
- To publish by hand, run from the repository root with an account that owns
75
- the `@tearleads` npm scope:
74
+ Merging to `main` publishes. When `packages/client-sdk` changes there,
75
+ `.github/workflows/client-sdk-publish.yml` publishes the version in
76
+ `package.json` if it is newer than npm's `latest`, after running the smoke
77
+ script; a merge that leaves the version alone, a re-run, or a run that finishes
78
+ after a newer release succeeds without publishing
79
+ (`scripts/lib/npmPublishDecision.ts` makes that call). Because the package
80
+ ships the workspace packages above, `agent-tool.json` lists it under
81
+ `versions.bundles`: a change to any of them also bumps the SDK's version, so it
82
+ publishes too. The workflow authenticates with
83
+ [npm trusted publishing](https://docs.npmjs.com/trusted-publishers) and
84
+ attaches provenance to each version. On npmjs.com the package's trusted
85
+ publisher names the `a2f0` owner, the `tearleads` repository, the
86
+ `client-sdk-publish.yml` workflow, and the `npm` environment, which the
87
+ repository restricts to `main`. Renaming the workflow or the environment breaks
88
+ publishing until that setting matches.
89
+
90
+ To publish by hand instead, run from the repository root with an account that
91
+ owns the `@tearleads` npm scope:
76
92
 
77
93
  ```sh
78
94
  npm login --registry https://registry.npmjs.org
@@ -13,6 +13,7 @@ import { type Identity, type IdentityOptions } from "./identity.js";
13
13
  import { type Logger } from "./logger.js";
14
14
  import { Network } from "./network.js";
15
15
  import { type Organizations } from "./organizations/index.js";
16
+ import type { PrincipalHistoryKeyProvider } from "./principalHistoryProtection.js";
16
17
  import { type Root } from "./root/index.js";
17
18
  import { type SecurityIncidentListener, type SecurityIncidents } from "./securityIncidents.js";
18
19
  import type { Session } from "./session/sessionTypes.js";
@@ -43,6 +44,8 @@ export interface ClientOptions {
43
44
  * peer ids (e.g. the pane's local identity namespace). Omit for single-pane.
44
45
  */
45
46
  peerScope?: string | undefined;
47
+ /** Private host key for durable history progress; omitted uses disposable session keys. */
48
+ principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;
46
49
  /**
47
50
  * App-owned system containers born with every new organization (both
48
51
  * registration and additional-org creation provision them atomically in the
@@ -71,6 +74,7 @@ export declare class Tearleads {
71
74
  private readonly apiClient;
72
75
  private readonly documentProjectors;
73
76
  private readonly disposeSecurityIncidents;
77
+ private retirePrincipalHistoryProtection;
74
78
  private domainScopeKey;
75
79
  private domainScopeValue;
76
80
  private readonly logErrorHandler;
@@ -55,6 +55,7 @@ export class Tearleads {
55
55
  apiClient;
56
56
  documentProjectors;
57
57
  disposeSecurityIncidents;
58
+ retirePrincipalHistoryProtection = () => { };
58
59
  // Tracks the storage/identity pair that owns domain-scoped runtime state.
59
60
  domainScopeKey = null;
60
61
  // Recreated when the storage database or signing identity changes.
@@ -138,6 +139,8 @@ export class Tearleads {
138
139
  }
139
140
  /** Rebinds the session's trust callbacks once the runtime exists. */
140
141
  bindTrustedIdentityRuntime(runtime) {
142
+ this.retirePrincipalHistoryProtection =
143
+ runtime.retirePrincipalHistoryProtection;
141
144
  this.pinLocalUserIdentity = (userId, candidate) => runtime.pinLocalUserIdentity(userId, candidate);
142
145
  this.boundUserId = (signingKeyFingerprint) => runtime.boundUserId(signingKeyFingerprint);
143
146
  }
@@ -166,6 +169,7 @@ export class Tearleads {
166
169
  logError: this.logError,
167
170
  network: this.network,
168
171
  peerScope: options.peerScope ?? null,
172
+ principalHistoryKeyProvider: options.principalHistoryKeyProvider,
169
173
  reportSecurityIncident,
170
174
  session: this.session,
171
175
  syncBillingGate: this.syncBillingGate,
@@ -206,6 +210,7 @@ export class Tearleads {
206
210
  dispose() {
207
211
  const domainScope = this.domainScope;
208
212
  this.disposeSecurityIncidents();
213
+ this.retirePrincipalHistoryProtection();
209
214
  this.deviceFirst.dispose();
210
215
  disposeDomainSyncCoordinator(domainScope);
211
216
  }
@@ -1 +1 @@
1
- {"version":3,"file":"Tearleads.js","sourceRoot":"","sources":["Tearleads.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAElD,OAAO,EAGL,gCAAgC,GACjC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAoB,MAAM,qBAAqB,CAAC;AAE1E,OAAO,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAEzE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAyB,KAAK,EAAE,MAAM,SAAS,CAAC;AACvD,OAAO,EAEL,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAwB,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAoB,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,eAAe,EAAkB,MAAM,aAAa,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EACL,cAAc,GAGf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAe,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAsB,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EA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O;YACT,CAAC;YAED,IACE,IAAI,CAAC,+BAA+B;gBACpC,IAAI,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO,EAChC,CAAC;gBACD,OAAO;YACT,CAAC;YAED,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC,QAAQ;iBACjD,QAAQ,EAAE;iBACV,IAAI,CAAC,GAAG,EAAE;gBACT,IAAI,CAAC,uBAAuB,GAAG,IAAI,CAAC;gBACpC,wBAAwB,EAAE,CAAC;YAC7B,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACxB,IAAI,CAAC;oBACH,IAAI,CAAC,QAAQ,CAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;gBACjE,CAAC;gBAAC,MAAM,CAAC;oBACP,gFAAgF;gBAClF,CAAC;YACH,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACZ,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC;YAC9C,CAAC,CAAC,CAAC;QACP,CAAC,CAAC;QAEF,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;QAC9D,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACtD,CAAC;CACF","sourcesContent":["import { ApiClient } from \"@tearleads/api-client\";\nimport type { BlobStore } from \"../data/blobContracts\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../data/documents/documentKinds\";\nimport { createDomainScope, type DomainScope } from \"../data/domainScope\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { disposeDomainSyncCoordinator } from \"../data/sync/syncCoordinator\";\nimport { resolveIdentityTrustDomain } from \"../data/trustedUserIdentity\";\nimport type { ProvisionedSystemContainerSpec } from \"../workflows/registration\";\nimport { ApiVersion } from \"./apiVersion\";\nimport { type BlobStoreFactory, Blobs } from \"./blobs\";\nimport {\n type ContainerContents,\n createContainerContents,\n} from \"./containerContents\";\nimport { Database, type DatabaseOptions } from \"./database\";\nimport { createDeviceFirst, type DeviceFirst } from \"./deviceFirst\";\nimport { createDocuments, type Documents } from \"./documents\";\nimport { Events } from \"./events\";\nimport {\n createIdentity,\n type Identity,\n type IdentityOptions,\n} from \"./identity\";\nimport { type Logger, logErrorToConsole } from \"./logger\";\nimport { Network } from \"./network\";\nimport { createOrganizations, type Organizations } from \"./organizations\";\nimport { createRoot, type Root, rootRuntimeOf } from \"./root\";\nimport {\n createSecurityIncidentService,\n type SecurityIncidentListener,\n type SecurityIncidents,\n} from \"./securityIncidents\";\nimport { createSession } from \"./session\";\nimport type { Session } from \"./session/sessionTypes\";\nimport { SyncBillingGate } from \"./syncBillingGate\";\nimport { createUserIdentities, type UserIdentities } from \"./userIdentities\";\nimport {\n createRuntime,\n type InternalRuntime,\n type Runtime,\n} from \"./workflowRuntime\";\n\nfunction createClientSecurityIncidentService(input: {\n readonly apiBaseUrl: string;\n readonly database: Database;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly options: ClientOptions;\n}) {\n const identityTrustDomain = resolveIdentityTrustDomain({\n apiBaseUrl: input.apiBaseUrl,\n identityTrustDomain: input.options.identityTrustDomain,\n });\n return {\n identityTrustDomain,\n service: createSecurityIncidentService({\n database: input.database,\n logError: input.logError,\n onIncident: input.options.onSecurityIncident,\n trustDomain: identityTrustDomain,\n }),\n };\n}\n\nexport type ClientDatabaseOptions = Omit<DatabaseOptions, \"status\">;\n\nexport interface ClientOptions {\n apiBaseUrl?: string | undefined;\n blobStore?: BlobStore | undefined;\n blobStoreFactory?: BlobStoreFactory | undefined;\n database?: ClientDatabaseOptions | undefined;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n events?: ReadonlyArray<unknown> | undefined;\n identity?: IdentityOptions | undefined;\n /**\n * Absolute, host-controlled API namespace for durable user-identity pins.\n * Required only when apiBaseUrl is relative and no browser origin exists.\n */\n identityTrustDomain?: string | undefined;\n identityProvisioning?: \"auto\" | \"manual\" | undefined;\n logger?: Logger | undefined;\n online?: boolean | undefined;\n /** Called after a trust-boundary verification failure is durably recorded. */\n onSecurityIncident?: SecurityIncidentListener | undefined;\n /**\n * Per-pane discriminator so documents in distinct panes derive distinct Loro\n * peer ids (e.g. the pane's local identity namespace). Omit for single-pane.\n */\n peerScope?: string | undefined;\n /**\n * App-owned system containers born with every new organization (both\n * registration and additional-org creation provision them atomically in the\n * same server call), e.g. a trash bin. The app owns these because their slot\n * namespaces are app concepts the SDK stays agnostic to.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n}\n\nexport class Tearleads {\n readonly apiVersion = new ApiVersion();\n readonly 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 // 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 boundUserId: InternalRuntime[\"boundUserId\"] = async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n\n constructor(options: ClientOptions = {}) {\n const apiBaseUrl = options.apiBaseUrl ?? \"\";\n this.apiClient = new ApiClient(apiBaseUrl);\n this.blobs = new Blobs(options.blobStore, options.blobStoreFactory);\n this.database = new Database(options.database);\n this.documentProjectors = resolveDocumentProjectorRegistry(\n options.documentProjectors,\n );\n this.events = new Events(options.events, () =>\n this.apiClient.clearWriterProjectionCaches(),\n );\n this.logHandler = options.logger?.log ?? (() => undefined);\n this.logErrorHandler = options.logger?.logError ?? logErrorToConsole;\n const security = createClientSecurityIncidentService({\n apiBaseUrl,\n database: this.database,\n logError: this.logError,\n options,\n });\n this.securityIncidents = security.service.incidents;\n this.disposeSecurityIncidents = security.service.dispose;\n this.network = new Network(options.online);\n this.syncBillingGate = new SyncBillingGate();\n let session: Session | null = null;\n this.identity = createIdentity(\n options.identity,\n (signingFingerprint) =>\n this.blobs.updateIdentityNamespace(signingFingerprint),\n this.log,\n {\n bootstrapLocalRootContainer: async () => {\n if (this.database.status !== \"ready\") {\n throw new Error(\n \"identity.generate requires a ready SQLite database.\",\n );\n }\n if (!session) {\n throw new Error(\n \"identity.generate requires an initialized session.\",\n );\n }\n\n return session.bootstrapLocalRootContainer();\n },\n getUserId: () => session?.userId ?? null,\n },\n );\n session = createSession({\n api: this.apiClient,\n database: this.database,\n documentProjectors: this.documentProjectors,\n identity: this.identity,\n log: this.log,\n logError: this.logError,\n boundUserIdForSigningKey: (signingKeyFingerprint) =>\n this.boundUserId(signingKeyFingerprint),\n onUserIdentityAvailable: (userId, candidate) =>\n this.pinLocalUserIdentity(userId, candidate),\n provisionedSystemContainers: options.provisionedSystemContainers,\n reportSecurityIncident: security.service.report,\n });\n this.session = session;\n const runtime = this.createWorkflowRuntime(\n security.identityTrustDomain,\n options,\n security.service.report,\n );\n this.bindTrustedIdentityRuntime(runtime);\n this.runtime = runtime.publicRuntime;\n this.documents = createDocuments({\n getDefaultContainerId: () => this.session.containerId,\n runtime,\n });\n this.containerContents = createContainerContents(runtime);\n this.deviceFirst = createDeviceFirst(runtime, this.containerContents);\n this.organizations = createOrganizations(runtime, this.containerContents);\n this.root = createRoot(rootRuntimeOf(runtime, this.session));\n this.userIdentities = createUserIdentities({\n log: this.log,\n resolveTrustedUserIdentity: (userId) =>\n runtime.workflowInput().resolveTrustedUserIdentity(userId),\n });\n\n this.configureApiClientCallbacks();\n\n if (options.identityProvisioning === \"auto\") {\n this.startAutomaticIdentityProvisioning();\n }\n }\n\n /** Rebinds the session's trust callbacks once the runtime exists. */\n private bindTrustedIdentityRuntime(runtime: InternalRuntime): void {\n this.pinLocalUserIdentity = (userId, candidate) =>\n runtime.pinLocalUserIdentity(userId, candidate);\n this.boundUserId = (signingKeyFingerprint) =>\n runtime.boundUserId(signingKeyFingerprint);\n }\n\n private configureApiClientCallbacks(): void {\n this.apiClient.setOnError((message) => this.logError(message));\n // An authoritative host source owns connectivity. Without one, request\n // outcomes remain reachability hints. Browser and native app bindings both\n // install authoritative sources so a backend outage cannot stop retries.\n this.apiClient.setOnNetworkError(() =>\n this.network.reportReachability(false),\n );\n this.apiClient.setOnNetworkSuccess(() =>\n this.network.reportReachability(true),\n );\n this.apiClient.setOnApiVersion((version) =>\n this.apiVersion.observe(version),\n );\n this.apiClient.setOnSessionExpired(() => this.loginAfterSessionExpired());\n this.apiClient.setOnPaymentRequired((organizationId) =>\n this.syncBillingGate.notifyPaymentRequired(organizationId),\n );\n }\n\n private createWorkflowRuntime(\n identityTrustDomain: string | null,\n options: ClientOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): InternalRuntime {\n return createRuntime({\n api: this.apiClient,\n blobs: this.blobs,\n database: this.database,\n documentProjectors: this.documentProjectors,\n events: this.events,\n getDomainScope: () => this.domainScope,\n identity: this.identity,\n identityTrustDomain,\n log: this.log,\n logError: this.logError,\n network: this.network,\n peerScope: options.peerScope ?? null,\n 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 * Mint a single-use ticket to authenticate the server-events websocket\n * handshake (which cannot carry the bearer header). Returns null when no\n * session is active. The caller appends it to the websocket URL.\n */\n requestWebSocketTicket(): Promise<string | null> {\n return this.apiClient.requestWebSocketTicket();\n }\n\n get domainScope(): DomainScope {\n const nextScopeKey = JSON.stringify([\n this.database.id,\n this.identity.signingFingerprint,\n ]);\n if (this.domainScopeKey !== nextScopeKey) {\n this.domainScopeKey = nextScopeKey;\n this.domainScopeValue = createDomainScope();\n }\n\n return this.domainScopeValue;\n }\n\n /**\n * Tear down background work for the active domain scope: stop the reconciler\n * and force-stop the sync coordinator pump, then drop the coordinator from\n * its registry. Hosts call this from unmount/cleanup so a pump cannot outlive\n * the React tree that created it. A later access for the same scope rebuilds\n * fresh state.\n */\n dispose(): void {\n const domainScope = this.domainScope;\n this.disposeSecurityIncidents();\n this.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 this.expiredSessionLoginPromise ??= this.session.login().finally(() => {\n this.expiredSessionLoginPromise = null;\n });\n return this.expiredSessionLoginPromise;\n }\n\n private startAutomaticIdentityProvisioning(): void {\n let unsubscribe: (() => void) | null = null;\n const stopProvisioningListener = () => {\n unsubscribe?.();\n unsubscribe = null;\n };\n const maybeProvisionIdentity = () => {\n if (this.autoIdentityProvisioned || this.identity.signingKeyPair) {\n stopProvisioningListener();\n return;\n }\n\n if (\n this.autoIdentityProvisioningPromise ||\n this.database.status !== \"ready\"\n ) {\n return;\n }\n\n this.autoIdentityProvisioningPromise = this.identity\n .generate()\n .then(() => {\n this.autoIdentityProvisioned = true;\n stopProvisioningListener();\n })\n .catch((error: unknown) => {\n try {\n this.logError(\"Automatic identity provisioning failed\", error);\n } catch {\n // Keep background provisioning failures from surfacing as unhandled rejections.\n }\n })\n .finally(() => {\n this.autoIdentityProvisioningPromise = null;\n });\n };\n\n unsubscribe = this.database.subscribe(maybeProvisionIdentity);\n void Promise.resolve().then(maybeProvisionIdentity);\n }\n}\n"]}
1
+ {"version":3,"file":"Tearleads.js","sourceRoot":"","sources":["Tearleads.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAElD,OAAO,EAGL,gCAAgC,GACjC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAoB,MAAM,qBAAqB,CAAC;AAE1E,OAAO,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAEzE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAyB,KAAK,EAAE,MAAM,SAAS,CAAC;AACvD,OAAO,EAEL,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAwB,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAoB,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,eAAe,EAAkB,MAAM,aAAa,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EACL,cAAc,GAGf,MAAM,YAAY,CAAC;AACpB,OAAO,EAAe,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAsB,MAAM,iBAAiB,CAAC;AAE1E,OAAO,EAAE,UAAU,EAAa,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC9D,OAAO,EACL,6BAA6B,GAG9B,MAAM,qBAAqB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uBAAuB,IAAI,IAAI,CAAC,QAAQ,CAAC,cAAc,EAAE,CAAC;gBACjE,wBAAwB,EAAE,CAAC;gBAC3B,OAAO;YACT,CAAC;YAED,IACE,IAAI,CAAC,+BAA+B;gBACpC,IAAI,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO,EAChC,CAAC;gBACD,OAAO;YACT,CAAC;YAED,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC,QAAQ;iBACjD,QAAQ,EAAE;iBACV,IAAI,CAAC,GAAG,EAAE;gBACT,IAAI,CAAC,uBAAuB,GAAG,IAAI,CAAC;gBACpC,wBAAwB,EAAE,CAAC;YAC7B,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACxB,IAAI,CAAC;oBACH,IAAI,CAAC,QAAQ,CAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;gBACjE,CAAC;gBAAC,MAAM,CAAC;oBACP,gFAAgF;gBAClF,CAAC;YACH,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACZ,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC;YAC9C,CAAC,CAAC,CAAC;QACP,CAAC,CAAC;QAEF,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;QAC9D,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACtD,CAAC;CACF","sourcesContent":["import { ApiClient } from \"@tearleads/api-client\";\nimport type { BlobStore } from \"../data/blobContracts\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../data/documents/documentKinds\";\nimport { createDomainScope, type DomainScope } from \"../data/domainScope\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { disposeDomainSyncCoordinator } from \"../data/sync/syncCoordinator\";\nimport { resolveIdentityTrustDomain } from \"../data/trustedUserIdentity\";\nimport type { ProvisionedSystemContainerSpec } from \"../workflows/registration\";\nimport { ApiVersion } from \"./apiVersion\";\nimport { type BlobStoreFactory, Blobs } from \"./blobs\";\nimport {\n type ContainerContents,\n createContainerContents,\n} from \"./containerContents\";\nimport { Database, type DatabaseOptions } from \"./database\";\nimport { createDeviceFirst, type DeviceFirst } from \"./deviceFirst\";\nimport { createDocuments, type Documents } from \"./documents\";\nimport { Events } from \"./events\";\nimport {\n createIdentity,\n type Identity,\n type IdentityOptions,\n} from \"./identity\";\nimport { type Logger, logErrorToConsole } from \"./logger\";\nimport { Network } from \"./network\";\nimport { createOrganizations, type Organizations } from \"./organizations\";\nimport type { PrincipalHistoryKeyProvider } from \"./principalHistoryProtection\";\nimport { createRoot, type Root, rootRuntimeOf } from \"./root\";\nimport {\n createSecurityIncidentService,\n type SecurityIncidentListener,\n type SecurityIncidents,\n} from \"./securityIncidents\";\nimport { createSession } from \"./session\";\nimport type { Session } from \"./session/sessionTypes\";\nimport { SyncBillingGate } from \"./syncBillingGate\";\nimport { createUserIdentities, type UserIdentities } from \"./userIdentities\";\nimport {\n createRuntime,\n type InternalRuntime,\n type Runtime,\n} from \"./workflowRuntime\";\n\nfunction createClientSecurityIncidentService(input: {\n readonly apiBaseUrl: string;\n readonly database: Database;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly options: ClientOptions;\n}) {\n const identityTrustDomain = resolveIdentityTrustDomain({\n apiBaseUrl: input.apiBaseUrl,\n identityTrustDomain: input.options.identityTrustDomain,\n });\n return {\n identityTrustDomain,\n service: createSecurityIncidentService({\n database: input.database,\n logError: input.logError,\n onIncident: input.options.onSecurityIncident,\n trustDomain: identityTrustDomain,\n }),\n };\n}\n\nexport type ClientDatabaseOptions = Omit<DatabaseOptions, \"status\">;\n\nexport interface ClientOptions {\n apiBaseUrl?: string | undefined;\n blobStore?: BlobStore | undefined;\n blobStoreFactory?: BlobStoreFactory | undefined;\n database?: ClientDatabaseOptions | undefined;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n events?: ReadonlyArray<unknown> | undefined;\n identity?: IdentityOptions | undefined;\n /**\n * Absolute, host-controlled API namespace for durable user-identity pins.\n * Required only when apiBaseUrl is relative and no browser origin exists.\n */\n identityTrustDomain?: string | undefined;\n identityProvisioning?: \"auto\" | \"manual\" | undefined;\n logger?: Logger | undefined;\n online?: boolean | undefined;\n /** Called after a trust-boundary verification failure is durably recorded. */\n onSecurityIncident?: SecurityIncidentListener | undefined;\n /**\n * Per-pane discriminator so documents in distinct panes derive distinct Loro\n * peer ids (e.g. the pane's local identity namespace). Omit for single-pane.\n */\n peerScope?: string | undefined;\n /** Private host key for durable history progress; omitted uses disposable session keys. */\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n /**\n * App-owned system containers born with every new organization (both\n * registration and additional-org creation provision them atomically in the\n * same server call), e.g. a trash bin. The app owns these because their slot\n * namespaces are app concepts the SDK stays agnostic to.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n}\n\nexport class Tearleads {\n readonly apiVersion = new ApiVersion();\n readonly 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 boundUserId: InternalRuntime[\"boundUserId\"] = async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n\n constructor(options: ClientOptions = {}) {\n const apiBaseUrl = options.apiBaseUrl ?? \"\";\n this.apiClient = new ApiClient(apiBaseUrl);\n this.blobs = new Blobs(options.blobStore, options.blobStoreFactory);\n this.database = new Database(options.database);\n this.documentProjectors = resolveDocumentProjectorRegistry(\n options.documentProjectors,\n );\n this.events = new Events(options.events, () =>\n this.apiClient.clearWriterProjectionCaches(),\n );\n this.logHandler = options.logger?.log ?? (() => undefined);\n this.logErrorHandler = options.logger?.logError ?? logErrorToConsole;\n const security = createClientSecurityIncidentService({\n apiBaseUrl,\n database: this.database,\n logError: this.logError,\n options,\n });\n this.securityIncidents = security.service.incidents;\n this.disposeSecurityIncidents = security.service.dispose;\n this.network = new Network(options.online);\n this.syncBillingGate = new SyncBillingGate();\n let session: Session | null = null;\n this.identity = createIdentity(\n options.identity,\n (signingFingerprint) =>\n this.blobs.updateIdentityNamespace(signingFingerprint),\n this.log,\n {\n bootstrapLocalRootContainer: async () => {\n if (this.database.status !== \"ready\") {\n throw new Error(\n \"identity.generate requires a ready SQLite database.\",\n );\n }\n if (!session) {\n throw new Error(\n \"identity.generate requires an initialized session.\",\n );\n }\n\n return session.bootstrapLocalRootContainer();\n },\n getUserId: () => session?.userId ?? null,\n },\n );\n session = createSession({\n api: this.apiClient,\n database: this.database,\n documentProjectors: this.documentProjectors,\n identity: this.identity,\n log: this.log,\n logError: this.logError,\n boundUserIdForSigningKey: (signingKeyFingerprint) =>\n this.boundUserId(signingKeyFingerprint),\n onUserIdentityAvailable: (userId, candidate) =>\n this.pinLocalUserIdentity(userId, candidate),\n provisionedSystemContainers: options.provisionedSystemContainers,\n reportSecurityIncident: security.service.report,\n });\n this.session = session;\n const runtime = this.createWorkflowRuntime(\n security.identityTrustDomain,\n options,\n security.service.report,\n );\n this.bindTrustedIdentityRuntime(runtime);\n this.runtime = runtime.publicRuntime;\n this.documents = createDocuments({\n getDefaultContainerId: () => this.session.containerId,\n runtime,\n });\n this.containerContents = createContainerContents(runtime);\n this.deviceFirst = createDeviceFirst(runtime, this.containerContents);\n this.organizations = createOrganizations(runtime, this.containerContents);\n this.root = createRoot(rootRuntimeOf(runtime, this.session));\n this.userIdentities = createUserIdentities({\n log: this.log,\n resolveTrustedUserIdentity: (userId) =>\n runtime.workflowInput().resolveTrustedUserIdentity(userId),\n });\n\n this.configureApiClientCallbacks();\n\n if (options.identityProvisioning === \"auto\") {\n this.startAutomaticIdentityProvisioning();\n }\n }\n\n /** 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.boundUserId = (signingKeyFingerprint) =>\n runtime.boundUserId(signingKeyFingerprint);\n }\n\n private configureApiClientCallbacks(): void {\n this.apiClient.setOnError((message) => this.logError(message));\n // An authoritative host source owns connectivity. Without one, request\n // outcomes remain reachability hints. Browser and native app bindings both\n // install authoritative sources so a backend outage cannot stop retries.\n this.apiClient.setOnNetworkError(() =>\n this.network.reportReachability(false),\n );\n this.apiClient.setOnNetworkSuccess(() =>\n this.network.reportReachability(true),\n );\n this.apiClient.setOnApiVersion((version) =>\n this.apiVersion.observe(version),\n );\n this.apiClient.setOnSessionExpired(() => this.loginAfterSessionExpired());\n this.apiClient.setOnPaymentRequired((organizationId) =>\n this.syncBillingGate.notifyPaymentRequired(organizationId),\n );\n }\n\n private createWorkflowRuntime(\n identityTrustDomain: string | null,\n options: ClientOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): InternalRuntime {\n return createRuntime({\n api: this.apiClient,\n blobs: this.blobs,\n database: this.database,\n documentProjectors: this.documentProjectors,\n events: this.events,\n getDomainScope: () => this.domainScope,\n identity: this.identity,\n identityTrustDomain,\n log: this.log,\n logError: this.logError,\n network: this.network,\n peerScope: options.peerScope ?? null,\n principalHistoryKeyProvider: options.principalHistoryKeyProvider,\n 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 * Mint a single-use ticket to authenticate the server-events websocket\n * handshake (which cannot carry the bearer header). Returns null when no\n * session is active. The caller appends it to the websocket URL.\n */\n requestWebSocketTicket(): Promise<string | null> {\n return this.apiClient.requestWebSocketTicket();\n }\n\n get domainScope(): DomainScope {\n const nextScopeKey = JSON.stringify([\n this.database.id,\n this.identity.signingFingerprint,\n ]);\n if (this.domainScopeKey !== nextScopeKey) {\n this.domainScopeKey = nextScopeKey;\n this.domainScopeValue = createDomainScope();\n }\n\n return this.domainScopeValue;\n }\n\n /**\n * Tear down background work for the active domain scope: stop the reconciler\n * and force-stop the sync coordinator pump, then drop the coordinator from\n * its registry. Hosts call this from unmount/cleanup so a pump cannot outlive\n * the React tree that created it. A later access for the same scope rebuilds\n * fresh state.\n */\n dispose(): void {\n const domainScope = this.domainScope;\n this.disposeSecurityIncidents();\n this.retirePrincipalHistoryProtection();\n this.deviceFirst.dispose();\n disposeDomainSyncCoordinator(domainScope);\n }\n\n private loginAfterSessionExpired(): Promise<boolean> {\n if (!this.session.authToken || !this.identity.signingKeyPair) {\n this.session.logout();\n return Promise.resolve(false);\n }\n\n this.expiredSessionLoginPromise ??= this.session.login().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"]}
package/client/index.d.ts CHANGED
@@ -21,6 +21,7 @@ export { createPinCodeBrowserLocalKeyring, createPinCodeWrappingKeyKeystore, isP
21
21
  export type { Logger } from "./logger.js";
22
22
  export { createBrowserNetworkStatusSource, Network, type NetworkListener, type NetworkMode, type NetworkStatusSource, } from "./network.js";
23
23
  export type { AddOrganizationGroupUserInput, ImportedOrganizationUser, LocalOrganizationSummary, OrganizationBilling, OrganizationBillingHistory, OrganizationBillingHistoryEntry, OrganizationBillingManagementUrl, OrganizationBillingView, OrganizationContainerGrant, OrganizationContainerGrants, OrganizationDataUsage, OrganizationDirectory, OrganizationDirectoryAndGroups, OrganizationDirectoryUser, OrganizationGrantRef, OrganizationGroupContainer, OrganizationGroupContainers, OrganizationGroupDetails, OrganizationGroupMember, OrganizationGroupMembers, OrganizationGroupPolicyHistory, OrganizationGroupSummary, OrganizationPolicyGrantChange, OrganizationPolicyGroupChange, OrganizationPolicyHistory, OrganizationPolicyHistoryEntry, OrganizationProfile, Organizations, OrganizationUserDetail, RemoveOrganizationGroupUserInput, } from "./organizations/index.js";
24
+ export type { PrincipalHistoryKeyProvider, PrincipalHistoryKeyScope, } from "./principalHistoryProtection.js";
24
25
  export type { SecurityIncident, SecurityIncidentListener, SecurityIncidentObjectKind, SecurityIncidents, } from "./securityIncidents.js";
25
26
  export { PurgedOrganizationRecoveryBillingRequiredError } from "./session/sessionRecoveryErrors.js";
26
27
  export type { CreateOrganizationOptions, Session, SessionContext, SessionCreateOrganizationResult, SessionListener, SessionRecoverOrganizationResult, SessionRegistrationRefusal, SessionRegistrationResult, SessionSnapshot, UserSession, } from "./session/sessionTypes.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAoB,MAAM,qBAAqB,CAAC;AAK1E,OAAO,EACL,8BAA8B,GAE/B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,+BAA+B,EAK/B,8BAA8B,GAC/B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,yBAAyB,EACzB,0BAA0B,EAC1B,oBAAoB,EACpB,yBAAyB,EACzB,sBAAsB,EACtB,4BAA4B,EAC5B,4BAA4B,EAE5B,yBAAyB,GAO1B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAyB,KAAK,EAAE,MAAM,SAAS,CAAC;AAgDvD,OAAO,EAAE,sCAAsC,EAAE,MAAM,qBAAqB,CAAC;AAC7E,OAAO,EACL,QAAQ,GAKT,MAAM,YAAY,CAAC;AAuBpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EACL,MAAM,GAGP,MAAM,UAAU,CAAC;AASlB,OAAO,EACL,2BAA2B,GAE5B,MAAM,sBAAsB,CAAC;AAyB9B,OAAO,EACL,yBAAyB,EACzB,sCAAsC,EACtC,wCAAwC,EACxC,kCAAkC,EAClC,kBAAkB,EAClB,2CAA2C,EAC3C,qCAAqC,EACrC,+BAA+B,EAC/B,yBAAyB,EACzB,2BAA2B,EAC3B,2BAA2B,EAC3B,6BAA6B,EAC7B,oBAAoB,EACpB,0BAA0B,EAC1B,yBAAyB,EACzB,6BAA6B,EAC7B,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AAMxB,OAAO,EACL,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,GACpC,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EACL,gCAAgC,EAChC,OAAO,GAIR,MAAM,WAAW,CAAC;AAuCnB,OAAO,EAAE,8CAA8C,EAAE,MAAM,iCAAiC,CAAC;AAajG,OAAO,EACL,eAAe,GAEhB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,SAAS,GACV,MAAM,aAAa,CAAC","sourcesContent":["export { createDomainScope, type DomainScope } from \"../data/domainScope\";\nexport type {\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n} from \"../stores/local-projection\";\nexport {\n enqueueReconciliationForEvents,\n type ReconciliationService,\n} from \"../sync/reconciliation\";\nexport {\n createUnavailableDirectCheckout,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n} from \"./billing/directCheckout\";\nexport {\n createRevenueCatPurchases,\n createUnavailablePurchases,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n} from \"./billing/purchases\";\nexport { type BlobStoreFactory, Blobs } from \"./blobs\";\nexport type {\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentInfo,\n DocumentInfoInput,\n LinkDocumentToContainerInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n PurgeDocumentInput,\n PurgeDocumentResult,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n} from \"./containerContents\";\nexport { createContainerDocumentObjectSyncState } from \"./containerContents\";\nexport {\n Database,\n type DatabaseListener,\n type DatabaseOptions,\n type DatabaseSnapshot,\n type DatabaseStatus,\n} from \"./database\";\nexport type {\n DeviceFirst,\n DeviceFirstContainerContents,\n LocalProjectionView,\n} from \"./deviceFirst\";\nexport type {\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentContextValue,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n ListDocumentsInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n PersistedDocumentListener,\n} from \"./documents\";\nexport { DEFAULT_DOCUMENT_ID } from \"./documents\";\nexport {\n Events,\n type EventsListener,\n type EventsSnapshot,\n} from \"./events\";\nexport type { FileSaver, SaveFileRequest } from \"./fileSaver\";\nexport type {\n Identity,\n IdentityGenerationResult,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n} from \"./identity\";\nexport {\n IDENTITY_KEY_PACKAGE_FORMAT,\n type IdentityKeyPackage,\n} from \"./identityKeyPackage\";\nexport type {\n BrowserLocalKeyringOptions,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n NormalizedLocalKeyringScope,\n UnwrapLocalSecretInput,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./localKeyring\";\nexport {\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createWebViewLocalKeyring,\n decodeLocalKeyringSqliteKey,\n encodeLocalKeyringSqliteKey,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n normalizeLocalKeyringScope,\n parseLocalKeyringManifest,\n serializeLocalKeyringManifest,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./localKeyring\";\nexport type {\n LocalKeyringPinCode,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n} from \"./localKeyring/localKeyringPinCode\";\nexport {\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n isPinCodeWrappedLocalSecretEnvelope,\n} from \"./localKeyring/localKeyringPinCode\";\nexport type { Logger } from \"./logger\";\nexport {\n createBrowserNetworkStatusSource,\n Network,\n type NetworkListener,\n type NetworkMode,\n type NetworkStatusSource,\n} from \"./network\";\nexport type {\n AddOrganizationGroupUserInput,\n ImportedOrganizationUser,\n LocalOrganizationSummary,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n Organizations,\n OrganizationUserDetail,\n RemoveOrganizationGroupUserInput,\n} from \"./organizations\";\nexport type {\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n} from \"./securityIncidents\";\nexport { PurgedOrganizationRecoveryBillingRequiredError } from \"./session/sessionRecoveryErrors\";\nexport type {\n CreateOrganizationOptions,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n UserSession,\n} from \"./session/sessionTypes\";\nexport {\n SyncBillingGate,\n type SyncBillingGateListener,\n} from \"./syncBillingGate\";\nexport {\n type ClientDatabaseOptions,\n type ClientOptions,\n Tearleads,\n} from \"./Tearleads\";\nexport type {\n ResolvedUserIdentity,\n UserIdentities,\n} from \"./userIdentities\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAoB,MAAM,qBAAqB,CAAC;AAK1E,OAAO,EACL,8BAA8B,GAE/B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,+BAA+B,EAK/B,8BAA8B,GAC/B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,yBAAyB,EACzB,0BAA0B,EAC1B,oBAAoB,EACpB,yBAAyB,EACzB,sBAAsB,EACtB,4BAA4B,EAC5B,4BAA4B,EAE5B,yBAAyB,GAO1B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAyB,KAAK,EAAE,MAAM,SAAS,CAAC;AAgDvD,OAAO,EAAE,sCAAsC,EAAE,MAAM,qBAAqB,CAAC;AAC7E,OAAO,EACL,QAAQ,GAKT,MAAM,YAAY,CAAC;AAuBpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EACL,MAAM,GAGP,MAAM,UAAU,CAAC;AASlB,OAAO,EACL,2BAA2B,GAE5B,MAAM,sBAAsB,CAAC;AAyB9B,OAAO,EACL,yBAAyB,EACzB,sCAAsC,EACtC,wCAAwC,EACxC,kCAAkC,EAClC,kBAAkB,EAClB,2CAA2C,EAC3C,qCAAqC,EACrC,+BAA+B,EAC/B,yBAAyB,EACzB,2BAA2B,EAC3B,2BAA2B,EAC3B,6BAA6B,EAC7B,oBAAoB,EACpB,0BAA0B,EAC1B,yBAAyB,EACzB,6BAA6B,EAC7B,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AAMxB,OAAO,EACL,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,GACpC,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EACL,gCAAgC,EAChC,OAAO,GAIR,MAAM,WAAW,CAAC;AA2CnB,OAAO,EAAE,8CAA8C,EAAE,MAAM,iCAAiC,CAAC;AAajG,OAAO,EACL,eAAe,GAEhB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,SAAS,GACV,MAAM,aAAa,CAAC","sourcesContent":["export { createDomainScope, type DomainScope } from \"../data/domainScope\";\nexport type {\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n} from \"../stores/local-projection\";\nexport {\n enqueueReconciliationForEvents,\n type ReconciliationService,\n} from \"../sync/reconciliation\";\nexport {\n createUnavailableDirectCheckout,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n} from \"./billing/directCheckout\";\nexport {\n createRevenueCatPurchases,\n createUnavailablePurchases,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n} from \"./billing/purchases\";\nexport { type BlobStoreFactory, Blobs } from \"./blobs\";\nexport type {\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentInfo,\n DocumentInfoInput,\n LinkDocumentToContainerInput,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n OpenContainerDocumentInput,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n PurgeDocumentInput,\n PurgeDocumentResult,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n} from \"./containerContents\";\nexport { createContainerDocumentObjectSyncState } from \"./containerContents\";\nexport {\n Database,\n type DatabaseListener,\n type DatabaseOptions,\n type DatabaseSnapshot,\n type DatabaseStatus,\n} from \"./database\";\nexport type {\n DeviceFirst,\n DeviceFirstContainerContents,\n LocalProjectionView,\n} from \"./deviceFirst\";\nexport type {\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentContextValue,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n ListDocumentsInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n PersistedDocumentListener,\n} from \"./documents\";\nexport { DEFAULT_DOCUMENT_ID } from \"./documents\";\nexport {\n Events,\n type EventsListener,\n type EventsSnapshot,\n} from \"./events\";\nexport type { FileSaver, SaveFileRequest } from \"./fileSaver\";\nexport type {\n Identity,\n IdentityGenerationResult,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n} from \"./identity\";\nexport {\n IDENTITY_KEY_PACKAGE_FORMAT,\n type IdentityKeyPackage,\n} from \"./identityKeyPackage\";\nexport type {\n BrowserLocalKeyringOptions,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n NormalizedLocalKeyringScope,\n UnwrapLocalSecretInput,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./localKeyring\";\nexport {\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createWebViewLocalKeyring,\n decodeLocalKeyringSqliteKey,\n encodeLocalKeyringSqliteKey,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n normalizeLocalKeyringScope,\n parseLocalKeyringManifest,\n serializeLocalKeyringManifest,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./localKeyring\";\nexport type {\n LocalKeyringPinCode,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n} from \"./localKeyring/localKeyringPinCode\";\nexport {\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n isPinCodeWrappedLocalSecretEnvelope,\n} from \"./localKeyring/localKeyringPinCode\";\nexport type { Logger } from \"./logger\";\nexport {\n createBrowserNetworkStatusSource,\n Network,\n type NetworkListener,\n type NetworkMode,\n type NetworkStatusSource,\n} from \"./network\";\nexport type {\n AddOrganizationGroupUserInput,\n ImportedOrganizationUser,\n LocalOrganizationSummary,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n Organizations,\n OrganizationUserDetail,\n RemoveOrganizationGroupUserInput,\n} from \"./organizations\";\nexport type {\n PrincipalHistoryKeyProvider,\n PrincipalHistoryKeyScope,\n} from \"./principalHistoryProtection\";\nexport type {\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n} from \"./securityIncidents\";\nexport { PurgedOrganizationRecoveryBillingRequiredError } from \"./session/sessionRecoveryErrors\";\nexport type {\n CreateOrganizationOptions,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n UserSession,\n} from \"./session/sessionTypes\";\nexport {\n SyncBillingGate,\n type SyncBillingGateListener,\n} from \"./syncBillingGate\";\nexport {\n type ClientDatabaseOptions,\n type ClientOptions,\n Tearleads,\n} from \"./Tearleads\";\nexport type {\n ResolvedUserIdentity,\n UserIdentities,\n} from \"./userIdentities\";\n"]}
@@ -0,0 +1,19 @@
1
+ import type { PrincipalHistoryProtectionLease } from "../data/principals/principalHistoryProtection.js";
2
+ export interface PrincipalHistoryKeyScope {
3
+ readonly identityTrustDomain: string;
4
+ readonly signingFingerprint: string;
5
+ }
6
+ /** Return a fresh owned 32-byte key. The SDK clears it after each operation. */
7
+ export type PrincipalHistoryKeyProvider = (scope: PrincipalHistoryKeyScope) => Promise<Uint8Array>;
8
+ interface RuntimeProtectionScope extends PrincipalHistoryKeyScope {
9
+ readonly database: object;
10
+ readonly generation: number;
11
+ }
12
+ export declare function createPrincipalHistoryProtectionCustody(input: {
13
+ readonly readScope: () => RuntimeProtectionScope | null;
14
+ readonly keyProvider?: PrincipalHistoryKeyProvider | undefined;
15
+ }): {
16
+ retire(): void;
17
+ bind(): PrincipalHistoryProtectionLease | undefined;
18
+ };
19
+ export {};
@@ -0,0 +1,76 @@
1
+ import { KeyingVerificationError } from "../internal/crypto/index.js";
2
+ import { assertProjectionVerificationCurrent } from "../data/keyingProjectionVerification/types.js";
3
+ function sameKeyScope(a, b) {
4
+ return (a?.database === b.database &&
5
+ a.identityTrustDomain === b.identityTrustDomain &&
6
+ a.signingFingerprint === b.signingFingerprint);
7
+ }
8
+ export function createPrincipalHistoryProtectionCustody(input) {
9
+ let retirement = 0;
10
+ let ephemeral = null;
11
+ const clearEphemeral = () => {
12
+ ephemeral?.key.fill(0);
13
+ ephemeral = null;
14
+ };
15
+ return {
16
+ retire() {
17
+ retirement += 1;
18
+ clearEphemeral();
19
+ },
20
+ bind() {
21
+ const scope = input.readScope();
22
+ if (!scope) {
23
+ clearEphemeral();
24
+ return undefined;
25
+ }
26
+ if (ephemeral && !sameKeyScope(ephemeral.scope, scope))
27
+ clearEphemeral();
28
+ const boundRetirement = retirement;
29
+ const boundGeneration = scope.generation;
30
+ const stillCurrent = () => {
31
+ const current = input.readScope();
32
+ return (retirement === boundRetirement &&
33
+ current?.generation === boundGeneration &&
34
+ sameKeyScope(current, scope));
35
+ };
36
+ const context = JSON.stringify([
37
+ "tearleads.sdk.principal-history.runtime.v1",
38
+ scope.identityTrustDomain,
39
+ scope.signingFingerprint,
40
+ ]);
41
+ return async (operation) => {
42
+ assertProjectionVerificationCurrent(stillCurrent);
43
+ let key;
44
+ try {
45
+ if (input.keyProvider) {
46
+ key = await input.keyProvider({
47
+ identityTrustDomain: scope.identityTrustDomain,
48
+ signingFingerprint: scope.signingFingerprint,
49
+ });
50
+ }
51
+ else {
52
+ ephemeral ??= {
53
+ scope,
54
+ key: crypto.getRandomValues(new Uint8Array(32)),
55
+ };
56
+ key = new Uint8Array(ephemeral.key);
57
+ }
58
+ if (!(key instanceof Uint8Array) || key.byteLength !== 32)
59
+ throw new KeyingVerificationError("invalid_shape", "Principal history key provider must return 32 private bytes");
60
+ assertProjectionVerificationCurrent(stillCurrent);
61
+ const result = await operation({
62
+ protection: { localKey: key, context },
63
+ stillCurrent,
64
+ });
65
+ assertProjectionVerificationCurrent(stillCurrent);
66
+ return result;
67
+ }
68
+ finally {
69
+ if (key instanceof Uint8Array)
70
+ key.fill(0);
71
+ }
72
+ };
73
+ },
74
+ };
75
+ }
76
+ //# sourceMappingURL=principalHistoryProtection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalHistoryProtection.js","sourceRoot":"","sources":["principalHistoryProtection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,4CAA4C,CAAC;AAkBjG,SAAS,YAAY,CACnB,CAAgC,EAChC,CAAyB;IAEzB,OAAO,CACL,CAAC,EAAE,QAAQ,KAAK,CAAC,CAAC,QAAQ;QAC1B,CAAC,CAAC,mBAAmB,KAAK,CAAC,CAAC,mBAAmB;QAC/C,CAAC,CAAC,kBAAkB,KAAK,CAAC,CAAC,kBAAkB,CAC9C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,uCAAuC,CAAC,KAGvD;IACC,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,IAAI,SAAS,GACX,IAAI,CAAC;IACP,MAAM,cAAc,GAAG,GAAG,EAAE;QAC1B,SAAS,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACvB,SAAS,GAAG,IAAI,CAAC;IACnB,CAAC,CAAC;IACF,OAAO;QACL,MAAM;YACJ,UAAU,IAAI,CAAC,CAAC;YAChB,cAAc,EAAE,CAAC;QACnB,CAAC;QACD,IAAI;YACF,MAAM,KAAK,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC;YAChC,IAAI,CAAC,KAAK,EAAE,CAAC;gBACX,cAAc,EAAE,CAAC;gBACjB,OAAO,SAAS,CAAC;YACnB,CAAC;YACD,IAAI,SAAS,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC;gBAAE,cAAc,EAAE,CAAC;YACzE,MAAM,eAAe,GAAG,UAAU,CAAC;YACnC,MAAM,eAAe,GAAG,KAAK,CAAC,UAAU,CAAC;YACzC,MAAM,YAAY,GAA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,CAAC;oBACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;oBAClD,OAAO,MAAM,CAAC;gBAChB,CAAC;wBAAS,CAAC;oBACT,IAAI,GAAG,YAAY,UAAU;wBAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBAC7C,CAAC;YACH,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../data/principals/principalHistoryProtection\";\n\nexport interface PrincipalHistoryKeyScope {\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n}\n\n/** Return a fresh owned 32-byte key. The SDK clears it after each operation. */\nexport type PrincipalHistoryKeyProvider = (\n scope: PrincipalHistoryKeyScope,\n) => Promise<Uint8Array>;\n\ninterface RuntimeProtectionScope extends PrincipalHistoryKeyScope {\n readonly database: object;\n readonly generation: number;\n}\n\nfunction sameKeyScope(\n a: RuntimeProtectionScope | null,\n b: RuntimeProtectionScope,\n): boolean {\n return (\n a?.database === b.database &&\n a.identityTrustDomain === b.identityTrustDomain &&\n a.signingFingerprint === b.signingFingerprint\n );\n}\n\nexport function createPrincipalHistoryProtectionCustody(input: {\n readonly readScope: () => RuntimeProtectionScope | null;\n readonly keyProvider?: PrincipalHistoryKeyProvider | undefined;\n}) {\n let retirement = 0;\n let ephemeral: { scope: RuntimeProtectionScope; key: Uint8Array } | null =\n null;\n const clearEphemeral = () => {\n ephemeral?.key.fill(0);\n ephemeral = null;\n };\n return {\n retire() {\n retirement += 1;\n clearEphemeral();\n },\n bind(): PrincipalHistoryProtectionLease | undefined {\n const scope = input.readScope();\n if (!scope) {\n clearEphemeral();\n return undefined;\n }\n if (ephemeral && !sameKeyScope(ephemeral.scope, scope)) clearEphemeral();\n const boundRetirement = retirement;\n const boundGeneration = scope.generation;\n const stillCurrent = () => {\n const current = input.readScope();\n return (\n retirement === boundRetirement &&\n current?.generation === boundGeneration &&\n sameKeyScope(current, scope)\n );\n };\n const context = JSON.stringify([\n \"tearleads.sdk.principal-history.runtime.v1\",\n scope.identityTrustDomain,\n scope.signingFingerprint,\n ]);\n return async (operation) => {\n assertProjectionVerificationCurrent(stillCurrent);\n let key: Uint8Array | undefined;\n try {\n if (input.keyProvider) {\n key = await input.keyProvider({\n identityTrustDomain: scope.identityTrustDomain,\n signingFingerprint: scope.signingFingerprint,\n });\n } else {\n ephemeral ??= {\n scope,\n key: crypto.getRandomValues(new Uint8Array(32)),\n };\n key = new Uint8Array(ephemeral.key);\n }\n if (!(key instanceof Uint8Array) || key.byteLength !== 32)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal history key provider must return 32 private bytes\",\n );\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await operation({\n protection: { localKey: key, context },\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n if (key instanceof Uint8Array) key.fill(0);\n }\n };\n },\n };\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import type { ApiClient } from "../internal/api-client/index.js";
2
2
  import type { DocumentProjectorRegistry } from "../data/documents/documentKinds.js";
3
3
  import type { DomainScope } from "../data/domainScope.js";
4
+ import type { PrincipalHistoryProtectionLease } from "../data/principals/principalHistoryProtection.js";
4
5
  import type { SecurityIncidentReporter } from "../data/securityIncidents.js";
5
6
  import { type LocalUserIdentityCandidate, type TrustedUserIdentityResolver } from "../data/trustedUserIdentity/index.js";
6
7
  import type { ContainerContentsRootAdopter } from "../workflows/container-contents/runtime.js";
@@ -10,6 +11,7 @@ import type { Database } from "./database.js";
10
11
  import type { Events } from "./events.js";
11
12
  import type { Identity } from "./identity.js";
12
13
  import type { Network } from "./network.js";
14
+ import { type PrincipalHistoryKeyProvider } from "./principalHistoryProtection.js";
13
15
  import type { Session } from "./session/sessionTypes.js";
14
16
  import type { SyncBillingGate } from "./syncBillingGate.js";
15
17
  type HostWorkflowRuntimeUtilInput = Omit<WorkflowRuntimeUtilInput, "reportSecurityIncident">;
@@ -25,8 +27,10 @@ export interface Runtime {
25
27
  export interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {
26
28
  readonly apiClient: ApiClient;
27
29
  readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
30
+ readonly withPrincipalHistoryProtection?: PrincipalHistoryProtectionLease | undefined;
28
31
  }
29
32
  export interface InternalRuntime {
33
+ retirePrincipalHistoryProtection(): void;
30
34
  readonly sessionGeneration: number;
31
35
  readonly adoptRootContainer: ContainerContentsRootAdopter;
32
36
  readonly publicRuntime: Runtime;
@@ -47,6 +51,7 @@ interface WorkflowRuntimeDependencies {
47
51
  logError: (message: string | Error, cause?: unknown) => void;
48
52
  network: Network;
49
53
  peerScope?: string | null;
54
+ principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;
50
55
  reportSecurityIncident: SecurityIncidentReporter;
51
56
  session: Session;
52
57
  syncBillingGate?: SyncBillingGate | undefined;
@@ -2,6 +2,7 @@ import { runWithSecurityIncidentReporting } from "../data/keyingProjectionVerifi
2
2
  import { unavailableExecSql } from "../data/sqlite/sqlSchema.js";
3
3
  import { createApiUserIdentitySource, createTrustedUserIdentityService, } from "../data/trustedUserIdentity/index.js";
4
4
  import { createListenerSet } from "./listenerSet.js";
5
+ import { createPrincipalHistoryProtectionCustody, } from "./principalHistoryProtection.js";
5
6
  import { adoptSessionRootContainer } from "./rootContainerAdoption.js";
6
7
  import { acknowledgedSessionRoot } from "./session/sessionRootAuthority.js";
7
8
  export function createRuntime(dependencies) {
@@ -32,8 +33,26 @@ export function createRuntime(dependencies) {
32
33
  organizationId: dependencies.session.organizationId,
33
34
  }, () => trustedUserIdentityService.resolve(userId));
34
35
  const runtimeSubscription = createRuntimeSubscription(dependencies);
35
- const runtimeInput = createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity);
36
+ const historyProtection = createPrincipalHistoryProtectionCustody({
37
+ keyProvider: dependencies.principalHistoryKeyProvider,
38
+ readScope: () => {
39
+ const signingFingerprint = dependencies.identity.signingFingerprint;
40
+ const identityTrustDomain = dependencies.identityTrustDomain;
41
+ if (!signingFingerprint ||
42
+ !identityTrustDomain ||
43
+ dependencies.database.status !== "ready")
44
+ return null;
45
+ return {
46
+ signingFingerprint,
47
+ identityTrustDomain,
48
+ database: dependencies.getDomainScope(),
49
+ generation: runtimeSubscription.recoveryGeneration,
50
+ };
51
+ },
52
+ });
53
+ const runtimeInput = createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, historyProtection.bind);
36
54
  return {
55
+ retirePrincipalHistoryProtection: historyProtection.retire,
37
56
  get sessionGeneration() {
38
57
  return runtimeSubscription.sessionGeneration;
39
58
  },
@@ -61,25 +80,34 @@ function createRuntimeSubscription(dependencies) {
61
80
  const listeners = createListenerSet();
62
81
  let version = 0;
63
82
  let sessionGeneration = 0;
83
+ let recoveryGeneration = 0;
64
84
  let sessionSnapshot = dependencies.session.snapshot;
65
85
  const notifyListeners = () => {
66
86
  version += 1;
67
87
  listeners.notify();
68
88
  };
69
- dependencies.database.subscribe(notifyListeners);
89
+ const notifyAuthority = () => {
90
+ recoveryGeneration += 1;
91
+ notifyListeners();
92
+ };
93
+ dependencies.database.subscribe(notifyAuthority);
70
94
  dependencies.events.subscribe(notifyListeners);
71
- dependencies.identity.subscribe(notifyListeners);
95
+ dependencies.identity.subscribe(notifyAuthority);
72
96
  dependencies.network.subscribe(() => notifyListeners());
73
97
  dependencies.session.subscribe(() => {
74
98
  const next = dependencies.session.snapshot;
75
99
  if (sessionAuthorityChanged(sessionSnapshot, next)) {
76
100
  sessionGeneration += 1;
101
+ recoveryGeneration += 1;
77
102
  }
78
103
  sessionSnapshot = next;
79
104
  notifyListeners();
80
105
  });
81
106
  dependencies.syncBillingGate?.subscribe(notifyListeners);
82
107
  return {
108
+ get recoveryGeneration() {
109
+ return recoveryGeneration;
110
+ },
83
111
  get sessionGeneration() {
84
112
  return sessionGeneration;
85
113
  },
@@ -110,7 +138,7 @@ function sessionAuthorityChanged(previous, next) {
110
138
  next.organizationId !== previous.organizationId ||
111
139
  next.userId !== previous.userId);
112
140
  }
113
- function createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity) {
141
+ function createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, bindHistoryProtection) {
114
142
  let auth;
115
143
  let crypto;
116
144
  let infra;
@@ -169,11 +197,12 @@ function createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity) {
169
197
  state,
170
198
  util,
171
199
  resolveTrustedUserIdentity,
200
+ withPrincipalHistoryProtection: bindHistoryProtection(),
172
201
  };
173
202
  };
174
203
  return {
175
204
  hostInput(containerId) {
176
- const { apiClient: _apiClient, resolveTrustedUserIdentity: _resolveTrustedUserIdentity, util: workflowUtil, ...input } = workflowInput(containerId);
205
+ const { apiClient: _apiClient, resolveTrustedUserIdentity: _resolveTrustedUserIdentity, withPrincipalHistoryProtection: _withPrincipalHistoryProtection, util: workflowUtil, ...input } = workflowInput(containerId);
177
206
  hostUtil = reuseIfShallowEqual(hostUtil, {
178
207
  isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,
179
208
  log: workflowUtil.log,
@@ -1 +1 @@
1
- {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAE9F,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GAGjC,MAAM,6BAA6B,CAAC;AAcrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AA2DzE,MAAM,UAAU,aAAa,CAC3B,YAAyC;IAEzC,MAAM,0BAA0B,G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;QACL,SAAS,CAAC,WAAW;YACnB,MAAM,EACJ,SAAS,EAAE,UAAU,EACrB,0BAA0B,EAAE,2BAA2B,EACvD,IAAI,EAAE,YAAY,EAClB,GAAG,KAAK,EACT,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;YAC/B,QAAQ,GAAG,mBAAmB,CAAC,QAAQ,EAAE;gBACvC,mBAAmB,EAAE,YAAY,CAAC,mBAAmB;gBACrD,GAAG,EAAE,YAAY,CAAC,GAAG;gBACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;aAChC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAC1B,OAAsB,EACtB,IAAO;IAEP,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../data/documents/documentKinds\";\nimport type { DomainScope } from \"../data/domainScope\";\nimport { runWithSecurityIncidentReporting } from \"../data/keyingProjectionVerification/error\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { unavailableExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n type TrustedUserIdentityResolver,\n} from \"../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../workflows/container-contents/runtime\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../workflows/runtimeInput\";\nimport type { Blobs } from \"./blobs\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Identity } from \"./identity\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { acknowledgedSessionRoot } from \"./session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"./session/sessionTypes\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: ApiClient;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport interface InternalRuntime {\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null,\n getLocalIdentity: () => {\n const encapsulationKeyPair = dependencies.identity.encapsulationKeyPair;\n const signingKeyPair = dependencies.identity.signingKeyPair;\n if (!encapsulationKeyPair || !signingKeyPair) {\n return null;\n }\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: dependencies.identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n },\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n );\n\n return {\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n dependencies.database.subscribe(notifyListeners);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyListeners);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n }\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken ||\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: dependencies.api,\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
1
+ {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAG9F,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GAGjC,MAAM,6BAA6B,CAAC;AAcrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAA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AAE,YAAY,CAAC,mBAAmB;gBACrD,GAAG,EAAE,YAAY,CAAC,GAAG;gBACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;aAChC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAC1B,OAAsB,EACtB,IAAO;IAEP,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../data/documents/documentKinds\";\nimport type { DomainScope } from \"../data/domainScope\";\nimport { runWithSecurityIncidentReporting } from \"../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../data/principals/principalHistoryProtection\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { unavailableExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n type TrustedUserIdentityResolver,\n} from \"../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../workflows/container-contents/runtime\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../workflows/runtimeInput\";\nimport type { Blobs } from \"./blobs\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Identity } from \"./identity\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { acknowledgedSessionRoot } from \"./session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"./session/sessionTypes\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: ApiClient;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null,\n getLocalIdentity: () => {\n const encapsulationKeyPair = dependencies.identity.encapsulationKeyPair;\n const signingKeyPair = dependencies.identity.signingKeyPair;\n if (!encapsulationKeyPair || !signingKeyPair) {\n return null;\n }\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: dependencies.identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n },\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n );\n\n return {\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken ||\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: dependencies.api,\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { type AnyVerifiedPrincipalPolicy } from "../../../internal/crypto/index.js";
2
1
  import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
2
+ import type { PrincipalPolicyCheckpointEvidence } from "../../principals/principalPolicyEvidence.js";
3
3
  import type { ContainerMutationAuthor } from "./types.js";
4
4
  export declare class ContainerAuthorAccessError extends Error {
5
5
  readonly code = "unauthorized";
@@ -10,6 +10,6 @@ export declare class ContainerAuthorAccessError extends Error {
10
10
  export declare function assertContainerAuthorAccess(input: {
11
11
  author: ContainerMutationAuthor;
12
12
  minimumAccess: "write" | "admin";
13
- principalPolicies: readonly AnyVerifiedPrincipalPolicy[];
13
+ principalPolicies: readonly PrincipalPolicyCheckpointEvidence[];
14
14
  projection: ContainerWriterProjectionResponse;
15
15
  }): void;