@tearleads/client-sdk 0.1.11 → 0.1.13
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/README.md +18 -2
- package/client/Tearleads.d.ts +4 -0
- package/client/Tearleads.js +5 -0
- package/client/Tearleads.js.map +1 -1
- package/client/index.d.ts +1 -0
- package/client/index.js.map +1 -1
- package/client/principalHistoryProtection.d.ts +19 -0
- package/client/principalHistoryProtection.js +76 -0
- package/client/principalHistoryProtection.js.map +1 -0
- package/client/workflowRuntime.d.ts +5 -0
- package/client/workflowRuntime.js +34 -5
- package/client/workflowRuntime.js.map +1 -1
- package/data/containers/shared/authorAccess.d.ts +2 -2
- package/data/containers/shared/authorAccess.js.map +1 -1
- package/data/containers/shared/heldContainerHeads.js.map +1 -1
- package/data/containers/shared/principalPolicies.js.map +1 -1
- package/data/containers/shared/types.d.ts +3 -2
- package/data/containers/shared/types.js.map +1 -1
- package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
- package/data/keyingProjectionVerification/checkpointContext.d.ts +4 -3
- package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
- package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/containerPathVerification.js.map +1 -1
- package/data/keyingProjectionVerification/containerProjectionVerification.d.ts +4 -3
- package/data/keyingProjectionVerification/containerProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentManifestPolicies.js.map +1 -1
- package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
- package/data/keyingProjectionVerification/documentProjectionVerification.d.ts +3 -2
- package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
- package/data/keyingProjectionVerification/organizationFounderBinding.js +9 -4
- package/data/keyingProjectionVerification/organizationFounderBinding.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicyCache.js +3 -4
- package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicyVerification.js +12 -2
- package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
- package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +1 -1
- package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js +70 -0
- package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js.map +1 -0
- package/data/keyingProjectionVerification/types.d.ts +17 -2
- package/data/keyingProjectionVerification/types.js +12 -0
- package/data/keyingProjectionVerification/types.js.map +1 -1
- package/data/persistence/organizationFounderPersistence.js +3 -2
- package/data/persistence/organizationFounderPersistence.js.map +1 -1
- package/data/persistence/principalHistoryEvidencePersistence.js +91 -0
- package/data/persistence/principalHistoryEvidencePersistence.js.map +1 -0
- package/data/persistence/principalHistoryPrefixPersistence.js +52 -0
- package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -0
- package/data/persistence/principalHistoryStagePersistence.js +9 -2
- package/data/persistence/principalHistoryStagePersistence.js.map +1 -1
- package/data/persistence/principalKeyEnvelopeCandidates.js +67 -0
- package/data/persistence/principalKeyEnvelopeCandidates.js.map +1 -0
- package/data/principals/principalHistoryPrefixProtection.js +29 -0
- package/data/principals/principalHistoryPrefixProtection.js.map +1 -0
- package/data/principals/principalHistoryProtection.d.ts +10 -0
- package/data/principals/principalHistoryProtection.js +14 -0
- package/data/principals/principalHistoryProtection.js.map +1 -0
- package/data/principals/principalHistoryStageProtection.js.map +1 -1
- package/data/principals/principalPolicyCrypto.js +11 -21
- package/data/principals/principalPolicyCrypto.js.map +1 -1
- package/data/principals/principalPolicyEvidence.d.ts +4 -0
- package/data/principals/principalPolicyEvidence.js +12 -0
- package/data/principals/principalPolicyEvidence.js.map +1 -0
- package/data/sqlite/principalHistoryEvidenceSchema.js +46 -0
- package/data/sqlite/principalHistoryEvidenceSchema.js.map +1 -0
- package/data/sqlite/principalKeyFingerprintJson.js +9 -0
- package/data/sqlite/principalKeyFingerprintJson.js.map +1 -0
- package/data/sqlite/principalPolicySchema.js +4 -0
- package/data/sqlite/principalPolicySchema.js.map +1 -1
- package/data/sqlite/schema.d.ts +304 -0
- package/data/sqlite/schema.js +5 -0
- package/data/sqlite/schema.js.map +1 -1
- package/data/sqlite/sqlTableSchema.js +1 -1
- package/data/sqlite/sqlTableSchema.js.map +1 -1
- package/index.d.ts +3 -3
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/internal/api-client/principalPolicyPages.d.ts +2 -0
- package/internal/api-client/principalPolicyPages.js +11 -2
- package/internal/api-client/principalPolicyPages.js.map +1 -1
- package/internal/crypto/index.d.ts +1 -1
- package/internal/crypto/index.js +1 -1
- package/internal/crypto/index.js.map +1 -1
- package/internal/crypto/keying/index.d.ts +1 -1
- package/internal/crypto/keying/index.js +1 -1
- package/internal/crypto/keying/index.js.map +1 -1
- package/internal/crypto/keying/principalPolicyHistoryIndex.d.ts +6 -2
- package/internal/crypto/keying/principalPolicyHistoryIndex.js +11 -5
- package/internal/crypto/keying/principalPolicyHistoryIndex.js.map +1 -1
- package/internal/crypto/keying/principalPolicyHistoryReferences.d.ts +2 -0
- package/internal/crypto/keying/principalPolicyHistoryReferences.js +19 -2
- package/internal/crypto/keying/principalPolicyHistoryReferences.js.map +1 -1
- package/package.json +1 -1
- package/workflows/containers/child/create.js.map +1 -1
- package/workflows/containers/child/move.js.map +1 -1
- package/workflows/containers/child/moveWraps.js.map +1 -1
- package/workflows/containers/child/mutationRequestCore.js.map +1 -1
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/child/rekey.d.ts +3 -2
- package/workflows/containers/child/rekey.js.map +1 -1
- package/workflows/containers/child/revoke.d.ts +2 -2
- package/workflows/containers/child/revoke.js.map +1 -1
- package/workflows/containers/child/rotationPrincipalPolicies.js.map +1 -1
- package/workflows/containers/child/rotationWraps.js.map +1 -1
- package/workflows/containers/child/sharePlanCore.d.ts +11 -10
- package/workflows/containers/child/sharePlanCore.js.map +1 -1
- package/workflows/documents/linkSetAuthority.js.map +1 -1
- package/workflows/principals/index.d.ts +1 -0
- package/workflows/principals/index.js +1 -0
- package/workflows/principals/index.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryPrefix.js +65 -0
- package/workflows/principals/principalHistoryRecoveryPrefix.js.map +1 -0
- package/workflows/principals/principalHistoryRecoveryReferences.js +60 -0
- package/workflows/principals/principalHistoryRecoveryReferences.js.map +1 -0
- package/workflows/principals/principalHistoryRecoveryStage.js +38 -2
- package/workflows/principals/principalHistoryRecoveryStage.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryTypes.d.ts +9 -1
- package/workflows/principals/principalHistoryRecoveryTypes.js +7 -0
- package/workflows/principals/principalHistoryRecoveryTypes.js.map +1 -1
- package/workflows/principals/principalHistoryRecoveryVerification.js +24 -0
- package/workflows/principals/principalHistoryRecoveryVerification.js.map +1 -0
- package/workflows/principals/principalRecoveryDirectory.d.ts +10 -0
- package/workflows/principals/principalRecoveryDirectory.js +107 -0
- package/workflows/principals/principalRecoveryDirectory.js.map +1 -0
- package/workflows/principals/principalRecoveryMemo.js +46 -0
- package/workflows/principals/principalRecoveryMemo.js.map +1 -0
- package/workflows/principals/principalRecoveryOutage.js +40 -0
- package/workflows/principals/principalRecoveryOutage.js.map +1 -0
- package/workflows/principals/principalRecoveryQueue.js +22 -0
- package/workflows/principals/principalRecoveryQueue.js.map +1 -0
- package/workflows/principals/recoverPrincipalPolicyHistory.d.ts +1 -0
- package/workflows/principals/recoverPrincipalPolicyHistory.js +108 -36
- package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +13 -0
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +150 -0
- package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -0
- package/workflows/principals/runtimePolicyRecovery.js +65 -0
- package/workflows/principals/runtimePolicyRecovery.js.map +1 -0
- package/workflows/principals/runtimePolicyWarmer.js +5 -1
- package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
- package/workflows/sync/remoteResetPrincipalScope.js +10 -0
- package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
|
@@ -1,19 +1,20 @@
|
|
|
1
|
-
import { type AccessEvent, type AccessManifest, type ContainerAccessManifestState, type ContainerDirectGrant, type ContainerGrantAccessEventBody, type ContainerGrantPrincipalHead, type ContainerKekRecipientTarget, type ContainerKeyWrap, type ContainerUserRecipientKey
|
|
1
|
+
import { type AccessEvent, type AccessManifest, type ContainerAccessManifestState, type ContainerDirectGrant, type ContainerGrantAccessEventBody, type ContainerGrantPrincipalHead, type ContainerKekRecipientTarget, type ContainerKeyWrap, type ContainerUserRecipientKey } from "../../../internal/crypto/index.js";
|
|
2
2
|
import type { AccessManifestBundleWire } from "../../../internal/validators/request/index.js";
|
|
3
3
|
import type { ContainerKekResponse, ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
|
|
4
4
|
import type { ContainerSharePlan, MaterializedContainerSharePlan } from "../../../data/containers/shared/types.js";
|
|
5
5
|
import { type PrincipalPolicyCache, type ProjectionUserKeyResolver, type ReferencedPrincipalPolicyWarmer } from "../../../data/keyingProjectionVerification.js";
|
|
6
|
+
import type { PrincipalPolicyCurrentEvidence } from "../../../data/principals/principalPolicyEvidence.js";
|
|
6
7
|
import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
7
8
|
export type ContainerShareRecipient = {
|
|
8
9
|
readonly recipientEncapsulationPublicKey: Uint8Array;
|
|
9
10
|
readonly subjectId: string;
|
|
10
11
|
readonly subjectType: "user";
|
|
11
12
|
} | {
|
|
12
|
-
readonly principalPolicy:
|
|
13
|
+
readonly principalPolicy: PrincipalPolicyCurrentEvidence;
|
|
13
14
|
readonly subjectId: string;
|
|
14
15
|
readonly subjectType: "group";
|
|
15
16
|
};
|
|
16
|
-
export declare function referencedPrincipalHeadFromPolicy(policy:
|
|
17
|
+
export declare function referencedPrincipalHeadFromPolicy(policy: PrincipalPolicyCurrentEvidence): ContainerGrantPrincipalHead;
|
|
17
18
|
/**
|
|
18
19
|
* The previous manifest's referenced principal heads with the replacement
|
|
19
20
|
* policy's head upserted in place of any stale head for the same principal.
|
|
@@ -23,16 +24,16 @@ export declare function referencedPrincipalHeadFromPolicy(policy: VerifiedPrinci
|
|
|
23
24
|
*/
|
|
24
25
|
export declare function refreshedPrincipalReferences(input: {
|
|
25
26
|
readonly previousState: ContainerAccessManifestState;
|
|
26
|
-
readonly replacementPrincipalPolicy?:
|
|
27
|
+
readonly replacementPrincipalPolicy?: PrincipalPolicyCurrentEvidence | undefined;
|
|
27
28
|
}): ContainerGrantPrincipalHead[];
|
|
28
29
|
/**
|
|
29
30
|
* The previous policies with the replacement policy substituted for any
|
|
30
31
|
* existing policy of the same principal identity.
|
|
31
32
|
*/
|
|
32
33
|
export declare function refreshedPrincipalPolicies(input: {
|
|
33
|
-
readonly previousPolicies: readonly
|
|
34
|
-
readonly replacementPrincipalPolicy?:
|
|
35
|
-
}):
|
|
34
|
+
readonly previousPolicies: readonly PrincipalPolicyCurrentEvidence[];
|
|
35
|
+
readonly replacementPrincipalPolicy?: PrincipalPolicyCurrentEvidence | undefined;
|
|
36
|
+
}): PrincipalPolicyCurrentEvidence[];
|
|
36
37
|
export declare function deriveContainerShareManifest(input: {
|
|
37
38
|
eventHash: string;
|
|
38
39
|
grant: ContainerDirectGrant;
|
|
@@ -57,7 +58,7 @@ export declare function buildContainerSharePlanResult(input: {
|
|
|
57
58
|
manifestHash: string;
|
|
58
59
|
previousManifest: AccessManifestBundleWire;
|
|
59
60
|
previousProjection: ContainerWriterProjectionResponse;
|
|
60
|
-
principalPolicies: readonly
|
|
61
|
+
principalPolicies: readonly PrincipalPolicyCurrentEvidence[];
|
|
61
62
|
recipientTarget: ContainerKekRecipientTarget;
|
|
62
63
|
state: ContainerAccessManifestState;
|
|
63
64
|
targetKek: ContainerKekResponse;
|
|
@@ -74,8 +75,8 @@ export declare function collectContainerSharePrincipalPolicies(input: {
|
|
|
74
75
|
persistVerificationCheckpoints?: boolean | undefined;
|
|
75
76
|
principalPolicyCache?: PrincipalPolicyCache | undefined;
|
|
76
77
|
previousProjection: ContainerWriterProjectionResponse;
|
|
77
|
-
recipientPolicy?:
|
|
78
|
+
recipientPolicy?: PrincipalPolicyCurrentEvidence | undefined;
|
|
78
79
|
resolveUserKey: ProjectionUserKeyResolver;
|
|
79
80
|
stillCurrent?: (() => boolean) | undefined;
|
|
80
81
|
warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
|
|
81
|
-
}): Promise<
|
|
82
|
+
}): Promise<PrincipalPolicyCurrentEvidence[]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sharePlanCore.js","sourceRoot":"","sources":["sharePlanCore.ts"],"names":[],"mappings":"AAAA,OAAO,EAWL,yBAAyB,EACzB,6BAA6B,GAE9B,MAAM,mBAAmB,CAAC;AAS3B,OAAO,EAAE,uBAAuB,EAAE,MAAM,mDAAmD,CAAC;AAC5F,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,gCAAgC,EAChC,qBAAqB,GACtB,MAAM,yCAAyC,CAAC;AAKjD,OAAO,EACL,iDAAiD,GAIlD,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,uBAAuB,CAAC;AAc/B,SAAS,QAAQ,CACf,KAA8D;IAE9D,OAAO,GAAG,KAAK,CAAC,WAAW,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;AACnD,CAAC;AAED,SAAS,oBAAoB,CAC3B,MAAuC,EACvC,KAA2B;IAE3B,OAAO;QACL,GAAG,MAAM,CAAC,MAAM,CACd,CAAC,aAAa,EAAE,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC,KAAK,QAAQ,CAAC,KAAK,CAAC,CAC/D;QACD,KAAK;KACN,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,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,mBAAmB,CAAC,MAAM,EAChC,KAAK,CAAC,mBAAmB,CAC1B,CAAC;IACJ,CAAC;IAED,MAAM,aAAa,GAAG,CAAC,GAAG,aAAa,CAAC,CAAC,IAAI,CAC3C,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,wBAAwB,CAAC,GAAG,CAAC,MAAM,CAAC,CAClD,CAAC;IACF,IAAI,aAAa,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CACb,kEAAkE,aAAa,EAAE,CAClF,CAAC;IACJ,CAAC;IAED,OAAO,CAAC,GAAG,wBAAwB,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACjE,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC,CACxC,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAAC,KAS5D;IACC,MAAM,gBAAgB,GACpB,MAAM,iDAAiD,CAAC;QACtD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,8BAA8B,EAAE,KAAK,CAAC,8BAA8B;QACpE,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,UAAU,EAAE,KAAK,CAAC,kBAAkB;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACL,OAAO,0BAA0B,CAAC;QAChC,gBAAgB;QAChB,0BAA0B,EAAE,KAAK,CAAC,eAAe;KAClD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n type AccessEvent,\n type AccessManifest,\n type ContainerAccessManifestState,\n type ContainerDirectGrant,\n type ContainerGrantAccessEventBody,\n type ContainerGrantPrincipalHead,\n type ContainerKekRecipientTarget,\n type ContainerKeyEpoch,\n type ContainerKeyWrap,\n type ContainerUserRecipientKey,\n computeAccessManifestHash,\n deriveContainerAccessManifest,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerMutationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerKekResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { uniquePrincipalPolicies } from \"../../../data/containers/shared/principalPolicies\";\nimport {\n asContainerManifestBundle,\n getParentKekForTarget,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport {\n readContainerKekRecipientTargets,\n readContainerKeyEpoch,\n} from \"../../../data/containers/shared/readers\";\nimport type {\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n containerMutationRequestCore,\n previousPathRequestFields,\n readCanonicalRecordOrNull,\n} from \"./mutationRequestCore\";\n\nexport type ContainerShareRecipient =\n | {\n readonly recipientEncapsulationPublicKey: Uint8Array;\n readonly subjectId: string;\n readonly subjectType: \"user\";\n }\n | {\n readonly principalPolicy: VerifiedPrincipalPolicy;\n readonly subjectId: string;\n readonly subjectType: \"group\";\n };\n\nfunction grantKey(\n grant: Pick<ContainerDirectGrant, \"subjectId\" | \"subjectType\">,\n): string {\n return `${grant.subjectType}:${grant.subjectId}`;\n}\n\nfunction upsertContainerGrant(\n grants: readonly ContainerDirectGrant[],\n grant: ContainerDirectGrant,\n): ContainerDirectGrant[] {\n return [\n ...grants.filter(\n (existingGrant) => grantKey(existingGrant) !== grantKey(grant),\n ),\n grant,\n ].sort((left, right) => grantKey(left).localeCompare(grantKey(right)));\n}\n\nfunction referencedPrincipalKey(reference: {\n readonly principalId: string;\n readonly principalType: \"group\";\n}): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nexport function referencedPrincipalHeadFromPolicy(\n policy: VerifiedPrincipalPolicy,\n): ContainerGrantPrincipalHead {\n if (policy.principalType !== \"group\") {\n throw new Error(\"Container grants can reference only group policies\");\n }\n return {\n principalType: \"group\",\n principalId: policy.principalId,\n version: policy.version,\n keyEpoch: policy.keyEpoch,\n stateHash: policy.stateHash,\n keyFingerprint: policy.state.keyFingerprint,\n };\n}\n\nfunction upsertReferencedPrincipalHead(\n references: readonly ContainerGrantPrincipalHead[],\n reference: ContainerGrantPrincipalHead,\n): ContainerGrantPrincipalHead[] {\n return [\n ...references.filter(\n (existingReference) =>\n referencedPrincipalKey(existingReference) !==\n referencedPrincipalKey(reference),\n ),\n reference,\n ].sort((left, right) =>\n referencedPrincipalKey(left).localeCompare(referencedPrincipalKey(right)),\n );\n}\n\n/**\n * The previous manifest's referenced principal heads with the replacement\n * policy's head upserted in place of any stale head for the same principal.\n * A rekey substitutes references and never adds one: a manifest may reference\n * only principals it grants, so a replacement for one it does not grant —\n * a carried rekey below the container the policy is granted on — is left out.\n */\nexport function refreshedPrincipalReferences(input: {\n readonly previousState: ContainerAccessManifestState;\n readonly replacementPrincipalPolicy?: VerifiedPrincipalPolicy | undefined;\n}): ContainerGrantPrincipalHead[] {\n const replacement = input.replacementPrincipalPolicy;\n if (\n !replacement ||\n !input.previousState.directGrants.some(\n (grant) =>\n grant.subjectType === replacement.principalType &&\n grant.subjectId === replacement.principalId,\n )\n ) {\n return [...input.previousState.referencedPrincipalHeads];\n }\n return upsertReferencedPrincipalHead(\n input.previousState.referencedPrincipalHeads,\n referencedPrincipalHeadFromPolicy(replacement),\n );\n}\n\n/**\n * The previous policies with the replacement policy substituted for any\n * existing policy of the same principal identity.\n */\nexport function refreshedPrincipalPolicies(input: {\n readonly previousPolicies: readonly VerifiedPrincipalPolicy[];\n readonly replacementPrincipalPolicy?: VerifiedPrincipalPolicy | undefined;\n}): VerifiedPrincipalPolicy[] {\n const replacement = input.replacementPrincipalPolicy;\n if (!replacement) {\n return uniquePrincipalPolicies(input.previousPolicies);\n }\n return uniquePrincipalPolicies([\n ...input.previousPolicies.filter(\n (policy) =>\n policy.principalType !== replacement.principalType ||\n policy.principalId !== replacement.principalId,\n ),\n replacement,\n ]);\n}\n\nexport async function deriveContainerShareManifest(input: {\n eventHash: string;\n grant: ContainerDirectGrant;\n previousManifest: ContainerWriterProjectionResponse[\"path\"][number];\n referencedPrincipalHead: ContainerGrantPrincipalHead | null;\n}): Promise<Pick<ContainerSharePlan, \"manifest\" | \"manifestHash\" | \"state\">> {\n const previousState = readContainerState(input.previousManifest);\n const state: ContainerAccessManifestState = {\n ...previousState,\n epoch: previousState.epoch + 1,\n previousManifestHash: input.previousManifest.manifestHash,\n eventHash: input.eventHash,\n directGrants: upsertContainerGrant(previousState.directGrants, input.grant),\n referencedPrincipalHeads: input.referencedPrincipalHead\n ? upsertReferencedPrincipalHead(\n previousState.referencedPrincipalHeads,\n input.referencedPrincipalHead,\n )\n : previousState.referencedPrincipalHeads,\n };\n const manifest = await deriveContainerAccessManifest(state);\n\n return {\n manifest,\n manifestHash: await computeAccessManifestHash(manifest),\n state,\n };\n}\n\nfunction buildContainerShareRequest(input: {\n body: ContainerGrantAccessEventBody;\n containerManifestHistory: readonly AccessManifestBundleWire[];\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n parentKek: ContainerKekResponse | null;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly VerifiedPrincipalPolicy[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n ...containerMutationRequestCore(\"share\", input),\n ...previousPathRequestFields(\n input.previousManifest,\n input.previousProjection,\n ),\n containerManifestHistory: [...input.containerManifestHistory],\n predecessorBridge: null,\n keyring: null,\n parentKekState: readCanonicalRecordOrNull(\n input.parentKek,\n \"Container share parent KEK state\",\n ),\n };\n}\n\nexport function replaceContainerWrap(\n wraps: readonly ContainerKeyWrap[],\n nextWrap: ContainerKeyWrap,\n): ContainerKeyWrap[] {\n return [\n ...wraps.filter(\n (wrap) =>\n !(\n wrap.recipientKind === nextWrap.recipientKind &&\n wrap.recipientId === nextWrap.recipientId\n ),\n ),\n nextWrap,\n ];\n}\n\nexport function shareManifestHistory(input: {\n readonly containerId: string;\n readonly targetKek: ContainerKekResponse;\n readonly targetManifest: ContainerWriterProjectionResponse[\"path\"][number];\n}): AccessManifestBundleWire[] {\n const byHash = new Map<string, AccessManifestBundleWire>();\n for (const bundle of [\n input.targetManifest,\n ...input.targetKek.containerManifestHistory,\n ]) {\n if (\n readContainerState(bundle).containerId === input.containerId &&\n !byHash.has(bundle.manifestHash)\n ) {\n byHash.set(bundle.manifestHash, asContainerManifestBundle(bundle));\n }\n }\n return [...byHash.values()];\n}\n\nexport function buildContainerSharePlanResult(input: {\n body: ContainerGrantAccessEventBody;\n containerManifestHistory: readonly AccessManifestBundleWire[];\n containerId: string;\n containerKey: Uint8Array;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly VerifiedPrincipalPolicy[];\n recipientTarget: ContainerKekRecipientTarget;\n state: ContainerAccessManifestState;\n targetKek: ContainerKekResponse;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}): MaterializedContainerSharePlan {\n const keyEpoch = readContainerKeyEpoch(\n input.targetKek.keyEpoch,\n \"Container share key epoch\",\n );\n const plan: ContainerSharePlan = {\n body: input.body,\n containerId: input.containerId,\n event: input.event,\n eventHash: input.eventHash,\n grant: input.grant,\n keyEpoch,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n previousKeyring: readCanonicalRecordOrNull(\n input.previousProjection.containerKeks.at(-1)?.keyring ?? null,\n \"Container share previous keyring\",\n ),\n previousManifest: input.previousManifest,\n recipientTarget: input.recipientTarget,\n request: buildContainerShareRequest({\n body: input.body,\n containerManifestHistory: input.containerManifestHistory,\n event: input.event,\n keyEpoch,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n parentKek: getParentKekForTarget(input.previousProjection),\n previousManifest: input.previousManifest,\n previousProjection: input.previousProjection,\n principalPolicies: input.principalPolicies,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n }),\n state: input.state,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n };\n\n return { containerKey: input.containerKey, plan };\n}\n\nexport function collectShareUserRecipientKeys(input: {\n newUserRecipientKey?: ContainerUserRecipientKey | undefined;\n state: ContainerAccessManifestState;\n targetKek: ContainerKekResponse;\n}): ContainerUserRecipientKey[] {\n const directUserIds = new Set(\n input.state.directGrants.flatMap((grant) =>\n grant.subjectType === \"user\" ? [grant.subjectId] : [],\n ),\n );\n const userRecipientKeyByUserId = new Map<string, ContainerUserRecipientKey>();\n\n for (const target of readContainerKekRecipientTargets(\n input.targetKek.recipientTargets,\n \"Container share target KEK recipient targets\",\n )) {\n if (\n target.recipientKind !== \"user\" ||\n !directUserIds.has(target.recipientId)\n ) {\n continue;\n }\n userRecipientKeyByUserId.set(target.recipientId, {\n userId: target.recipientId,\n recipientKeyEpochId: target.recipientKeyEpochId,\n recipientKeyFingerprint: target.recipientKeyFingerprint,\n });\n }\n\n if (input.newUserRecipientKey) {\n userRecipientKeyByUserId.set(\n input.newUserRecipientKey.userId,\n input.newUserRecipientKey,\n );\n }\n\n const missingUserId = [...directUserIds].find(\n (userId) => !userRecipientKeyByUserId.has(userId),\n );\n if (missingUserId) {\n throw new Error(\n `Container share recipient key is missing for direct user grant ${missingUserId}`,\n );\n }\n\n return [...userRecipientKeyByUserId.values()].sort((left, right) =>\n left.userId.localeCompare(right.userId),\n );\n}\n\nexport async function collectContainerSharePrincipalPolicies(input: {\n execSql: ExecSql;\n persistVerificationCheckpoints?: boolean | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n recipientPolicy?: VerifiedPrincipalPolicy | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const previousPolicies =\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: input.previousProjection,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n return refreshedPrincipalPolicies({\n previousPolicies,\n replacementPrincipalPolicy: input.recipientPolicy,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sharePlanCore.js","sourceRoot":"","sources":["sharePlanCore.ts"],"names":[],"mappings":"AAAA,OAAO,EAWL,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,mBAAmB,CAAC;AAS3B,OAAO,EAAE,uBAAuB,EAAE,MAAM,mDAAmD,CAAC;AAC5F,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,gCAAgC,EAChC,qBAAqB,GACtB,MAAM,yCAAyC,CAAC;AAKjD,OAAO,EACL,iDAAiD,GAIlD,MAAM,4CAA4C,CAAC;AAGpD,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,EACzB,yBAAyB,GAC1B,MAAM,uBAAuB,CAAC;AAc/B,SAAS,QAAQ,CACf,KAA8D;IAE9D,OAAO,GAAG,KAAK,CAAC,WAAW,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;AACnD,CAAC;AAED,SAAS,oBAAoB,CAC3B,MAAuC,EACvC,KAA2B;IAE3B,OAAO;QACL,GAAG,MAAM,CAAC,MAAM,CACd,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n type ContainerDirectGrant,\n type ContainerGrantAccessEventBody,\n type ContainerGrantPrincipalHead,\n type ContainerKekRecipientTarget,\n type ContainerKeyEpoch,\n type ContainerKeyWrap,\n type ContainerUserRecipientKey,\n computeAccessManifestHash,\n deriveContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerMutationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerKekResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { uniquePrincipalPolicies } from \"../../../data/containers/shared/principalPolicies\";\nimport {\n asContainerManifestBundle,\n getParentKekForTarget,\n readContainerState,\n} from \"../../../data/containers/shared/projection\";\nimport {\n readContainerKekRecipientTargets,\n readContainerKeyEpoch,\n} from \"../../../data/containers/shared/readers\";\nimport type {\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../../data/principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n containerMutationRequestCore,\n previousPathRequestFields,\n readCanonicalRecordOrNull,\n} from \"./mutationRequestCore\";\n\nexport type ContainerShareRecipient =\n | {\n readonly recipientEncapsulationPublicKey: Uint8Array;\n readonly subjectId: string;\n readonly subjectType: \"user\";\n }\n | {\n readonly principalPolicy: PrincipalPolicyCurrentEvidence;\n readonly subjectId: string;\n readonly subjectType: \"group\";\n };\n\nfunction grantKey(\n grant: Pick<ContainerDirectGrant, \"subjectId\" | \"subjectType\">,\n): string {\n return `${grant.subjectType}:${grant.subjectId}`;\n}\n\nfunction upsertContainerGrant(\n grants: readonly ContainerDirectGrant[],\n grant: ContainerDirectGrant,\n): ContainerDirectGrant[] {\n return [\n ...grants.filter(\n (existingGrant) => grantKey(existingGrant) !== grantKey(grant),\n ),\n grant,\n ].sort((left, right) => grantKey(left).localeCompare(grantKey(right)));\n}\n\nfunction referencedPrincipalKey(reference: {\n readonly principalId: string;\n readonly principalType: \"group\";\n}): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nexport function referencedPrincipalHeadFromPolicy(\n policy: PrincipalPolicyCurrentEvidence,\n): ContainerGrantPrincipalHead {\n if (policy.principalType !== \"group\") {\n throw new Error(\"Container grants can reference only group policies\");\n }\n return {\n principalType: \"group\",\n principalId: policy.principalId,\n version: policy.version,\n keyEpoch: policy.keyEpoch,\n stateHash: policy.stateHash,\n keyFingerprint: policy.state.keyFingerprint,\n };\n}\n\nfunction upsertReferencedPrincipalHead(\n references: readonly ContainerGrantPrincipalHead[],\n reference: ContainerGrantPrincipalHead,\n): ContainerGrantPrincipalHead[] {\n return [\n ...references.filter(\n (existingReference) =>\n referencedPrincipalKey(existingReference) !==\n referencedPrincipalKey(reference),\n ),\n reference,\n ].sort((left, right) =>\n referencedPrincipalKey(left).localeCompare(referencedPrincipalKey(right)),\n );\n}\n\n/**\n * The previous manifest's referenced principal heads with the replacement\n * policy's head upserted in place of any stale head for the same principal.\n * A rekey substitutes references and never adds one: a manifest may reference\n * only principals it grants, so a replacement for one it does not grant —\n * a carried rekey below the container the policy is granted on — is left out.\n */\nexport function refreshedPrincipalReferences(input: {\n readonly previousState: ContainerAccessManifestState;\n readonly replacementPrincipalPolicy?:\n | PrincipalPolicyCurrentEvidence\n | undefined;\n}): ContainerGrantPrincipalHead[] {\n const replacement = input.replacementPrincipalPolicy;\n if (\n !replacement ||\n !input.previousState.directGrants.some(\n (grant) =>\n grant.subjectType === replacement.principalType &&\n grant.subjectId === replacement.principalId,\n )\n ) {\n return [...input.previousState.referencedPrincipalHeads];\n }\n return upsertReferencedPrincipalHead(\n input.previousState.referencedPrincipalHeads,\n referencedPrincipalHeadFromPolicy(replacement),\n );\n}\n\n/**\n * The previous policies with the replacement policy substituted for any\n * existing policy of the same principal identity.\n */\nexport function refreshedPrincipalPolicies(input: {\n readonly previousPolicies: readonly PrincipalPolicyCurrentEvidence[];\n readonly replacementPrincipalPolicy?:\n | PrincipalPolicyCurrentEvidence\n | undefined;\n}): PrincipalPolicyCurrentEvidence[] {\n const replacement = input.replacementPrincipalPolicy;\n if (!replacement) {\n return uniquePrincipalPolicies(input.previousPolicies);\n }\n return uniquePrincipalPolicies([\n ...input.previousPolicies.filter(\n (policy) =>\n policy.principalType !== replacement.principalType ||\n policy.principalId !== replacement.principalId,\n ),\n replacement,\n ]);\n}\n\nexport async function deriveContainerShareManifest(input: {\n eventHash: string;\n grant: ContainerDirectGrant;\n previousManifest: ContainerWriterProjectionResponse[\"path\"][number];\n referencedPrincipalHead: ContainerGrantPrincipalHead | null;\n}): Promise<Pick<ContainerSharePlan, \"manifest\" | \"manifestHash\" | \"state\">> {\n const previousState = readContainerState(input.previousManifest);\n const state: ContainerAccessManifestState = {\n ...previousState,\n epoch: previousState.epoch + 1,\n previousManifestHash: input.previousManifest.manifestHash,\n eventHash: input.eventHash,\n directGrants: upsertContainerGrant(previousState.directGrants, input.grant),\n referencedPrincipalHeads: input.referencedPrincipalHead\n ? upsertReferencedPrincipalHead(\n previousState.referencedPrincipalHeads,\n input.referencedPrincipalHead,\n )\n : previousState.referencedPrincipalHeads,\n };\n const manifest = await deriveContainerAccessManifest(state);\n\n return {\n manifest,\n manifestHash: await computeAccessManifestHash(manifest),\n state,\n };\n}\n\nfunction buildContainerShareRequest(input: {\n body: ContainerGrantAccessEventBody;\n containerManifestHistory: readonly AccessManifestBundleWire[];\n event: AccessEvent;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n parentKek: ContainerKekResponse | null;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n userRecipientKeys: readonly ContainerUserRecipientKey[];\n wraps: readonly ContainerKeyWrap[];\n}): ContainerMutationRequest {\n return {\n ...containerMutationRequestCore(\"share\", input),\n ...previousPathRequestFields(\n input.previousManifest,\n input.previousProjection,\n ),\n containerManifestHistory: [...input.containerManifestHistory],\n predecessorBridge: null,\n keyring: null,\n parentKekState: readCanonicalRecordOrNull(\n input.parentKek,\n \"Container share parent KEK state\",\n ),\n };\n}\n\nexport function replaceContainerWrap(\n wraps: readonly ContainerKeyWrap[],\n nextWrap: ContainerKeyWrap,\n): ContainerKeyWrap[] {\n return [\n ...wraps.filter(\n (wrap) =>\n !(\n wrap.recipientKind === nextWrap.recipientKind &&\n wrap.recipientId === nextWrap.recipientId\n ),\n ),\n nextWrap,\n ];\n}\n\nexport function shareManifestHistory(input: {\n readonly containerId: string;\n readonly targetKek: ContainerKekResponse;\n readonly targetManifest: ContainerWriterProjectionResponse[\"path\"][number];\n}): AccessManifestBundleWire[] {\n const byHash = new Map<string, AccessManifestBundleWire>();\n for (const bundle of [\n input.targetManifest,\n ...input.targetKek.containerManifestHistory,\n ]) {\n if (\n readContainerState(bundle).containerId === input.containerId &&\n !byHash.has(bundle.manifestHash)\n ) {\n byHash.set(bundle.manifestHash, asContainerManifestBundle(bundle));\n }\n }\n return [...byHash.values()];\n}\n\nexport function buildContainerSharePlanResult(input: {\n body: ContainerGrantAccessEventBody;\n containerManifestHistory: readonly AccessManifestBundleWire[];\n containerId: string;\n containerKey: Uint8Array;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n previousProjection: ContainerWriterProjectionResponse;\n principalPolicies: readonly PrincipalPolicyCurrentEvidence[];\n recipientTarget: ContainerKekRecipientTarget;\n state: ContainerAccessManifestState;\n targetKek: ContainerKekResponse;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}): MaterializedContainerSharePlan {\n const keyEpoch = readContainerKeyEpoch(\n input.targetKek.keyEpoch,\n \"Container share key epoch\",\n );\n const plan: ContainerSharePlan = {\n body: input.body,\n containerId: input.containerId,\n event: input.event,\n eventHash: input.eventHash,\n grant: input.grant,\n keyEpoch,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n previousKeyring: readCanonicalRecordOrNull(\n input.previousProjection.containerKeks.at(-1)?.keyring ?? null,\n \"Container share previous keyring\",\n ),\n previousManifest: input.previousManifest,\n recipientTarget: input.recipientTarget,\n request: buildContainerShareRequest({\n body: input.body,\n containerManifestHistory: input.containerManifestHistory,\n event: input.event,\n keyEpoch,\n manifest: input.manifest,\n manifestHash: input.manifestHash,\n parentKek: getParentKekForTarget(input.previousProjection),\n previousManifest: input.previousManifest,\n previousProjection: input.previousProjection,\n principalPolicies: input.principalPolicies,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n }),\n state: input.state,\n userRecipientKeys: input.userRecipientKeys,\n wraps: input.wraps,\n };\n\n return { containerKey: input.containerKey, plan };\n}\n\nexport function collectShareUserRecipientKeys(input: {\n newUserRecipientKey?: ContainerUserRecipientKey | undefined;\n state: ContainerAccessManifestState;\n targetKek: ContainerKekResponse;\n}): ContainerUserRecipientKey[] {\n const directUserIds = new Set(\n input.state.directGrants.flatMap((grant) =>\n grant.subjectType === \"user\" ? [grant.subjectId] : [],\n ),\n );\n const userRecipientKeyByUserId = new Map<string, ContainerUserRecipientKey>();\n\n for (const target of readContainerKekRecipientTargets(\n input.targetKek.recipientTargets,\n \"Container share target KEK recipient targets\",\n )) {\n if (\n target.recipientKind !== \"user\" ||\n !directUserIds.has(target.recipientId)\n ) {\n continue;\n }\n userRecipientKeyByUserId.set(target.recipientId, {\n userId: target.recipientId,\n recipientKeyEpochId: target.recipientKeyEpochId,\n recipientKeyFingerprint: target.recipientKeyFingerprint,\n });\n }\n\n if (input.newUserRecipientKey) {\n userRecipientKeyByUserId.set(\n input.newUserRecipientKey.userId,\n input.newUserRecipientKey,\n );\n }\n\n const missingUserId = [...directUserIds].find(\n (userId) => !userRecipientKeyByUserId.has(userId),\n );\n if (missingUserId) {\n throw new Error(\n `Container share recipient key is missing for direct user grant ${missingUserId}`,\n );\n }\n\n return [...userRecipientKeyByUserId.values()].sort((left, right) =>\n left.userId.localeCompare(right.userId),\n );\n}\n\nexport async function collectContainerSharePrincipalPolicies(input: {\n execSql: ExecSql;\n persistVerificationCheckpoints?: boolean | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n previousProjection: ContainerWriterProjectionResponse;\n recipientPolicy?: PrincipalPolicyCurrentEvidence | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const previousPolicies =\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: input.previousProjection,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n return refreshedPrincipalPolicies({\n previousPolicies,\n replacementPrincipalPolicy: input.recipientPolicy,\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linkSetAuthority.js","sourceRoot":"","sources":["linkSetAuthority.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"linkSetAuthority.js","sourceRoot":"","sources":["linkSetAuthority.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,2BAA2B,EAC3B,0BAA0B,GAC3B,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,0CAA0C,EAAE,MAAM,wCAAwC,CAAC;AAEpG,OAAO,EAEL,yBAAyB,GAC1B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,iDAAiD,GAElD,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,4BAA4B,EAAE,MAAM,sEAA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AG,4BAA4B,CAAC,KAAK,CAAC,gBAAgB,CAAC;SACxD,EAAE,CAAC;YACF,MAAM,iDAAiD,CAAC;gBACtD,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;gBAChD,UAAU;gBACV,cAAc,EAAE,KAAK,CAAC,wBAAwB;gBAC9C,YAAY,EAAE,KAAK,CAAC,YAAY;gBAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;aACvE,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,uCAAuC,CACrC,KAAK,EACL,sDAAsD,CACvD,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n assertContainerAuthorAccess,\n ContainerAuthorAccessError,\n} from \"../../data/containers/shared/authorAccess\";\nimport { readLinkedContainerIdsFromDocumentManifest } from \"../../data/documents/shared/projection\";\nimport type { DocumentCreateAuthor } from \"../../data/documents/shared/types\";\nimport {\n type ProjectionVerificationOptions,\n resolveProjectionVerifier,\n} from \"../../data/documents/shared/types\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n type PrincipalPolicyCache,\n} from \"../../data/keyingProjectionVerification\";\nimport { documentContainerProjections } from \"../../data/keyingProjectionVerification/documentContainerProjections\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../data/keyingProjectionVerification/error\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../data/principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\n/** Both paths have been verified; a readable proof does not authorize a link. */\nexport function assertDocumentLinkAuthorAccess(input: {\n author: DocumentCreateAuthor;\n principalPolicies: readonly PrincipalPolicyCheckpointEvidence[];\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}): void {\n const author = {\n ...input.author,\n organizationId: input.targetContainerProjection.organizationId,\n };\n const permission = {\n author,\n minimumAccess: \"write\" as const,\n principalPolicies: input.principalPolicies,\n };\n assertContainerAuthorAccess({\n ...permission,\n projection: input.targetContainerProjection,\n });\n const linked = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n for (const projection of documentContainerProjections(\n input.writerProjection,\n )) {\n if (!linked.includes(projection.containerId)) continue;\n try {\n assertContainerAuthorAccess({ ...permission, projection });\n return;\n } catch (error) {\n if (!(error instanceof ContainerAuthorAccessError)) throw error;\n }\n }\n throw new ContainerAuthorAccessError(\n \"Document signer lacks write access through a linked container\",\n );\n}\n\n/** Current write authorization needs full policies for the readable paths. */\nexport async function verifyDocumentLinkSetCurrentPolicies(\n input: {\n execSql?: ExecSql | undefined;\n principalPolicyCache: PrincipalPolicyCache;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<void> {\n resolveProjectionVerifier(input, \"Document link-set current policies\");\n if (input.trustedLocalProjection === true) return;\n try {\n for (const projection of [\n input.targetContainerProjection,\n ...documentContainerProjections(input.writerProjection),\n ]) {\n await collectContainerWriterProjectionPrincipalPolicies({\n execSql: input.execSql,\n principalPolicyCache: input.principalPolicyCache,\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n }\n } catch (error) {\n throwKeyingVerificationErrorWithContext(\n error,\n \"Document link-set current policy verification failed\",\n );\n }\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { type CachePrincipalPolicyBundlesOptions, type CacheReferencedPrincipalPoliciesOptions, cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache.js";
|
|
2
2
|
export { PrincipalPolicyHistoryReadError, type RecoveredPrincipalPolicyHistory, type RecoverPrincipalPolicyHistoryOptions, } from "./principalHistoryRecoveryTypes.js";
|
|
3
3
|
export { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
|
|
4
|
+
export { type RecoveredScopedPrincipalPolicyHistory, type RecoverScopedPrincipalPolicyHistoryOptions, recoverScopedPrincipalPolicyHistory, } from "./recoverScopedPrincipalPolicyHistory.js";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache.js";
|
|
2
2
|
export { PrincipalPolicyHistoryReadError, } from "./principalHistoryRecoveryTypes.js";
|
|
3
3
|
export { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
|
|
4
|
+
export { recoverScopedPrincipalPolicyHistory, } from "./recoverScopedPrincipalPolicyHistory.js";
|
|
4
5
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,+BAA+B,GAGhC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC","sourcesContent":["export {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,+BAA+B,GAGhC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAGL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC","sourcesContent":["export {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\nexport {\n type RecoveredScopedPrincipalPolicyHistory,\n type RecoverScopedPrincipalPolicyHistoryOptions,\n recoverScopedPrincipalPolicyHistory,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n"]}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { restorePrincipalPolicyHistoryVerifier, serializeKeyingCanonicalJson, } from "../../internal/crypto/index.js";
|
|
2
|
+
import { isReferencedPrincipalStateResponse } from "../../internal/validators/response/index.js";
|
|
3
|
+
import { discardPrincipalHistoryPrefix, loadPrincipalHistoryPrefix, savePrincipalHistoryPrefix, } from "../../data/persistence/principalHistoryPrefixPersistence.js";
|
|
4
|
+
import { principalHistoryPrefixProtection } from "../../data/principals/principalHistoryPrefixProtection.js";
|
|
5
|
+
import { parsePrincipalHistoryStageCurrent } from "../../data/principals/principalHistoryStageProtection.js";
|
|
6
|
+
export async function loadVerifiedPrincipalHistoryPrefix(options, historyInput, scopeId) {
|
|
7
|
+
const saved = await loadPrincipalHistoryPrefix(options.execSql, scopeId);
|
|
8
|
+
if (!saved)
|
|
9
|
+
return null;
|
|
10
|
+
let head;
|
|
11
|
+
try {
|
|
12
|
+
head = JSON.parse(saved.headJson);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
head = null;
|
|
16
|
+
}
|
|
17
|
+
if (saved.organizationId === options.organizationId &&
|
|
18
|
+
isReferencedPrincipalStateResponse(head) &&
|
|
19
|
+
head.principalType === historyInput.principalType &&
|
|
20
|
+
head.principalId === historyInput.principalId &&
|
|
21
|
+
head.version === saved.version) {
|
|
22
|
+
const restored = await restorePrincipalPolicyHistoryVerifier(historyInput, saved.progress, await principalHistoryPrefixProtection(options.protection, saved));
|
|
23
|
+
const current = parsePrincipalHistoryStageCurrent({
|
|
24
|
+
currentJson: saved.currentJson,
|
|
25
|
+
afterVersion: saved.version - 1,
|
|
26
|
+
});
|
|
27
|
+
if (restored.ok && restored.value.finish(head).ok && current)
|
|
28
|
+
return { verifier: restored.value, head, current };
|
|
29
|
+
}
|
|
30
|
+
await discardPrincipalHistoryPrefix({
|
|
31
|
+
execSql: options.execSql,
|
|
32
|
+
prefix: saved,
|
|
33
|
+
stillCurrent: () => !options.signal?.aborted && options.stillCurrent(),
|
|
34
|
+
});
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
export async function restoreReusablePrincipalHistoryPrefix(options, historyInput, scopeId) {
|
|
38
|
+
const prefix = await loadVerifiedPrincipalHistoryPrefix(options, historyInput, scopeId);
|
|
39
|
+
if (!prefix || prefix.head.version > options.expectedHead.version)
|
|
40
|
+
return null;
|
|
41
|
+
if (prefix.head.version < options.expectedHead.version ||
|
|
42
|
+
prefix.verifier.finish(options.expectedHead).ok)
|
|
43
|
+
return { ...prefix, version: prefix.head.version };
|
|
44
|
+
// An incompatible target cannot erase an independently valid local hint.
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
/** The verifier must use stable empty selection/checkpoint inputs. */
|
|
48
|
+
export async function publishReusablePrincipalHistoryPrefix(options, scopeId, verifier, current) {
|
|
49
|
+
const prefix = {
|
|
50
|
+
scopeId,
|
|
51
|
+
organizationId: options.organizationId,
|
|
52
|
+
version: options.expectedHead.version,
|
|
53
|
+
headJson: serializeKeyingCanonicalJson({ ...options.expectedHead }),
|
|
54
|
+
currentJson: JSON.stringify(current),
|
|
55
|
+
};
|
|
56
|
+
const sealed = await verifier.exportProgress(await principalHistoryPrefixProtection(options.protection, prefix));
|
|
57
|
+
if (!sealed.ok)
|
|
58
|
+
throw sealed.error;
|
|
59
|
+
await savePrincipalHistoryPrefix({
|
|
60
|
+
execSql: options.execSql,
|
|
61
|
+
prefix: { ...prefix, progress: sealed.value },
|
|
62
|
+
stillCurrent: () => !options.signal?.aborted && options.stillCurrent(),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
//# sourceMappingURL=principalHistoryRecoveryPrefix.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principalHistoryRecoveryPrefix.js","sourceRoot":"","sources":["principalHistoryRecoveryPrefix.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,qCAAqC,EACrC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AACpF,OAAO,EACL,6BAA6B,EAC7B,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,gCAAgC,EAAE,MAAM,wDAAwD,CAAC;AAC1G,OAAO,EAAE,iCAAiC,EAAE,MAAM,uDAAuD,CAAC;AAG1G,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,OAAmE,EACnE,YAAyC,EACzC,OAAe;IAMf,MAAM,KAAK,GAAG,MAAM,0BAA0B,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACzE,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC;IACxB,IAAI,IAAa,CAAC;IAClB,IAAI,CAAC;QACH,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACpC,CAAC;IAAC,MAAM,CAAC;QACP,IAAI,GAAG,IAAI,CAAC;IACd,CAAC;IACD,IACE,KAAK,CAAC,cAAc,KAAK,OAAO,CAAC,cAAc;QAC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AAI,CAAC,OAAO,GAAG,OAAO,CAAC,YAAY,CAAC,OAAO;QAClD,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE;QAE/C,OAAO,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IACrD,yEAAyE;IACzE,OAAO,IAAI,CAAC;AACd,CAAC;AAED,sEAAsE;AACtE,MAAM,CAAC,KAAK,UAAU,qCAAqC,CACzD,OAA6C,EAC7C,OAAe,EACf,QAAwC,EACxC,OAAmC;IAEnC,MAAM,MAAM,GAAG;QACb,OAAO;QACP,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,OAAO;QACrC,QAAQ,EAAE,4BAA4B,CAAC,EAAE,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;QACnE,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;KACrC,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,cAAc,CAC1C,MAAM,gCAAgC,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,CAAC,CACnE,CAAC;IACF,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,MAAM,CAAC,KAAK,CAAC;IACnC,MAAM,0BAA0B,CAAC;QAC/B,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,KAAK,EAAE;QAC7C,YAAY,EAAE,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,IAAI,OAAO,CAAC,YAAY,EAAE;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n type PrincipalPolicyHistoryInput,\n type PrincipalPolicyHistoryVerifier,\n type ReferencedPrincipalHead,\n restorePrincipalPolicyHistoryVerifier,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { isReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport {\n discardPrincipalHistoryPrefix,\n loadPrincipalHistoryPrefix,\n savePrincipalHistoryPrefix,\n} from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHistoryPrefixProtection } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { parsePrincipalHistoryStageCurrent } from \"../../data/principals/principalHistoryStageProtection\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nexport async function loadVerifiedPrincipalHistoryPrefix(\n options: Omit<RecoverPrincipalPolicyHistoryOptions, \"expectedHead\">,\n historyInput: PrincipalPolicyHistoryInput,\n scopeId: string,\n): Promise<{\n verifier: PrincipalPolicyHistoryVerifier;\n head: ReferencedPrincipalHead;\n current: PrincipalPolicyPageCurrent;\n} | null> {\n const saved = await loadPrincipalHistoryPrefix(options.execSql, scopeId);\n if (!saved) return null;\n let head: unknown;\n try {\n head = JSON.parse(saved.headJson);\n } catch {\n head = null;\n }\n if (\n saved.organizationId === options.organizationId &&\n isReferencedPrincipalStateResponse(head) &&\n head.principalType === historyInput.principalType &&\n head.principalId === historyInput.principalId &&\n head.version === saved.version\n ) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n saved.progress,\n await principalHistoryPrefixProtection(options.protection, saved),\n );\n const current = parsePrincipalHistoryStageCurrent({\n currentJson: saved.currentJson,\n afterVersion: saved.version - 1,\n });\n if (restored.ok && restored.value.finish(head).ok && current)\n return { verifier: restored.value, head, current };\n }\n await discardPrincipalHistoryPrefix({\n execSql: options.execSql,\n prefix: saved,\n stillCurrent: () => !options.signal?.aborted && options.stillCurrent(),\n });\n return null;\n}\n\nexport async function restoreReusablePrincipalHistoryPrefix(\n options: RecoverPrincipalPolicyHistoryOptions,\n historyInput: PrincipalPolicyHistoryInput,\n scopeId: string,\n) {\n const prefix = await loadVerifiedPrincipalHistoryPrefix(\n options,\n historyInput,\n scopeId,\n );\n if (!prefix || prefix.head.version > options.expectedHead.version)\n return null;\n if (\n prefix.head.version < options.expectedHead.version ||\n prefix.verifier.finish(options.expectedHead).ok\n )\n return { ...prefix, version: prefix.head.version };\n // An incompatible target cannot erase an independently valid local hint.\n return null;\n}\n\n/** The verifier must use stable empty selection/checkpoint inputs. */\nexport async function publishReusablePrincipalHistoryPrefix(\n options: RecoverPrincipalPolicyHistoryOptions,\n scopeId: string,\n verifier: PrincipalPolicyHistoryVerifier,\n current: PrincipalPolicyPageCurrent,\n): Promise<void> {\n const prefix = {\n scopeId,\n organizationId: options.organizationId,\n version: options.expectedHead.version,\n headJson: serializeKeyingCanonicalJson({ ...options.expectedHead }),\n currentJson: JSON.stringify(current),\n };\n const sealed = await verifier.exportProgress(\n await principalHistoryPrefixProtection(options.protection, prefix),\n );\n if (!sealed.ok) throw sealed.error;\n await savePrincipalHistoryPrefix({\n execSql: options.execSql,\n prefix: { ...prefix, progress: sealed.value },\n stillCurrent: () => !options.signal?.aborted && options.stillCurrent(),\n });\n}\n"]}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { KeyingVerificationError, verifyPrincipalPolicyHistoryReferences, } from "../../internal/crypto/index.js";
|
|
2
|
+
import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
|
|
3
|
+
import { loadPrincipalHistoryReference } from "../../data/persistence/principalHistoryEvidencePersistence.js";
|
|
4
|
+
import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
|
|
5
|
+
export class PrincipalHistoryEvidenceUnavailableError extends Error {
|
|
6
|
+
verificationError;
|
|
7
|
+
constructor(verificationError) {
|
|
8
|
+
super(verificationError.message);
|
|
9
|
+
this.verificationError = verificationError;
|
|
10
|
+
this.name = "PrincipalHistoryEvidenceUnavailableError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
async function selectReferences(input) {
|
|
14
|
+
const { options, scopeId, history } = input;
|
|
15
|
+
const current = () => !options.signal?.aborted && options.stillCurrent();
|
|
16
|
+
const base = { execSql: options.execSql, scopeId, history };
|
|
17
|
+
const references = [];
|
|
18
|
+
for (const reference of options.retainedReferences ?? []) {
|
|
19
|
+
assertProjectionVerificationCurrent(current);
|
|
20
|
+
references.push(await loadPrincipalHistoryReference({
|
|
21
|
+
...base,
|
|
22
|
+
version: reference.version,
|
|
23
|
+
}));
|
|
24
|
+
}
|
|
25
|
+
assertProjectionVerificationCurrent(current);
|
|
26
|
+
const checkpointReference = input.checkpoint
|
|
27
|
+
? await loadPrincipalHistoryReference({
|
|
28
|
+
...base,
|
|
29
|
+
version: input.checkpoint.version,
|
|
30
|
+
})
|
|
31
|
+
: undefined;
|
|
32
|
+
const selected = await verifyPrincipalPolicyHistoryReferences({
|
|
33
|
+
history,
|
|
34
|
+
references,
|
|
35
|
+
checkpointReference,
|
|
36
|
+
});
|
|
37
|
+
if (!selected.ok)
|
|
38
|
+
throw selected.error;
|
|
39
|
+
assertProjectionVerificationCurrent(current);
|
|
40
|
+
return selected.value;
|
|
41
|
+
}
|
|
42
|
+
export async function selectRecoveredPrincipalHistory(input) {
|
|
43
|
+
let selected;
|
|
44
|
+
try {
|
|
45
|
+
selected = await selectReferences(input);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (error instanceof KeyingVerificationError)
|
|
49
|
+
throw new PrincipalHistoryEvidenceUnavailableError(error);
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
// First authenticate the stored entry against the private root. Only then
|
|
53
|
+
// compare the caller's citation, so a bad request is not treated as cache loss.
|
|
54
|
+
for (const reference of input.options.retainedReferences ?? []) {
|
|
55
|
+
if (!selected.retainedEntries.some(({ state }) => principalHeadMatchesReference(state, reference)))
|
|
56
|
+
throw new KeyingVerificationError("object_mismatch", "Requested citation does not match the verified principal history");
|
|
57
|
+
}
|
|
58
|
+
return selected;
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=principalHistoryRecoveryReferences.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principalHistoryRecoveryReferences.js","sourceRoot":"","sources":["principalHistoryRecoveryReferences.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAIvB,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,4DAA4D,CAAC;AAC3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AAGtG,MAAM,OAAO,wCAAyC,SAAQ,KAAK;IAC5C;IAArB,YAAqB,iBAA0C;QAC7D,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QADd,sBAAiB,GAAjB,iBAAiB,CAAyB;QAE7D,IAAI,CAAC,IAAI,GAAG,0CAA0C,CAAC;IACzD,CAAC;CACF;AAED,KAAK,UAAU,gBAAgB,CAAC,KAK/B;IACC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IAC5C,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IACzE,MAAM,IAAI,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;IAC5D,MAAM,UAAU,GAA2C,EAAE,CAAC;IAC9D,KAAK,MAAM,SAAS,IAAI,OAAO,CAAC,kBAAkB,IAAI,EAAE,EAAE,CAAC;QACzD,mCAAmC,CAAC,OAAO,CAAC,CAAC;QAC7C,UAAU,CAAC,IAAI,CACb,MAAM,6BAA6B,CAAC;YAClC,GAAG,IAAI;YACP,OAAO,EAAE,SAAS,CAAC,OAAO;SAC3B,CAAC,CACH,CAAC;IACJ,CAAC;IACD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incipalPolicyHistoryReferenceProof,\n type VerifiedPrincipalPolicyHistory,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { loadPrincipalHistoryReference } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nexport class PrincipalHistoryEvidenceUnavailableError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PrincipalHistoryEvidenceUnavailableError\";\n }\n}\n\nasync function selectReferences(input: {\n readonly options: RecoverPrincipalPolicyHistoryOptions;\n readonly scopeId: string;\n readonly history: VerifiedPrincipalPolicyHistory;\n readonly checkpoint: PrincipalPolicyCheckpoint | null;\n}): Promise<VerifiedPrincipalPolicyHistory> {\n const { options, scopeId, history } = input;\n const current = () => !options.signal?.aborted && options.stillCurrent();\n const base = { execSql: options.execSql, scopeId, history };\n const references: PrincipalPolicyHistoryReferenceProof[] = [];\n for (const reference of options.retainedReferences ?? []) {\n assertProjectionVerificationCurrent(current);\n references.push(\n await loadPrincipalHistoryReference({\n ...base,\n version: reference.version,\n }),\n );\n }\n assertProjectionVerificationCurrent(current);\n const checkpointReference = input.checkpoint\n ? await loadPrincipalHistoryReference({\n ...base,\n version: input.checkpoint.version,\n })\n : undefined;\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references,\n checkpointReference,\n });\n if (!selected.ok) throw selected.error;\n assertProjectionVerificationCurrent(current);\n return selected.value;\n}\n\nexport async function selectRecoveredPrincipalHistory(\n input: Parameters<typeof selectReferences>[0],\n): Promise<VerifiedPrincipalPolicyHistory> {\n let selected: VerifiedPrincipalPolicyHistory;\n try {\n selected = await selectReferences(input);\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n }\n // First authenticate the stored entry against the private root. Only then\n // compare the caller's citation, so a bad request is not treated as cache loss.\n for (const reference of input.options.retainedReferences ?? []) {\n if (\n !selected.retainedEntries.some(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Requested citation does not match the verified principal history\",\n );\n }\n return selected;\n}\n"]}
|
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import { createPrincipalPolicyHistoryVerifier, restorePrincipalPolicyHistoryVerifier, } from "../../internal/crypto/index.js";
|
|
2
2
|
import { discardPrincipalHistoryStage, loadPrincipalHistoryStage, } from "../../data/persistence/principalHistoryStagePersistence.js";
|
|
3
|
+
import { principalHistoryEvidenceScopeId } from "../../data/principals/principalHistoryPrefixProtection.js";
|
|
3
4
|
import { parsePrincipalHistoryStageCurrent, principalHistoryStageId, principalHistoryStageProtection, } from "../../data/principals/principalHistoryStageProtection.js";
|
|
4
|
-
|
|
5
|
+
import { restoreReusablePrincipalHistoryPrefix } from "./principalHistoryRecoveryPrefix.js";
|
|
6
|
+
export async function restorePrincipalHistoryRecoveryStage(input, historyInput, useReusablePrefix = true) {
|
|
7
|
+
const scopeId = await principalHistoryEvidenceScopeId({
|
|
8
|
+
organizationId: input.organizationId,
|
|
9
|
+
head: input.expectedHead,
|
|
10
|
+
protection: input.protection,
|
|
11
|
+
});
|
|
5
12
|
const id = await principalHistoryStageId(input.organizationId, input.expectedHead, input.protection.context, input.retainedReferences ?? []);
|
|
6
13
|
const saved = await loadPrincipalHistoryStage(input.execSql, id);
|
|
7
14
|
if (saved) {
|
|
@@ -9,17 +16,46 @@ export async function restorePrincipalHistoryRecoveryStage(input, historyInput)
|
|
|
9
16
|
if (current && saved.organizationId === input.organizationId) {
|
|
10
17
|
const restored = await restorePrincipalPolicyHistoryVerifier(historyInput, saved.progress, await principalHistoryStageProtection(input.protection, input.expectedHead, saved));
|
|
11
18
|
if (restored.ok)
|
|
12
|
-
return {
|
|
19
|
+
return {
|
|
20
|
+
id,
|
|
21
|
+
scopeId,
|
|
22
|
+
verifier: restored.value,
|
|
23
|
+
current,
|
|
24
|
+
saved,
|
|
25
|
+
complete: saved.complete,
|
|
26
|
+
initialAfterVersion: saved.afterVersion,
|
|
27
|
+
fromCache: true,
|
|
28
|
+
};
|
|
13
29
|
}
|
|
14
30
|
// Saved bytes are a disposable hint. Only a locally authenticated restore
|
|
15
31
|
// can skip signed history; missing keys or changed inputs replay genesis.
|
|
16
32
|
await discardPrincipalHistoryStage(input.execSql, saved, () => !input.signal?.aborted && input.stillCurrent());
|
|
17
33
|
}
|
|
34
|
+
const prefix = useReusablePrefix
|
|
35
|
+
? await restoreReusablePrincipalHistoryPrefix(input, historyInput, scopeId)
|
|
36
|
+
: null;
|
|
37
|
+
if (prefix) {
|
|
38
|
+
const complete = prefix.version === input.expectedHead.version;
|
|
39
|
+
return {
|
|
40
|
+
id,
|
|
41
|
+
scopeId,
|
|
42
|
+
verifier: prefix.verifier,
|
|
43
|
+
current: complete ? prefix.current : null,
|
|
44
|
+
saved: null,
|
|
45
|
+
complete,
|
|
46
|
+
initialAfterVersion: prefix.version - (complete ? 1 : 0),
|
|
47
|
+
fromCache: true,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
18
50
|
return {
|
|
19
51
|
id,
|
|
52
|
+
scopeId,
|
|
20
53
|
verifier: createPrincipalPolicyHistoryVerifier(historyInput),
|
|
21
54
|
current: null,
|
|
22
55
|
saved: null,
|
|
56
|
+
complete: false,
|
|
57
|
+
initialAfterVersion: 0,
|
|
58
|
+
fromCache: false,
|
|
23
59
|
};
|
|
24
60
|
}
|
|
25
61
|
//# sourceMappingURL=principalHistoryRecoveryStage.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalHistoryRecoveryStage.js","sourceRoot":"","sources":["principalHistoryRecoveryStage.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EAGpC,qCAAqC,GACtC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAE1B,MAAM,yDAAyD,CAAC;AACjE,OAAO,EACL,iCAAiC,EACjC,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,uDAAuD,CAAC;
|
|
1
|
+
{"version":3,"file":"principalHistoryRecoveryStage.js","sourceRoot":"","sources":["principalHistoryRecoveryStage.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EAGpC,qCAAqC,GACtC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAE1B,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,+BAA+B,EAAE,MAAM,wDAAwD,CAAC;AACzG,OAAO,EACL,iCAAiC,EACjC,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AAczF,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,KAA2C,EAC3C,YAAyC,EACzC,iBAAiB,GAAG,IAAI;IAExB,MAAM,OAAO,GAAG,MAAM,+BAA+B,CAAC;QACpD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,IAAI,EAAE,KAAK,CAAC,YAAY;QACxB,UAAU,EAAE,KAAK,CAAC,UAAU;KAC7B,CAAC,CAAC;IACH,MAAM,EAAE,GAAG,MAAM,uBAAuB,CACtC,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,YAAY,EAClB,KAAK,CAAC,UAAU,CAAC,OAAO,EACxB,KAAK,CAAC,kBAAkB,IAAI,EAAE,CAC/B,CAAC;IACF,MAAM,KAAK,GAAG,MAAM,yBAAyB,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IACjE,IAAI,KAAK,EAAE,CAAC;QACV,MAAM,OAAO,GAAG,iCAAiC,CAAC,KAAK,CAAC,CAAC;QACzD,IAAI,OAAO,IAAI,KAAK,CAAC,cAAc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AS,EAAE,IAAI;SAChB,CAAC;IACJ,CAAC;IACD,OAAO;QACL,EAAE;QACF,OAAO;QACP,QAAQ,EAAE,oCAAoC,CAAC,YAAY,CAAC;QAC5D,OAAO,EAAE,IAAI;QACb,KAAK,EAAE,IAAI;QACX,QAAQ,EAAE,KAAK;QACf,mBAAmB,EAAE,CAAC;QACtB,SAAS,EAAE,KAAK;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n createPrincipalPolicyHistoryVerifier,\n type PrincipalPolicyHistoryInput,\n type PrincipalPolicyHistoryVerifier,\n restorePrincipalPolicyHistoryVerifier,\n} from \"@tearleads/crypto\";\nimport {\n discardPrincipalHistoryStage,\n loadPrincipalHistoryStage,\n type PrincipalHistoryStage,\n} from \"../../data/persistence/principalHistoryStagePersistence\";\nimport { principalHistoryEvidenceScopeId } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport {\n parsePrincipalHistoryStageCurrent,\n principalHistoryStageId,\n principalHistoryStageProtection,\n} from \"../../data/principals/principalHistoryStageProtection\";\nimport { restoreReusablePrincipalHistoryPrefix } from \"./principalHistoryRecoveryPrefix\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nexport interface PrincipalHistoryRecoveryStage {\n readonly id: string;\n readonly scopeId: string;\n readonly verifier: PrincipalPolicyHistoryVerifier;\n readonly initialAfterVersion: number;\n readonly fromCache: boolean;\n complete: boolean;\n current: PrincipalPolicyPageCurrent | null;\n saved: PrincipalHistoryStage | null;\n}\n\nexport async function restorePrincipalHistoryRecoveryStage(\n input: RecoverPrincipalPolicyHistoryOptions,\n historyInput: PrincipalPolicyHistoryInput,\n useReusablePrefix = true,\n): Promise<PrincipalHistoryRecoveryStage> {\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: input.expectedHead,\n protection: input.protection,\n });\n const id = await principalHistoryStageId(\n input.organizationId,\n input.expectedHead,\n input.protection.context,\n input.retainedReferences ?? [],\n );\n const saved = await loadPrincipalHistoryStage(input.execSql, id);\n if (saved) {\n const current = parsePrincipalHistoryStageCurrent(saved);\n if (current && saved.organizationId === input.organizationId) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n saved.progress,\n await principalHistoryStageProtection(\n input.protection,\n input.expectedHead,\n saved,\n ),\n );\n if (restored.ok)\n return {\n id,\n scopeId,\n verifier: restored.value,\n current,\n saved,\n complete: saved.complete,\n initialAfterVersion: saved.afterVersion,\n fromCache: true,\n };\n }\n // Saved bytes are a disposable hint. Only a locally authenticated restore\n // can skip signed history; missing keys or changed inputs replay genesis.\n await discardPrincipalHistoryStage(\n input.execSql,\n saved,\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n }\n const prefix = useReusablePrefix\n ? await restoreReusablePrincipalHistoryPrefix(input, historyInput, scopeId)\n : null;\n if (prefix) {\n const complete = prefix.version === input.expectedHead.version;\n return {\n id,\n scopeId,\n verifier: prefix.verifier,\n current: complete ? prefix.current : null,\n saved: null,\n complete,\n initialAfterVersion: prefix.version - (complete ? 1 : 0),\n fromCache: true,\n };\n }\n return {\n id,\n scopeId,\n verifier: createPrincipalPolicyHistoryVerifier(historyInput),\n current: null,\n saved: null,\n complete: false,\n initialAfterVersion: 0,\n fromCache: false,\n };\n}\n"]}
|
|
@@ -1,15 +1,23 @@
|
|
|
1
1
|
import type { ApiClient, PrincipalPolicyPageCurrent, RequestFailure } from "../../internal/api-client/index.js";
|
|
2
|
-
import type
|
|
2
|
+
import { KeyingVerificationError, type PrincipalPolicyExternalAuthority, type PrincipalPolicyHistoryProgressOptions, type PrincipalPolicyStateChainEntry, 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
|
+
/** A locally observed race, distinct from a rejected signed predecessor. */
|
|
6
|
+
export declare class PrincipalHistoryRecoveryRaceError extends KeyingVerificationError {
|
|
7
|
+
constructor(message: string);
|
|
8
|
+
}
|
|
5
9
|
export interface RecoverPrincipalPolicyHistoryOptions {
|
|
6
10
|
readonly apiClient: Pick<ApiClient, "getPrincipalPolicyPages">;
|
|
7
11
|
readonly execSql: ExecSql;
|
|
8
12
|
readonly organizationId: string;
|
|
9
13
|
readonly expectedHead: ReferencedPrincipalHead;
|
|
14
|
+
/** Only use locally authenticated completed evidence; never perform HTTP. */
|
|
15
|
+
readonly offline?: boolean | undefined;
|
|
10
16
|
/** Device-controlled key and stable identity/trust-policy context, never supplied by the API. */
|
|
11
17
|
readonly protection: PrincipalPolicyHistoryProgressOptions;
|
|
12
18
|
readonly retainedReferences?: readonly ReferencedPrincipalHead[] | undefined;
|
|
19
|
+
/** Strict Admins mode checks every historical projection in a separate cache scope. */
|
|
20
|
+
readonly historyVerification?: "standard" | "direct-admins" | undefined;
|
|
13
21
|
readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
|
|
14
22
|
/** Return only authority already authenticated by this client. */
|
|
15
23
|
readonly loadExternalAuthority?: ((entries: readonly PrincipalPolicyStateChainEntry[]) => Promise<PrincipalPolicyExternalAuthority | undefined>) | undefined;
|
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
import { KeyingVerificationError, } from "../../internal/crypto/index.js";
|
|
2
|
+
/** A locally observed race, distinct from a rejected signed predecessor. */
|
|
3
|
+
export class PrincipalHistoryRecoveryRaceError extends KeyingVerificationError {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super("stale_predecessor", message);
|
|
6
|
+
}
|
|
7
|
+
}
|
|
1
8
|
export class PrincipalPolicyHistoryReadError extends Error {
|
|
2
9
|
failure;
|
|
3
10
|
constructor(failure) {
|
|
@@ -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":"AAKA,OAAO,EACL,uBAAuB,GAMxB,MAAM,mBAAmB,CAAC;AAI3B,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 ApiClient,\n PrincipalPolicyPageCurrent,\n RequestFailure,\n} from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type PrincipalPolicyHistoryProgressOptions,\n type PrincipalPolicyStateChainEntry,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\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 apiClient: Pick<ApiClient, \"getPrincipalPolicyPages\">;\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 /** Return only authority already authenticated by this client. */\n readonly loadExternalAuthority?:\n | ((\n entries: readonly PrincipalPolicyStateChainEntry[],\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,24 @@
|
|
|
1
|
+
import { KeyingVerificationError, serializeKeyingCanonicalJson, } from "../../internal/crypto/index.js";
|
|
2
|
+
export function principalHistoryVerificationContext(input) {
|
|
3
|
+
const mode = input.historyVerification ?? "standard";
|
|
4
|
+
if (mode !== "standard" && mode !== "direct-admins")
|
|
5
|
+
throw new KeyingVerificationError("invalid_shape", "Unknown principal history verification mode");
|
|
6
|
+
if (mode === "standard")
|
|
7
|
+
return input.protection.context;
|
|
8
|
+
if (input.expectedHead.principalType !== "group" ||
|
|
9
|
+
input.loadExternalAuthority)
|
|
10
|
+
throw new KeyingVerificationError("invalid_shape", "Strict Admins history requires a group without external authority fallback");
|
|
11
|
+
// Retire this local attestation domain whenever strict validation changes.
|
|
12
|
+
return serializeKeyingCanonicalJson([
|
|
13
|
+
"tearleads.sdk.principal-history.direct-admins.v1",
|
|
14
|
+
input.protection.context,
|
|
15
|
+
]);
|
|
16
|
+
}
|
|
17
|
+
export function assertPrincipalHistoryVerificationMode(input, entries) {
|
|
18
|
+
if (input.historyVerification !== "direct-admins")
|
|
19
|
+
return;
|
|
20
|
+
if (entries.some((entry) => entry.projection.length === 0 ||
|
|
21
|
+
entry.projection.some((member) => member.role !== "admin")))
|
|
22
|
+
throw new KeyingVerificationError("invalid_shape", "Reserved Admins history must contain only direct admin users");
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=principalHistoryRecoveryVerification.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"principalHistoryRecoveryVerification.js","sourceRoot":"","sources":["principalHistoryRecoveryVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAG3B,MAAM,UAAU,mCAAmC,CACjD,KAA2C;IAE3C,MAAM,IAAI,GAAG,KAAK,CAAC,mBAAmB,IAAI,UAAU,CAAC;IACrD,IAAI,IAAI,KAAK,UAAU,IAAI,IAAI,KAAK,eAAe;QACjD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,6CAA6C,CAC9C,CAAC;IACJ,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC;IACzD,IACE,KAAK,CAAC,YAAY,CAAC,aAAa,KAAK,OAAO;QAC5C,KAAK,CAAC,qBAAqB;QAE3B,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,4EAA4E,CAC7E,CAAC;IACJ,2EAA2E;IAC3E,OAAO,4BAA4B,CAAC;QAClC,kDAAkD;QAClD,KAAK,CAAC,UAAU,CAAC,OAAO;KACzB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,KAA2C,EAC3C,OAAkD;IAElD,IAAI,KAAK,CAAC,mBAAmB,KAAK,eAAe;QAAE,OAAO;IAC1D,IACE,OAAO,CAAC,IAAI,CACV,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC;QAC7B,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,OAAO,CAAC,CAC7D;QAED,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,8DAA8D,CAC/D,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyStateChainEntry,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\n\nexport function principalHistoryVerificationContext(\n input: RecoverPrincipalPolicyHistoryOptions,\n): string {\n const mode = input.historyVerification ?? \"standard\";\n if (mode !== \"standard\" && mode !== \"direct-admins\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Unknown principal history verification mode\",\n );\n if (mode === \"standard\") return input.protection.context;\n if (\n input.expectedHead.principalType !== \"group\" ||\n input.loadExternalAuthority\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Strict Admins history requires a group without external authority fallback\",\n );\n // Retire this local attestation domain whenever strict validation changes.\n return serializeKeyingCanonicalJson([\n \"tearleads.sdk.principal-history.direct-admins.v1\",\n input.protection.context,\n ]);\n}\n\nexport function assertPrincipalHistoryVerificationMode(\n input: RecoverPrincipalPolicyHistoryOptions,\n entries: readonly PrincipalPolicyStateChainEntry[],\n): void {\n if (input.historyVerification !== \"direct-admins\") return;\n if (\n entries.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Reserved Admins history must contain only direct admin users\",\n );\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type ReferencedPrincipalHead } from "../../internal/crypto/index.js";
|
|
2
|
+
import { type OrganizationAuthorityDescriptor } from "../../data/principals/organizationAuthorityDescriptor.js";
|
|
3
|
+
import { type RecoveredPrincipalPolicyHistory, type RecoverPrincipalPolicyHistoryOptions } from "./principalHistoryRecoveryTypes.js";
|
|
4
|
+
export type PrincipalRecoveryContext = Omit<RecoverPrincipalPolicyHistoryOptions, "expectedHead" | "retainedReferences" | "historyVerification" | "loadExternalAuthority">;
|
|
5
|
+
export interface RecoveredPolicyDirectory extends RecoveredPrincipalPolicyHistory {
|
|
6
|
+
readonly descriptor: OrganizationAuthorityDescriptor;
|
|
7
|
+
}
|
|
8
|
+
export declare class PrincipalRecoveryDirectoryAdvanced extends Error {
|
|
9
|
+
}
|
|
10
|
+
export declare function recoverPolicyDirectory(input: PrincipalRecoveryContext, references: readonly ReferencedPrincipalHead[]): Promise<RecoveredPolicyDirectory>;
|