@tearleads/client-sdk 0.1.111 → 0.1.112

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 (50) hide show
  1. package/Tearleads.js +0 -2
  2. package/Tearleads.js.map +1 -1
  3. package/client/containerContents/index.js +5 -1
  4. package/client/containerContents/index.js.map +1 -1
  5. package/client/deviceFirst/index.js +5 -1
  6. package/client/deviceFirst/index.js.map +1 -1
  7. package/client/identity/userIdentities.d.ts +13 -8
  8. package/client/identity/userIdentities.js +4 -22
  9. package/client/identity/userIdentities.js.map +1 -1
  10. package/client/index.d.ts +2 -2
  11. package/client/index.js +1 -0
  12. package/client/index.js.map +1 -1
  13. package/client/organizations/index.d.ts +1 -1
  14. package/client/organizations/index.js +12 -9
  15. package/client/organizations/index.js.map +1 -1
  16. package/client/organizations/organizationsTypes.d.ts +1 -2
  17. package/client/organizations/organizationsTypes.js.map +1 -1
  18. package/client/runtime/workflowRuntime.d.ts +1 -1
  19. package/client/runtime/workflowRuntime.js.map +1 -1
  20. package/data/persistence/trustedUserIdentityPinPersistence.js +30 -4
  21. package/data/persistence/trustedUserIdentityPinPersistence.js.map +1 -1
  22. package/data/sqlite/schema/index.d.ts +45 -5
  23. package/data/sqlite/schema/index.js +14 -6
  24. package/data/sqlite/schema/index.js.map +1 -1
  25. package/data/trustedUserIdentity/admission.d.ts +10 -0
  26. package/data/trustedUserIdentity/admission.js +15 -0
  27. package/data/trustedUserIdentity/admission.js.map +1 -0
  28. package/data/trustedUserIdentity/index.d.ts +1 -0
  29. package/data/trustedUserIdentity/index.js +1 -0
  30. package/data/trustedUserIdentity/index.js.map +1 -1
  31. package/data/trustedUserIdentity/service.d.ts +1 -5
  32. package/data/trustedUserIdentity/service.js +119 -46
  33. package/data/trustedUserIdentity/service.js.map +1 -1
  34. package/data/trustedUserIdentity/types.d.ts +12 -1
  35. package/data/trustedUserIdentity/types.js.map +1 -1
  36. package/index.d.ts +3 -3
  37. package/index.js +2 -2
  38. package/index.js.map +1 -1
  39. package/package.json +1 -1
  40. package/stores/container-contents/containerContentsStore.js +10 -1
  41. package/stores/container-contents/containerContentsStore.js.map +1 -1
  42. package/workflows/container-contents/runtime.d.ts +7 -1
  43. package/workflows/container-contents/runtime.js +2 -1
  44. package/workflows/container-contents/runtime.js.map +1 -1
  45. package/workflows/organizations/index.d.ts +0 -1
  46. package/workflows/organizations/index.js +0 -1
  47. package/workflows/organizations/index.js.map +1 -1
  48. package/workflows/organizations/organizationUserImport.d.ts +0 -8
  49. package/workflows/organizations/organizationUserImport.js +0 -10
  50. package/workflows/organizations/organizationUserImport.js.map +0 -1
@@ -222,13 +222,15 @@ export const documentPurgeCheckpoints = sqliteTable("document_purge_checkpoints"
222
222
  updatedAt: text("updated_at").notNull(),
223
223
  });
