@tearleads/client-sdk 0.1.241 → 0.1.243

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 (62) hide show
  1. package/client/organizations/currentPrincipalMutations.js +1 -0
  2. package/client/organizations/currentPrincipalMutations.js.map +1 -1
  3. package/client/organizations/principalMutations.js +1 -0
  4. package/client/organizations/principalMutations.js.map +1 -1
  5. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +12 -3
  6. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  7. package/data/keyingProjectionVerification/checkpoints/verifiedBundleBytes.js +73 -8
  8. package/data/keyingProjectionVerification/checkpoints/verifiedBundleBytes.js.map +1 -1
  9. package/data/keyingProjectionVerification/container/containerAncestorCitations.js +20 -4
  10. package/data/keyingProjectionVerification/container/containerAncestorCitations.js.map +1 -1
  11. package/data/keyingProjectionVerification/container/containerManifestVerification.js +43 -32
  12. package/data/keyingProjectionVerification/container/containerManifestVerification.js.map +1 -1
  13. package/data/keyingProjectionVerification/container/containerSignedParentReference.js +129 -0
  14. package/data/keyingProjectionVerification/container/containerSignedParentReference.js.map +1 -0
  15. package/data/keyingProjectionVerification/document/documentManifestVerification.js +28 -7
  16. package/data/keyingProjectionVerification/document/documentManifestVerification.js.map +1 -1
  17. package/data/persistence/verifiedCitations/bundleCitationRows.js.map +1 -1
  18. package/data/persistence/verifiedCitations/citationCollection.js +2 -2
  19. package/data/persistence/verifiedCitations/citationCollection.js.map +1 -1
  20. package/data/persistence/verifiedManifestBundlePersistence.d.ts +3 -2
  21. package/data/persistence/verifiedManifestBundlePersistence.js +1 -1
  22. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  23. package/data/principals/organizationDirectoryKeying.js +136 -0
  24. package/data/principals/organizationDirectoryKeying.js.map +1 -0
  25. package/data/principals/organizationGroupDirectoryRequest.js +17 -11
  26. package/data/principals/organizationGroupDirectoryRequest.js.map +1 -1
  27. package/internal/api-client/verifiedManifestCitations.d.ts +4 -3
  28. package/internal/api-client/verifiedManifestCitations.js +3 -3
  29. package/internal/api-client/verifiedManifestCitations.js.map +1 -1
  30. package/internal/validators/operation/writerProjections.d.ts +8 -8
  31. package/internal/validators/response/container.d.ts +4 -4
  32. package/internal/validators/response/documentMutation.d.ts +4 -4
  33. package/internal/validators/response/manifestBundleReferences.js +4 -3
  34. package/internal/validators/response/manifestBundleReferences.js.map +1 -1
  35. package/internal/validators/response/writerProjectionWire.d.ts +4 -4
  36. package/internal/validators/response/writerProjectionWire.js +8 -5
  37. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  38. package/internal/validators/util/index.d.ts +1 -0
  39. package/internal/validators/util/index.js +1 -0
  40. package/internal/validators/util/index.js.map +1 -1
  41. package/internal/validators/util/servedManifestBundle.d.ts +71 -0
  42. package/internal/validators/util/servedManifestBundle.js +100 -0
  43. package/internal/validators/util/servedManifestBundle.js.map +1 -0
  44. package/package.json +1 -1
  45. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js +1 -0
  46. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
  47. package/workflows/organizations/groupShare/currentShareGrantMutation.js +3 -0
  48. package/workflows/organizations/groupShare/currentShareGrantMutation.js.map +1 -1
  49. package/workflows/organizations/groupShare/shareWithGroup.js +2 -0
  50. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
  51. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +3 -0
  52. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  53. package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js +1 -0
  54. package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js.map +1 -1
  55. package/workflows/organizations/groups/deleteOrganizationGroup.d.ts +2 -0
  56. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -0
  57. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  58. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -0
  59. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  60. package/workflows/organizations/principalPolicy/index.d.ts +12 -0
  61. package/workflows/organizations/principalPolicy/index.js +11 -0
  62. package/workflows/organizations/principalPolicy/index.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"citationCollection.js","sourceRoot":"","sources":["citationCollection.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAEL,kCAAkC,GACnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,6BAA6B,IAAI,OAAO,EAAE,MAAM,kDAAkD,CAAC;AAE5G,OAAO,EACL,iBAAiB,EACjB,UAAU,EAEV,aAAa,GACd,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAChF,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,KAAK,UAAU,gBAAgB,CAC7B,GAAoB;IAEpB,IACE,CAAC,MAAM,aAAa,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC;QAC/D,GAAG,CAAC,YAAY;QAEhB,OAAO,IAAI,CAAC;IACd,IAAI,CAAC;QACH,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACnD,OAAO,kCAAkC,CAAC,MAAM,CAAC;YAC/C,MAAM,CAAC,YAAY,KAAK,GAAG,CAAC,YAAY;YACxC,CAAC,CAAC,MAAM;YACR,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,S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IACpD,IAAI,SAAS,CAAC,OAAO,CAAC,MAAM,GAAG,WAAW;QACxC,KACE,IAAI,MAAM,GAAG,CAAC,EACd,MAAM,GAAG,MAAM,IAAI,SAAS,CAAC,SAAS,EAAE,GAAG,CAAC,EAC5C,MAAM,IAAI,KAAK;YAEf,MAAM,SAAS,CAAC,OAAO,CACrB,MAAM,UAAU,CACd,EAAE,EACF,cAAc,EACd,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC,EAChC,EAAE,EACF,MAAM,CACP,CACF,CAAC;AACR,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,EAAwB,EACxB,cAAsB,EACtB,OAA+B,EAC/B,MAA8B,EAC9B,KAAa;IAEb,MAAM,SAAS,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC;IAC3C,IAAI,KAAK,EAAE,MAAM,GAAG,IAAI,gBAAgB,CACtC,EAAE,EACF,cAAc,EACd,OAAO,EACP,MAAM,EACN,SAAS,CAAC,SAAS,CACpB;QACC,MAAM,SAAS,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,EAAE,kBAAkB,CAAC,CAAC;IACrD,MAAM,cAAc,CAAC,EAAE,EAAE,cAAc,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAC7D,MAAM,aAAa,CAAC,EAAE,EAAE,cAAc,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;IAC1D,OAAO,EAAE,KAAK,EAAE,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,EAAE,CAAC;AAC9E,CAAC","sourcesContent":["import type {\n HeldProjectionCitation,\n WriterProjectionTarget,\n} from \"@tearleads/api-client\";\nimport { toFingerprint } from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n isAccessManifestBundleWireResponse,\n} from \"@tearleads/validators/response\";\nimport { and, asc, desc, eq, ne, notInArray } from \"drizzle-orm\";\nimport { verifiedAccessManifestBundles as bundles } from \"../../sqlite/schema/verifiedManifestBundleSchema\";\nimport type { ClientSQLiteDatabase } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n batchedObjectRows,\n objectRows,\n type StoredBundleRow,\n storedColumns,\n} from \"./bundleCitationRows\";\nimport type { CitedObject } from \"./citationScope\";\nimport { KEK_LEVEL_OBJECT_KIND, readStoredKekLevel } from \"./kekLevelCitations\";\nimport { lineageKekLevels } from \"./levelCitationRows\";\n\nasync function readStoredBundle(\n row: StoredBundleRow,\n): Promise<AccessManifestBundleWireResponse | null> {\n if (\n (await toFingerprint(new TextEncoder().encode(row.bundleJson))) !==\n row.bundleDigest\n )\n return null;\n try {\n const bundle: unknown = JSON.parse(row.bundleJson);\n return isAccessManifestBundleWireResponse(bundle) &&\n bundle.manifestHash === row.manifestHash\n ? bundle\n : null;\n } catch {\n return null;\n }\n}\n\nfunction recentRows(\n db: ClientSQLiteDatabase,\n organizationId: string,\n limit: number,\n excluded: readonly string[] = [],\n offset = 0,\n) {\n return db\n .select(storedColumns)\n .from(bundles)\n .where(\n and(\n eq(bundles.organizationId, organizationId),\n ne(bundles.objectKind, KEK_LEVEL_OBJECT_KIND),\n excluded.length > 0\n ? notInArray(bundles.manifestHash, [...excluded])\n : undefined,\n ),\n )\n .orderBy(desc(bundles.verifiedAt), asc(bundles.manifestHash))\n .limit(limit)\n .offset(offset);\n}\n\nfunction citationCollector(limit: number) {\n const cited = new Map<string, HeldProjectionCitation>();\n const damaged: string[] = [];\n return {\n cited,\n damaged,\n remaining: () => limit - cited.size,\n async collect(\n rows: readonly StoredBundleRow[],\n read: (\n row: StoredBundleRow,\n ) => Promise<HeldProjectionCitation | null> = readStoredBundle,\n ) {\n for (const row of rows) {\n if (cited.size >= limit || cited.has(row.manifestHash)) continue;\n const citation = await read(row);\n if (citation) cited.set(row.manifestHash, citation);\n else damaged.push(row.manifestHash);\n }\n },\n };\n}\n\ntype CitationCollector = ReturnType<typeof citationCollector>;\n\nasync function collectObjects(\n db: ClientSQLiteDatabase,\n organizationId: string,\n objects: readonly CitedObject[],\n collector: CitationCollector,\n) {\n if (collector.remaining() === 0) return;\n const rows =\n objects.length > 2\n ? await batchedObjectRows(\n db,\n organizationId,\n objects,\n collector.remaining(),\n readStoredBundle,\n )\n : null;\n if (rows) await collector.collect(rows);\n else\n for (const object of objects)\n if (collector.remaining() > 0)\n await collector.collect(\n await objectRows(db, organizationId, object, collector.remaining()),\n );\n}\n\nasync function collectRecent(\n db: ClientSQLiteDatabase,\n organizationId: string,\n collector: CitationCollector,\n limit: number,\n) {\n if (collector.remaining() === 0) return;\n const window = limit + collector.cited.size;\n const damageCount = collector.damaged.length;\n await collector.collect(\n await recentRows(db, organizationId, collector.remaining(), [\n ...collector.cited.keys(),\n ]),\n );\n // Damage can free quota. Replay the original recent window in bounded\n // pages; a healthy read never loads duplicate JSON.\n if (collector.damaged.length > damageCount)\n for (\n let offset = 0;\n offset < window && collector.remaining() > 0;\n offset += limit\n )\n await collector.collect(\n await recentRows(\n db,\n organizationId,\n Math.min(limit, window - offset),\n [],\n offset,\n ),\n );\n}\n\n/**\n * Healthy reads load at most the hint quota in JSON across all phases. Damage\n * may require more reads to preserve the old fallback, each bounded by that\n * quota; only accepted citations are retained. None are verifier trust input.\n */\nexport async function collectVerifiedManifestCitations(\n db: ClientSQLiteDatabase,\n organizationId: string,\n objects: readonly CitedObject[],\n target: WriterProjectionTarget,\n limit: number,\n) {\n const collector = citationCollector(limit);\n for await (const row of lineageKekLevels(\n db,\n organizationId,\n objects,\n target,\n collector.remaining,\n ))\n await collector.collect([row], readStoredKekLevel);\n await collectObjects(db, organizationId, objects, collector);\n await collectRecent(db, organizationId, collector, limit);\n return { cited: [...collector.cited.values()], damaged: collector.damaged };\n}\n"]}
