@tearleads/client-sdk 0.1.242 → 0.1.244

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 (137) hide show
  1. package/client/organizations/currentPrincipalMutations.js +1 -0
  2. package/client/organizations/currentPrincipalMutations.js.map +1 -1
  3. package/client/organizations/principalMutations.d.ts +5 -0
  4. package/client/organizations/principalMutations.js +1 -0
  5. package/client/organizations/principalMutations.js.map +1 -1
  6. package/data/containers/shared/mutationAcknowledgement.d.ts +1 -1
  7. package/data/containers/shared/mutationAcknowledgement.js +3 -8
  8. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  9. package/data/documents/shared/sync/mutationAcknowledgement.js +11 -2
  10. package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -1
  11. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.d.ts +26 -0
  12. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js +46 -0
  13. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js.map +1 -0
  14. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +7 -4
  15. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +5 -1
  16. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
  17. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +9 -2
  18. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  19. package/data/keyingProjectionVerification/document/documentContainerProjections.js +2 -1
  20. package/data/keyingProjectionVerification/document/documentContainerProjections.js.map +1 -1
  21. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +9 -2
  22. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
  23. package/data/keyingProjectionVerification/index.d.ts +1 -0
  24. package/data/keyingProjectionVerification/index.js +1 -0
  25. package/data/keyingProjectionVerification/index.js.map +1 -1
  26. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js +16 -4
  27. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js.map +1 -1
  28. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +13 -0
  29. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +11 -0
  30. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  31. package/data/persistence/verifiedCitations/authoredBundleCitation.d.ts +20 -0
  32. package/data/persistence/verifiedCitations/authoredBundleCitation.js +32 -0
  33. package/data/persistence/verifiedCitations/authoredBundleCitation.js.map +1 -0
  34. package/data/persistence/verifiedManifestBundlePersistence.d.ts +10 -0
  35. package/data/persistence/verifiedManifestBundlePersistence.js +95 -9
  36. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  37. package/data/principals/organizationDirectoryKeying.js +136 -0
  38. package/data/principals/organizationDirectoryKeying.js.map +1 -0
  39. package/data/principals/organizationGroupDirectoryRequest.js +17 -11
  40. package/data/principals/organizationGroupDirectoryRequest.js.map +1 -1
  41. package/internal/api-client/ApiClient.d.ts +55 -0
  42. package/internal/api-client/client/containerMutations.d.ts +11 -0
  43. package/internal/api-client/client/documents.d.ts +5 -0
  44. package/internal/api-client/client/organizations.d.ts +20 -0
  45. package/internal/api-client/client/principalPolicies.d.ts +9 -0
  46. package/internal/api-client/client/session.d.ts +10 -0
  47. package/internal/api-client/principalPolicyRequests.d.ts +7 -0
  48. package/internal/api-client/writerProjectionCitations.d.ts +3 -0
  49. package/internal/api-client/writerProjectionCitations.js +12 -0
  50. package/internal/api-client/writerProjectionCitations.js.map +1 -1
  51. package/internal/crypto/index.d.ts +1 -1
  52. package/internal/crypto/index.js +1 -1
  53. package/internal/crypto/index.js.map +1 -1
  54. package/internal/crypto/keying/canonicalJsonGuard.d.ts +13 -0
  55. package/internal/crypto/keying/canonicalJsonGuard.js +23 -0
  56. package/internal/crypto/keying/canonicalJsonGuard.js.map +1 -1
  57. package/internal/crypto/keying/index.d.ts +1 -1
  58. package/internal/crypto/keying/index.js +1 -1
  59. package/internal/crypto/keying/index.js.map +1 -1
  60. package/internal/crypto/keying/keyingHashDomains.d.ts +1 -1
  61. package/internal/crypto/keying/keyingHashDomains.js.map +1 -1
  62. package/internal/validators/operation/auth.d.ts +40 -0
  63. package/internal/validators/operation/containerMutations.d.ts +44 -0
  64. package/internal/validators/operation/documentMutations.d.ts +12 -0
  65. package/internal/validators/operation/organizations.d.ts +48 -0
  66. package/internal/validators/operation/principals.d.ts +16 -0
  67. package/internal/validators/response/areas/containers.d.ts +1 -1
  68. package/internal/validators/response/areas/containers.js +1 -1
  69. package/internal/validators/response/areas/containers.js.map +1 -1
  70. package/internal/validators/response/container.d.ts +16 -0
  71. package/internal/validators/response/container.js +3 -0
  72. package/internal/validators/response/container.js.map +1 -1
  73. package/internal/validators/response/containerMetadata.d.ts +8 -0
  74. package/internal/validators/response/documentMutation.d.ts +8 -0
  75. package/internal/validators/response/documentMutation.js +2 -1
  76. package/internal/validators/response/documentMutation.js.map +1 -1
  77. package/internal/validators/response/organization.d.ts +8 -0
  78. package/internal/validators/response/organizationProvisioning.d.ts +113 -0
  79. package/internal/validators/response/organizationProvisioning.js +2 -1
  80. package/internal/validators/response/organizationProvisioning.js.map +1 -1
  81. package/internal/validators/response/principal.d.ts +16 -0
  82. package/internal/validators/response/registration.d.ts +40 -0
  83. package/internal/validators/response/writerProjectionWire.d.ts +25 -0
  84. package/internal/validators/response/writerProjectionWire.js +109 -3
  85. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  86. package/package.json +1 -1
  87. package/stores/documents/documentStore/rotation/index.js +3 -1
  88. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  89. package/stores/documents/documentStore/sync/syncAttachments.js +4 -1
  90. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  91. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -1
  92. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  93. package/stores/documents/documentStore/sync/syncRequest.js +3 -1
  94. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  95. package/workflows/container-contents/container-state/create/createAdoption.js +11 -3
  96. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  97. package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
  98. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  99. package/workflows/container-contents/container-state/projectionCache.js +3 -0
  100. package/workflows/container-contents/container-state/projectionCache.js.map +1 -1
  101. package/workflows/container-contents/metadata/index.js +5 -2
  102. package/workflows/container-contents/metadata/index.js.map +1 -1
  103. package/workflows/containers/child/recite.js +4 -2
  104. package/workflows/containers/child/recite.js.map +1 -1
  105. package/workflows/documents/create/createAdoption.js +11 -2
  106. package/workflows/documents/create/createAdoption.js.map +1 -1
  107. package/workflows/documents/create/createResponse.js +1 -0
  108. package/workflows/documents/create/createResponse.js.map +1 -1
  109. package/workflows/documents/linkSet/linkSetRemote.js +1 -0
  110. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  111. package/workflows/documents/sync/syncAttemptPlanning.js +8 -2
  112. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  113. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +3 -2
  114. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  115. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js +3 -2
  116. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js.map +1 -1
  117. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js +1 -0
  118. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
  119. package/workflows/organizations/groupShare/currentShareGrantMutation.js +3 -0
  120. package/workflows/organizations/groupShare/currentShareGrantMutation.js.map +1 -1
  121. package/workflows/organizations/groupShare/shareWithGroup.js +2 -0
  122. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
  123. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +3 -0
  124. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  125. package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js +1 -0
  126. package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js.map +1 -1
  127. package/workflows/organizations/groups/deleteOrganizationGroup.d.ts +2 -0
  128. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -0
  129. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  130. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -0
  131. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  132. package/workflows/organizations/principalPolicy/index.d.ts +12 -0
  133. package/workflows/organizations/principalPolicy/index.js +11 -0
  134. package/workflows/organizations/principalPolicy/index.js.map +1 -1
  135. package/workflows/registration/organizationCreation/organizationCreationIntent.d.ts +10 -0
  136. package/workflows/registration/provisioningAcknowledgement.js +16 -11
  137. package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
@@ -167,6 +167,18 @@ export async function loadVerifiedManifestCitations(execSql, target, requestedLi
167
167
  const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));
168
168
  if (!(limit > 0))
169
169
  return [];