224
224
  /**
225
- * Durable trust-on-first-use pins for remote user identity bundles.
225
+ * Durable pins for user identity bundles.
226
226
  *
227
- * The first validated identity observed for a user in a configured API trust
227
+ * The first validated identity accepted for a user in a configured API trust
228
228
  * domain is inserted once. Later observations must match every suite, public
229
- * key, and fingerprint exactly; the persistence adapter never updates these
230
- * rows. `firstSeenAt` records when the local trust decision was made and is
231
- * likewise immutable.
229
+ * key, and fingerprint exactly; the persistence adapter never changes those
230
+ * columns. `firstSeenAt` records when the local trust decision was made and is
231
+ * likewise immutable. `provenance` (`self`, `link`, or `observed`) records how
232
+ * the pin was established; only `self` and `link` admit a user, and it only
233
+ * rises. A table without it is an obsolete local database.
232
234
  *
233
235
  * Indexes:
234
236
  * - `(identityTrustDomain, userId)` is the primary key and scopes a user pin to
@@ -253,6 +255,9 @@ export const trustedUserIdentityPins = sqliteTable("trusted_user_identity_pins",
253
255
  encapsulationPublicKey: text("encapsulation_public_key").notNull(),
254
256
  encapsulationKeyFingerprint: text("encapsulation_key_fingerprint").notNull(),
255
257
  firstSeenAt: text("first_seen_at").notNull(),
258
+ provenance: text("provenance", {
259
+ enum: ["self", "link", "observed"],
260
+ }).notNull(),
256
261
  }, (table) => [
257
262
  primaryKey({
258
263
  columns: [table.identityTrustDomain, table.userId],
@@ -426,7 +431,10 @@ export const keyingCheckpointTables = [
426
431
  defineSqlTableSchema(principalPolicyCheckpoints),
427
432
  ];
428
433
  export const trustedUserIdentityPinTables = [
429
- defineSqlTableSchema(trustedUserIdentityPins),
434
+ {
435
+ ...defineSqlTableSchema(trustedUserIdentityPins),
436
+ requiredColumns: ["provenance"],
437
+ },
430
438
  ];
431
439
  const securityIncidentTables = [
432
440
  securityIncidentTable,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EACL,KAAK,EACL,OAAO,EACP,UAAU,EACV,WAAW,EACX,IAAI,EACJ,WAAW,GACZ,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAuB,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,+BAA+B,EAAE,MAAM,wCAAwC,CAAC;AACzF,OAAO,EACL,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,0BAA0B,EAC1B,8BAA8B,GAC/B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,yBAAyB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,mBAAmB,MAAM,yCAAyC,CAAC;AAC/E,OAAO,EACL,iCAAiC,EACjC,2BAA2B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AoB,CAAC,uBAAuB,CAAC;QAChD,eAAe,EAAE,CAAC,YAAY,CAAC;KAChC;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,eAAe,GAAkC;IAC5D,GAAG,8BAA8B;IACjC,GAAG,cAAc;IACjB,GAAG,qBAAqB;IACxB,GAAG,sBAAsB;IACzB,GAAG,4BAA4B;IAC/B,GAAG,4BAA4B;IAC/B,GAAG,sBAAsB;IACzB,GAAG,eAAe;IAClB,GAAG,iCAAiC;IACpC,GAAG,6BAA6B;IAChC,GAAG,wBAAwB;IAC3B,GAAG,4BAA4B;IAC/B,GAAG,2BAA2B;IAC9B,GAAG,qBAAqB,CAAC,2BAA2B;IACpD,GAAG,mBAAmB,CAAC,qCAAqC;IAC5D,GAAG,qBAAqB,CAAC,2BAA2B;CACrD,CAAC;AAEF,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,8BAA8B;IAC9B,0BAA0B;IAC1B,2BAA2B;IAC3B,wBAAwB;IACxB,uBAAuB;IACvB,qBAAqB;IACrB,wBAAwB;IACxB,sBAAsB;IACtB,oBAAoB;IACpB,yBAAyB;IACzB,SAAS;IACT,iBAAiB;IACjB,4BAA4B;IAC5B,+BAA+B;IAC/B,4BAA4B;IAC5B,yBAAyB;IACzB,wBAAwB;IACxB,0BAA0B;IAC1B,6BAA6B;IAC7B,uBAAuB;IACvB,iBAAiB;IACjB,GAAG,qBAAqB;IACxB,2BAA2B;IAC3B,YAAY;IACZ,yBAAyB;IACzB,kBAAkB;IAClB,0BAA0B;IAC1B,gCAAgC;IAChC,0BAA0B,EAAE,0BAA0B;IACtD,uBAAuB;IACvB,GAAG,iCAAiC;IACpC,GAAG,qBAAqB,CAAC,iCAAiC;IAC1D,GAAG,mBAAmB,CAAC,2CAA2C;IAClE,GAAG,qBAAqB,CAAC,iCAAiC;CAC3D,CAAC","sourcesContent":["import { sql } from \"drizzle-orm\";\nimport {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n uniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema, type SqlTableSchema } from \"../sqlTableSchema\";\nimport { containerDocumentTombstoneHolds } from \"./containerDocumentTombstoneHoldSchema\";\nimport {\n containerSQLiteSchema,\n containerTableSchemas,\n} from \"./containerSchema\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"./documentAttachmentSchema\";\nimport {\n documentDiscoveryHeads,\n documentDiscoverySequence,\n pendingDocumentDiscoveries,\n} from \"./documentDiscoveryEvidenceSchema\";\nimport {\n documentOrphanBlobReclaims,\n documentOrphanBlobReclaimTable,\n} from \"./documentOrphanBlobReclaimSchema\";\nimport { documentIntentLinkTargets } from \"./documentPlacementIntentSchema\";\nimport { localIntents } from \"./localIntentSchema\";\nimport * as organizationDataUsage from \"./organizationDataUsageSchema\";\nimport { organizationFounders } from \"./organizationFounderSchema\";\nimport * as provisioningAttempt from \"./organizationProvisioningAttemptSchema\";\nimport {\n organizationReadModelSQLiteSchema,\n organizationReadModelTables,\n} from \"./organizationReadModelTableRegistry\";\nimport * as organizationSyncPause from \"./organizationSyncPauseSchema\";\nimport { principalGrantRetirements } from \"./principalGrantRetirementSchema\";\nimport {\n principalHistoryEntries,\n principalHistoryEvidenceTables,\n principalHistoryNodes,\n principalHistoryPrefixes,\n} from \"./principalHistoryEvidenceSchema\";\nimport {\n principalHistoryNodeReferences,\n principalHistoryRootOwners,\n} from \"./principalHistoryNodeRetentionSchema\";\nimport { principalKeyEnvelopeArchive } from \"./principalHistoryRetentionSchema\";\nimport {\n principalHistoryStages,\n principalHistoryStageTables,\n} from \"./principalHistoryStageSchema\";\nimport {\n principalMutationJournal,\n principalMutationJournalTables,\n} from \"./principalMutationJournalSchema\";\nimport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n principalPolicyOrganizations,\n} from \"./principalPolicySchema\";\nimport {\n securityIncidents,\n securityIncidentTable,\n} from \"./securityIncidentSchema\";\nimport {\n verifiedAccessManifestBundles,\n verifiedManifestBundleTables,\n} from \"./verifiedManifestBundleSchema\";\n\nexport {\n containerHydrationTombstones,\n containers,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n supersededContainerBindings,\n} from \"./containerSchema\";\nexport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"./documentAttachmentSchema\";\nexport {\n inContainerIntentLanes,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"./localIntentSchema\";\nexport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n principalPolicyOrganizations,\n} from \"./principalPolicySchema\";\nexport { securityIncidents } from \"./securityIncidentSchema\";\nexport { containerDocumentTombstoneHolds, organizationReadModelTables };\n\nconst accessLevelColumn = \"effective_access_level\";\n\n/**\n * Durable Loro-backed document records shared by app features.\n *\n * This table stores encrypted document runtime state for multiple app domains.\n * `appKind` namespaces records for documents and container metadata. User-facing\n * list data is projected into feature-specific read models.\n *\n * Columns:\n * - `appKind`: Local domain namespace for the row, such as `documents` or\n * `container-metadata`.\n * - `localId`: Stable local id inside `appKind`. It may be created before a\n * server `documentId` exists.\n * - `documentId`: Server document id once the record is known remotely, or\n * `null` while the document is local-only.\n * - `accessEpoch`: Latest access epoch persisted for the document. Defaults to\n * the initial epoch.\n * - `accessStateHash`: Current document access/manifest state hash returned by\n * sync, when known.\n * - `lastCommitLsn`: Last remote commit cursor applied to this local document.\n * - `documentManifestBundle`: Serialized document manifest bundle used for\n * encrypted document sync.\n * - `contentKeyBundle`: Serialized content-key material needed to open the\n * local document.\n * - `documentKekTargets`: Serialized KEK target state for document key wraps.\n * - `pendingBaseVersion`: Encoded oplog version through which every persisted\n * op is already enqueued or synced. Persisted so a restart restores the\n * outgoing-delta marker instead of re-seeding it past a device-first\n * `deferRemoteSync` write's un-advanced op. `null` when unset.\n * - `snapshotEndVersion`: Encoded end version vector of the persisted content\n * (which lives in the durable-history tables, never on this row), written on\n * every content persist. Lets the pending-write queue's deferred-tail scan\n * compare version coverage without loading content. Empty string when the\n * document has never hydrated content, which readers treat as \"no deferred\n * tail claimable\".\n * - `recoveryGeneration`: Atomic raw-history recovery writer fence.\n * - `recoveryDocumentId`: Former server id for cross-client post-purge recreation.\n * - `pullContinuation`: Durable progress for the next bounded remote pull.\n * - `syncFailureStatus`, `syncFailureMessage`, `syncFailureAttemptedAt`: The\n * last terminal sync failure or quarantined incoming update for this scope.\n * The durable write queue (queued rows of `documentHistoryUpdates`) has no\n * status columns, so these let the write-queue view and footer explain why\n * the document is blocked. `syncFailureMessage` is non-null exactly when a\n * failure is recorded; a newer failure replaces the old, and a later fully\n * validated sync pass, a remote reset, or the scope's teardown clears all\n * three.\n * - `updatedAt`: Local timestamp for the last persisted runtime-state update.\n *\n * Indexes:\n * - `(appKind, localId)` is the primary key and scopes local document lookups.\n * - `(appKind, documentId) where documentId is not null` supports resolving a\n * server document id back to the local row during discovery and relinking.\n */\nexport const documents = sqliteTable(\n \"documents\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n documentId: text(\"document_id\"),\n accessEpoch: integer(\"access_epoch\").notNull().default(1),\n accessStateHash: text(\"access_state_hash\"),\n effectiveAccessLevel: text(accessLevelColumn).notNull().default(\"read\"),\n lastCommitLsn: text(\"last_commit_lsn\"),\n documentManifestBundle: text(\"document_manifest_bundle\"),\n contentKeyBundle: text(\"content_key_bundle\"),\n documentKekTargets: text(\"document_kek_targets\"),\n pendingBaseVersion: text(\"pending_base_version\"),\n pullContinuation: text(\"pull_continuation\"),\n recoveryGeneration: integer(\"recovery_generation\").notNull().default(0),\n recoveryDocumentId: text(\"recovery_document_id\"),\n snapshotEndVersion: text(\"snapshot_end_version\").notNull().default(\"\"),\n syncFailureStatus: integer(\"sync_failure_status\"),\n syncFailureMessage: text(\"sync_failure_message\"),\n syncFailureAttemptedAt: text(\"sync_failure_attempted_at\"),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.appKind, table.localId] }),\n index(\"documents_app_document_idx\")\n .on(table.appKind, table.documentId)\n .where(sql`${table.documentId} IS NOT NULL`),\n ],\n);\n\n/**\n * Full-history persistence for local documents (checkpoint + tail) — the ONLY\n * durable content source. Record rows in `documents` carry runtime metadata\n * and the content frontier (`snapshotEndVersion`), never content. The\n * checkpoint holds a full-history snapshot refreshed only at compaction, and\n * the tail appends every update (local deltas and decrypted remote updates)\n * written since. Restore = import checkpoint + replay tail; compaction =\n * export full history from the live doc, replace the checkpoint, clear the\n * tail — all bounded and amortized. Container metadata stores its content (an\n * exported-updates blob) as its checkpoint row, with no tail.\n */\nexport const documentHistoryCheckpoints = sqliteTable(\n \"document_history_checkpoints\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n snapshot: text(\"snapshot\").notNull(),\n endVersionVector: text(\"end_version_vector\").notNull(),\n revision: text(\"revision\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.appKind, table.localId] })],\n);\n\n/**\n * The local update log: one row per Loro update, serving as both the history\n * tail (restore = checkpoint + tail) and the outbound write queue.\n *\n * Every locally authored update is stored once. While it waits for sync it\n * carries an `updateId` (the id submitted to the server) and the version-vector\n * metadata the submission needs; settlement clears them, leaving the row as\n * ordinary tail history until compaction folds it into a checkpoint.\n *\n * Columns:\n * - `id`: Row id; tail compaction deletes by it.\n * - `appKind`, `localId`: Document scope matching `documents`.\n * - `updateData`: Serialized Loro update payload.\n * - `origin`: \"local\" (authored on this device) or \"remote\" (decrypted\n * pulled update) for tail rows. Restores use it to advance the\n * outgoing-delta marker across remote rows — their ops are already\n * server-side — while a local row left behind by a crash stays below the\n * marker so the next edit re-derives and sends it. \"outbox\" marks a queued\n * update with no tail role (container metadata, whose content is its\n * checkpoint, and full-state re-uploads after a remote reset); restores and\n * compaction never see it and settlement deletes it.\n * - `createdAt`: Insertion timestamp; with `rowid`, deterministic replay order.\n * - `updateId`: Present exactly while the row is queued for sync; rekeyed\n * after a lost acknowledgement poisons the submitted id.\n * - `partialStartVersionVector` / `partialEndVersionVector`: Version vectors\n * around a queued partial update.\n * - `sourceVersionVector`: Present on a queued rotation baseline checkpoint.\n * - `rekeyCount`: Durable bound on rekeys of a queued row.\n *\n * Invariant: compaction never deletes a queued row, so a checkpoint can cover\n * a queued update's operations without removing it from the queue.\n */\nexport const documentHistoryUpdates = sqliteTable(\n \"document_history_updates\",\n {\n id: text(\"id\"),\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n updateData: text(\"update_data\").notNull(),\n origin: text(\"origin\").notNull(),\n createdAt: text(\"created_at\").notNull(),\n updateId: text(\"update_id\"),\n partialStartVersionVector: text(\"partial_start_version_vector\"),\n partialEndVersionVector: text(\"partial_end_version_vector\"),\n sourceVersionVector: text(\"source_version_vector\"),\n rekeyCount: integer(\"rekey_count\").notNull().default(0),\n },\n (table) => [\n primaryKey({ columns: [table.id] }),\n index(\"document_history_updates_scope_created_idx\").on(\n table.appKind,\n table.localId,\n table.createdAt,\n ),\n uniqueIndex(\"document_history_updates_update_id_idx\")\n .on(table.updateId)\n .where(sql`${table.updateId} IS NOT NULL`),\n ],\n);\n\n/**\n * Anti-rollback pin for verified access manifests.\n *\n * Records the highest access-manifest epoch this client has verified for each\n * object, so a later projection that serves an older epoch (rollback) or a\n * conflicting manifest at the same epoch (equivocation) is detected before any\n * key is unwrapped. Updated monotonically after a projection verifies cleanly.\n *\n * Columns:\n * - `objectKind`: Access object kind (`container`, `document`, ...).\n * - `organizationId`: Organization boundary that owns the object.\n * - `objectId`: Stable object id.\n * - `epoch`: Highest verified manifest epoch.\n * - `manifestHash`: Manifest hash pinned at that epoch.\n * - `updatedAt`: Local timestamp for the pin.\n *\n * Indexes:\n * - `(objectKind, organizationId, objectId)` is the primary key and gives one\n * pin per object.\n */\nexport const accessManifestCheckpoints = sqliteTable(\n \"access_manifest_checkpoints\",\n {\n objectKind: text(\"object_kind\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n objectId: text(\"object_id\").notNull(),\n epoch: integer(\"epoch\").notNull(),\n manifestHash: text(\"manifest_hash\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [\n primaryKey({\n columns: [table.objectKind, table.organizationId, table.objectId],\n }),\n ],\n);\n\n/**\n * Durable terminal pins for documents whose signed purge proof was verified.\n * These survive remote-state resets so a dishonest API cannot later replay the\n * pre-purge writer projection and resurrect locally deleted content.\n */\nexport const documentPurgeCheckpoints = sqliteTable(\n \"document_purge_checkpoints\",\n {\n documentId: text(\"document_id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n documentManifestHash: text(\"document_manifest_hash\").notNull(),\n purgeEventHash: text(\"purge_event_hash\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n);\n\n/**\n * Durable trust-on-first-use pins for remote user identity bundles.\n *\n * The first validated identity observed for a user in a configured API trust\n * domain is inserted once. Later observations must match every suite, public\n * key, and fingerprint exactly; the persistence adapter never updates these\n * rows. `firstSeenAt` records when the local trust decision was made and is\n * likewise immutable.\n *\n * Indexes:\n * - `(identityTrustDomain, userId)` is the primary key and scopes a user pin to\n * the host-configured API authority that supplied it.\n * - `(identityTrustDomain, signingKeyFingerprint)` binds the reverse identity\n * mapping durably, including across session recreation. There is no\n * migration for a table that already violates it. Earlier builds pinned a\n * registration's user id before the server confirmed it, so a device that\n * ran one may hold two users on one key; deployments are greenfield, and\n * such a device clears its local data, which recreates this table empty. A\n * device that used an environment before a reset does the same (see\n * docs/developer/greenfield-reset.md).\n */\nexport const trustedUserIdentityPins = sqliteTable(\n \"trusted_user_identity_pins\",\n {\n identityTrustDomain: text(\"identity_trust_domain\").notNull(),\n userId: text(\"user_id\").notNull(),\n formatVersion: integer(\"format_version\").notNull(),\n signingSuite: text(\"signing_suite\").notNull(),\n signingPublicKey: text(\"signing_public_key\").notNull(),\n signingKeyFingerprint: text(\"signing_key_fingerprint\").notNull(),\n encapsulationSuite: text(\"encapsulation_suite\").notNull(),\n encapsulationPublicKey: text(\"encapsulation_public_key\").notNull(),\n encapsulationKeyFingerprint: text(\n \"encapsulation_key_fingerprint\",\n ).notNull(),\n firstSeenAt: text(\"first_seen_at\").notNull(),\n },\n (table) => [\n primaryKey({\n columns: [table.identityTrustDomain, table.userId],\n }),\n uniqueIndex(\"trusted_user_identity_pins_domain_signing_fingerprint_idx\").on(\n table.identityTrustDomain,\n table.signingKeyFingerprint,\n ),\n ],\n);\n\n/**\n * Local many-to-many projection between documents and containers.\n *\n * The document summary row stores one selected `containerId` for primary list\n * placement, while this table keeps the full set of linked containers returned\n * by container/document sync. Removing a container deletes its links and may\n * repair affected document summary rows to point at another remaining link.\n *\n * Columns:\n * - `documentId`: Server document id whose container links are projected.\n * - `containerId`: Linked container id.\n * - `updatedAt`: Local timestamp for the last replacement of the link set.\n *\n * Indexes:\n * - `(documentId, containerId)` is the primary key and prevents duplicate\n * links for the same document/container pair.\n */\nexport const documentContainerProjection = sqliteTable(\n \"document_container_projection\",\n {\n documentId: text(\"document_id\").notNull(),\n containerId: text(\"container_id\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.documentId, table.containerId] })],\n);\n\n/**\n * Queryable document summary and detail projection.\n *\n * The durable Loro state lives in `documents`. This table stores the fields the\n * app needs for document lists, summaries, and fast detail hydration without\n * opening the full Loro snapshot on every read.\n *\n * Columns:\n * - `localId`: Stable local document id. This joins to `documents.localId` for\n * rows where `documents.appKind = documents`.\n * - `documentId`: Server document id when known.\n * - `containerId`: Selected container for primary document placement, or\n * `null` if the document is not currently linked to a visible container.\n * - `organizationId`: Last-known owning organization. Stamped from the\n * container row when the document is detached because its container was\n * removed locally (e.g. access to a shared org was revoked and the container\n * tombstoned), so pending writes keep their org attribution after the\n * `containers` join source disappears. Read as a fallback only — a live\n * container join always wins.\n * - `documentKind`: Stored document kind. Defaults to `note`.\n * - `title`: Plain projected title. Defaults to the note fallback title.\n * - `updatedAt`: Timestamp used for document list ordering.\n *\n * The projected full text lives in `documentProjectionText`, keyed by the same\n * `localId`. Keeping it out of this row keeps list/window scans narrow: the\n * sidebar and summary queries read titles and placement from rows whose size\n * does not grow with document content.\n *\n * Indexes:\n * - `localId` is the primary key for document projection lookups.\n * - `(containerId) where containerId is not null` serves container-scoped\n * window/count scans without walking the whole table.\n * - `(organizationId) where containerId is null` serves the orphan-recovery\n * existence and window scans.\n * - `(documentId) where documentId is not null` serves the linked-placement\n * join from `documentContainerProjection` and server-id lookups.\n */\nexport const documentProjection = sqliteTable(\n \"document_projection\",\n {\n localId: text(\"local_id\"),\n documentId: text(\"document_id\"),\n containerId: text(\"container_id\"),\n organizationId: text(\"organization_id\"),\n documentKind: text(\"document_kind\").notNull().default(\"note\"),\n title: text(\"title\").notNull().default(\"Untitled note\"),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.localId] }),\n index(\"document_projection_container_idx\")\n .on(table.containerId)\n .where(sql`${table.containerId} IS NOT NULL`),\n index(\"document_projection_orphan_organization_idx\")\n .on(table.organizationId)\n .where(sql`${table.containerId} IS NULL`),\n index(\"document_projection_document_idx\")\n .on(table.documentId)\n .where(sql`${table.documentId} IS NOT NULL`),\n ],\n);\n\n/**\n * Projected document text, split from `documentProjection` so content size\n * never bloats the rows that list/window queries scan. Loaded only by detail\n * reads (`loadDocument`) and the save-timestamp change check.\n *\n * Columns:\n * - `localId`: Stable local document id, matching `documentProjection.localId`.\n * - `text`: Plain projected text used to rebuild summaries/details.\n */\nexport const documentProjectionText = sqliteTable(\n \"document_projection_text\",\n {\n localId: text(\"local_id\"),\n text: text(\"text\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.localId] })],\n);\n\n/**\n * Per-lane sync state for container data: the server cursor and the local\n * freshness marker share one row per lane.\n *\n * Container sync is split into lanes, such as a parent-container child lane or\n * a container-document membership lane. The cursor lets the next request\n * resume without replaying the entire tree. The freshness marker records the\n * last fully drained check independently of the cursor: empty server\n * responses do not always carry a new watermark, but startup still needs to\n * know that it recently checked the lane before polling again.\n *\n * Columns:\n * - `laneKind`: Sync lane category, such as `container_parent` or\n * `container_documents`.\n * - `laneId`: Lane identity. Root parent sync uses `root`, child sync uses a\n * parent-prefixed container id, and document lanes use the container id.\n * - `watermarkUpdatedAt`: Server `updatedAt` value for the stored watermark;\n * null until a watermark is saved.\n * - `watermarkId`: Server id tie-breaker for the stored watermark; null\n * exactly when `watermarkUpdatedAt` is.\n * - `updatedAt`: Local timestamp for when the cursor was saved.\n * - `checkedAt`: Local timestamp for the most recent fully drained lane check;\n * null until one completes.\n *\n * Indexes:\n * - `(laneKind, laneId)` is the primary key and stores one row per lane.\n */\nexport const containerSyncWatermarks = sqliteTable(\n \"container_sync_watermarks\",\n {\n laneKind: text(\"lane_kind\").notNull(),\n laneId: text(\"lane_id\").notNull(),\n watermarkUpdatedAt: text(\"watermark_updated_at\"),\n watermarkId: text(\"watermark_id\"),\n updatedAt: text(\"updated_at\"),\n checkedAt: text(\"checked_at\"),\n },\n (table) => [primaryKey({ columns: [table.laneKind, table.laneId] })],\n);\n\nexport const documentTables: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(documents),\n requiredColumns: [\n \"pull_continuation\",\n \"recovery_generation\",\n \"recovery_document_id\",\n \"sync_failure_status\",\n \"sync_failure_message\",\n \"sync_failure_attempted_at\",\n ],\n },\n defineSqlTableSchema(documentHistoryCheckpoints),\n {\n ...defineSqlTableSchema(documentHistoryUpdates),\n requiredColumns: [\"update_id\"],\n },\n];\n\nexport const principalPolicyTables: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(principalPolicies),\n requiredColumns: [\"current_grants_json\"],\n },\n {\n ...defineSqlTableSchema(principalPolicyBundleHistory),\n requiredColumns: [\"current_grants_json\"],\n },\n defineSqlTableSchema(principalPolicyBundleReferences),\n defineSqlTableSchema(principalPolicyOrganizations),\n ...principalHistoryStageTables,\n ...principalHistoryEvidenceTables,\n];\n\nexport const keyingCheckpointTables: ReadonlyArray<SqlTableSchema> = [\n defineSqlTableSchema(organizationFounders),\n defineSqlTableSchema(accessManifestCheckpoints),\n defineSqlTableSchema(principalGrantRetirements),\n defineSqlTableSchema(documentPurgeCheckpoints),\n defineSqlTableSchema(principalPolicyCheckpoints),\n];\n\nexport const trustedUserIdentityPinTables: ReadonlyArray<SqlTableSchema> = [\n defineSqlTableSchema(trustedUserIdentityPins),\n];\n\nconst securityIncidentTables: ReadonlyArray<SqlTableSchema> = [\n securityIncidentTable,\n];\n\nexport const containerTables = containerTableSchemas;\n\nexport const documentContainerProjectionTables: ReadonlyArray<SqlTableSchema> =\n [\n defineSqlTableSchema(documentContainerProjection),\n {\n ...defineSqlTableSchema(containerDocumentTombstoneHolds),\n requiredColumns: [\"hidden\"],\n },\n defineSqlTableSchema(pendingDocumentDiscoveries),\n {\n ...defineSqlTableSchema(documentDiscoveryHeads),\n requiredColumns: [\"organization_id\"],\n },\n defineSqlTableSchema(documentDiscoverySequence),\n ];\n\nexport const localIntentTables: ReadonlyArray<SqlTableSchema> = [\n defineSqlTableSchema(localIntents),\n];\n\nexport const documentPlacementIntentTables: ReadonlyArray<SqlTableSchema> = [\n ...localIntentTables,\n defineSqlTableSchema(documentIntentLinkTargets),\n];\n\nexport const documentProjectionTables: ReadonlyArray<SqlTableSchema> = [\n defineSqlTableSchema(documentProjection),\n defineSqlTableSchema(documentProjectionText),\n {\n ...defineSqlTableSchema(documentPendingAttachments),\n requiredColumns: [\"content_sha256\"],\n },\n {\n ...defineSqlTableSchema(documentAttachmentBlobProjection),\n requiredColumns: [\"content_sha256\"],\n },\n documentOrphanBlobReclaimTable,\n];\n\nexport const containerSyncWatermarkTables: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(containerSyncWatermarks),\n requiredColumns: [\"checked_at\"],\n },\n];\n\nexport const clientSqlTables: ReadonlyArray<SqlTableSchema> = [\n ...principalMutationJournalTables,\n ...documentTables,\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ...verifiedManifestBundleTables,\n ...trustedUserIdentityPinTables,\n ...securityIncidentTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentPlacementIntentTables,\n ...documentProjectionTables,\n ...containerSyncWatermarkTables,\n ...organizationReadModelTables,\n ...organizationDataUsage.organizationDataUsageTables,\n ...provisioningAttempt.organizationProvisioningAttemptTables,\n ...organizationSyncPause.organizationSyncPauseTables,\n];\n\nexport const clientSQLiteSchema = {\n principalHistoryNodeReferences,\n principalHistoryRootOwners,\n principalKeyEnvelopeArchive,\n principalMutationJournal,\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n principalHistoryStages,\n organizationFounders,\n principalGrantRetirements,\n documents,\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyOrganizations,\n accessManifestCheckpoints,\n documentPurgeCheckpoints,\n principalPolicyCheckpoints,\n verifiedAccessManifestBundles,\n trustedUserIdentityPins,\n securityIncidents,\n ...containerSQLiteSchema,\n documentContainerProjection,\n localIntents,\n documentIntentLinkTargets,\n documentProjection,\n documentPendingAttachments,\n documentAttachmentBlobProjection,\n documentOrphanBlobReclaims: documentOrphanBlobReclaims,\n containerSyncWatermarks,\n ...organizationReadModelSQLiteSchema,\n ...organizationDataUsage.organizationDataUsageSQLiteSchema,\n ...provisioningAttempt.organizationProvisioningAttemptSQLiteSchema,\n ...organizationSyncPause.organizationSyncPauseSQLiteSchema,\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EACL,KAAK,EACL,OAAO,EACP,UAAU,EACV,WAAW,EACX,IAAI,EACJ,WAAW,GACZ,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAuB,MAAM,mBAAmB,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C,2BAA2B;IACpD,GAAG,mBAAmB,CAAC,qCAAqC;IAC5D,GAAG,qBAAqB,CAAC,2BAA2B;CACrD,CAAC;AAEF,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,8BAA8B;IAC9B,0BAA0B;IAC1B,2BAA2B;IAC3B,wBAAwB;IACxB,uBAAuB;IACvB,qBAAqB;IACrB,wBAAwB;IACxB,sBAAsB;IACtB,oBAAoB;IACpB,yBAAyB;IACzB,SAAS;IACT,iBAAiB;IACjB,4BAA4B;IAC5B,+BAA+B;IAC/B,4BAA4B;IAC5B,yBAAyB;IACzB,wBAAwB;IACxB,0BAA0B;IAC1B,6BAA6B;IAC7B,uBAAuB;IACvB,iBAAiB;IACjB,GAAG,qBAAqB;IACxB,2BAA2B;IAC3B,YAAY;IACZ,yBAAyB;IACzB,kBAAkB;IAClB,0BAA0B;IAC1B,gCAAgC;IAChC,0BAA0B,EAAE,0BAA0B;IACtD,uBAAuB;IACvB,GAAG,iCAAiC;IACpC,GAAG,qBAAqB,CAAC,iCAAiC;IAC1D,GAAG,mBAAmB,CAAC,2CAA2C;IAClE,GAAG,qBAAqB,CAAC,iCAAiC;CAC3D,CAAC","sourcesContent":["import { sql } from \"drizzle-orm\";\nimport {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n uniqueIndex,\n} from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema, type SqlTableSchema } from \"../sqlTableSchema\";\nimport { containerDocumentTombstoneHolds } from \"./containerDocumentTombstoneHoldSchema\";\nimport {\n containerSQLiteSchema,\n containerTableSchemas,\n} from \"./containerSchema\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"./documentAttachmentSchema\";\nimport {\n documentDiscoveryHeads,\n documentDiscoverySequence,\n pendingDocumentDiscoveries,\n} from \"./documentDiscoveryEvidenceSchema\";\nimport {\n documentOrphanBlobReclaims,\n documentOrphanBlobReclaimTable,\n} from \"./documentOrphanBlobReclaimSchema\";\nimport { documentIntentLinkTargets } from \"./documentPlacementIntentSchema\";\nimport { localIntents } from \"./localIntentSchema\";\nimport * as organizationDataUsage from \"./organizationDataUsageSchema\";\nimport { organizationFounders } from \"./organizationFounderSchema\";\nimport * as provisioningAttempt from \"./organizationProvisioningAttemptSchema\";\nimport {\n organizationReadModelSQLiteSchema,\n organizationReadModelTables,\n} from \"./organizationReadModelTableRegistry\";\nimport * as organizationSyncPause from \"./organizationSyncPauseSchema\";\nimport { principalGrantRetirements } from \"./principalGrantRetirementSchema\";\nimport {\n principalHistoryEntries,\n principalHistoryEvidenceTables,\n principalHistoryNodes,\n principalHistoryPrefixes,\n} from \"./principalHistoryEvidenceSchema\";\nimport {\n principalHistoryNodeReferences,\n principalHistoryRootOwners,\n} from \"./principalHistoryNodeRetentionSchema\";\nimport { principalKeyEnvelopeArchive } from \"./principalHistoryRetentionSchema\";\nimport {\n principalHistoryStages,\n principalHistoryStageTables,\n} from \"./principalHistoryStageSchema\";\nimport {\n principalMutationJournal,\n principalMutationJournalTables,\n} from \"./principalMutationJournalSchema\";\nimport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n principalPolicyOrganizations,\n} from \"./principalPolicySchema\";\nimport {\n securityIncidents,\n securityIncidentTable,\n} from \"./securityIncidentSchema\";\nimport {\n verifiedAccessManifestBundles,\n verifiedManifestBundleTables,\n} from \"./verifiedManifestBundleSchema\";\n\nexport {\n containerHydrationTombstones,\n containers,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n supersededContainerBindings,\n} from \"./containerSchema\";\nexport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"./documentAttachmentSchema\";\nexport {\n inContainerIntentLanes,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"./localIntentSchema\";\nexport {\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyCheckpoints,\n principalPolicyOrganizations,\n} from \"./principalPolicySchema\";\nexport { securityIncidents } from \"./securityIncidentSchema\";\nexport { containerDocumentTombstoneHolds, organizationReadModelTables };\n\nconst accessLevelColumn = \"effective_access_level\";\n\n/**\n * Durable Loro-backed document records shared by app features.\n *\n * This table stores encrypted document runtime state for multiple app domains.\n * `appKind` namespaces records for documents and container metadata. User-facing\n * list data is projected into feature-specific read models.\n *\n * Columns:\n * - `appKind`: Local domain namespace for the row, such as `documents` or\n * `container-metadata`.\n * - `localId`: Stable local id inside `appKind`. It may be created before a\n * server `documentId` exists.\n * - `documentId`: Server document id once the record is known remotely, or\n * `null` while the document is local-only.\n * - `accessEpoch`: Latest access epoch persisted for the document. Defaults to\n * the initial epoch.\n * - `accessStateHash`: Current document access/manifest state hash returned by\n * sync, when known.\n * - `lastCommitLsn`: Last remote commit cursor applied to this local document.\n * - `documentManifestBundle`: Serialized document manifest bundle used for\n * encrypted document sync.\n * - `contentKeyBundle`: Serialized content-key material needed to open the\n * local document.\n * - `documentKekTargets`: Serialized KEK target state for document key wraps.\n * - `pendingBaseVersion`: Encoded oplog version through which every persisted\n * op is already enqueued or synced. Persisted so a restart restores the\n * outgoing-delta marker instead of re-seeding it past a device-first\n * `deferRemoteSync` write's un-advanced op. `null` when unset.\n * - `snapshotEndVersion`: Encoded end version vector of the persisted content\n * (which lives in the durable-history tables, never on this row), written on\n * every content persist. Lets the pending-write queue's deferred-tail scan\n * compare version coverage without loading content. Empty string when the\n * document has never hydrated content, which readers treat as \"no deferred\n * tail claimable\".\n * - `recoveryGeneration`: Atomic raw-history recovery writer fence.\n * - `recoveryDocumentId`: Former server id for cross-client post-purge recreation.\n * - `pullContinuation`: Durable progress for the next bounded remote pull.\n * - `syncFailureStatus`, `syncFailureMessage`, `syncFailureAttemptedAt`: The\n * last terminal sync failure or quarantined incoming update for this scope.\n * The durable write queue (queued rows of `documentHistoryUpdates`) has no\n * status columns, so these let the write-queue view and footer explain why\n * the document is blocked. `syncFailureMessage` is non-null exactly when a\n * failure is recorded; a newer failure replaces the old, and a later fully\n * validated sync pass, a remote reset, or the scope's teardown clears all\n * three.\n * - `updatedAt`: Local timestamp for the last persisted runtime-state update.\n *\n * Indexes:\n * - `(appKind, localId)` is the primary key and scopes local document lookups.\n * - `(appKind, documentId) where documentId is not null` supports resolving a\n * server document id back to the local row during discovery and relinking.\n */\nexport const documents = sqliteTable(\n \"documents\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n documentId: text(\"document_id\"),\n accessEpoch: integer(\"access_epoch\").notNull().default(1),\n accessStateHash: text(\"access_state_hash\"),\n effectiveAccessLevel: text(accessLevelColumn).notNull().default(\"read\"),\n lastCommitLsn: text(\"last_commit_lsn\"),\n documentManifestBundle: text(\"document_manifest_bundle\"),\n contentKeyBundle: text(\"content_key_bundle\"),\n documentKekTargets: text(\"document_kek_targets\"),\n pendingBaseVersion: text(\"pending_base_version\"),\n pullContinuation: text(\"pull_continuation\"),\n recoveryGeneration: integer(\"recovery_generation\").notNull().default(0),\n recoveryDocumentId: text(\"recovery_document_id\"),\n snapshotEndVersion: text(\"snapshot_end_version\").notNull().default(\"\"),\n syncFailureStatus: integer(\"sync_failure_status\"),\n syncFailureMessage: text(\"sync_failure_message\"),\n syncFailureAttemptedAt: text(\"sync_failure_attempted_at\"),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.appKind, table.localId] }),\n index(\"documents_app_document_idx\")\n .on(table.appKind, table.documentId)\n .where(sql`${table.documentId} IS NOT NULL`),\n ],\n);\n\n/**\n * Full-history persistence for local documents (checkpoint + tail) — the ONLY\n * durable content source. Record rows in `documents` carry runtime metadata\n * and the content frontier (`snapshotEndVersion`), never content. The\n * checkpoint holds a full-history snapshot refreshed only at compaction, and\n * the tail appends every update (local deltas and decrypted remote updates)\n * written since. Restore = import checkpoint + replay tail; compaction =\n * export full history from the live doc, replace the checkpoint, clear the\n * tail — all bounded and amortized. Container metadata stores its content (an\n * exported-updates blob) as its checkpoint row, with no tail.\n */\nexport const documentHistoryCheckpoints = sqliteTable(\n \"document_history_checkpoints\",\n {\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n snapshot: text(\"snapshot\").notNull(),\n endVersionVector: text(\"end_version_vector\").notNull(),\n revision: text(\"revision\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.appKind, table.localId] })],\n);\n\n/**\n * The local update log: one row per Loro update, serving as both the history\n * tail (restore = checkpoint + tail) and the outbound write queue.\n *\n * Every locally authored update is stored once. While it waits for sync it\n * carries an `updateId` (the id submitted to the server) and the version-vector\n * metadata the submission needs; settlement clears them, leaving the row as\n * ordinary tail history until compaction folds it into a checkpoint.\n *\n * Columns:\n * - `id`: Row id; tail compaction deletes by it.\n * - `appKind`, `localId`: Document scope matching `documents`.\n * - `updateData`: Serialized Loro update payload.\n * - `origin`: \"local\" (authored on this device) or \"remote\" (decrypted\n * pulled update) for tail rows. Restores use it to advance the\n * outgoing-delta marker across remote rows — their ops are already\n * server-side — while a local row left behind by a crash stays below the\n * marker so the next edit re-derives and sends it. \"outbox\" marks a queued\n * update with no tail role (container metadata, whose content is its\n * checkpoint, and full-state re-uploads after a remote reset); restores and\n * compaction never see it and settlement deletes it.\n * - `createdAt`: Insertion timestamp; with `rowid`, deterministic replay order.\n * - `updateId`: Present exactly while the row is queued for sync; rekeyed\n * after a lost acknowledgement poisons the submitted id.\n * - `partialStartVersionVector` / `partialEndVersionVector`: Version vectors\n * around a queued partial update.\n * - `sourceVersionVector`: Present on a queued rotation baseline checkpoint.\n * - `rekeyCount`: Durable bound on rekeys of a queued row.\n *\n * Invariant: compaction never deletes a queued row, so a checkpoint can cover\n * a queued update's operations without removing it from the queue.\n */\nexport const documentHistoryUpdates = sqliteTable(\n \"document_history_updates\",\n {\n id: text(\"id\"),\n appKind: text(\"app_kind\").notNull(),\n localId: text(\"local_id\").notNull(),\n updateData: text(\"update_data\").notNull(),\n origin: text(\"origin\").notNull(),\n createdAt: text(\"created_at\").notNull(),\n updateId: text(\"update_id\"),\n partialStartVersionVector: text(\"partial_start_version_vector\"),\n partialEndVersionVector: text(\"partial_end_version_vector\"),\n sourceVersionVector: text(\"source_version_vector\"),\n rekeyCount: integer(\"rekey_count\").notNull().default(0),\n },\n (table) => [\n primaryKey({ columns: [table.id] }),\n index(\"document_history_updates_scope_created_idx\").on(\n table.appKind,\n table.localId,\n table.createdAt,\n ),\n uniqueIndex(\"document_history_updates_update_id_idx\")\n .on(table.updateId)\n .where(sql`${table.updateId} IS NOT NULL`),\n ],\n);\n\n/**\n * Anti-rollback pin for verified access manifests.\n *\n * Records the highest access-manifest epoch this client has verified for each\n * object, so a later projection that serves an older epoch (rollback) or a\n * conflicting manifest at the same epoch (equivocation) is detected before any\n * key is unwrapped. Updated monotonically after a projection verifies cleanly.\n *\n * Columns:\n * - `objectKind`: Access object kind (`container`, `document`, ...).\n * - `organizationId`: Organization boundary that owns the object.\n * - `objectId`: Stable object id.\n * - `epoch`: Highest verified manifest epoch.\n * - `manifestHash`: Manifest hash pinned at that epoch.\n * - `updatedAt`: Local timestamp for the pin.\n *\n * Indexes:\n * - `(objectKind, organizationId, objectId)` is the primary key and gives one\n * pin per object.\n */\nexport const accessManifestCheckpoints = sqliteTable(\n \"access_manifest_checkpoints\",\n {\n objectKind: text(\"object_kind\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n objectId: text(\"object_id\").notNull(),\n epoch: integer(\"epoch\").notNull(),\n manifestHash: text(\"manifest_hash\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [\n primaryKey({\n columns: [table.objectKind, table.organizationId, table.objectId],\n }),\n ],\n);\n\n/**\n * Durable terminal pins for documents whose signed purge proof was verified.\n * These survive remote-state resets so a dishonest API cannot later replay the\n * pre-purge writer projection and resurrect locally deleted content.\n */\nexport const documentPurgeCheckpoints = sqliteTable(\n \"document_purge_checkpoints\",\n {\n documentId: text(\"document_id\").primaryKey(),\n organizationId: text(\"organization_id\").notNull(),\n documentManifestHash: text(\"document_manifest_hash\").notNull(),\n purgeEventHash: text(\"purge_event_hash\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n);\n\n/**\n * Durable pins for user identity bundles.\n *\n * The first validated identity accepted for a user in a configured API trust\n * domain is inserted once. Later observations must match every suite, public\n * key, and fingerprint exactly; the persistence adapter never changes those\n * columns. `firstSeenAt` records when the local trust decision was made and is\n * likewise immutable. `provenance` (`self`, `link`, or `observed`) records how\n * the pin was established; only `self` and `link` admit a user, and it only\n * rises. A table without it is an obsolete local database.\n *\n * Indexes:\n * - `(identityTrustDomain, userId)` is the primary key and scopes a user pin to\n * the host-configured API authority that supplied it.\n * - `(identityTrustDomain, signingKeyFingerprint)` binds the reverse identity\n * mapping durably, including across session recreation. There is no\n * migration for a table that already violates it. Earlier builds pinned a\n * registration's user id before the server confirmed it, so a device that\n * ran one may hold two users on one key; deployments are greenfield, and\n * such a device clears its local data, which recreates this table empty. A\n * device that used an environment before a reset does the same (see\n * docs/developer/greenfield-reset.md).\n */\nexport const trustedUserIdentityPins = sqliteTable(\n \"trusted_user_identity_pins\",\n {\n identityTrustDomain: text(\"identity_trust_domain\").notNull(),\n userId: text(\"user_id\").notNull(),\n formatVersion: integer(\"format_version\").notNull(),\n signingSuite: text(\"signing_suite\").notNull(),\n signingPublicKey: text(\"signing_public_key\").notNull(),\n signingKeyFingerprint: text(\"signing_key_fingerprint\").notNull(),\n encapsulationSuite: text(\"encapsulation_suite\").notNull(),\n encapsulationPublicKey: text(\"encapsulation_public_key\").notNull(),\n encapsulationKeyFingerprint: text(\n \"encapsulation_key_fingerprint\",\n ).notNull(),\n firstSeenAt: text(\"first_seen_at\").notNull(),\n provenance: text(\"provenance\", {\n enum: [\"self\", \"link\", \"observed\"],\n }).notNull(),\n },\n (table) => [\n primaryKey({\n columns: [table.identityTrustDomain, table.userId],\n }),\n uniqueIndex(\"trusted_user_identity_pins_domain_signing_fingerprint_idx\").on(\n table.identityTrustDomain,\n table.signingKeyFingerprint,\n ),\n ],\n);\n\n/**\n * Local many-to-many projection between documents and containers.\n *\n * The document summary row stores one selected `containerId` for primary list\n * placement, while this table keeps the full set of linked containers returned\n * by container/document sync. Removing a container deletes its links and may\n * repair affected document summary rows to point at another remaining link.\n *\n * Columns:\n * - `documentId`: Server document id whose container links are projected.\n * - `containerId`: Linked container id.\n * - `updatedAt`: Local timestamp for the last replacement of the link set.\n *\n * Indexes:\n * - `(documentId, containerId)` is the primary key and prevents duplicate\n * links for the same document/container pair.\n */\nexport const documentContainerProjection = sqliteTable(\n \"document_container_projection\",\n {\n documentId: text(\"document_id\").notNull(),\n containerId: text(\"container_id\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.documentId, table.containerId] })],\n);\n\n/**\n * Queryable document summary and detail projection.\n *\n * The durable Loro state lives in `documents`. This table stores the fields the\n * app needs for document lists, summaries, and fast detail hydration without\n * opening the full Loro snapshot on every read.\n *\n * Columns:\n * - `localId`: Stable local document id. This joins to `documents.localId` for\n * rows where `documents.appKind = documents`.\n * - `documentId`: Server document id when known.\n * - `containerId`: Selected container for primary document placement, or\n * `null` if the document is not currently linked to a visible container.\n * - `organizationId`: Last-known owning organization. Stamped from the\n * container row when the document is detached because its container was\n * removed locally (e.g. access to a shared org was revoked and the container\n * tombstoned), so pending writes keep their org attribution after the\n * `containers` join source disappears. Read as a fallback only — a live\n * container join always wins.\n * - `documentKind`: Stored document kind. Defaults to `note`.\n * - `title`: Plain projected title. Defaults to the note fallback title.\n * - `updatedAt`: Timestamp used for document list ordering.\n *\n * The projected full text lives in `documentProjectionText`, keyed by the same\n * `localId`. Keeping it out of this row keeps list/window scans narrow: the\n * sidebar and summary queries read titles and placement from rows whose size\n * does not grow with document content.\n *\n * Indexes:\n * - `localId` is the primary key for document projection lookups.\n * - `(containerId) where containerId is not null` serves container-scoped\n * window/count scans without walking the whole table.\n * - `(organizationId) where containerId is null` serves the orphan-recovery\n * existence and window scans.\n * - `(documentId) where documentId is not null` serves the linked-placement\n * join from `documentContainerProjection` and server-id lookups.\n */\nexport const documentProjection = sqliteTable(\n \"document_projection\",\n {\n localId: text(\"local_id\"),\n documentId: text(\"document_id\"),\n containerId: text(\"container_id\"),\n organizationId: text(\"organization_id\"),\n documentKind: text(\"document_kind\").notNull().default(\"note\"),\n title: text(\"title\").notNull().default(\"Untitled note\"),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.localId] }),\n index(\"document_projection_container_idx\")\n .on(table.containerId)\n .where(sql`${table.containerId} IS NOT NULL`),\n index(\"document_projection_orphan_organization_idx\")\n .on(table.organizationId)\n .where(sql`${table.containerId} IS NULL`),\n index(\"document_projection_document_idx\")\n .on(table.documentId)\n .where(sql`${table.documentId} IS NOT NULL`),\n ],\n);\n\n/**\n * Projected document text, split from `documentProjection` so content size\n * never bloats the rows that list/window queries scan. Loaded only by detail\n * reads (`loadDocument`) and the save-timestamp change check.\n *\n * Columns:\n * - `localId`: Stable local document id, matching `documentProjection.localId`.\n * - `text`: Plain projected text used to rebuild summaries/details.\n */\nexport const documentProjectionText = sqliteTable(\n \"document_projection_text\",\n {\n localId: text(\"local_id\"),\n text: text(\"text\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.localId] })],\n);\n\n/**\n * Per-lane sync state for container data: the server cursor and the local\n * freshness marker share one row per lane.\n *\n * Container sync is split into lanes, such as a parent-container child lane or\n * a container-document membership lane. The cursor lets the next request\n * resume without replaying the entire tree. The freshness marker records the\n * last fully drained check independently of the cursor: empty server\n * responses do not always carry a new watermark, but startup still needs to\n * know that it recently checked the lane before polling again.\n *\n * Columns:\n * - `laneKind`: Sync lane category, such as `container_parent` or\n * `container_documents`.\n * - `laneId`: Lane identity. Root parent sync uses `root`, child sync uses a\n * parent-prefixed container id, and document lanes use the container id.\n * - `watermarkUpdatedAt`: Server `updatedAt` value for the stored watermark;\n * null until a watermark is saved.\n * - `watermarkId`: Server id tie-breaker for the stored watermark; null\n * exactly when `watermarkUpdatedAt` is.\n * - `updatedAt`: Local timestamp for when the cursor was saved.\n * - `checkedAt`: Local timestamp for the most recent fully drained lane check;\n * null until one completes.\n *\n * Indexes:\n * - `(laneKind, laneId)` is the primary key and stores one row per lane.\n */\nexport const containerSyncWatermarks = sqliteTable(\n \"container_sync_watermarks\",\n {\n laneKind: text(\"lane_kind\").notNull(),\n laneId: text(\"lane_id\").notNull(),\n watermarkUpdatedAt: text(\"watermark_updated_at\"),\n watermarkId: text(\"watermark_id\"),\n updatedAt: text(\"updated_at\"),\n checkedAt: text(\"checked_at\"),\n },\n (table) => [primaryKey({ columns: [table.laneKind, table.laneId] })],\n);\n\nexport const documentTables: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(documents),\n requiredColumns: [\n \"pull_continuation\",\n \"recovery_generation\",\n \"recovery_document_id\",\n \"sync_failure_status\",\n \"sync_failure_message\",\n \"sync_failure_attempted_at\",\n ],\n },\n defineSqlTableSchema(documentHistoryCheckpoints),\n {\n ...defineSqlTableSchema(documentHistoryUpdates),\n requiredColumns: [\"update_id\"],\n },\n];\n\nexport const principalPolicyTables: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(principalPolicies),\n requiredColumns: [\"current_grants_json\"],\n },\n {\n ...defineSqlTableSchema(principalPolicyBundleHistory),\n requiredColumns: [\"current_grants_json\"],\n },\n defineSqlTableSchema(principalPolicyBundleReferences),\n defineSqlTableSchema(principalPolicyOrganizations),\n ...principalHistoryStageTables,\n ...principalHistoryEvidenceTables,\n];\n\nexport const keyingCheckpointTables: ReadonlyArray<SqlTableSchema> = [\n defineSqlTableSchema(organizationFounders),\n defineSqlTableSchema(accessManifestCheckpoints),\n defineSqlTableSchema(principalGrantRetirements),\n defineSqlTableSchema(documentPurgeCheckpoints),\n defineSqlTableSchema(principalPolicyCheckpoints),\n];\n\nexport const trustedUserIdentityPinTables: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(trustedUserIdentityPins),\n requiredColumns: [\"provenance\"],\n },\n];\n\nconst securityIncidentTables: ReadonlyArray<SqlTableSchema> = [\n securityIncidentTable,\n];\n\nexport const containerTables = containerTableSchemas;\n\nexport const documentContainerProjectionTables: ReadonlyArray<SqlTableSchema> =\n [\n defineSqlTableSchema(documentContainerProjection),\n {\n ...defineSqlTableSchema(containerDocumentTombstoneHolds),\n requiredColumns: [\"hidden\"],\n },\n defineSqlTableSchema(pendingDocumentDiscoveries),\n {\n ...defineSqlTableSchema(documentDiscoveryHeads),\n requiredColumns: [\"organization_id\"],\n },\n defineSqlTableSchema(documentDiscoverySequence),\n ];\n\nexport const localIntentTables: ReadonlyArray<SqlTableSchema> = [\n defineSqlTableSchema(localIntents),\n];\n\nexport const documentPlacementIntentTables: ReadonlyArray<SqlTableSchema> = [\n ...localIntentTables,\n defineSqlTableSchema(documentIntentLinkTargets),\n];\n\nexport const documentProjectionTables: ReadonlyArray<SqlTableSchema> = [\n defineSqlTableSchema(documentProjection),\n defineSqlTableSchema(documentProjectionText),\n {\n ...defineSqlTableSchema(documentPendingAttachments),\n requiredColumns: [\"content_sha256\"],\n },\n {\n ...defineSqlTableSchema(documentAttachmentBlobProjection),\n requiredColumns: [\"content_sha256\"],\n },\n documentOrphanBlobReclaimTable,\n];\n\nexport const containerSyncWatermarkTables: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(containerSyncWatermarks),\n requiredColumns: [\"checked_at\"],\n },\n];\n\nexport const clientSqlTables: ReadonlyArray<SqlTableSchema> = [\n ...principalMutationJournalTables,\n ...documentTables,\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ...verifiedManifestBundleTables,\n ...trustedUserIdentityPinTables,\n ...securityIncidentTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentPlacementIntentTables,\n ...documentProjectionTables,\n ...containerSyncWatermarkTables,\n ...organizationReadModelTables,\n ...organizationDataUsage.organizationDataUsageTables,\n ...provisioningAttempt.organizationProvisioningAttemptTables,\n ...organizationSyncPause.organizationSyncPauseTables,\n];\n\nexport const clientSQLiteSchema = {\n principalHistoryNodeReferences,\n principalHistoryRootOwners,\n principalKeyEnvelopeArchive,\n principalMutationJournal,\n principalHistoryEntries,\n principalHistoryNodes,\n principalHistoryPrefixes,\n principalHistoryStages,\n organizationFounders,\n principalGrantRetirements,\n documents,\n principalPolicies,\n principalPolicyBundleHistory,\n principalPolicyBundleReferences,\n principalPolicyOrganizations,\n accessManifestCheckpoints,\n documentPurgeCheckpoints,\n principalPolicyCheckpoints,\n verifiedAccessManifestBundles,\n trustedUserIdentityPins,\n securityIncidents,\n ...containerSQLiteSchema,\n documentContainerProjection,\n localIntents,\n documentIntentLinkTargets,\n documentProjection,\n documentPendingAttachments,\n documentAttachmentBlobProjection,\n documentOrphanBlobReclaims: documentOrphanBlobReclaims,\n containerSyncWatermarks,\n ...organizationReadModelSQLiteSchema,\n ...organizationDataUsage.organizationDataUsageSQLiteSchema,\n ...provisioningAttempt.organizationProvisioningAttemptSQLiteSchema,\n ...organizationSyncPause.organizationSyncPauseSQLiteSchema,\n};\n"]}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Refuses to admit a user (contact, roster, group member, or share recipient)