1
+ {"version":3,"file":"citationCollection.js","sourceRoot":"","sources":["citationCollection.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,EAAE,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AC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC,EAChC,EAAE,EACF,MAAM,CACP,CACF,CAAC;AACR,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,EAAwB,EACxB,cAAsB,EACtB,OAA+B,EAC/B,MAA8B,EAC9B,KAAa;IAEb,MAAM,SAAS,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC;IAC3C,IAAI,KAAK,EAAE,MAAM,GAAG,IAAI,gBAAgB,CACtC,EAAE,EACF,cAAc,EACd,OAAO,EACP,MAAM,EACN,SAAS,CAAC,SAAS,CACpB;QACC,MAAM,SAAS,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,EAAE,kBAAkB,CAAC,CAAC;IACrD,MAAM,cAAc,CAAC,EAAE,EAAE,cAAc,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAC7D,MAAM,aAAa,CAAC,EAAE,EAAE,cAAc,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;IAC1D,OAAO,EAAE,KAAK,EAAE,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,EAAE,CAAC;AAC9E,CAAC","sourcesContent":["import type {\n HeldProjectionCitation,\n WriterProjectionTarget,\n} from \"@tearleads/api-client\";\nimport { toFingerprint } from \"@tearleads/crypto\";\nimport {\n isServedAccessManifestBundleWireResponse,\n type ServedAccessManifestBundleWireResponse,\n} from \"@tearleads/validators/util\";\nimport { and, asc, desc, eq, ne, notInArray } from \"drizzle-orm\";\nimport { verifiedAccessManifestBundles as bundles } from \"../../sqlite/schema/verifiedManifestBundleSchema\";\nimport type { ClientSQLiteDatabase } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n batchedObjectRows,\n objectRows,\n type StoredBundleRow,\n storedColumns,\n} from \"./bundleCitationRows\";\nimport type { CitedObject } from \"./citationScope\";\nimport { KEK_LEVEL_OBJECT_KIND, readStoredKekLevel } from \"./kekLevelCitations\";\nimport { lineageKekLevels } from \"./levelCitationRows\";\n\nasync function readStoredBundle(\n row: StoredBundleRow,\n): Promise<ServedAccessManifestBundleWireResponse | null> {\n if (\n (await toFingerprint(new TextEncoder().encode(row.bundleJson))) !==\n row.bundleDigest\n )\n return null;\n try {\n const bundle: unknown = JSON.parse(row.bundleJson);\n return isServedAccessManifestBundleWireResponse(bundle) &&\n bundle.manifestHash === row.manifestHash\n ? bundle\n : null;\n } catch {\n return null;\n }\n}\n\nfunction recentRows(\n db: ClientSQLiteDatabase,\n organizationId: string,\n limit: number,\n excluded: readonly string[] = [],\n offset = 0,\n) {\n return db\n .select(storedColumns)\n .from(bundles)\n .where(\n and(\n eq(bundles.organizationId, organizationId),\n ne(bundles.objectKind, KEK_LEVEL_OBJECT_KIND),\n excluded.length > 0\n ? notInArray(bundles.manifestHash, [...excluded])\n : undefined,\n ),\n )\n .orderBy(desc(bundles.verifiedAt), asc(bundles.manifestHash))\n .limit(limit)\n .offset(offset);\n}\n\nfunction citationCollector(limit: number) {\n const cited = new Map<string, HeldProjectionCitation>();\n const damaged: string[] = [];\n return {\n cited,\n damaged,\n remaining: () => limit - cited.size,\n async collect(\n rows: readonly StoredBundleRow[],\n read: (\n row: StoredBundleRow,\n ) => Promise<HeldProjectionCitation | null> = readStoredBundle,\n ) {\n for (const row of rows) {\n if (cited.size >= limit || cited.has(row.manifestHash)) continue;\n const citation = await read(row);\n if (citation) cited.set(row.manifestHash, citation);\n else damaged.push(row.manifestHash);\n }\n },\n };\n}\n\ntype CitationCollector = ReturnType<typeof citationCollector>;\n\nasync function collectObjects(\n db: ClientSQLiteDatabase,\n organizationId: string,\n objects: readonly CitedObject[],\n collector: CitationCollector,\n) {\n if (collector.remaining() === 0) return;\n const rows =\n objects.length > 2\n ? await batchedObjectRows(\n db,\n organizationId,\n objects,\n collector.remaining(),\n readStoredBundle,\n )\n : null;\n if (rows) await collector.collect(rows);\n else\n for (const object of objects)\n if (collector.remaining() > 0)\n await collector.collect(\n await objectRows(db, organizationId, object, collector.remaining()),\n );\n}\n\nasync function collectRecent(\n db: ClientSQLiteDatabase,\n organizationId: string,\n collector: CitationCollector,\n limit: number,\n) {\n if (collector.remaining() === 0) return;\n const window = limit + collector.cited.size;\n const damageCount = collector.damaged.length;\n await collector.collect(\n await recentRows(db, organizationId, collector.remaining(), [\n ...collector.cited.keys(),\n ]),\n );\n // Damage can free quota. Replay the original recent window in bounded\n // pages; a healthy read never loads duplicate JSON.\n if (collector.damaged.length > damageCount)\n for (\n let offset = 0;\n offset < window && collector.remaining() > 0;\n offset += limit\n )\n await collector.collect(\n await recentRows(\n db,\n organizationId,\n Math.min(limit, window - offset),\n [],\n offset,\n ),\n );\n}\n\n/**\n * Healthy reads load at most the hint quota in JSON across all phases. Damage\n * may require more reads to preserve the old fallback, each bounded by that\n * quota; only accepted citations are retained. None are verifier trust input.\n */\nexport async function collectVerifiedManifestCitations(\n db: ClientSQLiteDatabase,\n organizationId: string,\n objects: readonly CitedObject[],\n target: WriterProjectionTarget,\n limit: number,\n) {\n const collector = citationCollector(limit);\n for await (const row of lineageKekLevels(\n db,\n organizationId,\n objects,\n target,\n collector.remaining,\n ))\n await collector.collect([row], readStoredKekLevel);\n await collectObjects(db, organizationId, objects, collector);\n await collectRecent(db, organizationId, collector, limit);\n return { cited: [...collector.cited.values()], damaged: collector.damaged };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { HeldProjectionCitation, VerifiedManifestCitations, WriterProjectionTarget } from "../../internal/api-client/index.js";
2
- import type { AccessManifestBundleWireResponse } from "../../internal/validators/response/index.js";
2
+ import { type ServedAccessManifestBundleWireResponse } from "../../internal/validators/util/index.js";
3
3
  import { verifiedAccessManifestBundles as bundles } from "../sqlite/schema/verifiedManifestBundleSchema.js";
4
4
  import { type ClientSQLiteTransactionScope } from "../sqlite/sqlitePersistenceRuntime.js";
5
5
  import { type ExecSql } from "../sqlite/sqlSchema.js";
@@ -10,7 +10,8 @@ import { type VerifiedKekLevel } from "./verifiedCitations/kekLevelCitations.js"
10
10
  */
11
11
  export declare const MAX_VERIFIED_MANIFEST_BUNDLES = 1024;
12
12
  interface VerifiedBundle {
13
- readonly bundle: AccessManifestBundleWireResponse;
13
+ /** The served bytes; the decoded state is rebuilt from them on refill. */
14
+ readonly bundle: ServedAccessManifestBundleWireResponse;
14
15
  readonly checkpoint: {
15
16
  readonly objectKind: string;
16
17
  readonly organizationId: string;
@@ -1,5 +1,5 @@
1
1
  import { toFingerprint } from "../../internal/crypto/index.js";
2
- import { KNOWN_MANIFEST_HINT_LIMIT } from "../../internal/validators/util/index.js";
2
+ import { KNOWN_MANIFEST_HINT_LIMIT, } from "../../internal/validators/util/index.js";
3
3
  import { and, asc, eq, inArray, notInArray, sql } from "drizzle-orm";
4
4
  import { containerTables, localIntentTables } from "../sqlite/schema/index.js";
5
5
  import { documentContainerProjectionTables, documentProjectionTables, } from "../sqlite/schema/documentProjectionSchema.js";
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedManifestBundlePersistence.js","sourceRoot":"","sources":["verifiedManifestBundlePersistence.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EACL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,6BAA6B,IAAI,OAAO,EACxC,4BAA4B,GAC7B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CA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CAAC,MAAM,GAAG,CAAC;QACpB,MAAM,iCAAiC,CAAC,OAAO,CAAC;aAC7C,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE;YAC5B,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC;gBAChD,MAAM,MAAM;qBACT,MAAM,CAAC,OAAO,CAAC;qBACf,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;qBAC3C,GAAG,EAAE,CAAC;QACb,CAAC,CAAC;aACD,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC5B,OAAO,KAAK,CAAC;AACf,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 type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport { KNOWN_MANIFEST_HINT_LIMIT } 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 readonly bundle: AccessManifestBundleWireResponse;\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,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EACL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,6BAA6B,IAAI,OAAO,EACxC,4BAA4B,GAC7B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,E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C,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE;YAC5B,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC;gBAChD,MAAM,MAAM;qBACT,MAAM,CAAC,OAAO,CAAC;qBACf,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;qBAC3C,GAAG,EAAE,CAAC;QACb,CAAC,CAAC;aACD,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC5B,OAAO,KAAK,CAAC;AACf,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 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"]}
@@ -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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E,OAAO,aAAa,CAAC,KAAK,CAAC,CAAC;IACzC,MAAM,oBAAoB,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;IACpD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QACpB,OAAO,UAAU,CAAC,KAAK,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC;IAC3D,OAAO,UAAU,CAAC,KAAK,CAAC,aAAa,EAAE;QACrC,GAAG,gBAAgB;QACnB,GAAG,CAAC,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,K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Aa,CAAC,YAAY,CAAC,QAAQ,GAAG,CAAC;QACvD,sBAAsB,EAAE,aAAa,CAAC,eAAe,CAAC,SAAS,CAAC;QAChE,cAAc,EAAE,MAAM,aAAa,CAAC,eAAe,CAAC,SAAS,CAAC;QAC9D,OAAO,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;QAChE,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,CA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AE,MAAM,CAAC,eAAe;QACvC,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,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"]}
@@ -1,4 +1,5 @@
1
- import { type AccessManifestBundleWireResponse, type ContainerKekWireLevel } from "../validators/response/index.js";
1
+ import { type ContainerKekWireLevel } from "../validators/response/index.js";
2
+ import { type ServedAccessManifestBundleWireResponse } from "../validators/util/index.js";
2
3
  /** Citation only saves bytes: a source slower than this sends the read uncited. */
3
4
  export declare const MANIFEST_CITATION_DEADLINE_MS = 250;
4
5
  /**
@@ -15,7 +16,7 @@ export interface WriterProjectionTarget {
15
16
  readonly listing?: WriterProjectionListing | undefined;
16
17
  }
17
18
  /** A held access-manifest bundle or a held container KEK level. */
18
- export type HeldProjectionCitation = AccessManifestBundleWireResponse | ContainerKekWireLevel;
19
+ export type HeldProjectionCitation = ServedAccessManifestBundleWireResponse | ContainerKekWireLevel;
19
20
  /**
20
21
  * Verified access-manifest bundles and container KEK levels a device durably
21
22
  * holds that a writer projection of `target` may cite, most useful first.
@@ -28,7 +29,7 @@ export interface VerifiedManifestCitations {
28
29
  }
29
30
  /** The exact bytes one request cites: bundles by hash, levels by digest. */
30
31
  export interface HeldProjectionCitations {
31
- readonly bundles: Map<string, AccessManifestBundleWireResponse>;
32
+ readonly bundles: Map<string, ServedAccessManifestBundleWireResponse>;
32
33
  readonly kekLevels: Map<string, ContainerKekWireLevel>;
33
34
  }
34
35
  /**
@@ -1,6 +1,6 @@
1
1
  import { computeContainerKekLevelDigest } from "../crypto/index.js";
2
- import { isAccessManifestBundleWireResponse, isContainerKekWireLevel, } from "../validators/response/index.js";
3
- import { isSha256HexString, KNOWN_MANIFEST_HINT_LIMIT, } from "../validators/util/index.js";
2
+ import { isContainerKekWireLevel, } from "../validators/response/index.js";
3
+ import { isServedAccessManifestBundleWireResponse, isSha256HexString, KNOWN_MANIFEST_HINT_LIMIT, } from "../validators/util/index.js";
4
4
  /** Citation only saves bytes: a source slower than this sends the read uncited. */
5
5
  export const MANIFEST_CITATION_DEADLINE_MS = 250;
6
6
  function noCitations() {
@@ -48,7 +48,7 @@ async function prepareHeldCitations(entries) {
48
48
  try {
49
49
  if (isContainerKekWireLevel(entry))
50
50
  levels.push(structuredClone(entry));
51
- else if (isAccessManifestBundleWireResponse(entry) &&
51
+ else if (isServedAccessManifestBundleWireResponse(entry) &&
52
52
  isSha256HexString(entry.manifestHash) &&
53
53
  !held.bundles.has(entry.manifestHash))
54
54
  held.bundles.set(entry.manifestHash, structuredClone(entry));
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedManifestCitations.js","sourceRoot":"","sources":["verifiedManifestCitations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAGL,kCAAkC,EAClC,uBAAuB,GACxB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,iBAAiB,EACjB,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AAEpC,mFAAmF;AACnF,MAAM,CAAC,MAAM,6BAA6B,GAAG,GAAG,CAAC;AAyCjD,SAAS,WAAW;IAClB,OAAO,EAAE,OAAO,EAAE,IAAI,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,GAAG,EAAE,EAAE,CAAC;AACtD,CAAC;AAED;;;;GAIG;AACH,SAAS,eAAe,CACtB,OAA+C,EAC/C,MAA+B;IAE/B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,MAAM,MAAM,GAAG,CAAC,IAA6B,EAAE,EAAE;YAC/C,IAAI,OAAO;gBAAE,OAAO;YACpB,OAAO,GAAG,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AAO,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;QACjE,CAAC;QAAC,MAAM,CAAC;YACP,4DAA4D;QAC9D,CAAC;IACH,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC,CAAC;IAC9E,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAC9B,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;QAC9B,IAAI,MAAM,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC;YACvC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,MAAwC,EACxC,MAA8B,EAC9B,MAAgC;IAEhC,IAAI,CAAC,MAAM;QAAE,OAAO,WAAW,EAAE,CAAC;IAClC,OAAO,eAAe,CACpB,KAAK,IAAI,EAAE,CAAC,oBAAoB,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAC3D,MAAM,CACP,CAAC;AACJ,CAAC","sourcesContent":["import { computeContainerKekLevelDigest } from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKekWireLevel,\n isAccessManifestBundleWireResponse,\n isContainerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport {\n isSha256HexString,\n KNOWN_MANIFEST_HINT_LIMIT,\n} from \"@tearleads/validators/util\";\n\n/** Citation only saves bytes: a source slower than this sends the read uncited. */\nexport const MANIFEST_CITATION_DEADLINE_MS = 250;\n\n/**\n * Where a listing placed a container the device has not stored yet. Only\n * which held bytes a read cites depends on it, never what the read accepts.\n */\nexport interface WriterProjectionListing {\n readonly organizationId: string;\n readonly parentId: string | null;\n}\n\nexport interface WriterProjectionTarget {\n readonly kind: \"container\" | \"document\";\n readonly id: string;\n readonly listing?: WriterProjectionListing | undefined;\n}\n\n/** A held access-manifest bundle or a held container KEK level. */\nexport type HeldProjectionCitation =\n | AccessManifestBundleWireResponse\n | ContainerKekWireLevel;\n\n/**\n * Verified access-manifest bundles and container KEK levels a device durably\n * holds that a writer projection of `target` may cite, most useful first.\n * This is never trust input: the exact cited bytes only fill the response's\n * omitted positions, and the caller verifies the rebuilt projection exactly\n * as a full one.\n */\nexport interface VerifiedManifestCitations {\n cite(\n target: WriterProjectionTarget,\n ): Promise<readonly HeldProjectionCitation[]>;\n}\n\n/** The exact bytes one request cites: bundles by hash, levels by digest. */\nexport interface HeldProjectionCitations {\n readonly bundles: Map<string, AccessManifestBundleWireResponse>;\n readonly kekLevels: Map<string, ContainerKekWireLevel>;\n}\n\nfunction noCitations(): HeldProjectionCitations {\n return { bundles: new Map(), kekLevels: new Map() };\n}\n\n/**\n * The prepared citations, or none once the deadline passes, the caller\n * aborts, or the source or preparation throws or rejects. A late answer is\n * discarded: it can never reach a request that was already sent.\n */\nfunction boundedCitation(\n prepare: () => Promise<HeldProjectionCitations>,\n signal: AbortSignal | undefined,\n): Promise<HeldProjectionCitations> {\n return new Promise((resolve) => {\n let settled = false;\n const finish = (held: HeldProjectionCitations) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", abandon);\n resolve(held);\n };\n const abandon = () => finish(noCitations());\n const timer = setTimeout(abandon, MANIFEST_CITATION_DEADLINE_MS);\n if (signal?.aborted) return abandon();\n signal?.addEventListener(\"abort\", abandon, { once: true });\n try {\n prepare().then(finish, abandon);\n } catch {\n abandon();\n }\n });\n}\n\n/**\n * Copies the source's answer and keys each KEK level by the digest\n * recomputed from its own bytes, never by a digest the source names.\n */\nasync function prepareHeldCitations(\n entries: readonly unknown[],\n): Promise<HeldProjectionCitations> {\n const held = noCitations();\n const levels: ContainerKekWireLevel[] = [];\n for (const entry of entries) {\n if (held.bundles.size + levels.length >= KNOWN_MANIFEST_HINT_LIMIT) break;\n try {\n if (isContainerKekWireLevel(entry)) levels.push(structuredClone(entry));\n else if (\n isAccessManifestBundleWireResponse(entry) &&\n isSha256HexString(entry.manifestHash) &&\n !held.bundles.has(entry.manifestHash)\n )\n held.bundles.set(entry.manifestHash, structuredClone(entry));\n } catch {\n // An uncloneable entry is skipped; its bytes simply travel.\n }\n }\n const digests = await Promise.all(levels.map(computeContainerKekLevelDigest));\n levels.forEach((level, index) => {\n const digest = digests[index];\n if (digest && !held.kekLevels.has(digest))\n held.kekLevels.set(digest, level);\n });\n return held;\n}\n\n/**\n * The bytes one request cites, copied so a later eviction or mutation of the\n * source cannot change what fills its omissions. Citing only saves bytes, so\n * it never blocks or fails a read: a slow, failing, or abandoned source or\n * preparation yields no hints, within one deadline.\n */\nexport async function heldManifestCitations(\n source: VerifiedManifestCitations | null,\n target: WriterProjectionTarget,\n signal?: AbortSignal | undefined,\n): Promise<HeldProjectionCitations> {\n if (!source) return noCitations();\n return boundedCitation(\n async () => prepareHeldCitations(await source.cite(target)),\n signal,\n );\n}\n"]}
1
+ {"version":3,"file":"verifiedManifestCitations.js","sourceRoot":"","sources":["verifiedManifestCitations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAEL,uBAAuB,GACxB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,wCAAwC,EACxC,iBAAiB,EACjB,yBAAyB,GAE1B,MAAM,4BAA4B,CAAC;AAEpC,mFAAmF;AACnF,MAAM,CAAC,MAAM,6BAA6B,GAAG,GAAG,CAAC;AAyCjD,SAAS,WAAW;IAClB,OAAO,EAAE,OAAO,EAAE,IAAI,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,GAAG,EAAE,EAAE,CAAC;AACtD,CA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AK,CAAC;gBAAE,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;iBACnE,IACH,wCAAwC,CAAC,KAAK,CAAC;gBAC/C,iBAAiB,CAAC,KAAK,CAAC,YAAY,CAAC;gBACrC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,CAAC;gBAErC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;QACjE,CAAC;QAAC,MAAM,CAAC;YACP,4DAA4D;QAC9D,CAAC;IACH,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC,CAAC;IAC9E,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAC9B,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;QAC9B,IAAI,MAAM,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC;YACvC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,MAAwC,EACxC,MAA8B,EAC9B,MAAgC;IAEhC,IAAI,CAAC,MAAM;QAAE,OAAO,WAAW,EAAE,CAAC;IAClC,OAAO,eAAe,CACpB,KAAK,IAAI,EAAE,CAAC,oBAAoB,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAC3D,MAAM,CACP,CAAC;AACJ,CAAC","sourcesContent":["import { computeContainerKekLevelDigest } from \"@tearleads/crypto\";\nimport {\n type ContainerKekWireLevel,\n isContainerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport {\n isServedAccessManifestBundleWireResponse,\n isSha256HexString,\n KNOWN_MANIFEST_HINT_LIMIT,\n type ServedAccessManifestBundleWireResponse,\n} from \"@tearleads/validators/util\";\n\n/** Citation only saves bytes: a source slower than this sends the read uncited. */\nexport const MANIFEST_CITATION_DEADLINE_MS = 250;\n\n/**\n * Where a listing placed a container the device has not stored yet. Only\n * which held bytes a read cites depends on it, never what the read accepts.\n */\nexport interface WriterProjectionListing {\n readonly organizationId: string;\n readonly parentId: string | null;\n}\n\nexport interface WriterProjectionTarget {\n readonly kind: \"container\" | \"document\";\n readonly id: string;\n readonly listing?: WriterProjectionListing | undefined;\n}\n\n/** A held access-manifest bundle or a held container KEK level. */\nexport type HeldProjectionCitation =\n | ServedAccessManifestBundleWireResponse\n | ContainerKekWireLevel;\n\n/**\n * Verified access-manifest bundles and container KEK levels a device durably\n * holds that a writer projection of `target` may cite, most useful first.\n * This is never trust input: the exact cited bytes only fill the response's\n * omitted positions, and the caller verifies the rebuilt projection exactly\n * as a full one.\n */\nexport interface VerifiedManifestCitations {\n cite(\n target: WriterProjectionTarget,\n ): Promise<readonly HeldProjectionCitation[]>;\n}\n\n/** The exact bytes one request cites: bundles by hash, levels by digest. */\nexport interface HeldProjectionCitations {\n readonly bundles: Map<string, ServedAccessManifestBundleWireResponse>;\n readonly kekLevels: Map<string, ContainerKekWireLevel>;\n}\n\nfunction noCitations(): HeldProjectionCitations {\n return { bundles: new Map(), kekLevels: new Map() };\n}\n\n/**\n * The prepared citations, or none once the deadline passes, the caller\n * aborts, or the source or preparation throws or rejects. A late answer is\n * discarded: it can never reach a request that was already sent.\n */\nfunction boundedCitation(\n prepare: () => Promise<HeldProjectionCitations>,\n signal: AbortSignal | undefined,\n): Promise<HeldProjectionCitations> {\n return new Promise((resolve) => {\n let settled = false;\n const finish = (held: HeldProjectionCitations) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", abandon);\n resolve(held);\n };\n const abandon = () => finish(noCitations());\n const timer = setTimeout(abandon, MANIFEST_CITATION_DEADLINE_MS);\n if (signal?.aborted) return abandon();\n signal?.addEventListener(\"abort\", abandon, { once: true });\n try {\n prepare().then(finish, abandon);\n } catch {\n abandon();\n }\n });\n}\n\n/**\n * Copies the source's answer and keys each KEK level by the digest\n * recomputed from its own bytes, never by a digest the source names.\n */\nasync function prepareHeldCitations(\n entries: readonly unknown[],\n): Promise<HeldProjectionCitations> {\n const held = noCitations();\n const levels: ContainerKekWireLevel[] = [];\n for (const entry of entries) {\n if (held.bundles.size + levels.length >= KNOWN_MANIFEST_HINT_LIMIT) break;\n try {\n if (isContainerKekWireLevel(entry)) levels.push(structuredClone(entry));\n else if (\n isServedAccessManifestBundleWireResponse(entry) &&\n isSha256HexString(entry.manifestHash) &&\n !held.bundles.has(entry.manifestHash)\n )\n held.bundles.set(entry.manifestHash, structuredClone(entry));\n } catch {\n // An uncloneable entry is skipped; its bytes simply travel.\n }\n }\n const digests = await Promise.all(levels.map(computeContainerKekLevelDigest));\n levels.forEach((level, index) => {\n const digest = digests[index];\n if (digest && !held.kekLevels.has(digest))\n held.kekLevels.set(digest, level);\n });\n return held;\n}\n\n/**\n * The bytes one request cites, copied so a later eviction or mutation of the\n * source cannot change what fills its omissions. Citing only saves bytes, so\n * it never blocks or fails a read: a slow, failing, or abandoned source or\n * preparation yields no hints, within one deadline.\n */\nexport async function heldManifestCitations(\n source: VerifiedManifestCitations | null,\n target: WriterProjectionTarget,\n signal?: AbortSignal | undefined,\n): Promise<HeldProjectionCitations> {\n if (!source) return noCitations();\n return boundedCitation(\n async () => prepareHeldCitations(await source.cite(target)),\n signal,\n );\n}\n"]}
@@ -161,7 +161,7 @@ export declare const getContainerWriterProjectionOperation: Omit<{
161
161
  };
162
162
  manifest: Record<string, unknown>;
163
163
  manifestHash: string;
164
- state: Record<string, unknown>;
164
+ state: import("../util/index.js").ServedManifestState;
165
165
  }>;
166
166
  omittedBundles: string[];
167
167
  }, {
@@ -243,7 +243,7 @@ export declare const getContainerWriterProjectionOperation: Omit<{
243
243
  };
244
244
  manifest: Record<string, unknown>;
245
245
  manifestHash: string;
246
- state: Record<string, unknown>;
246
+ state: import("../util/index.js").ServedManifestState;
247
247
  }>;
248
248
  omittedBundles: string[];
249
249
  }, z.core.$ZodTypeInternals<{
@@ -325,7 +325,7 @@ export declare const getContainerWriterProjectionOperation: Omit<{
325
325
  };
326
326
  manifest: Record<string, unknown>;
327
327
  manifestHash: string;
328
- state: Record<string, unknown>;
328
+ state: import("../util/index.js").ServedManifestState;
329
329
  }>;
330
330
  omittedBundles: string[];
331
331
  }, {
@@ -407,7 +407,7 @@ export declare const getContainerWriterProjectionOperation: Omit<{
407
407
  };
408
408
  manifest: Record<string, unknown>;
409
409
  manifestHash: string;
410
- state: Record<string, unknown>;
410
+ state: import("../util/index.js").ServedManifestState;
411
411
  }>;
412
412
  omittedBundles: string[];
413
413
  }>>;
@@ -568,7 +568,7 @@ export declare const getDocumentWriterProjectionOperation: Omit<{
568
568
  };
569
569
  manifest: Record<string, unknown>;
570
570
  manifestHash: string;
571
- state: Record<string, unknown>;
571
+ state: import("../util/index.js").ServedManifestState;
572
572
  }>;
