@tearleads/client-sdk 0.1.247 → 0.1.249

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 (151) hide show
  1. package/Tearleads.js +4 -2
  2. package/Tearleads.js.map +1 -1
  3. package/client/organizations/index.js +5 -3
  4. package/client/organizations/index.js.map +1 -1
  5. package/client/organizations/organizationGroupPresentation.d.ts +1 -1
  6. package/client/organizations/organizationGroupPresentation.js.map +1 -1
  7. package/client/organizations/organizationLeaveRequestVerifier.js +21 -0
  8. package/client/organizations/organizationLeaveRequestVerifier.js.map +1 -0
  9. package/client/organizations/{organizationReadModels.d.ts → organizationReadModelCoordinator.d.ts} +18 -16
  10. package/client/organizations/organizationReadModelCoordinator.js +2 -0
  11. package/client/organizations/organizationReadModelCoordinator.js.map +1 -0
  12. package/client/organizations/organizationReadModelPresentation.js +51 -0
  13. package/client/organizations/organizationReadModelPresentation.js.map +1 -0
  14. package/client/organizations/organizationReadModelScopes.js +37 -0
  15. package/client/organizations/organizationReadModelScopes.js.map +1 -0
  16. package/client/organizations/organizationReadModels.js +131 -88
  17. package/client/organizations/organizationReadModels.js.map +1 -1
  18. package/client/organizations/organizationsTypes.d.ts +13 -5
  19. package/client/organizations/organizationsTypes.js.map +1 -1
  20. package/client/organizations/principalMutations.d.ts +18 -2
  21. package/client/organizations/principalMutations.js +29 -15
  22. package/client/organizations/principalMutations.js.map +1 -1
  23. package/client/runtime/principalMutationApi.d.ts +2 -0
  24. package/client/runtime/principalMutationApi.js +2 -0
  25. package/client/runtime/principalMutationApi.js.map +1 -1
  26. package/client/runtime/principalMutationDispatch.js +47 -10
  27. package/client/runtime/principalMutationDispatch.js.map +1 -1
  28. package/client/runtime/workflowRuntime.js +5 -4
  29. package/client/runtime/workflowRuntime.js.map +1 -1
  30. package/data/containers/shared/mutationRequestOptions.d.ts +2 -0
  31. package/data/containers/shared/mutationRequestOptions.js.map +1 -1
  32. package/data/containers/shared/types.d.ts +12 -2
  33. package/data/containers/shared/types.js.map +1 -1
  34. package/data/persistence/organizations/organizationReadModelRepository.js +20 -2
  35. package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -1
  36. package/data/persistence/principalPolicy/heldOrganizationDirectories.js +53 -0
  37. package/data/persistence/principalPolicy/heldOrganizationDirectories.js.map +1 -0
  38. package/data/persistence/verifiedManifestBundlePersistence.d.ts +8 -3
  39. package/data/persistence/verifiedManifestBundlePersistence.js +34 -15
  40. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  41. package/internal/api-client/ApiClient.d.ts +4 -1
  42. package/internal/api-client/client/containerMutations.d.ts +2 -2
  43. package/internal/api-client/client/containerMutations.js +2 -1
  44. package/internal/api-client/client/containerMutations.js.map +1 -1
  45. package/internal/api-client/client/principalPolicies.d.ts +3 -0
  46. package/internal/api-client/heldDirectoryCitations.d.ts +19 -0
  47. package/internal/api-client/heldDirectoryCitations.js +37 -0
  48. package/internal/api-client/heldDirectoryCitations.js.map +1 -0
  49. package/internal/api-client/index.d.ts +1 -1
  50. package/internal/api-client/index.js.map +1 -1
  51. package/internal/api-client/principalPolicyRequests.d.ts +2 -0
  52. package/internal/api-client/principalPolicyRequests.js +6 -4
  53. package/internal/api-client/principalPolicyRequests.js.map +1 -1
  54. package/internal/api-client/routes/containers/mutations.js +3 -3
  55. package/internal/api-client/routes/containers/mutations.js.map +1 -1
  56. package/internal/api-client/routes/organizations/createGroup.js +3 -5
  57. package/internal/api-client/routes/organizations/createGroup.js.map +1 -1
  58. package/internal/api-client/routes/principals/policy.js +2 -5
  59. package/internal/api-client/routes/principals/policy.js.map +1 -1
  60. package/internal/api-client/types.d.ts +6 -0
  61. package/internal/api-client/types.js.map +1 -1
  62. package/internal/api-client/verifiedManifestCitations.d.ts +16 -6
  63. package/internal/api-client/verifiedManifestCitations.js +32 -13
  64. package/internal/api-client/verifiedManifestCitations.js.map +1 -1
  65. package/internal/api-client/writerProjectionRequests.js +5 -3
  66. package/internal/api-client/writerProjectionRequests.js.map +1 -1
  67. package/internal/validators/knownManifestsRefinements.js +1 -1
  68. package/internal/validators/knownManifestsRefinements.js.map +1 -1
  69. package/internal/validators/operation/containerMutations.d.ts +20 -3
  70. package/internal/validators/operation/containerMutations.js +18 -20
  71. package/internal/validators/operation/containerMutations.js.map +1 -1
  72. package/internal/validators/operation/index.d.ts +1 -1
  73. package/internal/validators/operation/index.js +1 -1
  74. package/internal/validators/operation/index.js.map +1 -1
  75. package/internal/validators/operation/organizations.d.ts +17 -1
  76. package/internal/validators/operation/organizations.js +4 -2
  77. package/internal/validators/operation/organizations.js.map +1 -1
  78. package/internal/validators/operation/principals.d.ts +17 -1
  79. package/internal/validators/operation/principals.js +5 -2
  80. package/internal/validators/operation/principals.js.map +1 -1
  81. package/internal/validators/operation/writerProjections.d.ts +11 -11
  82. package/internal/validators/operation/writerProjections.js +1 -1
  83. package/internal/validators/operation/writerProjections.js.map +1 -1
  84. package/internal/validators/request/index.d.ts +1 -1
  85. package/internal/validators/request/index.js +1 -1
  86. package/internal/validators/request/index.js.map +1 -1
  87. package/internal/validators/request/organization.d.ts +15 -0
  88. package/internal/validators/request/organization.js +8 -0
  89. package/internal/validators/request/organization.js.map +1 -1
  90. package/internal/validators/response/areas/organizations.d.ts +3 -2
  91. package/internal/validators/response/areas/organizations.js +3 -2
  92. package/internal/validators/response/areas/organizations.js.map +1 -1
  93. package/internal/validators/response/areas/principals.d.ts +3 -2
  94. package/internal/validators/response/areas/principals.js +2 -2
  95. package/internal/validators/response/areas/principals.js.map +1 -1
  96. package/internal/validators/response/committedReadModel.d.ts +697 -0
  97. package/internal/validators/response/committedReadModel.js +52 -0
  98. package/internal/validators/response/committedReadModel.js.map +1 -0
  99. package/internal/validators/response/container.d.ts +56 -4
  100. package/internal/validators/response/container.js +5 -5
  101. package/internal/validators/response/container.js.map +1 -1
  102. package/internal/validators/response/documentMutation.d.ts +4 -4
  103. package/internal/validators/response/documentMutation.js +2 -2
  104. package/internal/validators/response/documentMutation.js.map +1 -1
  105. package/internal/validators/response/organization.d.ts +0 -191
  106. package/internal/validators/response/organization.js +0 -7
  107. package/internal/validators/response/organization.js.map +1 -1
  108. package/internal/validators/response/organizationReadModel.d.ts +167 -0
  109. package/internal/validators/response/organizationReadModel.js +5 -0
  110. package/internal/validators/response/organizationReadModel.js.map +1 -1
  111. package/internal/validators/response/policyEvidenceWire.d.ts +17 -0
  112. package/internal/validators/response/policyEvidenceWire.js +36 -0
  113. package/internal/validators/response/policyEvidenceWire.js.map +1 -0
  114. package/internal/validators/response/principal.d.ts +0 -403
  115. package/internal/validators/response/principal.js +0 -8
  116. package/internal/validators/response/principal.js.map +1 -1
  117. package/internal/validators/response/projectionPolicyEvidence.d.ts +175 -0
  118. package/internal/validators/response/projectionPolicyEvidence.js +13 -0
  119. package/internal/validators/response/projectionPolicyEvidence.js.map +1 -1
  120. package/internal/validators/response/writerProjectionWire.d.ts +11 -7
  121. package/internal/validators/response/writerProjectionWire.js +19 -10
  122. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  123. package/internal/validators/util/index.d.ts +1 -1
  124. package/internal/validators/util/index.js +1 -1
  125. package/internal/validators/util/index.js.map +1 -1
  126. package/internal/validators/util/knownManifestWire.d.ts +9 -3
  127. package/internal/validators/util/knownManifestWire.js +24 -8
  128. package/internal/validators/util/knownManifestWire.js.map +1 -1
  129. package/package.json +1 -1
  130. package/workflows/container-contents/container-state/organizationHost.d.ts +9 -0
  131. package/workflows/container-contents/container-state/organizationHost.js.map +1 -1
  132. package/workflows/container-contents/container-state/remote.js +6 -0
  133. package/workflows/container-contents/container-state/remote.js.map +1 -1
  134. package/workflows/containers/child/share/index.d.ts +4 -2
  135. package/workflows/containers/child/share/index.js +37 -20
  136. package/workflows/containers/child/share/index.js.map +1 -1
  137. package/workflows/organizations/containerContentsHost.js +20 -1
  138. package/workflows/organizations/containerContentsHost.js.map +1 -1
  139. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js +5 -1
  140. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -1
  141. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +8 -1
  142. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  143. package/workflows/organizations/index.d.ts +1 -0
  144. package/workflows/organizations/index.js +1 -0
  145. package/workflows/organizations/index.js.map +1 -1
  146. package/workflows/organizations/readModel/committedReadModel.d.ts +66 -0
  147. package/workflows/organizations/readModel/committedReadModel.js +150 -0
  148. package/workflows/organizations/readModel/committedReadModel.js.map +1 -0
  149. package/workflows/organizations/readModel/readModelProjection.d.ts +15 -2
  150. package/workflows/organizations/readModel/readModelProjection.js +26 -4
  151. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
@@ -1,6 +1,7 @@
1
1
  import { type ServedAccessManifestBundleWireResponse } from "../util/index.js";
2
2
  import { type ContainerKekResponse, type ContainerKekWireLevel, type ContainerWriterProjectionResponse, type ContainerWriterProjectionWireResponse } from "./container.js";
3
3
  import { type DocumentWriterProjectionResponse, type DocumentWriterProjectionWireResponse } from "./documentMutation.js";
4
+ import { type HeldDirectoryPayloads } from "./policyEvidenceWire.js";
4
5
  type ServedBundle = ServedAccessManifestBundleWireResponse;
5
6
  type HeldLevels = ReadonlyMap<string, ContainerKekWireLevel>;
6
7
  /** A KEK level's wire form: its manifest history cited by hash. */
@@ -14,11 +15,13 @@ export type HeldKekLevelDigest = (kek: ContainerKekResponse) => string | null;
14
15
  /**
15
16
  * Call only after authorization and stored-evidence verification. `known`
16
17
  * holds the request's manifest hints; only hashes this projection cites are
17
- * omitted. `heldLevel` names each KEK level the request holds exactly.
18
+ * omitted. `heldLevel` names each KEK level the request holds exactly, and
19
+ * `heldDirectories` the organization states whose directory payloads it
20
+ * holds.
18
21
  */
19
- export declare function encodeContainerWriterProjection(projection: ContainerWriterProjectionResponse, known?: ReadonlySet<string>, heldLevel?: HeldKekLevelDigest): ContainerWriterProjectionWireResponse;
22
+ export declare function encodeContainerWriterProjection(projection: ContainerWriterProjectionResponse, known?: ReadonlySet<string>, heldLevel?: HeldKekLevelDigest, heldDirectories?: ReadonlySet<string>): ContainerWriterProjectionWireResponse;
20
23
  /** See {@link encodeContainerWriterProjection}. */
21
- export declare function encodeDocumentWriterProjection(projection: DocumentWriterProjectionResponse, known?: ReadonlySet<string>, heldLevel?: HeldKekLevelDigest): DocumentWriterProjectionWireResponse;
24
+ export declare function encodeDocumentWriterProjection(projection: DocumentWriterProjectionResponse, known?: ReadonlySet<string>, heldLevel?: HeldKekLevelDigest, heldDirectories?: ReadonlySet<string>): DocumentWriterProjectionWireResponse;
22
25
  /**
23
26
  * The held bundles a decoded projection filled omissions from. A verifier
24
27
  * that refuses such a projection drops exactly those held rows, so the next
@@ -45,11 +48,12 @@ export declare function rejectDecodedProjection(projection: object): void;
45
48
  export declare function acceptDecodedProjection(projection: object): void;
46
49
  export declare function isRejectedDecodedProjection(projection: unknown): boolean;
47
50
  /**
48
- * Null for any wire inconsistency or an omission `held` (bundles) or
49
- * `heldLevels` (KEK levels by digest) cannot fill; the caller treats either
51
+ * Null for any wire inconsistency or an omission `held` (bundles),
52
+ * `heldLevels` (KEK levels by digest) or `heldDirectories` (directory
53
+ * payloads by organization state hash) cannot fill; the caller treats either
50
54
  * as a shape failure.
51
55
  */
52
- export declare function decodeContainerWriterProjection(value: unknown, held?: ReadonlyMap<string, ServedBundle>, heldLevels?: HeldLevels): ContainerWriterProjectionResponse | null;
56
+ export declare function decodeContainerWriterProjection(value: unknown, held?: ReadonlyMap<string, ServedBundle>, heldLevels?: HeldLevels, heldDirectories?: HeldDirectoryPayloads): ContainerWriterProjectionResponse | null;
53
57
  /** See {@link decodeContainerWriterProjection}. */
54
- export declare function decodeDocumentWriterProjection(value: unknown, held?: ReadonlyMap<string, ServedBundle>, heldLevels?: HeldLevels): DocumentWriterProjectionResponse | null;
58
+ export declare function decodeDocumentWriterProjection(value: unknown, held?: ReadonlyMap<string, ServedBundle>, heldLevels?: HeldLevels, heldDirectories?: HeldDirectoryPayloads): DocumentWriterProjectionResponse | null;
55
59
  export {};
@@ -1,6 +1,7 @@
1
1
  import { completeServedAccessManifestBundle, toServedAccessManifestBundle, } from "../util/index.js";