3
+ * whose pin was not established by a verified identity link or by this
4
+ * device's own keys. A pin observed on first sight cannot stand in for a link.
5
+ */
6
+ export declare class UnverifiedUserIdentityError extends Error {
7
+ readonly code = "user_identity_unverified";
8
+ readonly userId: string;
9
+ constructor(userId: string);
10
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Refuses to admit a user (contact, roster, group member, or share recipient)
3
+ * whose pin was not established by a verified identity link or by this
4
+ * device's own keys. A pin observed on first sight cannot stand in for a link.
5
+ */
6
+ export class UnverifiedUserIdentityError extends Error {
7
+ code = "user_identity_unverified";
8
+ userId;
9
+ constructor(userId) {
10
+ super("Ask this person for their identity link and verify it before adding them.");
11
+ this.name = "UnverifiedUserIdentityError";
12
+ this.userId = userId;
13
+ }
14
+ }
15
+ //# sourceMappingURL=admission.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admission.js","sourceRoot":"","sources":["admission.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,OAAO,2BAA4B,SAAQ,KAAK;IAC3C,IAAI,GAAG,0BAA0B,CAAC;IAClC,MAAM,CAAS;IAExB,YAAY,MAAc;QACxB,KAAK,CACH,2EAA2E,CAC5E,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,6BAA6B,CAAC;QAC1C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF","sourcesContent":["/**\n * Refuses to admit a user (contact, roster, group member, or share recipient)\n * whose pin was not established by a verified identity link or by this\n * device's own keys. A pin observed on first sight cannot stand in for a link.\n */\nexport class UnverifiedUserIdentityError extends Error {\n readonly code = \"user_identity_unverified\";\n readonly userId: string;\n\n constructor(userId: string) {\n super(\n \"Ask this person for their identity link and verify it before adding them.\",\n );\n this.name = \"UnverifiedUserIdentityError\";\n this.userId = userId;\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
+ export { UnverifiedUserIdentityError } from "./admission.js";
1
2
  export { createApiUserIdentitySource } from "./apiAdapter.js";
2
3
  export { parseIdentityLink } from "./identityLink.js";
3
4
  export { requireTrustedUserIdentityResolver } from "./requiredResolver.js";
@@ -1,3 +1,4 @@
1
+ export { UnverifiedUserIdentityError } from "./admission.js";
1
2
  export { createApiUserIdentitySource } from "./apiAdapter.js";
2
3
  export { parseIdentityLink } from "./identityLink.js";
3
4
  export { requireTrustedUserIdentityResolver } from "./requiredResolver.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,kCAAkC,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EACL,gCAAgC,EAChC,sBAAsB,GACvB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,0BAA0B,EAAE,MAAM,eAAe,CAAC;AAO3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export { createApiUserIdentitySource } from \"./apiAdapter\";\nexport { parseIdentityLink } from \"./identityLink\";\nexport { requireTrustedUserIdentityResolver } from \"./requiredResolver\";\nexport {\n createTrustedUserIdentityService,\n loadPinnedUserIdentity,\n} from \"./service\";\nexport { resolveIdentityTrustDomain } from \"./trustDomain\";\nexport type {\n LocalUserIdentityCandidate,\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n TrustedUserIdentityService,\n} from \"./types\";\nexport { validateUserIdentityKeys } from \"./validation\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,kCAAkC,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EACL,gCAAgC,EAChC,sBAAsB,GACvB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,0BAA0B,EAAE,MAAM,eAAe,CAAC;AAO3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export { UnverifiedUserIdentityError } from \"./admission\";\nexport { createApiUserIdentitySource } from \"./apiAdapter\";\nexport { parseIdentityLink } from \"./identityLink\";\nexport { requireTrustedUserIdentityResolver } from \"./requiredResolver\";\nexport {\n createTrustedUserIdentityService,\n loadPinnedUserIdentity,\n} from \"./service\";\nexport { resolveIdentityTrustDomain } from \"./trustDomain\";\nexport type {\n LocalUserIdentityCandidate,\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n TrustedUserIdentityService,\n} from \"./types\";\nexport { validateUserIdentityKeys } from \"./validation\";\n"]}