573
573
  omittedBundles: string[];
574
574
  policyEvidence: {
@@ -680,7 +680,7 @@ export declare const getDocumentWriterProjectionOperation: Omit<{
680
680
  };
681
681
  manifest: Record<string, unknown>;
682
682
  manifestHash: string;
683
- state: Record<string, unknown>;
683
+ state: import("../util/index.js").ServedManifestState;
684
684
  }>;
685
685
  omittedBundles: string[];
686
686
  policyEvidence: {
@@ -792,7 +792,7 @@ export declare const getDocumentWriterProjectionOperation: Omit<{
792
792
  };
793
793
  manifest: Record<string, unknown>;
794
794
  manifestHash: string;
795
- state: Record<string, unknown>;
795
+ state: import("../util/index.js").ServedManifestState;
796
796
  }>;
797
797
  omittedBundles: string[];
798
798
  policyEvidence: {
@@ -904,7 +904,7 @@ export declare const getDocumentWriterProjectionOperation: Omit<{
904
904
  };
905
905
  manifest: Record<string, unknown>;
906
906
  manifestHash: string;
907
- state: Record<string, unknown>;
907
+ state: import("../util/index.js").ServedManifestState;
908
908
  }>;
909
909
  omittedBundles: string[];
910
910
  policyEvidence: {