@tearleads/client-sdk 0.1.249 → 0.1.250

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 (76) hide show
  1. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js +1 -4
  2. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js.map +1 -1
  3. package/data/persistence/principalPolicy/heldOrganizationDirectories.js +6 -1
  4. package/data/persistence/principalPolicy/heldOrganizationDirectories.js.map +1 -1
  5. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js +1 -1
  6. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js.map +1 -1
  7. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js +1 -5
  8. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js.map +1 -1
  9. package/data/principals/organizationGroupDirectoryRequest.js +0 -2
  10. package/data/principals/organizationGroupDirectoryRequest.js.map +1 -1
  11. package/data/principals/organizationPolicyRequest.js +0 -2
  12. package/data/principals/organizationPolicyRequest.js.map +1 -1
  13. package/data/principals/principalPolicyRequest.js +0 -2
  14. package/data/principals/principalPolicyRequest.js.map +1 -1
  15. package/internal/api-client/ApiClient.d.ts +0 -58
  16. package/internal/api-client/client/apiClientContext.d.ts +0 -30
  17. package/internal/api-client/client/documents.d.ts +0 -12
  18. package/internal/api-client/client/principalPolicies.d.ts +0 -18
  19. package/internal/api-client/client/writerProjections.d.ts +0 -12
  20. package/internal/api-client/heldDirectoryCitations.d.ts +8 -4
  21. package/internal/api-client/heldDirectoryCitations.js +6 -10
  22. package/internal/api-client/heldDirectoryCitations.js.map +1 -1
  23. package/internal/api-client/organizationPolicyHistory.d.ts +0 -6
  24. package/internal/api-client/principalPolicyRequests.d.ts +0 -18
  25. package/internal/api-client/verifiedManifestCitations.js +3 -3
  26. package/internal/api-client/verifiedManifestCitations.js.map +1 -1
  27. package/internal/crypto/index.d.ts +1 -1
  28. package/internal/crypto/index.js.map +1 -1
  29. package/internal/crypto/keying/principalPolicyPayload.js +2 -12
  30. package/internal/crypto/keying/principalPolicyPayload.js.map +1 -1
  31. package/internal/crypto/keying/principalPolicyTypes.d.ts +5 -6
  32. package/internal/crypto/keying/principalPolicyTypes.js.map +1 -1
  33. package/internal/crypto/principalState.d.ts +1 -1
  34. package/internal/crypto/principalState.js.map +1 -1
  35. package/internal/crypto/principalStateTypes.d.ts +0 -1
  36. package/internal/crypto/principalStateTypes.js.map +1 -1
  37. package/internal/validators/operation/auth.d.ts +0 -24
  38. package/internal/validators/operation/documentMutations.d.ts +0 -48
  39. package/internal/validators/operation/organizationPolicyHistory.d.ts +0 -24
  40. package/internal/validators/operation/organizations.d.ts +0 -48
  41. package/internal/validators/operation/principals.d.ts +0 -56
  42. package/internal/validators/operation/writerProjections.d.ts +0 -48
  43. package/internal/validators/request/organization.d.ts +0 -32
  44. package/internal/validators/request/organizationProvisioning.d.ts +0 -72
  45. package/internal/validators/request/principal.d.ts +4 -48
  46. package/internal/validators/request/principal.js +4 -2
  47. package/internal/validators/request/principal.js.map +1 -1
  48. package/internal/validators/request/registration.d.ts +0 -24
  49. package/internal/validators/response/container.d.ts +0 -48
  50. package/internal/validators/response/documentMutation.d.ts +0 -96
  51. package/internal/validators/response/organizationPolicyHistory.d.ts +0 -24
  52. package/internal/validators/response/policyEvidenceWire.d.ts +5 -3
  53. package/internal/validators/response/policyEvidenceWire.js +6 -4
  54. package/internal/validators/response/policyEvidenceWire.js.map +1 -1
  55. package/internal/validators/response/principal.d.ts +0 -48
  56. package/internal/validators/response/principalPolicyPage.d.ts +0 -48
  57. package/internal/validators/response/principalSnapshot.d.ts +4 -24
  58. package/internal/validators/response/principalSnapshot.js +4 -6
  59. package/internal/validators/response/principalSnapshot.js.map +1 -1
  60. package/internal/validators/response/projectionPolicyEvidence.d.ts +0 -48
  61. package/package.json +1 -1
  62. package/workflows/organizations/groupPolicy/currentPolicyMutationAcknowledgement.js +1 -6
  63. package/workflows/organizations/groupPolicy/currentPolicyMutationAcknowledgement.js.map +1 -1
  64. package/workflows/organizations/groupPolicy/groupPolicyMutationAcknowledgement.js +1 -6
  65. package/workflows/organizations/groupPolicy/groupPolicyMutationAcknowledgement.js.map +1 -1
  66. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js +4 -6
  67. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js.map +1 -1
  68. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +1 -7
  69. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
  70. package/workflows/principals/policyCache/principalPolicyCacheValidation.js +0 -13
  71. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
  72. package/workflows/principals/publicHistory/publicProjectionDirectory.js +4 -5
  73. package/workflows/principals/publicHistory/publicProjectionDirectory.js.map +1 -1
  74. package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -6
  75. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -7
  76. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
@@ -22,13 +22,7 @@ export declare const ProjectionPolicyEvidenceResponseSchema: z.ZodType<{
22
22
  version: number;
23
23
  };
24
24
  payload: {
25
- cipherSuite: "aes-256-gcm";
26
25
  ciphertext: string;
27
- ciphertextHash: string;
28
- createdAt: string;
29
- principalId: string;
30
- principalType: "group" | "organization";
31
- stateHash: string;
32
26
  };
33
27
  }[];
34
28
  groups: {
@@ -64,13 +58,7 @@ export declare const ProjectionPolicyEvidenceResponseSchema: z.ZodType<{
64
58
  version: number;
65
59
  };
66
60
  payload: {
67
- cipherSuite: "aes-256-gcm";
68
61
  ciphertext: string;
69
- ciphertextHash: string;
70
- createdAt: string;
71
- principalId: string;
72
- principalType: "group" | "organization";
73
- stateHash: string;
74
62
  };
75
63
  }[];
76
64
  groups: {
@@ -106,13 +94,7 @@ export declare const ProjectionPolicyEvidenceResponseSchema: z.ZodType<{
106
94
  version: number;
107
95
  };
108
96
  payload: {
109
- cipherSuite: "aes-256-gcm";
110
97
  ciphertext: string;
111
- ciphertextHash: string;
112
- createdAt: string;
113
- principalId: string;
114
- principalType: "group" | "organization";
115
- stateHash: string;
116
98
  };
117
99
  }[];
118
100
  groups: {
@@ -148,13 +130,7 @@ export declare const ProjectionPolicyEvidenceResponseSchema: z.ZodType<{
148
130
  version: number;
149
131
  };
150
132
  payload: {
151
- cipherSuite: "aes-256-gcm";
152
133
  ciphertext: string;
153
- ciphertextHash: string;
154
- createdAt: string;
155
- principalId: string;
156
- principalType: "group" | "organization";
157
- stateHash: string;
158
134
  };
159
135
  }[];
160
136
  groups: {
@@ -197,13 +173,7 @@ export declare const ProjectionPolicyEvidenceWireResponseSchema: z.ZodType<{
197
173
  version: number;
198
174
  };
199
175
  payload: {
200
- cipherSuite: "aes-256-gcm";
201
176
  ciphertext: string;
202
- ciphertextHash: string;
203
- createdAt: string;
204
- principalId: string;
205
- principalType: "group" | "organization";
206
- stateHash: string;
207
177
  } | null;
208
178
  }[];
209
179
  groups: {
@@ -239,13 +209,7 @@ export declare const ProjectionPolicyEvidenceWireResponseSchema: z.ZodType<{
239
209
  version: number;
240
210
  };
241
211
  payload: {
242
- cipherSuite: "aes-256-gcm";
243
212
  ciphertext: string;
244
- ciphertextHash: string;
245
- createdAt: string;
246
- principalId: string;
247
- principalType: "group" | "organization";
248
- stateHash: string;
249
213
  } | null;
250
214
  }[];
251
215
  groups: {
@@ -281,13 +245,7 @@ export declare const ProjectionPolicyEvidenceWireResponseSchema: z.ZodType<{
281
245
  version: number;
282
246
  };
283
247
  payload: {
284
- cipherSuite: "aes-256-gcm";
285
248
  ciphertext: string;
286
- ciphertextHash: string;
287
- createdAt: string;
288
- principalId: string;
289
- principalType: "group" | "organization";
290
- stateHash: string;
291
249
  } | null;
292
250
  }[];
293
251
  groups: {
@@ -323,13 +281,7 @@ export declare const ProjectionPolicyEvidenceWireResponseSchema: z.ZodType<{
323
281
  version: number;
324
282
  };
325
283
  payload: {
326
- cipherSuite: "aes-256-gcm";
327
284
  ciphertext: string;
328
- ciphertextHash: string;
329
- createdAt: string;
330
- principalId: string;
331
- principalType: "group" | "organization";
332
- stateHash: string;
333
285
  } | null;
334
286
  }[];
335
287
  groups: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.249",