@@ -1,10 +1,6 @@
1
1
  import type { ExecSql } from "../sqlite/sqlSchema.js";
2
2
  import { type TrustedUserIdentity, type TrustedUserIdentityService, type TrustedUserIdentityServiceDependencies } from "./types.js";
3
- /**
4
- * Read-only: the identity this trust store already pins for `userId`, or null.
5
- * The stored keys must still match their stored fingerprints. Never inserts,
6
- * compares against or replaces a pin.
7
- */
3
+ /** Read-only: the pinned identity for `userId` of any provenance, or null. */
8
4
  export declare function loadPinnedUserIdentity(input: {
9
5
  readonly execSql: ExecSql;
10
6
  readonly identityTrustDomain: string;
@@ -3,6 +3,7 @@ import { base64ToBytes, bytesToBase64 } from "../../internal/encoding/index.js";
3
3
  import { compareOrInsertTrustedUserIdentityPin, loadTrustedUserIdentityPin, loadTrustedUserIdForSigningKey, TrustedUserIdentityPinCorruptError, TrustedUserIdentityPinMismatchError, } from "../persistence/trustedUserIdentityPinPersistence.js";
4
4
  import { TrustedUserIdentityPinContentionError } from "../persistence/trustedUserIdentityPinTransaction.js";
5
5
  import { DatabaseUnavailableError } from "../sync/databaseUnavailable.js";
6
+ import { UnverifiedUserIdentityError } from "./admission.js";
6
7
  import { assertIdentityLinkMatches, createIdentityLink, parseIdentityLink, } from "./identityLink.js";
7
8
  import { brandTrustedUserIdentity, TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE, TRUSTED_USER_IDENTITY_FORMAT_VERSION, TRUSTED_USER_IDENTITY_SIGNING_SUITE, } from "./types.js";
8
9
  import { assertTrustedUserIdentityUserId, validateLocalUserIdentity, validateRemoteUserIdentity, validateUserIdentityKeys, } from "./validation.js";
@@ -34,6 +35,7 @@ async function compareWithDurablePin(input) {
34
35
  encapsulationPublicKey: bytesToBase64(input.identity.encapsulationPublicKey),
35
36
  encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,
36
37
  firstSeenAt: input.firstSeenAt,
38
+ provenance: input.provenance,
37
39
  formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,
38
40
  identityTrustDomain: input.identity.identityTrustDomain,
39
41
  signingKeyFingerprint: input.identity.signingKeyFingerprint,
@@ -60,6 +62,11 @@ async function compareWithDurablePin(input) {
60
62
  throw error;
61
63
  }
62
64
  }
65
+ /**
66
+ * The candidate for `userId` and where it came from: this device's own keys
67
+ * (`self`) or the identity endpoint (`observed`). Provenance follows the
68
+ * source, never the account that happens to be active once a lookup returns.
69
+ */
63
70
  async function resolveCandidate(dependencies, userId, identityTrustDomain) {
64
71
  const localUserId = dependencies.getLocalUserId();
65
72
  if (userId === localUserId) {
@@ -67,35 +74,49 @@ async function resolveCandidate(dependencies, userId, identityTrustDomain) {
67
74
  if (!localIdentity) {
68
75
  throw new KeyingVerificationError("missing_dependency", "Authoritative local identity keys are unavailable");
69
76
  }
70
- return validateLocalUserIdentity({
71
- candidate: localIdentity,
72
- identityTrustDomain,
73
- userId,
74
- });
77
+ return {
78
+ identity: await validateLocalUserIdentity({
79
+ candidate: localIdentity,
80
+ identityTrustDomain,
81
+ userId,
82
+ }),
83
+ source: "self",
84
+ };
75
85
  }
76
86
  const remoteIdentity = await dependencies.remoteSource.load(userId);
77
87
  return remoteIdentity
78
- ? validateRemoteUserIdentity({
79
- candidate: remoteIdentity,
80
- identityTrustDomain,
81
- requestedUserId: userId,
82
- })
88
+ ? {
89
+ identity: await validateRemoteUserIdentity({
90
+ candidate: remoteIdentity,
91
+ identityTrustDomain,
92
+ requestedUserId: userId,
93
+ }),
94
+ source: "observed",
95
+ }
83
96
  : null;
84
97
  }
98
+ /** The trust store and account a lookup started under must still be active. */
99
+ function assertResolutionScope(dependencies, scope, message) {
100
+ if (dependencies.getExecSql() !== scope.execSql ||
101
+ dependencies.getLocalUserId() !== scope.localUserId) {
102
+ throw new DatabaseUnavailableError(message);
103
+ }
104
+ }
85
105
  async function pinIdentity(input) {
86
106
  await compareWithDurablePin({
87
107
  execSql: input.execSql,
88
108
  firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),
89
109
  identity: input.identity,
110
+ provenance: input.provenance,
90
111
  });
91
112
  return brandTrustedUserIdentity(input.identity);
92
113
  }
93
114
  /**
94
- * Read-only: the identity this trust store already pins for `userId`, or null.
95
- * The stored keys must still match their stored fingerprints. Never inserts,
96
- * compares against or replaces a pin.
115
+ * Read-only: the identity this trust store already pins for `userId` and how
116
+ * it was established, or null. The stored keys must still match their stored
117
+ * fingerprints. Never inserts, compares against or replaces a pin.
97
118
  */
98
- export async function loadPinnedUserIdentity(input) {
119
+ async function loadPin(input) {
99
120
  assertTrustedUserIdentityUserId(input.userId);
100
121
  const pin = await loadTrustedUserIdentityPin(input);
101
122
  if (!pin)
@@ -108,11 +129,72 @@ export async function loadPinnedUserIdentity(input) {
108
129
  },
109
130
  encapsulationKeyFingerprint: pin.encapsulationKeyFingerprint,
110
131
  });
111
- return brandTrustedUserIdentity({
112
- ...keys,
113
- identityTrustDomain: input.identityTrustDomain,
114
- userId: input.userId,
115
- });
132
+ return {
133
+ identity: brandTrustedUserIdentity({
134
+ ...keys,
135
+ identityTrustDomain: input.identityTrustDomain,
136
+ userId: input.userId,
137
+ }),
138
+ provenance: pin.provenance,
139
+ };
140
+ }
141
+ /** Read-only: the pinned identity for `userId` of any provenance, or null. */
142
+ export async function loadPinnedUserIdentity(input) {
143
+ return (await loadPin(input))?.identity ?? null;
144
+ }
145
+ /** Compares an independently received link before pinning it as `link`. */
146
+ async function verifyIdentityLink(dependencies, link) {
147
+ const expectation = parseIdentityLink(link);
148
+ const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
149
+ if (expectation.identityTrustDomain !== identityTrustDomain) {
150
+ throw new Error("This identity link belongs to a different Tearleads service.");
151
+ }
152
+ const localUserId = dependencies.getLocalUserId();
153
+ try {
154
+ const candidate = await resolveCandidate(dependencies, expectation.userId, identityTrustDomain);
155
+ if (!candidate)
156
+ throw new Error("The identity in this link is unavailable.");
157
+ await assertIdentityLinkMatches(expectation, candidate.identity);
158
+ assertResolutionScope(dependencies, { execSql, localUserId }, "The active identity changed. Open the identity link again.");
159
+ return await pinIdentity({
160
+ dependencies,
161
+ execSql,
162
+ identity: candidate.identity,
163
+ provenance: candidate.source === "self" ? "self" : "link",
164
+ });
165
+ }
166
+ catch (error) {
167
+ dependencies.remoteSource.invalidate(expectation.userId);
168
+ throw error;
169
+ }
170
+ }
171
+ function admissionScopeChanged() {
172
+ return new DatabaseUnavailableError("The active database changed while admitting this user. Try again.");
173
+ }
174
+ /** Reads that admit a user: only `self` and `link` pins qualify. */
175
+ function verifiedPinReaders(dependencies) {
176
+ const resolveVerified = async (userId) => {
177
+ const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
178
+ const pin = await loadPin({ execSql, identityTrustDomain, userId });
179
+ if (dependencies.getExecSql() !== execSql)
180
+ throw admissionScopeChanged();
181
+ return pin && pin.provenance !== "observed" ? pin.identity : null;
182
+ };
183
+ return {
184
+ resolveVerified,
185
+ async requireVerified(userId, admittingExecSql) {
186
+ const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
187
+ if (execSql !== admittingExecSql)
188
+ throw admissionScopeChanged();
189
+ const pin = await loadPin({ execSql, identityTrustDomain, userId });
190
+ if (dependencies.getExecSql() !== execSql)
191
+ throw admissionScopeChanged();
192
+ if (!pin || pin.provenance === "observed") {
193
+ throw new UnverifiedUserIdentityError(userId);
194
+ }
195
+ return pin.identity;
196
+ },
197
+ };
116
198
  }
117
199
  export function createTrustedUserIdentityService(dependencies) {
118
200
  return {
@@ -120,6 +202,7 @@ export function createTrustedUserIdentityService(dependencies) {
120
202
  const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
121
203
  return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });
122
204
  },
205
+ ...verifiedPinReaders(dependencies),
123
206
  async createLink(appUrl) {
124
207
  const identityTrustDomain = requireTrustDomain(dependencies);
125
208
  const userId = dependencies.getLocalUserId();
@@ -134,29 +217,7 @@ export function createTrustedUserIdentityService(dependencies) {
134
217
  });
135
218
  return createIdentityLink(identity, appUrl);
136
219
  },