170
+ const loadGeneration = evictionGeneration;
171
+ citationLoadsInFlight += 1;
172
+ try {
173
+ return await loadCitableManifestCitations(execSql, target, limit).then((cited) => cited.filter((citation) => citable(citation, loadGeneration)));
174
+ }
175
+ finally {
176
+ citationLoadsInFlight -= 1;
177
+ if (citationLoadsInFlight === 0)
178
+ evictedInGeneration.clear();
179
+ }
180
+ }
181
+ async function loadCitableManifestCitations(execSql, target, limit) {
170
182
  await ensureSqlTables(execSql, [
171
183
  ...verifiedManifestBundleTables,
172
184
  ...containerTables,
@@ -181,17 +193,91 @@ export async function loadVerifiedManifestCitations(execSql, target, requestedLi
181
193
  return [];
182
194
  const { cited, damaged } = await collectVerifiedManifestCitations(db, organizationId, objects, target, limit);
183
195
  if (damaged.length > 0)
184
- await getClientSQLitePersistenceRuntime(execSql)
185
- .runMutation(async (handle) => {
186
- for (const batch of batches([...new Set(damaged)]))
187
- await handle
188
- .delete(bundles)
189
- .where(inArray(bundles.manifestHash, batch))
190
- .run();
191
- })
192
- .catch(() => undefined);
196
+ await dropVerifiedManifestBundles(execSql, damaged).catch(() => undefined);
193
197
  return cited;
194
198
  }
199
+ // Manifest hashes whose held rows a refused read is dropping: no read cites
200
+ // them meanwhile, so none can be rebuilt from the bytes being dropped. Each
201
+ // eviction also advances a generation, so a citation load that started
202
+ // before it never returns the rows it read: they may already be gone.
203
+ const suppressedCitations = new Map();
204
+ const evictedInGeneration = new Map();
205
+ let evictionGeneration = 0;
206
+ // Loads in flight; once none overlap, the eviction log has nothing to guard.
207
+ let citationLoadsInFlight = 0;
208
+ /** Keeps these held bundles out of citations until the release runs. */
209
+ export function suppressHeldCitations(manifestHashes) {
210
+ evictionGeneration += 1;
211
+ for (const hash of manifestHashes) {
212
+ suppressedCitations.set(hash, (suppressedCitations.get(hash) ?? 0) + 1);
213
+ evictedInGeneration.set(hash, evictionGeneration);
214
+ }
215
+ return () => {
216
+ // The drop is complete: a load that started before now may hold the
217
+ // dropped bytes, so it is newer than none of them.
218
+ evictionGeneration += 1;
219
+ for (const hash of manifestHashes) {
220
+ evictedInGeneration.set(hash, evictionGeneration);
221
+ const count = (suppressedCitations.get(hash) ?? 1) - 1;
222
+ if (count > 0)
223
+ suppressedCitations.set(hash, count);
224
+ else
225
+ suppressedCitations.delete(hash);
226
+ }
227
+ };
228
+ }
229
+ function citable(citation, loadGeneration) {
230
+ if (!("manifestHash" in citation))
231
+ return true;
232
+ const { manifestHash } = citation;
233
+ return (!suppressedCitations.has(manifestHash) &&
234
+ (evictedInGeneration.get(manifestHash) ?? 0) <= loadGeneration);
235
+ }
236
+ /**
237
+ * Drops the stored rows of held bundles a projection that cited them failed
238
+ * to verify with, so the next read fetches them from the server. Only a row
239
+ * still holding the exact bytes cited goes, so a newer verified copy written
240
+ * meanwhile stays; nothing is dropped once `stillCurrent` turns false.
241
+ * Resolves whether the drop committed.
242
+ */
243
+ export async function dropHeldManifestBundles(execSql, heldBundles, stillCurrent) {
244
+ if (heldBundles.length === 0)
245
+ return true;
246
+ const cited = await Promise.all(heldBundles.map(async (bundle) => ({
247
+ manifestHash: bundle.manifestHash,
248
+ bundleDigest: await sha256Hex(JSON.stringify(bundle)),
249
+ })));
250
+ await ensureSqlTables(execSql, verifiedManifestBundleTables);
251
+ const runtime = getClientSQLitePersistenceRuntime(execSql);
252
+ const drop = async (tx) => {
253
+ for (const row of cited)
254
+ await tx
255
+ .delete(bundles)
256
+ .where(and(eq(bundles.manifestHash, row.manifestHash), eq(bundles.bundleDigest, row.bundleDigest)))
257
+ .run();
258
+ };
259
+ if (!stillCurrent) {
260
+ await runtime.transaction(drop, { behavior: "immediate" });
261
+ return true;
262
+ }
263
+ const { committed } = await runtime.guardedTransaction(drop, stillCurrent, {
264
+ behavior: "immediate",
265
+ });
266
+ return committed;
267
+ }
268
+ /** Drops damaged stored rows so no later read cites them. */
269
+ async function dropVerifiedManifestBundles(execSql, manifestHashes) {
270
+ if (manifestHashes.length === 0)
271
+ return;
272
+ await ensureSqlTables(execSql, verifiedManifestBundleTables);
273
+ await getClientSQLitePersistenceRuntime(execSql).runMutation(async (handle) => {
274
+ for (const batch of batches([...new Set(manifestHashes)]))
275
+ await handle
276
+ .delete(bundles)
277
+ .where(inArray(bundles.manifestHash, batch))
278
+ .run();
279
+ });
280
+ }
195
281
  /** Cites from whichever database the signed-in identity currently uses. */
196
282
  export function createVerifiedManifestCitations(resolveExecSql) {
197
283
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedManifestBundlePersistence.js","sourceRoot":"","sources":["verifiedManifestBundlePersistence.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EACL,yBAAyB,GAE1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EA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AAE;SACL,MAAM,CAAC,OAAO,CAAC;SACf,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;SACjD,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import type {\n HeldProjectionCitation,\n VerifiedManifestCitations,\n WriterProjectionTarget,\n} from \"@tearleads/api-client\";\nimport { toFingerprint } from \"@tearleads/crypto\";\nimport {\n KNOWN_MANIFEST_HINT_LIMIT,\n type ServedAccessManifestBundleWireResponse,\n} from \"@tearleads/validators/util\";\nimport { and, asc, eq, inArray, notInArray, sql } from \"drizzle-orm\";\nimport { containerTables, localIntentTables } from \"../sqlite/schema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../sqlite/schema/documentProjectionSchema\";\nimport {\n verifiedAccessManifestBundles as bundles,\n verifiedManifestBundleTables,\n} from \"../sqlite/schema/verifiedManifestBundleSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../sqlite/sqliteUpsert\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { collectVerifiedManifestCitations } from \"./verifiedCitations/citationCollection\";\nimport {\n citedObjects,\n targetOrganization,\n} from \"./verifiedCitations/citationScope\";\nimport {\n KEK_LEVEL_OBJECT_KIND,\n kekLevelRow,\n type VerifiedKekLevel,\n} from \"./verifiedCitations/kekLevelCitations\";\n\n/**\n * Bounds local bytes (a bundle is ~10–20 KB). Evicting the least recently\n * verified rows only makes a later read carry those bundles again.\n */\nexport const MAX_VERIFIED_MANIFEST_BUNDLES = 1024;\nconst STATEMENT_BATCH = 200;\n\ninterface VerifiedBundle {\n /** The served bytes; the decoded state is rebuilt from them on refill. */\n readonly bundle: ServedAccessManifestBundleWireResponse;\n readonly checkpoint: {\n readonly objectKind: string;\n readonly organizationId: string;\n readonly objectId: string;\n readonly epoch: number;\n };\n}\n\n/** Bytes a projection verification accepted: a bundle or a KEK level. */\nexport type VerifiedManifestBundle = VerifiedBundle | VerifiedKekLevel;\n\nfunction sha256Hex(text: string): Promise<string> {\n return toFingerprint(new TextEncoder().encode(text));\n}\n\nconst BUNDLE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(bundles);\n\nfunction slices<T>(values: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < values.length; index += size)\n result.push(values.slice(index, index + size));\n return result;\n}\n\nfunction batches<T>(values: readonly T[]): T[][] {\n return slices(values, STATEMENT_BATCH);\n}\n\nasync function pruneInTransaction(\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n const [row] = await tx.select({ count: sql<number>`count(*)` }).from(bundles);\n const excess = (row?.count ?? 0) - MAX_VERIFIED_MANIFEST_BUNDLES;\n if (excess <= 0) return;\n const evicted = await tx\n .select({ manifestHash: bundles.manifestHash })\n .from(bundles)\n .orderBy(asc(bundles.verifiedAt), asc(bundles.manifestHash))\n .limit(excess);\n for (const batch of batches(evicted.map((entry) => entry.manifestHash)))\n await tx.delete(bundles).where(inArray(bundles.manifestHash, batch)).run();\n}\n\n/** A verified bundle's exact JSON and that JSON's digest. */\nexport type VerifiedManifestBundleRow = Omit<\n typeof bundles.$inferInsert,\n \"verifiedAt\"\n>;\n\n/**\n * Prepares rows for bundles and KEK levels that just passed projection\n * verification. The digests are computed here, before the checkpoint\n * transaction that writes them begins.\n */\nexport async function verifiedManifestBundleRows(\n entries: readonly VerifiedManifestBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleEntries: VerifiedBundle[] = [];\n const levelEntries: VerifiedKekLevel[] = [];\n for (const entry of entries)\n if (\"kekLevel\" in entry) levelEntries.push(entry);\n else bundleEntries.push(entry);\n // One level per container: its newest epoch, the last one seen on a tie.\n const levelRows = new Map<string, VerifiedManifestBundleRow>();\n for (const level of levelEntries) {\n const row = await kekLevelRow(level);\n const held = row && levelRows.get(row.objectId);\n if (row && (!held || held.epoch <= row.epoch))\n levelRows.set(row.objectId, row);\n }\n return [...(await bundleRows(bundleEntries)), ...levelRows.values()];\n}\n\nfunction bundleRows(\n entries: readonly VerifiedBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const unique = new Map(\n entries.map((entry) => [entry.bundle.manifestHash, entry]),\n );\n return Promise.all(\n [...unique.values()].map(async ({ bundle, checkpoint }) => {\n const bundleJson = JSON.stringify(bundle);\n return {\n manifestHash: bundle.manifestHash,\n organizationId: checkpoint.organizationId,\n objectKind: checkpoint.objectKind,\n objectId: checkpoint.objectId,\n epoch: checkpoint.epoch,\n bundleJson,\n bundleDigest: await sha256Hex(bundleJson),\n };\n }),\n );\n}\n\n/**\n * Records verified bundles inside the transaction that finalizes their\n * projection's checkpoints, so they commit or roll back with it and no cache\n * work outlives the verification. Freshly verified bytes replace any stored\n * copy.\n */\nexport async function writeVerifiedManifestBundlesInTransaction(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n verifiedAt: string,\n): Promise<void> {\n if (rows.length === 0) return;\n const stored = await touchStoredDigests(\n tx,\n rows.map((row) => row.manifestHash),\n verifiedAt,\n );\n // A repeated hash keeps its last changed row, as sequential upserts would.\n const changed = new Map(\n rows\n .filter((row) => stored.get(row.manifestHash) !== row.bundleDigest)\n .map((row) => [row.manifestHash, { ...row, verifiedAt }]),\n );\n for (const batch of slices([...changed.values()], BUNDLE_WRITE_BATCH_SIZE))\n await tx\n .insert(bundles)\n .values(batch)\n .onConflictDoUpdate({\n target: bundles.manifestHash,\n set: {\n organizationId: excludedValue(bundles.organizationId),\n objectKind: excludedValue(bundles.objectKind),\n objectId: excludedValue(bundles.objectId),\n epoch: excludedValue(bundles.epoch),\n bundleJson: excludedValue(bundles.bundleJson),\n bundleDigest: excludedValue(bundles.bundleDigest),\n verifiedAt: excludedValue(bundles.verifiedAt),\n },\n })\n .run();\n // All incremental SDK level writes pass here. Both checkpoint callers\n // prepare them with verifiedManifestBundleRows (one level per container),\n // then write and drop siblings in the same serialized transaction. Thus an\n // unchanged level already removed its siblings; eviction/reset only delete.\n // Restored caches must preserve that invariant too: this fast path does not\n // repair externally injected stale siblings.\n await dropSupersededKekLevels(tx, [...changed.values()]);\n // Replacing or touching existing rows cannot grow the bounded cache.\n if (rows.some((row) => !stored.has(row.manifestHash))) {\n await pruneInTransaction(tx);\n }\n}\n\n/**\n * A container keeps only its latest verified level: the API serves its\n * current level, so an older one can never be cited usefully again.\n */\nasync function dropSupersededKekLevels(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n): Promise<void> {\n const levels = rows.filter((row) => row.objectKind === KEK_LEVEL_OBJECT_KIND);\n for (const batch of batches(levels))\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.objectKind, KEK_LEVEL_OBJECT_KIND),\n inArray(\n bundles.objectId,\n batch.map((row) => row.objectId),\n ),\n notInArray(\n bundles.manifestHash,\n batch.map((row) => row.manifestHash),\n ),\n ),\n )\n .run();\n}\n\nasync function touchStoredDigests(\n tx: ClientSQLiteTransactionScope,\n manifestHashes: readonly string[],\n verifiedAt: string,\n): Promise<Map<string, string>> {\n const digests = new Map<string, string>();\n for (const batch of batches(manifestHashes)) {\n const rows = await tx\n .update(bundles)\n .set({ verifiedAt })\n .where(inArray(bundles.manifestHash, batch))\n .returning({\n bundleDigest: bundles.bundleDigest,\n manifestHash: bundles.manifestHash,\n });\n for (const row of rows) digests.set(row.manifestHash, row.bundleDigest);\n }\n return digests;\n}\n\n/**\n * The latest verified KEK level of each container the target's projection\n * walks (supplemented by organization-recency levels for a pending move,\n * or when the lineage has no stored level); then verified bundles of those\n * objects, newest epochs first; then\n * the most recently verified bundles of its organization, since a\n * just-verified parent is the likeliest part of a new child's projection.\n * Citations never leave the target's organization: an object whose\n * organization the device cannot place cites nothing. Damaged rows are\n * dropped.\n */\nexport async function loadVerifiedManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n requestedLimit = KNOWN_MANIFEST_HINT_LIMIT,\n): Promise<HeldProjectionCitation[]> {\n const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));\n if (!(limit > 0)) return [];\n await ensureSqlTables(execSql, [\n ...verifiedManifestBundleTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...localIntentTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const objects = await citedObjects(db, target);\n const organizationId = await targetOrganization(db, target, objects);\n if (organizationId === null) return [];\n const { cited, damaged } = await collectVerifiedManifestCitations(\n db,\n organizationId,\n objects,\n target,\n limit,\n );\n if (damaged.length > 0)\n await getClientSQLitePersistenceRuntime(execSql)\n .runMutation(async (handle) => {\n for (const batch of batches([...new Set(damaged)]))\n await handle\n .delete(bundles)\n .where(inArray(bundles.manifestHash, batch))\n .run();\n })\n .catch(() => undefined);\n return cited;\n}\n\n/** Cites from whichever database the signed-in identity currently uses. */\nexport function createVerifiedManifestCitations(\n resolveExecSql: () => ExecSql | null,\n): VerifiedManifestCitations {\n return {\n cite: async (target) => {\n const execSql = resolveExecSql();\n return execSql ? loadVerifiedManifestCitations(execSql, target) : [];\n },\n };\n}\n\n/** Drops an organization's verified bundles when a remote reset forgets it. */\nexport async function deleteVerifiedManifestBundlesForOrganization(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n await tx\n .delete(bundles)\n .where(eq(bundles.organizationId, organizationId))\n .run();\n}\n"]}
1
+ {"version":3,"file":"verifiedManifestBundlePersistence.js","sourceRoot":"","sources":["verifiedManifestBundlePersistence.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EACL,yBAAyB,GAE1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,EA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6D;AAC7D,KAAK,UAAU,2BAA2B,CACxC,OAAgB,EAChB,cAAiC;IAEjC,IAAI,cAAc,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IACxC,MAAM,eAAe,CAAC,OAAO,EAAE,4BAA4B,CAAC,CAAC;IAC7D,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAC1D,KAAK,EAAE,MAAM,EAAE,EAAE;QACf,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC;YACvD,MAAM,MAAM;iBACT,MAAM,CAAC,OAAO,CAAC;iBACf,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;iBAC3C,GAAG,EAAE,CAAC;IACb,CAAC,CACF,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,+BAA+B,CAC7C,cAAoC;IAEpC,OAAO;QACL,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;YACrB,MAAM,OAAO,GAAG,cAAc,EAAE,CAAC;YACjC,OAAO,OAAO,CAAC,CAAC,CAAC,6BAA6B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACvE,CAAC;KACF,CAAC;AACJ,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAChE,EAAgC,EAChC,cAAsB;IAEtB,MAAM,EAAE;SACL,MAAM,CAAC,OAAO,CAAC;SACf,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;SACjD,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import type {\n HeldProjectionCitation,\n VerifiedManifestCitations,\n WriterProjectionTarget,\n} from \"@tearleads/api-client\";\nimport { toFingerprint } from \"@tearleads/crypto\";\nimport {\n KNOWN_MANIFEST_HINT_LIMIT,\n type ServedAccessManifestBundleWireResponse,\n} from \"@tearleads/validators/util\";\nimport { and, asc, eq, inArray, notInArray, sql } from \"drizzle-orm\";\nimport { containerTables, localIntentTables } from \"../sqlite/schema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../sqlite/schema/documentProjectionSchema\";\nimport {\n verifiedAccessManifestBundles as bundles,\n verifiedManifestBundleTables,\n} from \"../sqlite/schema/verifiedManifestBundleSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../sqlite/sqliteUpsert\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { collectVerifiedManifestCitations } from \"./verifiedCitations/citationCollection\";\nimport {\n citedObjects,\n targetOrganization,\n} from \"./verifiedCitations/citationScope\";\nimport {\n KEK_LEVEL_OBJECT_KIND,\n kekLevelRow,\n type VerifiedKekLevel,\n} from \"./verifiedCitations/kekLevelCitations\";\n\n/**\n * Bounds local bytes (a bundle is ~10–20 KB). Evicting the least recently\n * verified rows only makes a later read carry those bundles again.\n */\nexport const MAX_VERIFIED_MANIFEST_BUNDLES = 1024;\nconst STATEMENT_BATCH = 200;\n\ninterface VerifiedBundle {\n /** The served bytes; the decoded state is rebuilt from them on refill. */\n readonly bundle: ServedAccessManifestBundleWireResponse;\n readonly checkpoint: {\n readonly objectKind: string;\n readonly organizationId: string;\n readonly objectId: string;\n readonly epoch: number;\n };\n}\n\n/** Bytes a projection verification accepted: a bundle or a KEK level. */\nexport type VerifiedManifestBundle = VerifiedBundle | VerifiedKekLevel;\n\nfunction sha256Hex(text: string): Promise<string> {\n return toFingerprint(new TextEncoder().encode(text));\n}\n\nconst BUNDLE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(bundles);\n\nfunction slices<T>(values: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < values.length; index += size)\n result.push(values.slice(index, index + size));\n return result;\n}\n\nfunction batches<T>(values: readonly T[]): T[][] {\n return slices(values, STATEMENT_BATCH);\n}\n\nasync function pruneInTransaction(\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n const [row] = await tx.select({ count: sql<number>`count(*)` }).from(bundles);\n const excess = (row?.count ?? 0) - MAX_VERIFIED_MANIFEST_BUNDLES;\n if (excess <= 0) return;\n const evicted = await tx\n .select({ manifestHash: bundles.manifestHash })\n .from(bundles)\n .orderBy(asc(bundles.verifiedAt), asc(bundles.manifestHash))\n .limit(excess);\n for (const batch of batches(evicted.map((entry) => entry.manifestHash)))\n await tx.delete(bundles).where(inArray(bundles.manifestHash, batch)).run();\n}\n\n/** A verified bundle's exact JSON and that JSON's digest. */\nexport type VerifiedManifestBundleRow = Omit<\n typeof bundles.$inferInsert,\n \"verifiedAt\"\n>;\n\n/**\n * Prepares rows for bundles and KEK levels that just passed projection\n * verification. The digests are computed here, before the checkpoint\n * transaction that writes them begins.\n */\nexport async function verifiedManifestBundleRows(\n entries: readonly VerifiedManifestBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleEntries: VerifiedBundle[] = [];\n const levelEntries: VerifiedKekLevel[] = [];\n for (const entry of entries)\n if (\"kekLevel\" in entry) levelEntries.push(entry);\n else bundleEntries.push(entry);\n // One level per container: its newest epoch, the last one seen on a tie.\n const levelRows = new Map<string, VerifiedManifestBundleRow>();\n for (const level of levelEntries) {\n const row = await kekLevelRow(level);\n const held = row && levelRows.get(row.objectId);\n if (row && (!held || held.epoch <= row.epoch))\n levelRows.set(row.objectId, row);\n }\n return [...(await bundleRows(bundleEntries)), ...levelRows.values()];\n}\n\nfunction bundleRows(\n entries: readonly VerifiedBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const unique = new Map(\n entries.map((entry) => [entry.bundle.manifestHash, entry]),\n );\n return Promise.all(\n [...unique.values()].map(async ({ bundle, checkpoint }) => {\n const bundleJson = JSON.stringify(bundle);\n return {\n manifestHash: bundle.manifestHash,\n organizationId: checkpoint.organizationId,\n objectKind: checkpoint.objectKind,\n objectId: checkpoint.objectId,\n epoch: checkpoint.epoch,\n bundleJson,\n bundleDigest: await sha256Hex(bundleJson),\n };\n }),\n );\n}\n\n/**\n * Records verified bundles inside the transaction that finalizes their\n * projection's checkpoints, so they commit or roll back with it and no cache\n * work outlives the verification. Freshly verified bytes replace any stored\n * copy.\n */\nexport async function writeVerifiedManifestBundlesInTransaction(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n verifiedAt: string,\n): Promise<void> {\n if (rows.length === 0) return;\n const stored = await touchStoredDigests(\n tx,\n rows.map((row) => row.manifestHash),\n verifiedAt,\n );\n // A repeated hash keeps its last changed row, as sequential upserts would.\n const changed = new Map(\n rows\n .filter((row) => stored.get(row.manifestHash) !== row.bundleDigest)\n .map((row) => [row.manifestHash, { ...row, verifiedAt }]),\n );\n for (const batch of slices([...changed.values()], BUNDLE_WRITE_BATCH_SIZE))\n await tx\n .insert(bundles)\n .values(batch)\n .onConflictDoUpdate({\n target: bundles.manifestHash,\n set: {\n organizationId: excludedValue(bundles.organizationId),\n objectKind: excludedValue(bundles.objectKind),\n objectId: excludedValue(bundles.objectId),\n epoch: excludedValue(bundles.epoch),\n bundleJson: excludedValue(bundles.bundleJson),\n bundleDigest: excludedValue(bundles.bundleDigest),\n verifiedAt: excludedValue(bundles.verifiedAt),\n },\n })\n .run();\n // All incremental SDK level writes pass here. Both checkpoint callers\n // prepare them with verifiedManifestBundleRows (one level per container),\n // then write and drop siblings in the same serialized transaction. Thus an\n // unchanged level already removed its siblings; eviction/reset only delete.\n // Restored caches must preserve that invariant too: this fast path does not\n // repair externally injected stale siblings.\n await dropSupersededKekLevels(tx, [...changed.values()]);\n // Replacing or touching existing rows cannot grow the bounded cache.\n if (rows.some((row) => !stored.has(row.manifestHash))) {\n await pruneInTransaction(tx);\n }\n}\n\n/**\n * A container keeps only its latest verified level: the API serves its\n * current level, so an older one can never be cited usefully again.\n */\nasync function dropSupersededKekLevels(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n): Promise<void> {\n const levels = rows.filter((row) => row.objectKind === KEK_LEVEL_OBJECT_KIND);\n for (const batch of batches(levels))\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.objectKind, KEK_LEVEL_OBJECT_KIND),\n inArray(\n bundles.objectId,\n batch.map((row) => row.objectId),\n ),\n notInArray(\n bundles.manifestHash,\n batch.map((row) => row.manifestHash),\n ),\n ),\n )\n .run();\n}\n\nasync function touchStoredDigests(\n tx: ClientSQLiteTransactionScope,\n manifestHashes: readonly string[],\n verifiedAt: string,\n): Promise<Map<string, string>> {\n const digests = new Map<string, string>();\n for (const batch of batches(manifestHashes)) {\n const rows = await tx\n .update(bundles)\n .set({ verifiedAt })\n .where(inArray(bundles.manifestHash, batch))\n .returning({\n bundleDigest: bundles.bundleDigest,\n manifestHash: bundles.manifestHash,\n });\n for (const row of rows) digests.set(row.manifestHash, row.bundleDigest);\n }\n return digests;\n}\n\n/**\n * The latest verified KEK level of each container the target's projection\n * walks (supplemented by organization-recency levels for a pending move,\n * or when the lineage has no stored level); then verified bundles of those\n * objects, newest epochs first; then\n * the most recently verified bundles of its organization, since a\n * just-verified parent is the likeliest part of a new child's projection.\n * Citations never leave the target's organization: an object whose\n * organization the device cannot place cites nothing. Damaged rows are\n * dropped.\n */\nexport async function loadVerifiedManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n requestedLimit = KNOWN_MANIFEST_HINT_LIMIT,\n): Promise<HeldProjectionCitation[]> {\n const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));\n if (!(limit > 0)) return [];\n const loadGeneration = evictionGeneration;\n citationLoadsInFlight += 1;\n try {\n return await loadCitableManifestCitations(execSql, target, limit).then(\n (cited) => cited.filter((citation) => citable(citation, loadGeneration)),\n );\n } finally {\n citationLoadsInFlight -= 1;\n if (citationLoadsInFlight === 0) evictedInGeneration.clear();\n }\n}\n\nasync function loadCitableManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n limit: number,\n): Promise<HeldProjectionCitation[]> {\n await ensureSqlTables(execSql, [\n ...verifiedManifestBundleTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...localIntentTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const objects = await citedObjects(db, target);\n const organizationId = await targetOrganization(db, target, objects);\n if (organizationId === null) return [];\n const { cited, damaged } = await collectVerifiedManifestCitations(\n db,\n organizationId,\n objects,\n target,\n limit,\n );\n if (damaged.length > 0)\n await dropVerifiedManifestBundles(execSql, damaged).catch(() => undefined);\n return cited;\n}\n\n// Manifest hashes whose held rows a refused read is dropping: no read cites\n// them meanwhile, so none can be rebuilt from the bytes being dropped. Each\n// eviction also advances a generation, so a citation load that started\n// before it never returns the rows it read: they may already be gone.\nconst suppressedCitations = new Map<string, number>();\nconst evictedInGeneration = new Map<string, number>();\nlet evictionGeneration = 0;\n// Loads in flight; once none overlap, the eviction log has nothing to guard.\nlet citationLoadsInFlight = 0;\n\n/** Keeps these held bundles out of citations until the release runs. */\nexport function suppressHeldCitations(\n manifestHashes: readonly string[],\n): () => void {\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n suppressedCitations.set(hash, (suppressedCitations.get(hash) ?? 0) + 1);\n evictedInGeneration.set(hash, evictionGeneration);\n }\n return () => {\n // The drop is complete: a load that started before now may hold the\n // dropped bytes, so it is newer than none of them.\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n evictedInGeneration.set(hash, evictionGeneration);\n const count = (suppressedCitations.get(hash) ?? 1) - 1;\n if (count > 0) suppressedCitations.set(hash, count);\n else suppressedCitations.delete(hash);\n }\n };\n}\n\nfunction citable(\n citation: HeldProjectionCitation,\n loadGeneration: number,\n): boolean {\n if (!(\"manifestHash\" in citation)) return true;\n const { manifestHash } = citation;\n return (\n !suppressedCitations.has(manifestHash) &&\n (evictedInGeneration.get(manifestHash) ?? 0) <= loadGeneration\n );\n}\n\n/**\n * Drops the stored rows of held bundles a projection that cited them failed\n * to verify with, so the next read fetches them from the server. Only a row\n * still holding the exact bytes cited goes, so a newer verified copy written\n * meanwhile stays; nothing is dropped once `stillCurrent` turns false.\n * Resolves whether the drop committed.\n */\nexport async function dropHeldManifestBundles(\n execSql: ExecSql,\n heldBundles: readonly ServedAccessManifestBundleWireResponse[],\n stillCurrent?: () => boolean,\n): Promise<boolean> {\n if (heldBundles.length === 0) return true;\n const cited = await Promise.all(\n heldBundles.map(async (bundle) => ({\n manifestHash: bundle.manifestHash,\n bundleDigest: await sha256Hex(JSON.stringify(bundle)),\n })),\n );\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const drop = async (tx: ClientSQLiteTransactionScope) => {\n for (const row of cited)\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.manifestHash, row.manifestHash),\n eq(bundles.bundleDigest, row.bundleDigest),\n ),\n )\n .run();\n };\n if (!stillCurrent) {\n await runtime.transaction(drop, { behavior: \"immediate\" });\n return true;\n }\n const { committed } = await runtime.guardedTransaction(drop, stillCurrent, {\n behavior: \"immediate\",\n });\n return committed;\n}\n\n/** Drops damaged stored rows so no later read cites them. */\nasync function dropVerifiedManifestBundles(\n execSql: ExecSql,\n manifestHashes: readonly string[],\n): Promise<void> {\n if (manifestHashes.length === 0) return;\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n await getClientSQLitePersistenceRuntime(execSql).runMutation(\n async (handle) => {\n for (const batch of batches([...new Set(manifestHashes)]))\n await handle\n .delete(bundles)\n .where(inArray(bundles.manifestHash, batch))\n .run();\n },\n );\n}\n\n/** Cites from whichever database the signed-in identity currently uses. */\nexport function createVerifiedManifestCitations(\n resolveExecSql: () => ExecSql | null,\n): VerifiedManifestCitations {\n return {\n cite: async (target) => {\n const execSql = resolveExecSql();\n return execSql ? loadVerifiedManifestCitations(execSql, target) : [];\n },\n };\n}\n\n/** Drops an organization's verified bundles when a remote reset forgets it. */\nexport async function deleteVerifiedManifestBundlesForOrganization(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n await tx\n .delete(bundles)\n .where(eq(bundles.organizationId, organizationId))\n .run();\n}\n"]}
@@ -0,0 +1,136 @@
1
+ import { generateKemSeedAndKeyPair, normalizePrincipalProjectionMembers, toFingerprint, unwrapDek, } from "../../internal/crypto/index.js";
2
+ import { bytesToBase64 } from "../../internal/encoding/index.js";
3
+ import { assertPrincipalIdentityCommitments } from "../principalContracts/principalIdentityCommitments.js";
4
+ import { principalSecretKeyMatchesState } from "./principalKeyValidation.js";
5
+ import { rewrapProjectionMemberEnvelopes, toRecipientEntries, } from "./principalPolicyRecipients.js";
6
+ function projectionMemberKey(member) {
7
+ return `${member.userId}\0${member.role}\0${member.identityBundleFingerprint}`;
8
+ }
9
+ function keptKeying(currentPolicy, memberEnvelopes) {
10
+ const { currentState } = currentPolicy;
11
+ return {
12
+ encapsulationPublicKey: currentState.encapsulationPublicKey,
13
+ keyEpoch: currentState.keyEpoch,
14
+ keyFingerprint: currentState.keyFingerprint,
15
+ memberEnvelopes,
16
+ };
17
+ }
18
+ /**
19
+ * The organization secret the signer's own envelope opens, when it matches
20
+ * the signed key. Null sends the successor through a rotation, which needs
21
+ * no held secret and repairs any envelope that does not open to it.
22
+ */
23
+ async function heldOrganizationSecret(input) {
24
+ if (!input.currentUserSecretKey)
25
+ return null;
26
+ // Only the signer's own envelope: one decapsulation.
27
+ const own = input.currentPolicy.currentMemberEnvelopes.envelopes.filter((envelope) => envelope.userId === input.signerUserId);
28
+ if (own.length !== 1)
29
+ return null;
30
+ let secret;
31
+ try {
32
+ secret = await unwrapDek(toRecipientEntries(own), input.currentUserSecretKey);
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ return (await principalSecretKeyMatchesState(secret, input.currentPolicy.currentState))
38
+ ? secret
39
+ : null;
40
+ }
41
+ /**
42
+ * A kept key re-wraps nobody, or only the added admins, so the checks a full
43
+ * re-wrap runs across the projection run here before any request is built:
44
+ * every member's identity commitment against the resolved identities, and no
45
+ * added admin sharing an encapsulation key with a retained envelope.
46
+ */
47
+ async function assertKeptRecipients(input, retained) {
48
+ const users = new Map(input.users.map((user) => [user.userId, user]));
49
+ await assertPrincipalIdentityCommitments({
50
+ authenticated: false,
51
+ projections: [input.projection],
52
+ resolveTrustedUserIdentity: async (userId) => users.get(userId) ?? null,
53
+ });
54
+ const fingerprints = new Set(retained.map((envelope) => envelope.memberKeyFingerprint));
55
+ const retainedUsers = new Set(retained.map((envelope) => envelope.userId));
56
+ for (const member of input.projection) {
57
+ if (retainedUsers.has(member.userId))
58
+ continue;
59
+ const user = users.get(member.userId);
60
+ if (!user || fingerprints.has(user.encapsulationKeyFingerprint))
61
+ throw new Error("Organization directory recipients must not share an encapsulation key");
62
+ }
63
+ }
64
+ /**
65
+ * A fresh key wrapped for every admin of the successor. A removed admin that
66
+ * holds a retained admin's KEM secret still opens that admin's envelope: no
67
+ * directory key can exclude it, and refusing the removal would let a
68
+ * directory an honest server serves block it, so that case belongs to the
69
+ * retained admin's own identity key rotation.
70
+ */
71
+ async function rotatedKeying(input) {
72
+ const organizationKem = generateKemSeedAndKeyPair();
73
+ return {
74
+ encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),
75
+ keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,
76
+ keyFingerprint: await toFingerprint(organizationKem.publicKey),
77
+ memberEnvelopes: await rewrapProjectionMemberEnvelopes({
78
+ projection: input.projection,
79
+ secretKey: organizationKem.secretKey,
80
+ users: input.users,
81
+ }),
82
+ };
83
+ }
84
+ /**
85
+ * Key material for the next organization directory state. An unchanged admin
86
+ * projection keeps the key, epoch and envelopes; a projection that only adds
87
+ * admins keeps the key and epoch and wraps the held secret for the added
88
+ * admins alone. Any removal or changed member rotates to a fresh key wrapped
89
+ * for every admin, so a removed admin never holds the successor's secret.
90
+ */
91
+ export async function organizationDirectoryKeying(input) {
92
+ const previous = new Set(normalizePrincipalProjectionMembers(input.currentPolicy.currentProjection).map(projectionMemberKey));
93
+ const added = input.projection.filter((member) => !previous.has(projectionMemberKey(member)));
94
+ const keepsEveryMember = input.projection.length - added.length === previous.size;
95
+ if (!keepsEveryMember)
96
+ return rotatedKeying(input);
97
+ // The predecessor's signed envelopes, re-served with only their signed
98
+ // fields: a response may carry fields the request must not forward.
99
+ const currentEnvelopes = input.currentPolicy.currentMemberEnvelopes.envelopes.map((envelope) => ({
100
+ kemCipherText: envelope.kemCipherText,
101
+ memberKeyFingerprint: envelope.memberKeyFingerprint,
102
+ userId: envelope.userId,
103
+ wrappedKey: envelope.wrappedKey,
104
+ }));
105
+ // Envelopes that share an encapsulation key are never re-served: rotating
106
+ // re-wraps for every admin, which refuses a shared key as it always has.
107
+ if (new Set(currentEnvelopes.map((envelope) => envelope.memberKeyFingerprint))
108
+ .size !== currentEnvelopes.length)
109
+ return rotatedKeying(input);
110
+ // A key is kept only when the signer's own envelope opens it and it
111
+ // matches the signed key. Otherwise, or without the signer's key, the write
112
+ // rotates, which re-wraps a fresh key for every admin. Measured (best of
113
+ // 25): keeping costs about 3.6 ms of client CPU at any size, rotating 2.0 ms
114
+ // for one admin, 3.0 ms for two and 6.0 ms for five; API statements and
115
+ // request bytes are equal. A single admin keeps too, since a held epoch is
116
+ // what lets a successor cite its predecessor's envelope set (#2903).
117
+ // Keeping does not check that the signed key is fresh, and need not: the
118
+ // directory key encrypts no data (the payload is a plain signed descriptor
119
+ // and grants name only groups or users). Anything that encrypts to it must
120
+ // first restore rotation on every write or a no-reuse rule.
121
+ const secret = await heldOrganizationSecret(input);
122
+ if (!secret)
123
+ return rotatedKeying(input);
124
+ await assertKeptRecipients(input, currentEnvelopes);
125
+ if (added.length === 0)
126
+ return keptKeying(input.currentPolicy, currentEnvelopes);
127
+ return keptKeying(input.currentPolicy, [
128
+ ...currentEnvelopes,
129
+ ...(await rewrapProjectionMemberEnvelopes({
130
+ projection: added,
131
+ secretKey: secret,
132
+ users: input.users,
133
+ })),
134
+ ]);
135
+ }
136
+ //# sourceMappingURL=organizationDirectoryKeying.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"organizationDirectoryKeying.js","sourceRoot":"","sources":["organizationDirectoryKeying.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,mCAAmC,EACnC,aAAa,EACb,SAAS,GACV,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EAAE,kCAAkC,EAAE,MAAM,oDAAoD,CAAC;AAExG,OAAO,EAAE,8BAA8B,EAAE,MAAM,0BAA0B,CAAC;AAC1E,OAAO,EACL,+BAA+B,EAC/B,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AAsBrC,SAAS,mBAAmB,CAAC,MAAwC;IACnE,OAAO,GAAG,MAAM,CAAC,MAAM,KAAK,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,yBAAyB,EAAE,CAAC;AACjF,CAAC;AAED,SAAS,UAAU,CACjB,aAAiD,EACjD,eAAiD;IAEjD,MAAM,EAAE,YAAY,EAAE,GAAG,aAAa,CAAC;IACvC,OAAO;QACL,sBAAsB,EAAE,YAAY,CAAC,sBAAsB;QAC3D,QAAQ,EAAE,YAAY,CAAC,QAAQ;QAC/B,cAAc,EAAE,YAAY,CAAC,cAAc;QAC3C,eAAe;KAChB,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,sBAAsB,CAAC,KAIrC;IACC,IAAI,CAAC,KAAK,CAAC,oBAAoB;QAAE,OAAO,IAAI,CAAC;IAC7C,qDAAqD;IACrD,MAAM,GAAG,GAAG,KAAK,CAAC,aAAa,CAAC,sBAAsB,CAAC,SAAS,CAAC,MAAM,CACrE,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,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C,MAAM,+BAA+B,CAAC;YACxC,UAAU,EAAE,KAAK;YACjB,SAAS,EAAE,MAAM;YACjB,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC,CAAC;KACJ,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n generateKemSeedAndKeyPair,\n normalizePrincipalProjectionMembers,\n toFingerprint,\n unwrapDek,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalMemberEnvelopeRequest,\n PrincipalProjectionMemberRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertPrincipalIdentityCommitments } from \"../principalContracts/principalIdentityCommitments\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\nimport { principalSecretKeyMatchesState } from \"./principalKeyValidation\";\nimport {\n rewrapProjectionMemberEnvelopes,\n toRecipientEntries,\n} from \"./principalPolicyRecipients\";\n\n/** The predecessor fields the keep-or-rotate decision reads. */\nexport interface OrganizationDirectoryCurrentPolicy {\n readonly currentMemberEnvelopes: {\n readonly envelopes: readonly PrincipalMemberEnvelopeRequest[];\n };\n readonly currentProjection: readonly PrincipalProjectionMemberRequest[];\n readonly currentState: Pick<\n PrincipalPolicyBundleResponse[\"currentState\"],\n \"encapsulationPublicKey\" | \"keyEpoch\" | \"keyFingerprint\"\n >;\n}\n\n/** The key material a directory successor signs. */\nexport interface OrganizationDirectoryKeying {\n readonly encapsulationPublicKey: string;\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly memberEnvelopes: PrincipalMemberEnvelopeRequest[];\n}\n\nfunction projectionMemberKey(member: PrincipalProjectionMemberRequest): string {\n return `${member.userId}\\0${member.role}\\0${member.identityBundleFingerprint}`;\n}\n\nfunction keptKeying(\n currentPolicy: OrganizationDirectoryCurrentPolicy,\n memberEnvelopes: PrincipalMemberEnvelopeRequest[],\n): OrganizationDirectoryKeying {\n const { currentState } = currentPolicy;\n return {\n encapsulationPublicKey: currentState.encapsulationPublicKey,\n keyEpoch: currentState.keyEpoch,\n keyFingerprint: currentState.keyFingerprint,\n memberEnvelopes,\n };\n}\n\n/**\n * The organization secret the signer's own envelope opens, when it matches\n * the signed key. Null sends the successor through a rotation, which needs\n * no held secret and repairs any envelope that does not open to it.\n */\nasync function heldOrganizationSecret(input: {\n readonly currentPolicy: OrganizationDirectoryCurrentPolicy;\n readonly currentUserSecretKey: Uint8Array | null;\n readonly signerUserId: string;\n}): Promise<Uint8Array | null> {\n if (!input.currentUserSecretKey) return null;\n // Only the signer's own envelope: one decapsulation.\n const own = input.currentPolicy.currentMemberEnvelopes.envelopes.filter(\n (envelope) => envelope.userId === input.signerUserId,\n );\n if (own.length !== 1) return null;\n let secret: Uint8Array;\n try {\n secret = await unwrapDek(\n toRecipientEntries(own),\n input.currentUserSecretKey,\n );\n } catch {\n return null;\n }\n return (await principalSecretKeyMatchesState(\n secret,\n input.currentPolicy.currentState,\n ))\n ? secret\n : null;\n}\n\n/**\n * A kept key re-wraps nobody, or only the added admins, so the checks a full\n * re-wrap runs across the projection run here before any request is built:\n * every member's identity commitment against the resolved identities, and no\n * added admin sharing an encapsulation key with a retained envelope.\n */\nasync function assertKeptRecipients(\n input: {\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly users: ReadonlyArray<TrustedUserIdentity>;\n },\n retained: readonly PrincipalMemberEnvelopeRequest[],\n): Promise<void> {\n const users = new Map(input.users.map((user) => [user.userId, user]));\n await assertPrincipalIdentityCommitments({\n authenticated: false,\n projections: [input.projection],\n resolveTrustedUserIdentity: async (userId) => users.get(userId) ?? null,\n });\n const fingerprints = new Set(\n retained.map((envelope) => envelope.memberKeyFingerprint),\n );\n const retainedUsers = new Set(retained.map((envelope) => envelope.userId));\n for (const member of input.projection) {\n if (retainedUsers.has(member.userId)) continue;\n const user = users.get(member.userId);\n if (!user || fingerprints.has(user.encapsulationKeyFingerprint))\n throw new Error(\n \"Organization directory recipients must not share an encapsulation key\",\n );\n }\n}\n\n/**\n * A fresh key wrapped for every admin of the successor. A removed admin that\n * holds a retained admin's KEM secret still opens that admin's envelope: no\n * directory key can exclude it, and refusing the removal would let a\n * directory an honest server serves block it, so that case belongs to the\n * retained admin's own identity key rotation.\n */\nasync function rotatedKeying(input: {\n readonly currentPolicy: OrganizationDirectoryCurrentPolicy;\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly users: ReadonlyArray<TrustedUserIdentity>;\n}): Promise<OrganizationDirectoryKeying> {\n const organizationKem = generateKemSeedAndKeyPair();\n return {\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n memberEnvelopes: await rewrapProjectionMemberEnvelopes({\n projection: input.projection,\n secretKey: organizationKem.secretKey,\n users: input.users,\n }),\n };\n}\n\n/**\n * Key material for the next organization directory state. An unchanged admin\n * projection keeps the key, epoch and envelopes; a projection that only adds\n * admins keeps the key and epoch and wraps the held secret for the added\n * admins alone. Any removal or changed member rotates to a fresh key wrapped\n * for every admin, so a removed admin never holds the successor's secret.\n */\nexport async function organizationDirectoryKeying(input: {\n readonly currentPolicy: OrganizationDirectoryCurrentPolicy;\n readonly currentUserSecretKey: Uint8Array | null;\n /** The signing admin; only its envelope is opened to check the key. */\n readonly signerUserId: string;\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly users: ReadonlyArray<TrustedUserIdentity>;\n}): Promise<OrganizationDirectoryKeying> {\n const previous = new Set(\n normalizePrincipalProjectionMembers(\n input.currentPolicy.currentProjection,\n ).map(projectionMemberKey),\n );\n const added = input.projection.filter(\n (member) => !previous.has(projectionMemberKey(member)),\n );\n const keepsEveryMember =\n input.projection.length - added.length === previous.size;\n if (!keepsEveryMember) return rotatedKeying(input);\n // The predecessor's signed envelopes, re-served with only their signed\n // fields: a response may carry fields the request must not forward.\n const currentEnvelopes =\n input.currentPolicy.currentMemberEnvelopes.envelopes.map(\n (envelope): PrincipalMemberEnvelopeRequest => ({\n kemCipherText: envelope.kemCipherText,\n memberKeyFingerprint: envelope.memberKeyFingerprint,\n userId: envelope.userId,\n wrappedKey: envelope.wrappedKey,\n }),\n );\n // Envelopes that share an encapsulation key are never re-served: rotating\n // re-wraps for every admin, which refuses a shared key as it always has.\n if (\n new Set(currentEnvelopes.map((envelope) => envelope.memberKeyFingerprint))\n .size !== currentEnvelopes.length\n )\n return rotatedKeying(input);\n // A key is kept only when the signer's own envelope opens it and it\n // matches the signed key. Otherwise, or without the signer's key, the write\n // rotates, which re-wraps a fresh key for every admin. Measured (best of\n // 25): keeping costs about 3.6 ms of client CPU at any size, rotating 2.0 ms\n // for one admin, 3.0 ms for two and 6.0 ms for five; API statements and\n // request bytes are equal. A single admin keeps too, since a held epoch is\n // what lets a successor cite its predecessor's envelope set (#2903).\n // Keeping does not check that the signed key is fresh, and need not: the\n // directory key encrypts no data (the payload is a plain signed descriptor\n // and grants name only groups or users). Anything that encrypts to it must\n // first restore rotation on every write or a no-reuse rule.\n const secret = await heldOrganizationSecret(input);\n if (!secret) return rotatedKeying(input);\n await assertKeptRecipients(input, currentEnvelopes);\n if (added.length === 0)\n return keptKeying(input.currentPolicy, currentEnvelopes);\n return keptKeying(input.currentPolicy, [\n ...currentEnvelopes,\n ...(await rewrapProjectionMemberEnvelopes({\n projection: added,\n secretKey: secret,\n users: input.users,\n })),\n ]);\n}\n"]}
@@ -1,7 +1,6 @@
1
- import { buildPrincipalStateSigningInput, generateKemSeedAndKeyPair, normalizePrincipalProjectionMembers, signPrincipalState, toFingerprint, } from "../../internal/crypto/index.js";
2
- import { bytesToBase64 } from "../../internal/encoding/index.js";
1
+ import { buildPrincipalStateSigningInput, normalizePrincipalProjectionMembers, signPrincipalState, } from "../../internal/crypto/index.js";
3
2
  import { encodeOrganizationAuthorityDescriptor, normalizeOrganizationGroupHeads, } from "../principalContracts/organizationAuthorityDescriptor.js";
4
- import { rewrapProjectionMemberEnvelopes } from "./principalPolicyRecipients.js";
3
+ import { organizationDirectoryKeying, } from "./organizationDirectoryKeying.js";
5
4
  export function organizationGroupHead(head) {
6
5
  if (head.principalType !== "group") {
7
6
  throw new Error("Organization directory can contain only group heads");
@@ -15,16 +14,23 @@ export function replaceOrganizationGroupHead(input) {
15
14
  nextHead,
16
15
  ]);
17
16
  }
17
+ /**
18
+ * The organization's successor directory state. Its key follows the Admins
19
+ * projection (see `organizationDirectoryKeying`): `currentUserSecretKey` is
20
+ * the signer's KEM secret, needed only to keep the key while admins grow;
21
+ * without it a growth rotates.
22
+ */
18
23
  export async function buildOrganizationGroupDirectoryPolicyRequest(input) {
19
24
  const projection = normalizePrincipalProjectionMembers(input.adminProjection);
20
25
  if (projection.length === 0 ||
21
26
  projection.some((member) => member.role !== "admin")) {
22
27
  throw new Error("Organization policy must mirror the Admins projection");
23
28
  }
24
- const organizationKem = generateKemSeedAndKeyPair();
25
- const memberEnvelopes = await rewrapProjectionMemberEnvelopes({
29
+ const keying = await organizationDirectoryKeying({
30
+ currentPolicy: input.currentPolicy,
31
+ currentUserSecretKey: input.currentUserSecretKey,
26
32
  projection,
27
- secretKey: organizationKem.secretKey,
33
+ signerUserId: input.signerUserId,
28
34
  users: input.adminUsers,
29
35
  });
30
36
  const payloadCiphertext = encodeOrganizationAuthorityDescriptor({
@@ -36,11 +42,11 @@ export async function buildOrganizationGroupDirectoryPolicyRequest(input) {
36
42
  principalId: input.descriptor.organizationId,
37
43
  version: input.currentPolicy.currentState.version + 1,
38
44
  prevStateHash: input.currentPolicy.currentState.stateHash,
39
- keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,
40
- encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),
41
- keyFingerprint: await toFingerprint(organizationKem.publicKey),
45
+ keyEpoch: keying.keyEpoch,
46
+ encapsulationPublicKey: keying.encapsulationPublicKey,
47
+ keyFingerprint: keying.keyFingerprint,
42
48
  members: projection.map((member) => ({ userId: member.userId })),
43
- memberEnvelopes,
49
+ memberEnvelopes: keying.memberEnvelopes,
44
50
  projection,
45
51
  grants: [],
46
52
  payloadCiphertext,
@@ -56,7 +62,7 @@ export async function buildOrganizationGroupDirectoryPolicyRequest(input) {
56
62
  ciphertextHash: state.payloadCiphertextHash,
57
63
  },
58
64
  grants: [],
59
- memberEnvelopes,
65
+ memberEnvelopes: keying.memberEnvelopes,
60
66
  projection,
61
67
  state,
62
68
  };
@@ -1 +1 @@
1
- {"version":3,"file":"organizationGroupDirectoryRequest.js","sourceRoot":"","sources":["organizationGroupDirectoryRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,mCAAmC,EAGnC,kBAAkB,EAClB,aAAa,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMpD,OAAO,EACL,qCAAqC,EACrC,+BAA+B,GAGhC,MAAM,uDAAuD,CAAC;AAE/D,OAAO,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,CAAC;AAE9E,MAAM,UAAU,qBAAqB,CACnC,IAA6B;IAE7B,IAAI,IAAI,CAAC,aAAa,KAAK,OAAO,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,CAAC;IACD,OAAO,EAAE,GAAG,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,KAG5C;IACC,MAAM,QAAQ,GAAG,qBAAqB,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACvD,OAAO,+BAA+B,CAAC;QACrC,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,MAAM,CACnC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW,CACpD;QACD,QAAQ;KACT,CAAC,CAAC;AACL,CAAC;AAED,MAAM,C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ChE,eAAe;QACf,UAAU;QACV,MAAM,EAAE,EAAE;QACV,iBAAiB;QACjB,iBAAiB,EAAE,IAAI;QACvB,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QAClC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,wBAAwB,EAAE,KAAK,CAAC,kBAAkB;KACnD,CAAC,EACF,KAAK,CAAC,cAAc,CAAC,iBAAiB,CACvC,CAAC;IAEF,OAAO;QACL,gBAAgB,EAAE;YAChB,WAAW,EAAE,aAAa;YAC1B,UAAU,EAAE,iBAAiB;YAC7B,cAAc,EAAE,KAAK,CAAC,qBAAqB;SAC5C;QACD,MAAM,EAAE,EAAE;QACV,eAAe;QACf,UAAU;QACV,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n generateKemSeedAndKeyPair,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../principalContracts/organizationAuthorityDescriptor\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\nimport { rewrapProjectionMemberEnvelopes } from \"./principalPolicyRecipients\";\n\nexport function organizationGroupHead(\n head: ReferencedPrincipalHead,\n): OrganizationGroupHead {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n}\n\nexport function replaceOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly nextHead: ReferencedPrincipalHead;\n}): OrganizationGroupHead[] {\n const nextHead = organizationGroupHead(input.nextHead);\n return normalizeOrganizationGroupHeads([\n ...input.descriptor.groupHeads.filter(\n (head) => head.principalId !== nextHead.principalId,\n ),\n nextHead,\n ]);\n}\n\nexport async function buildOrganizationGroupDirectoryPolicyRequest(input: {\n readonly adminProjection: readonly PrincipalProjectionMemberRequest[];\n readonly adminUsers: readonly TrustedUserIdentity[];\n readonly currentPolicy: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupHeads: readonly OrganizationGroupHead[];\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.adminProjection);\n if (\n projection.length === 0 ||\n projection.some((member) => member.role !== \"admin\")\n ) {\n throw new Error(\"Organization policy must mirror the Admins projection\");\n }\n const organizationKem = generateKemSeedAndKeyPair();\n const memberEnvelopes = await rewrapProjectionMemberEnvelopes({\n projection,\n secretKey: organizationKem.secretKey,\n users: input.adminUsers,\n });\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n ...input.descriptor,\n groupHeads: input.groupHeads,\n });\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.descriptor.organizationId,\n version: input.currentPolicy.currentState.version + 1,\n prevStateHash: input.currentPolicy.currentState.stateHash,\n keyEpoch: input.currentPolicy.currentState.keyEpoch + 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: projection.map((member) => ({ userId: member.userId })),\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n grants: [],\n memberEnvelopes,\n projection,\n state,\n };\n}\n"]}
1
+ {"version":3,"file":"organizationGroupDirectoryRequest.js","sourceRoot":"","sources":["organizationGroupDirectoryRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,mCAAmC,EAGnC,kBAAkB,GACnB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EACL,qCAAqC,EACrC,+BAA+B,GAGhC,MAAM,uDAAuD,CAAC;AAE/D,OAAO,EAEL,2BAA2B,GAC5B,MAAM,+BAA+B,CAAC;AAEvC,MAAM,UAAU,qBAAqB,CACnC,IAA6B;IAE7B,IAAI,IAAI,CAAC,aAAa,KAAK,OAAO,EAAE,CAAC;QACnC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,CAAC;IACD,OAAO,EAAE,GAAG,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,KAG5C;IACC,MAAM,QAAQ,GAAG,qBAAqB,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACvD,OAAO,+BAA+B,CAAC;QACrC,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,MAAM,CACnC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW,CACpD;QACD,QAAQ;KACT,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAAC,KAWlE;IACC,MAAM,UAAU,GAAG,mCAAmC,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;IAC9E,IACE,UAAU,CAAC,MAAM,KAAK,CAAC;QACvB,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,OAAO,CAAC,EACpD,CAAC;QACD,M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F,OAAO;QACL,gBAAgB,EAAE;YAChB,WAAW,EAAE,aAAa;YAC1B,UAAU,EAAE,iBAAiB;YAC7B,cAAc,EAAE,KAAK,CAAC,qBAAqB;SAC5C;QACD,MAAM,EAAE,EAAE;QACV,eAAe,EAAE,MAAM,CAAC,eAAe;QACvC,UAAU;QACV,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n encodeOrganizationAuthorityDescriptor,\n normalizeOrganizationGroupHeads,\n type OrganizationAuthorityDescriptor,\n type OrganizationGroupHead,\n} from \"../principalContracts/organizationAuthorityDescriptor\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\nimport {\n type OrganizationDirectoryCurrentPolicy,\n organizationDirectoryKeying,\n} from \"./organizationDirectoryKeying\";\n\nexport function organizationGroupHead(\n head: ReferencedPrincipalHead,\n): OrganizationGroupHead {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n}\n\nexport function replaceOrganizationGroupHead(input: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly nextHead: ReferencedPrincipalHead;\n}): OrganizationGroupHead[] {\n const nextHead = organizationGroupHead(input.nextHead);\n return normalizeOrganizationGroupHeads([\n ...input.descriptor.groupHeads.filter(\n (head) => head.principalId !== nextHead.principalId,\n ),\n nextHead,\n ]);\n}\n\n/**\n * The organization's successor directory state. Its key follows the Admins\n * projection (see `organizationDirectoryKeying`): `currentUserSecretKey` is\n * the signer's KEM secret, needed only to keep the key while admins grow;\n * without it a growth rotates.\n */\nexport async function buildOrganizationGroupDirectoryPolicyRequest(input: {\n readonly adminProjection: readonly PrincipalProjectionMemberRequest[];\n readonly adminUsers: readonly TrustedUserIdentity[];\n readonly currentPolicy: OrganizationDirectoryCurrentPolicy &\n Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly currentUserSecretKey: Uint8Array | null;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly groupHeads: readonly OrganizationGroupHead[];\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.adminProjection);\n if (\n projection.length === 0 ||\n projection.some((member) => member.role !== \"admin\")\n ) {\n throw new Error(\"Organization policy must mirror the Admins projection\");\n }\n const keying = await organizationDirectoryKeying({\n currentPolicy: input.currentPolicy,\n currentUserSecretKey: input.currentUserSecretKey,\n projection,\n signerUserId: input.signerUserId,\n users: input.adminUsers,\n });\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n ...input.descriptor,\n groupHeads: input.groupHeads,\n });\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.descriptor.organizationId,\n version: input.currentPolicy.currentState.version + 1,\n prevStateHash: input.currentPolicy.currentState.stateHash,\n keyEpoch: keying.keyEpoch,\n encapsulationPublicKey: keying.encapsulationPublicKey,\n keyFingerprint: keying.keyFingerprint,\n members: projection.map((member) => ({ userId: member.userId })),\n memberEnvelopes: keying.memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n grants: [],\n memberEnvelopes: keying.memberEnvelopes,\n projection,\n state,\n };\n}\n"]}