3
+ "version": "0.1.250",
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": {
@@ -36,12 +36,7 @@ export async function verifyCurrentPolicyMutation(input, acknowledgedState) {
36
36
  currentState: state,
37
37
  currentProjection: request.projection,
38
38
  currentGrants: request.grants,
39
- currentPayload: {
40
- ...request.encryptedPayload,
41
- principalId: state.principalId,
42
- principalType: state.principalType,
43
- stateHash: state.stateHash,
44
- },
39
+ currentPayload: { ciphertext: request.encryptedPayload.ciphertext },
45
40
  currentMemberEnvelopes: {
46
41
  envelopes: request.memberEnvelopes,
47
42
  principalId: state.principalId,
@@ -1 +1 @@
1
- {"version":3,"file":"currentPolicyMutationAcknowledgement.js","sourceRoot":"","sources":["currentPolicyMutationAcknowledgement.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,+BAA+B,EAC/B,qCAAqC,GACtC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,4CAA4C,EAAE,MAAM,2BAA2B,CAAC;AAazF,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,KAAiC,EACjC,iBAA0C;IAE1C,MAAM,QAAQ,GAAG,KAAK,CAAC,qBAAqB,CAAC;IAC7C,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IACxC,MAAM,KAAK,GAAG,eAAe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CAAC,aAAa;gBAClC,SAAS,EAAE,KAAK,CAAC,SAAS;aAC3B;YACD,sBAAsB,EAAE;gBACtB,SAAS,EAAE,OAAO,CAAC,eAAe;gBAClC,WAAW,EAAE,KAAK,CAAC,WAAW;gBAC9B,aAAa,EAAE,KAAK,CAAC,aAAa;gBAClC,SAAS,EAAE,KAAK,CAAC,SAAS;gBAC1B,KAAK,EAAE,KAAK,CAAC,QAAQ;aACtB;SACF;KACF,CAAC,CAAC;IACH,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,MAAM,QAAQ,CAAC,KAAK,CAAC;IACvC,4CAA4C,CAC1C,QAAQ,CAAC,KAAK,CAAC,KAAK,EACpB,YAAY,CACb,CAAC;IACF,+BAA+B,CAAC;QAC9B,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,eAAe;QACrC,YAAY,EAAE,QAAQ,CAAC,KAAK,CAAC,KAAK;QAClC,eAAe,EAAE,KAAK,CAAC,qBAAqB;KAC7C,CAAC,CAAC;IACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO,QAAQ,CAAC,KAAK,CAAC;AACxB,CAAC","sourcesContent":["import {\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyExternalAuthority,\n type PrincipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyCurrentSuccessor,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalStateResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { assertPrincipalPolicyCurrentStateMatchesHead } from \"./groupPolicyMutationHead\";\n\nexport interface CurrentPolicyMutationInput {\n readonly currentPolicy?: never;\n readonly verifiedCurrentPolicy: VerifiedPrincipalPolicyCurrent;\n readonly expectedHead: ReferencedPrincipalHead;\n readonly request: PutPrincipalPolicyRequest;\n readonly signerPublicKeys: readonly PrincipalPolicySignerPublicKey[];\n readonly externalAuthority?: PrincipalPolicyExternalAuthority | undefined;\n readonly localPolicyCheckpoint?: PrincipalPolicyCheckpoint | null;\n readonly stillCurrent: () => boolean;\n}\n\n/** Verify a single authored successor; this neither admits it nor persists a pin. */\nexport async function verifyCurrentPolicyMutation(\n input: CurrentPolicyMutationInput,\n acknowledgedState?: PrincipalStateResponse,\n): Promise<VerifiedPrincipalPolicyCurrent> {\n const previous = input.verifiedCurrentPolicy;\n const stillCurrent = input.stillCurrent;\n const owned = structuredClone({\n expectedHead: input.expectedHead,\n request: input.request,\n signerPublicKeys: input.signerPublicKeys,\n externalAuthority: input.externalAuthority,\n localPolicyCheckpoint: input.localPolicyCheckpoint,\n acknowledgedState,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const { request, expectedHead } = owned;\n const state = owned.acknowledgedState ?? {\n ...request.state,\n stateHash: expectedHead.stateHash,\n createdAt: request.state.signedAt,\n };\n if (owned.acknowledgedState) {\n const { createdAt: _createdAt, stateHash, ...responseState } = state;\n if (\n stateHash !== expectedHead.stateHash ||\n canonicalKeyingJsonString(responseState, \"stored group policy state\") !==\n canonicalKeyingJsonString(request.state, \"authored group policy state\")\n )\n throw new Error(\"Group policy state acknowledgement mismatch\");\n }\n const verified = await verifyPrincipalPolicyCurrentSuccessor({\n previous,\n signerPublicKeys: owned.signerPublicKeys,\n externalAuthority: owned.externalAuthority,\n current: {\n currentState: state,\n currentProjection: request.projection,\n currentGrants: request.grants,\n currentPayload: {\n ...request.encryptedPayload,\n principalId: state.principalId,\n principalType: state.principalType,\n stateHash: state.stateHash,\n },\n currentMemberEnvelopes: {\n envelopes: request.memberEnvelopes,\n principalId: state.principalId,\n principalType: state.principalType,\n stateHash: state.stateHash,\n epoch: state.keyEpoch,\n },\n },\n });\n if (!verified.ok) throw verified.error;\n assertPrincipalPolicyCurrentStateMatchesHead(\n verified.value.state,\n expectedHead,\n );\n verifyPrincipalPolicyCheckpoint({\n chain: verified.value.retainedHistory,\n currentState: verified.value.state,\n localCheckpoint: owned.localPolicyCheckpoint,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return verified.value;\n}\n"]}
1
+ {"version":3,"file":"currentPolicyMutationAcknowledgement.js","sourceRoot":"","sources":["currentPolicyMutationAcknowledgement.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,+BAA+B,EAC/B,qCAAqC,GACtC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,4CAA4C,EAAE,MAAM,2BAA2B,CAAC;AAazF,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,KAAiC,EACjC,iBAA0C;IAE1C,MAAM,QAAQ,GAAG,KAAK,CAAC,qBAAqB,CAAC;IAC7C,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IACxC,MAAM,KAAK,GAAG,eAAe,CAAC;QAC5B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,iBAAiB;KAClB,CAAC,CAAC;IACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,GAAG,KAAK,CAAC;IACxC,MAAM,KAAK,GAAG,KAAK,CAAC,iBAAiB,IAAI;QACvC,GAAG,OAAO,CAAC,KAAK;QAChB,SAAS,EAAE,YAAY,CAAC,SAAS;QACjC,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,QAAQ;KAClC,CAAC;IACF,IA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AC;IACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO,QAAQ,CAAC,KAAK,CAAC;AACxB,CAAC","sourcesContent":["import {\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyExternalAuthority,\n type PrincipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyCurrentSuccessor,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalStateResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { assertPrincipalPolicyCurrentStateMatchesHead } from \"./groupPolicyMutationHead\";\n\nexport interface CurrentPolicyMutationInput {\n readonly currentPolicy?: never;\n readonly verifiedCurrentPolicy: VerifiedPrincipalPolicyCurrent;\n readonly expectedHead: ReferencedPrincipalHead;\n readonly request: PutPrincipalPolicyRequest;\n readonly signerPublicKeys: readonly PrincipalPolicySignerPublicKey[];\n readonly externalAuthority?: PrincipalPolicyExternalAuthority | undefined;\n readonly localPolicyCheckpoint?: PrincipalPolicyCheckpoint | null;\n readonly stillCurrent: () => boolean;\n}\n\n/** Verify a single authored successor; this neither admits it nor persists a pin. */\nexport async function verifyCurrentPolicyMutation(\n input: CurrentPolicyMutationInput,\n acknowledgedState?: PrincipalStateResponse,\n): Promise<VerifiedPrincipalPolicyCurrent> {\n const previous = input.verifiedCurrentPolicy;\n const stillCurrent = input.stillCurrent;\n const owned = structuredClone({\n expectedHead: input.expectedHead,\n request: input.request,\n signerPublicKeys: input.signerPublicKeys,\n externalAuthority: input.externalAuthority,\n localPolicyCheckpoint: input.localPolicyCheckpoint,\n acknowledgedState,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const { request, expectedHead } = owned;\n const state = owned.acknowledgedState ?? {\n ...request.state,\n stateHash: expectedHead.stateHash,\n createdAt: request.state.signedAt,\n };\n if (owned.acknowledgedState) {\n const { createdAt: _createdAt, stateHash, ...responseState } = state;\n if (\n stateHash !== expectedHead.stateHash ||\n canonicalKeyingJsonString(responseState, \"stored group policy state\") !==\n canonicalKeyingJsonString(request.state, \"authored group policy state\")\n )\n throw new Error(\"Group policy state acknowledgement mismatch\");\n }\n const verified = await verifyPrincipalPolicyCurrentSuccessor({\n previous,\n signerPublicKeys: owned.signerPublicKeys,\n externalAuthority: owned.externalAuthority,\n current: {\n currentState: state,\n currentProjection: request.projection,\n currentGrants: request.grants,\n currentPayload: { ciphertext: request.encryptedPayload.ciphertext },\n currentMemberEnvelopes: {\n envelopes: request.memberEnvelopes,\n principalId: state.principalId,\n principalType: state.principalType,\n stateHash: state.stateHash,\n epoch: state.keyEpoch,\n },\n },\n });\n if (!verified.ok) throw verified.error;\n assertPrincipalPolicyCurrentStateMatchesHead(\n verified.value.state,\n expectedHead,\n );\n verifyPrincipalPolicyCheckpoint({\n chain: verified.value.retainedHistory,\n currentState: verified.value.state,\n localCheckpoint: owned.localPolicyCheckpoint,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return verified.value;\n}\n"]}
@@ -40,7 +40,6 @@ async function assertPolicyRequestCommitments(request) {
40
40
  request.state.memberCount !== projection.length ||
41
41
  request.state.grantRoot !== grantRoot ||
42
42
  request.state.grantCount !== request.grants.length ||
43
- request.encryptedPayload.ciphertextHash !== payloadCiphertextHash ||
44
43
  request.state.payloadCiphertextHash !== payloadCiphertextHash) {
45
44
  throw new Error("Authored group policy commitments are invalid");
46
45
  }
@@ -164,11 +163,7 @@ export async function acknowledgeInitialGroupPolicy(input) {
164
163
  stateHash: input.stateHash,
165
164
  },
166
165
  currentPayload: {
167
- principalId: state.principalId,
168
- principalType: state.principalType,
169
- stateHash: input.stateHash,
170
- ...input.request.initialGroupPolicy.encryptedPayload,
171
- createdAt: input.response.createdAt,
166
+ ciphertext: input.request.initialGroupPolicy.encryptedPayload.ciphertext,
172
167
  },
173
168
  currentProjection: input.request.initialGroupPolicy.projection,
174
169
  currentGrants: input.request.initialGroupPolicy.grants,
@@ -1 +1 @@
1
- {"version":3,"file":"groupPolicyMutationAcknowledgement.js","sourceRoot":"","sources":["groupPolicyMutationAcknowledgement.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kCAAkC,EAClC,mCAAmC,EACnC,8BAA8B,EAC9B,8BAA8B,EAC9B,0CAA0C,EAC1C,2BAA2B,EAC3B,mCAAmC,GAIpC,MAAM,mBAAmB,CAAC;AAW3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EAAE,kCAAkC,EAAE,MAAM,oDAAoD,CAAC;AACxG,OAAO,EAEL,2BAA2B,GAC5B,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EAAE,8CAA8C,EAAE,MAAM,oDAAoD,CAAC;AAEpH,SAAS,kBAAkB,CACzB,MAAqC;IAErC,OAAO;QACL,GAAG,MAAM,CAAC,cAAc;QACxB;YACE,KAAK,EAAE,MAAM,CAAC,YAAY;YAC1B,UAAU,EAAE,MAAM,CAAC,iBAAiB;YACpC,MAAM,EAAE,MAAM,CAAC,aAAa;SAC7B;KACF,CAAC;AACJ,CAAC;AAED,SAAS,6BAA6B,CACpC,KAQC,EACD,YAAqC,EACrC,QAAgC;IAEhC,OAAO,CACL,KAAK,CAAC,aAAa,KAAK,YAAY,CAAC,aAAa;QAClD,KAAK,CAAC,WAAW,KAAK,YAAY,CAAC,WAAW;QAC9C,KAAK,CAAC,OAAO,KAAK,YAAY,CAAC,OAAO;QACtC,KAAK,CAAC,QAAQ,KAAK,YAAY,CAAC,QAAQ;QACxC,KAAK,CAAC,cAAc,KAAK,YAAY,CAAC,cAAc;QACpD,KAAK,CAAC,aAAa,KAAK,QAAQ,CAAC,aAAa;QAC9C,KAAK,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW;QAC1C,KAAK,CAAC,OAAO,KAAK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YAAY,EAAE,WAAW;QACzB,cAAc,EAAE,EAAE;KACnB,CAAC;IACF,OAAO;QACL,MAAM;QACN,MAAM,EAAE,cAAc,CAAC;YACrB,UAAU,EAAE,KAAK,CAAC,OAAO,CAAC,kBAAkB,CAAC,UAAU;YACvD,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,kBAAkB,CAAC,MAAM;YAC/C,KAAK,EAAE,WAAW;SACnB,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n computePrincipalContainerGrantRoot,\n computePrincipalMemberEnvelopesRoot,\n computePrincipalMembershipRoot,\n computePrincipalProjectionRoot,\n computePrincipalStatePayloadCiphertextHash,\n makeVerifiedPrincipalPolicy,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n OrganizationGroupSummaryResponse,\n PrincipalPolicyBundleResponse,\n PrincipalPolicyMutationResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport { acknowledgedPrincipalPolicyCurrent } from \"../principalPolicy/principalPolicyReceiptArtifacts\";\nimport {\n type CurrentPolicyMutationInput,\n verifyCurrentPolicyMutation,\n} from \"./currentPolicyMutationAcknowledgement\";\n\nexport { assertGroupPolicyEnvelopesMatchAcknowledgement } from \"../principalPolicy/principalPolicyReceiptArtifacts\";\n\nfunction historyWithCurrent(\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyBundleResponse[\"previousStates\"] {\n return [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ];\n}\n\nfunction isAuthoredSuccessorConsistent(\n state: Pick<\n PrincipalStateResponse,\n | \"keyEpoch\"\n | \"keyFingerprint\"\n | \"prevStateHash\"\n | \"principalId\"\n | \"principalType\"\n | \"version\"\n >,\n expectedHead: ReferencedPrincipalHead,\n previous: PrincipalStateResponse,\n): boolean {\n return (\n state.principalType === expectedHead.principalType &&\n state.principalId === expectedHead.principalId &&\n state.version === expectedHead.version &&\n state.keyEpoch === expectedHead.keyEpoch &&\n state.keyFingerprint === expectedHead.keyFingerprint &&\n state.principalType === previous.principalType &&\n state.principalId === previous.principalId &&\n state.version === previous.version + 1 &&\n state.prevStateHash === previous.stateHash\n );\n}\n\nasync function assertPolicyRequestCommitments(\n request: PutPrincipalPolicyRequest,\n): Promise<void> {\n const projection = normalizePrincipalProjectionMembers(request.projection);\n const members = projection.map((member) => ({ userId: member.userId }));\n const [\n membershipRoot,\n memberEnvelopesRoot,\n projectionRoot,\n payloadCiphertextHash,\n grantRoot,\n ] = await Promise.all([\n computePrincipalMembershipRoot(members),\n computePrincipalMemberEnvelopesRoot(request.memberEnvelopes),\n computePrincipalProjectionRoot(projection),\n computePrincipalStatePayloadCiphertextHash(\n request.encryptedPayload.ciphertext,\n ),\n computePrincipalContainerGrantRoot(request.grants),\n ]);\n if (\n request.state.membershipRoot !== membershipRoot ||\n request.state.memberEnvelopesRoot !== memberEnvelopesRoot ||\n request.state.projectionRoot !== projectionRoot ||\n request.state.memberCount !== projection.length ||\n request.state.grantRoot !== grantRoot ||\n request.state.grantCount !== request.grants.length ||\n request.encryptedPayload.ciphertextHash !== payloadCiphertextHash ||\n request.state.payloadCiphertextHash !== payloadCiphertextHash\n ) {\n throw new Error(\"Authored group policy commitments are invalid\");\n }\n}\n\nfunction verifiedPolicy(input: {\n currentPolicy?: PrincipalPolicyBundleResponse | undefined;\n projection: PutPrincipalPolicyRequest[\"projection\"];\n grants: PutPrincipalPolicyRequest[\"grants\"];\n state: PrincipalStateResponse;\n}): VerifiedPrincipalPolicy {\n const previousStates = input.currentPolicy\n ? historyWithCurrent(input.currentPolicy)\n : [];\n return makeVerifiedPrincipalPolicy({\n checkpoint: {\n principalId: input.state.principalId,\n principalType: input.state.principalType,\n stateHash: input.state.stateHash,\n version: input.state.version,\n },\n history: [\n ...previousStates,\n {\n state: input.state,\n projection: input.projection,\n grants: input.grants,\n },\n ],\n keyEpoch: input.state.keyEpoch,\n principalId: input.state.principalId,\n principalType: input.state.principalType,\n projection: input.projection,\n grants: input.grants,\n state: input.state,\n stateHash: input.state.stateHash,\n version: input.state.version,\n });\n}\n\ninterface FullPolicyMutationInput {\n readonly verifiedCurrentPolicy?: never;\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly expectedHead: ReferencedPrincipalHead;\n readonly request: PutPrincipalPolicyRequest;\n}\n\nexport function acknowledgeGroupPolicyState(\n input: CurrentPolicyMutationInput & {\n readonly response: PrincipalStateResponse;\n },\n): Promise<VerifiedPrincipalPolicyCurrent>;\nexport function acknowledgeGroupPolicyState(\n input: FullPolicyMutationInput & {\n readonly response: PrincipalStateResponse;\n },\n): Promise<VerifiedPrincipalPolicy>;\nexport async function acknowledgeGroupPolicyState(\n input: (FullPolicyMutationInput | CurrentPolicyMutationInput) & {\n readonly response: PrincipalStateResponse;\n },\n): Promise<VerifiedPrincipalPolicy | VerifiedPrincipalPolicyCurrent> {\n if (input.verifiedCurrentPolicy !== undefined)\n return verifyCurrentPolicyMutation(input, input.response);\n await assertPolicyRequestCommitments(input.request);\n const { createdAt: _createdAt, stateHash, ...responseState } = input.response;\n const previous = input.currentPolicy.currentState;\n if (\n stateHash !== input.expectedHead.stateHash ||\n !isAuthoredSuccessorConsistent(\n input.response,\n input.expectedHead,\n previous,\n ) ||\n canonicalKeyingJsonString(responseState, \"stored group policy state\") !==\n canonicalKeyingJsonString(\n input.request.state,\n \"authored group policy state\",\n )\n ) {\n throw new Error(\"Group policy state acknowledgement mismatch\");\n }\n return verifiedPolicy({\n currentPolicy: input.currentPolicy,\n projection: input.request.projection,\n grants: input.request.grants,\n state: input.response,\n });\n}\n\n/**\n * Rebuild an acknowledged successor from the authored request, check it\n * against the full predecessor, and return the bundle to retain with it.\n */\nexport async function acknowledgeGroupPolicyBundle(input: {\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly expectedHead: ReferencedPrincipalHead;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): Promise<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}> {\n const current = await acknowledgedPrincipalPolicyCurrent(input);\n const policy = await acknowledgeGroupPolicyState({\n currentPolicy: input.currentPolicy,\n expectedHead: input.expectedHead,\n request: input.request,\n response: current.currentState,\n });\n return {\n bundle: {\n ...current,\n previousStates: historyWithCurrent(input.currentPolicy),\n },\n policy,\n };\n}\n\n/**\n * Materialize the locally signed successor before submission so dependent\n * container mutations can wrap to the exact head that will commit with it.\n * The server still performs the authoritative signature, transition, and\n * authorization checks inside the combined transaction.\n */\nexport function prepareAuthoredGroupPolicy(\n input: CurrentPolicyMutationInput,\n): Promise<VerifiedPrincipalPolicyCurrent>;\nexport function prepareAuthoredGroupPolicy(\n input: FullPolicyMutationInput,\n): Promise<VerifiedPrincipalPolicy>;\nexport async function prepareAuthoredGroupPolicy(\n input: FullPolicyMutationInput | CurrentPolicyMutationInput,\n): Promise<VerifiedPrincipalPolicy | VerifiedPrincipalPolicyCurrent> {\n if (input.verifiedCurrentPolicy !== undefined)\n return verifyCurrentPolicyMutation(input);\n await assertPolicyRequestCommitments(input.request);\n const previous = input.currentPolicy.currentState;\n const state = input.request.state;\n if (!isAuthoredSuccessorConsistent(state, input.expectedHead, previous)) {\n throw new Error(\"Authored group policy successor is inconsistent\");\n }\n return verifiedPolicy({\n currentPolicy: input.currentPolicy,\n projection: input.request.projection,\n grants: input.request.grants,\n state: {\n ...state,\n stateHash: input.expectedHead.stateHash,\n createdAt: state.signedAt,\n },\n });\n}\n\nexport async function acknowledgeInitialGroupPolicy(input: {\n readonly organizationId: string;\n readonly request: CreateOrganizationGroupRequest;\n readonly response: OrganizationGroupSummaryResponse;\n readonly stateHash: string;\n}): Promise<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}> {\n await assertPolicyRequestCommitments(input.request.initialGroupPolicy);\n const state = input.request.initialGroupPolicy.state;\n if (\n input.response.groupId !== input.request.groupId ||\n input.response.organizationId !== input.organizationId ||\n input.response.isBuiltin ||\n input.response.currentState?.stateHash !== input.stateHash ||\n input.response.currentState.version !== state.version ||\n input.response.currentState.keyEpoch !== state.keyEpoch ||\n input.response.currentState.keyFingerprint !== state.keyFingerprint ||\n input.response.currentState.memberCount !== state.memberCount ||\n state.principalType !== \"group\" ||\n state.principalId !== input.request.groupId ||\n state.version !== 1 ||\n state.prevStateHash !== null\n ) {\n throw new Error(\"Created group policy acknowledgement mismatch\");\n }\n const storedState = {\n ...state,\n createdAt: input.response.createdAt,\n stateHash: input.stateHash,\n };\n const bundle: PrincipalPolicyBundleResponse = {\n currentMemberEnvelopes: {\n envelopes: input.request.initialGroupPolicy.memberEnvelopes,\n epoch: state.keyEpoch,\n principalId: state.principalId,\n principalType: state.principalType,\n stateHash: input.stateHash,\n },\n currentPayload: {\n principalId: state.principalId,\n principalType: state.principalType,\n stateHash: input.stateHash,\n ...input.request.initialGroupPolicy.encryptedPayload,\n createdAt: input.response.createdAt,\n },\n currentProjection: input.request.initialGroupPolicy.projection,\n currentGrants: input.request.initialGroupPolicy.grants,\n currentState: storedState,\n previousStates: [],\n };\n return {\n bundle,\n policy: verifiedPolicy({\n projection: input.request.initialGroupPolicy.projection,\n grants: input.request.initialGroupPolicy.grants,\n state: storedState,\n }),\n };\n}\n"]}
1
+ {"version":3,"file":"groupPolicyMutationAcknowledgement.js","sourceRoot":"","sources":["groupPolicyMutationAcknowledgement.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kCAAkC,EAClC,mCAAmC,EACnC,8BAA8B,EAC9B,8BAA8B,EAC9B,0CAA0C,EAC1C,2BAA2B,EAC3B,mCAAmC,GAIpC,MAAM,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CAAC;QACD,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnE,CAAC;IACD,MAAM,WAAW,GAAG;QAClB,GAAG,KAAK;QACR,SAAS,EAAE,KAAK,CAAC,QAAQ,CAAC,SAAS;QACnC,SAAS,EAAE,KAAK,CAAC,SAAS;KAC3B,CAAC;IACF,MAAM,MAAM,GAAkC;QAC5C,sBAAsB,EAAE;YACtB,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,kBAAkB,CAAC,eAAe;YAC3D,KAAK,EAAE,KAAK,CAAC,QAAQ;YACrB,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,SAAS,EAAE,KAAK,CAAC,SAAS;SAC3B;QACD,cAAc,EAAE;YACd,UAAU,EAAE,KAAK,CAAC,OAAO,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,UAAU;SACzE;QACD,iBAAiB,EAAE,KAAK,CAAC,OAAO,CAAC,kBAAkB,CAAC,UAAU;QAC9D,aAAa,EAAE,KAAK,CAAC,OAAO,CAAC,kBAAkB,CAAC,MAAM;QACtD,YAAY,EAAE,WAAW;QACzB,cAAc,EAAE,EAAE;KACnB,CAAC;IACF,OAAO;QACL,MAAM;QACN,MAAM,EAAE,cAAc,CAAC;YACrB,UAAU,EAAE,KAAK,CAAC,OAAO,CAAC,kBAAkB,CAAC,UAAU;YACvD,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,kBAAkB,CAAC,MAAM;YAC/C,KAAK,EAAE,WAAW;SACnB,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n computePrincipalContainerGrantRoot,\n computePrincipalMemberEnvelopesRoot,\n computePrincipalMembershipRoot,\n computePrincipalProjectionRoot,\n computePrincipalStatePayloadCiphertextHash,\n makeVerifiedPrincipalPolicy,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n OrganizationGroupSummaryResponse,\n PrincipalPolicyBundleResponse,\n PrincipalPolicyMutationResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport { acknowledgedPrincipalPolicyCurrent } from \"../principalPolicy/principalPolicyReceiptArtifacts\";\nimport {\n type CurrentPolicyMutationInput,\n verifyCurrentPolicyMutation,\n} from \"./currentPolicyMutationAcknowledgement\";\n\nexport { assertGroupPolicyEnvelopesMatchAcknowledgement } from \"../principalPolicy/principalPolicyReceiptArtifacts\";\n\nfunction historyWithCurrent(\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyBundleResponse[\"previousStates\"] {\n return [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ];\n}\n\nfunction isAuthoredSuccessorConsistent(\n state: Pick<\n PrincipalStateResponse,\n | \"keyEpoch\"\n | \"keyFingerprint\"\n | \"prevStateHash\"\n | \"principalId\"\n | \"principalType\"\n | \"version\"\n >,\n expectedHead: ReferencedPrincipalHead,\n previous: PrincipalStateResponse,\n): boolean {\n return (\n state.principalType === expectedHead.principalType &&\n state.principalId === expectedHead.principalId &&\n state.version === expectedHead.version &&\n state.keyEpoch === expectedHead.keyEpoch &&\n state.keyFingerprint === expectedHead.keyFingerprint &&\n state.principalType === previous.principalType &&\n state.principalId === previous.principalId &&\n state.version === previous.version + 1 &&\n state.prevStateHash === previous.stateHash\n );\n}\n\nasync function assertPolicyRequestCommitments(\n request: PutPrincipalPolicyRequest,\n): Promise<void> {\n const projection = normalizePrincipalProjectionMembers(request.projection);\n const members = projection.map((member) => ({ userId: member.userId }));\n const [\n membershipRoot,\n memberEnvelopesRoot,\n projectionRoot,\n payloadCiphertextHash,\n grantRoot,\n ] = await Promise.all([\n computePrincipalMembershipRoot(members),\n computePrincipalMemberEnvelopesRoot(request.memberEnvelopes),\n computePrincipalProjectionRoot(projection),\n computePrincipalStatePayloadCiphertextHash(\n request.encryptedPayload.ciphertext,\n ),\n computePrincipalContainerGrantRoot(request.grants),\n ]);\n if (\n request.state.membershipRoot !== membershipRoot ||\n request.state.memberEnvelopesRoot !== memberEnvelopesRoot ||\n request.state.projectionRoot !== projectionRoot ||\n request.state.memberCount !== projection.length ||\n request.state.grantRoot !== grantRoot ||\n request.state.grantCount !== request.grants.length ||\n request.state.payloadCiphertextHash !== payloadCiphertextHash\n ) {\n throw new Error(\"Authored group policy commitments are invalid\");\n }\n}\n\nfunction verifiedPolicy(input: {\n currentPolicy?: PrincipalPolicyBundleResponse | undefined;\n projection: PutPrincipalPolicyRequest[\"projection\"];\n grants: PutPrincipalPolicyRequest[\"grants\"];\n state: PrincipalStateResponse;\n}): VerifiedPrincipalPolicy {\n const previousStates = input.currentPolicy\n ? historyWithCurrent(input.currentPolicy)\n : [];\n return makeVerifiedPrincipalPolicy({\n checkpoint: {\n principalId: input.state.principalId,\n principalType: input.state.principalType,\n stateHash: input.state.stateHash,\n version: input.state.version,\n },\n history: [\n ...previousStates,\n {\n state: input.state,\n projection: input.projection,\n grants: input.grants,\n },\n ],\n keyEpoch: input.state.keyEpoch,\n principalId: input.state.principalId,\n principalType: input.state.principalType,\n projection: input.projection,\n grants: input.grants,\n state: input.state,\n stateHash: input.state.stateHash,\n version: input.state.version,\n });\n}\n\ninterface FullPolicyMutationInput {\n readonly verifiedCurrentPolicy?: never;\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly expectedHead: ReferencedPrincipalHead;\n readonly request: PutPrincipalPolicyRequest;\n}\n\nexport function acknowledgeGroupPolicyState(\n input: CurrentPolicyMutationInput & {\n readonly response: PrincipalStateResponse;\n },\n): Promise<VerifiedPrincipalPolicyCurrent>;\nexport function acknowledgeGroupPolicyState(\n input: FullPolicyMutationInput & {\n readonly response: PrincipalStateResponse;\n },\n): Promise<VerifiedPrincipalPolicy>;\nexport async function acknowledgeGroupPolicyState(\n input: (FullPolicyMutationInput | CurrentPolicyMutationInput) & {\n readonly response: PrincipalStateResponse;\n },\n): Promise<VerifiedPrincipalPolicy | VerifiedPrincipalPolicyCurrent> {\n if (input.verifiedCurrentPolicy !== undefined)\n return verifyCurrentPolicyMutation(input, input.response);\n await assertPolicyRequestCommitments(input.request);\n const { createdAt: _createdAt, stateHash, ...responseState } = input.response;\n const previous = input.currentPolicy.currentState;\n if (\n stateHash !== input.expectedHead.stateHash ||\n !isAuthoredSuccessorConsistent(\n input.response,\n input.expectedHead,\n previous,\n ) ||\n canonicalKeyingJsonString(responseState, \"stored group policy state\") !==\n canonicalKeyingJsonString(\n input.request.state,\n \"authored group policy state\",\n )\n ) {\n throw new Error(\"Group policy state acknowledgement mismatch\");\n }\n return verifiedPolicy({\n currentPolicy: input.currentPolicy,\n projection: input.request.projection,\n grants: input.request.grants,\n state: input.response,\n });\n}\n\n/**\n * Rebuild an acknowledged successor from the authored request, check it\n * against the full predecessor, and return the bundle to retain with it.\n */\nexport async function acknowledgeGroupPolicyBundle(input: {\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly expectedHead: ReferencedPrincipalHead;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): Promise<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}> {\n const current = await acknowledgedPrincipalPolicyCurrent(input);\n const policy = await acknowledgeGroupPolicyState({\n currentPolicy: input.currentPolicy,\n expectedHead: input.expectedHead,\n request: input.request,\n response: current.currentState,\n });\n return {\n bundle: {\n ...current,\n previousStates: historyWithCurrent(input.currentPolicy),\n },\n policy,\n };\n}\n\n/**\n * Materialize the locally signed successor before submission so dependent\n * container mutations can wrap to the exact head that will commit with it.\n * The server still performs the authoritative signature, transition, and\n * authorization checks inside the combined transaction.\n */\nexport function prepareAuthoredGroupPolicy(\n input: CurrentPolicyMutationInput,\n): Promise<VerifiedPrincipalPolicyCurrent>;\nexport function prepareAuthoredGroupPolicy(\n input: FullPolicyMutationInput,\n): Promise<VerifiedPrincipalPolicy>;\nexport async function prepareAuthoredGroupPolicy(\n input: FullPolicyMutationInput | CurrentPolicyMutationInput,\n): Promise<VerifiedPrincipalPolicy | VerifiedPrincipalPolicyCurrent> {\n if (input.verifiedCurrentPolicy !== undefined)\n return verifyCurrentPolicyMutation(input);\n await assertPolicyRequestCommitments(input.request);\n const previous = input.currentPolicy.currentState;\n const state = input.request.state;\n if (!isAuthoredSuccessorConsistent(state, input.expectedHead, previous)) {\n throw new Error(\"Authored group policy successor is inconsistent\");\n }\n return verifiedPolicy({\n currentPolicy: input.currentPolicy,\n projection: input.request.projection,\n grants: input.request.grants,\n state: {\n ...state,\n stateHash: input.expectedHead.stateHash,\n createdAt: state.signedAt,\n },\n });\n}\n\nexport async function acknowledgeInitialGroupPolicy(input: {\n readonly organizationId: string;\n readonly request: CreateOrganizationGroupRequest;\n readonly response: OrganizationGroupSummaryResponse;\n readonly stateHash: string;\n}): Promise<{\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}> {\n await assertPolicyRequestCommitments(input.request.initialGroupPolicy);\n const state = input.request.initialGroupPolicy.state;\n if (\n input.response.groupId !== input.request.groupId ||\n input.response.organizationId !== input.organizationId ||\n input.response.isBuiltin ||\n input.response.currentState?.stateHash !== input.stateHash ||\n input.response.currentState.version !== state.version ||\n input.response.currentState.keyEpoch !== state.keyEpoch ||\n input.response.currentState.keyFingerprint !== state.keyFingerprint ||\n input.response.currentState.memberCount !== state.memberCount ||\n state.principalType !== \"group\" ||\n state.principalId !== input.request.groupId ||\n state.version !== 1 ||\n state.prevStateHash !== null\n ) {\n throw new Error(\"Created group policy acknowledgement mismatch\");\n }\n const storedState = {\n ...state,\n createdAt: input.response.createdAt,\n stateHash: input.stateHash,\n };\n const bundle: PrincipalPolicyBundleResponse = {\n currentMemberEnvelopes: {\n envelopes: input.request.initialGroupPolicy.memberEnvelopes,\n epoch: state.keyEpoch,\n principalId: state.principalId,\n principalType: state.principalType,\n stateHash: input.stateHash,\n },\n currentPayload: {\n ciphertext: input.request.initialGroupPolicy.encryptedPayload.ciphertext,\n },\n currentProjection: input.request.initialGroupPolicy.projection,\n currentGrants: input.request.initialGroupPolicy.grants,\n currentState: storedState,\n previousStates: [],\n };\n return {\n bundle,\n policy: verifiedPolicy({\n projection: input.request.initialGroupPolicy.projection,\n grants: input.request.initialGroupPolicy.grants,\n state: storedState,\n }),\n };\n}\n"]}
@@ -28,14 +28,12 @@ export async function verifyOrganizationPolicyHistory(input) {
28
28
  const entry = entries[index];
29
29
  if (!entry ||
30
30
  !principalHeadMatchesReference(entry.state, reference) ||
31
- payload.principalType !== "organization" ||
32
- payload.principalId !== head.principalId ||
33
- payload.stateHash !== reference.stateHash ||
31
+ reference.principalType !== "organization" ||
32
+ reference.principalId !== head.principalId ||
34
33
  descriptors.has(reference.stateHash))
35
34
  reject("directory payload scope or order is invalid");
36
- const hash = await computePrincipalStatePayloadCiphertextHash(payload.ciphertext);
37
- if (hash !== entry.state.payloadCiphertextHash ||
38
- hash !== payload.ciphertextHash)
35
+ if ((await computePrincipalStatePayloadCiphertextHash(payload.ciphertext)) !==
36
+ entry.state.payloadCiphertextHash)
39
37
  reject("directory payload does not match its signed hash");
40
38
  const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);
41
39
  if (descriptor.organizationId !== head.principalId)
@@ -1 +1 @@
1
- {"version":3,"file":"organizationPolicyHistoryVerification.js","sourceRoot":"","sources":["organizationPolicyHistoryVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0CAA0C,EAC1C,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAG1E,SAAS,MAAM,CAAC,OAAe;IAC7B,MAAM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AoB,CAC3B,MAA4C,EAC5C,UAA8C;IAE9C,KAAK,MAAM,KAAK,IAAI,UAAU,EAAE,CAAC;QAC/B,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAC/C,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,OAAO,GAAG,QAAQ,CAAC,OAAO;YAC/C,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC;IACzC,CAAC;AACH,CAAC;AAED,SAAS,kBAAkB,CACzB,QAA2C,EAC3C,MAA4C;IAE5C,IAAI,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,KAAK,MAAM,CAAC,IAAI;QACjD,MAAM,CAAC,yBAAyB,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,MAAM,IAAI,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QAC9C,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACrD,IACE,CAAC,QAAQ;YACT,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC;YACjC,CAAC,6BAA6B,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC;YAErD,MAAM,CAAC,yDAAyD,CAAC,CAAC;QACpE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["import {\n computePrincipalStatePayloadCiphertextHash,\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { OrganizationPolicyHistoryResponse } from \"@tearleads/validators/response\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { RecoveredPrincipalHistoryPage } from \"../../principals/historyRecovery/loadRecoveredPrincipalHistoryPage\";\n\nfunction reject(message: string): never {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n `Organization policy history: ${message}`,\n );\n}\n\n/** Bind every display payload and public source to the privately verified page. */\nexport async function verifyOrganizationPolicyHistory(input: {\n readonly head: ReferencedPrincipalHead;\n readonly page: RecoveredPrincipalHistoryPage;\n readonly evidence: OrganizationPolicyHistoryResponse;\n}) {\n const { head, page, evidence } = input;\n const beforeVersion = (page.entries.at(-1)?.state.version ?? 0) + 1;\n if (\n head.principalType !== \"organization\" ||\n evidence.organizationId !== head.principalId ||\n evidence.stateHash !== head.stateHash ||\n evidence.beforeVersion !== beforeVersion ||\n evidence.nextBeforeVersion !== page.nextBeforeVersion ||\n !evidence.evidence.organization ||\n !principalHeadMatchesReference(evidence.evidence.organization.head, head)\n )\n reject(\"response does not match the requested organization page\");\n const entries = page.predecessor\n ? [page.predecessor, ...page.entries]\n : page.entries;\n if (evidence.evidence.organizationPayloads.length !== entries.length)\n reject(\"directory page is incomplete\");\n const descriptors = new Map<string, OrganizationAuthorityDescriptor>();\n const references: ReferencedPrincipalHead[] = [head];\n const groups = new Map<string, ReferencedPrincipalHead>();\n for (const [\n index,\n item,\n ] of evidence.evidence.organizationPayloads.entries()) {\n const { reference, payload } = item;\n const entry = entries[index];\n if (\n !entry ||\n !principalHeadMatchesReference(entry.state, reference) ||\n payload.principalType !== \"organization\" ||\n payload.principalId !== head.principalId ||\n payload.stateHash !== reference.stateHash ||\n descriptors.has(reference.stateHash)\n )\n reject(\"directory payload scope or order is invalid\");\n const hash = await computePrincipalStatePayloadCiphertextHash(\n payload.ciphertext,\n );\n if (\n hash !== entry.state.payloadCiphertextHash ||\n hash !== payload.ciphertextHash\n )\n reject(\"directory payload does not match its signed hash\");\n const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);\n if (descriptor.organizationId !== head.principalId)\n reject(\"directory belongs to another organization\");\n descriptors.set(reference.stateHash, descriptor);\n references.push(reference, ...descriptor.groupHeads);\n keepNewestGroupHeads(groups, descriptor.groupHeads);\n }\n verifyGroupSources(evidence, groups);\n return { descriptors, references };\n}\n\nfunction keepNewestGroupHeads(\n groups: Map<string, ReferencedPrincipalHead>,\n groupHeads: readonly ReferencedPrincipalHead[],\n) {\n for (const group of groupHeads) {\n const previous = groups.get(group.principalId);\n if (!previous || group.version > previous.version)\n groups.set(group.principalId, group);\n }\n}\n\nfunction verifyGroupSources(\n evidence: OrganizationPolicyHistoryResponse,\n groups: Map<string, ReferencedPrincipalHead>,\n) {\n if (evidence.evidence.groups.length !== groups.size)\n reject(\"unexpected group source\");\n const seen = new Set<string>();\n for (const source of evidence.evidence.groups) {\n const expected = groups.get(source.head.principalId);\n if (\n !expected ||\n seen.has(source.head.principalId) ||\n !principalHeadMatchesReference(source.head, expected)\n )\n reject(\"group source extends beyond the page's signed directory\");\n seen.add(source.head.principalId);\n }\n}\n"]}
1
+ {"version":3,"file":"organizationPolicyHistoryVerification.js","sourceRoot":"","sources":["organizationPolicyHistoryVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0CAA0C,EAC1C,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAG1E,SAAS,MAAM,CAAC,OAAe;IAC7B,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,gCAAgC,OAAO,EAAE,CAC1C,CAAC;AACJ,CAAC;AAED,mFAAmF;AACnF,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAIrD;IACC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;IACvC,MAAM,aAAa,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,OAAO,IAAI,CAAC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AK,MAAM,CAAC,IAAI;QACjD,MAAM,CAAC,yBAAyB,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,MAAM,IAAI,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QAC9C,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACrD,IACE,CAAC,QAAQ;YACT,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC;YACjC,CAAC,6BAA6B,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC;YAErD,MAAM,CAAC,yDAAyD,CAAC,CAAC;QACpE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["import {\n computePrincipalStatePayloadCiphertextHash,\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { OrganizationPolicyHistoryResponse } from \"@tearleads/validators/response\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { RecoveredPrincipalHistoryPage } from \"../../principals/historyRecovery/loadRecoveredPrincipalHistoryPage\";\n\nfunction reject(message: string): never {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n `Organization policy history: ${message}`,\n );\n}\n\n/** Bind every display payload and public source to the privately verified page. */\nexport async function verifyOrganizationPolicyHistory(input: {\n readonly head: ReferencedPrincipalHead;\n readonly page: RecoveredPrincipalHistoryPage;\n readonly evidence: OrganizationPolicyHistoryResponse;\n}) {\n const { head, page, evidence } = input;\n const beforeVersion = (page.entries.at(-1)?.state.version ?? 0) + 1;\n if (\n head.principalType !== \"organization\" ||\n evidence.organizationId !== head.principalId ||\n evidence.stateHash !== head.stateHash ||\n evidence.beforeVersion !== beforeVersion ||\n evidence.nextBeforeVersion !== page.nextBeforeVersion ||\n !evidence.evidence.organization ||\n !principalHeadMatchesReference(evidence.evidence.organization.head, head)\n )\n reject(\"response does not match the requested organization page\");\n const entries = page.predecessor\n ? [page.predecessor, ...page.entries]\n : page.entries;\n if (evidence.evidence.organizationPayloads.length !== entries.length)\n reject(\"directory page is incomplete\");\n const descriptors = new Map<string, OrganizationAuthorityDescriptor>();\n const references: ReferencedPrincipalHead[] = [head];\n const groups = new Map<string, ReferencedPrincipalHead>();\n for (const [\n index,\n item,\n ] of evidence.evidence.organizationPayloads.entries()) {\n const { reference, payload } = item;\n const entry = entries[index];\n if (\n !entry ||\n !principalHeadMatchesReference(entry.state, reference) ||\n reference.principalType !== \"organization\" ||\n reference.principalId !== head.principalId ||\n descriptors.has(reference.stateHash)\n )\n reject(\"directory payload scope or order is invalid\");\n if (\n (await computePrincipalStatePayloadCiphertextHash(payload.ciphertext)) !==\n entry.state.payloadCiphertextHash\n )\n reject(\"directory payload does not match its signed hash\");\n const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);\n if (descriptor.organizationId !== head.principalId)\n reject(\"directory belongs to another organization\");\n descriptors.set(reference.stateHash, descriptor);\n references.push(reference, ...descriptor.groupHeads);\n keepNewestGroupHeads(groups, descriptor.groupHeads);\n }\n verifyGroupSources(evidence, groups);\n return { descriptors, references };\n}\n\nfunction keepNewestGroupHeads(\n groups: Map<string, ReferencedPrincipalHead>,\n groupHeads: readonly ReferencedPrincipalHead[],\n) {\n for (const group of groupHeads) {\n const previous = groups.get(group.principalId);\n if (!previous || group.version > previous.version)\n groups.set(group.principalId, group);\n }\n}\n\nfunction verifyGroupSources(\n evidence: OrganizationPolicyHistoryResponse,\n groups: Map<string, ReferencedPrincipalHead>,\n) {\n if (evidence.evidence.groups.length !== groups.size)\n reject(\"unexpected group source\");\n const seen = new Set<string>();\n for (const source of evidence.evidence.groups) {\n const expected = groups.get(source.head.principalId);\n if (\n !expected ||\n seen.has(source.head.principalId) ||\n !principalHeadMatchesReference(source.head, expected)\n )\n reject(\"group source extends beyond the page's signed directory\");\n seen.add(source.head.principalId);\n }\n}\n"]}
@@ -96,13 +96,7 @@ export async function acknowledgedPrincipalPolicyCurrent(input) {
96
96
  const { createdAt } = response;
97
97
  return {
98
98
  currentState: { ...state, stateHash, createdAt },
99
- currentPayload: {
100
- principalType,
101
- principalId,
102
- stateHash,
103
- ...request.encryptedPayload,
104
- createdAt,
105
- },
99
+ currentPayload: { ciphertext: request.encryptedPayload.ciphertext },
106
100
  currentProjection: request.projection,
107
101
  currentGrants: request.grants,
108
102
  currentMemberEnvelopes: {
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyReceiptArtifacts.js","sourceRoot":"","sources":["principalPolicyReceiptArtifacts.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,sCAAsC,EACtC,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EACL,eAAe,EACf,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAEjH,SAAS,qBAAqB,CAAI,MAAoB,EAAE,KAAa;IACnE,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACtC,uBAAuB,CACrB,yBAAyB,CAAC,IAAI,EAAE,KAAK,CAAC,EACtC,yBAAyB,CAAC,KAAK,EAAE,KAAK,CAAC,CACxC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8CAA8C,CAC5D,QAAiD,EACjD,QAAiD;IAEjD,MAAM,UAAU,GAAG,CAAC,KAA8C,EAAE,EAAE,CAAC,CAAC;QACtE,GAAG,KAAK;QACR,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AAK,EAAE,GAAG,OAAO,CAAC;IAC1B,MAAM,SAAS,GAAG,MAAM,yBAAyB,CAAC,KAAK,CAAC,CAAC;IACzD,IACE,CAAC,6BAA6B,CAAC,QAAQ,CAAC,IAAI,EAAE;QAC5C,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,SAAS;QACT,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC;QAEF,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,MAAM,uCAAuC,CAAC;QAC5C,QAAQ,EAAE,OAAO,CAAC,kBAAkB,IAAI,EAAE;QAC1C,SAAS,EAAE,QAAQ,CAAC,kBAAkB;KACvC,CAAC,CAAC;IACH,MAAM,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC;IAC7C,MAAM,EAAE,SAAS,EAAE,GAAG,QAAQ,CAAC;IAC/B,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QAChD,cAAc,EAAE;YACd,aAAa;YACb,WAAW;YACX,SAAS;YACT,GAAG,OAAO,CAAC,gBAAgB;YAC3B,SAAS;SACV;QACD,iBAAiB,EAAE,OAAO,CAAC,UAAU;QACrC,aAAa,EAAE,OAAO,CAAC,MAAM;QAC7B,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,KAAK,CAAC,QAAQ;YACrB,SAAS,EAAE,OAAO,CAAC,eAAe;SACnC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n compareCanonicalStrings,\n computeAccessEventHash,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n computePrincipalStateHash,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport {\n readAccessEvent,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../../../data/keyingProjectionVerification/readers\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\n\nfunction sortedCanonicalValues<T>(values: readonly T[], label: string): T[] {\n return [...values].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, label),\n canonicalKeyingJsonString(right, label),\n ),\n );\n}\n\nexport function assertGroupPolicyEnvelopesMatchAcknowledgement(\n expected: CurrentPrincipalMemberEnvelopesResponse,\n observed: CurrentPrincipalMemberEnvelopesResponse,\n): void {\n const normalized = (value: CurrentPrincipalMemberEnvelopesResponse) => ({\n ...value,\n envelopes: sortedCanonicalValues(\n value.envelopes,\n \"principal member envelope\",\n ),\n });\n if (\n canonicalKeyingJsonString(\n normalized(expected),\n \"acknowledged group member envelopes\",\n ) !==\n canonicalKeyingJsonString(\n normalized(observed),\n \"observed group member envelopes\",\n )\n ) {\n throw new Error(\"Group member envelopes changed after acknowledgement\");\n }\n}\n\n/**\n * Each rematerialized container's acknowledgement names its commit by hash;\n * match every hash against the request this client authored.\n */\nasync function assertContainerMutationAcknowledgements(input: {\n readonly requests: readonly NonNullable<\n PutPrincipalPolicyRequest[\"containerMutations\"]\n >[number][];\n readonly responses: readonly ContainerMutationResponse[] | undefined;\n}): Promise<void> {\n if (!input.responses || input.responses.length !== input.requests.length) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n for (const [index, request] of input.requests.entries()) {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n const label = \"authored group policy container mutation\";\n const keyEpoch = readContainerKeyEpoch(request.keyEpoch, label);\n const recipientTargets = sortedCanonicalValues(\n request.wraps.map((value) => {\n const wrap = readContainerKeyWrap(value, label);\n return {\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n };\n }),\n \"authored recipient target\",\n );\n // The request carries this client's own hash of the manifest it signed\n // and the signed event, whose hashes the acknowledgement must name. The\n // manifest hash commits the epoch, but the request no longer names it,\n // so the receipt's epoch label is not compared here: journal recovery\n // discards the receipt after this check, and the in-process path stores\n // a head only through the plan-based container acknowledgement, which\n // requires the plan's epoch. Every field compared here is one the\n // server received in the request, so this binds the receipt to the\n // request; it never proved a commit, with or without the epoch. A\n // rotation's signed body commits its keyring hash, so a substituted\n // keyring must refuse here, before journal recovery clears the saved\n // request. A grant that keeps its epoch commits none; the container\n // acknowledgement checks the retained keyring against the epoch's own.\n const committedKeyringHash = Reflect.get(\n Object(request.body),\n \"keyringHash\",\n );\n if (\n response.manifestHead.manifestHash !== request.expectedManifestHash ||\n response.eventHash !==\n (await computeAccessEventHash(readAccessEvent(request.event, label))) ||\n response.containerKek.containerKeyEpochId !== keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== keyEpoch.keyEpoch ||\n response.containerKek.keyEpochHash !==\n (await computeContainerKeyEpochHash(keyEpoch)) ||\n (typeof committedKeyringHash === \"string\" &&\n response.containerKek.keyringHash !== committedKeyringHash) ||\n response.containerKek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(recipientTargets))\n ) {\n throw new Error(\"Group policy container acknowledgement mismatch\");\n }\n }\n}\n\n/**\n * The current an acknowledgement commits, rebuilt from this client's own\n * signed request: the server returns only the head it stored, the insertion\n * time it assigned to the state and payload, and hash-form container\n * acknowledgements. A head other than the one the request commits to refuses.\n * Nothing here manufactures predecessor history or pins.\n */\nexport async function acknowledgedPrincipalPolicyCurrent(input: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): Promise<PrincipalPolicyPageCurrent> {\n const { request, response } = input;\n const { state } = request;\n const stateHash = await computePrincipalStateHash(state);\n if (\n !principalHeadMatchesReference(response.head, {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash,\n keyFingerprint: state.keyFingerprint,\n })\n )\n throw new Error(\"Principal policy acknowledgement names another head\");\n await assertContainerMutationAcknowledgements({\n requests: request.containerMutations ?? [],\n responses: response.containerMutations,\n });\n const { principalType, principalId } = state;\n const { createdAt } = response;\n return {\n currentState: { ...state, stateHash, createdAt },\n currentPayload: {\n principalType,\n principalId,\n stateHash,\n ...request.encryptedPayload,\n createdAt,\n },\n currentProjection: request.projection,\n currentGrants: request.grants,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: state.keyEpoch,\n envelopes: request.memberEnvelopes,\n },\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyReceiptArtifacts.js","sourceRoot":"","sources":["principalPolicyReceiptArtifacts.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,sBAAsB,EACtB,sCAAsC,EACtC,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EACL,eAAe,EACf,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAEjH,SAAS,qBAAqB,CAAI,MAAoB,EAAE,KAAa;IACnE,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACtC,uBAAuB,CACrB,yBAAyB,CAAC,IAAI,EAAE,KAAK,CAAC,EACtC,yBAAyB,CAAC,KAAK,EAAE,KAAK,CAAC,CACxC,CACF,CAAC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ads/api-client\";\nimport {\n compareCanonicalStrings,\n computeAccessEventHash,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n computePrincipalStateHash,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport {\n readAccessEvent,\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../../../data/keyingProjectionVerification/readers\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\n\nfunction sortedCanonicalValues<T>(values: readonly T[], label: string): T[] {\n return [...values].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, label),\n canonicalKeyingJsonString(right, label),\n ),\n );\n}\n\nexport function assertGroupPolicyEnvelopesMatchAcknowledgement(\n expected: CurrentPrincipalMemberEnvelopesResponse,\n observed: CurrentPrincipalMemberEnvelopesResponse,\n): void {\n const normalized = (value: CurrentPrincipalMemberEnvelopesResponse) => ({\n ...value,\n envelopes: sortedCanonicalValues(\n value.envelopes,\n \"principal member envelope\",\n ),\n });\n if (\n canonicalKeyingJsonString(\n normalized(expected),\n \"acknowledged group member envelopes\",\n ) !==\n canonicalKeyingJsonString(\n normalized(observed),\n \"observed group member envelopes\",\n )\n ) {\n throw new Error(\"Group member envelopes changed after acknowledgement\");\n }\n}\n\n/**\n * Each rematerialized container's acknowledgement names its commit by hash;\n * match every hash against the request this client authored.\n */\nasync function assertContainerMutationAcknowledgements(input: {\n readonly requests: readonly NonNullable<\n PutPrincipalPolicyRequest[\"containerMutations\"]\n >[number][];\n readonly responses: readonly ContainerMutationResponse[] | undefined;\n}): Promise<void> {\n if (!input.responses || input.responses.length !== input.requests.length) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n for (const [index, request] of input.requests.entries()) {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n const label = \"authored group policy container mutation\";\n const keyEpoch = readContainerKeyEpoch(request.keyEpoch, label);\n const recipientTargets = sortedCanonicalValues(\n request.wraps.map((value) => {\n const wrap = readContainerKeyWrap(value, label);\n return {\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n };\n }),\n \"authored recipient target\",\n );\n // The request carries this client's own hash of the manifest it signed\n // and the signed event, whose hashes the acknowledgement must name. The\n // manifest hash commits the epoch, but the request no longer names it,\n // so the receipt's epoch label is not compared here: journal recovery\n // discards the receipt after this check, and the in-process path stores\n // a head only through the plan-based container acknowledgement, which\n // requires the plan's epoch. Every field compared here is one the\n // server received in the request, so this binds the receipt to the\n // request; it never proved a commit, with or without the epoch. A\n // rotation's signed body commits its keyring hash, so a substituted\n // keyring must refuse here, before journal recovery clears the saved\n // request. A grant that keeps its epoch commits none; the container\n // acknowledgement checks the retained keyring against the epoch's own.\n const committedKeyringHash = Reflect.get(\n Object(request.body),\n \"keyringHash\",\n );\n if (\n response.manifestHead.manifestHash !== request.expectedManifestHash ||\n response.eventHash !==\n (await computeAccessEventHash(readAccessEvent(request.event, label))) ||\n response.containerKek.containerKeyEpochId !== keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== keyEpoch.keyEpoch ||\n response.containerKek.keyEpochHash !==\n (await computeContainerKeyEpochHash(keyEpoch)) ||\n (typeof committedKeyringHash === \"string\" &&\n response.containerKek.keyringHash !== committedKeyringHash) ||\n response.containerKek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(recipientTargets))\n ) {\n throw new Error(\"Group policy container acknowledgement mismatch\");\n }\n }\n}\n\n/**\n * The current an acknowledgement commits, rebuilt from this client's own\n * signed request: the server returns only the head it stored, the insertion\n * time it assigned to the state and payload, and hash-form container\n * acknowledgements. A head other than the one the request commits to refuses.\n * Nothing here manufactures predecessor history or pins.\n */\nexport async function acknowledgedPrincipalPolicyCurrent(input: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): Promise<PrincipalPolicyPageCurrent> {\n const { request, response } = input;\n const { state } = request;\n const stateHash = await computePrincipalStateHash(state);\n if (\n !principalHeadMatchesReference(response.head, {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash,\n keyFingerprint: state.keyFingerprint,\n })\n )\n throw new Error(\"Principal policy acknowledgement names another head\");\n await assertContainerMutationAcknowledgements({\n requests: request.containerMutations ?? [],\n responses: response.containerMutations,\n });\n const { principalType, principalId } = state;\n const { createdAt } = response;\n return {\n currentState: { ...state, stateHash, createdAt },\n currentPayload: { ciphertext: request.encryptedPayload.ciphertext },\n currentProjection: request.projection,\n currentGrants: request.grants,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: state.keyEpoch,\n envelopes: request.memberEnvelopes,\n },\n };\n}\n"]}
@@ -44,19 +44,6 @@ function getBundleReferenceFailure(reference, bundle) {
44
44
  message: "member envelope epoch does not match current principal",
45
45
  };
46
46
  }
47
- if (bundle.currentPayload.principalType !== bundle.currentState.principalType ||
48
- bundle.currentPayload.principalId !== bundle.currentState.principalId) {
49
- return {
50
- code: "object_mismatch",
51
- message: "payload principal does not match current principal",
52
- };
53
- }
54
- if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {
55
- return {
56
- code: "hash_mismatch",
57
- message: "payload state hash does not match current principal",
58
- };
59
- }
60
47
  return null;
61
48
  }
62
49
  function getCheckpointFailure(checkpoint, bundle) {
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,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;gBAClC,eAAe,EAAE,KAAK,CAAC,eAAe;gBACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;aACpD,CAAC,EACF,CAAC;gBACD,MAAM,IAAI,oCAAoC,CAC5C,6CAA6C,CAC9C,CAAC;YACJ,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC9D,OAAO;QACL,mBAAmB,EAAE,uBAAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../../../data/principals/principalPolicyVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,+BAA+B,EAC/B,yDAAyD,G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AAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../../../data/principals/principalPolicyVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
@@ -10,14 +10,13 @@ export async function publicProjectionDirectoryBindings(evidence, organization)
10
10
  const state = entries.find(({ state }) => principalHeadMatchesReference(state, reference))?.state;
11
11
  if (!state ||
12
12
  reference.version > organization.options.source.head.version ||
13
- payload.principalType !== "organization" ||
14
- payload.principalId !== organization.options.organizationId ||
15
- payload.stateHash !== state.stateHash ||
13
+ state.principalType !== "organization" ||
14
+ state.principalId !== organization.options.organizationId ||
16
15
  seen.has(state.stateHash))
17
16
  rejectPublicProjection("directory payload scope is invalid");
18
17
  seen.add(state.stateHash);
19
- const hash = await computePrincipalStatePayloadCiphertextHash(payload.ciphertext);
20
- if (hash !== payload.ciphertextHash || hash !== state.payloadCiphertextHash)
18
+ if ((await computePrincipalStatePayloadCiphertextHash(payload.ciphertext)) !==
19
+ state.payloadCiphertextHash)
21
20
  rejectPublicProjection("directory payload differs from its signed hash");
22
21
  const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);
23
22
  if (descriptor.organizationId !== organization.options.organizationId)
@@ -1 +1 @@
1
- {"version":3,"file":"publicProjectionDirectory.js","sourceRoot":"","sources":["publicProjectionDirectory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0CAA0C,GAE3C,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAEL,sBAAsB,EACt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AG,oCAAoC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QAC5E,IAAI,UAAU,CAAC,cAAc,KAAK,YAAY,CAAC,OAAO,CAAC,cAAc;YACnE,sBAAsB,CAAC,2CAA2C,CAAC,CAAC;QACtE,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAC/B,CAAC;IACD,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkD,CAAC;IAC3E,KAAK,MAAM,MAAM,IAAI,QAAQ,CAAC,MAAM,EAAE,CAAC;QACrC,IACE,MAAM,CAAC,IAAI,CAAC,aAAa,KAAK,OAAO;YACrC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC;YAErC,sBAAsB,CAAC,+CAA+C,CAAC,CAAC;QAC1E,MAAM,SAAS,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAC/C,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CACjC,6BAA6B,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CACjD,CACF,CAAC;QACF,MAAM,SAAS,GAAG,SAAS,EAAE,UAAU,CAAC,IAAI,CAC1C,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,YAAY,CACtD,CAAC;QACF,IAAI,CAAC,SAAS;YACZ,sBAAsB,CAAC,iDAAiD,CAAC,CAAC;QAC5E,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n computePrincipalStatePayloadCiphertextHash,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport {\n type PublicProjectionPrincipal,\n rejectPublicProjection,\n selectPublicProjectionPrincipal,\n} from \"./publicProjectionPrincipal\";\n\nexport async function publicProjectionDirectoryBindings(\n evidence: ProjectionPolicyEvidenceResponse,\n organization: PublicProjectionPrincipal,\n) {\n const policies = await selectPublicProjectionPrincipal(organization);\n const entries = policies.flatMap((policy) => policy.retainedHistory);\n const descriptors = [];\n const seen = new Set<string>();\n for (const { reference, payload } of evidence.organizationPayloads) {\n const state = entries.find(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )?.state;\n if (\n !state ||\n reference.version > organization.options.source.head.version ||\n payload.principalType !== \"organization\" ||\n payload.principalId !== organization.options.organizationId ||\n payload.stateHash !== state.stateHash ||\n seen.has(state.stateHash)\n )\n rejectPublicProjection(\"directory payload scope is invalid\");\n seen.add(state.stateHash);\n const hash = await computePrincipalStatePayloadCiphertextHash(\n payload.ciphertext,\n );\n if (hash !== payload.ciphertextHash || hash !== state.payloadCiphertextHash)\n rejectPublicProjection(\"directory payload differs from its signed hash\");\n const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);\n if (descriptor.organizationId !== organization.options.organizationId)\n rejectPublicProjection(\"directory belongs to another organization\");\n descriptors.push(descriptor);\n }\n const bindings = new Map<string, { adminHead: ReferencedPrincipalHead }>();\n for (const source of evidence.groups) {\n if (\n source.head.principalType !== \"group\" ||\n bindings.has(source.head.principalId)\n )\n rejectPublicProjection(\"group sources have invalid or repeated scopes\");\n const directory = descriptors.find((candidate) =>\n candidate.groupHeads.some((head) =>\n principalHeadMatchesReference(head, source.head),\n ),\n );\n const adminHead = directory?.groupHeads.find(\n (head) => head.principalId === directory.adminGroupId,\n );\n if (!adminHead)\n rejectPublicProjection(\"group source lacks its signed directory binding\");\n bindings.set(source.head.principalId, { adminHead });\n }\n return bindings;\n}\n"]}
1
+ {"version":3,"file":"publicProjectionDirectory.js","sourceRoot":"","sources":["publicProjectionDirect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YAE3B,sBAAsB,CAAC,gDAAgD,CAAC,CAAC;QAC3E,MAAM,UAAU,GAAG,oCAAoC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QAC5E,IAAI,UAAU,CAAC,cAAc,KAAK,YAAY,CAAC,OAAO,CAAC,cAAc;YACnE,sBAAsB,CAAC,2CAA2C,CAAC,CAAC;QACtE,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAC/B,CAAC;IACD,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkD,CAAC;IAC3E,KAAK,MAAM,MAAM,IAAI,QAAQ,CAAC,MAAM,EAAE,CAAC;QACrC,IACE,MAAM,CAAC,IAAI,CAAC,aAAa,KAAK,OAAO;YACrC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC;YAErC,sBAAsB,CAAC,+CAA+C,CAAC,CAAC;QAC1E,MAAM,SAAS,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAC/C,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CACjC,6BAA6B,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CACjD,CACF,CAAC;QACF,MAAM,SAAS,GAAG,SAAS,EAAE,UAAU,CAAC,IAAI,CAC1C,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,YAAY,CACtD,CAAC;QACF,IAAI,CAAC,SAAS;YACZ,sBAAsB,CAAC,iDAAiD,CAAC,CAAC;QAC5E,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n computePrincipalStatePayloadCiphertextHash,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport {\n type PublicProjectionPrincipal,\n rejectPublicProjection,\n selectPublicProjectionPrincipal,\n} from \"./publicProjectionPrincipal\";\n\nexport async function publicProjectionDirectoryBindings(\n evidence: ProjectionPolicyEvidenceResponse,\n organization: PublicProjectionPrincipal,\n) {\n const policies = await selectPublicProjectionPrincipal(organization);\n const entries = policies.flatMap((policy) => policy.retainedHistory);\n const descriptors = [];\n const seen = new Set<string>();\n for (const { reference, payload } of evidence.organizationPayloads) {\n const state = entries.find(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )?.state;\n if (\n !state ||\n reference.version > organization.options.source.head.version ||\n state.principalType !== \"organization\" ||\n state.principalId !== organization.options.organizationId ||\n seen.has(state.stateHash)\n )\n rejectPublicProjection(\"directory payload scope is invalid\");\n seen.add(state.stateHash);\n if (\n (await computePrincipalStatePayloadCiphertextHash(payload.ciphertext)) !==\n state.payloadCiphertextHash\n )\n rejectPublicProjection(\"directory payload differs from its signed hash\");\n const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);\n if (descriptor.organizationId !== organization.options.organizationId)\n rejectPublicProjection(\"directory belongs to another organization\");\n descriptors.push(descriptor);\n }\n const bindings = new Map<string, { adminHead: ReferencedPrincipalHead }>();\n for (const source of evidence.groups) {\n if (\n source.head.principalType !== \"group\" ||\n bindings.has(source.head.principalId)\n )\n rejectPublicProjection(\"group sources have invalid or repeated scopes\");\n const directory = descriptors.find((candidate) =>\n candidate.groupHeads.some((head) =>\n principalHeadMatchesReference(head, source.head),\n ),\n );\n const adminHead = directory?.groupHeads.find(\n (head) => head.principalId === directory.adminGroupId,\n );\n if (!adminHead)\n rejectPublicProjection(\"group source lacks its signed directory binding\");\n bindings.set(source.head.principalId, { adminHead });\n }\n return bindings;\n}\n"]}
@@ -86,13 +86,7 @@ export declare function buildInitialRootProvisioning(input: {
86
86
  version: number;
87
87
  };
88
88
  payload: {
89
- cipherSuite: "aes-256-gcm";
90
89
  ciphertext: string;
91
- ciphertextHash: string;
92
- createdAt: string;
93
- principalId: string;
94
- principalType: "group" | "organization";
95
- stateHash: string;
96
90
  };
97
91
  }[];
98
92
  groups: {
@@ -5,13 +5,7 @@ async function principalPolicyBundleFromInitialRequest(principalType, principalI
5
5
  const stateHash = await computePrincipalStateHash(policy.state);
6
6
  return {
7
7
  currentState: { ...policy.state, stateHash, createdAt },
8
- currentPayload: {
9
- principalType,
10
- principalId,
11
- stateHash,
12
- ...policy.encryptedPayload,
13
- createdAt,
14
- },
8
+ currentPayload: { ciphertext: policy.encryptedPayload.ciphertext },
15
9
  currentGrants: policy.grants,
16
10
  currentProjection: policy.projection,
17
11
  currentMemberEnvelopes: {
@@ -1 +1 @@
1
- {"version":3,"file":"registrationPrincipalPolicyPersistence.js","sourceRoot":"","sources":["registrationPrincipalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,2BAA2B,GAE5B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,+BAA+B,EAAE,MAAM,wEAAwE,CAAC;AAGzH,KAAK,UAAU,uCAAuC,CACpD,aAAuC,EACvC,WAAmB,EACnB,MAAiC;IAEjC,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,SAAS,GAAG,MAAM,yBAAyB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAEhE,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QACvD,cAAc,EAAE;YACd,aAAa;YACb,WAAW;YACX,SAAS;YACT,GAAG,MAAM,CAAC,gBAAgB;YAC1B,SAAS;SACV;QACD,aAAa,EAAE,MAAM,CAAC,MAAM;QAC5B,iBAAiB,EAAE,MAAM,CAAC,UAAU;QACpC,sBAAsB,EAAE;YACtB,a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AC7B;SACF;QACD,UAAU,EAAE;YACV,aAAa,EAAE,MAAM,CAAC,YAAY,CAAC,aAAa;YAChD,WAAW,EAAE,MAAM,CAAC,YAAY,CAAC,WAAW;YAC5C,OAAO,EAAE,MAAM,CAAC,YAAY,CAAC,OAAO;YACpC,SAAS,EAAE,MAAM,CAAC,YAAY,CAAC,SAAS;SACzC;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAK1D;IACC,MAAM,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,6CAA6C,CAAC;QAC9C,OAAO,EAAE,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC,GAAG,CACpE,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YACX,MAAM;YACN,MAAM,EAAE,iCAAiC,CAAC,MAAM,CAAC;SAClD,CAAC,CACH;QACD,cAAc,EAAE,KAAK,CAAC,YAAY,CAAC,YAAY,CAAC,WAAW;KAC5D,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computePrincipalStateHash,\n makeVerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n PutPrincipalPolicyRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { PrincipalPolicyBundleRepository } from \"../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nasync function principalPolicyBundleFromInitialRequest(\n principalType: \"group\" | \"organization\",\n principalId: string,\n policy: PutPrincipalPolicyRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n const createdAt = new Date().toISOString();\n const stateHash = await computePrincipalStateHash(policy.state);\n\n return {\n currentState: { ...policy.state, stateHash, createdAt },\n currentPayload: {\n principalType,\n principalId,\n stateHash,\n ...policy.encryptedPayload,\n createdAt,\n },\n currentGrants: policy.grants,\n currentProjection: policy.projection,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: policy.state.keyEpoch,\n envelopes: policy.memberEnvelopes,\n },\n previousStates: [],\n };\n}\n\nexport async function principalPolicyBundleFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"group\",\n input.groupId,\n input.initialGroupPolicy,\n );\n}\n\nexport async function principalPolicyBundleFromInitialOrganizationRequest(\n input: RegistrationRequest[\"initialOrganizationPolicy\"],\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"organization\",\n input.state.principalId,\n input,\n );\n}\n\nexport async function verifiedPrincipalPolicyFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<VerifiedPrincipalPolicy> {\n const bundle = await principalPolicyBundleFromInitialGroupRequest(input);\n\n return verifiedPrincipalPolicyFromBundle(bundle);\n}\n\nfunction verifiedPrincipalPolicyFromBundle(\n bundle: PrincipalPolicyBundleResponse,\n): VerifiedPrincipalPolicy {\n return makeVerifiedPrincipalPolicy({\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n keyEpoch: bundle.currentState.keyEpoch,\n stateHash: bundle.currentState.stateHash,\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n history: [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ],\n checkpoint: {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n stateHash: bundle.currentState.stateHash,\n },\n });\n}\n\nexport async function persistRegistrationPrincipalPolicies(input: {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}): Promise<void> {\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).seedLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input.adminGroup, input.memberGroup, input.organization].map(\n (bundle) => ({\n bundle,\n policy: verifiedPrincipalPolicyFromBundle(bundle),\n }),\n ),\n organizationId: input.organization.currentState.principalId,\n });\n}\n"]}
1
+ {"version":3,"file":"registrationPrincipalPolicyPersistence.js","sourceRoot":"","sources":["registrationPrincipalPolicyPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,2BAA2B,GAE5B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,+BAA+B,EAAE,MAAM,wEAAwE,CAAC;AAGzH,KAAK,UAAU,uCAAuC,CACpD,aAAuC,EACvC,WAAmB,EACnB,MAAiC;IAEjC,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,SAAS,GAAG,MAAM,yBAAyB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAEhE,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QACvD,cAAc,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE;QAClE,aAAa,EAAE,MAAM,CAAC,MAAM;QAC5B,iBAAiB,EAAE,MAAM,CAAC,UAAU;QACpC,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,QAAQ;YAC5B,SAAS,EAAE,MAAM,CAAC,eAAe;SAClC;QACD,cAAc,EAAE,EAAE;KACnB,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAChE,KAAqC;IAErC,OAAO,uCAAuC,CAC5C,OAAO,EACP,KAAK,CAAC,OAAO,EACb,KAAK,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oCAAoC,CAAC,KAK1D;IACC,MAAM,IAAI,+BAA+B,CACvC,KAAK,CAAC,OAAO,CACd,CAAC,6CAA6C,CAAC;QAC9C,OAAO,EAAE,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,WAAW,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC,GAAG,CACpE,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;YACX,MAAM;YACN,MAAM,EAAE,iCAAiC,CAAC,MAAM,CAAC;SAClD,CAAC,CACH;QACD,cAAc,EAAE,KAAK,CAAC,YAAY,CAAC,YAAY,CAAC,WAAW;KAC5D,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computePrincipalStateHash,\n makeVerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n PutPrincipalPolicyRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { PrincipalPolicyBundleRepository } from \"../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nasync function principalPolicyBundleFromInitialRequest(\n principalType: \"group\" | \"organization\",\n principalId: string,\n policy: PutPrincipalPolicyRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n const createdAt = new Date().toISOString();\n const stateHash = await computePrincipalStateHash(policy.state);\n\n return {\n currentState: { ...policy.state, stateHash, createdAt },\n currentPayload: { ciphertext: policy.encryptedPayload.ciphertext },\n currentGrants: policy.grants,\n currentProjection: policy.projection,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: policy.state.keyEpoch,\n envelopes: policy.memberEnvelopes,\n },\n previousStates: [],\n };\n}\n\nexport async function principalPolicyBundleFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"group\",\n input.groupId,\n input.initialGroupPolicy,\n );\n}\n\nexport async function principalPolicyBundleFromInitialOrganizationRequest(\n input: RegistrationRequest[\"initialOrganizationPolicy\"],\n): Promise<PrincipalPolicyBundleResponse> {\n return principalPolicyBundleFromInitialRequest(\n \"organization\",\n input.state.principalId,\n input,\n );\n}\n\nexport async function verifiedPrincipalPolicyFromInitialGroupRequest(\n input: CreateOrganizationGroupRequest,\n): Promise<VerifiedPrincipalPolicy> {\n const bundle = await principalPolicyBundleFromInitialGroupRequest(input);\n\n return verifiedPrincipalPolicyFromBundle(bundle);\n}\n\nfunction verifiedPrincipalPolicyFromBundle(\n bundle: PrincipalPolicyBundleResponse,\n): VerifiedPrincipalPolicy {\n return makeVerifiedPrincipalPolicy({\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n keyEpoch: bundle.currentState.keyEpoch,\n stateHash: bundle.currentState.stateHash,\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n history: [\n ...bundle.previousStates,\n {\n state: bundle.currentState,\n projection: bundle.currentProjection,\n grants: bundle.currentGrants,\n },\n ],\n checkpoint: {\n principalType: bundle.currentState.principalType,\n principalId: bundle.currentState.principalId,\n version: bundle.currentState.version,\n stateHash: bundle.currentState.stateHash,\n },\n });\n}\n\nexport async function persistRegistrationPrincipalPolicies(input: {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}): Promise<void> {\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).seedLocallyAcknowledgedPrincipalPolicyBundles({\n entries: [input.adminGroup, input.memberGroup, input.organization].map(\n (bundle) => ({\n bundle,\n policy: verifiedPrincipalPolicyFromBundle(bundle),\n }),\n ),\n organizationId: input.organization.currentState.principalId,\n });\n}\n"]}