137
- async verifyLink(link) {
138
- const expectation = parseIdentityLink(link);
139
- const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
140
- if (expectation.identityTrustDomain !== identityTrustDomain) {
141
- throw new Error("This identity link belongs to a different Tearleads service.");
142
- }
143
- const localUserId = dependencies.getLocalUserId();
144
- try {
145
- const identity = await resolveCandidate(dependencies, expectation.userId, identityTrustDomain);
146
- if (!identity)
147
- throw new Error("The identity in this link is unavailable.");
148
- await assertIdentityLinkMatches(expectation, identity);
149
- if (dependencies.getExecSql() !== execSql ||
150
- dependencies.getLocalUserId() !== localUserId) {
151
- throw new DatabaseUnavailableError("The active identity changed. Open the identity link again.");
152
- }
153
- return await pinIdentity({ dependencies, execSql, identity });
154
- }
155
- catch (error) {
156
- dependencies.remoteSource.invalidate(expectation.userId);
157
- throw error;
158
- }
159
- },
220
+ verifyLink: (link) => verifyIdentityLink(dependencies, link),
160
221
  async boundUserId(signingKeyFingerprint) {
161
222
  const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
162
223
  return loadTrustedUserIdForSigningKey({
@@ -173,17 +234,29 @@ export function createTrustedUserIdentityService(dependencies) {
173
234
  identityTrustDomain,
174
235
  userId,
175
236
  });
176
- return pinIdentity({ dependencies, execSql, identity });
237
+ return pinIdentity({
238
+ dependencies,
239
+ execSql,
240
+ identity,
241
+ provenance: "self",
242
+ });
177
243
  },
178
244
  async resolve(userId) {
179
245
  assertTrustedUserIdentityUserId(userId);
180
246
  const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
247
+ const localUserId = dependencies.getLocalUserId();
181
248
  try {
182
- const identity = await resolveCandidate(dependencies, userId, identityTrustDomain);
183
- if (!identity) {
249
+ const candidate = await resolveCandidate(dependencies, userId, identityTrustDomain);
250
+ if (!candidate) {
184
251
  return null;
185
252
  }
186
- return await pinIdentity({ dependencies, execSql, identity });
253
+ assertResolutionScope(dependencies, { execSql, localUserId }, "The active identity changed while resolving this user.");
254
+ return await pinIdentity({
255
+ dependencies,
256
+ execSql,
257
+ identity: candidate.identity,
258
+ provenance: candidate.source,
259
+ });
187
260
  }
188
261
  catch (error) {
189
262
  dependencies.remoteSource.invalidate(userId);