@tearleads/client-sdk 0.1.54 → 0.1.55
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.
- package/package.json +1 -1
- package/workflows/containers/child/runtimeCurrentGroupShare.js +5 -8
- package/workflows/containers/child/runtimeCurrentGroupShare.js.map +1 -1
- package/workflows/organizations/currentOrganizationMutationRetention.js +1 -1
- package/workflows/organizations/currentOrganizationMutationRetention.js.map +1 -1
- package/workflows/organizations/currentPrincipalMutationLease.js +5 -4
- package/workflows/organizations/currentPrincipalMutationLease.js.map +1 -1
- package/workflows/organizations/runtimeCurrentGroupMutation.js +4 -4
- package/workflows/organizations/runtimeCurrentGroupMutation.js.map +1 -1
- package/workflows/organizations/runtimeCurrentOrganizationMutation.js +2 -2
- package/workflows/organizations/runtimeCurrentOrganizationMutation.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryTypes.d.ts +3 -2
- package/workflows/principals/principalHistoryRecoveryTypes.js.map +1 -1
- package/workflows/principals/principalPolicyHistoryReader.d.ts +20 -0
- package/workflows/principals/principalPolicyHistoryReader.js +13 -0
- package/workflows/principals/principalPolicyHistoryReader.js.map +1 -0
- package/workflows/principals/principalRecoveryDirectory.js +6 -6
- package/workflows/principals/principalRecoveryDirectory.js.map +1 -1
- package/workflows/principals/principalRecoveryDiscoveryPage.js +4 -4
- package/workflows/principals/principalRecoveryDiscoveryPage.js.map +1 -1
- package/workflows/principals/publicPrincipalHistoryTypes.d.ts +2 -2
- package/workflows/principals/publicPrincipalHistoryTypes.js.map +1 -1
- package/workflows/principals/recoverPrincipalPolicyHistory.js +1 -1
- package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/recoverPublicPrincipalHistory.js +1 -1
- package/workflows/principals/recoverPublicPrincipalHistory.js.map +1 -1
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +1 -1
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/runtimePolicyRecovery.js +4 -3
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
- package/workflows/principals/runtimeProjectionPolicyRecovery.js +4 -3
- package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
- package/workflows/registration/provisionedPrincipalHistory.js +1 -1
- package/workflows/registration/provisionedPrincipalHistory.js.map +1 -1
package/package.json
CHANGED
|
@@ -2,6 +2,7 @@ import { nullOnProjectionVerificationCancellation, requireProjectionUserKeyResol
|
|
|
2
2
|
import { principalPolicyCacheForVerifiedPolicies } from "../../../data/keyingProjectionVerification/principalPolicyCache.js";
|
|
3
3
|
import { inheritPrincipalHistoryProtection } from "../../../data/principals/principalHistoryRuntime.js";
|
|
4
4
|
import { createRuntimeCurrentGroupMutation } from "../../organizations/runtimeCurrentGroupMutation.js";
|
|
5
|
+
import { apiPrincipalPolicyPageReader, apiProjectionPolicyHistoryReader, } from "../../principals/principalPolicyHistoryReader.js";
|
|
5
6
|
import { commitCurrentShareGrant } from "./currentShareGrantMutation.js";
|
|
6
7
|
import { createRuntimeCurrentSharePrincipalPolicy } from "./currentSharePrincipalPolicy.js";
|
|
7
8
|
import { submitAcknowledgedContainerMutation, submitPlainContainerMutation, } from "./mutationSubmit.js";
|
|
@@ -11,18 +12,14 @@ import { resolveShareProjection } from "./shareProjection.js";
|
|
|
11
12
|
export function createRuntimeCurrentGroupShare(runtime) {
|
|
12
13
|
const readCurrent = createRuntimeCurrentSharePrincipalPolicy(runtime);
|
|
13
14
|
const api = runtime.apiClient;
|
|
14
|
-
const
|
|
15
|
-
if (!readCurrent || !
|
|
15
|
+
const historyReader = apiPrincipalPolicyPageReader(api);
|
|
16
|
+
if (!readCurrent || !historyReader)
|
|
16
17
|
return undefined;
|
|
17
18
|
const mutate = createRuntimeCurrentGroupMutation(inheritPrincipalHistoryProtection(runtime, {
|
|
18
19
|
...runtime,
|
|
19
20
|
apiClient: {
|
|
20
|
-
|
|
21
|
-
...(api
|
|
22
|
-
? {
|
|
23
|
-
getProjectionPolicyHistoryPages: api.getProjectionPolicyHistoryPages.bind(api),
|
|
24
|
-
}
|
|
25
|
-
: {}),
|
|
21
|
+
...historyReader,
|
|
22
|
+
...apiProjectionPolicyHistoryReader(api),
|
|
26
23
|
recoverPendingPrincipalMutation: async (organizationId) => {
|
|
27
24
|
// Built-in clients supply journal recovery; standalone hosts retain
|
|
28
25
|
// responsibility for transport and exact-outcome recovery.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtimeCurrentGroupShare.js","sourceRoot":"","sources":["runtimeCurrentGroupShare.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wCAAwC,EACxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,uCAAuC,EAAE,MAAM,iEAAiE,CAAC;AAC1H,OAAO,EAAE,iCAAiC,EAAE,MAAM,kDAAkD,CAAC;AACrG,OAAO,EAAE,iCAAiC,EAAE,MAAM,iDAAiD,CAAC;AACpG,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,wCAAwC,EAAE,MAAM,+BAA+B,CAAC;AACzF,OAAO,EACL,mCAAmC,EACnC,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,mCAAmC,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAE3D,sFAAsF;AACtF,MAAM,UAAU,8BAA8B,CAC5C,OAAuE;IAEvE,MAAM,WAAW,GAAG,wCAAwC,CAAC,OAAO,CAAC,CAAC;IACtE,MAAM,GAAG,GAAG,OAAO,CAAC,SAAS,CAAC;IAC9B,MAAM,
|
|
1
|
+
{"version":3,"file":"runtimeCurrentGroupShare.js","sourceRoot":"","sources":["runtimeCurrentGroupShare.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wCAAwC,EACxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,E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AClB,uCAAuC,CAAC,kBAAkB,CAAC;gBAC7D,SAAS,EAAE;oBACT,eAAe,EAAE,MAAM;oBACvB,SAAS,EAAE,KAAK,CAAC,gBAAgB;oBACjC,WAAW,EAAE,OAAO;iBACrB;gBACD,wBAAwB;aACzB,CAAC,CAAC;YACH,OAAO,mCAAmC,CAAC;gBACzC,GAAG,KAAK;gBACR,kBAAkB,EAAE,kBAAkB;gBACtC,sBAAsB;gBACtB,YAAY,EAAE,YAAY,CAAC,YAAY;gBACvC,IAAI,EAAE,YAAY,CAAC,IAAI;gBACvB,MAAM,EAAE,GAAG,EAAE,CACX,4BAA4B,CAAC,GAAG,EAAE,CAChC,KAAK,CAAC,SAAS,CAAC,cAAc,CAC5B,KAAK,CAAC,WAAW,EACjB,YAAY,CAAC,IAAI,CAAC,OAAO,EACzB;oBACE,qCAAqC,EACnC,KAAK,CAAC,MAAM,CAAC,cAAc;iBAC9B,CACF,CACF;aACJ,CAAC,CAAC;QACL,CAAC,CACF,CACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n nullOnProjectionVerificationCancellation,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { inheritPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryRuntime\";\nimport { createRuntimeCurrentGroupMutation } from \"../../organizations/runtimeCurrentGroupMutation\";\nimport {\n apiPrincipalPolicyPageReader,\n apiProjectionPolicyHistoryReader,\n} from \"../../principals/principalPolicyHistoryReader\";\nimport { commitCurrentShareGrant } from \"./currentShareGrantMutation\";\nimport { createRuntimeCurrentSharePrincipalPolicy } from \"./currentSharePrincipalPolicy\";\nimport {\n submitAcknowledgedContainerMutation,\n submitPlainContainerMutation,\n} from \"./mutationSubmit\";\nimport type { shareRemoteContainerWithGroup } from \"./share\";\nimport { buildMaterializedContainerSharePlan } from \"./shareMaterialization\";\nimport { resolveShareProjection } from \"./shareProjection\";\n\n/** Current evidence covers planning, any compound grant mint, and acknowledgement. */\nexport function createRuntimeCurrentGroupShare(\n runtime: Parameters<typeof createRuntimeCurrentSharePrincipalPolicy>[0],\n): typeof shareRemoteContainerWithGroup | undefined {\n const readCurrent = createRuntimeCurrentSharePrincipalPolicy(runtime);\n const api = runtime.apiClient;\n const historyReader = apiPrincipalPolicyPageReader(api);\n if (!readCurrent || !historyReader) return undefined;\n const mutate = createRuntimeCurrentGroupMutation(\n inheritPrincipalHistoryProtection(runtime, {\n ...runtime,\n apiClient: {\n ...historyReader,\n ...apiProjectionPolicyHistoryReader(api),\n recoverPendingPrincipalMutation: async (organizationId: string) => {\n // Built-in clients supply journal recovery; standalone hosts retain\n // responsibility for transport and exact-outcome recovery.\n await api.recoverPendingPrincipalMutation?.(organizationId);\n },\n },\n }),\n );\n if (!mutate) throw new Error(\"Current group mutation custody is unavailable\");\n return async (input) => {\n if (input.stillCurrent?.() === false) return null;\n const recitationStillCurrent = input.stillCurrent ?? (() => true);\n return nullOnProjectionVerificationCancellation(() =>\n readCurrent(\n {\n expectedGroupName: input.expectedGroupName ?? undefined,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n },\n async ({ policy, checkpointPolicies, stillCurrent }) => {\n const share = { ...input, stillCurrent };\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const previousProjection = await resolveShareProjection(\n share,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n const grant = policy.grants.find(\n (candidate) => candidate.containerId === input.containerId,\n );\n if (!grant || grant.accessLevel !== input.accessLevel)\n return commitCurrentShareGrant({\n runtime,\n share,\n mutate,\n recitationStillCurrent,\n });\n const materialized = await buildMaterializedContainerSharePlan({\n ...share,\n previousProjection,\n principalPolicyCache:\n principalPolicyCacheForVerifiedPolicies(checkpointPolicies),\n recipient: {\n principalPolicy: policy,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n },\n resolveProjectionUserKey,\n });\n return submitAcknowledgedContainerMutation({\n ...share,\n recitationPolicies: checkpointPolicies,\n recitationStillCurrent,\n containerKey: materialized.containerKey,\n plan: materialized.plan,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materialized.plan.request,\n {\n expectedPaymentRequiredOrganizationId:\n input.author.organizationId,\n },\n ),\n ),\n });\n },\n ),\n );\n };\n}\n"]}
|
|
@@ -36,7 +36,7 @@ export async function createCurrentOrganizationMutationRetention(input) {
|
|
|
36
36
|
request: receipt.request,
|
|
37
37
|
response: receipt.response,
|
|
38
38
|
recovery: {
|
|
39
|
-
|
|
39
|
+
historyReader: input.historyReader,
|
|
40
40
|
expectedHead: principalPolicyReferenceFromBundle(receipt.response),
|
|
41
41
|
protection: scopedGroupHistoryProtection(input.protection, input.organizationId, input.authority.descriptor.adminGroupId),
|
|
42
42
|
resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currentOrganizationMutationRetention.js","sourceRoot":"","sources":["currentOrganizationMutationRetention.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"currentOrganizationMutationRetention.js","sourceRoot":"","sources":["currentOrganizationMutationRetention.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,4BAA4B,EAAE,MAAM,uDAAuD,CAAC;AACrG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAGvG,OAAO,EAAE,uCAAuC,EAAE,MAAM,oCAAoC,CAAC;AAE7F,OAAO,EAEL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC;AAE/C,yFAAyF;AACzF,MAAM,CAAC,KAAK,UAAU,0CAA0C,CAAC,KAUhE;IACC,MAAM,WAAW,GAAG,MAAM,uCAAuC,CAA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CAAC,UAAU,CAAC,YAAY,CACxC;wBACD,0BAA0B,EACxB,KAAK,CAAC,OAAO,CAAC,0BAA0B;wBAC1C,qBAAqB,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC;4BAClC,WAAW,EAAE,SAAS;4BACtB,MAAM,EAAE;gCACN;oCACE,IAAI,EAAE,SAAS;oCACf,UAAU,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU;iCACrD;6BACF;yBACF,CAAC;qBACH;iBACF;gBACD;oBACE,WAAW;oBACX,OAAO,EAAE,OAAO,CAAC,mBAAmB;oBACpC,QAAQ,EAAE,OAAO,CAAC,oBAAoB;oBACtC,QAAQ,EAAE,KAAK,CAAC,iBAAiB;iBAClC;aACF,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { scopedGroupHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyPageReader } from \"../principals/principalPolicyHistoryReader\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"../principals/runtimePolicyRecovery\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"./acknowledgedPrincipalPredecessor\";\nimport type { loadCurrentOrganizationAuthority } from \"./currentOrganizationAuthority\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\n/** Couple directory acknowledgements to any newly created group under the same lease. */\nexport async function createCurrentOrganizationMutationRetention(input: {\n readonly runtime: PrincipalPolicyRecoveryRuntime;\n readonly authority: Awaited<\n ReturnType<typeof loadCurrentOrganizationAuthority>\n >;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly organizationId: string;\n readonly directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"];\n readonly stillCurrent: () => boolean;\n}) {\n const predecessor = await captureAcknowledgedPrincipalPredecessor({\n ...input.directoryRecovery,\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n const retain = async (\n entries: readonly AcknowledgedPrincipalCurrentInput[],\n ) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n entries,\n stillCurrent: input.stillCurrent,\n });\n };\n return {\n retainDirectory: (\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n ) =>\n retain([\n { predecessor, request, response, recovery: input.directoryRecovery },\n ]),\n retainCreatedGroup: (receipt: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly organizationResponse: PrincipalPolicyMutationResponse;\n }) => {\n const adminHead = {\n ...principalPolicyReferenceFromBundle(input.authority.admins.current),\n principalType: \"group\" as const,\n };\n return retain([\n {\n initialGroup: true,\n predecessor: null,\n request: receipt.request,\n response: receipt.response,\n recovery: {\n historyReader: input.historyReader,\n expectedHead: principalPolicyReferenceFromBundle(receipt.response),\n protection: scopedGroupHistoryProtection(\n input.protection,\n input.organizationId,\n input.authority.descriptor.adminGroupId,\n ),\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n loadExternalAuthority: async () => ({\n currentHead: adminHead,\n states: [\n {\n head: adminHead,\n projection: input.authority.admins.policy.projection,\n },\n ],\n }),\n },\n },\n {\n predecessor,\n request: receipt.organizationRequest,\n response: receipt.organizationResponse,\n recovery: input.directoryRecovery,\n },\n ]);\n },\n };\n}\n"]}
|
|
@@ -2,13 +2,14 @@ import { assertProjectionVerificationCurrent } from "../../data/keyingProjection
|
|
|
2
2
|
import { readPrincipalHistoryProtection } from "../../data/principals/principalHistoryRuntime.js";
|
|
3
3
|
import { directoryHistoryProtection } from "../../data/principals/principalHistoryScopeProtection.js";
|
|
4
4
|
import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
|
|
5
|
+
import { apiPrincipalPolicyPageReader, } from "../principals/principalPolicyHistoryReader.js";
|
|
5
6
|
import { createRuntimePrincipalPolicyCurrentResolver, } from "../principals/runtimePolicyRecovery.js";
|
|
6
7
|
/** One lifetime fence and private custody boundary for every current-policy mutation. */
|
|
7
8
|
export function createCurrentPrincipalMutationLease(runtime) {
|
|
8
9
|
const lease = readPrincipalHistoryProtection(runtime);
|
|
9
10
|
const resolveCurrentPolicy = createRuntimePrincipalPolicyCurrentResolver(runtime);
|
|
10
|
-
const
|
|
11
|
-
if (!lease || !resolveCurrentPolicy || !
|
|
11
|
+
const historyReader = apiPrincipalPolicyPageReader(runtime.apiClient);
|
|
12
|
+
if (!lease || !resolveCurrentPolicy || !historyReader)
|
|
12
13
|
return undefined;
|
|
13
14
|
return async (callerCurrent, work) => lease(async ({ protection, stillCurrent: leaseCurrent }) => {
|
|
14
15
|
let active = true;
|
|
@@ -19,9 +20,9 @@ export function createCurrentPrincipalMutationLease(runtime) {
|
|
|
19
20
|
protection,
|
|
20
21
|
stillCurrent,
|
|
21
22
|
resolveCurrentPolicy,
|
|
22
|
-
|
|
23
|
+
historyReader,
|
|
23
24
|
directoryRecovery: (current) => ({
|
|
24
|
-
|
|
25
|
+
historyReader,
|
|
25
26
|
expectedHead: principalPolicyReferenceFromBundle(current),
|
|
26
27
|
protection: directoryHistoryProtection(protection),
|
|
27
28
|
resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currentPrincipalMutationLease.js","sourceRoot":"","sources":["currentPrincipalMutationLease.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EAAE,0BAA0B,EAAE,MAAM,uDAAuD,CAAC;AACnG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EACL,2CAA2C,GAE5C,MAAM,qCAAqC,CAAC;
|
|
1
|
+
{"version":3,"file":"currentPrincipalMutationLease.js","sourceRoot":"","sources":["currentPrincipalMutationLease.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EAAE,0BAA0B,EAAE,MAAM,uDAAuD,CAAC;AACnG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EACL,4BAA4B,GAE7B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,2CAA2C,GAE5C,MAAM,qCAAqC,CAAC;AAoB7C,yFAAyF;AACzF,MAAM,UAAU,mCAAmC,CACjD,OAAuC;IAEvC,MAAM,KAAK,GAAG,8BAA8B,CAAC,OAAO,CAAC,CAAC;IACtD,MAAM,oBAAoB,GACxB,2CAA2C,CAAC,OAAO,CAAC,CAAC;IACvD,MAAM,aAAa,GAAG,4BAA4B,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACtE,IAAI,CAAC,KAAK,IAAI,CAAC,oBAAoB,IAAI,CAAC,aAAa;QAAE,OAAO,SAAS,CAAC;IACxE,OAAO,KAAK,EACV,aAA4B,EAC5B,IAAmE,EACvD,EAAE,CACd,KAAK,CAAC,KAAK,EAAE,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,EAAE,EAAE;QACzD,IAAI,MAAM,GAAG,IAAI,CAAC;QAClB,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,MAAM,IAAI,YAAY,EAAE,IAAI,aAAa,EAAE,CAAC;QACvE,IAAI,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC;gBACxB,UAAU;gBACV,YAAY;gBACZ,oBAAoB;gBACpB,aAAa;gBACb,iBAAiB,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;oBAC/B,aAAa;oBACb,YAAY,EAAE,kCAAkC,CAAC,OAAO,CAAC;oBACzD,UAAU,EAAE,0BAA0B,CAAC,UAAU,CAAC;oBAClD,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;iBAC/D,CAAC;aACH,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,OAAO,MAAM,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,MAAM,GAAG,KAAK,CAAC;QACjB,CAAC;IACH,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport { directoryHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyPageReader,\n} from \"../principals/principalPolicyHistoryReader\";\nimport {\n createRuntimePrincipalPolicyCurrentResolver,\n type PrincipalPolicyRecoveryRuntime,\n} from \"../principals/runtimePolicyRecovery\";\nimport type { AcknowledgedPrincipalCurrentInput } from \"./retainAcknowledgedPrincipalCurrents\";\n\ninterface CurrentPrincipalMutationLeaseContext {\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly stillCurrent: () => boolean;\n readonly resolveCurrentPolicy: NonNullable<\n ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>\n >;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly directoryRecovery: (\n current: PrincipalPolicyPageCurrent,\n ) => AcknowledgedPrincipalCurrentInput[\"recovery\"];\n}\n\ntype CurrentPrincipalMutationLease = <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n) => Promise<T>;\n\n/** One lifetime fence and private custody boundary for every current-policy mutation. */\nexport function createCurrentPrincipalMutationLease(\n runtime: PrincipalPolicyRecoveryRuntime,\n): CurrentPrincipalMutationLease | undefined {\n const lease = readPrincipalHistoryProtection(runtime);\n const resolveCurrentPolicy =\n createRuntimePrincipalPolicyCurrentResolver(runtime);\n const historyReader = apiPrincipalPolicyPageReader(runtime.apiClient);\n if (!lease || !resolveCurrentPolicy || !historyReader) return undefined;\n return async <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n ): Promise<T> =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n let active = true;\n const stillCurrent = () => active && leaseCurrent() && callerCurrent();\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await work({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery: (current) => ({\n historyReader,\n expectedHead: principalPolicyReferenceFromBundle(current),\n protection: directoryHistoryProtection(protection),\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n }),\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n active = false;\n }\n });\n}\n"]}
|
|
@@ -13,7 +13,7 @@ export function createRuntimeCurrentGroupMutation(runtime) {
|
|
|
13
13
|
return undefined;
|
|
14
14
|
return async (input, work) => {
|
|
15
15
|
input = { ...input };
|
|
16
|
-
return lease(input.stillCurrent, async ({ protection, stillCurrent, resolveCurrentPolicy,
|
|
16
|
+
return lease(input.stillCurrent, async ({ protection, stillCurrent, resolveCurrentPolicy, historyReader, directoryRecovery, }) => {
|
|
17
17
|
const loadGroup = async (groupId) => {
|
|
18
18
|
const context = await loadCurrentGroupPolicyMutationContext({
|
|
19
19
|
...input,
|
|
@@ -23,7 +23,7 @@ export function createRuntimeCurrentGroupMutation(runtime) {
|
|
|
23
23
|
recoverPendingPrincipalMutation: (organizationId) => runtime.apiClient.recoverPendingPrincipalMutation(organizationId),
|
|
24
24
|
stillCurrent,
|
|
25
25
|
});
|
|
26
|
-
const retention = await createCurrentMutationRetention(runtime, { ...input, groupId }, context, protection,
|
|
26
|
+
const retention = await createCurrentMutationRetention(runtime, { ...input, groupId }, context, protection, historyReader, directoryRecovery(context.organizationCurrent.current));
|
|
27
27
|
return {
|
|
28
28
|
...context,
|
|
29
29
|
...retention,
|
|
@@ -44,9 +44,9 @@ export function createRuntimeCurrentGroupMutation(runtime) {
|
|
|
44
44
|
});
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
|
-
async function createCurrentMutationRetention(runtime, input, context, protection,
|
|
47
|
+
async function createCurrentMutationRetention(runtime, input, context, protection, historyReader, directoryRecovery) {
|
|
48
48
|
const common = {
|
|
49
|
-
|
|
49
|
+
historyReader,
|
|
50
50
|
resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,
|
|
51
51
|
};
|
|
52
52
|
const groupRecovery = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtimeCurrentGroupMutation.js","sourceRoot":"","sources":["runtimeCurrentGroupMutation.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,4BAA4B,EAAE,MAAM,uDAAuD,CAAC;AACrG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAEvG,OAAO,EAAE,uCAAuC,EAAE,MAAM,oCAAoC,CAAC;AAC7F,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,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H;oBACE,WAAW,EAAE,KAAK,CAAC,OAAO;oBAC1B,aAAa,EAAE,OAAO;oBACtB,YAAY,EAAE,OAAO,CAAC,mBAAmB,IAAI,EAAE;iBAChD;aACF;YACD,YAAY,EAAE,OAAO,CAAC,YAAY;SACnC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO;QACL,cAAc,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE;QAC1E,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { CurrentPolicyReferenceResolver } from \"../../data/principals/currentPolicyReferenceResolver\";\nimport { scopedGroupHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"../principals/runtimePolicyRecovery\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"./acknowledgedPrincipalPredecessor\";\nimport { resolveCurrentGroupMutationReferences } from \"./currentGroupMutationReferences\";\nimport { loadCurrentGroupPolicyMutationContext } from \"./currentGroupPolicyMutationContext\";\nimport { createCurrentPrincipalMutationLease } from \"./currentPrincipalMutationLease\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\ntype MutationRuntime = PrincipalPolicyRecoveryRuntime & {\n readonly apiClient: PrincipalPolicyRecoveryRuntime[\"apiClient\"] &\n Pick<PrincipalMutationRecoveryApi, \"recoverPendingPrincipalMutation\">;\n};\n\ntype CurrentMutationContext = Awaited<\n ReturnType<typeof loadCurrentGroupPolicyMutationContext>\n>;\n\nexport type RuntimeCurrentGroupMutationContext = CurrentMutationContext & {\n readonly resolveAuthoredPolicyReferences: CurrentPolicyReferenceResolver;\n readonly loadGroup: (\n groupId: string,\n ) => Promise<RuntimeCurrentGroupMutationContext>;\n readonly groupRetention: Pick<\n AcknowledgedPrincipalCurrentInput,\n \"recovery\" | \"predecessor\"\n >;\n readonly retainAcknowledged: (\n receipt: CurrentMutationReceipt,\n ) => Promise<void>;\n};\n\ninterface CurrentMutationReceipt {\n readonly additionalGroups?:\n | readonly (AcknowledgedPrincipalCurrentInput & {\n readonly retiredContainerIds?: readonly string[] | undefined;\n })[]\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly response: CommitOrganizationGroupPolicyResponse;\n readonly retiredContainerIds?: readonly string[] | undefined;\n}\n\ninterface MutationInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/** Keep private prefix custody inside the entire mutation and its acknowledgement. */\nexport function createRuntimeCurrentGroupMutation(runtime: MutationRuntime) {\n const lease = createCurrentPrincipalMutationLease(runtime);\n if (!lease) return undefined;\n return async <T>(\n input: MutationInput,\n work: (context: RuntimeCurrentGroupMutationContext) => Promise<T>,\n ): Promise<T> => {\n input = { ...input };\n return lease(\n input.stillCurrent,\n async ({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n readPages,\n directoryRecovery,\n }) => {\n const loadGroup = async (\n groupId: string,\n ): Promise<RuntimeCurrentGroupMutationContext> => {\n const context = await loadCurrentGroupPolicyMutationContext({\n ...input,\n groupId,\n execSql: runtime.infra.execSql,\n resolveCurrentPolicy,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n stillCurrent,\n });\n const retention = await createCurrentMutationRetention(\n runtime,\n { ...input, groupId },\n context,\n protection,\n readPages,\n directoryRecovery(context.organizationCurrent.current),\n );\n return {\n ...context,\n ...retention,\n loadGroup,\n resolveAuthoredPolicyReferences: (current, references) =>\n resolveCurrentGroupMutationReferences({\n current,\n predecessor: context.verifiedCurrentPolicy,\n references,\n readPredecessorReference: context.readPredecessorReference,\n stillCurrent: context.stillCurrent,\n }),\n };\n };\n const context = await loadGroup(input.groupId);\n const result = await work(context);\n assertProjectionVerificationCurrent(context.stillCurrent);\n return result;\n },\n );\n };\n}\n\nasync function createCurrentMutationRetention(\n runtime: MutationRuntime,\n input: MutationInput,\n context: CurrentMutationContext,\n protection: PrincipalPolicyHistoryProgressOptions,\n readPages: ApiClient[\"getPrincipalPolicyPages\"],\n directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"],\n) {\n const common = {\n apiClient: { getPrincipalPolicyPages: readPages },\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n };\n const groupRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"] = {\n ...common,\n expectedHead: principalPolicyReferenceFromBundle(context.currentPolicy),\n protection: context.isOrganizationAdminsGroup\n ? protection\n : scopedGroupHistoryProtection(\n protection,\n input.organizationId,\n context.adminGroupId,\n ),\n historyVerification: context.isOrganizationAdminsGroup\n ? \"direct-admins\"\n : \"standard\",\n ...(context.isOrganizationAdminsGroup\n ? {}\n : { loadExternalAuthority: async () => context.externalAuthority }),\n };\n const capture = (recovery: AcknowledgedPrincipalCurrentInput[\"recovery\"]) =>\n captureAcknowledgedPrincipalPredecessor({\n ...recovery,\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: context.stillCurrent,\n });\n const groupPredecessor = await capture(groupRecovery);\n const directoryPredecessor = await capture(directoryRecovery);\n const retainAcknowledged = async (\n receipt: CurrentMutationReceipt,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(context.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n entries: [\n ...(receipt.additionalGroups ?? []),\n {\n recovery: groupRecovery,\n predecessor: groupPredecessor,\n request: receipt.request,\n response: receipt.response.groupPolicy,\n },\n {\n recovery: directoryRecovery,\n predecessor: directoryPredecessor,\n request: receipt.organizationRequest,\n response: receipt.response.organizationPolicy,\n },\n ],\n retirements: [\n ...(receipt.additionalGroups ?? []).map((entry) => ({\n principalId: entry.request.state.principalId,\n principalType: \"group\" as const,\n containerIds: entry.retiredContainerIds ?? [],\n })),\n {\n principalId: input.groupId,\n principalType: \"group\",\n containerIds: receipt.retiredContainerIds ?? [],\n },\n ],\n stillCurrent: context.stillCurrent,\n });\n };\n return {\n groupRetention: { recovery: groupRecovery, predecessor: groupPredecessor },\n retainAcknowledged,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtimeCurrentGroupMutation.js","sourceRoot":"","sources":["runtimeCurrentGroupMutation.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,4BAA4B,EAAE,MAAM,uDAAuD,CAAC;AACrG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAGvG,OAAO,EAAE,uCAAuC,EAAE,MAAM,oCAAoC,CAAC;AAC7F,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EAAE,qCAAqC,EAAE,MAAM,qCAAqC,CAAC;AAC5F,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AAEtF,OAAO,EAEL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC;AA4C/C,sFAAsF;AACtF,MAAM,UAAU,iCAAiC,CAAC,OAAwB;IACxE,MAAM,KAAK,GAAG,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC3D,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,KAAK,EACV,KAAoB,EACpB,IAAiE,EACrD,EAAE;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C,CAAC;QAC1D,MAAM,mCAAmC,CAAC;YACxC,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;YAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,OAAO,EAAE;gBACP,GAAG,CAAC,OAAO,CAAC,gBAAgB,IAAI,EAAE,CAAC;gBACnC;oBACE,QAAQ,EAAE,aAAa;oBACvB,WAAW,EAAE,gBAAgB;oBAC7B,OAAO,EAAE,OAAO,CAAC,OAAO;oBACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,WAAW;iBACvC;gBACD;oBACE,QAAQ,EAAE,iBAAiB;oBAC3B,WAAW,EAAE,oBAAoB;oBACjC,OAAO,EAAE,OAAO,CAAC,mBAAmB;oBACpC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,kBAAkB;iBAC9C;aACF;YACD,WAAW,EAAE;gBACX,GAAG,CAAC,OAAO,CAAC,gBAAgB,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;oBAClD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;oBAC5C,aAAa,EAAE,OAAgB;oBAC/B,YAAY,EAAE,KAAK,CAAC,mBAAmB,IAAI,EAAE;iBAC9C,CAAC,CAAC;gBACH;oBACE,WAAW,EAAE,KAAK,CAAC,OAAO;oBAC1B,aAAa,EAAE,OAAO;oBACtB,YAAY,EAAE,OAAO,CAAC,mBAAmB,IAAI,EAAE;iBAChD;aACF;YACD,YAAY,EAAE,OAAO,CAAC,YAAY;SACnC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO;QACL,cAAc,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE;QAC1E,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { CurrentPolicyReferenceResolver } from \"../../data/principals/currentPolicyReferenceResolver\";\nimport { scopedGroupHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyPageReader } from \"../principals/principalPolicyHistoryReader\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"../principals/runtimePolicyRecovery\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"./acknowledgedPrincipalPredecessor\";\nimport { resolveCurrentGroupMutationReferences } from \"./currentGroupMutationReferences\";\nimport { loadCurrentGroupPolicyMutationContext } from \"./currentGroupPolicyMutationContext\";\nimport { createCurrentPrincipalMutationLease } from \"./currentPrincipalMutationLease\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\ntype MutationRuntime = PrincipalPolicyRecoveryRuntime & {\n readonly apiClient: PrincipalPolicyRecoveryRuntime[\"apiClient\"] &\n Pick<PrincipalMutationRecoveryApi, \"recoverPendingPrincipalMutation\">;\n};\n\ntype CurrentMutationContext = Awaited<\n ReturnType<typeof loadCurrentGroupPolicyMutationContext>\n>;\n\nexport type RuntimeCurrentGroupMutationContext = CurrentMutationContext & {\n readonly resolveAuthoredPolicyReferences: CurrentPolicyReferenceResolver;\n readonly loadGroup: (\n groupId: string,\n ) => Promise<RuntimeCurrentGroupMutationContext>;\n readonly groupRetention: Pick<\n AcknowledgedPrincipalCurrentInput,\n \"recovery\" | \"predecessor\"\n >;\n readonly retainAcknowledged: (\n receipt: CurrentMutationReceipt,\n ) => Promise<void>;\n};\n\ninterface CurrentMutationReceipt {\n readonly additionalGroups?:\n | readonly (AcknowledgedPrincipalCurrentInput & {\n readonly retiredContainerIds?: readonly string[] | undefined;\n })[]\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly response: CommitOrganizationGroupPolicyResponse;\n readonly retiredContainerIds?: readonly string[] | undefined;\n}\n\ninterface MutationInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/** Keep private prefix custody inside the entire mutation and its acknowledgement. */\nexport function createRuntimeCurrentGroupMutation(runtime: MutationRuntime) {\n const lease = createCurrentPrincipalMutationLease(runtime);\n if (!lease) return undefined;\n return async <T>(\n input: MutationInput,\n work: (context: RuntimeCurrentGroupMutationContext) => Promise<T>,\n ): Promise<T> => {\n input = { ...input };\n return lease(\n input.stillCurrent,\n async ({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery,\n }) => {\n const loadGroup = async (\n groupId: string,\n ): Promise<RuntimeCurrentGroupMutationContext> => {\n const context = await loadCurrentGroupPolicyMutationContext({\n ...input,\n groupId,\n execSql: runtime.infra.execSql,\n resolveCurrentPolicy,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n stillCurrent,\n });\n const retention = await createCurrentMutationRetention(\n runtime,\n { ...input, groupId },\n context,\n protection,\n historyReader,\n directoryRecovery(context.organizationCurrent.current),\n );\n return {\n ...context,\n ...retention,\n loadGroup,\n resolveAuthoredPolicyReferences: (current, references) =>\n resolveCurrentGroupMutationReferences({\n current,\n predecessor: context.verifiedCurrentPolicy,\n references,\n readPredecessorReference: context.readPredecessorReference,\n stillCurrent: context.stillCurrent,\n }),\n };\n };\n const context = await loadGroup(input.groupId);\n const result = await work(context);\n assertProjectionVerificationCurrent(context.stillCurrent);\n return result;\n },\n );\n };\n}\n\nasync function createCurrentMutationRetention(\n runtime: MutationRuntime,\n input: MutationInput,\n context: CurrentMutationContext,\n protection: PrincipalPolicyHistoryProgressOptions,\n historyReader: PrincipalPolicyPageReader,\n directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"],\n) {\n const common = {\n historyReader,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n };\n const groupRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"] = {\n ...common,\n expectedHead: principalPolicyReferenceFromBundle(context.currentPolicy),\n protection: context.isOrganizationAdminsGroup\n ? protection\n : scopedGroupHistoryProtection(\n protection,\n input.organizationId,\n context.adminGroupId,\n ),\n historyVerification: context.isOrganizationAdminsGroup\n ? \"direct-admins\"\n : \"standard\",\n ...(context.isOrganizationAdminsGroup\n ? {}\n : { loadExternalAuthority: async () => context.externalAuthority }),\n };\n const capture = (recovery: AcknowledgedPrincipalCurrentInput[\"recovery\"]) =>\n captureAcknowledgedPrincipalPredecessor({\n ...recovery,\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: context.stillCurrent,\n });\n const groupPredecessor = await capture(groupRecovery);\n const directoryPredecessor = await capture(directoryRecovery);\n const retainAcknowledged = async (\n receipt: CurrentMutationReceipt,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(context.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n entries: [\n ...(receipt.additionalGroups ?? []),\n {\n recovery: groupRecovery,\n predecessor: groupPredecessor,\n request: receipt.request,\n response: receipt.response.groupPolicy,\n },\n {\n recovery: directoryRecovery,\n predecessor: directoryPredecessor,\n request: receipt.organizationRequest,\n response: receipt.response.organizationPolicy,\n },\n ],\n retirements: [\n ...(receipt.additionalGroups ?? []).map((entry) => ({\n principalId: entry.request.state.principalId,\n principalType: \"group\" as const,\n containerIds: entry.retiredContainerIds ?? [],\n })),\n {\n principalId: input.groupId,\n principalType: \"group\",\n containerIds: receipt.retiredContainerIds ?? [],\n },\n ],\n stillCurrent: context.stillCurrent,\n });\n };\n return {\n groupRetention: { recovery: groupRecovery, predecessor: groupPredecessor },\n retainAcknowledged,\n };\n}\n"]}
|
|
@@ -10,7 +10,7 @@ export function createRuntimeCurrentOrganizationMutation(runtime) {
|
|
|
10
10
|
return undefined;
|
|
11
11
|
return async (input, work) => {
|
|
12
12
|
const owned = { ...input };
|
|
13
|
-
return lease(owned.stillCurrent, async ({ protection,
|
|
13
|
+
return lease(owned.stillCurrent, async ({ protection, historyReader, stillCurrent, resolveCurrentPolicy, directoryRecovery, }) => {
|
|
14
14
|
const { authority } = await loadCurrentOrganizationMutationAuthority({
|
|
15
15
|
execSql: runtime.infra.execSql,
|
|
16
16
|
organizationId: owned.organizationId,
|
|
@@ -34,7 +34,7 @@ export function createRuntimeCurrentOrganizationMutation(runtime) {
|
|
|
34
34
|
runtime,
|
|
35
35
|
authority,
|
|
36
36
|
protection,
|
|
37
|
-
|
|
37
|
+
historyReader,
|
|
38
38
|
organizationId: owned.organizationId,
|
|
39
39
|
directoryRecovery: directoryRecovery(authority.directory.current),
|
|
40
40
|
stillCurrent: current,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtimeCurrentOrganizationMutation.js","sourceRoot":"","sources":["runtimeCurrentOrganizationMutation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,2DAA2D,CAAC;AAG/G,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAClG,OAAO,EAAE,0CAA0C,EAAE,MAAM,wCAAwC,CAAC;AACpG,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AAmBtF,mFAAmF;AACnF,MAAM,UAAU,wCAAwC,CAAC,OAAgB;IACvE,MAAM,KAAK,GAAG,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC3D,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,KAAK,EACV,KAAY,EACZ,IAAiE,EACrD,EAAE;QACd,MAAM,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;QAC3B,OAAO,KAAK,CACV,KAAK,CAAC,YAAY,EAClB,KAAK,EAAE,EACL,UAAU,EACV,
|
|
1
|
+
{"version":3,"file":"runtimeCurrentOrganizationMutation.js","sourceRoot":"","sources":["runtimeCurrentOrganizationMutation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,2DAA2D,CAAC;AAG/G,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAClG,OAAO,EAAE,0CAA0C,EAAE,MAAM,wCAAwC,CAAC;AACpG,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AAmBtF,mFAAmF;AACnF,MAAM,UAAU,wCAAwC,CAAC,OAAgB;IACvE,MAAM,KAAK,GAAG,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC3D,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,KAAK,EACV,KAAY,EACZ,IAAiE,EACrD,EAAE;QACd,MAAM,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;QAC3B,OAAO,KAAK,CACV,KAAK,CAAC,YAAY,EAClB,KAAK,EAAE,EACL,UAAU,EACV,aAAa,EACb,YAAY,EACZ,oBAAoB,EACpB,iBAAiB,GAClB,EAAE,EAAE;YACH,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,wCAAwC,CAAC;gBACnE,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;gBAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,YAAY,EAAE,KAAK,CAAC,YAAY;gBAChC,+BAA+B,EAAE,CAAC,cAAc,EAAE,EAAE,CAClD,OAAO,CAAC,SAAS,CAAC,+BAA+B,CAAC,cAAc,CAAC;gBACnE,oBAAoB;gBACpB,YAAY;aACb,CAAC,CAAC;YACH,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,SAAS,CAAC,YAAY,EAAE,CAAC;YACjE,MAAM,kCAAkC,CAAC;gBACvC,MAAM,EAAE,EAAE;gBACV,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;gBAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,QAAQ,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC;gBAC/D,YAAY,EAAE,OAAO;aACtB,CAAC,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC;gBACxB,GAAG,SAAS;gBACZ,YAAY,EAAE,OAAO;gBACrB,GAAG,CAAC,MAAM,0CAA0C,CAAC;oBACnD,OAAO;oBACP,SAAS;oBACT,UAAU;oBACV,aAAa;oBACb,cAAc,EAAE,KAAK,CAAC,cAAc;oBACpC,iBAAiB,EAAE,iBAAiB,CAAC,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC;oBACjE,YAAY,EAAE,OAAO;iBACtB,CAAC,CAAC;aACJ,CAAC,CAAC;YACH,mCAAmC,CAAC,OAAO,CAAC,CAAC;YAC7C,OAAO,MAAM,CAAC;QAChB,CAAC,CACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../data/persistence/keyingCheckpointAdvancePersistence\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"../principals/runtimePolicyRecovery\";\nimport type { loadCurrentOrganizationAuthority } from \"./currentOrganizationAuthority\";\nimport { loadCurrentOrganizationMutationAuthority } from \"./currentOrganizationMutationAuthority\";\nimport { createCurrentOrganizationMutationRetention } from \"./currentOrganizationMutationRetention\";\nimport { createCurrentPrincipalMutationLease } from \"./currentPrincipalMutationLease\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\n\ntype Runtime = PrincipalPolicyRecoveryRuntime & {\n readonly apiClient: PrincipalPolicyRecoveryRuntime[\"apiClient\"] &\n Pick<PrincipalMutationRecoveryApi, \"recoverPendingPrincipalMutation\">;\n};\n\ninterface Input {\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\ntype Authority = Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>;\n\nexport type CurrentOrganizationMutationContext = Authority &\n Awaited<ReturnType<typeof createCurrentOrganizationMutationRetention>>;\n\n/** Keep directory authoring and exact acknowledgement inside one private lease. */\nexport function createRuntimeCurrentOrganizationMutation(runtime: Runtime) {\n const lease = createCurrentPrincipalMutationLease(runtime);\n if (!lease) return undefined;\n return async <T>(\n input: Input,\n work: (context: CurrentOrganizationMutationContext) => Promise<T>,\n ): Promise<T> => {\n const owned = { ...input };\n return lease(\n owned.stillCurrent,\n async ({\n protection,\n historyReader,\n stillCurrent,\n resolveCurrentPolicy,\n directoryRecovery,\n }) => {\n const { authority } = await loadCurrentOrganizationMutationAuthority({\n execSql: runtime.infra.execSql,\n organizationId: owned.organizationId,\n signerUserId: owned.signerUserId,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n resolveCurrentPolicy,\n stillCurrent,\n });\n const current = () => stillCurrent() && authority.stillCurrent();\n await advanceKeyingCheckpointsAtomically({\n access: [],\n execSql: runtime.infra.execSql,\n organizationId: owned.organizationId,\n policies: [authority.directory.policy, authority.admins.policy],\n stillCurrent: current,\n });\n const result = await work({\n ...authority,\n stillCurrent: current,\n ...(await createCurrentOrganizationMutationRetention({\n runtime,\n authority,\n protection,\n historyReader,\n organizationId: owned.organizationId,\n directoryRecovery: directoryRecovery(authority.directory.current),\n stillCurrent: current,\n })),\n });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n );\n };\n}\n"]}
|
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { PrincipalPolicyPageCurrent, RequestFailure } from "../../internal/api-client/index.js";
|
|
2
2
|
import { KeyingVerificationError, type PrincipalPolicyExternalAuthority, type PrincipalPolicyHistoryProgressOptions, type ReferencedPrincipalHead, type VerifiedPrincipalPolicyCurrent } from "../../internal/crypto/index.js";
|
|
3
3
|
import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
|
|
4
4
|
import type { TrustedUserIdentityResolver } from "../../data/trustedUserIdentity/index.js";
|
|
5
|
+
import type { PrincipalPolicyPageReader } from "./principalPolicyHistoryReader.js";
|
|
5
6
|
/** A locally observed race, distinct from a rejected signed predecessor. */
|
|
6
7
|
export declare class PrincipalHistoryRecoveryRaceError extends KeyingVerificationError {
|
|
7
8
|
constructor(message: string);
|
|
8
9
|
}
|
|
9
10
|
export interface RecoverPrincipalPolicyHistoryOptions {
|
|
10
|
-
readonly
|
|
11
|
+
readonly historyReader: PrincipalPolicyPageReader;
|
|
11
12
|
readonly execSql: ExecSql;
|
|
12
13
|
readonly organizationId: string;
|
|
13
14
|
readonly expectedHead: ReferencedPrincipalHead;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryRecoveryTypes.js","sourceRoot":"","sources":["principalHistoryRecoveryTypes.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"principalHistoryRecoveryTypes.js","sourceRoot":"","sources":["principalHistoryRecoveryTypes.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,uBAAuB,GAKxB,MAAM,mBAAmB,CAAC;AAK3B,4EAA4E;AAC5E,MAAM,OAAO,iCAAkC,SAAQ,uBAAuB;IAC5E,YAAY,OAAe;QACzB,KAAK,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC;CACF;AA8BD,MAAM,OAAO,+BAAgC,SAAQ,KAAK;IACnC;IAArB,YAAqB,OAAuB;QAC1C,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QADJ,YAAO,GAAP,OAAO,CAAgB;QAE1C,IAAI,CAAC,IAAI,GAAG,iCAAiC,CAAC;IAChD,CAAC;CACF","sourcesContent":["import type {\n PrincipalPolicyPageCurrent,\n RequestFailure,\n} from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type PrincipalPolicyHistoryProgressOptions,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { PrincipalPolicyPageReader } from \"./principalPolicyHistoryReader\";\n\n/** A locally observed race, distinct from a rejected signed predecessor. */\nexport class PrincipalHistoryRecoveryRaceError extends KeyingVerificationError {\n constructor(message: string) {\n super(\"stale_predecessor\", message);\n }\n}\n\nexport interface RecoverPrincipalPolicyHistoryOptions {\n readonly historyReader: PrincipalPolicyPageReader;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly expectedHead: ReferencedPrincipalHead;\n /** Only use locally authenticated completed evidence; never perform HTTP. */\n readonly offline?: boolean | undefined;\n /** Device-controlled key and stable identity/trust-policy context, never supplied by the API. */\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly retainedReferences?: readonly ReferencedPrincipalHead[] | undefined;\n /** Strict Admins mode checks every historical projection in a separate cache scope. */\n readonly historyVerification?: \"standard\" | \"direct-admins\" | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** Authenticate these exact authority references, including cached-prefix citations. */\n readonly loadExternalAuthority?:\n | ((\n references: readonly ReferencedPrincipalHead[],\n ) => Promise<PrincipalPolicyExternalAuthority | undefined>)\n | undefined;\n readonly stillCurrent: () => boolean;\n readonly signal?: AbortSignal | undefined;\n}\n\nexport interface RecoveredPrincipalPolicyHistory {\n readonly current: PrincipalPolicyPageCurrent;\n readonly policy: VerifiedPrincipalPolicyCurrent;\n}\n\nexport class PrincipalPolicyHistoryReadError extends Error {\n constructor(readonly failure: RequestFailure) {\n super(failure.message);\n this.name = \"PrincipalPolicyHistoryReadError\";\n }\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ApiClient } from "../../internal/api-client/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Where recovery reads signed principal policy history. The API client is the
|
|
4
|
+
* production reader; registration reads a just-provisioned principal from its
|
|
5
|
+
* local bundles, and directory discovery replays a page it already fetched.
|
|
6
|
+
* Every page is untrusted input to the same verifier, whichever reader
|
|
7
|
+
* supplied it.
|
|
8
|
+
*/
|
|
9
|
+
export interface PrincipalPolicyHistoryReader {
|
|
10
|
+
readonly getPrincipalPolicyPages: ApiClient["getPrincipalPolicyPages"];
|
|
11
|
+
readonly getProjectionPolicyHistoryPages: ApiClient["getProjectionPolicyHistoryPages"];
|
|
12
|
+
}
|
|
13
|
+
/** Reads one principal's own policy history. */
|
|
14
|
+
export type PrincipalPolicyPageReader = Pick<PrincipalPolicyHistoryReader, "getPrincipalPolicyPages">;
|
|
15
|
+
/** Reads an organization's public projection policy history. */
|
|
16
|
+
export type ProjectionPolicyHistoryReader = Pick<PrincipalPolicyHistoryReader, "getProjectionPolicyHistoryPages">;
|
|
17
|
+
/** The API client as a page reader, or undefined when this client has none. */
|
|
18
|
+
export declare function apiPrincipalPolicyPageReader(apiClient: Partial<PrincipalPolicyPageReader>): PrincipalPolicyPageReader | undefined;
|
|
19
|
+
/** The API client as a projection reader, or undefined when it has none. */
|
|
20
|
+
export declare function apiProjectionPolicyHistoryReader(apiClient: Partial<ProjectionPolicyHistoryReader>): ProjectionPolicyHistoryReader | undefined;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The API client as a page reader, or undefined when this client has none. */
|
|
2
|
+
export function apiPrincipalPolicyPageReader(apiClient) {
|
|
3
|
+
const getPrincipalPolicyPages = apiClient.getPrincipalPolicyPages?.bind(apiClient);
|
|
4
|
+
return getPrincipalPolicyPages ? { getPrincipalPolicyPages } : undefined;
|
|
5
|
+
}
|
|
6
|
+
/** The API client as a projection reader, or undefined when it has none. */
|
|
7
|
+
export function apiProjectionPolicyHistoryReader(apiClient) {
|
|
8
|
+
const getProjectionPolicyHistoryPages = apiClient.getProjectionPolicyHistoryPages?.bind(apiClient);
|
|
9
|
+
return getProjectionPolicyHistoryPages
|
|
10
|
+
? { getProjectionPolicyHistoryPages }
|
|
11
|
+
: undefined;
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=principalPolicyHistoryReader.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principalPolicyHistoryReader.js","sourceRoot":"","sources":["principalPolicyHistoryReader.ts"],"names":[],"mappings":"AA0BA,+EAA+E;AAC/E,MAAM,UAAU,4BAA4B,CAC1C,SAA6C;IAE7C,MAAM,uBAAuB,GAC3B,SAAS,CAAC,uBAAuB,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IACrD,OAAO,uBAAuB,CAAC,CAAC,CAAC,EAAE,uBAAuB,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAC3E,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,gCAAgC,CAC9C,SAAiD;IAEjD,MAAM,+BAA+B,GACnC,SAAS,CAAC,+BAA+B,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAC7D,OAAO,+BAA+B;QACpC,CAAC,CAAC,EAAE,+BAA+B,EAAE;QACrC,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\n\n/**\n * Where recovery reads signed principal policy history. The API client is the\n * production reader; registration reads a just-provisioned principal from its\n * local bundles, and directory discovery replays a page it already fetched.\n * Every page is untrusted input to the same verifier, whichever reader\n * supplied it.\n */\nexport interface PrincipalPolicyHistoryReader {\n readonly getPrincipalPolicyPages: ApiClient[\"getPrincipalPolicyPages\"];\n readonly getProjectionPolicyHistoryPages: ApiClient[\"getProjectionPolicyHistoryPages\"];\n}\n\n/** Reads one principal's own policy history. */\nexport type PrincipalPolicyPageReader = Pick<\n PrincipalPolicyHistoryReader,\n \"getPrincipalPolicyPages\"\n>;\n\n/** Reads an organization's public projection policy history. */\nexport type ProjectionPolicyHistoryReader = Pick<\n PrincipalPolicyHistoryReader,\n \"getProjectionPolicyHistoryPages\"\n>;\n\n/** The API client as a page reader, or undefined when this client has none. */\nexport function apiPrincipalPolicyPageReader(\n apiClient: Partial<PrincipalPolicyPageReader>,\n): PrincipalPolicyPageReader | undefined {\n const getPrincipalPolicyPages =\n apiClient.getPrincipalPolicyPages?.bind(apiClient);\n return getPrincipalPolicyPages ? { getPrincipalPolicyPages } : undefined;\n}\n\n/** The API client as a projection reader, or undefined when it has none. */\nexport function apiProjectionPolicyHistoryReader(\n apiClient: Partial<ProjectionPolicyHistoryReader>,\n): ProjectionPolicyHistoryReader | undefined {\n const getProjectionPolicyHistoryPages =\n apiClient.getProjectionPolicyHistoryPages?.bind(apiClient);\n return getProjectionPolicyHistoryPages\n ? { getProjectionPolicyHistoryPages }\n : undefined;\n}\n"]}
|
|
@@ -54,10 +54,10 @@ async function discoverDirectoryHead(input) {
|
|
|
54
54
|
return {
|
|
55
55
|
head: prefix.head,
|
|
56
56
|
genesis: genesis.reference,
|
|
57
|
-
|
|
57
|
+
historyReader: input.historyReader,
|
|
58
58
|
};
|
|
59
59
|
}
|
|
60
|
-
for await (const result of input.
|
|
60
|
+
for await (const result of input.historyReader.getPrincipalPolicyPages("organization", input.organizationId, { signal: input.signal })) {
|
|
61
61
|
if (!result.ok)
|
|
62
62
|
throw new PrincipalPolicyHistoryReadError(result);
|
|
63
63
|
assertProjectionVerificationCurrent(() => !input.signal?.aborted && input.stillCurrent());
|
|
@@ -68,7 +68,7 @@ async function discoverDirectoryHead(input) {
|
|
|
68
68
|
first.principalId !== input.organizationId)
|
|
69
69
|
throw new KeyingVerificationError("missing_dependency", "Organization directory discovery requires genesis");
|
|
70
70
|
return {
|
|
71
|
-
|
|
71
|
+
historyReader: reusePrincipalDiscoveryPage(input.historyReader, result),
|
|
72
72
|
genesis: {
|
|
73
73
|
principalType: first.principalType,
|
|
74
74
|
principalId: first.principalId,
|
|
@@ -94,11 +94,11 @@ export async function recoverPolicyDirectory(input, references, selected) {
|
|
|
94
94
|
...input,
|
|
95
95
|
protection: directoryHistoryProtection(input.protection),
|
|
96
96
|
};
|
|
97
|
-
const { head: expectedHead, genesis,
|
|
97
|
+
const { head: expectedHead, genesis, historyReader, } = selected
|
|
98
98
|
? {
|
|
99
99
|
head: exactHead(selected.policy.state),
|
|
100
100
|
genesis: selected.policy.retainedHistory[0]?.state,
|
|
101
|
-
|
|
101
|
+
historyReader: input.historyReader,
|
|
102
102
|
}
|
|
103
103
|
: await discoverDirectoryHead(scoped);
|
|
104
104
|
if (genesis?.version !== 1)
|
|
@@ -107,7 +107,7 @@ export async function recoverPolicyDirectory(input, references, selected) {
|
|
|
107
107
|
throw new PrincipalRecoveryDirectoryAdvanced();
|
|
108
108
|
const recovered = await recoverPrincipalPolicyHistory({
|
|
109
109
|
...scoped,
|
|
110
|
-
|
|
110
|
+
historyReader,
|
|
111
111
|
expectedHead,
|
|
112
112
|
retainedReferences: references.some((reference) => reference.version === 1)
|
|
113
113
|
? references
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalRecoveryDirectory.js","sourceRoot":"","sources":["principalRecoveryDirectory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAC3G,OAAO,EAEL,oCAAoC,GACrC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,+BAA+B,EAAE,MAAM,wDAAwD,CAAC;AACzG,OAAO,EAAE,0BAA0B,EAAE,MAAM,u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AAC,CAAC,CAAC,EAAE,KAAK;YAClD,SAAS,EAAE,KAAK,CAAC,SAAS;SAC3B;QACH,CAAC,CAAC,MAAM,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACxC,IAAI,OAAO,EAAE,OAAO,KAAK,CAAC;QACxB,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,2DAA2D,CAC5D,CAAC;IACJ,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC;QAC1E,MAAM,IAAI,kCAAkC,EAAE,CAAC;IACjD,MAAM,SAAS,GAAG,MAAM,6BAA6B,CAAC;QACpD,GAAG,MAAM;QACT,SAAS;QACT,YAAY;QACZ,kBAAkB,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,KAAK,CAAC,CAAC;YACzE,CAAC,CAAC,UAAU;YACZ,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,GAAG,UAAU,CAAC;KACxC,CAAC,CAAC;IACH,IAAI,UAA2C,CAAC;IAChD,IAAI,CAAC;QACH,UAAU,GAAG,oCAAoC,CAC/C,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,UAAU,CAC5C,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,2CAA2C,CAC5C,CAAC;IACJ,CAAC;IACD,IAAI,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;IACJ,OAAO,EAAE,GAAG,SAAS,EAAE,UAAU,EAAE,CAAC;AACtC,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { principalHistoryEvidenceScopeId } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { directoryHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { loadVerifiedPrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport { reusePrincipalDiscoveryPage } from \"./principalRecoveryDiscoveryPage\";\nimport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n\nexport type PrincipalRecoveryContext = Omit<\n RecoverPrincipalPolicyHistoryOptions,\n | \"expectedHead\"\n | \"retainedReferences\"\n | \"historyVerification\"\n | \"loadExternalAuthority\"\n>;\n\nexport interface RecoveredPolicyDirectory\n extends RecoveredPrincipalPolicyHistory {\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport class PrincipalRecoveryDirectoryAdvanced extends Error {}\n\nfunction exactHead(state: ReferencedPrincipalHead): ReferencedPrincipalHead {\n return {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n}\n\n/** An unverified discovery read chooses a pin; recovery must authenticate it. */\nasync function discoverDirectoryHead(input: PrincipalRecoveryContext): Promise<{\n head: ReferencedPrincipalHead;\n genesis: ReferencedPrincipalHead;\n apiClient: PrincipalRecoveryContext[\"apiClient\"];\n}> {\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n if (input.offline) {\n const principal = {\n principalType: \"organization\" as const,\n principalId: input.organizationId,\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: principal,\n protection: input.protection,\n });\n const prefix = await loadVerifiedPrincipalHistoryPrefix(\n input,\n principal,\n scopeId,\n );\n if (!prefix)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory is unavailable offline\",\n );\n const history = prefix.verifier.finish(prefix.head);\n if (!history.ok) throw history.error;\n const genesis = await loadPrincipalHistoryReference({\n execSql: input.execSql,\n scopeId,\n history: history.value,\n version: 1,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history: history.value,\n references: [genesis],\n });\n if (!selected.ok) throw selected.error;\n return {\n head: prefix.head,\n genesis: genesis.reference,\n apiClient: input.apiClient,\n };\n }\n for await (const result of input.apiClient.getPrincipalPolicyPages(\n \"organization\",\n input.organizationId,\n { signal: input.signal },\n )) {\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n const state = result.data.currentState;\n const first = result.data.previousStates[0]?.state ?? state;\n if (\n first.version !== 1 ||\n first.principalType !== \"organization\" ||\n first.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory discovery requires genesis\",\n );\n return {\n apiClient: reusePrincipalDiscoveryPage(input.apiClient, result),\n genesis: {\n principalType: first.principalType,\n principalId: first.principalId,\n version: first.version,\n stateHash: first.stateHash,\n keyEpoch: first.keyEpoch,\n keyFingerprint: first.keyFingerprint,\n },\n head: {\n principalType: \"organization\",\n principalId: input.organizationId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n },\n };\n }\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory head is unavailable\",\n );\n}\n\nexport async function recoverPolicyDirectory(\n input: PrincipalRecoveryContext,\n references: readonly ReferencedPrincipalHead[],\n selected?: RecoveredPolicyDirectory,\n): Promise<RecoveredPolicyDirectory> {\n const scoped = {\n ...input,\n protection: directoryHistoryProtection(input.protection),\n };\n const {\n head: expectedHead,\n genesis,\n apiClient,\n } = selected\n ? {\n head: exactHead(selected.policy.state),\n genesis: selected.policy.retainedHistory[0]?.state,\n apiClient: input.apiClient,\n }\n : await discoverDirectoryHead(scoped);\n if (genesis?.version !== 1)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory recovery requires verified genesis\",\n );\n if (references.some((reference) => reference.version > expectedHead.version))\n throw new PrincipalRecoveryDirectoryAdvanced();\n const recovered = await recoverPrincipalPolicyHistory({\n ...scoped,\n apiClient,\n expectedHead,\n retainedReferences: references.some((reference) => reference.version === 1)\n ? references\n : [exactHead(genesis), ...references],\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n recovered.current.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Organization directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization directory scope does not match\",\n );\n return { ...recovered, descriptor };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"principalRecoveryDirectory.js","sourceRoot":"","sources":["principalRecoveryDirectory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAC3G,OAAO,EAEL,oCAAoC,GACrC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,+BAA+B,EAAE,MAAM,wDAAwD,CAAC;AACzG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uDAAuD,CAAC;AACnG,OAAO,EAAE,kCAAkC,EAAE,MAAM,kCAAkC,CAAC;AACtF,OAAO,EACL,+BAA+B,GA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AAqB,CAAC,MAAM,CAAC,CAAC;IACxC,IAAI,OAAO,EAAE,OAAO,KAAK,CAAC;QACxB,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,2DAA2D,CAC5D,CAAC;IACJ,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC;QAC1E,MAAM,IAAI,kCAAkC,EAAE,CAAC;IACjD,MAAM,SAAS,GAAG,MAAM,6BAA6B,CAAC;QACpD,GAAG,MAAM;QACT,aAAa;QACb,YAAY;QACZ,kBAAkB,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,KAAK,CAAC,CAAC;YACzE,CAAC,CAAC,UAAU;YACZ,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,GAAG,UAAU,CAAC;KACxC,CAAC,CAAC;IACH,IAAI,UAA2C,CAAC;IAChD,IAAI,CAAC;QACH,UAAU,GAAG,oCAAoC,CAC/C,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,UAAU,CAC5C,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,2CAA2C,CAC5C,CAAC;IACJ,CAAC;IACD,IAAI,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;IACJ,OAAO,EAAE,GAAG,SAAS,EAAE,UAAU,EAAE,CAAC;AACtC,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { principalHistoryEvidenceScopeId } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { directoryHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { loadVerifiedPrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport { reusePrincipalDiscoveryPage } from \"./principalRecoveryDiscoveryPage\";\nimport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n\nexport type PrincipalRecoveryContext = Omit<\n RecoverPrincipalPolicyHistoryOptions,\n | \"expectedHead\"\n | \"retainedReferences\"\n | \"historyVerification\"\n | \"loadExternalAuthority\"\n>;\n\nexport interface RecoveredPolicyDirectory\n extends RecoveredPrincipalPolicyHistory {\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport class PrincipalRecoveryDirectoryAdvanced extends Error {}\n\nfunction exactHead(state: ReferencedPrincipalHead): ReferencedPrincipalHead {\n return {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n}\n\n/** An unverified discovery read chooses a pin; recovery must authenticate it. */\nasync function discoverDirectoryHead(input: PrincipalRecoveryContext): Promise<{\n head: ReferencedPrincipalHead;\n genesis: ReferencedPrincipalHead;\n historyReader: PrincipalRecoveryContext[\"historyReader\"];\n}> {\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n if (input.offline) {\n const principal = {\n principalType: \"organization\" as const,\n principalId: input.organizationId,\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: principal,\n protection: input.protection,\n });\n const prefix = await loadVerifiedPrincipalHistoryPrefix(\n input,\n principal,\n scopeId,\n );\n if (!prefix)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory is unavailable offline\",\n );\n const history = prefix.verifier.finish(prefix.head);\n if (!history.ok) throw history.error;\n const genesis = await loadPrincipalHistoryReference({\n execSql: input.execSql,\n scopeId,\n history: history.value,\n version: 1,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history: history.value,\n references: [genesis],\n });\n if (!selected.ok) throw selected.error;\n return {\n head: prefix.head,\n genesis: genesis.reference,\n historyReader: input.historyReader,\n };\n }\n for await (const result of input.historyReader.getPrincipalPolicyPages(\n \"organization\",\n input.organizationId,\n { signal: input.signal },\n )) {\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n const state = result.data.currentState;\n const first = result.data.previousStates[0]?.state ?? state;\n if (\n first.version !== 1 ||\n first.principalType !== \"organization\" ||\n first.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory discovery requires genesis\",\n );\n return {\n historyReader: reusePrincipalDiscoveryPage(input.historyReader, result),\n genesis: {\n principalType: first.principalType,\n principalId: first.principalId,\n version: first.version,\n stateHash: first.stateHash,\n keyEpoch: first.keyEpoch,\n keyFingerprint: first.keyFingerprint,\n },\n head: {\n principalType: \"organization\",\n principalId: input.organizationId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n },\n };\n }\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory head is unavailable\",\n );\n}\n\nexport async function recoverPolicyDirectory(\n input: PrincipalRecoveryContext,\n references: readonly ReferencedPrincipalHead[],\n selected?: RecoveredPolicyDirectory,\n): Promise<RecoveredPolicyDirectory> {\n const scoped = {\n ...input,\n protection: directoryHistoryProtection(input.protection),\n };\n const {\n head: expectedHead,\n genesis,\n historyReader,\n } = selected\n ? {\n head: exactHead(selected.policy.state),\n genesis: selected.policy.retainedHistory[0]?.state,\n historyReader: input.historyReader,\n }\n : await discoverDirectoryHead(scoped);\n if (genesis?.version !== 1)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory recovery requires verified genesis\",\n );\n if (references.some((reference) => reference.version > expectedHead.version))\n throw new PrincipalRecoveryDirectoryAdvanced();\n const recovered = await recoverPrincipalPolicyHistory({\n ...scoped,\n historyReader,\n expectedHead,\n retainedReferences: references.some((reference) => reference.version === 1)\n ? references\n : [exactHead(genesis), ...references],\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n recovered.current.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Organization directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization directory scope does not match\",\n );\n return { ...recovered, descriptor };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Reuse the discovery bytes as untrusted input to the ordinary verifier. */
|
|
2
|
-
export function reusePrincipalDiscoveryPage(
|
|
2
|
+
export function reusePrincipalDiscoveryPage(reader, discovery) {
|
|
3
3
|
const first = structuredClone(discovery);
|
|
4
4
|
const page = first.data;
|
|
5
5
|
const current = {
|
|
@@ -16,7 +16,7 @@ export function reusePrincipalDiscoveryPage(apiClient, discovery) {
|
|
|
16
16
|
options.stateHash !== current.currentState.stateHash ||
|
|
17
17
|
principalType !== current.currentState.principalType ||
|
|
18
18
|
principalId !== current.currentState.principalId) {
|
|
19
|
-
yield*
|
|
19
|
+
yield* reader.getPrincipalPolicyPages(principalType, principalId, options);
|
|
20
20
|
return;
|
|
21
21
|
}
|
|
22
22
|
yield structuredClone(first);
|
|
@@ -24,8 +24,8 @@ export function reusePrincipalDiscoveryPage(apiClient, discovery) {
|
|
|
24
24
|
if (next === null)
|
|
25
25
|
return;
|
|
26
26
|
// Resume binds every later page to these exact artifacts, including bytes
|
|
27
|
-
// outside the signed head. The
|
|
28
|
-
yield*
|
|
27
|
+
// outside the signed head. The wrapped reader's cursor/shape checks still run.
|
|
28
|
+
yield* reader.getPrincipalPolicyPages(principalType, principalId, {
|
|
29
29
|
...options,
|
|
30
30
|
afterVersion: undefined,
|
|
31
31
|
resume: { current, afterVersion: next },
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalRecoveryDiscoveryPage.js","sourceRoot":"","sources":["principalRecoveryDiscoveryPage.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"principalRecoveryDiscoveryPage.js","sourceRoot":"","sources":["principalRecoveryDiscoveryPage.ts"],"names":[],"mappings":"AAIA,6EAA6E;AAC7E,MAAM,UAAU,2BAA2B,CACzC,MAAiC,EACjC,SAAsD;IAEtD,MAAM,KAAK,GAAG,eAAe,CAAC,SAAS,CAAC,CAAC;IACzC,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IACxB,MAAM,OAAO,GAAG;QACd,YAAY,EAAE,IAAI,CAAC,YAAY;QAC/B,cAAc,EAAE,IAAI,CAAC,cAAc;QACnC,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;QACzC,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,sBAAsB,EAAE,IAAI,CAAC,sBAAsB;KACpD,CAAC;IACF,OAAO;QACL,KAAK,CAAC,CAAC,uBAAuB,CAAC,aAAa,EAAE,WAAW,EAAE,OAAO,GAAG,EAAE;YACrE,IACE,OAAO,CAAC,MAAM,KAAK,SAAS;gBAC5B,CAAC,OAAO,CAAC,YAAY,IAAI,CAAC,CAAC,KAAK,CAAC;gBACjC,OAAO,CAAC,SAAS,KAAK,OAAO,CAAC,YAAY,CAAC,SAAS;gBACpD,aAAa,KAAK,OAAO,CAAC,YAAY,CAAC,aAAa;gBACpD,WAAW,KAAK,OAAO,CAAC,YAAY,CAAC,WAAW,EAChD,CAAC;gBACD,KAAK,CAAC,CAAC,MAAM,CAAC,uBAAuB,CACnC,aAAa,EACb,WAAW,EACX,OAAO,CACR,CAAC;gBACF,OAAO;YACT,CAAC;YACD,MAAM,eAAe,CAAC,KAAK,CAAC,CAAC;YAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC;YAC/C,IAAI,IAAI,KAAK,IAAI;gBAAE,OAAO;YAC1B,0EAA0E;YAC1E,+EAA+E;YAC/E,KAAK,CAAC,CAAC,MAAM,CAAC,uBAAuB,CAAC,aAAa,EAAE,WAAW,EAAE;gBAChE,GAAG,OAAO;gBACV,YAAY,EAAE,SAAS;gBACvB,MAAM,EAAE,EAAE,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE;aACxC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { RequestSuccess } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyPageResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyPageReader } from \"./principalPolicyHistoryReader\";\n\n/** Reuse the discovery bytes as untrusted input to the ordinary verifier. */\nexport function reusePrincipalDiscoveryPage(\n reader: PrincipalPolicyPageReader,\n discovery: RequestSuccess<PrincipalPolicyPageResponse>,\n): PrincipalPolicyPageReader {\n const first = structuredClone(discovery);\n const page = first.data;\n const current = {\n currentState: page.currentState,\n currentPayload: page.currentPayload,\n currentProjection: page.currentProjection,\n currentGrants: page.currentGrants,\n currentMemberEnvelopes: page.currentMemberEnvelopes,\n };\n return {\n async *getPrincipalPolicyPages(principalType, principalId, options = {}) {\n if (\n options.resume !== undefined ||\n (options.afterVersion ?? 0) !== 0 ||\n options.stateHash !== current.currentState.stateHash ||\n principalType !== current.currentState.principalType ||\n principalId !== current.currentState.principalId\n ) {\n yield* reader.getPrincipalPolicyPages(\n principalType,\n principalId,\n options,\n );\n return;\n }\n yield structuredClone(first);\n const next = page.historyPage.nextAfterVersion;\n if (next === null) return;\n // Resume binds every later page to these exact artifacts, including bytes\n // outside the signed head. The wrapped reader's cursor/shape checks still run.\n yield* reader.getPrincipalPolicyPages(principalType, principalId, {\n ...options,\n afterVersion: undefined,\n resume: { current, afterVersion: next },\n });\n },\n };\n}\n"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import type { ApiClient } from "../../internal/api-client/index.js";
|
|
2
1
|
import type { PrincipalPolicyExternalAuthority, PrincipalPolicyHistoryProgressOptions, PrincipalPolicyHistoryVerifier, ReferencedPrincipalHead, VerifiedPrincipalPolicyHistory } from "../../internal/crypto/index.js";
|
|
3
2
|
import type { PrincipalPolicyHistorySourceResponse } from "../../internal/validators/response/index.js";
|
|
4
3
|
import type { PrincipalHistoryPrefix } from "../../data/persistence/principalHistoryPrefixPersistence.js";
|
|
5
4
|
import type { PrincipalHistoryStage } from "../../data/persistence/principalHistoryStagePersistence.js";
|
|
6
5
|
import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
|
|
7
6
|
import type { TrustedUserIdentityResolver } from "../../data/trustedUserIdentity/index.js";
|
|
7
|
+
import type { ProjectionPolicyHistoryReader } from "./principalPolicyHistoryReader.js";
|
|
8
8
|
export interface PublicPrincipalHistoryOptions {
|
|
9
|
-
readonly
|
|
9
|
+
readonly historyReader: ProjectionPolicyHistoryReader;
|
|
10
10
|
/** Terminal proof verification defers durable currency until all artifacts authenticate. */
|
|
11
11
|
readonly historicalProof?: boolean | undefined;
|
|
12
12
|
readonly source: PrincipalPolicyHistorySourceResponse;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"publicPrincipalHistoryTypes.js","sourceRoot":"","sources":["publicPrincipalHistoryTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"publicPrincipalHistoryTypes.js","sourceRoot":"","sources":["publicPrincipalHistoryTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n PrincipalPolicyExternalAuthority,\n PrincipalPolicyHistoryProgressOptions,\n PrincipalPolicyHistoryVerifier,\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicyHistory,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyHistorySourceResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport type { PrincipalHistoryStage } from \"../../data/persistence/principalHistoryStagePersistence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { ProjectionPolicyHistoryReader } from \"./principalPolicyHistoryReader\";\n\nexport interface PublicPrincipalHistoryOptions {\n readonly historyReader: ProjectionPolicyHistoryReader;\n /** Terminal proof verification defers durable currency until all artifacts authenticate. */\n readonly historicalProof?: boolean | undefined;\n readonly source: PrincipalPolicyHistorySourceResponse;\n readonly organizationId: string;\n readonly execSql: ExecSql;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: () => boolean;\n readonly signal?: AbortSignal | undefined;\n readonly offline?: boolean | undefined;\n /** Retry disposable evidence loss once from signatures, without reusing hints. */\n readonly replay?: boolean | undefined;\n readonly strictAdmins?: boolean | undefined;\n /** Already verified organization binding; included in the protected cache scope. */\n readonly authorityGroupId?: string | undefined;\n readonly loadExternalAuthority?:\n | ((\n references: readonly ReferencedPrincipalHead[],\n cachedPrefix?: boolean,\n ) => Promise<PrincipalPolicyExternalAuthority | undefined>)\n | undefined;\n}\n\nexport interface PublicPrincipalHistoryProgress {\n readonly id: string;\n readonly scopeId: string;\n readonly verifier: PrincipalPolicyHistoryVerifier;\n readonly completedHead: ReferencedPrincipalHead | null;\n readonly afterVersion: number;\n readonly saved: PrincipalHistoryStage | null;\n readonly cachedPrefix: PrincipalHistoryPrefix | null;\n readonly authorityReference: ReferencedPrincipalHead | null;\n}\n\n/** Public authorization only; caller must check directory binding and local pins. */\nexport interface RecoveredPublicPrincipalHistory {\n readonly scopeId: string;\n readonly history: VerifiedPrincipalPolicyHistory;\n}\n"]}
|
|
@@ -186,7 +186,7 @@ async function readRecoveryPages(input, stage) {
|
|
|
186
186
|
if (completedStageMatchesHead(stage, input.expectedHead))
|
|
187
187
|
return true;
|
|
188
188
|
let receivedFinalPage = false;
|
|
189
|
-
for await (const result of input.
|
|
189
|
+
for await (const result of input.historyReader.getPrincipalPolicyPages(input.expectedHead.principalType, input.expectedHead.principalId, {
|
|
190
190
|
signal: input.signal,
|
|
191
191
|
stateHash: input.expectedHead.stateHash,
|
|
192
192
|
...(stage.saved && stage.current
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recoverPrincipalPolicyHistory.js","sourceRoot":"","sources":["recoverPrincipalPolicyHistory.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,kCAAkC,EAGlC,+BAA+B,EAC/B,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,mCAAmC,EAAE,MAAM,4DAA4D,CAAC;AACjH,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,+BAA+B,EAAE,MAAM,uDAAuD,CAAC;AACxG,OAAO,EAAE,sCAAsC,EAAE,MAAM,sBAAsB,CAAC;AAC9E,OAAO,EAAE,yCAAyC,EAAE,MAAM,qCAAqC,CAAC;AAChG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAEL,oCAAoC,GACrC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,iCA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AC9B,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,GAAG,OAAO,CAAC,YAAY,CAAC,OAAO,CAChE;QAED,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,yDAAyD,CAC1D,CAAC;IACJ,MAAM,KAAK,GAAG;QACZ,GAAG,OAAO;QACV,mBAAmB,EAAE,OAAO,CAAC,mBAAmB,IAAI,UAAU;QAC9D,YAAY,EAAE,eAAe,CAAC,OAAO,CAAC,YAAY,CAAC;QACnD,kBAAkB,EAAE,eAAe,CAAC,OAAO,CAAC,kBAAkB,IAAI,EAAE,CAAC;QACrE,gBAAgB,EAAE,CAAC,GAAG,gBAAgB,CAAC;QACvC,UAAU,EAAE,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC;KAC9D,CAAC;IACF,IAAI,CAAC;QACH,KAAK,CAAC,UAAU,CAAC,OAAO,GAAG,mCAAmC,CAAC,KAAK,CAAC,CAAC;QACtE,OAAO,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;YAAS,CAAC;QACT,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryInput,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyPageResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport {\n discardPrincipalHistoryStage,\n savePrincipalHistoryStage,\n} from \"../../data/persistence/principalHistoryStagePersistence\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { principalHistoryStageProtection } from \"../../data/principals/principalHistoryStageProtection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./policyVerification\";\nimport { validatePrincipalHistoryRecoveryAuthority } from \"./principalHistoryRecoveryAuthority\";\nimport { publishReusablePrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport {\n PrincipalHistoryEvidenceUnavailableError,\n type PrincipalHistorySelectionOptions,\n selectRecoveredPrincipalHistory,\n} from \"./principalHistoryRecoveryReferences\";\nimport {\n type PrincipalHistoryRecoveryStage,\n restorePrincipalHistoryRecoveryStage,\n} from \"./principalHistoryRecoveryStage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"./principalHistoryRecoveryVerification\";\n\nclass PrincipalHistoryPrefixDisconnectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PrincipalHistoryPrefixDisconnectedError\";\n }\n}\n\n/** Stored current artifacts of a completed stage failed their signed-history check. */\nclass StoredPrincipalCurrentRejectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"StoredPrincipalCurrentRejectedError\";\n }\n}\n\nfunction currentArtifacts(\n page: PrincipalPolicyPageResponse,\n): PrincipalPolicyPageCurrent {\n return {\n currentState: page.currentState,\n currentPayload: page.currentPayload,\n currentProjection: page.currentProjection,\n currentGrants: page.currentGrants,\n currentMemberEnvelopes: page.currentMemberEnvelopes,\n };\n}\n\nfunction recoveryIsCurrent(\n input: RecoverPrincipalPolicyHistoryOptions,\n): boolean {\n return !input.signal?.aborted && input.stillCurrent();\n}\n\nfunction assertCurrent(input: RecoverPrincipalPolicyHistoryOptions): void {\n assertProjectionVerificationCurrent(() => recoveryIsCurrent(input));\n}\n\nfunction assertExpectedHead(\n current: PrincipalPolicyPageCurrent,\n expectedHead: RecoverPrincipalPolicyHistoryOptions[\"expectedHead\"],\n): void {\n for (const field of [\n \"principalType\",\n \"principalId\",\n \"version\",\n \"stateHash\",\n \"keyEpoch\",\n \"keyFingerprint\",\n ] as const) {\n if (current.currentState[field] !== expectedHead[field])\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history page does not match its requested head\",\n );\n }\n}\n\nasync function acceptPage(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n response: PrincipalPolicyPageResponse,\n): Promise<void> {\n const page = structuredClone(response);\n assertCurrent(input);\n assertExpectedHead(page, input.expectedHead);\n if (stage.complete) {\n if (\n page.previousStates.length !== 0 ||\n page.historyPage.nextAfterVersion !== null\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed history returned additional entries\",\n );\n stage.current = currentArtifacts(page);\n return;\n }\n const complete = page.historyPage.nextAfterVersion === null;\n const current = currentArtifacts(page);\n const entries = [...page.previousStates];\n if (complete)\n entries.push({\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n });\n assertPrincipalHistoryVerificationMode(input, entries);\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: page.previousStates },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Principal history signer identity could not be authenticated\",\n );\n const externalAuthority = await input.loadExternalAuthority?.(\n entries.flatMap(({ state }) =>\n state.externalAuthority ? [state.externalAuthority] : [],\n ),\n );\n const appended = await stage.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) {\n if (appended.error.code === \"stale_predecessor\")\n throw new PrincipalHistoryPrefixDisconnectedError(appended.error);\n throw appended.error;\n }\n const next = {\n id: stage.id,\n organizationId: input.organizationId,\n currentJson: JSON.stringify(current),\n afterVersion: appended.value.throughVersion - (complete ? 1 : 0),\n complete,\n };\n const protectedProgress = await stage.verifier.exportProgress(\n await principalHistoryStageProtection(\n input.protection,\n input.expectedHead,\n next,\n ),\n );\n if (!protectedProgress.ok) throw protectedProgress.error;\n const saved = { ...next, progress: protectedProgress.value };\n await savePrincipalHistoryStage({\n execSql: input.execSql,\n stage: saved,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId: stage.scopeId,\n organizationId: input.organizationId,\n entries,\n nodes: appended.value.indexNodes,\n }),\n previousProgress: stage.saved?.progress ?? null,\n stillCurrent: () => recoveryIsCurrent(input),\n });\n stage.current = current;\n stage.saved = saved;\n stage.complete = complete;\n}\n\nasync function finishRecovery(\n input: PrincipalHistorySelectionOptions,\n stage: PrincipalHistoryRecoveryStage,\n checkpoint: PrincipalPolicyCheckpoint | null,\n storedCurrent: boolean,\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (!stage.current || !stage.complete)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history ended before its pinned head\",\n );\n const history = stage.verifier.finish(input.expectedHead);\n if (!history.ok) throw history.error;\n const selected = await selectRecoveredPrincipalHistory({\n options: input,\n scopeId: stage.scopeId,\n history: history.value,\n checkpoint,\n });\n const current = await verifyPrincipalPolicyCurrent({\n current: stage.current,\n history: selected,\n });\n if (!current.ok) {\n if (storedCurrent)\n throw new StoredPrincipalCurrentRejectedError(current.error);\n throw current.error;\n }\n verifyPrincipalPolicyCheckpoint({\n chain: current.value.retainedHistory,\n currentState: current.value.state,\n localCheckpoint: checkpoint,\n });\n const latest = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (\n latest?.version !== checkpoint?.version ||\n latest?.stateHash !== checkpoint?.stateHash\n )\n throw new PrincipalHistoryRecoveryRaceError(\n \"Local principal checkpoint changed during history recovery\",\n );\n assertCurrent(input);\n if (!input.offline)\n await publishReusablePrincipalHistoryPrefix(\n input,\n stage.scopeId,\n stage.verifier,\n stage.current,\n );\n assertCurrent(input);\n return { current: stage.current, policy: current.value };\n}\n\nfunction completedStageMatchesHead(\n stage: PrincipalHistoryRecoveryStage,\n expectedHead: RecoverPrincipalPolicyHistoryOptions[\"expectedHead\"],\n): boolean {\n if (!stage.complete || !stage.current) return false;\n try {\n assertExpectedHead(stage.current, expectedHead);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Returns whether the stage's current artifacts came from local storage. A\n * completed stage already authenticates every signed entry through the exact\n * pinned head, so an online read of that head could only return the pinned\n * bytes or refuse. Server-current freshness belongs to the caller's discovery.\n */\nasync function readRecoveryPages(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n): Promise<boolean> {\n if (input.offline) {\n if (!stage.complete || !stage.current)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed principal history is unavailable offline\",\n );\n assertExpectedHead(stage.current, input.expectedHead);\n return true;\n }\n if (completedStageMatchesHead(stage, input.expectedHead)) return true;\n let receivedFinalPage = false;\n for await (const result of input.apiClient.getPrincipalPolicyPages(\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n {\n signal: input.signal,\n stateHash: input.expectedHead.stateHash,\n ...(stage.saved && stage.current\n ? {\n resume: {\n current: stage.current,\n afterVersion: stage.saved.afterVersion,\n },\n }\n : { afterVersion: stage.initialAfterVersion }),\n },\n )) {\n if (!result.ok) {\n // A rejected transport pin cannot justify skipping history on retry.\n // Discard only this operation's progress, then let a new call replay it.\n if (result.kind === \"shape\" && stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n throw new PrincipalPolicyHistoryReadError(result);\n }\n await acceptPage(input, stage, result.data);\n receivedFinalPage = result.data.historyPage.nextAfterVersion === null;\n }\n if (!receivedFinalPage)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history transport did not complete\",\n );\n return false;\n}\n\nasync function recover(\n input: PrincipalHistorySelectionOptions,\n allowEvidenceRebuild = true,\n): Promise<RecoveredPrincipalPolicyHistory> {\n assertCurrent(input);\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (checkpoint && input.expectedHead.version < checkpoint.version)\n throw new KeyingVerificationError(\n input.offline ? \"missing_dependency\" : \"rollback\",\n \"Requested principal history predates the local checkpoint\",\n );\n // Validate the requested pin/selection before creating any disposable caches.\n createPrincipalPolicyHistoryVerifier({\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n localCheckpoint: checkpoint,\n retainedReferences: input.retainedReferences ?? [],\n });\n const historyInput: PrincipalPolicyHistoryInput = {\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n };\n const stage = await restorePrincipalHistoryRecoveryStage(\n input,\n historyInput,\n allowEvidenceRebuild,\n );\n try {\n if (stage.fromCache)\n await validatePrincipalHistoryRecoveryAuthority(input, stage.verifier);\n const stored = await readRecoveryPages(input, stage);\n return await finishRecovery(\n input,\n stage,\n checkpoint,\n stored && !input.offline,\n );\n } catch (error) {\n const lostEvidence =\n error instanceof PrincipalHistoryEvidenceUnavailableError;\n // Disposable stored artifacts never refuse an online reader: replay them.\n const disposable =\n error instanceof PrincipalHistoryPrefixDisconnectedError ||\n error instanceof StoredPrincipalCurrentRejectedError;\n if (!lostEvidence && !disposable) throw error;\n if (stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n if (\n !input.offline &&\n allowEvidenceRebuild &&\n (lostEvidence || stage.fromCache)\n )\n return recover(input, false);\n throw error.verificationError;\n }\n}\n\n/**\n * Recover one exact head with bounded retained history and durable checked progress.\n * The result is a sparse current-policy capability; this does not advance app checkpoints.\n * Retain organization version 1 when the result will establish founder binding.\n */\nexport function recoverPrincipalPolicyHistory(\n options: RecoverPrincipalPolicyHistoryOptions,\n): Promise<RecoveredPrincipalPolicyHistory> {\n return recoverPrincipalPolicyHistoryWithVersions(options, []);\n}\n\n/** Internal bounded display selection; missing proof rows use the normal single rebuild. */\nexport async function recoverPrincipalPolicyHistoryWithVersions(\n options: RecoverPrincipalPolicyHistoryOptions,\n retainedVersions: readonly number[],\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (\n !Array.isArray(retainedVersions) ||\n retainedVersions.length + (options.retainedReferences?.length ?? 0) >\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT ||\n retainedVersions.some(\n (version) =>\n !Number.isSafeInteger(version) ||\n version < 1 ||\n version > options.expectedHead.version,\n )\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal display history selection exceeds its bounded range\",\n );\n if (options.offline !== undefined && typeof options.offline !== \"boolean\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid principal history transport mode\",\n );\n if (\n !options.organizationId ||\n (options.expectedHead.principalType === \"organization\" &&\n options.expectedHead.principalId !== options.organizationId)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history organization scope is invalid\",\n );\n if (\n options.retainedReferences?.some(\n (reference) => reference.version > options.expectedHead.version,\n )\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested history reference is beyond the recovery head\",\n );\n const input = {\n ...options,\n historyVerification: options.historyVerification ?? \"standard\",\n expectedHead: structuredClone(options.expectedHead),\n retainedReferences: structuredClone(options.retainedReferences ?? []),\n retainedVersions: [...retainedVersions],\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n input.protection.context = principalHistoryVerificationContext(input);\n return await recover(input);\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n"]}
|
|
1
|
+
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,EAAE,CAAC,GAAG,gBAAgB,CAAC;QACvC,UAAU,EAAE,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC;KAC9D,CAAC;IACF,IAAI,CAAC;QACH,KAAK,CAAC,UAAU,CAAC,OAAO,GAAG,mCAAmC,CAAC,KAAK,CAAC,CAAC;QACtE,OAAO,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;YAAS,CAAC;QACT,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryInput,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyPageResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport {\n discardPrincipalHistoryStage,\n savePrincipalHistoryStage,\n} from \"../../data/persistence/principalHistoryStagePersistence\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { principalHistoryStageProtection } from \"../../data/principals/principalHistoryStageProtection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./policyVerification\";\nimport { validatePrincipalHistoryRecoveryAuthority } from \"./principalHistoryRecoveryAuthority\";\nimport { publishReusablePrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport {\n PrincipalHistoryEvidenceUnavailableError,\n type PrincipalHistorySelectionOptions,\n selectRecoveredPrincipalHistory,\n} from \"./principalHistoryRecoveryReferences\";\nimport {\n type PrincipalHistoryRecoveryStage,\n restorePrincipalHistoryRecoveryStage,\n} from \"./principalHistoryRecoveryStage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"./principalHistoryRecoveryVerification\";\n\nclass PrincipalHistoryPrefixDisconnectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PrincipalHistoryPrefixDisconnectedError\";\n }\n}\n\n/** Stored current artifacts of a completed stage failed their signed-history check. */\nclass StoredPrincipalCurrentRejectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"StoredPrincipalCurrentRejectedError\";\n }\n}\n\nfunction currentArtifacts(\n page: PrincipalPolicyPageResponse,\n): PrincipalPolicyPageCurrent {\n return {\n currentState: page.currentState,\n currentPayload: page.currentPayload,\n currentProjection: page.currentProjection,\n currentGrants: page.currentGrants,\n currentMemberEnvelopes: page.currentMemberEnvelopes,\n };\n}\n\nfunction recoveryIsCurrent(\n input: RecoverPrincipalPolicyHistoryOptions,\n): boolean {\n return !input.signal?.aborted && input.stillCurrent();\n}\n\nfunction assertCurrent(input: RecoverPrincipalPolicyHistoryOptions): void {\n assertProjectionVerificationCurrent(() => recoveryIsCurrent(input));\n}\n\nfunction assertExpectedHead(\n current: PrincipalPolicyPageCurrent,\n expectedHead: RecoverPrincipalPolicyHistoryOptions[\"expectedHead\"],\n): void {\n for (const field of [\n \"principalType\",\n \"principalId\",\n \"version\",\n \"stateHash\",\n \"keyEpoch\",\n \"keyFingerprint\",\n ] as const) {\n if (current.currentState[field] !== expectedHead[field])\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history page does not match its requested head\",\n );\n }\n}\n\nasync function acceptPage(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n response: PrincipalPolicyPageResponse,\n): Promise<void> {\n const page = structuredClone(response);\n assertCurrent(input);\n assertExpectedHead(page, input.expectedHead);\n if (stage.complete) {\n if (\n page.previousStates.length !== 0 ||\n page.historyPage.nextAfterVersion !== null\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed history returned additional entries\",\n );\n stage.current = currentArtifacts(page);\n return;\n }\n const complete = page.historyPage.nextAfterVersion === null;\n const current = currentArtifacts(page);\n const entries = [...page.previousStates];\n if (complete)\n entries.push({\n state: current.currentState,\n projection: current.currentProjection,\n grants: current.currentGrants,\n });\n assertPrincipalHistoryVerificationMode(input, entries);\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { ...current, previousStates: page.previousStates },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Principal history signer identity could not be authenticated\",\n );\n const externalAuthority = await input.loadExternalAuthority?.(\n entries.flatMap(({ state }) =>\n state.externalAuthority ? [state.externalAuthority] : [],\n ),\n );\n const appended = await stage.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) {\n if (appended.error.code === \"stale_predecessor\")\n throw new PrincipalHistoryPrefixDisconnectedError(appended.error);\n throw appended.error;\n }\n const next = {\n id: stage.id,\n organizationId: input.organizationId,\n currentJson: JSON.stringify(current),\n afterVersion: appended.value.throughVersion - (complete ? 1 : 0),\n complete,\n };\n const protectedProgress = await stage.verifier.exportProgress(\n await principalHistoryStageProtection(\n input.protection,\n input.expectedHead,\n next,\n ),\n );\n if (!protectedProgress.ok) throw protectedProgress.error;\n const saved = { ...next, progress: protectedProgress.value };\n await savePrincipalHistoryStage({\n execSql: input.execSql,\n stage: saved,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId: stage.scopeId,\n organizationId: input.organizationId,\n entries,\n nodes: appended.value.indexNodes,\n }),\n previousProgress: stage.saved?.progress ?? null,\n stillCurrent: () => recoveryIsCurrent(input),\n });\n stage.current = current;\n stage.saved = saved;\n stage.complete = complete;\n}\n\nasync function finishRecovery(\n input: PrincipalHistorySelectionOptions,\n stage: PrincipalHistoryRecoveryStage,\n checkpoint: PrincipalPolicyCheckpoint | null,\n storedCurrent: boolean,\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (!stage.current || !stage.complete)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history ended before its pinned head\",\n );\n const history = stage.verifier.finish(input.expectedHead);\n if (!history.ok) throw history.error;\n const selected = await selectRecoveredPrincipalHistory({\n options: input,\n scopeId: stage.scopeId,\n history: history.value,\n checkpoint,\n });\n const current = await verifyPrincipalPolicyCurrent({\n current: stage.current,\n history: selected,\n });\n if (!current.ok) {\n if (storedCurrent)\n throw new StoredPrincipalCurrentRejectedError(current.error);\n throw current.error;\n }\n verifyPrincipalPolicyCheckpoint({\n chain: current.value.retainedHistory,\n currentState: current.value.state,\n localCheckpoint: checkpoint,\n });\n const latest = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (\n latest?.version !== checkpoint?.version ||\n latest?.stateHash !== checkpoint?.stateHash\n )\n throw new PrincipalHistoryRecoveryRaceError(\n \"Local principal checkpoint changed during history recovery\",\n );\n assertCurrent(input);\n if (!input.offline)\n await publishReusablePrincipalHistoryPrefix(\n input,\n stage.scopeId,\n stage.verifier,\n stage.current,\n );\n assertCurrent(input);\n return { current: stage.current, policy: current.value };\n}\n\nfunction completedStageMatchesHead(\n stage: PrincipalHistoryRecoveryStage,\n expectedHead: RecoverPrincipalPolicyHistoryOptions[\"expectedHead\"],\n): boolean {\n if (!stage.complete || !stage.current) return false;\n try {\n assertExpectedHead(stage.current, expectedHead);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Returns whether the stage's current artifacts came from local storage. A\n * completed stage already authenticates every signed entry through the exact\n * pinned head, so an online read of that head could only return the pinned\n * bytes or refuse. Server-current freshness belongs to the caller's discovery.\n */\nasync function readRecoveryPages(\n input: RecoverPrincipalPolicyHistoryOptions,\n stage: PrincipalHistoryRecoveryStage,\n): Promise<boolean> {\n if (input.offline) {\n if (!stage.complete || !stage.current)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed principal history is unavailable offline\",\n );\n assertExpectedHead(stage.current, input.expectedHead);\n return true;\n }\n if (completedStageMatchesHead(stage, input.expectedHead)) return true;\n let receivedFinalPage = false;\n for await (const result of input.historyReader.getPrincipalPolicyPages(\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n {\n signal: input.signal,\n stateHash: input.expectedHead.stateHash,\n ...(stage.saved && stage.current\n ? {\n resume: {\n current: stage.current,\n afterVersion: stage.saved.afterVersion,\n },\n }\n : { afterVersion: stage.initialAfterVersion }),\n },\n )) {\n if (!result.ok) {\n // A rejected transport pin cannot justify skipping history on retry.\n // Discard only this operation's progress, then let a new call replay it.\n if (result.kind === \"shape\" && stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n throw new PrincipalPolicyHistoryReadError(result);\n }\n await acceptPage(input, stage, result.data);\n receivedFinalPage = result.data.historyPage.nextAfterVersion === null;\n }\n if (!receivedFinalPage)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Principal history transport did not complete\",\n );\n return false;\n}\n\nasync function recover(\n input: PrincipalHistorySelectionOptions,\n allowEvidenceRebuild = true,\n): Promise<RecoveredPrincipalPolicyHistory> {\n assertCurrent(input);\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n input.expectedHead.principalType,\n input.expectedHead.principalId,\n );\n if (checkpoint && input.expectedHead.version < checkpoint.version)\n throw new KeyingVerificationError(\n input.offline ? \"missing_dependency\" : \"rollback\",\n \"Requested principal history predates the local checkpoint\",\n );\n // Validate the requested pin/selection before creating any disposable caches.\n createPrincipalPolicyHistoryVerifier({\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n localCheckpoint: checkpoint,\n retainedReferences: input.retainedReferences ?? [],\n });\n const historyInput: PrincipalPolicyHistoryInput = {\n principalType: input.expectedHead.principalType,\n principalId: input.expectedHead.principalId,\n };\n const stage = await restorePrincipalHistoryRecoveryStage(\n input,\n historyInput,\n allowEvidenceRebuild,\n );\n try {\n if (stage.fromCache)\n await validatePrincipalHistoryRecoveryAuthority(input, stage.verifier);\n const stored = await readRecoveryPages(input, stage);\n return await finishRecovery(\n input,\n stage,\n checkpoint,\n stored && !input.offline,\n );\n } catch (error) {\n const lostEvidence =\n error instanceof PrincipalHistoryEvidenceUnavailableError;\n // Disposable stored artifacts never refuse an online reader: replay them.\n const disposable =\n error instanceof PrincipalHistoryPrefixDisconnectedError ||\n error instanceof StoredPrincipalCurrentRejectedError;\n if (!lostEvidence && !disposable) throw error;\n if (stage.saved)\n await discardPrincipalHistoryStage(input.execSql, stage.saved, () =>\n recoveryIsCurrent(input),\n );\n if (\n !input.offline &&\n allowEvidenceRebuild &&\n (lostEvidence || stage.fromCache)\n )\n return recover(input, false);\n throw error.verificationError;\n }\n}\n\n/**\n * Recover one exact head with bounded retained history and durable checked progress.\n * The result is a sparse current-policy capability; this does not advance app checkpoints.\n * Retain organization version 1 when the result will establish founder binding.\n */\nexport function recoverPrincipalPolicyHistory(\n options: RecoverPrincipalPolicyHistoryOptions,\n): Promise<RecoveredPrincipalPolicyHistory> {\n return recoverPrincipalPolicyHistoryWithVersions(options, []);\n}\n\n/** Internal bounded display selection; missing proof rows use the normal single rebuild. */\nexport async function recoverPrincipalPolicyHistoryWithVersions(\n options: RecoverPrincipalPolicyHistoryOptions,\n retainedVersions: readonly number[],\n): Promise<RecoveredPrincipalPolicyHistory> {\n if (\n !Array.isArray(retainedVersions) ||\n retainedVersions.length + (options.retainedReferences?.length ?? 0) >\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT ||\n retainedVersions.some(\n (version) =>\n !Number.isSafeInteger(version) ||\n version < 1 ||\n version > options.expectedHead.version,\n )\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Principal display history selection exceeds its bounded range\",\n );\n if (options.offline !== undefined && typeof options.offline !== \"boolean\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid principal history transport mode\",\n );\n if (\n !options.organizationId ||\n (options.expectedHead.principalType === \"organization\" &&\n options.expectedHead.principalId !== options.organizationId)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal history organization scope is invalid\",\n );\n if (\n options.retainedReferences?.some(\n (reference) => reference.version > options.expectedHead.version,\n )\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested history reference is beyond the recovery head\",\n );\n const input = {\n ...options,\n historyVerification: options.historyVerification ?? \"standard\",\n expectedHead: structuredClone(options.expectedHead),\n retainedReferences: structuredClone(options.retainedReferences ?? []),\n retainedVersions: [...retainedVersions],\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n input.protection.context = principalHistoryVerificationContext(input);\n return await recover(input);\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n"]}
|
|
@@ -28,7 +28,7 @@ async function readPublicPages(input, initial) {
|
|
|
28
28
|
// Completed progress already verified every signed entry through the cited
|
|
29
29
|
// head; a read pinned to that head could only repeat it or refuse.
|
|
30
30
|
if (!input.offline && !progress.completedHead) {
|
|
31
|
-
for await (const result of input.
|
|
31
|
+
for await (const result of input.historyReader.getProjectionPolicyHistoryPages(input.source, { afterVersion: progress.afterVersion, signal: input.signal })) {
|
|
32
32
|
assertProjectionVerificationCurrent(current);
|
|
33
33
|
if (!result.ok)
|
|
34
34
|
throw new PrincipalPolicyHistoryReadError(result);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recoverPubl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;QAC3C,UAAU,CAAC,OAAO;QAClB,OAAO,CAAC,YAAY,KAAK,IAAI;QAC7B,OAAO,CAAC,gBAAgB,IAAI,IAAI;KACjC,CAAC,CAAC;IACH,MAAM,KAAK,GAAG;QACZ,GAAG,OAAO;QACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC;QACvC,UAAU;KACX,CAAC;IACF,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IACvD,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPageResponse,\n type PrincipalPolicySnapshotPageResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport type { PrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { PrincipalPolicyHistoryReadError } from \"./principalHistoryRecoveryTypes\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPageResponse,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPageResponse(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPageResponse | undefined;\n // Completed progress already verified every signed entry through the cited\n // head; a read pinned to that head could only repeat it or refuse.\n if (!input.offline && !progress.completedHead) {\n for await (const result of input.apiClient.getProjectionPolicyHistoryPages(\n input.source,\n { afterVersion: progress.afterVersion, signal: input.signal },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (progress.completedHead)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n progress = await appendPublicPrincipalHistoryPage(input, progress, page);\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n // A signed cached candidate need not belong to this requested chain. Only\n // reused progress permits one replay; a fresh disconnected chain fails.\n if (mayReplay && initial.afterVersion > 0)\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await loadPrincipalHistoryReference({\n execSql: input.execSql,\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n if (lastPage) {\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n }\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<RecoveredPublicPrincipalHistory> {\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix);\n } catch (error) {\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix);\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.historicalProof !== undefined &&\n typeof options.historicalProof !== \"boolean\") ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"recoverPublicPrincipalHistory.js","sourceRoot":"","sources":["recoverPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAEvB,4BAA4B,EAC5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,qCAAqC,GAEtC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAE3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,sCAAsC,EAAE,MAAM,mCAAmC,CAAC;AAC3F,OAAO,EACL,gCAAgC,EAChC,6CAA6C,GAC9C,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,mCAAmC,EACnC,qCAAqC,GACtC,MAAM,kCAAkC,CAAC;AAO1C,SAAS,UAAU,CACjB,KAAoC,EACpC,IAAyC,EACzC,KAAa;IAEb,IACE,CAAC,qCAAqC,CAAC,IAAI,CAAC;QAC5C,CAAC,6BAA6B,CAAC,IAAI,CAAC,YAAY,EAAE,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC;QACpE,IAAI,CAAC,WAAW,CAAC,YAAY,KAAK,KAAK;QAEvC,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,kEAAkE,CACnE,CAAC;IACJ,MAAM,OAAO,GAAG,KAAK,GAAG,IAAI,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AAW;QAC5C,kBAAkB,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC;KAC1C,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACrE,UAAU,CAAC,OAAO,GAAG,4BAA4B,CAAC;QAChD,2CAA2C;QAC3C,UAAU,CAAC,OAAO;QAClB,OAAO,CAAC,YAAY,KAAK,IAAI;QAC7B,OAAO,CAAC,gBAAgB,IAAI,IAAI;KACjC,CAAC,CAAC;IACH,MAAM,KAAK,GAAG;QACZ,GAAG,OAAO;QACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC;QACvC,UAAU;KACX,CAAC;IACF,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IACvD,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPageResponse,\n type PrincipalPolicySnapshotPageResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport type { PrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { PrincipalPolicyHistoryReadError } from \"./principalHistoryRecoveryTypes\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPageResponse,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPageResponse(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPageResponse | undefined;\n // Completed progress already verified every signed entry through the cited\n // head; a read pinned to that head could only repeat it or refuse.\n if (!input.offline && !progress.completedHead) {\n for await (const result of input.historyReader.getProjectionPolicyHistoryPages(\n input.source,\n { afterVersion: progress.afterVersion, signal: input.signal },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (progress.completedHead)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n progress = await appendPublicPrincipalHistoryPage(input, progress, page);\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n // A signed cached candidate need not belong to this requested chain. Only\n // reused progress permits one replay; a fresh disconnected chain fails.\n if (mayReplay && initial.afterVersion > 0)\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await loadPrincipalHistoryReference({\n execSql: input.execSql,\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n if (lastPage) {\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n }\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<RecoveredPublicPrincipalHistory> {\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix);\n } catch (error) {\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix);\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.historicalProof !== undefined &&\n typeof options.historicalProof !== \"boolean\") ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
|
|
@@ -102,7 +102,7 @@ async function recoverScopedPrincipalPolicyHistoryInBatch(options, memo) {
|
|
|
102
102
|
if (!options.organizationId)
|
|
103
103
|
throw new KeyingVerificationError("object_mismatch", "Principal recovery requires an organization scope");
|
|
104
104
|
const input = {
|
|
105
|
-
|
|
105
|
+
historyReader: options.historyReader,
|
|
106
106
|
execSql: options.execSql,
|
|
107
107
|
organizationId: options.organizationId,
|
|
108
108
|
offline: options.offline,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recoverScopedPrincipalPolicyHistory.js","sourceRoot":"","sources":["recoverScopedPrincipalPolicyHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EACL,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAEvG,OAAO,EACL,iCAAiC,GAGlC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,kCAAkC,GAEnC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,6BAA6B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O,EAAE,EAAE,CAAC,0CAA0C,CAAC,OAAO,CAAC,CAAC;AAEnE,KAAK,UAAU,oBAAoB,CACjC,KAAiD,EACjD,OAA6C;IAE7C,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO,EAAE,CAAC;IAClC,OAAO;QACL,WAAW,EAAE,MAAM,2BAA2B,CAC5C,OAAO,EACP,KAAK,CAAC,WAAW,CAAC,aAAa,IAAI,KAAK,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,CAC/D;KACF,CAAC;AACJ,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,uCAAuC,CACrD,OAA8B;IAC5B,WAAW,EAAE,IAAI,GAAG,EAAE;IACtB,MAAM,EAAE,IAAI,GAAG,EAAE;CAClB;IAED,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,0CAA0C,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport {\n directoryHistoryProtection,\n scopedGroupHistoryProtection,\n} from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { RecoveredPrincipalHistoryPage } from \"./loadRecoveredPrincipalHistoryPage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n type PrincipalRecoveryContext,\n PrincipalRecoveryDirectoryAdvanced,\n type RecoveredPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\nimport {\n createPrincipalRecoveryReader,\n type PrincipalRecoveryMemo,\n} from \"./principalRecoveryMemo\";\nimport { recoverPrincipalHistoryPage } from \"./recoverPrincipalHistoryPage\";\nimport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n\nexport interface RecoverScopedPrincipalPolicyHistoryOptions\n extends PrincipalRecoveryContext {\n readonly reference: ReferencedPrincipalHead;\n /** Optional bounded display history ending before this exclusive version. */\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\nexport interface RecoveredScopedPrincipalPolicyHistory\n extends RecoveredPrincipalPolicyHistory {\n /** Submit these with policy when atomically admitting its organization scope. */\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\n/** Internal result: valid only while every evidence producer behind it is. */\nexport interface ScopedPrincipalPolicyRecovery\n extends RecoveredScopedPrincipalPolicyHistory {\n readonly stillCurrent: () => boolean;\n}\n\nexport type ScopedPrincipalPolicyRecoveryBatch = (\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n) => Promise<ScopedPrincipalPolicyRecovery>;\n\nfunction groupHead(directory: RecoveredPolicyDirectory, principalId: string) {\n const head = directory.descriptor.groupHeads.find(\n (entry) => entry.principalId === principalId,\n );\n if (!head)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Group is absent from the signed organization directory\",\n );\n return head;\n}\n\nfunction authorityHead(state: ReferencedPrincipalHead) {\n return {\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n}\n\nasync function recoverScopedPolicy(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<ScopedPrincipalPolicyRecovery> {\n if (\n input.reference.principalType === \"organization\" &&\n input.reference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Requested organization policy is outside its scope\",\n );\n const read = createPrincipalRecoveryReader(input, memo);\n // Reused or derived evidence keeps its producers' lifetimes to its use.\n const stillCurrent = () =>\n !input.signal?.aborted && input.stillCurrent() && read.stillCurrent();\n const directory = await read.directory(\n input.reference.principalType === \"organization\" ? [input.reference] : [],\n );\n if (input.reference.principalType === \"organization\")\n return {\n current: directory.current,\n policy: directory.policy,\n dependencies: [],\n stillCurrent,\n ...(await selectDisplayHistory(input, {\n ...input,\n expectedHead: principalPolicyReferenceFromBundle(directory.current),\n protection: directoryHistoryProtection(input.protection),\n })),\n };\n const expectedHead = groupHead(directory, input.reference.principalId);\n if (input.reference.version > expectedHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n const adminHead = groupHead(directory, directory.descriptor.adminGroupId);\n const isAdmins = expectedHead.principalId === adminHead.principalId;\n let admins: VerifiedPrincipalPolicyCurrent | null = null;\n if (!isAdmins) {\n admins = (await read.admins(adminHead)).policy;\n }\n const loadExternalAuthority = async (\n citations: readonly ReferencedPrincipalHead[],\n ): Promise<PrincipalPolicyExternalAuthority | undefined> => {\n const references = new Map<string, ReferencedPrincipalHead>();\n for (const citation of citations) {\n if (citation.principalId !== adminHead.principalId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Group cites another organization's Admins authority\",\n );\n if (citation.version > adminHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n references.set(`${citation.version}:${citation.stateHash}`, citation);\n }\n if (!references.size) return undefined;\n const recovered = await read.admins(adminHead, [...references.values()]);\n return {\n currentHead: adminHead,\n states: recovered.policy.retainedHistory.map(({ state, projection }) => ({\n head: authorityHead(state),\n projection,\n })),\n };\n };\n const recoveryOptions: RecoverPrincipalPolicyHistoryOptions = {\n ...input,\n expectedHead,\n retainedReferences: [input.reference],\n historyVerification: isAdmins ? \"direct-admins\" : \"standard\",\n ...(isAdmins\n ? {}\n : {\n protection: scopedGroupHistoryProtection(\n input.protection,\n input.organizationId,\n adminHead.principalId,\n ),\n }),\n ...(isAdmins ? {} : { loadExternalAuthority }),\n };\n const recovered = isAdmins\n ? await read.admins(expectedHead, [input.reference])\n : await recoverPrincipalPolicyHistory(recoveryOptions);\n return {\n ...recovered,\n dependencies: admins ? [directory.policy, admins] : [directory.policy],\n stillCurrent,\n ...(await selectDisplayHistory(input, recoveryOptions)),\n };\n}\n\n/** Recover signed directory and strict Admins dependencies without full histories. */\nasync function recoverScopedPrincipalPolicyHistoryInBatch(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<ScopedPrincipalPolicyRecovery> {\n if (options.offline !== undefined && typeof options.offline !== \"boolean\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid principal history transport mode\",\n );\n if (!options.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal recovery requires an organization scope\",\n );\n const input = {\n apiClient: options.apiClient,\n execSql: options.execSql,\n organizationId: options.organizationId,\n offline: options.offline,\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n signal: options.signal,\n stillCurrent: options.stillCurrent,\n reference: structuredClone(options.reference),\n historyPage: options.historyPage ? { ...options.historyPage } : undefined,\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n // Reject malformed exact citations before any discovery or disposable writes.\n createPrincipalPolicyHistoryVerifier({\n principalId: input.reference.principalId,\n principalType: input.reference.principalType,\n retainedReferences: [input.reference],\n });\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n const recovered = await recoverScopedPolicy(input, memo);\n assertProjectionVerificationCurrent(recovered.stillCurrent);\n return recovered;\n } catch (error) {\n if (!(error instanceof PrincipalRecoveryDirectoryAdvanced)) throw error;\n memo?.directories.clear();\n memo?.admins.clear();\n if (input.offline)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested principal evidence is newer than the offline directory\",\n );\n }\n }\n throw new PrincipalHistoryRecoveryRaceError(\n \"Organization directory remains behind the requested policy evidence\",\n );\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n\nexport function recoverScopedPrincipalPolicyHistory(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n return recoverScopedPrincipalPolicyHistoryInBatch(options);\n}\n\n/** Internal unbatched recovery that keeps its result's lifetime. */\nexport const recoverLeasedScopedPrincipalPolicyHistory: ScopedPrincipalPolicyRecoveryBatch =\n (options) => recoverScopedPrincipalPolicyHistoryInBatch(options);\n\nasync function selectDisplayHistory(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n options: RecoverPrincipalPolicyHistoryOptions,\n) {\n if (!input.historyPage) return {};\n return {\n historyPage: await recoverPrincipalHistoryPage(\n options,\n input.historyPage.beforeVersion ?? input.reference.version + 1,\n ),\n };\n}\n\n/** Internal runtime batch: shared results never outlive its operation or caller. */\nexport function createScopedPrincipalPolicyHistoryBatch(\n memo: PrincipalRecoveryMemo = {\n directories: new Map(),\n admins: new Map(),\n },\n): ScopedPrincipalPolicyRecoveryBatch {\n return (options) => recoverScopedPrincipalPolicyHistoryInBatch(options, memo);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"recoverScopedPrincipalPolicyHistory.js","sourceRoot":"","sources":["recoverScopedPrincipalPolicyHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EACL,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAEvG,OAAO,EACL,iCAAiC,GAGlC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,kCAAkC,GAEnC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,6BAA6B,GAE9B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EA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C,CAAC;AAEnE,KAAK,UAAU,oBAAoB,CACjC,KAAiD,EACjD,OAA6C;IAE7C,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO,EAAE,CAAC;IAClC,OAAO;QACL,WAAW,EAAE,MAAM,2BAA2B,CAC5C,OAAO,EACP,KAAK,CAAC,WAAW,CAAC,aAAa,IAAI,KAAK,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,CAC/D;KACF,CAAC;AACJ,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,uCAAuC,CACrD,OAA8B;IAC5B,WAAW,EAAE,IAAI,GAAG,EAAE;IACtB,MAAM,EAAE,IAAI,GAAG,EAAE;CAClB;IAED,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,0CAA0C,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport {\n directoryHistoryProtection,\n scopedGroupHistoryProtection,\n} from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { RecoveredPrincipalHistoryPage } from \"./loadRecoveredPrincipalHistoryPage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n type PrincipalRecoveryContext,\n PrincipalRecoveryDirectoryAdvanced,\n type RecoveredPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\nimport {\n createPrincipalRecoveryReader,\n type PrincipalRecoveryMemo,\n} from \"./principalRecoveryMemo\";\nimport { recoverPrincipalHistoryPage } from \"./recoverPrincipalHistoryPage\";\nimport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n\nexport interface RecoverScopedPrincipalPolicyHistoryOptions\n extends PrincipalRecoveryContext {\n readonly reference: ReferencedPrincipalHead;\n /** Optional bounded display history ending before this exclusive version. */\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\nexport interface RecoveredScopedPrincipalPolicyHistory\n extends RecoveredPrincipalPolicyHistory {\n /** Submit these with policy when atomically admitting its organization scope. */\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\n/** Internal result: valid only while every evidence producer behind it is. */\nexport interface ScopedPrincipalPolicyRecovery\n extends RecoveredScopedPrincipalPolicyHistory {\n readonly stillCurrent: () => boolean;\n}\n\nexport type ScopedPrincipalPolicyRecoveryBatch = (\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n) => Promise<ScopedPrincipalPolicyRecovery>;\n\nfunction groupHead(directory: RecoveredPolicyDirectory, principalId: string) {\n const head = directory.descriptor.groupHeads.find(\n (entry) => entry.principalId === principalId,\n );\n if (!head)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Group is absent from the signed organization directory\",\n );\n return head;\n}\n\nfunction authorityHead(state: ReferencedPrincipalHead) {\n return {\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n}\n\nasync function recoverScopedPolicy(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<ScopedPrincipalPolicyRecovery> {\n if (\n input.reference.principalType === \"organization\" &&\n input.reference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Requested organization policy is outside its scope\",\n );\n const read = createPrincipalRecoveryReader(input, memo);\n // Reused or derived evidence keeps its producers' lifetimes to its use.\n const stillCurrent = () =>\n !input.signal?.aborted && input.stillCurrent() && read.stillCurrent();\n const directory = await read.directory(\n input.reference.principalType === \"organization\" ? [input.reference] : [],\n );\n if (input.reference.principalType === \"organization\")\n return {\n current: directory.current,\n policy: directory.policy,\n dependencies: [],\n stillCurrent,\n ...(await selectDisplayHistory(input, {\n ...input,\n expectedHead: principalPolicyReferenceFromBundle(directory.current),\n protection: directoryHistoryProtection(input.protection),\n })),\n };\n const expectedHead = groupHead(directory, input.reference.principalId);\n if (input.reference.version > expectedHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n const adminHead = groupHead(directory, directory.descriptor.adminGroupId);\n const isAdmins = expectedHead.principalId === adminHead.principalId;\n let admins: VerifiedPrincipalPolicyCurrent | null = null;\n if (!isAdmins) {\n admins = (await read.admins(adminHead)).policy;\n }\n const loadExternalAuthority = async (\n citations: readonly ReferencedPrincipalHead[],\n ): Promise<PrincipalPolicyExternalAuthority | undefined> => {\n const references = new Map<string, ReferencedPrincipalHead>();\n for (const citation of citations) {\n if (citation.principalId !== adminHead.principalId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Group cites another organization's Admins authority\",\n );\n if (citation.version > adminHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n references.set(`${citation.version}:${citation.stateHash}`, citation);\n }\n if (!references.size) return undefined;\n const recovered = await read.admins(adminHead, [...references.values()]);\n return {\n currentHead: adminHead,\n states: recovered.policy.retainedHistory.map(({ state, projection }) => ({\n head: authorityHead(state),\n projection,\n })),\n };\n };\n const recoveryOptions: RecoverPrincipalPolicyHistoryOptions = {\n ...input,\n expectedHead,\n retainedReferences: [input.reference],\n historyVerification: isAdmins ? \"direct-admins\" : \"standard\",\n ...(isAdmins\n ? {}\n : {\n protection: scopedGroupHistoryProtection(\n input.protection,\n input.organizationId,\n adminHead.principalId,\n ),\n }),\n ...(isAdmins ? {} : { loadExternalAuthority }),\n };\n const recovered = isAdmins\n ? await read.admins(expectedHead, [input.reference])\n : await recoverPrincipalPolicyHistory(recoveryOptions);\n return {\n ...recovered,\n dependencies: admins ? [directory.policy, admins] : [directory.policy],\n stillCurrent,\n ...(await selectDisplayHistory(input, recoveryOptions)),\n };\n}\n\n/** Recover signed directory and strict Admins dependencies without full histories. */\nasync function recoverScopedPrincipalPolicyHistoryInBatch(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<ScopedPrincipalPolicyRecovery> {\n if (options.offline !== undefined && typeof options.offline !== \"boolean\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid principal history transport mode\",\n );\n if (!options.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal recovery requires an organization scope\",\n );\n const input = {\n historyReader: options.historyReader,\n execSql: options.execSql,\n organizationId: options.organizationId,\n offline: options.offline,\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n signal: options.signal,\n stillCurrent: options.stillCurrent,\n reference: structuredClone(options.reference),\n historyPage: options.historyPage ? { ...options.historyPage } : undefined,\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n // Reject malformed exact citations before any discovery or disposable writes.\n createPrincipalPolicyHistoryVerifier({\n principalId: input.reference.principalId,\n principalType: input.reference.principalType,\n retainedReferences: [input.reference],\n });\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n const recovered = await recoverScopedPolicy(input, memo);\n assertProjectionVerificationCurrent(recovered.stillCurrent);\n return recovered;\n } catch (error) {\n if (!(error instanceof PrincipalRecoveryDirectoryAdvanced)) throw error;\n memo?.directories.clear();\n memo?.admins.clear();\n if (input.offline)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested principal evidence is newer than the offline directory\",\n );\n }\n }\n throw new PrincipalHistoryRecoveryRaceError(\n \"Organization directory remains behind the requested policy evidence\",\n );\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n\nexport function recoverScopedPrincipalPolicyHistory(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n return recoverScopedPrincipalPolicyHistoryInBatch(options);\n}\n\n/** Internal unbatched recovery that keeps its result's lifetime. */\nexport const recoverLeasedScopedPrincipalPolicyHistory: ScopedPrincipalPolicyRecoveryBatch =\n (options) => recoverScopedPrincipalPolicyHistoryInBatch(options);\n\nasync function selectDisplayHistory(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n options: RecoverPrincipalPolicyHistoryOptions,\n) {\n if (!input.historyPage) return {};\n return {\n historyPage: await recoverPrincipalHistoryPage(\n options,\n input.historyPage.beforeVersion ?? input.reference.version + 1,\n ),\n };\n}\n\n/** Internal runtime batch: shared results never outlive its operation or caller. */\nexport function createScopedPrincipalPolicyHistoryBatch(\n memo: PrincipalRecoveryMemo = {\n directories: new Map(),\n admins: new Map(),\n },\n): ScopedPrincipalPolicyRecoveryBatch {\n return (options) => recoverScopedPrincipalPolicyHistoryInBatch(options, memo);\n}\n"]}
|
|
@@ -5,6 +5,7 @@ import { assertProjectionVerificationCurrent, } from "../../data/keyingProjectio
|
|
|
5
5
|
import { readPrincipalHistoryProtection } from "../../data/principals/principalHistoryRuntime.js";
|
|
6
6
|
import { createPrincipalCurrentRecoveryBatch } from "./principalCurrentRecoveryBatch.js";
|
|
7
7
|
import { PrincipalHistoryRecoveryRaceError, PrincipalPolicyHistoryReadError, } from "./principalHistoryRecoveryTypes.js";
|
|
8
|
+
import { apiPrincipalPolicyPageReader, } from "./principalPolicyHistoryReader.js";
|
|
8
9
|
import { recoverWithPrincipalLocalPreference } from "./principalRecoveryLocalPreference.js";
|
|
9
10
|
import { queuePrincipalRecovery } from "./principalRecoveryQueue.js";
|
|
10
11
|
/** Keep the private recovery key inside its runtime lease while resolving cited evidence. */
|
|
@@ -17,8 +18,8 @@ export function createRuntimePrincipalPolicyResolver(runtime, options = {}) {
|
|
|
17
18
|
/** Keep current artifacts with their verified evidence and private runtime lifetime. */
|
|
18
19
|
export function createRuntimePrincipalPolicyCurrentResolver(runtime) {
|
|
19
20
|
const lease = readPrincipalHistoryProtection(runtime);
|
|
20
|
-
const
|
|
21
|
-
if (!lease || !
|
|
21
|
+
const historyReader = apiPrincipalPolicyPageReader(runtime.apiClient);
|
|
22
|
+
if (!lease || !historyReader)
|
|
22
23
|
return undefined;
|
|
23
24
|
const batches = new WeakMap();
|
|
24
25
|
const recoverFor = (batch) => {
|
|
@@ -43,7 +44,7 @@ export function createRuntimePrincipalPolicyCurrentResolver(runtime) {
|
|
|
43
44
|
const offline = runtime.state?.online === false;
|
|
44
45
|
try {
|
|
45
46
|
const options = {
|
|
46
|
-
|
|
47
|
+
historyReader,
|
|
47
48
|
execSql: runtime.infra.execSql,
|
|
48
49
|
offline,
|
|
49
50
|
organizationId: input.organizationId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,mCAAmC,GAIpC,MAAM,+CAA+C,CAAC;AAEvD,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAK/F,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,OAAO,EACL,iCAAiC,EACjC,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,mCAAmC,EAAE,MAAM,oCAAoC,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAmBlE,6FAA6F;AAC7F,MAAM,UAAU,oCAAoC,CAClD,OAAuC,EACvC,UAAqD,EAAE;IAEvD,MAAM,OAAO,GAAG,2CAA2C,CAAC,OAAO,CAAC,CAAC;IACrE,OA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AC;YACnD,OAAO;gBACL,OAAO,EAAE,MAAM,CAAC,OAAO;gBACvB,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,MAAM,EAAE,MAAM,CAAC,MAAM;gBACrB,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,WAAW,EAAE,MAAM,CAAC,WAAW;gBAC/B,YAAY,EAAE,aAAa;aAC5B,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,IACE,KAAK,YAAY,+BAA+B;gBAChD,KAAK,YAAY,iCAAiC;gBAClD,CAAC,KAAK,YAAY,uBAAuB;oBACvC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC;gBAEtC,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACL,CACF,CAAC;AACN,CAAC;AAED,SAAS,wBAAwB,CAAC,KAAoC;IACpE,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO;IAC/B,MAAM,MAAM,GAAG,KAAK,CAAC,WAAW,CAAC,aAAa,CAAC;IAC/C,IACE,CAAC,KAAK,CAAC,SAAS;QAChB,CAAC,MAAM,KAAK,SAAS;YACnB,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;gBAC5B,MAAM,IAAI,CAAC;gBACX,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;QAE1C,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,iEAAiE,CAClE,CAAC;AACN,CAAC","sourcesContent":["import type {\n ApiClient,\n PrincipalPolicyPageCurrent,\n} from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyResolveRequest,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { RecoveredPrincipalHistoryPage } from \"./loadRecoveredPrincipalHistoryPage\";\nimport { createPrincipalCurrentRecoveryBatch } from \"./principalCurrentRecoveryBatch\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n} from \"./principalHistoryRecoveryTypes\";\nimport { recoverWithPrincipalLocalPreference } from \"./principalRecoveryLocalPreference\";\nimport { queuePrincipalRecovery } from \"./principalRecoveryQueue\";\nimport type { ScopedPrincipalPolicyRecovery } from \"./recoverScopedPrincipalPolicyHistory\";\n\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<\n Pick<\n ApiClient,\n \"getPrincipalPolicyPages\" | \"getProjectionPolicyHistoryPages\"\n >\n >;\n readonly infra: { readonly execSql: ExecSql };\n readonly state?: { readonly online: boolean } | undefined;\n readonly util: { readonly reportSecurityIncident: SecurityIncidentReporter };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\n/** Keep the private recovery key inside its runtime lease while resolving cited evidence. */\nexport function createRuntimePrincipalPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n options: { readonly preferLocalCurrent?: boolean } = {},\n): ReferencedPrincipalPolicyWarmer[\"resolveReference\"] {\n const resolve = createRuntimePrincipalPolicyCurrentResolver(runtime);\n return resolve\n ? (input) =>\n resolve({ ...input, preferLocalCurrent: options.preferLocalCurrent })\n : undefined;\n}\n\nexport interface ResolvedPrincipalPolicyCurrent\n extends ResolvedPrincipalPolicyEvidence {\n readonly current: PrincipalPolicyPageCurrent;\n /** Rows end at the selected reference; current/policy may describe a newer recovered head. */\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\ninterface PrincipalPolicyCurrentRequest\n extends Omit<PrincipalPolicyResolveRequest, \"reference\"> {\n readonly reference?: PrincipalPolicyResolveRequest[\"reference\"] | undefined;\n /** A read-model caller has selected this exact signed head; not a freshness read. */\n readonly preferLocalCurrent?: boolean | undefined;\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\n/** Keep current artifacts with their verified evidence and private runtime lifetime. */\nexport function createRuntimePrincipalPolicyCurrentResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n):\n | ((\n input: PrincipalPolicyCurrentRequest,\n ) => Promise<ResolvedPrincipalPolicyCurrent>)\n | undefined {\n const lease = readPrincipalHistoryProtection(runtime);\n const readPages = runtime.apiClient.getPrincipalPolicyPages?.bind(\n runtime.apiClient,\n );\n if (!lease || !readPages) return undefined;\n const batches = new WeakMap<\n object,\n ReturnType<typeof createPrincipalCurrentRecoveryBatch>\n >();\n const recoverFor = (batch: object | undefined) => {\n if (!batch) return createPrincipalCurrentRecoveryBatch();\n let recover = batches.get(batch);\n if (!recover) {\n recover = createPrincipalCurrentRecoveryBatch();\n batches.set(batch, recover);\n }\n return recover;\n };\n return (input) =>\n queuePrincipalRecovery(runtime.infra.execSql, input.organizationId, () =>\n runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: input.reference?.principalId ?? input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.policy.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n assertHistoryPageRequest(input);\n const offline = runtime.state?.online === false;\n try {\n const options = {\n apiClient: { getPrincipalPolicyPages: readPages },\n execSql: runtime.infra.execSql,\n offline,\n organizationId: input.organizationId,\n protection,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const batch = recoverFor(input.recoveryBatch);\n const result: ScopedPrincipalPolicyRecovery = input.reference\n ? await recoverWithPrincipalLocalPreference(\n batch.recover,\n {\n ...options,\n reference: input.reference,\n historyPage: input.historyPage,\n },\n input.preferLocalCurrent === true ||\n input.preferLocalHistory === true,\n input.preferLocalHistory === true,\n )\n : await batch.discover(options);\n // Reused evidence stays bound to every producer lifetime.\n const resultCurrent = () =>\n stillCurrent() && result.stillCurrent();\n assertProjectionVerificationCurrent(resultCurrent);\n return {\n current: result.current,\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n historyPage: result.historyPage,\n stillCurrent: resultCurrent,\n };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n error instanceof PrincipalHistoryRecoveryRaceError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n\nfunction assertHistoryPageRequest(input: PrincipalPolicyCurrentRequest) {\n if (!input.historyPage) return;\n const before = input.historyPage.beforeVersion;\n if (\n !input.reference ||\n (before !== undefined &&\n (!Number.isSafeInteger(before) ||\n before <= 1 ||\n before > input.reference.version + 1))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"History display requires a selected head and an in-range cursor\",\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAA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G,KAAK,CAAC,WAAW,CAAC,aAAa,CAAC;IAC/C,IACE,CAAC,KAAK,CAAC,SAAS;QAChB,CAAC,MAAM,KAAK,SAAS;YACnB,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;gBAC5B,MAAM,IAAI,CAAC;gBACX,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;QAE1C,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,iEAAiE,CAClE,CAAC;AACN,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyResolveRequest,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { RecoveredPrincipalHistoryPage } from \"./loadRecoveredPrincipalHistoryPage\";\nimport { createPrincipalCurrentRecoveryBatch } from \"./principalCurrentRecoveryBatch\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyHistoryReader,\n} from \"./principalPolicyHistoryReader\";\nimport { recoverWithPrincipalLocalPreference } from \"./principalRecoveryLocalPreference\";\nimport { queuePrincipalRecovery } from \"./principalRecoveryQueue\";\nimport type { ScopedPrincipalPolicyRecovery } from \"./recoverScopedPrincipalPolicyHistory\";\n\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<PrincipalPolicyHistoryReader>;\n readonly infra: { readonly execSql: ExecSql };\n readonly state?: { readonly online: boolean } | undefined;\n readonly util: { readonly reportSecurityIncident: SecurityIncidentReporter };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\n/** Keep the private recovery key inside its runtime lease while resolving cited evidence. */\nexport function createRuntimePrincipalPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n options: { readonly preferLocalCurrent?: boolean } = {},\n): ReferencedPrincipalPolicyWarmer[\"resolveReference\"] {\n const resolve = createRuntimePrincipalPolicyCurrentResolver(runtime);\n return resolve\n ? (input) =>\n resolve({ ...input, preferLocalCurrent: options.preferLocalCurrent })\n : undefined;\n}\n\nexport interface ResolvedPrincipalPolicyCurrent\n extends ResolvedPrincipalPolicyEvidence {\n readonly current: PrincipalPolicyPageCurrent;\n /** Rows end at the selected reference; current/policy may describe a newer recovered head. */\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\ninterface PrincipalPolicyCurrentRequest\n extends Omit<PrincipalPolicyResolveRequest, \"reference\"> {\n readonly reference?: PrincipalPolicyResolveRequest[\"reference\"] | undefined;\n /** A read-model caller has selected this exact signed head; not a freshness read. */\n readonly preferLocalCurrent?: boolean | undefined;\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\n/** Keep current artifacts with their verified evidence and private runtime lifetime. */\nexport function createRuntimePrincipalPolicyCurrentResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n):\n | ((\n input: PrincipalPolicyCurrentRequest,\n ) => Promise<ResolvedPrincipalPolicyCurrent>)\n | undefined {\n const lease = readPrincipalHistoryProtection(runtime);\n const historyReader = apiPrincipalPolicyPageReader(runtime.apiClient);\n if (!lease || !historyReader) return undefined;\n const batches = new WeakMap<\n object,\n ReturnType<typeof createPrincipalCurrentRecoveryBatch>\n >();\n const recoverFor = (batch: object | undefined) => {\n if (!batch) return createPrincipalCurrentRecoveryBatch();\n let recover = batches.get(batch);\n if (!recover) {\n recover = createPrincipalCurrentRecoveryBatch();\n batches.set(batch, recover);\n }\n return recover;\n };\n return (input) =>\n queuePrincipalRecovery(runtime.infra.execSql, input.organizationId, () =>\n runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: input.reference?.principalId ?? input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.policy.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n assertHistoryPageRequest(input);\n const offline = runtime.state?.online === false;\n try {\n const options = {\n historyReader,\n execSql: runtime.infra.execSql,\n offline,\n organizationId: input.organizationId,\n protection,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const batch = recoverFor(input.recoveryBatch);\n const result: ScopedPrincipalPolicyRecovery = input.reference\n ? await recoverWithPrincipalLocalPreference(\n batch.recover,\n {\n ...options,\n reference: input.reference,\n historyPage: input.historyPage,\n },\n input.preferLocalCurrent === true ||\n input.preferLocalHistory === true,\n input.preferLocalHistory === true,\n )\n : await batch.discover(options);\n // Reused evidence stays bound to every producer lifetime.\n const resultCurrent = () =>\n stillCurrent() && result.stillCurrent();\n assertProjectionVerificationCurrent(resultCurrent);\n return {\n current: result.current,\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n historyPage: result.historyPage,\n stillCurrent: resultCurrent,\n };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n error instanceof PrincipalHistoryRecoveryRaceError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n\nfunction assertHistoryPageRequest(input: PrincipalPolicyCurrentRequest) {\n if (!input.historyPage) return;\n const before = input.historyPage.beforeVersion;\n if (\n !input.reference ||\n (before !== undefined &&\n (!Number.isSafeInteger(before) ||\n before <= 1 ||\n before > input.reference.version + 1))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"History display requires a selected head and an in-range cursor\",\n );\n}\n"]}
|
|
@@ -4,6 +4,7 @@ import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVer
|
|
|
4
4
|
import { assertProjectionVerificationCurrent, } from "../../data/keyingProjectionVerification/types.js";
|
|
5
5
|
import { readPrincipalHistoryProtection } from "../../data/principals/principalHistoryRuntime.js";
|
|
6
6
|
import { PrincipalPolicyHistoryReadError } from "./principalHistoryRecoveryTypes.js";
|
|
7
|
+
import { apiProjectionPolicyHistoryReader } from "./principalPolicyHistoryReader.js";
|
|
7
8
|
import { isPrincipalRecoveryOutage } from "./principalRecoveryOutage.js";
|
|
8
9
|
import { queuePrincipalRecovery } from "./principalRecoveryQueue.js";
|
|
9
10
|
import { recoverProjectionPolicyHistory, } from "./recoverProjectionPolicyHistory.js";
|
|
@@ -20,8 +21,8 @@ async function recoverWithOutageFallback(options) {
|
|
|
20
21
|
}
|
|
21
22
|
export function createRuntimeProjectionPolicyResolver(runtime) {
|
|
22
23
|
const lease = readPrincipalHistoryProtection(runtime);
|
|
23
|
-
const
|
|
24
|
-
if (!lease || !
|
|
24
|
+
const historyReader = apiProjectionPolicyHistoryReader(runtime.apiClient);
|
|
25
|
+
if (!lease || !historyReader)
|
|
25
26
|
return undefined;
|
|
26
27
|
return (input) => queuePrincipalRecovery(runtime.infra.execSql, input.organizationId, () => runWithSecurityIncidentReporting(runtime.util.reportSecurityIncident, {
|
|
27
28
|
objectId: input.organizationId,
|
|
@@ -34,7 +35,7 @@ export function createRuntimeProjectionPolicyResolver(runtime) {
|
|
|
34
35
|
try {
|
|
35
36
|
const policies = await recoverWithOutageFallback({
|
|
36
37
|
...input,
|
|
37
|
-
|
|
38
|
+
historyReader,
|
|
38
39
|
execSql: runtime.infra.execSql,
|
|
39
40
|
protection,
|
|
40
41
|
stillCurrent,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtimeProjectionPolicyRecovery.js","sourceRoot":"","sources":["runtimeProjectionPolicyRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,mCAAmC,GAEpC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAEL,8BAA8B,GAC/B,MAAM,kCAAkC,CAAC;AAG1C,KAAK,UAAU,yBAAyB,CACtC,OAA+C;IAE/C,IAAI,CAAC;QACH,OAAO,MAAM,8BAA8B,CAAC,OAAO,CAAC,CAAC;IACvD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC1D,IAAI,OAAO,CAAC,OAAO,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC;YAAE,MAAM,KAAK,CAAC;QACtE,OAAO,8BAA8B,CAAC,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IACvE,CAAC;AACH,CAAC;AAED,MAAM,UAAU,qCAAqC,CACnD,OAAuC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oC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACL,CACF,CAAC;AACN,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport { PrincipalPolicyHistoryReadError } from \"./principalHistoryRecoveryTypes\";\nimport { apiProjectionPolicyHistoryReader } from \"./principalPolicyHistoryReader\";\nimport { isPrincipalRecoveryOutage } from \"./principalRecoveryOutage\";\nimport { queuePrincipalRecovery } from \"./principalRecoveryQueue\";\nimport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./recoverProjectionPolicyHistory\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"./runtimePolicyRecovery\";\n\nasync function recoverWithOutageFallback(\n options: ProjectionPolicyHistoryRecoveryOptions,\n) {\n try {\n return await recoverProjectionPolicyHistory(options);\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (options.offline || !isPrincipalRecoveryOutage(error)) throw error;\n return recoverProjectionPolicyHistory({ ...options, offline: true });\n }\n}\n\nexport function createRuntimeProjectionPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n const lease = readPrincipalHistoryProtection(runtime);\n const historyReader = apiProjectionPolicyHistoryReader(runtime.apiClient);\n if (!lease || !historyReader) return undefined;\n return (input) =>\n queuePrincipalRecovery(runtime.infra.execSql, input.organizationId, () =>\n runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.projection.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n try {\n const policies = await recoverWithOutageFallback({\n ...input,\n historyReader,\n execSql: runtime.infra.execSql,\n protection,\n stillCurrent,\n offline: runtime.state?.online === false,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n });\n return { policies, stillCurrent };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n"]}
|
|
@@ -36,7 +36,7 @@ function provisionedPolicyPages(policies) {
|
|
|
36
36
|
async function primeProvisionedPrincipalHistory(input) {
|
|
37
37
|
const { recover } = createPrincipalCurrentRecoveryBatch();
|
|
38
38
|
const options = {
|
|
39
|
-
|
|
39
|
+
historyReader: provisionedPolicyPages(input.policies),
|
|
40
40
|
execSql: input.execSql,
|
|
41
41
|
offline: false,
|
|
42
42
|
organizationId: input.organizationId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provisionedPrincipalHistory.js","sourceRoot":"","sources":["provisionedPrincipalHistory.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAMvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,6CAA6C,CAAC;AAClG,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAyB9E;;;;GAIG;AACH,SAAS,sBAAsB,CAC7B,QAAsC;IAEtC,MAAM,OAAO,GAAG;QACd,QAAQ,CAAC,YAAY;QACrB,Q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AAE;QACF,IAAI,YAAY,KAAK,KAAK,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QAC/C,mCAAmC,CAAC,YAAY,CAAC,CAAC;QAClD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QACzE,mCAAmC,CAAC,YAAY,CAAC,CAAC;QAClD,OAAO,QAAQ,EAAE,qBAAqB,KAAK,kBAAkB;YAC3D,CAAC,CAAC,QAAQ;YACV,CAAC,CAAC,IAAI,CAAC;IACX,CAAC,CAAC;IACF,MAAM,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,cAAc,EAAE,GAAG,EAAE,CAC/D,KAAK,CAAC,CAAC,EAAE,UAAU,EAAE,YAAY,EAAE,EAAE,EAAE,CACrC,gCAAgC,CAAC;QAC/B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,UAAU;QACV,0BAA0B;QAC1B,wDAAwD;QACxD,YAAY,EAAE,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,YAAY,EAAE;KACrD,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql, ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport { createPrincipalCurrentRecoveryBatch } from \"../principals/principalCurrentRecoveryBatch\";\nimport { queuePrincipalRecovery } from \"../principals/principalRecoveryQueue\";\n\n/** The version-1 policies a provisioning request signed and its response acknowledged. */\ninterface ProvisionedPrincipalPolicies {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}\n\n/**\n * Records verified recovery progress for an organization's founding policy\n * heads, so the device's first scoped recovery of them needs no history read.\n * It is bound to the provisioning scope: the database the bootstrap committed\n * to and the identity that signed it. Failure leaves the online path.\n */\nexport type ProvisionedPrincipalHistoryPrimer = (input: {\n /** The database client the provisioning bootstrap committed to. */\n readonly database: ExecSqlClientLike;\n /** Whether the identity that provisioned is still the active one. */\n readonly isCurrent: () => boolean;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly userId: string;\n}) => Promise<void>;\n\n/**\n * Serves only the acknowledged initial heads, each complete in one page. The\n * ordinary verifier still checks every signature, the directory binding and\n * strict Admins rules before any progress is saved.\n */\nfunction provisionedPolicyPages(\n policies: ProvisionedPrincipalPolicies,\n): Pick<ApiClient, \"getPrincipalPolicyPages\"> {\n const bundles = [\n policies.organization,\n policies.adminGroup,\n policies.memberGroup,\n ];\n return {\n async *getPrincipalPolicyPages(principalType, principalId, options = {}) {\n const bundle = bundles.find(\n ({ currentState }) =>\n currentState.principalType === principalType &&\n currentState.principalId === principalId,\n );\n if (\n !bundle ||\n options.resume !== undefined ||\n (options.afterVersion ?? 0) !== 0 ||\n (options.stateHash !== undefined &&\n options.stateHash !== bundle.currentState.stateHash)\n )\n throw new Error(\n \"Provisioned principal history holds only the acknowledged initial heads\",\n );\n yield {\n ok: true,\n data: {\n ...structuredClone(bundle),\n historyPage: { afterVersion: 0, nextAfterVersion: null },\n },\n };\n },\n };\n}\n\nasync function primeProvisionedPrincipalHistory(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const { recover } = createPrincipalCurrentRecoveryBatch();\n const options = {\n apiClient: provisionedPolicyPages(input.policies),\n execSql: input.execSql,\n offline: false,\n organizationId: input.organizationId,\n protection: input.protection,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n };\n // Scoped recovery of each group also completes the directory and strict\n // Admins stages; Members reuses them through the shared batch.\n for (const group of [input.policies.adminGroup, input.policies.memberGroup])\n await recover({\n ...options,\n reference: principalPolicyReferenceFromBundle(group),\n });\n}\n\n/** The runtime seams priming reads; none of them writes durable state. */\ninterface ProvisionedPrincipalHistoryRuntime {\n readonly bindLease: () => PrincipalHistoryProtectionLease | undefined;\n /** The runtime executor, only while `database` is its ready database. */\n readonly execSqlFor: (database: ExecSqlClientLike) => ExecSql | null;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n /** Read-only: the identity the trust store already pins for a user. */\n readonly loadPinnedIdentity: (\n execSql: ExecSql,\n userId: string,\n ) => Promise<TrustedUserIdentity | null>;\n readonly signingFingerprint: () => string | null;\n}\n\n/**\n * Binds priming to the exact provisioning scope, captured before any await:\n * the bootstrap's database and runtime executor, the identity whose key signed\n * the founding states, and a protection lease for that identity. Every later\n * step, and every progress write inside its transaction, rechecks that scope,\n * so a switched identity or database aborts priming without a durable write.\n * Priming never writes a trust pin; it only reads the founder's existing one.\n */\nexport function createProvisionedPrincipalHistoryPrimer(\n runtime: ProvisionedPrincipalHistoryRuntime,\n): ProvisionedPrincipalHistoryPrimer {\n return async (input) => {\n try {\n await primeInProvisioningScope(runtime, input);\n } catch (error) {\n runtime.logError(\n \"Provisioned principal history was not primed; recovery reads it online\",\n error,\n );\n }\n };\n}\n\nasync function primeInProvisioningScope(\n runtime: ProvisionedPrincipalHistoryRuntime,\n input: Parameters<ProvisionedPrincipalHistoryPrimer>[0],\n): Promise<void> {\n // Everything below is captured synchronously, before the first await.\n const founderFingerprint =\n input.policies.organization.currentState.signerUserKeyFingerprint;\n const execSql = runtime.execSqlFor(input.database);\n const scopeCurrent = () =>\n execSql !== null &&\n input.isCurrent() &&\n runtime.execSqlFor(input.database) === execSql &&\n runtime.signingFingerprint() === founderFingerprint;\n const lease = scopeCurrent() ? runtime.bindLease() : undefined;\n if (!execSql || !lease) return;\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = async (\n signerUserId,\n ) => {\n if (signerUserId !== input.userId) return null;\n assertProjectionVerificationCurrent(scopeCurrent);\n const identity = await runtime.loadPinnedIdentity(execSql, input.userId);\n assertProjectionVerificationCurrent(scopeCurrent);\n return identity?.signingKeyFingerprint === founderFingerprint\n ? identity\n : null;\n };\n await queuePrincipalRecovery(execSql, input.organizationId, () =>\n lease(({ protection, stillCurrent }) =>\n primeProvisionedPrincipalHistory({\n execSql,\n organizationId: input.organizationId,\n policies: input.policies,\n protection,\n resolveTrustedUserIdentity,\n // Progress writes check this inside their transactions.\n stillCurrent: () => stillCurrent() && scopeCurrent(),\n }),\n ),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provisionedPrincipalHistory.js","sourceRoot":"","sources":["provisionedPrincipalHistory.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAMvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,6CAA6C,CAAC;AAElG,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAyB9E;;;;GAIG;AACH,SAAS,sBAAsB,CAC7B,QAAsC;IAEtC,MAAM,OAAO,GAAG;QACd,QAAQ,CAAC,YAAY;QACrB,QAAQ,CAAC,UAAU;QACnB,QAAQ,CAAC,WAAW;KACrB,CAAC;IACF,OAAO;QACL,KAAK,CAAC,CAAC,uBAAuB,CAAC,aAAa,EAAE,WAAW,EAAE,OAAO,GAAG,EAAE;YAC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AAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;QACzE,mCAAmC,CAAC,YAAY,CAAC,CAAC;QAClD,OAAO,QAAQ,EAAE,qBAAqB,KAAK,kBAAkB;YAC3D,CAAC,CAAC,QAAQ;YACV,CAAC,CAAC,IAAI,CAAC;IACX,CAAC,CAAC;IACF,MAAM,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,cAAc,EAAE,GAAG,EAAE,CAC/D,KAAK,CAAC,CAAC,EAAE,UAAU,EAAE,YAAY,EAAE,EAAE,EAAE,CACrC,gCAAgC,CAAC;QAC/B,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,UAAU;QACV,0BAA0B;QAC1B,wDAAwD;QACxD,YAAY,EAAE,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,YAAY,EAAE;KACrD,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql, ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type {\n TrustedUserIdentity,\n TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport { createPrincipalCurrentRecoveryBatch } from \"../principals/principalCurrentRecoveryBatch\";\nimport type { PrincipalPolicyPageReader } from \"../principals/principalPolicyHistoryReader\";\nimport { queuePrincipalRecovery } from \"../principals/principalRecoveryQueue\";\n\n/** The version-1 policies a provisioning request signed and its response acknowledged. */\ninterface ProvisionedPrincipalPolicies {\n readonly adminGroup: PrincipalPolicyBundleResponse;\n readonly memberGroup: PrincipalPolicyBundleResponse;\n readonly organization: PrincipalPolicyBundleResponse;\n}\n\n/**\n * Records verified recovery progress for an organization's founding policy\n * heads, so the device's first scoped recovery of them needs no history read.\n * It is bound to the provisioning scope: the database the bootstrap committed\n * to and the identity that signed it. Failure leaves the online path.\n */\nexport type ProvisionedPrincipalHistoryPrimer = (input: {\n /** The database client the provisioning bootstrap committed to. */\n readonly database: ExecSqlClientLike;\n /** Whether the identity that provisioned is still the active one. */\n readonly isCurrent: () => boolean;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly userId: string;\n}) => Promise<void>;\n\n/**\n * Serves only the acknowledged initial heads, each complete in one page. The\n * ordinary verifier still checks every signature, the directory binding and\n * strict Admins rules before any progress is saved.\n */\nfunction provisionedPolicyPages(\n policies: ProvisionedPrincipalPolicies,\n): PrincipalPolicyPageReader {\n const bundles = [\n policies.organization,\n policies.adminGroup,\n policies.memberGroup,\n ];\n return {\n async *getPrincipalPolicyPages(principalType, principalId, options = {}) {\n const bundle = bundles.find(\n ({ currentState }) =>\n currentState.principalType === principalType &&\n currentState.principalId === principalId,\n );\n if (\n !bundle ||\n options.resume !== undefined ||\n (options.afterVersion ?? 0) !== 0 ||\n (options.stateHash !== undefined &&\n options.stateHash !== bundle.currentState.stateHash)\n )\n throw new Error(\n \"Provisioned principal history holds only the acknowledged initial heads\",\n );\n yield {\n ok: true,\n data: {\n ...structuredClone(bundle),\n historyPage: { afterVersion: 0, nextAfterVersion: null },\n },\n };\n },\n };\n}\n\nasync function primeProvisionedPrincipalHistory(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly policies: ProvisionedPrincipalPolicies;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const { recover } = createPrincipalCurrentRecoveryBatch();\n const options = {\n historyReader: provisionedPolicyPages(input.policies),\n execSql: input.execSql,\n offline: false,\n organizationId: input.organizationId,\n protection: input.protection,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n };\n // Scoped recovery of each group also completes the directory and strict\n // Admins stages; Members reuses them through the shared batch.\n for (const group of [input.policies.adminGroup, input.policies.memberGroup])\n await recover({\n ...options,\n reference: principalPolicyReferenceFromBundle(group),\n });\n}\n\n/** The runtime seams priming reads; none of them writes durable state. */\ninterface ProvisionedPrincipalHistoryRuntime {\n readonly bindLease: () => PrincipalHistoryProtectionLease | undefined;\n /** The runtime executor, only while `database` is its ready database. */\n readonly execSqlFor: (database: ExecSqlClientLike) => ExecSql | null;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n /** Read-only: the identity the trust store already pins for a user. */\n readonly loadPinnedIdentity: (\n execSql: ExecSql,\n userId: string,\n ) => Promise<TrustedUserIdentity | null>;\n readonly signingFingerprint: () => string | null;\n}\n\n/**\n * Binds priming to the exact provisioning scope, captured before any await:\n * the bootstrap's database and runtime executor, the identity whose key signed\n * the founding states, and a protection lease for that identity. Every later\n * step, and every progress write inside its transaction, rechecks that scope,\n * so a switched identity or database aborts priming without a durable write.\n * Priming never writes a trust pin; it only reads the founder's existing one.\n */\nexport function createProvisionedPrincipalHistoryPrimer(\n runtime: ProvisionedPrincipalHistoryRuntime,\n): ProvisionedPrincipalHistoryPrimer {\n return async (input) => {\n try {\n await primeInProvisioningScope(runtime, input);\n } catch (error) {\n runtime.logError(\n \"Provisioned principal history was not primed; recovery reads it online\",\n error,\n );\n }\n };\n}\n\nasync function primeInProvisioningScope(\n runtime: ProvisionedPrincipalHistoryRuntime,\n input: Parameters<ProvisionedPrincipalHistoryPrimer>[0],\n): Promise<void> {\n // Everything below is captured synchronously, before the first await.\n const founderFingerprint =\n input.policies.organization.currentState.signerUserKeyFingerprint;\n const execSql = runtime.execSqlFor(input.database);\n const scopeCurrent = () =>\n execSql !== null &&\n input.isCurrent() &&\n runtime.execSqlFor(input.database) === execSql &&\n runtime.signingFingerprint() === founderFingerprint;\n const lease = scopeCurrent() ? runtime.bindLease() : undefined;\n if (!execSql || !lease) return;\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = async (\n signerUserId,\n ) => {\n if (signerUserId !== input.userId) return null;\n assertProjectionVerificationCurrent(scopeCurrent);\n const identity = await runtime.loadPinnedIdentity(execSql, input.userId);\n assertProjectionVerificationCurrent(scopeCurrent);\n return identity?.signingKeyFingerprint === founderFingerprint\n ? identity\n : null;\n };\n await queuePrincipalRecovery(execSql, input.organizationId, () =>\n lease(({ protection, stillCurrent }) =>\n primeProvisionedPrincipalHistory({\n execSql,\n organizationId: input.organizationId,\n policies: input.policies,\n protection,\n resolveTrustedUserIdentity,\n // Progress writes check this inside their transactions.\n stillCurrent: () => stillCurrent() && scopeCurrent(),\n }),\n ),\n );\n}\n"]}
|