2
2
  import { ContainerWriterProjectionWireResponseSchema, isCitedContainerKekLevel, } from "./container.js";
3
3
  import { DocumentWriterProjectionWireResponseSchema, } from "./documentMutation.js";
4
+ import { decodeProjectionPolicyEvidence, encodeProjectionPolicyEvidence, } from "./policyEvidenceWire.js";
4
5
  /**
5
6
  * Collects each distinct manifest once. Every slot a server fills for one
6
7
  * hash comes from the same stored row, and the client verifies the bundle it
@@ -55,24 +56,28 @@ const noHeldLevels = () => null;
55
56
  /**
56
57
  * Call only after authorization and stored-evidence verification. `known`
57
58
  * holds the request's manifest hints; only hashes this projection cites are
58
- * omitted. `heldLevel` names each KEK level the request holds exactly.
59
+ * omitted. `heldLevel` names each KEK level the request holds exactly, and
60
+ * `heldDirectories` the organization states whose directory payloads it
61
+ * holds.
59
62
  */
60
- export function encodeContainerWriterProjection(projection, known = new Set(), heldLevel = noHeldLevels) {
63
+ export function encodeContainerWriterProjection(projection, known = new Set(), heldLevel = noHeldLevels, heldDirectories = new Set()) {
61
64
  const citations = bundleCitations(known);
62
65
  const encoded = encodeKeyingPath(projection, citations.cite, heldLevel);
63
66
  return {
64
67
  ...projection,
65
68
  ...encoded,
69
+ policyEvidence: encodeProjectionPolicyEvidence(projection.policyEvidence, heldDirectories),
66
70
  bundles: citations.bundles(),
67
71
  omittedBundles: citations.omitted(),
68
72
  };
69
73
  }
70
74
  /** See {@link encodeContainerWriterProjection}. */
71
- export function encodeDocumentWriterProjection(projection, known = new Set(), heldLevel = noHeldLevels) {
75
+ export function encodeDocumentWriterProjection(projection, known = new Set(), heldLevel = noHeldLevels, heldDirectories = new Set()) {
72
76
  const { cite, bundles, omitted } = bundleCitations(known);
73
77
  const authorizingContainerPaths = projection.authorizingContainerPaths.map((path) => encodeKeyingPath(path, cite, heldLevel));
74
78
  return {
75
79
  ...projection,
80
+ policyEvidence: encodeProjectionPolicyEvidence(projection.policyEvidence, heldDirectories),
76
81
  authorizingContainerPaths,
77
82
  documentContainerManifestHistory: projection.documentContainerManifestHistory.map(cite),
78
83
  documentManifest: cite(projection.documentManifest),
@@ -248,33 +253,36 @@ function withHeldBundles(projection, omittedBundles, held) {
248
253
  return projection;
249
254
  }
250
255
  /**
251
- * Null for any wire inconsistency or an omission `held` (bundles) or
252
- * `heldLevels` (KEK levels by digest) cannot fill; the caller treats either
256
+ * Null for any wire inconsistency or an omission `held` (bundles),
257
+ * `heldLevels` (KEK levels by digest) or `heldDirectories` (directory
258
+ * payloads by organization state hash) cannot fill; the caller treats either
253
259
  * as a shape failure.
254
260
  */
255
- export function decodeContainerWriterProjection(value, held = new Map(), heldLevels = new Map()) {
261
+ export function decodeContainerWriterProjection(value, held = new Map(), heldLevels = new Map(), heldDirectories = new Map()) {
256
262
  const parsed = ContainerWriterProjectionWireResponseSchema.safeParse(value);
257
263
  if (!parsed.success) {
258
264
  return null;
259
265
  }
260
266
  const { bundles, omittedBundles, ...projection } = parsed.data;
267
+ const policyEvidence = decodeProjectionPolicyEvidence(projection.policyEvidence, heldDirectories);
261
268
  const resolve = bundleResolver(bundles, omittedBundles, held);
262
269
  const path = resolve
263
270
  ? decodeKeyingPath(projection, resolve, heldLevels)
264
271
  : null;
265
- return path
266
- ? withHeldBundles({ ...projection, ...path }, omittedBundles, held)
272
+ return path && policyEvidence
273
+ ? withHeldBundles({ ...projection, ...path, policyEvidence }, omittedBundles, held)
267
274
  : null;
268
275
  }
269
276
  /** See {@link decodeContainerWriterProjection}. */
270
- export function decodeDocumentWriterProjection(value, held = new Map(), heldLevels = new Map()) {
277
+ export function decodeDocumentWriterProjection(value, held = new Map(), heldLevels = new Map(), heldDirectories = new Map()) {
271
278
  const parsed = DocumentWriterProjectionWireResponseSchema.safeParse(value);
272
279
  if (!parsed.success) {
273
280
  return null;
274
281
  }
275
282
  const { bundles, omittedBundles, ...projection } = parsed.data;
283
+ const policyEvidence = decodeProjectionPolicyEvidence(projection.policyEvidence, heldDirectories);
276
284
  const resolve = bundleResolver(bundles, omittedBundles, held);
277
- if (!resolve) {
285
+ if (!resolve || !policyEvidence) {
278
286
  return null;
279
287
  }
280
288
  const authorizingContainerPaths = [];
@@ -289,6 +297,7 @@ export function decodeDocumentWriterProjection(value, held = new Map(), heldLeve
289
297
  return null;
290
298
  return withHeldBundles({
291
299
  ...projection,
300
+ policyEvidence,
292
301
  authorizingContainerPaths: [firstPath, ...otherPaths],
293
302
  documentContainerManifestHistory: projection.documentContainerManifestHistory.map(resolve),
294
303
  documentManifest: resolve(projection.documentManifest),
@@ -1 +1 @@
1
- {"version":3,"file":"writerProjectionWire.js","sourceRoot":"","sources":["writerProjectionWire.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,kCAAkC,EAElC,4BAA4B,GAC7B,MAAM,SAAS,CAAC;AACjB,OAAO,EAOL,2CAA2C,EAC3C,wBAAwB,GACzB,MAAM,aAAa,CAAC;AACrB,OAAO,EAGL,0CAA0C,GAC3C,MAAM,oBAAoB,CAAC;AAM5B;;;;;;GAMG;AACH,SAAS,eAAe,CAAC,KAA0B;IACjD,MAAM,MAAM,GAAG,IAAI,GAAG,EAAwB,CAAC;IAC/C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,OAAO;QACL,IAAI,CAAC,MAAc;YACjB,MAAM,IAAI,GAAG,MAAM,CAAC,YAAY,CAAC;YACjC,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;gBAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;iBAClC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC;gBACxB,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,4BAA4B,CAAC,MAAM,CAAC,CAAC,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,uEAAuE;QACvE,OAAO,EAAE,GAAiC,EAAE,CAAC,MAAM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OAAO,CAAC;QAC1D,gBAAgB,EAAE,OAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC;QACtD,8BAA8B,EAC5B,UAAU,CAAC,8BAA8B,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACrD,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAClB;QACH,uBAAuB,EAAE,UAAU,CAAC,uBAAuB,CAAC,GAAG,CAAC,OAAO,CAAC;KACzE,EACD,cAAc,EACd,IAAI,CACL,CAAC;AACJ,CAAC","sourcesContent":["import {\n type AccessManifestBundleWireResponse,\n completeServedAccessManifestBundle,\n type ServedAccessManifestBundleWireResponse,\n toServedAccessManifestBundle,\n} from \"../util\";\nimport {\n type ContainerKekResponse,\n type ContainerKekWireLevel,\n type ContainerKeyingPathResponse,\n type ContainerKeyingPathWireResponse,\n type ContainerWriterProjectionResponse,\n type ContainerWriterProjectionWireResponse,\n ContainerWriterProjectionWireResponseSchema,\n isCitedContainerKekLevel,\n} from \"./container\";\nimport {\n type DocumentWriterProjectionResponse,\n type DocumentWriterProjectionWireResponse,\n DocumentWriterProjectionWireResponseSchema,\n} from \"./documentMutation\";\n\ntype Bundle = AccessManifestBundleWireResponse;\ntype ServedBundle = ServedAccessManifestBundleWireResponse;\ntype HeldLevels = ReadonlyMap<string, ContainerKekWireLevel>;\n\n/**\n * Collects each distinct manifest once. Every slot a server fills for one\n * hash comes from the same stored row, and the client verifies the bundle it\n * receives wherever that hash is cited, so the first occurrence stands. A\n * hash the request declared known is cited but not served. A served bundle's\n * state leaves out what its own signed bytes name; decoding fills it back.\n */\nfunction bundleCitations(known: ReadonlySet<string>) {\n const byHash = new Map<string, ServedBundle>();\n const omitted = new Set<string>();\n return {\n cite(bundle: Bundle): string {\n const hash = bundle.manifestHash;\n if (known.has(hash)) omitted.add(hash);\n else if (!byHash.has(hash))\n byHash.set(hash, toServedAccessManifestBundle(bundle));\n return hash;\n },\n // fromEntries defines own data properties, even for a \"__proto__\" key.\n bundles: (): Record<string, ServedBundle> => Object.fromEntries(byHash),\n omitted: (): string[] => [...omitted],\n };\n}\n\n/** A KEK level's wire form: its manifest history cited by hash. */\nexport function containerKekWireLevel(\n kek: ContainerKekResponse,\n): ContainerKekWireLevel {\n return {\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(\n (bundle) => bundle.manifestHash,\n ),\n };\n}\n\n/**\n * The digest a request declared for a KEK level it holds, or null when the\n * level travels in full. The caller derives it from the level's own served\n * bytes, so a level is omitted only when the held copy is exactly these.\n */\nexport type HeldKekLevelDigest = (kek: ContainerKekResponse) => string | null;\n\nfunction encodeKeyingPath(\n path: ContainerKeyingPathResponse,\n cite: (bundle: Bundle) => string,\n heldLevel: HeldKekLevelDigest,\n): ContainerKeyingPathWireResponse {\n return {\n ...path,\n path: path.path.map(cite),\n containerKeks: path.containerKeks.map((kek) => {\n const level = {\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(cite),\n };\n const levelDigest = heldLevel(kek);\n return levelDigest === null\n ? level\n : {\n levelDigest,\n containerManifestHistory: level.containerManifestHistory,\n };\n }),\n };\n}\n\nconst noHeldLevels: HeldKekLevelDigest = () => null;\n\n/**\n * Call only after authorization and stored-evidence verification. `known`\n * holds the request's manifest hints; only hashes this projection cites are\n * omitted. `heldLevel` names each KEK level the request holds exactly.\n */\nexport function encodeContainerWriterProjection(\n projection: ContainerWriterProjectionResponse,\n known: ReadonlySet<string> = new Set(),\n heldLevel: HeldKekLevelDigest = noHeldLevels,\n): ContainerWriterProjectionWireResponse {\n const citations = bundleCitations(known);\n const encoded = encodeKeyingPath(projection, citations.cite, heldLevel);\n return {\n ...projection,\n ...encoded,\n bundles: citations.bundles(),\n omittedBundles: citations.omitted(),\n };\n}\n\n/** See {@link encodeContainerWriterProjection}. */\nexport function encodeDocumentWriterProjection(\n projection: DocumentWriterProjectionResponse,\n known: ReadonlySet<string> = new Set(),\n heldLevel: HeldKekLevelDigest = noHeldLevels,\n): DocumentWriterProjectionWireResponse {\n const { cite, bundles, omitted } = bundleCitations(known);\n const authorizingContainerPaths = projection.authorizingContainerPaths.map(\n (path) => encodeKeyingPath(path, cite, heldLevel),\n );\n return {\n ...projection,\n authorizingContainerPaths,\n documentContainerManifestHistory:\n projection.documentContainerManifestHistory.map(cite),\n documentManifest: cite(projection.documentManifest),\n documentManifestContainerPaths:\n projection.documentManifestContainerPaths.map((path) => path.map(cite)),\n documentManifestHistory: projection.documentManifestHistory.map(cite),\n bundles: bundles(),\n omittedBundles: omitted(),\n };\n}\n\n/**\n * Served bundles plus the exact held bytes for each omitted hash. An omission\n * the caller cannot fill from `held` (which carries only what its request\n * cited) makes the response unusable. Each bundle's state gets back the\n * fields its own signed bytes name. Each cited position receives its own\n * copy, as when every slot carried its own JSON.\n */\nfunction bundleResolver(\n bundles: Record<string, ServedBundle>,\n omittedBundles: readonly string[],\n held: ReadonlyMap<string, ServedBundle>,\n): ((hash: string) => Bundle) | null {\n const byHash = new Map(\n Object.entries(bundles).map(\n ([hash, bundle]) =>\n [hash, completeServedAccessManifestBundle(bundle)] as const,\n ),\n );\n for (const hash of omittedBundles) {\n const bundle = held.get(hash);\n if (bundle?.manifestHash !== hash) return null;\n byHash.set(hash, completeServedAccessManifestBundle(bundle));\n }\n return (hash: string): Bundle => {\n const bundle = byHash.get(hash);\n if (!bundle) {\n throw new Error(`manifest ${hash} is cited without a bundle`);\n }\n return structuredClone(bundle);\n };\n}\n\nfunction sameHashes(left: readonly string[], right: readonly string[]) {\n return (\n left.length === right.length &&\n left.every((hash, index) => hash === right[index])\n );\n}\n\n/**\n * Each cited KEK level becomes its own copy of the exact held level this\n * request declared under that digest. A digest the request did not cite, or\n * a held level whose manifest citations differ from the stub's, makes the\n * path unusable: the caller refetches in full.\n */\nfunction fillKekLevels(\n path: ContainerKeyingPathWireResponse,\n heldLevels: HeldLevels,\n): ContainerKekWireLevel[] | null {\n const levels: ContainerKekWireLevel[] = [];\n for (const kek of path.containerKeks) {\n if (!isCitedContainerKekLevel(kek)) {\n levels.push(kek);\n continue;\n }\n const held = heldLevels.get(kek.levelDigest);\n if (\n !held ||\n !sameHashes(held.containerManifestHistory, kek.containerManifestHistory)\n )\n return null;\n levels.push(structuredClone(held));\n }\n return levels;\n}\n\nfunction decodeKeyingPath(\n path: ContainerKeyingPathWireResponse,\n resolve: (hash: string) => Bundle,\n heldLevels: HeldLevels,\n): ContainerKeyingPathResponse | null {\n const levels = fillKekLevels(path, heldLevels);\n if (!levels) return null;\n return {\n ...path,\n path: path.path.map(resolve),\n containerKeks: levels.map((kek) => ({\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(resolve),\n })),\n };\n}\n\n// The held bundles each decoded projection took from the caller's citations\n// rather than from the response, exactly as the caller held them.\nconst heldBundlesByProjection = new WeakMap<object, readonly ServedBundle[]>();\n\n/**\n * The held bundles a decoded projection filled omissions from. A verifier\n * that refuses such a projection drops exactly those held rows, so the next\n * read fetches them from the server instead of failing the same way.\n */\nexport function heldBundlesUsedBy(projection: object): readonly ServedBundle[] {\n return heldBundlesByProjection.get(projection) ?? [];\n}\n\n// Decoded projections a verifier refused after they took held bundles: a\n// cache must not hand one out again.\nconst rejectedProjections = new WeakSet<object>();\n// A projection derived from a decoded one (a path of a document projection,\n// a sliced path) answers for the decoded projection it came from.\nconst decodedOrigins = new WeakMap<object, object>();\n\n/**\n * Carries a decoded projection's held bundles to a projection built from it,\n * so a refusal of the derived one drops those bundles and refuses the decoded\n * projection a cache holds.\n */\nexport function deriveDecodedProjection<T extends object>(\n from: object,\n to: T,\n): T {\n const held = heldBundlesByProjection.get(from);\n if (held) {\n // Only the held bundles this projection still carries: verifying it\n // vouches for those and no others.\n const carried = manifestHashesIn(to);\n const kept = held.filter((bundle) => carried.has(bundle.manifestHash));\n if (kept.length > 0) heldBundlesByProjection.set(to, kept);\n }\n decodedOrigins.set(to, decodedOrigins.get(from) ?? from);\n return to;\n}\n\nfunction manifestHashesIn(value: unknown, found = new Set<string>()) {\n if (Array.isArray(value)) {\n for (const item of value) manifestHashesIn(item, found);\n } else if (typeof value === \"object\" && value !== null) {\n for (const [key, child] of Object.entries(value)) {\n if (key === \"manifestHash\" && typeof child === \"string\") found.add(child);\n else manifestHashesIn(child, found);\n }\n }\n return found;\n}\n\n// The exact held bytes refused projections took: any other projection\n// rebuilt from the same bytes is refused with them.\nconst rejectedHeldBytes = new Set<string>();\nconst MAX_REJECTED_HELD_BUNDLES = 64;\n\n/** Marks a decoded projection refused, so no cache serves it again. */\nexport function rejectDecodedProjection(projection: object): void {\n rejectedProjections.add(projection);\n const origin = decodedOrigins.get(projection);\n if (origin) rejectedProjections.add(origin);\n for (const bundle of heldBundlesUsedBy(projection)) {\n rejectedHeldBytes.add(JSON.stringify(bundle));\n // Bounded: the oldest refusals go first. Their projections stay refused\n // by identity; only rebuilds from the same bytes are no longer caught.\n if (rejectedHeldBytes.size > MAX_REJECTED_HELD_BUNDLES) {\n const [oldest] = rejectedHeldBytes;\n if (oldest !== undefined) rejectedHeldBytes.delete(oldest);\n }\n }\n}\n\n/**\n * Whether a projection, or the decoded projection it was derived from, was\n * refused: refusing any projection built from a decoded one refuses every\n * other projection built from it too.\n */\n/**\n * A projection whose held bundles just verified: those bytes are good again\n * for every other projection rebuilt from them.\n */\nexport function acceptDecodedProjection(projection: object): void {\n if (rejectedHeldBytes.size === 0) return;\n for (const bundle of heldBundlesUsedBy(projection))\n rejectedHeldBytes.delete(JSON.stringify(bundle));\n}\n\nexport function isRejectedDecodedProjection(projection: unknown): boolean {\n if (typeof projection !== \"object\" || projection === null) return false;\n const origin = decodedOrigins.get(projection);\n return (\n rejectedProjections.has(projection) ||\n (origin !== undefined && rejectedProjections.has(origin)) ||\n (rejectedHeldBytes.size > 0 &&\n heldBundlesUsedBy(projection).some((bundle) =>\n rejectedHeldBytes.has(JSON.stringify(bundle)),\n ))\n );\n}\n\nfunction withHeldBundles<T extends object>(\n projection: T,\n omittedBundles: readonly string[],\n held: ReadonlyMap<string, ServedBundle>,\n): T {\n const used = omittedBundles.flatMap((hash) => {\n const bundle = held.get(hash);\n return bundle ? [bundle] : [];\n });\n if (used.length > 0) heldBundlesByProjection.set(projection, used);\n return projection;\n}\n\n/**\n * Null for any wire inconsistency or an omission `held` (bundles) or\n * `heldLevels` (KEK levels by digest) cannot fill; the caller treats either\n * as a shape failure.\n */\nexport function decodeContainerWriterProjection(\n value: unknown,\n held: ReadonlyMap<string, ServedBundle> = new Map(),\n heldLevels: HeldLevels = new Map(),\n): ContainerWriterProjectionResponse | null {\n const parsed = ContainerWriterProjectionWireResponseSchema.safeParse(value);\n if (!parsed.success) {\n return null;\n }\n const { bundles, omittedBundles, ...projection } = parsed.data;\n const resolve = bundleResolver(bundles, omittedBundles, held);\n const path = resolve\n ? decodeKeyingPath(projection, resolve, heldLevels)\n : null;\n return path\n ? withHeldBundles({ ...projection, ...path }, omittedBundles, held)\n : null;\n}\n\n/** See {@link decodeContainerWriterProjection}. */\nexport function decodeDocumentWriterProjection(\n value: unknown,\n held: ReadonlyMap<string, ServedBundle> = new Map(),\n heldLevels: HeldLevels = new Map(),\n): DocumentWriterProjectionResponse | null {\n const parsed = DocumentWriterProjectionWireResponseSchema.safeParse(value);\n if (!parsed.success) {\n return null;\n }\n const { bundles, omittedBundles, ...projection } = parsed.data;\n const resolve = bundleResolver(bundles, omittedBundles, held);\n if (!resolve) {\n return null;\n }\n const authorizingContainerPaths: ContainerKeyingPathResponse[] = [];\n for (const path of projection.authorizingContainerPaths) {\n const decoded = decodeKeyingPath(path, resolve, heldLevels);\n if (!decoded) return null;\n authorizingContainerPaths.push(decoded);\n }\n const [firstPath, ...otherPaths] = authorizingContainerPaths;\n if (!firstPath) return null;\n return withHeldBundles(\n {\n ...projection,\n authorizingContainerPaths: [firstPath, ...otherPaths],\n documentContainerManifestHistory:\n projection.documentContainerManifestHistory.map(resolve),\n documentManifest: resolve(projection.documentManifest),\n documentManifestContainerPaths:\n projection.documentManifestContainerPaths.map((path) =>\n path.map(resolve),\n ),\n documentManifestHistory: projection.documentManifestHistory.map(resolve),\n },\n omittedBundles,\n held,\n );\n}\n"]}
1
+ {"version":3,"file":"writerProjectionWire.js","sourceRoot":"","sources":["writerProjectionWire.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,kCAAkC,EAElC,4BAA4B,GAC7B,MAAM,SAAS,CAAC;AACjB,OAAO,EAOL,2CAA2C,EAC3C,wBAAwB,GACzB,MAAM,aAAa,CAAC;AACrB,OAAO,EAGL,0CAA0C,GAC3C,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,8BAA8B,EAC9B,8BAA8B,GAE/B,MAAM,sBAAsB,CAAC;AAM9B;;;;;;GAMG;AACH,SAAS,eAAe,CAAC,KAA0B;IACjD,MAAM,MAAM,GAAG,IAAI,GAAG,EAAwB,CAAC;IAC/C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,OAAO;QACL,IAAI,CAAC,MAAc;YACjB,MAAM,IAAI,GAAG,MAAM,CAAC,YAAY,CAAC;YACjC,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;gBAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;iBAClC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC;gBACxB,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,4BAA4B,CAAC,MAAM,CAAC,CAAC,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,uEAAuE;QACvE,OAAO,EAAE,GAAiC,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC;QACvE,OAAO,EAAE,GAAa,EAAE,CAAC,CAAC,GAAG,OAAO,CAAC;KACtC,CAAC;AACJ,CAAC;AAED,mEAAmE;AACnE,MAAM,UAAU,qBAAqB,CACnC,GAAyB;IAEzB,OAAO;QACL,GAAG,GAAG;QACN,wBAAwB,EAAE,GAAG,CAAC,wBAAwB,CAAC,GAAG,CACxD,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC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,OAAO,IAAI,CAAC;IAC5B,OAAO,eAAe,CACpB;QACE,GAAG,UAAU;QACb,cAAc;QACd,yBAAyB,EAAE,CAAC,SAAS,EAAE,GAAG,UAAU,CAAC;QACrD,gCAAgC,EAC9B,UAAU,CAAC,gCAAgC,CAAC,GAAG,CAAC,OAAO,CAAC;QAC1D,gBAAgB,EAAE,OAAO,CAAC,UAAU,CAAC,gBAAgB,CAAC;QACtD,8BAA8B,EAC5B,UAAU,CAAC,8BAA8B,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACrD,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAClB;QACH,uBAAuB,EAAE,UAAU,CAAC,uBAAuB,CAAC,GAAG,CAAC,OAAO,CAAC;KACzE,EACD,cAAc,EACd,IAAI,CACL,CAAC;AACJ,CAAC","sourcesContent":["import {\n type AccessManifestBundleWireResponse,\n completeServedAccessManifestBundle,\n type ServedAccessManifestBundleWireResponse,\n toServedAccessManifestBundle,\n} from \"../util\";\nimport {\n type ContainerKekResponse,\n type ContainerKekWireLevel,\n type ContainerKeyingPathResponse,\n type ContainerKeyingPathWireResponse,\n type ContainerWriterProjectionResponse,\n type ContainerWriterProjectionWireResponse,\n ContainerWriterProjectionWireResponseSchema,\n isCitedContainerKekLevel,\n} from \"./container\";\nimport {\n type DocumentWriterProjectionResponse,\n type DocumentWriterProjectionWireResponse,\n DocumentWriterProjectionWireResponseSchema,\n} from \"./documentMutation\";\nimport {\n decodeProjectionPolicyEvidence,\n encodeProjectionPolicyEvidence,\n type HeldDirectoryPayloads,\n} from \"./policyEvidenceWire\";\n\ntype Bundle = AccessManifestBundleWireResponse;\ntype ServedBundle = ServedAccessManifestBundleWireResponse;\ntype HeldLevels = ReadonlyMap<string, ContainerKekWireLevel>;\n\n/**\n * Collects each distinct manifest once. Every slot a server fills for one\n * hash comes from the same stored row, and the client verifies the bundle it\n * receives wherever that hash is cited, so the first occurrence stands. A\n * hash the request declared known is cited but not served. A served bundle's\n * state leaves out what its own signed bytes name; decoding fills it back.\n */\nfunction bundleCitations(known: ReadonlySet<string>) {\n const byHash = new Map<string, ServedBundle>();\n const omitted = new Set<string>();\n return {\n cite(bundle: Bundle): string {\n const hash = bundle.manifestHash;\n if (known.has(hash)) omitted.add(hash);\n else if (!byHash.has(hash))\n byHash.set(hash, toServedAccessManifestBundle(bundle));\n return hash;\n },\n // fromEntries defines own data properties, even for a \"__proto__\" key.\n bundles: (): Record<string, ServedBundle> => Object.fromEntries(byHash),\n omitted: (): string[] => [...omitted],\n };\n}\n\n/** A KEK level's wire form: its manifest history cited by hash. */\nexport function containerKekWireLevel(\n kek: ContainerKekResponse,\n): ContainerKekWireLevel {\n return {\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(\n (bundle) => bundle.manifestHash,\n ),\n };\n}\n\n/**\n * The digest a request declared for a KEK level it holds, or null when the\n * level travels in full. The caller derives it from the level's own served\n * bytes, so a level is omitted only when the held copy is exactly these.\n */\nexport type HeldKekLevelDigest = (kek: ContainerKekResponse) => string | null;\n\nfunction encodeKeyingPath(\n path: ContainerKeyingPathResponse,\n cite: (bundle: Bundle) => string,\n heldLevel: HeldKekLevelDigest,\n): ContainerKeyingPathWireResponse {\n return {\n ...path,\n path: path.path.map(cite),\n containerKeks: path.containerKeks.map((kek) => {\n const level = {\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(cite),\n };\n const levelDigest = heldLevel(kek);\n return levelDigest === null\n ? level\n : {\n levelDigest,\n containerManifestHistory: level.containerManifestHistory,\n };\n }),\n };\n}\n\nconst noHeldLevels: HeldKekLevelDigest = () => null;\n\n/**\n * Call only after authorization and stored-evidence verification. `known`\n * holds the request's manifest hints; only hashes this projection cites are\n * omitted. `heldLevel` names each KEK level the request holds exactly, and\n * `heldDirectories` the organization states whose directory payloads it\n * holds.\n */\nexport function encodeContainerWriterProjection(\n projection: ContainerWriterProjectionResponse,\n known: ReadonlySet<string> = new Set(),\n heldLevel: HeldKekLevelDigest = noHeldLevels,\n heldDirectories: ReadonlySet<string> = new Set(),\n): ContainerWriterProjectionWireResponse {\n const citations = bundleCitations(known);\n const encoded = encodeKeyingPath(projection, citations.cite, heldLevel);\n return {\n ...projection,\n ...encoded,\n policyEvidence: encodeProjectionPolicyEvidence(\n projection.policyEvidence,\n heldDirectories,\n ),\n bundles: citations.bundles(),\n omittedBundles: citations.omitted(),\n };\n}\n\n/** See {@link encodeContainerWriterProjection}. */\nexport function encodeDocumentWriterProjection(\n projection: DocumentWriterProjectionResponse,\n known: ReadonlySet<string> = new Set(),\n heldLevel: HeldKekLevelDigest = noHeldLevels,\n heldDirectories: ReadonlySet<string> = new Set(),\n): DocumentWriterProjectionWireResponse {\n const { cite, bundles, omitted } = bundleCitations(known);\n const authorizingContainerPaths = projection.authorizingContainerPaths.map(\n (path) => encodeKeyingPath(path, cite, heldLevel),\n );\n return {\n ...projection,\n policyEvidence: encodeProjectionPolicyEvidence(\n projection.policyEvidence,\n heldDirectories,\n ),\n authorizingContainerPaths,\n documentContainerManifestHistory:\n projection.documentContainerManifestHistory.map(cite),\n documentManifest: cite(projection.documentManifest),\n documentManifestContainerPaths:\n projection.documentManifestContainerPaths.map((path) => path.map(cite)),\n documentManifestHistory: projection.documentManifestHistory.map(cite),\n bundles: bundles(),\n omittedBundles: omitted(),\n };\n}\n\n/**\n * Served bundles plus the exact held bytes for each omitted hash. An omission\n * the caller cannot fill from `held` (which carries only what its request\n * cited) makes the response unusable. Each bundle's state gets back the\n * fields its own signed bytes name. Each cited position receives its own\n * copy, as when every slot carried its own JSON.\n */\nfunction bundleResolver(\n bundles: Record<string, ServedBundle>,\n omittedBundles: readonly string[],\n held: ReadonlyMap<string, ServedBundle>,\n): ((hash: string) => Bundle) | null {\n const byHash = new Map(\n Object.entries(bundles).map(\n ([hash, bundle]) =>\n [hash, completeServedAccessManifestBundle(bundle)] as const,\n ),\n );\n for (const hash of omittedBundles) {\n const bundle = held.get(hash);\n if (bundle?.manifestHash !== hash) return null;\n byHash.set(hash, completeServedAccessManifestBundle(bundle));\n }\n return (hash: string): Bundle => {\n const bundle = byHash.get(hash);\n if (!bundle) {\n throw new Error(`manifest ${hash} is cited without a bundle`);\n }\n return structuredClone(bundle);\n };\n}\n\nfunction sameHashes(left: readonly string[], right: readonly string[]) {\n return (\n left.length === right.length &&\n left.every((hash, index) => hash === right[index])\n );\n}\n\n/**\n * Each cited KEK level becomes its own copy of the exact held level this\n * request declared under that digest. A digest the request did not cite, or\n * a held level whose manifest citations differ from the stub's, makes the\n * path unusable: the caller refetches in full.\n */\nfunction fillKekLevels(\n path: ContainerKeyingPathWireResponse,\n heldLevels: HeldLevels,\n): ContainerKekWireLevel[] | null {\n const levels: ContainerKekWireLevel[] = [];\n for (const kek of path.containerKeks) {\n if (!isCitedContainerKekLevel(kek)) {\n levels.push(kek);\n continue;\n }\n const held = heldLevels.get(kek.levelDigest);\n if (\n !held ||\n !sameHashes(held.containerManifestHistory, kek.containerManifestHistory)\n )\n return null;\n levels.push(structuredClone(held));\n }\n return levels;\n}\n\nfunction decodeKeyingPath(\n path: ContainerKeyingPathWireResponse,\n resolve: (hash: string) => Bundle,\n heldLevels: HeldLevels,\n): ContainerKeyingPathResponse | null {\n const levels = fillKekLevels(path, heldLevels);\n if (!levels) return null;\n return {\n ...path,\n path: path.path.map(resolve),\n containerKeks: levels.map((kek) => ({\n ...kek,\n containerManifestHistory: kek.containerManifestHistory.map(resolve),\n })),\n };\n}\n\n// The held bundles each decoded projection took from the caller's citations\n// rather than from the response, exactly as the caller held them.\nconst heldBundlesByProjection = new WeakMap<object, readonly ServedBundle[]>();\n\n/**\n * The held bundles a decoded projection filled omissions from. A verifier\n * that refuses such a projection drops exactly those held rows, so the next\n * read fetches them from the server instead of failing the same way.\n */\nexport function heldBundlesUsedBy(projection: object): readonly ServedBundle[] {\n return heldBundlesByProjection.get(projection) ?? [];\n}\n\n// Decoded projections a verifier refused after they took held bundles: a\n// cache must not hand one out again.\nconst rejectedProjections = new WeakSet<object>();\n// A projection derived from a decoded one (a path of a document projection,\n// a sliced path) answers for the decoded projection it came from.\nconst decodedOrigins = new WeakMap<object, object>();\n\n/**\n * Carries a decoded projection's held bundles to a projection built from it,\n * so a refusal of the derived one drops those bundles and refuses the decoded\n * projection a cache holds.\n */\nexport function deriveDecodedProjection<T extends object>(\n from: object,\n to: T,\n): T {\n const held = heldBundlesByProjection.get(from);\n if (held) {\n // Only the held bundles this projection still carries: verifying it\n // vouches for those and no others.\n const carried = manifestHashesIn(to);\n const kept = held.filter((bundle) => carried.has(bundle.manifestHash));\n if (kept.length > 0) heldBundlesByProjection.set(to, kept);\n }\n decodedOrigins.set(to, decodedOrigins.get(from) ?? from);\n return to;\n}\n\nfunction manifestHashesIn(value: unknown, found = new Set<string>()) {\n if (Array.isArray(value)) {\n for (const item of value) manifestHashesIn(item, found);\n } else if (typeof value === \"object\" && value !== null) {\n for (const [key, child] of Object.entries(value)) {\n if (key === \"manifestHash\" && typeof child === \"string\") found.add(child);\n else manifestHashesIn(child, found);\n }\n }\n return found;\n}\n\n// The exact held bytes refused projections took: any other projection\n// rebuilt from the same bytes is refused with them.\nconst rejectedHeldBytes = new Set<string>();\nconst MAX_REJECTED_HELD_BUNDLES = 64;\n\n/** Marks a decoded projection refused, so no cache serves it again. */\nexport function rejectDecodedProjection(projection: object): void {\n rejectedProjections.add(projection);\n const origin = decodedOrigins.get(projection);\n if (origin) rejectedProjections.add(origin);\n for (const bundle of heldBundlesUsedBy(projection)) {\n rejectedHeldBytes.add(JSON.stringify(bundle));\n // Bounded: the oldest refusals go first. Their projections stay refused\n // by identity; only rebuilds from the same bytes are no longer caught.\n if (rejectedHeldBytes.size > MAX_REJECTED_HELD_BUNDLES) {\n const [oldest] = rejectedHeldBytes;\n if (oldest !== undefined) rejectedHeldBytes.delete(oldest);\n }\n }\n}\n\n/**\n * Whether a projection, or the decoded projection it was derived from, was\n * refused: refusing any projection built from a decoded one refuses every\n * other projection built from it too.\n */\n/**\n * A projection whose held bundles just verified: those bytes are good again\n * for every other projection rebuilt from them.\n */\nexport function acceptDecodedProjection(projection: object): void {\n if (rejectedHeldBytes.size === 0) return;\n for (const bundle of heldBundlesUsedBy(projection))\n rejectedHeldBytes.delete(JSON.stringify(bundle));\n}\n\nexport function isRejectedDecodedProjection(projection: unknown): boolean {\n if (typeof projection !== \"object\" || projection === null) return false;\n const origin = decodedOrigins.get(projection);\n return (\n rejectedProjections.has(projection) ||\n (origin !== undefined && rejectedProjections.has(origin)) ||\n (rejectedHeldBytes.size > 0 &&\n heldBundlesUsedBy(projection).some((bundle) =>\n rejectedHeldBytes.has(JSON.stringify(bundle)),\n ))\n );\n}\n\nfunction withHeldBundles<T extends object>(\n projection: T,\n omittedBundles: readonly string[],\n held: ReadonlyMap<string, ServedBundle>,\n): T {\n const used = omittedBundles.flatMap((hash) => {\n const bundle = held.get(hash);\n return bundle ? [bundle] : [];\n });\n if (used.length > 0) heldBundlesByProjection.set(projection, used);\n return projection;\n}\n\n/**\n * Null for any wire inconsistency or an omission `held` (bundles),\n * `heldLevels` (KEK levels by digest) or `heldDirectories` (directory\n * payloads by organization state hash) cannot fill; the caller treats either\n * as a shape failure.\n */\nexport function decodeContainerWriterProjection(\n value: unknown,\n held: ReadonlyMap<string, ServedBundle> = new Map(),\n heldLevels: HeldLevels = new Map(),\n heldDirectories: HeldDirectoryPayloads = new Map(),\n): ContainerWriterProjectionResponse | null {\n const parsed = ContainerWriterProjectionWireResponseSchema.safeParse(value);\n if (!parsed.success) {\n return null;\n }\n const { bundles, omittedBundles, ...projection } = parsed.data;\n const policyEvidence = decodeProjectionPolicyEvidence(\n projection.policyEvidence,\n heldDirectories,\n );\n const resolve = bundleResolver(bundles, omittedBundles, held);\n const path = resolve\n ? decodeKeyingPath(projection, resolve, heldLevels)\n : null;\n return path && policyEvidence\n ? withHeldBundles(\n { ...projection, ...path, policyEvidence },\n omittedBundles,\n held,\n )\n : null;\n}\n\n/** See {@link decodeContainerWriterProjection}. */\nexport function decodeDocumentWriterProjection(\n value: unknown,\n held: ReadonlyMap<string, ServedBundle> = new Map(),\n heldLevels: HeldLevels = new Map(),\n heldDirectories: HeldDirectoryPayloads = new Map(),\n): DocumentWriterProjectionResponse | null {\n const parsed = DocumentWriterProjectionWireResponseSchema.safeParse(value);\n if (!parsed.success) {\n return null;\n }\n const { bundles, omittedBundles, ...projection } = parsed.data;\n const policyEvidence = decodeProjectionPolicyEvidence(\n projection.policyEvidence,\n heldDirectories,\n );\n const resolve = bundleResolver(bundles, omittedBundles, held);\n if (!resolve || !policyEvidence) {\n return null;\n }\n const authorizingContainerPaths: ContainerKeyingPathResponse[] = [];\n for (const path of projection.authorizingContainerPaths) {\n const decoded = decodeKeyingPath(path, resolve, heldLevels);\n if (!decoded) return null;\n authorizingContainerPaths.push(decoded);\n }\n const [firstPath, ...otherPaths] = authorizingContainerPaths;\n if (!firstPath) return null;\n return withHeldBundles(\n {\n ...projection,\n policyEvidence,\n authorizingContainerPaths: [firstPath, ...otherPaths],\n documentContainerManifestHistory:\n projection.documentContainerManifestHistory.map(resolve),\n documentManifest: resolve(projection.documentManifest),\n documentManifestContainerPaths:\n projection.documentManifestContainerPaths.map((path) =>\n path.map(resolve),\n ),\n documentManifestHistory: projection.documentManifestHistory.map(resolve),\n },\n omittedBundles,\n held,\n );\n}\n"]}
@@ -5,7 +5,7 @@ export { CONTAINER_KEK_LOG_PAGE_LIMIT, CONTAINER_KEK_LOG_PRINCIPAL_SCOPE_LIMIT,
5
5
  export { MAX_CONTAINER_PATH_LENGTH } from "./containerLimits.js";
6
6
  export { MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS, MAX_DOCUMENT_SYNC_AUTHORIZATION_PATHS, MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS, MAX_DOCUMENT_SYNC_OUTGOING_UPDATES, MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH, MAX_DOCUMENT_SYNC_REQUEST_BYTES, MAX_DOCUMENT_SYNC_RESPONSE_ENVELOPE_BYTES, MAX_DOCUMENT_SYNC_RESPONSE_PAGE_BYTES, MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES, MAX_DOCUMENT_SYNC_RESPONSE_UPDATE_PAGE_BYTES, } from "./documentSyncLimits.js";
7
7
  export { isSerializedKeyEnvelope, isSerializedKeyEnvelopeArray, type SerializedKeyEnvelope, } from "./keyEnvelope.js";
8
- export { formatKnownManifestHints, KNOWN_MANIFEST_HINT_LIMIT, type KnownManifestHints, KnownManifestsHeadersSchema, parseKnownManifestHints, } from "./knownManifestWire.js";
8
+ export { formatKnownManifestHints, KNOWN_DIRECTORY_HINT_LIMIT, KNOWN_MANIFEST_HINT_LIMIT, type KnownManifestHints, KnownManifestsHeadersSchema, parseKnownManifestHints, } from "./knownManifestWire.js";
9
9
  export { isOrganizationLeaveRequest, type OrganizationLeaveRequest, type OrganizationLeaveRequestMembersHead, OrganizationLeaveRequestSchema, } from "./organizationLeaveRequest.js";
10
10
  export { isOrganizationReplacementAuthorization, type OrganizationReplacementAuthorization, OrganizationReplacementAuthorizationSchema, } from "./organizationReplacement.js";
11
11
  export { PRINCIPAL_POLICY_HISTORY_PAGE_LIMIT, PRINCIPAL_POLICY_REPAIR_HEAD_LIMIT, } from "./principalHistoryWire.js";
@@ -5,7 +5,7 @@ export { CONTAINER_KEK_LOG_PAGE_LIMIT, CONTAINER_KEK_LOG_PRINCIPAL_SCOPE_LIMIT,
5
5
  export { MAX_CONTAINER_PATH_LENGTH } from "./containerLimits.js";
6
6
  export { MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS, MAX_DOCUMENT_SYNC_AUTHORIZATION_PATHS, MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS, MAX_DOCUMENT_SYNC_OUTGOING_UPDATES, MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH, MAX_DOCUMENT_SYNC_REQUEST_BYTES, MAX_DOCUMENT_SYNC_RESPONSE_ENVELOPE_BYTES, MAX_DOCUMENT_SYNC_RESPONSE_PAGE_BYTES, MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES, MAX_DOCUMENT_SYNC_RESPONSE_UPDATE_PAGE_BYTES, } from "./documentSyncLimits.js";
7
7
  export { isSerializedKeyEnvelope, isSerializedKeyEnvelopeArray, } from "./keyEnvelope.js";
8
- export { formatKnownManifestHints, KNOWN_MANIFEST_HINT_LIMIT, KnownManifestsHeadersSchema, parseKnownManifestHints, } from "./knownManifestWire.js";
8
+ export { formatKnownManifestHints, KNOWN_DIRECTORY_HINT_LIMIT, KNOWN_MANIFEST_HINT_LIMIT, KnownManifestsHeadersSchema, parseKnownManifestHints, } from "./knownManifestWire.js";
9
9
  export { isOrganizationLeaveRequest, OrganizationLeaveRequestSchema, } from "./organizationLeaveRequest.js";
10
10
  export { isOrganizationReplacementAuthorization, OrganizationReplacementAuthorizationSchema, } from "./organizationReplacement.js";
11
11
  export { PRINCIPAL_POLICY_HISTORY_PAGE_LIMIT, PRINCIPAL_POLICY_REPAIR_HEAD_LIMIT, } from "./principalHistoryWire.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,mCAAmC,EAGnC,sCAAsC,EACtC,8BAA8B,EAC9B,+BAA+B,EAC/B,0BAA0B,EAC1B,+BAA+B,EAC/B,kCAAkC,EAClC,uCAAuC,GACxC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,QAAQ,CAAC;AAChB,OAAO,EACL,wBAAwB,EACxB,8BAA8B,EAE9B,iCAAiC,EAEjC,6BAA6B,EAE7B,mCAAmC,EACnC,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,4BAA4B,EAC5B,uCAAuC,EACvC,mCAAmC,EACnC,mCAAmC,EACnC,+BAA+B,EAC/B,uBAAuB,EACvB,2BAA2B,EAC3B,6BAA6B,EAC7B,8CAA8C,EA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wB,CAAC;AAChC,OAAO,EACL,2BAA2B,EAC3B,mBAAmB,EACnB,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC","sourcesContent":["export {\n type AccessEventBundleWireResponse,\n AccessEventBundleWireResponseSchema,\n type AccessManifestBundleWire,\n type AccessManifestBundleWireResponse,\n AccessManifestBundleWireResponseSchema,\n AccessManifestBundleWireSchema,\n isAccessEventBundleWireResponse,\n isAccessManifestBundleWire,\n isAccessManifestBundleWireArray,\n isAccessManifestBundleWireResponse,\n isOptionalAccessManifestBundleWireArray,\n} from \"./accessManifestBundle\";\nexport {\n MAX_INITIATE_PART_UPLOADS,\n MAX_MULTIPART_BLOB_PART_BYTES,\n} from \"./blob\";\nexport {\n blobPartContentMd5Schema,\n MAX_MULTIPART_BLOB_PART_NUMBER,\n type MultipartBlobPartDescriptor,\n MultipartBlobPartDescriptorSchema,\n type MultipartBlobPartUpload,\n MultipartBlobPartUploadSchema,\n type MultipartBlobPartUploadSource,\n MultipartBlobPartUploadSourceSchema,\n signedBlobUrlExpirySchema,\n signedBlobUrlSchema,\n} from \"./blobTransferSchemas\";\nexport {\n CONTAINER_KEK_LOG_PAGE_LIMIT,\n CONTAINER_KEK_LOG_PRINCIPAL_SCOPE_LIMIT,\n CONTAINER_KEK_WRAPS_PER_EPOCH_LIMIT,\n ContainerKekKeyringWireRecordSchema,\n isContainerKekKeyringWireRecord,\n MAX_CONTAINER_KEY_EPOCH,\n MAX_INLINE_CONTAINER_REKEYS,\n MAX_ROTATION_CONTAINER_REKEYS,\n MAX_SEALED_CONTAINER_KEK_KEYRING_BASE64_LENGTH,\n SEALED_CONTAINER_KEK_KEYRING_AEAD_OVERHEAD_BYTES,\n SEALED_CONTAINER_KEK_KEYRING_ENTRY_BYTES,\n SEALED_CONTAINER_KEK_KEYRING_HEADER_BYTES,\n sealedContainerKekKeyringBytes,\n} from \"./containerKekKeyringWire\";\nexport { MAX_CONTAINER_PATH_LENGTH } from \"./containerLimits\";\nexport {\n MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS,\n MAX_DOCUMENT_SYNC_AUTHORIZATION_PATHS,\n MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS,\n MAX_DOCUMENT_SYNC_OUTGOING_UPDATES,\n MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH,\n MAX_DOCUMENT_SYNC_REQUEST_BYTES,\n MAX_DOCUMENT_SYNC_RESPONSE_ENVELOPE_BYTES,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_BYTES,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES,\n MAX_DOCUMENT_SYNC_RESPONSE_UPDATE_PAGE_BYTES,\n} from \"./documentSyncLimits\";\nexport {\n isSerializedKeyEnvelope,\n isSerializedKeyEnvelopeArray,\n type SerializedKeyEnvelope,\n} from \"./keyEnvelope\";\nexport {\n formatKnownManifestHints,\n KNOWN_MANIFEST_HINT_LIMIT,\n type KnownManifestHints,\n KnownManifestsHeadersSchema,\n parseKnownManifestHints,\n} from \"./knownManifestWire\";\nexport {\n isOrganizationLeaveRequest,\n type OrganizationLeaveRequest,\n type OrganizationLeaveRequestMembersHead,\n OrganizationLeaveRequestSchema,\n} from \"./organizationLeaveRequest\";\nexport {\n isOrganizationReplacementAuthorization,\n type OrganizationReplacementAuthorization,\n OrganizationReplacementAuthorizationSchema,\n} from \"./organizationReplacement\";\nexport {\n PRINCIPAL_POLICY_HISTORY_PAGE_LIMIT,\n PRINCIPAL_POLICY_REPAIR_HEAD_LIMIT,\n} from \"./principalHistoryWire\";\nexport {\n hasArrayProperty,\n hasBooleanProperty,\n hasNonEmptyStringProperty,\n hasNullableNumberProperty,\n hasNullableStringProperty,\n hasNumberProperty,\n hasObjectProperty,\n hasOptionalStringProperty,\n hasPositiveIntegerProperty,\n hasPropertyValue,\n hasStringProperty,\n isNonEmptyStringArray,\n isOptionalRecordArray,\n isOptionalRecordArrayArray,\n isRecordArray,\n isRecordArrayArray,\n isStringArray,\n} from \"./properties\";\nexport {\n AUTH_CHALLENGE_HEX_LENGTH,\n base64Length,\n canonicalBase64Pattern,\n isAuthChallengeHexString,\n isCanonicalBase64OfLength,\n isSha256HexString,\n ML_DSA87_PUBLIC_KEY_BYTES,\n ML_DSA87_SIGNATURE_BYTES,\n ML_KEM1024_PUBLIC_KEY_BYTES,\n SHA256_HEX_LENGTH,\n} from \"./protocol\";\nexport {\n completeServedAccessManifestBundle,\n isServedAccessManifestBundleWireResponse,\n type ServedAccessManifestBundleWireResponse,\n ServedAccessManifestBundleWireResponseSchema,\n type ServedManifestState,\n toServedAccessManifestBundle,\n} from \"./servedManifestBundle\";\nexport {\n CANONICAL_SIGNED_AT_PATTERN,\n isCanonicalSignedAt,\n MAX_SIGNED_AT_YEAR,\n MIN_SIGNED_AT_YEAR,\n SIGNED_AT_CONTRACT,\n} from \"./signedAt\";\nexport { isUuidV4String } from \"./uuid\";\nexport { isWalLsnString, parseWalLsn } from \"./walLsn\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,mCAAmC,EAGnC,sCAAsC,EACtC,8BAA8B,EAC9B,+BAA+B,EAC/B,0BAA0B,EAC1B,+BAA+B,EAC/B,kCAAkC,EAClC,uCAAuC,GACxC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,QAAQ,CAAC;AAChB,OAAO,EACL,wBAAwB,EACxB,8BAA8B,EAE9B,iCAAiC,EAEjC,6BAA6B,EAE7B,mCAAmC,EACnC,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,4BAA4B,EAC5B,uCAAuC,EACvC,mCAAmC,EACnC,mCAAmC,E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AAC;AACpB,OAAO,EACL,kCAAkC,EAClC,wCAAwC,EAExC,4CAA4C,EAE5C,4BAA4B,GAC7B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,2BAA2B,EAC3B,mBAAmB,EACnB,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC","sourcesContent":["export {\n type AccessEventBundleWireResponse,\n AccessEventBundleWireResponseSchema,\n type AccessManifestBundleWire,\n type AccessManifestBundleWireResponse,\n AccessManifestBundleWireResponseSchema,\n AccessManifestBundleWireSchema,\n isAccessEventBundleWireResponse,\n isAccessManifestBundleWire,\n isAccessManifestBundleWireArray,\n isAccessManifestBundleWireResponse,\n isOptionalAccessManifestBundleWireArray,\n} from \"./accessManifestBundle\";\nexport {\n MAX_INITIATE_PART_UPLOADS,\n MAX_MULTIPART_BLOB_PART_BYTES,\n} from \"./blob\";\nexport {\n blobPartContentMd5Schema,\n MAX_MULTIPART_BLOB_PART_NUMBER,\n type MultipartBlobPartDescriptor,\n MultipartBlobPartDescriptorSchema,\n type MultipartBlobPartUpload,\n MultipartBlobPartUploadSchema,\n type MultipartBlobPartUploadSource,\n MultipartBlobPartUploadSourceSchema,\n signedBlobUrlExpirySchema,\n signedBlobUrlSchema,\n} from \"./blobTransferSchemas\";\nexport {\n CONTAINER_KEK_LOG_PAGE_LIMIT,\n CONTAINER_KEK_LOG_PRINCIPAL_SCOPE_LIMIT,\n CONTAINER_KEK_WRAPS_PER_EPOCH_LIMIT,\n ContainerKekKeyringWireRecordSchema,\n isContainerKekKeyringWireRecord,\n MAX_CONTAINER_KEY_EPOCH,\n MAX_INLINE_CONTAINER_REKEYS,\n MAX_ROTATION_CONTAINER_REKEYS,\n MAX_SEALED_CONTAINER_KEK_KEYRING_BASE64_LENGTH,\n SEALED_CONTAINER_KEK_KEYRING_AEAD_OVERHEAD_BYTES,\n SEALED_CONTAINER_KEK_KEYRING_ENTRY_BYTES,\n SEALED_CONTAINER_KEK_KEYRING_HEADER_BYTES,\n sealedContainerKekKeyringBytes,\n} from \"./containerKekKeyringWire\";\nexport { MAX_CONTAINER_PATH_LENGTH } from \"./containerLimits\";\nexport {\n MAX_DOCUMENT_SYNC_AUTHORIZATION_PATH_REFS,\n MAX_DOCUMENT_SYNC_AUTHORIZATION_PATHS,\n MAX_DOCUMENT_SYNC_CONTENT_KEY_TARGETS,\n MAX_DOCUMENT_SYNC_OUTGOING_UPDATES,\n MAX_DOCUMENT_SYNC_PULL_CURSOR_LENGTH,\n MAX_DOCUMENT_SYNC_REQUEST_BYTES,\n MAX_DOCUMENT_SYNC_RESPONSE_ENVELOPE_BYTES,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_BYTES,\n MAX_DOCUMENT_SYNC_RESPONSE_PAGE_UPDATES,\n MAX_DOCUMENT_SYNC_RESPONSE_UPDATE_PAGE_BYTES,\n} from \"./documentSyncLimits\";\nexport {\n isSerializedKeyEnvelope,\n isSerializedKeyEnvelopeArray,\n type SerializedKeyEnvelope,\n} from \"./keyEnvelope\";\nexport {\n formatKnownManifestHints,\n KNOWN_DIRECTORY_HINT_LIMIT,\n KNOWN_MANIFEST_HINT_LIMIT,\n type KnownManifestHints,\n KnownManifestsHeadersSchema,\n parseKnownManifestHints,\n} from \"./knownManifestWire\";\nexport {\n isOrganizationLeaveRequest,\n type OrganizationLeaveRequest,\n type OrganizationLeaveRequestMembersHead,\n OrganizationLeaveRequestSchema,\n} from \"./organizationLeaveRequest\";\nexport {\n isOrganizationReplacementAuthorization,\n type OrganizationReplacementAuthorization,\n OrganizationReplacementAuthorizationSchema,\n} from \"./organizationReplacement\";\nexport {\n PRINCIPAL_POLICY_HISTORY_PAGE_LIMIT,\n PRINCIPAL_POLICY_REPAIR_HEAD_LIMIT,\n} from \"./principalHistoryWire\";\nexport {\n hasArrayProperty,\n hasBooleanProperty,\n hasNonEmptyStringProperty,\n hasNullableNumberProperty,\n hasNullableStringProperty,\n hasNumberProperty,\n hasObjectProperty,\n hasOptionalStringProperty,\n hasPositiveIntegerProperty,\n hasPropertyValue,\n hasStringProperty,\n isNonEmptyStringArray,\n isOptionalRecordArray,\n isOptionalRecordArrayArray,\n isRecordArray,\n isRecordArrayArray,\n isStringArray,\n} from \"./properties\";\nexport {\n AUTH_CHALLENGE_HEX_LENGTH,\n base64Length,\n canonicalBase64Pattern,\n isAuthChallengeHexString,\n isCanonicalBase64OfLength,\n isSha256HexString,\n ML_DSA87_PUBLIC_KEY_BYTES,\n ML_DSA87_SIGNATURE_BYTES,\n ML_KEM1024_PUBLIC_KEY_BYTES,\n SHA256_HEX_LENGTH,\n} from \"./protocol\";\nexport {\n completeServedAccessManifestBundle,\n isServedAccessManifestBundleWireResponse,\n type ServedAccessManifestBundleWireResponse,\n ServedAccessManifestBundleWireResponseSchema,\n type ServedManifestState,\n toServedAccessManifestBundle,\n} from \"./servedManifestBundle\";\nexport {\n CANONICAL_SIGNED_AT_PATTERN,\n isCanonicalSignedAt,\n MAX_SIGNED_AT_YEAR,\n MIN_SIGNED_AT_YEAR,\n SIGNED_AT_CONTRACT,\n} from \"./signedAt\";\nexport { isUuidV4String } from \"./uuid\";\nexport { isWalLsnString, parseWalLsn } from \"./walLsn\";\n"]}
@@ -4,17 +4,23 @@ import { z } from "zod";
4
4
  * receives: an uncited manifest or KEK level always travels.
5
5
  */
6
6
  export declare const KNOWN_MANIFEST_HINT_LIMIT = 48;
7
+ /**
8
+ * Organization directory states one request may declare held, beside its
9
+ * manifest and KEK-level hints.
10
+ */
11
+ export declare const KNOWN_DIRECTORY_HINT_LIMIT = 8;
7
12
  /** The typed digests one request declares held. */
8
13
  export interface KnownManifestHints {
9
14
  readonly manifests: readonly string[];
10
15
  readonly kekLevels: readonly string[];
16
+ readonly directories: readonly string[];
11
17
  }
12
18
  /**
13
- * Null unless the header is 1–48 unique typed entries, each `m:` or `k:`
14
- * followed by a lowercase SHA-256 hex digest.
19
+ * Null unless the header is unique typed entries, at most 48 `m:` or `k:`
20
+ * and at most 8 `d:`, each followed by a lowercase SHA-256 hex digest.
15
21
  */
16
22
  export declare function parseKnownManifestHints(value: string): KnownManifestHints | null;
17
- /** The header value for `hints`; callers keep the total within the limit. */
23
+ /** The header value for `hints`; callers keep each kind within its limit. */
18
24
  export declare function formatKnownManifestHints(hints: KnownManifestHints): string;
19
25
  export declare const KnownManifestsHeadersSchema: z.ZodObject<{
20
26
  "x-known-manifests": z.ZodOptional<z.ZodString>;
@@ -7,23 +7,33 @@ import { isSha256HexString, SHA256_HEX_LENGTH } from "./protocol.js";
7
7
  * receives: an uncited manifest or KEK level always travels.
8
8
  */
9
9
  export const KNOWN_MANIFEST_HINT_LIMIT = 48;
10
- /** `m:` cites a manifest bundle by hash, `k:` a KEK level by digest. */
10
+ /**
11
+ * Organization directory states one request may declare held, beside its
12
+ * manifest and KEK-level hints.
13
+ */
14
+ export const KNOWN_DIRECTORY_HINT_LIMIT = 8;
15
+ /**
16
+ * `m:` cites a manifest bundle by hash, `k:` a KEK level by digest, `d:` an
17
+ * organization directory payload by its signed state's hash.
18
+ */
11
19
  const MANIFEST_HINT_PREFIX = "m:";
12
20
  const KEK_LEVEL_HINT_PREFIX = "k:";
13
- const KNOWN_MANIFEST_HINT_CHARACTERS = KNOWN_MANIFEST_HINT_LIMIT *
21
+ const DIRECTORY_HINT_PREFIX = "d:";
22
+ const KNOWN_MANIFEST_HINT_CHARACTERS = (KNOWN_MANIFEST_HINT_LIMIT + KNOWN_DIRECTORY_HINT_LIMIT) *
14
23
  (MANIFEST_HINT_PREFIX.length + SHA256_HEX_LENGTH + 1) -
15
24
  1;
16
25
  /**
17
- * Null unless the header is 1–48 unique typed entries, each `m:` or `k:`
18
- * followed by a lowercase SHA-256 hex digest.
26
+ * Null unless the header is unique typed entries, at most 48 `m:` or `k:`
27
+ * and at most 8 `d:`, each followed by a lowercase SHA-256 hex digest.
19
28
  */
20
29
  export function parseKnownManifestHints(value) {
21
30
  const entries = value.split(",");
22
- if (entries.length > KNOWN_MANIFEST_HINT_LIMIT ||
31
+ if (entries.length > KNOWN_MANIFEST_HINT_LIMIT + KNOWN_DIRECTORY_HINT_LIMIT ||
23
32
  new Set(entries).size !== entries.length)
24
33
  return null;
25
34
  const manifests = [];
26
35
  const kekLevels = [];
36
+ const directories = [];
27
37
  for (const entry of entries) {
28
38
  const digest = entry.slice(MANIFEST_HINT_PREFIX.length);
29
39
  if (!isSha256HexString(digest))
@@ -32,22 +42,28 @@ export function parseKnownManifestHints(value) {
32
42
  manifests.push(digest);
33
43
  else if (entry.startsWith(KEK_LEVEL_HINT_PREFIX))
34
44
  kekLevels.push(digest);
45
+ else if (entry.startsWith(DIRECTORY_HINT_PREFIX))
46
+ directories.push(digest);
35
47
  else
36
48
  return null;
37
49
  }
38
- return { manifests, kekLevels };
50
+ if (manifests.length + kekLevels.length > KNOWN_MANIFEST_HINT_LIMIT ||
51
+ directories.length > KNOWN_DIRECTORY_HINT_LIMIT)
52
+ return null;
53
+ return { manifests, kekLevels, directories };
39
54
  }
40
- /** The header value for `hints`; callers keep the total within the limit. */
55
+ /** The header value for `hints`; callers keep each kind within its limit. */
41
56
  export function formatKnownManifestHints(hints) {
42
57
  return [
43
58
  ...hints.kekLevels.map((digest) => `${KEK_LEVEL_HINT_PREFIX}${digest}`),
44
59
  ...hints.manifests.map((hash) => `${MANIFEST_HINT_PREFIX}${hash}`),
60
+ ...hints.directories.map((hash) => `${DIRECTORY_HINT_PREFIX}${hash}`),
45
61
  ].join(",");
46
62
  }
47
63
  const hintHeader = registerJsonSchemaFragment(z.string().max(KNOWN_MANIFEST_HINT_CHARACTERS), {
48
64
  type: "string",
49
65
  maxLength: KNOWN_MANIFEST_HINT_CHARACTERS,
50
- description: `Comma-separated typed digests the device holds verified: m:<manifest hash> for an access-manifest bundle, k:<level digest> for a container KEK level; at most ${KNOWN_MANIFEST_HINT_LIMIT}, unique`,
66
+ description: `Comma-separated typed digests the device holds verified: m:<manifest hash> for an access-manifest bundle, k:<level digest> for a container KEK level (at most ${KNOWN_MANIFEST_HINT_LIMIT} of these), d:<organization state hash> for that state's directory payload (at most ${KNOWN_DIRECTORY_HINT_LIMIT}); unique`,
51
67
  });
52
68
  export const KnownManifestsHeadersSchema = z.object({
53
69
  "x-known-manifests": registerJsonSchemaRuntimeRefinements(hintHeader.refine((value) => parseKnownManifestHints(value) !== null), [knownManifestsHeaderRefinement]).optional(),
@@ -1 +1 @@
1
- {"version":3,"file":"knownManifestWire.js","sourceRoot":"","sources":["knownManifestWire.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,0BAA0B,EAC1B,oCAAoC,GACrC,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAElE;;;GAGG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAC5C,wEAAwE;AACxE,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAClC,MAAM,qBAAqB,GAAG,IAAI,CAAC;AACnC,MAAM,8BAA8B,GAClC,yBAAyB;IACvB,CAAC,oBAAoB,CAAC,MAAM,GAAG,iBAAiB,GAAG,CAAC,CAAC;IACvD,CAAC,CAAC;AAQJ;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CACrC,KAAa;IAEb,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACjC,IACE,OAAO,CAAC,MAAM,GAAG,yBAAyB;QAC1C,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,MAAM;QAExC,OAAO,IAAI,CAAC;IACd,MAAM,SAAS,GAAa,EAAE,CAAC;IAC/B,MAAM,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uBAAuB,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,EACrE,CAAC,8BAA8B,CAAC,CACjC,CAAC,QAAQ,EAAE;CACb,CAAC,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n registerJsonSchemaFragment,\n registerJsonSchemaRuntimeRefinements,\n} from \"../jsonSchema\";\nimport { knownManifestsHeaderRefinement } from \"../knownManifestsRefinements\";\nimport { isSha256HexString, SHA256_HEX_LENGTH } from \"./protocol\";\n\n/**\n * Hints bound the omission a request can ask for, never the history a reader\n * receives: an uncited manifest or KEK level always travels.\n */\nexport const KNOWN_MANIFEST_HINT_LIMIT = 48;\n/** `m:` cites a manifest bundle by hash, `k:` a KEK level by digest. */\nconst MANIFEST_HINT_PREFIX = \"m:\";\nconst KEK_LEVEL_HINT_PREFIX = \"k:\";\nconst KNOWN_MANIFEST_HINT_CHARACTERS =\n KNOWN_MANIFEST_HINT_LIMIT *\n (MANIFEST_HINT_PREFIX.length + SHA256_HEX_LENGTH + 1) -\n 1;\n\n/** The typed digests one request declares held. */\nexport interface KnownManifestHints {\n readonly manifests: readonly string[];\n readonly kekLevels: readonly string[];\n}\n\n/**\n * Null unless the header is 1–48 unique typed entries, each `m:` or `k:`\n * followed by a lowercase SHA-256 hex digest.\n */\nexport function parseKnownManifestHints(\n value: string,\n): KnownManifestHints | null {\n const entries = value.split(\",\");\n if (\n entries.length > KNOWN_MANIFEST_HINT_LIMIT ||\n new Set(entries).size !== entries.length\n )\n return null;\n const manifests: string[] = [];\n const kekLevels: string[] = [];\n for (const entry of entries) {\n const digest = entry.slice(MANIFEST_HINT_PREFIX.length);\n if (!isSha256HexString(digest)) return null;\n if (entry.startsWith(MANIFEST_HINT_PREFIX)) manifests.push(digest);\n else if (entry.startsWith(KEK_LEVEL_HINT_PREFIX)) kekLevels.push(digest);\n else return null;\n }\n return { manifests, kekLevels };\n}\n\n/** The header value for `hints`; callers keep the total within the limit. */\nexport function formatKnownManifestHints(hints: KnownManifestHints): string {\n return [\n ...hints.kekLevels.map((digest) => `${KEK_LEVEL_HINT_PREFIX}${digest}`),\n ...hints.manifests.map((hash) => `${MANIFEST_HINT_PREFIX}${hash}`),\n ].join(\",\");\n}\n\nconst hintHeader = registerJsonSchemaFragment(\n z.string().max(KNOWN_MANIFEST_HINT_CHARACTERS),\n {\n type: \"string\",\n maxLength: KNOWN_MANIFEST_HINT_CHARACTERS,\n description: `Comma-separated typed digests the device holds verified: m:<manifest hash> for an access-manifest bundle, k:<level digest> for a container KEK level; at most ${KNOWN_MANIFEST_HINT_LIMIT}, unique`,\n },\n);\n\nexport const KnownManifestsHeadersSchema = z.object({\n \"x-known-manifests\": registerJsonSchemaRuntimeRefinements(\n hintHeader.refine((value) => parseKnownManifestHints(value) !== null),\n [knownManifestsHeaderRefinement],\n ).optional(),\n});\n"]}
1
+ {"version":3,"file":"knownManifestWire.js","sourceRoot":"","sources":["knownManifestWire.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,0BAA0B,EAC1B,oCAAoC,GACrC,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAElE;;;GAGG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAC5C;;;GAGG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AAC5C;;;GAGG;AACH,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAClC,MAAM,qBAAqB,GAAG,IAAI,CAAC;AACnC,MAAM,qBAAqB,GAAG,IAAI,CAAC;AACnC,MAAM,8BAA8B,GAClC,CAAC,yBAAyB,GAAG,0BAA0B,CAAC;IACtD,CAAC,oBAAoB,CAAC,MAAM,GAAG,iBAAiB,GAAG,CAAC,CAAC;IACvD,CAAC,CAAC;AASJ;;;GAGG;AACH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EAAE,CAAC,GAAG,qBAAqB,GAAG,MAAM,EAAE,CAAC;QACvE,GAAG,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,oBAAoB,GAAG,IAAI,EAAE,CAAC;QAClE,GAAG,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,qBAAqB,GAAG,IAAI,EAAE,CAAC;KACtE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;AAED,MAAM,UAAU,GAAG,0BAA0B,CAC3C,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,8BAA8B,CAAC,EAC9C;IACE,IAAI,EAAE,QAAQ;IACd,SAAS,EAAE,8BAA8B;IACzC,WAAW,EAAE,iKAAiK,yBAAyB,uFAAuF,0BAA0B,WAAW;CACpU,CACF,CAAC;AAEF,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,CAAC,MAAM,CAAC;IAClD,mBAAmB,EAAE,oCAAoC,CACvD,UAAU,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,uBAAuB,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,EACrE,CAAC,8BAA8B,CAAC,CACjC,CAAC,QAAQ,EAAE;CACb,CAAC,CAAC","sourcesContent":["import { z } from \"zod\";\nimport {\n registerJsonSchemaFragment,\n registerJsonSchemaRuntimeRefinements,\n} from \"../jsonSchema\";\nimport { knownManifestsHeaderRefinement } from \"../knownManifestsRefinements\";\nimport { isSha256HexString, SHA256_HEX_LENGTH } from \"./protocol\";\n\n/**\n * Hints bound the omission a request can ask for, never the history a reader\n * receives: an uncited manifest or KEK level always travels.\n */\nexport const KNOWN_MANIFEST_HINT_LIMIT = 48;\n/**\n * Organization directory states one request may declare held, beside its\n * manifest and KEK-level hints.\n */\nexport const KNOWN_DIRECTORY_HINT_LIMIT = 8;\n/**\n * `m:` cites a manifest bundle by hash, `k:` a KEK level by digest, `d:` an\n * organization directory payload by its signed state's hash.\n */\nconst MANIFEST_HINT_PREFIX = \"m:\";\nconst KEK_LEVEL_HINT_PREFIX = \"k:\";\nconst DIRECTORY_HINT_PREFIX = \"d:\";\nconst KNOWN_MANIFEST_HINT_CHARACTERS =\n (KNOWN_MANIFEST_HINT_LIMIT + KNOWN_DIRECTORY_HINT_LIMIT) *\n (MANIFEST_HINT_PREFIX.length + SHA256_HEX_LENGTH + 1) -\n 1;\n\n/** The typed digests one request declares held. */\nexport interface KnownManifestHints {\n readonly manifests: readonly string[];\n readonly kekLevels: readonly string[];\n readonly directories: readonly string[];\n}\n\n/**\n * Null unless the header is unique typed entries, at most 48 `m:` or `k:`\n * and at most 8 `d:`, each followed by a lowercase SHA-256 hex digest.\n */\nexport function parseKnownManifestHints(\n value: string,\n): KnownManifestHints | null {\n const entries = value.split(\",\");\n if (\n entries.length > KNOWN_MANIFEST_HINT_LIMIT + KNOWN_DIRECTORY_HINT_LIMIT ||\n new Set(entries).size !== entries.length\n )\n return null;\n const manifests: string[] = [];\n const kekLevels: string[] = [];\n const directories: string[] = [];\n for (const entry of entries) {\n const digest = entry.slice(MANIFEST_HINT_PREFIX.length);\n if (!isSha256HexString(digest)) return null;\n if (entry.startsWith(MANIFEST_HINT_PREFIX)) manifests.push(digest);\n else if (entry.startsWith(KEK_LEVEL_HINT_PREFIX)) kekLevels.push(digest);\n else if (entry.startsWith(DIRECTORY_HINT_PREFIX)) directories.push(digest);\n else return null;\n }\n if (\n manifests.length + kekLevels.length > KNOWN_MANIFEST_HINT_LIMIT ||\n directories.length > KNOWN_DIRECTORY_HINT_LIMIT\n )\n return null;\n return { manifests, kekLevels, directories };\n}\n\n/** The header value for `hints`; callers keep each kind within its limit. */\nexport function formatKnownManifestHints(hints: KnownManifestHints): string {\n return [\n ...hints.kekLevels.map((digest) => `${KEK_LEVEL_HINT_PREFIX}${digest}`),\n ...hints.manifests.map((hash) => `${MANIFEST_HINT_PREFIX}${hash}`),\n ...hints.directories.map((hash) => `${DIRECTORY_HINT_PREFIX}${hash}`),\n ].join(\",\");\n}\n\nconst hintHeader = registerJsonSchemaFragment(\n z.string().max(KNOWN_MANIFEST_HINT_CHARACTERS),\n {\n type: \"string\",\n maxLength: KNOWN_MANIFEST_HINT_CHARACTERS,\n description: `Comma-separated typed digests the device holds verified: m:<manifest hash> for an access-manifest bundle, k:<level digest> for a container KEK level (at most ${KNOWN_MANIFEST_HINT_LIMIT} of these), d:<organization state hash> for that state's directory payload (at most ${KNOWN_DIRECTORY_HINT_LIMIT}); unique`,\n },\n);\n\nexport const KnownManifestsHeadersSchema = z.object({\n \"x-known-manifests\": registerJsonSchemaRuntimeRefinements(\n hintHeader.refine((value) => parseKnownManifestHints(value) !== null),\n [knownManifestsHeaderRefinement],\n ).optional(),\n});\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.247",
3
+ "version": "0.1.249",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1,5 +1,7 @@
1
1
  import type { ContainerAccessManifestState, ReferencedPrincipalHead } from "../../../internal/crypto/index.js";
2
+ import type { ContainerShareCommittedReadModel } from "../../../data/containers/shared/types.js";
2
3
  import type { PrincipalPolicyCurrentEvidence } from "../../../data/principalContracts/principalPolicyEvidence.js";
4
+ import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
3
5
  import type { createRuntimeCurrentGroupShare, shareRemoteContainerWithGroup } from "../../organizations/groupShare/index.js";
4
6
  import type { PrincipalPolicyRuntime } from "../../principals/principalPolicyService.js";
5
7
  type GroupShare = typeof shareRemoteContainerWithGroup;
@@ -31,6 +33,13 @@ export type ContainerContentsCurrentGroupPolicyReader = <Result>(input: {
31
33
  * them.
32
34
  */
33
35
  export interface ContainerContentsOrganizationHost {
36
+ /** Sends a share's held read-model cursor and keeps the delta it carries. */
37
+ readonly committedReadModel: (scope: {
38
+ readonly domainScope: object;
39
+ readonly execSql: ExecSql;
40
+ readonly organizationId: string;
41
+ readonly userId: string;
42
+ }) => ContainerShareCommittedReadModel;
34
43
  /** Shares with a group on current evidence; `undefined` without private paged recovery. */
35
44
  readonly createCurrentGroupShare: (runtime: GroupShareRuntime) => GroupShare | undefined;
36
45
  /** Reads current group policy; `undefined` without private paged recovery. */
@@ -1 +1 @@
1
- {"version":3,"file":"organizationHost.js","sourceRoot":"","sources":["organizationHost.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ContainerAccessManifestState,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principalContracts/principalPolicyEvidence\";\nimport type {\n createRuntimeCurrentGroupShare,\n shareRemoteContainerWithGroup,\n} from \"../../organizations/groupShare\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\n\ntype GroupShare = typeof shareRemoteContainerWithGroup;\n\n/** What the group operations read from a container contents runtime. */\ntype GroupShareRuntime = Parameters<typeof createRuntimeCurrentGroupShare>[0];\n\n/** The verified current group a share or rewrap acts on. */\nexport interface ContainerContentsCurrentGroupPolicy {\n readonly policy: PrincipalPolicyCurrentEvidence;\n /** The group policy and its dependencies, as checkpointed for this read. */\n readonly checkpointPolicies: readonly PrincipalPolicyCurrentEvidence[];\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * Runs `work` on the group's current policy under a current principal\n * mutation lease, after the group's name and expected head are checked.\n */\nexport type ContainerContentsCurrentGroupPolicyReader = <Result>(\n input: {\n readonly expectedGroupHead?: ReferencedPrincipalHead | undefined;\n readonly expectedGroupName?: string | undefined;\n readonly groupId: string;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n },\n work: (current: ContainerContentsCurrentGroupPolicy) => Promise<Result>,\n) => Promise<Result>;\n\n/**\n * The Organization Read Models operations container contents runs. Group\n * shares, group metadata, and the organization directory belong to the\n * organization workflows, which sit above container contents; the composition\n * root binds their implementations here so container contents never imports\n * them.\n */\nexport interface ContainerContentsOrganizationHost {\n /** Shares with a group on current evidence; `undefined` without private paged recovery. */\n readonly createCurrentGroupShare: (\n runtime: GroupShareRuntime,\n ) => GroupShare | undefined;\n /** Reads current group policy; `undefined` without private paged recovery. */\n readonly createCurrentGroupPolicyReader: (\n runtime: GroupShareRuntime,\n ) => ContainerContentsCurrentGroupPolicyReader | undefined;\n /** Decrypts a group's name from the organization's signed metadata container. */\n readonly groupMetadataNameReader: (\n runtime: GroupShareRuntime,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n ) => NonNullable<Parameters<GroupShare>[0][\"readEncryptedName\"]>;\n /** Checks a metadata root destination against the current organization authority. */\n readonly verifyGroupMetadataAuthority: (input: {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly state: ContainerAccessManifestState;\n readonly organizationReference?: ReferencedPrincipalHead | undefined;\n readonly stillCurrent: () => boolean;\n }) => Promise<void>;\n /**\n * Runs `load` again once, after `evictRoot`, when the metadata root it read\n * was behind the signed directory; a root still behind is an incident.\n */\n readonly withMetadataRootReload: <Result>(\n load: (reread: boolean) => Promise<Result>,\n evictRoot: () => void,\n ) => Promise<Result>;\n}\n"]}
1
+ {"version":3,"file":"organizationHost.js","sourceRoot":"","sources":["organizationHost.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ContainerAccessManifestState,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ContainerShareCommittedReadModel } from \"../../../data/containers/shared/types\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principalContracts/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type {\n createRuntimeCurrentGroupShare,\n shareRemoteContainerWithGroup,\n} from \"../../organizations/groupShare\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\n\ntype GroupShare = typeof shareRemoteContainerWithGroup;\n\n/** What the group operations read from a container contents runtime. */\ntype GroupShareRuntime = Parameters<typeof createRuntimeCurrentGroupShare>[0];\n\n/** The verified current group a share or rewrap acts on. */\nexport interface ContainerContentsCurrentGroupPolicy {\n readonly policy: PrincipalPolicyCurrentEvidence;\n /** The group policy and its dependencies, as checkpointed for this read. */\n readonly checkpointPolicies: readonly PrincipalPolicyCurrentEvidence[];\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * Runs `work` on the group's current policy under a current principal\n * mutation lease, after the group's name and expected head are checked.\n */\nexport type ContainerContentsCurrentGroupPolicyReader = <Result>(\n input: {\n readonly expectedGroupHead?: ReferencedPrincipalHead | undefined;\n readonly expectedGroupName?: string | undefined;\n readonly groupId: string;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n },\n work: (current: ContainerContentsCurrentGroupPolicy) => Promise<Result>,\n) => Promise<Result>;\n\n/**\n * The Organization Read Models operations container contents runs. Group\n * shares, group metadata, and the organization directory belong to the\n * organization workflows, which sit above container contents; the composition\n * root binds their implementations here so container contents never imports\n * them.\n */\nexport interface ContainerContentsOrganizationHost {\n /** Sends a share's held read-model cursor and keeps the delta it carries. */\n readonly committedReadModel: (scope: {\n readonly domainScope: object;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly userId: string;\n }) => ContainerShareCommittedReadModel;\n /** Shares with a group on current evidence; `undefined` without private paged recovery. */\n readonly createCurrentGroupShare: (\n runtime: GroupShareRuntime,\n ) => GroupShare | undefined;\n /** Reads current group policy; `undefined` without private paged recovery. */\n readonly createCurrentGroupPolicyReader: (\n runtime: GroupShareRuntime,\n ) => ContainerContentsCurrentGroupPolicyReader | undefined;\n /** Decrypts a group's name from the organization's signed metadata container. */\n readonly groupMetadataNameReader: (\n runtime: GroupShareRuntime,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n ) => NonNullable<Parameters<GroupShare>[0][\"readEncryptedName\"]>;\n /** Checks a metadata root destination against the current organization authority. */\n readonly verifyGroupMetadataAuthority: (input: {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly state: ContainerAccessManifestState;\n readonly organizationReference?: ReferencedPrincipalHead | undefined;\n readonly stillCurrent: () => boolean;\n }) => Promise<void>;\n /**\n * Runs `load` again once, after `evictRoot`, when the metadata root it read\n * was behind the signed directory; a root still behind is an incident.\n */\n readonly withMetadataRootReload: <Result>(\n load: (reread: boolean) => Promise<Result>,\n evictRoot: () => void,\n ) => Promise<Result>;\n}\n"]}
@@ -57,6 +57,12 @@ export async function shareRemoteContainer(input) {
57
57
  const shared = await writer.containers.shareRemoteContainer({
58
58
  accessLevel: input.accessLevel,
59
59
  author: writer.author,
60
+ committedReadModel: input.runtime.organizations.committedReadModel({
61
+ domainScope: input.runtime.state.domainScope,
62
+ execSql: input.runtime.infra.execSql,
63
+ organizationId: writer.author.organizationId,
64
+ userId: writer.author.signerUserId,
65
+ }),
60
66
  containerId: input.containerId,
61
67
  previousProjection: input.previousProjection,
62
68
  recipientUserId: input.recipientUserId,
@@ -1 +1 @@
1
- {"version":3,"file":"remote.js","sourceRoot":"","sources":["remote.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAMrD,OAAO,EAAE,0BAA0B,EAAE,MAAM,kDAAkD,CAAC;AAE9F,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAClG,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAGL,wBAAwB,EACxB,iCAAiC,EACjC,uCAAuC,GACxC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAE9D,OAAO,EAEL,yCAAyC,GAC1C,MAAM,6BAA6B,CAAC;AASrC;;;;GAIG;AACH,SAAS,6BAA6B,CACpC,OAAiC,EACjC,SAIqB;IAErB,MAAM,MAAM,GAAG,2BAA2B,CAAC,OAAO,CAAC,CAAC;IACpD,MAAM,SAAS,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K,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAC1B,mEAAmE,KAAK,CAAC,OAAO,CAAC,WAAW,wBAAwB,cAAc,EAAE,CACrI,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type { ContainerAccessManifestState } from \"@tearleads/crypto\";\nimport { emptyVersionVector } from \"@tearleads/loro\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { isContainerNotFoundFailure } from \"../../../data/containers/shared/mutationFailures\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type AppliedContainerMove,\n type ContainerMutationCollaborators,\n ContainerMutationService,\n signedContainerMetadataDocumentId,\n signedContainerReferencedPrincipalHeads,\n} from \"../../containers\";\nimport { resolveDocumentCreateAuthor } from \"../../documents\";\n\nimport {\n type ContainerAlreadyCommitted,\n createRemoteContainerWithMetadataDocument,\n} from \"./create/createWithMetadata\";\nimport type {\n ContainerCreateIntentSyncState,\n ContainerWorkflowRuntime,\n CreatedRemoteContainerState,\n RemoteContainer,\n SharedRemoteContainerState,\n} from \"./types\";\n\n/**\n * Resolve the author and the runtime snapshot's container mutation\n * collaborators, with a service bound to them, logging a skip for the given\n * operation when the writer context is unavailable.\n */\nfunction resolveContainerWriterContext(\n runtime: ContainerWorkflowRuntime,\n operation:\n | \"container create\"\n | \"container group share\"\n | \"container move\"\n | \"container share\",\n) {\n const author = resolveDocumentCreateAuthor(runtime);\n const secretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!author || !secretKey) {\n runtime.util.log(\n `Container contents: skipped ${operation} because the writer context is unavailable.`,\n );\n return null;\n }\n\n const collaborators: ContainerMutationCollaborators<\n ContainerWorkflowRuntime[\"apiClient\"]\n > = {\n api: runtime.apiClient,\n encapsulationSecretKey: secretKey,\n execSql: runtime.infra.execSql,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n };\n return {\n author,\n collaborators,\n containers: new ContainerMutationService(collaborators),\n };\n}\n\nexport async function createRemoteContainer(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n containerId: string;\n metadataSeedUpdate?: Parameters<\n typeof createRemoteContainerWithMetadataDocument\n >[0][\"metadataSeedUpdate\"];\n parentContainerId: string;\n parentProjection?: ContainerWriterProjectionResponse | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedRemoteContainerState | ContainerAlreadyCommitted | null> {\n return createRemoteContainerWithMetadataDocument(input);\n}\n\n/** An acknowledged mutation: the server's commitments and the signed plan. */\ninterface AcknowledgedContainerMutation {\n readonly plan: { readonly state: ContainerAccessManifestState };\n readonly response: ContainerMutationResponse;\n}\n\nfunction sharedRemoteContainerStateFromMutation(\n previousProjection: ContainerWriterProjectionResponse,\n { plan, response }: AcknowledgedContainerMutation,\n): SharedRemoteContainerState {\n if (\n response.containerId !== previousProjection.containerId ||\n response.organizationId !== previousProjection.organizationId\n )\n throw new Error(\"Container mutation response projection mismatch\");\n return {\n accessManifestHash: response.manifestHead.manifestHash,\n accessEpoch: response.manifestHead.epoch,\n createdAt: response.createdAt,\n metadataDocumentId: signedContainerMetadataDocumentId(plan),\n referencedPrincipalHeads: signedContainerReferencedPrincipalHeads(plan),\n updatedAt: response.updatedAt,\n // The next read obtains the post-commit proof. A failed read cannot undo\n // acknowledgement of this successful mutation.\n writerProjection: null,\n };\n}\n\nexport async function shareRemoteContainer(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n previousProjection: ContainerWriterProjectionResponse;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container share\",\n );\n if (!writer) {\n return null;\n }\n const shared = await writer.containers.shareRemoteContainer({\n accessLevel: input.accessLevel,\n author: writer.author,\n containerId: input.containerId,\n previousProjection: input.previousProjection,\n recipientUserId: input.recipientUserId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared,\n );\n}\n\nexport async function shareRemoteContainerWithGroup(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n expectedGroupName?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container group share\",\n );\n if (!writer) {\n return null;\n }\n const { author, collaborators } = writer;\n\n const shareWithGroup = input.runtime.organizations.createCurrentGroupShare(\n input.runtime,\n );\n if (!shareWithGroup)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n const shared = await shareWithGroup({\n reportSecurityIncident: collaborators.reportSecurityIncident,\n accessLevel: input.accessLevel,\n apiClient: collaborators.api,\n author,\n containerId: input.containerId,\n execSql: collaborators.execSql,\n expectedGroupName: input.expectedGroupName ?? null,\n readEncryptedName: (bundle) =>\n input.runtime.organizations.groupMetadataNameReader(\n input.runtime,\n author.organizationId,\n input.stillCurrent,\n )(bundle),\n knownContainerKeks: input.knownContainerKeks,\n previousProjection: input.previousProjection,\n recipientGroupId: input.recipientGroupId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveTrustedUserIdentity: collaborators.resolveTrustedUserIdentity,\n signingKeyPair: input.runtime.crypto.signingKeyPair,\n stillCurrent: input.stillCurrent,\n targetSecretKey: collaborators.encapsulationSecretKey,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared,\n );\n}\n\n/**\n * Replays a queued move. `applied` carries the verified head when the server\n * already holds the container under the destination, so nothing is posted.\n */\nexport async function moveRemoteContainer(input: {\n containerId: string;\n onAccepted?: (() => void) | undefined;\n parentContainerId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n { applied: AppliedContainerMove } | { moved: RemoteContainer } | null\n> {\n const writer = resolveContainerWriterContext(input.runtime, \"container move\");\n if (!writer) {\n return null;\n }\n const replayed = await writer.containers.replayRemoteContainerMove({\n author: writer.author,\n containerId: input.containerId,\n destinationParentContainerId: input.parentContainerId,\n onAccepted: input.onAccepted,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (!replayed || \"applied\" in replayed) {\n return replayed;\n }\n\n const { plan, response } = replayed;\n return {\n moved: {\n createdAt: response.createdAt,\n effectiveAccessLevel: \"admin\",\n id: response.containerId,\n organizationId: response.organizationId,\n parentId: response.parentId,\n metadataDocumentId: signedContainerMetadataDocumentId(plan),\n metadataAccessEpoch: response.manifestHead.epoch,\n metadataAccessStateHash: response.manifestHead.manifestHash,\n metadataReferencedPrincipals:\n signedContainerReferencedPrincipalHeads(plan),\n // A move says nothing about the metadata document's version.\n metadataVersionVector: emptyVersionVector(),\n updatedAt: response.updatedAt,\n },\n };\n}\n\nexport async function deleteRemoteContainer(input: {\n containerId: string;\n organizationId: string;\n requiredAncestorId?: string | undefined;\n runtime: ContainerWorkflowRuntime;\n}): Promise<{ deletedAt: string } | null> {\n const deleteResult = await input.runtime.apiClient.deleteContainerResult(\n input.containerId,\n {\n expectedPaymentRequiredOrganizationId: input.organizationId,\n reportErrors: false,\n requiredAncestorId: input.requiredAncestorId,\n },\n );\n if (!deleteResult.ok && !isContainerNotFoundFailure(deleteResult)) {\n deleteResult.report();\n return null;\n }\n\n if (!deleteResult.ok) {\n // A 404 proves this immutable id is permanently absent, but it does not\n // carry the server deletion time. A maximal fence prevents an older\n // in-flight listing page from resurrecting it.\n return { deletedAt: \"9999-12-31T23:59:59.999Z\" };\n }\n\n return { deletedAt: deleteResult.data.deletedAt };\n}\n\n/** Best-effort delete of a remote container whose local folder is gone. */\nexport async function discardOrphanedRemoteContainer(input: {\n created: CreatedRemoteContainerState;\n isCurrent: () => boolean;\n state: Pick<ContainerCreateIntentSyncState, \"runtime\">;\n}): Promise<void> {\n if (!input.isCurrent()) {\n return;\n }\n const discardFailure = await deleteRemoteContainer({\n containerId: input.created.containerId,\n organizationId: input.created.organizationId,\n runtime: input.state.runtime,\n }).then(\n (deleted) => (deleted ? null : \"the server rejected the delete\"),\n (error: unknown) => errorMessage(error),\n );\n if (input.isCurrent() && discardFailure !== null) {\n input.state.runtime.util.log(\n `Container contents: failed to discard orphaned remote container ${input.created.containerId} after local delete: ${discardFailure}`,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"remote.js","sourceRoot":"","sources":["remote.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAMrD,OAAO,EAAE,0BAA0B,EAAE,MAAM,kDAAkD,CAAC;AAE9F,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAClG,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAGL,wBAAwB,EACxB,iCAAiC,EACjC,uCAAuC,GACxC,MAAM,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D;IACC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QACvB,OAAO;IACT,CAAC;IACD,MAAM,cAAc,GAAG,MAAM,qBAAqB,CAAC;QACjD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,WAAW;QACtC,cAAc,EAAE,KAAK,CAAC,OAAO,CAAC,cAAc;QAC5C,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO;KAC7B,CAAC,CAAC,IAAI,CACL,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,gCAAgC,CAAC,EAChE,CAAC,KAAc,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,CACxC,CAAC;IACF,IAAI,KAAK,CAAC,SAAS,EAAE,IAAI,cAAc,KAAK,IAAI,EAAE,CAAC;QACjD,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAC1B,mEAAmE,KAAK,CAAC,OAAO,CAAC,WAAW,wBAAwB,cAAc,EAAE,CACrI,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type { ContainerAccessManifestState } from \"@tearleads/crypto\";\nimport { emptyVersionVector } from \"@tearleads/loro\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { isContainerNotFoundFailure } from \"../../../data/containers/shared/mutationFailures\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type AppliedContainerMove,\n type ContainerMutationCollaborators,\n ContainerMutationService,\n signedContainerMetadataDocumentId,\n signedContainerReferencedPrincipalHeads,\n} from \"../../containers\";\nimport { resolveDocumentCreateAuthor } from \"../../documents\";\n\nimport {\n type ContainerAlreadyCommitted,\n createRemoteContainerWithMetadataDocument,\n} from \"./create/createWithMetadata\";\nimport type {\n ContainerCreateIntentSyncState,\n ContainerWorkflowRuntime,\n CreatedRemoteContainerState,\n RemoteContainer,\n SharedRemoteContainerState,\n} from \"./types\";\n\n/**\n * Resolve the author and the runtime snapshot's container mutation\n * collaborators, with a service bound to them, logging a skip for the given\n * operation when the writer context is unavailable.\n */\nfunction resolveContainerWriterContext(\n runtime: ContainerWorkflowRuntime,\n operation:\n | \"container create\"\n | \"container group share\"\n | \"container move\"\n | \"container share\",\n) {\n const author = resolveDocumentCreateAuthor(runtime);\n const secretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!author || !secretKey) {\n runtime.util.log(\n `Container contents: skipped ${operation} because the writer context is unavailable.`,\n );\n return null;\n }\n\n const collaborators: ContainerMutationCollaborators<\n ContainerWorkflowRuntime[\"apiClient\"]\n > = {\n api: runtime.apiClient,\n encapsulationSecretKey: secretKey,\n execSql: runtime.infra.execSql,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n };\n return {\n author,\n collaborators,\n containers: new ContainerMutationService(collaborators),\n };\n}\n\nexport async function createRemoteContainer(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n containerId: string;\n metadataSeedUpdate?: Parameters<\n typeof createRemoteContainerWithMetadataDocument\n >[0][\"metadataSeedUpdate\"];\n parentContainerId: string;\n parentProjection?: ContainerWriterProjectionResponse | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedRemoteContainerState | ContainerAlreadyCommitted | null> {\n return createRemoteContainerWithMetadataDocument(input);\n}\n\n/** An acknowledged mutation: the server's commitments and the signed plan. */\ninterface AcknowledgedContainerMutation {\n readonly plan: { readonly state: ContainerAccessManifestState };\n readonly response: ContainerMutationResponse;\n}\n\nfunction sharedRemoteContainerStateFromMutation(\n previousProjection: ContainerWriterProjectionResponse,\n { plan, response }: AcknowledgedContainerMutation,\n): SharedRemoteContainerState {\n if (\n response.containerId !== previousProjection.containerId ||\n response.organizationId !== previousProjection.organizationId\n )\n throw new Error(\"Container mutation response projection mismatch\");\n return {\n accessManifestHash: response.manifestHead.manifestHash,\n accessEpoch: response.manifestHead.epoch,\n createdAt: response.createdAt,\n metadataDocumentId: signedContainerMetadataDocumentId(plan),\n referencedPrincipalHeads: signedContainerReferencedPrincipalHeads(plan),\n updatedAt: response.updatedAt,\n // The next read obtains the post-commit proof. A failed read cannot undo\n // acknowledgement of this successful mutation.\n writerProjection: null,\n };\n}\n\nexport async function shareRemoteContainer(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n previousProjection: ContainerWriterProjectionResponse;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container share\",\n );\n if (!writer) {\n return null;\n }\n const shared = await writer.containers.shareRemoteContainer({\n accessLevel: input.accessLevel,\n author: writer.author,\n committedReadModel: input.runtime.organizations.committedReadModel({\n domainScope: input.runtime.state.domainScope,\n execSql: input.runtime.infra.execSql,\n organizationId: writer.author.organizationId,\n userId: writer.author.signerUserId,\n }),\n containerId: input.containerId,\n previousProjection: input.previousProjection,\n recipientUserId: input.recipientUserId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared,\n );\n}\n\nexport async function shareRemoteContainerWithGroup(input: {\n accessLevel: \"read\" | \"write\" | \"admin\";\n containerId: string;\n expectedGroupName?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedRemoteContainerState | null> {\n const writer = resolveContainerWriterContext(\n input.runtime,\n \"container group share\",\n );\n if (!writer) {\n return null;\n }\n const { author, collaborators } = writer;\n\n const shareWithGroup = input.runtime.organizations.createCurrentGroupShare(\n input.runtime,\n );\n if (!shareWithGroup)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n const shared = await shareWithGroup({\n reportSecurityIncident: collaborators.reportSecurityIncident,\n accessLevel: input.accessLevel,\n apiClient: collaborators.api,\n author,\n containerId: input.containerId,\n execSql: collaborators.execSql,\n expectedGroupName: input.expectedGroupName ?? null,\n readEncryptedName: (bundle) =>\n input.runtime.organizations.groupMetadataNameReader(\n input.runtime,\n author.organizationId,\n input.stillCurrent,\n )(bundle),\n knownContainerKeks: input.knownContainerKeks,\n previousProjection: input.previousProjection,\n recipientGroupId: input.recipientGroupId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n resolveTrustedUserIdentity: collaborators.resolveTrustedUserIdentity,\n signingKeyPair: input.runtime.crypto.signingKeyPair,\n stillCurrent: input.stillCurrent,\n targetSecretKey: collaborators.encapsulationSecretKey,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (!shared) {\n return null;\n }\n\n return sharedRemoteContainerStateFromMutation(\n input.previousProjection,\n shared,\n );\n}\n\n/**\n * Replays a queued move. `applied` carries the verified head when the server\n * already holds the container under the destination, so nothing is posted.\n */\nexport async function moveRemoteContainer(input: {\n containerId: string;\n onAccepted?: (() => void) | undefined;\n parentContainerId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n { applied: AppliedContainerMove } | { moved: RemoteContainer } | null\n> {\n const writer = resolveContainerWriterContext(input.runtime, \"container move\");\n if (!writer) {\n return null;\n }\n const replayed = await writer.containers.replayRemoteContainerMove({\n author: writer.author,\n containerId: input.containerId,\n destinationParentContainerId: input.parentContainerId,\n onAccepted: input.onAccepted,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (!replayed || \"applied\" in replayed) {\n return replayed;\n }\n\n const { plan, response } = replayed;\n return {\n moved: {\n createdAt: response.createdAt,\n effectiveAccessLevel: \"admin\",\n id: response.containerId,\n organizationId: response.organizationId,\n parentId: response.parentId,\n metadataDocumentId: signedContainerMetadataDocumentId(plan),\n metadataAccessEpoch: response.manifestHead.epoch,\n metadataAccessStateHash: response.manifestHead.manifestHash,\n metadataReferencedPrincipals:\n signedContainerReferencedPrincipalHeads(plan),\n // A move says nothing about the metadata document's version.\n metadataVersionVector: emptyVersionVector(),\n updatedAt: response.updatedAt,\n },\n };\n}\n\nexport async function deleteRemoteContainer(input: {\n containerId: string;\n organizationId: string;\n requiredAncestorId?: string | undefined;\n runtime: ContainerWorkflowRuntime;\n}): Promise<{ deletedAt: string } | null> {\n const deleteResult = await input.runtime.apiClient.deleteContainerResult(\n input.containerId,\n {\n expectedPaymentRequiredOrganizationId: input.organizationId,\n reportErrors: false,\n requiredAncestorId: input.requiredAncestorId,\n },\n );\n if (!deleteResult.ok && !isContainerNotFoundFailure(deleteResult)) {\n deleteResult.report();\n return null;\n }\n\n if (!deleteResult.ok) {\n // A 404 proves this immutable id is permanently absent, but it does not\n // carry the server deletion time. A maximal fence prevents an older\n // in-flight listing page from resurrecting it.\n return { deletedAt: \"9999-12-31T23:59:59.999Z\" };\n }\n\n return { deletedAt: deleteResult.data.deletedAt };\n}\n\n/** Best-effort delete of a remote container whose local folder is gone. */\nexport async function discardOrphanedRemoteContainer(input: {\n created: CreatedRemoteContainerState;\n isCurrent: () => boolean;\n state: Pick<ContainerCreateIntentSyncState, \"runtime\">;\n}): Promise<void> {\n if (!input.isCurrent()) {\n return;\n }\n const discardFailure = await deleteRemoteContainer({\n containerId: input.created.containerId,\n organizationId: input.created.organizationId,\n runtime: input.state.runtime,\n }).then(\n (deleted) => (deleted ? null : \"the server rejected the delete\"),\n (error: unknown) => errorMessage(error),\n );\n if (input.isCurrent() && discardFailure !== null) {\n input.state.runtime.util.log(\n `Container contents: failed to discard orphaned remote container ${input.created.containerId} after local delete: ${discardFailure}`,\n );\n }\n}\n"]}