@tearleads/client-sdk 0.1.198 → 0.1.200
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/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +2 -2
- package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +2 -2
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +6 -7
- package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
- package/data/persistence/identity/trustedUserIdentityPinModel.d.ts +4 -0
- package/data/persistence/identity/trustedUserIdentityPinModel.js +113 -0
- package/data/persistence/identity/trustedUserIdentityPinModel.js.map +1 -1
- package/data/persistence/identity/trustedUserIdentityPinRepository.js +196 -0
- package/data/persistence/identity/trustedUserIdentityPinRepository.js.map +1 -0
- package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js +4 -16
- package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -1
- package/data/persistence/principalPolicy/heldPrincipalState.js +2 -11
- package/data/persistence/principalPolicy/heldPrincipalState.js.map +1 -1
- package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +14 -65
- package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyBundleRepository.js +180 -0
- package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -0
- package/data/persistence/principalPolicy/principalPolicyPersistence.js +6 -62
- package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -1
- package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +11 -12
- package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -1
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js +24 -40
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js.map +1 -1
- package/data/principals/organizationGroupRoles.js +2 -2
- package/data/principals/organizationGroupRoles.js.map +1 -1
- package/data/principals/principalPolicyCrypto.js +2 -2
- package/data/principals/principalPolicyCrypto.js.map +1 -1
- package/data/trustedUserIdentity/pinnedIdentity.d.ts +1 -1
- package/data/trustedUserIdentity/pinnedIdentity.js +2 -2
- package/data/trustedUserIdentity/pinnedIdentity.js.map +1 -1
- package/data/trustedUserIdentity/pinnedResolution.js +4 -5
- package/data/trustedUserIdentity/pinnedResolution.js.map +1 -1
- package/data/trustedUserIdentity/service.js +12 -13
- package/data/trustedUserIdentity/service.js.map +1 -1
- package/package.json +1 -1
- package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +2 -2
- package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
- package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -5
- package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
- package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
- package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
- package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +4 -11
- package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js +7 -9
- package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
- package/workflows/organizations/groupShare/shareWithGroup.js +2 -2
- package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
- package/workflows/organizations/groups/deleteOrganizationGroup.js +2 -4
- package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
- package/workflows/organizations/groups/organizationGroupDirectory.js +2 -4
- package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
- package/workflows/organizations/readModel/localReadModelDetails.js +3 -3
- package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
- package/workflows/principals/externalAdminPolicy.js +2 -4
- package/workflows/principals/externalAdminPolicy.js.map +1 -1
- package/workflows/principals/policyCache/index.js +3 -5
- package/workflows/principals/policyCache/index.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +3 -2
- package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +2 -2
- package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -3
- package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
- package/workflows/registration/registrationPrincipalPolicyPersistence.js +2 -4
- package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
- package/data/persistence/identity/trustedUserIdentityPinBatch.js +0 -36
- package/data/persistence/identity/trustedUserIdentityPinBatch.js.map +0 -1
- package/data/persistence/identity/trustedUserIdentitySigningKeyBinding.js +0 -18
- package/data/persistence/identity/trustedUserIdentitySigningKeyBinding.js.map +0 -1
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js +0 -18
- package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
- package/data/persistence/trustedUserIdentityPinPersistence.d.ts +0 -37
- package/data/persistence/trustedUserIdentityPinPersistence.js +0 -258
- package/data/persistence/trustedUserIdentityPinPersistence.js.map +0 -1
- /package/data/persistence/{trustedUserIdentityPinTransaction.js → identity/trustedUserIdentityPinTransaction.js} +0 -0
- /package/data/persistence/{trustedUserIdentityPinTransaction.js.map → identity/trustedUserIdentityPinTransaction.js.map} +0 -0
|
@@ -1,57 +1,41 @@
|
|
|
1
1
|
import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
|
|
2
|
-
import { keyingCheckpointTables } from "../../sqlite/schema/keyingCheckpointSchema.js";
|
|
3
|
-
import { principalPolicyTables } from "../../sqlite/schema/principalPolicySchema.js";
|
|
4
|
-
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
5
|
-
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|
6
2
|
import { validatePrincipalPolicyCheckpointAdvances, writePrincipalPolicyCheckpoints, } from "../keyingCheckpoints/keyingCheckpointAdvancePersistence.js";
|
|
7
3
|
import { loadStoredPrincipalPolicyCheckpoints, principalPolicyKey, } from "../keyingCheckpoints/keyingCheckpointPersistence.js";
|
|
8
4
|
import { assertPrincipalPolicyBundleStoredInTransaction, writePrincipalPolicyBundleInTransaction, } from "./principalPolicyPersistence.js";
|
|
9
5
|
import { assertBundleMatchesVerifiedPolicy } from "./verifiedPrincipalPolicyBundle.js";
|
|
10
|
-
/**
|
|
11
|
-
|
|
12
|
-
* This prevents a crash or bundle-write failure from leaving a checkpoint
|
|
13
|
-
* without the exact same-head payload and member-envelope evidence.
|
|
14
|
-
*/
|
|
15
|
-
export async function persistVerifiedPrincipalPolicyBundlesAtomically(input) {
|
|
6
|
+
/** Rejects a batch that repeats a principal or mismatches its verified policy. */
|
|
7
|
+
export async function assertVerifiedPrincipalPolicyBundles(entries) {
|
|
16
8
|
const seen = new Set();
|
|
17
|
-
for (const entry of
|
|
9
|
+
for (const entry of entries) {
|
|
18
10
|
const key = principalPolicyKey(entry.policy);
|
|
19
11
|
if (seen.has(key)) {
|
|
20
12
|
throw new KeyingVerificationError("duplicate_entry", `verified policy bundle batch repeats ${key}`);
|
|
21
13
|
}
|
|
22
14
|
seen.add(key);
|
|
23
15
|
}
|
|
24
|
-
await Promise.all(
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
16
|
+
await Promise.all(entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)));
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Writes each verified bundle with its durable head, then reads both back, so
|
|
20
|
+
* a checkpoint never lands without its exact same-head bundle.
|
|
21
|
+
*/
|
|
22
|
+
export async function persistVerifiedPrincipalPolicyBundlesInTransaction(tx, input, updatedAt) {
|
|
23
|
+
const policies = await validatePrincipalPolicyCheckpointAdvances(tx, input.entries.map((entry) => entry.policy));
|
|
24
|
+
for (const entry of input.entries) {
|
|
25
|
+
await writePrincipalPolicyBundleInTransaction(tx, entry.bundle, updatedAt, input.organizationId);
|
|
26
|
+
await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);
|
|
27
|
+
}
|
|
28
|
+
await writePrincipalPolicyCheckpoints(tx, policies, updatedAt, input.organizationId);
|
|
29
|
+
const stored = await loadStoredPrincipalPolicyCheckpoints(tx, [
|
|
30
|
+
...policies.values(),
|
|
28
31
|
]);
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
}
|
|
36
|
-
await writePrincipalPolicyCheckpoints(tx, policies, input.updatedAt, input.organizationId);
|
|
37
|
-
const stored = await loadStoredPrincipalPolicyCheckpoints(tx, [
|
|
38
|
-
...policies.values(),
|
|
39
|
-
]);
|
|
40
|
-
for (const policy of policies.values()) {
|
|
41
|
-
const checkpoint = stored.get(principalPolicyKey(policy));
|
|
42
|
-
if (!checkpoint ||
|
|
43
|
-
checkpoint.version !== policy.version ||
|
|
44
|
-
checkpoint.stateHash !== policy.stateHash) {
|
|
45
|
-
throw new Error("Verified principal policy checkpoint was not persisted");
|
|
46
|
-
}
|
|
32
|
+
for (const policy of policies.values()) {
|
|
33
|
+
const checkpoint = stored.get(principalPolicyKey(policy));
|
|
34
|
+
if (!checkpoint ||
|
|
35
|
+
checkpoint.version !== policy.version ||
|
|
36
|
+
checkpoint.stateHash !== policy.stateHash) {
|
|
37
|
+
throw new Error("Verified principal policy checkpoint was not persisted");
|
|
47
38
|
}
|
|
48
|
-
};
|
|
49
|
-
if (input.stillCurrent) {
|
|
50
|
-
await runtime.guardedTransaction(persist, input.stillCurrent, {
|
|
51
|
-
behavior: "immediate",
|
|
52
|
-
});
|
|
53
|
-
return;
|
|
54
39
|
}
|
|
55
|
-
await runtime.transaction(persist, { behavior: "immediate" });
|
|
56
40
|
}
|
|
57
41
|
//# sourceMappingURL=verifiedPrincipalPolicyBundlePersistence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifiedPrincipalPolicyBundlePersistence.js","sourceRoot":"","sources":["verifiedPrincipalPolicyBundlePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"verifiedPrincipalPolicyBundlePersistence.js","sourceRoot":"","sources":["verifiedPrincipalPolicyBundlePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,yCAAyC,EACzC,+BAA+B,GAChC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EACL,oCAAoC,EACpC,kBAAkB,GACnB,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EACL,8CAA8C,EAC9C,uCAAuC,GACxC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AAOpF,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,OAAsD;IAEtD,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,GAAG,GAAG,kBAAkB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC7C,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YAClB,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,wCAAwC,GAAG,EAAE,CAC9C,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC;IACD,MAAM,OAAO,CAAC,GAAG,CACf,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,iCAAiC,CAAC,KAAK,CAAC,CAAC,CACjE,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,kDAAkD,CACtE,EAAgC,EAChC,KAGC,EACD,SAAiB;IAEjB,MAAM,QAAQ,GAAG,MAAM,yCAAyC,CAC9D,EAAE,EACF,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAC3C,CAAC;IACF,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QAClC,MAAM,uCAAuC,CAC3C,EAAE,EACF,KAAK,CAAC,MAAM,EACZ,SAAS,EACT,KAAK,CAAC,cAAc,CACrB,CAAC;QACF,MAAM,8CAA8C,CAAC,EAAE,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACzE,CAAC;IACD,MAAM,+BAA+B,CACnC,EAAE,EACF,QAAQ,EACR,SAAS,EACT,KAAK,CAAC,cAAc,CACrB,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,oCAAoC,CAAC,EAAE,EAAE;QAC5D,GAAG,QAAQ,CAAC,MAAM,EAAE;KACrB,CAAC,CAAC;IACH,KAAK,MAAM,MAAM,IAAI,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;QACvC,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC;QAC1D,IACE,CAAC,UAAU;YACX,UAAU,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO;YACrC,UAAU,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,EACzC,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;QAC5E,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n validatePrincipalPolicyCheckpointAdvances,\n writePrincipalPolicyCheckpoints,\n} from \"../keyingCheckpoints/keyingCheckpointAdvancePersistence\";\nimport {\n loadStoredPrincipalPolicyCheckpoints,\n principalPolicyKey,\n} from \"../keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n assertPrincipalPolicyBundleStoredInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\nexport interface VerifiedPrincipalPolicyBundleEntry {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\n/** Rejects a batch that repeats a principal or mismatches its verified policy. */\nexport async function assertVerifiedPrincipalPolicyBundles(\n entries: readonly VerifiedPrincipalPolicyBundleEntry[],\n): Promise<void> {\n const seen = new Set<string>();\n for (const entry of entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `verified policy bundle batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n await Promise.all(\n entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n}\n\n/**\n * Writes each verified bundle with its durable head, then reads both back, so\n * a checkpoint never lands without its exact same-head bundle.\n */\nexport async function persistVerifiedPrincipalPolicyBundlesInTransaction(\n tx: ClientSQLiteTransactionScope,\n input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly organizationId?: string | undefined;\n },\n updatedAt: string,\n): Promise<void> {\n const policies = await validatePrincipalPolicyCheckpointAdvances(\n tx,\n input.entries.map((entry) => entry.policy),\n );\n for (const entry of input.entries) {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n updatedAt,\n input.organizationId,\n );\n await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);\n }\n await writePrincipalPolicyCheckpoints(\n tx,\n policies,\n updatedAt,\n input.organizationId,\n );\n const stored = await loadStoredPrincipalPolicyCheckpoints(tx, [\n ...policies.values(),\n ]);\n for (const policy of policies.values()) {\n const checkpoint = stored.get(principalPolicyKey(policy));\n if (\n !checkpoint ||\n checkpoint.version !== policy.version ||\n checkpoint.stateHash !== policy.stateHash\n ) {\n throw new Error(\"Verified principal policy checkpoint was not persisted\");\n }\n }\n}\n"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { computePrincipalStateHash, computePrincipalStatePayloadCiphertextHash, } from "../../internal/crypto/index.js";
|
|
2
2
|
import { KeyingCheckpointRepository } from "../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
|
|
3
|
-
import {
|
|
3
|
+
import { PrincipalPolicyBundleRepository } from "../persistence/principalPolicy/principalPolicyBundleRepository.js";
|
|
4
4
|
import { parseOrganizationAuthorityDescriptor } from "./organizationAuthorityDescriptor.js";
|
|
5
5
|
/** Public labels come only from a descriptor pinned by prior verification. */
|
|
6
6
|
export async function loadVerifiedOrganizationGroupRoles(execSql, organizationId) {
|
|
7
7
|
const checkpoint = await new KeyingCheckpointRepository(execSql).loadPrincipalPolicyCheckpoint("organization", organizationId);
|
|
8
|
-
const bundle = await loadPrincipalPolicyBundle(
|
|
8
|
+
const bundle = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundle("organization", organizationId);
|
|
9
9
|
if (!checkpoint || !bundle)
|
|
10
10
|
return new Map();
|
|
11
11
|
const state = bundle.currentState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"organizationGroupRoles.js","sourceRoot":"","sources":["organizationGroupRoles.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,0CAA0C,GAC3C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,6DAA6D,CAAC;AACzG,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"organizationGroup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AAO,IAAI,GAAG,EAAE,CAAC;IACnE,OAAO,IAAI,GAAG,CAAC;QACb,CAAC,UAAU,CAAC,YAAY,EAAE,QAAQ,CAAC;QACnC,CAAC,UAAU,CAAC,aAAa,EAAE,SAAS,CAAC;KACtC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computePrincipalStateHash,\n computePrincipalStatePayloadCiphertextHash,\n} from \"@tearleads/crypto\";\nimport { KeyingCheckpointRepository } from \"../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { parseOrganizationAuthorityDescriptor } from \"./organizationAuthorityDescriptor\";\n\n/** Public labels come only from a descriptor pinned by prior verification. */\nexport async function loadVerifiedOrganizationGroupRoles(\n execSql: ExecSql,\n organizationId: string,\n): Promise<ReadonlyMap<string, string>> {\n const checkpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", organizationId);\n const bundle = await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundle(\"organization\", organizationId);\n if (!checkpoint || !bundle) return new Map();\n const state = bundle.currentState;\n if (\n state.principalType !== \"organization\" ||\n state.principalId !== organizationId ||\n state.version !== checkpoint.version ||\n state.stateHash !== checkpoint.stateHash ||\n (await computePrincipalStateHash(state)) !== checkpoint.stateHash ||\n (await computePrincipalStatePayloadCiphertextHash(\n bundle.currentPayload.ciphertext,\n )) !== state.payloadCiphertextHash\n )\n return new Map();\n const descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== organizationId) return new Map();\n return new Map([\n [descriptor.adminGroupId, \"Admins\"],\n [descriptor.memberGroupId, \"Members\"],\n ]);\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { unwrapDek } from "../../internal/crypto/index.js";
|
|
2
2
|
import { base64ToBytes } from "../../internal/encoding/index.js";
|
|
3
|
-
import {
|
|
3
|
+
import { PrincipalPolicyBundleRepository } from "../persistence/principalPolicy/principalPolicyBundleRepository.js";
|
|
4
4
|
function toKeyEnvelopeEntries(envelopes) {
|
|
5
5
|
return envelopes.map((envelope) => ({
|
|
6
6
|
keyFingerprint: envelope.keyFingerprint,
|
|
@@ -19,7 +19,7 @@ function principalBundleKey(bundle) {
|
|
|
19
19
|
return `${bundle.principalType}:${bundle.principalId}`;
|
|
20
20
|
}
|
|
21
21
|
async function createPrincipalPolicyResolutionContext(execSql, fingerprints) {
|
|
22
|
-
const bundles = await loadPrincipalKeyEnvelopeCandidates(
|
|
22
|
+
const bundles = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalKeyEnvelopeCandidates(fingerprints);
|
|
23
23
|
const bundlesByKeyFingerprint = new Map();
|
|
24
24
|
for (const bundle of bundles) {
|
|
25
25
|
const matchingBundles = bundlesByKeyFingerprint.get(bundle.currentState.keyFingerprint) ?? [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicyCrypto.js","sourceRoot":"","sources":["principalPolicyCrypto.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"principalPolicyCrypto.js","sourceRoot":"","sources":["principalPolicyCrypto.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAIpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,gEAAgE,CAAC;AAUjH,SAAS,oBAAoB,CAC3B,SAA+C;IAE/C,OAAO,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;QAClC,cAAc,EAAE,QAAQ,CAAC,cAAc;QACvC,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AAM,IAAI,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC;gBACH,MAAM,kBAAkB,GAAG,MAAM,wBAAwB,CACvD,MAAM,EACN,KAAK,CAAC,SAAS,CAChB,CAAC;gBAEF,OAAO,MAAM,SAAS,CAAC,UAAU,EAAE,kBAAkB,CAAC,CAAC;YACzD,CAAC;YAAC,MAAM,CAAC,CAAA,CAAC;QACZ,CAAC;IACH,CAAC;IAED,MAAM,IAAI,KAAK,CACb,uFAAuF,CACxF,CAAC;AACJ,CAAC","sourcesContent":["import { type RecipientEntry, unwrapDek } from \"@tearleads/crypto\";\nimport { base64ToBytes } from \"@tearleads/encoding\";\nimport type { PrincipalMemberEnvelopeResponse } from \"@tearleads/validators/response\";\nimport type { SerializedKeyEnvelope } from \"@tearleads/validators/util\";\nimport type { PrincipalKeyEnvelopeCandidate } from \"../persistence/principalKeys/principalKeyEnvelopeCandidates\";\nimport { PrincipalPolicyBundleRepository } from \"../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\n\ninterface PrincipalPolicyResolutionContext {\n bundlesByKeyFingerprint: ReadonlyMap<\n string,\n ReadonlyArray<PrincipalKeyEnvelopeCandidate>\n >;\n}\n\nfunction toKeyEnvelopeEntries(\n envelopes: ReadonlyArray<SerializedKeyEnvelope>,\n): RecipientEntry[] {\n return envelopes.map((envelope) => ({\n keyFingerprint: envelope.keyFingerprint,\n kemCipherText: base64ToBytes(envelope.kemCipherText),\n wrappedKey: base64ToBytes(envelope.wrappedKey),\n }));\n}\n\nfunction toMemberEnvelopeEntries(\n envelopes: ReadonlyArray<PrincipalMemberEnvelopeResponse>,\n): RecipientEntry[] {\n return envelopes.map((envelope) => ({\n keyFingerprint: envelope.memberKeyFingerprint,\n kemCipherText: base64ToBytes(envelope.kemCipherText),\n wrappedKey: base64ToBytes(envelope.wrappedKey),\n }));\n}\n\nfunction principalBundleKey(\n bundle: Pick<\n PrincipalKeyEnvelopeCandidate[\"currentState\"],\n \"principalType\" | \"principalId\"\n >,\n): string {\n return `${bundle.principalType}:${bundle.principalId}`;\n}\n\nasync function createPrincipalPolicyResolutionContext(\n execSql: ExecSql,\n fingerprints: readonly string[],\n): Promise<PrincipalPolicyResolutionContext> {\n const bundles = await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalKeyEnvelopeCandidates(fingerprints);\n const bundlesByKeyFingerprint = new Map<\n string,\n PrincipalKeyEnvelopeCandidate[]\n >();\n\n for (const bundle of bundles) {\n const matchingBundles =\n bundlesByKeyFingerprint.get(bundle.currentState.keyFingerprint) ?? [];\n matchingBundles.push(bundle);\n bundlesByKeyFingerprint.set(\n bundle.currentState.keyFingerprint,\n matchingBundles,\n );\n }\n\n return {\n bundlesByKeyFingerprint,\n };\n}\n\nasync function unwrapPrincipalSecretKey(\n bundle: PrincipalKeyEnvelopeCandidate,\n secretKey: Uint8Array,\n): Promise<Uint8Array> {\n const principalKey = principalBundleKey(bundle.currentState);\n const memberEnvelopeEntries = toMemberEnvelopeEntries(\n bundle.currentMemberEnvelopes.envelopes,\n );\n\n try {\n return await unwrapDek(memberEnvelopeEntries, secretKey);\n } catch {\n // No transitive fallback: a principal's envelopes are all addressed to\n // users directly, so if this identity key opens none of them the requester\n // is not a member.\n }\n\n throw new Error(`No matching principal member envelope for ${principalKey}`);\n}\n\nexport async function unwrapKeyEnvelopesWithPrincipalPolicies(input: {\n envelopes: ReadonlyArray<SerializedKeyEnvelope>;\n execSql?: ExecSql | undefined;\n secretKey: Uint8Array;\n}): Promise<Uint8Array> {\n const keyEntries = toKeyEnvelopeEntries(input.envelopes);\n\n try {\n return await unwrapDek(keyEntries, input.secretKey);\n } catch {\n if (!input.execSql) {\n throw new Error(\n \"No matching key envelope entry found for this secret key and no principal policy cache is available\",\n );\n }\n }\n\n const context = await createPrincipalPolicyResolutionContext(\n input.execSql,\n input.envelopes.map((envelope) => envelope.keyFingerprint),\n );\n const attemptedFingerprints = new Set<string>();\n\n for (const envelope of input.envelopes) {\n if (attemptedFingerprints.has(envelope.keyFingerprint)) continue;\n attemptedFingerprints.add(envelope.keyFingerprint);\n const candidateBundles =\n context.bundlesByKeyFingerprint.get(envelope.keyFingerprint) ?? [];\n\n for (const bundle of candidateBundles) {\n try {\n const principalSecretKey = await unwrapPrincipalSecretKey(\n bundle,\n input.secretKey,\n );\n\n return await unwrapDek(keyEntries, principalSecretKey);\n } catch {}\n }\n }\n\n throw new Error(\n \"No matching key envelope entry found for this secret key or cached principal policies\",\n );\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { TrustedUserIdentityPinProvenance } from "../persistence/identity/trustedUserIdentityPinModel.js";
|
|
2
2
|
import type { ExecSql } from "../sqlite/sqlSchema.js";
|
|
3
3
|
import { type TrustedUserIdentity } from "./types.js";
|
|
4
4
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { base64ToBytes } from "../../internal/encoding/index.js";
|
|
2
|
-
import {
|
|
2
|
+
import { TrustedUserIdentityPinRepository } from "../persistence/identity/trustedUserIdentityPinRepository.js";
|
|
3
3
|
import { brandTrustedUserIdentity } from "./types.js";
|
|
4
4
|
import { assertTrustedUserIdentityUserId, validateUserIdentityKeys, } from "./validation.js";
|
|
5
5
|
/**
|
|
@@ -9,7 +9,7 @@ import { assertTrustedUserIdentityUserId, validateUserIdentityKeys, } from "./va
|
|
|
9
9
|
*/
|
|
10
10
|
export async function loadPin(input) {
|
|
11
11
|
assertTrustedUserIdentityUserId(input.userId);
|
|
12
|
-
const pin = await loadTrustedUserIdentityPin(input);
|
|
12
|
+
const pin = await new TrustedUserIdentityPinRepository(input.execSql).loadTrustedUserIdentityPin(input);
|
|
13
13
|
if (!pin)
|
|
14
14
|
return null;
|
|
15
15
|
const keys = await validateUserIdentityKeys({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pinnedIdentity.js","sourceRoot":"","sources":["pinnedIdentity.ts"],"names":[],"mapp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AC,KAAK,CAAC,CAAC,EAAE,QAAQ,IAAI,IAAI,CAAC;AAClD,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport type { TrustedUserIdentityPinProvenance } from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { brandTrustedUserIdentity, type TrustedUserIdentity } from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateUserIdentityKeys,\n} from \"./validation\";\n\n/**\n * Read-only: the identity this trust store already pins for `userId` and how\n * it was established, or null. The stored keys must still match their stored\n * fingerprints. Never inserts, compares against or replaces a pin.\n */\nexport async function loadPin(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userId: string;\n}): Promise<{\n readonly identity: TrustedUserIdentity;\n readonly provenance: TrustedUserIdentityPinProvenance;\n} | null> {\n assertTrustedUserIdentityUserId(input.userId);\n const pin = await new TrustedUserIdentityPinRepository(\n input.execSql,\n ).loadTrustedUserIdentityPin(input);\n if (!pin) return null;\n const keys = await validateUserIdentityKeys({\n candidate: {\n encapsulationPublicKey: base64ToBytes(pin.encapsulationPublicKey),\n signingKeyFingerprint: pin.signingKeyFingerprint,\n signingPublicKey: base64ToBytes(pin.signingPublicKey),\n },\n encapsulationKeyFingerprint: pin.encapsulationKeyFingerprint,\n });\n return {\n identity: brandTrustedUserIdentity({\n ...keys,\n identityTrustDomain: input.identityTrustDomain,\n userId: input.userId,\n }),\n provenance: pin.provenance,\n };\n}\n\n/** Read-only: the pinned identity for `userId` of any provenance, or null. */\nexport async function loadPinnedUserIdentity(input: {\n readonly execSql: ExecSql;\n readonly identityTrustDomain: string;\n readonly userId: string;\n}): Promise<TrustedUserIdentity | null> {\n return (await loadPin(input))?.identity ?? null;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { TrustedUserIdentityPinContentionError } from "../persistence/trustedUserIdentityPinTransaction.js";
|
|
2
|
+
import { TrustedUserIdentityPinCorruptError, } from "../persistence/identity/trustedUserIdentityPinModel.js";
|
|
3
|
+
import { TrustedUserIdentityPinRepository } from "../persistence/identity/trustedUserIdentityPinRepository.js";
|
|
4
|
+
import { TrustedUserIdentityPinContentionError } from "../persistence/identity/trustedUserIdentityPinTransaction.js";
|
|
5
5
|
import { DatabaseUnavailableError } from "../sync/databaseUnavailable.js";
|
|
6
6
|
import { assertTrustedUserIdentityUserId, validateRemoteUserIdentity, } from "./validation.js";
|
|
7
7
|
/** The trust store, account, and runtime generation one operation runs in. */
|
|
@@ -109,8 +109,7 @@ export function withPinnedIdentityResolution(dependencies, resolve, firstSight,
|
|
|
109
109
|
let published = false;
|
|
110
110
|
let completed = false;
|
|
111
111
|
try {
|
|
112
|
-
const pins = await loadTrustedUserIdentityPins({
|
|
113
|
-
execSql: scope.execSql,
|
|
112
|
+
const pins = await new TrustedUserIdentityPinRepository(scope.execSql).loadTrustedUserIdentityPins({
|
|
114
113
|
identityTrustDomain: scope.identityTrustDomain,
|
|
115
114
|
// Self always rechecks the authoritative local keys and provenance.
|
|
116
115
|
userIds: userIds.filter((userId) => userId !== scope.localUserId),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pinnedResolution.js","sourceRoot":"","sources":["pinnedResolution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,qDAAqD,CAAC;AAClG,OAAO,EAAE,kCAAkC,EAAE,MAAM,qDAAqD,CAAC;AAEzG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AAEzG,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAYvE,OAAO,EACL,+BAA+B,EAC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AAM,EAAE,EAAE,CAAC,MAAM,KAAK,KAAK,CAAC,WAAW,CAAC;iBAClE,CAAC,CAAC;gBACH,KAAK,CAAC,aAAa,EAAE,CAAC;gBACtB,MAAM,MAAM,GAAG,MAAM,MAAM,CACzB,cAAc,CAAC;oBACb,OAAO;oBACP,UAAU;oBACV,OAAO;oBACP,IAAI;oBACJ,OAAO,EAAE,OAAO,CAAC,OAAO;oBACxB,OAAO;oBACP,KAAK;oBACL,MAAM;iBACP,CAAC,CACH,CAAC;gBACF,IAAI,OAAO,CAAC,OAAO,IAAI,MAAM,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;oBACvC,KAAK,CAAC,aAAa,EAAE,CAAC;oBACtB,MAAM,UAAU,CAAC,WAAW,CAC1B,KAAK,CAAC,OAAO,EACb,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EACpB,KAAK,CAAC,aAAa,CACpB,CAAC;gBACJ,CAAC;gBACD,KAAK,CAAC,aAAa,EAAE,CAAC;gBACtB,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC;gBAC5B,SAAS,GAAG,IAAI,CAAC;gBACjB,OAAO,MAAM,CAAC;YAChB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,aAAa,CAAC,KAAK,CAAC,CAAC;YAC7B,CAAC;oBAAS,CAAC;gBACT,WAAW,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;YACzE,CAAC;QACH,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { loadTrustedUserIdentityPins } from \"../persistence/identity/trustedUserIdentityPinBatch\";\nimport { TrustedUserIdentityPinCorruptError } from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport type { TrustedUserIdentityPin } from \"../persistence/trustedUserIdentityPinPersistence\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/trustedUserIdentityPinTransaction\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport type {\n HandoffScope,\n StagedIdentityHandoff,\n} from \"./stagedIdentityHandoff\";\nimport type {\n StagedUserIdentityOptions,\n StagedUserIdentityResolver,\n TrustedUserIdentityResolver,\n TrustedUserIdentityServiceDependencies,\n ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\n/** The gateway's own first-sight steps, split so a structural check can stage. */\nexport interface FirstSightIdentitySteps {\n /** The endpoint's validated candidate for a user; never pinned here. */\n readonly loadCandidate: (\n userId: string,\n identityTrustDomain: string,\n ) => Promise<ValidatedUserIdentityCandidate | null>;\n /**\n * Compare-or-insert candidates as `observed` pins in one write transaction:\n * a conflict on any of them, or a failed `assertCurrent` at COMMIT, commits\n * none, so a refused scope leaves no partial publication.\n */\n readonly pinObserved: (\n execSql: ExecSql,\n identities: readonly ValidatedUserIdentityCandidate[],\n assertCurrent: () => void,\n ) => Promise<unknown>;\n}\n\ninterface PinScope extends HandoffScope {\n readonly assertCurrent: () => void;\n}\n\n/** The trust store, account, and runtime generation one operation runs in. */\nfunction capturePinScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n): PinScope {\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (!identityTrustDomain)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n const execSql = dependencies.getExecSql();\n if (!execSql)\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n const localUserId = dependencies.getLocalUserId();\n const generation = dependencies.getScopeGeneration?.();\n return {\n execSql,\n generation,\n identityTrustDomain,\n localUserId,\n assertCurrent() {\n if (\n dependencies.getExecSql() !== execSql ||\n dependencies.getLocalUserId() !== localUserId ||\n dependencies.getScopeGeneration?.() !== generation\n )\n throw new DatabaseUnavailableError(\n \"The active identity changed while verifying pinned users.\",\n );\n },\n };\n}\n\n/**\n * Existing pins, self through ordinary resolution, and first sights staged in\n * memory; a publishing scope first takes an earlier unpublished scope's\n * handed-off answer. `fetched` records every such read so a failure evicts it.\n */\nfunction stagedResolver(input: {\n readonly fetched: Set<string>;\n readonly firstSight: FirstSightIdentitySteps;\n readonly handoff: StagedIdentityHandoff;\n readonly pins: ReadonlyMap<string, TrustedUserIdentityPin>;\n readonly publish: boolean;\n readonly resolve: TrustedUserIdentityResolver;\n readonly scope: PinScope;\n readonly staged: Map<string, ValidatedUserIdentityCandidate>;\n}): StagedUserIdentityResolver {\n const { scope } = input;\n return async (userId) => {\n scope.assertCurrent();\n if (userId === scope.localUserId) {\n const self = await input.resolve(userId);\n scope.assertCurrent();\n return self;\n }\n const pin = input.pins.get(userId);\n if (pin)\n return validateRemoteUserIdentity({\n candidate: pin,\n identityTrustDomain: scope.identityTrustDomain,\n requestedUserId: userId,\n });\n const known = input.staged.get(userId);\n if (known) return known;\n input.fetched.add(userId);\n const handed = input.publish\n ? input.handoff.take(scope, userId)\n : undefined;\n if (handed) {\n input.staged.set(userId, handed);\n return handed;\n }\n const candidate = await input.firstSight.loadCandidate(\n userId,\n scope.identityTrustDomain,\n );\n scope.assertCurrent();\n if (candidate) input.staged.set(userId, candidate);\n return candidate;\n };\n}\n\nfunction pinStoreError(error: unknown): unknown {\n if (error instanceof TrustedUserIdentityPinCorruptError)\n return new KeyingVerificationError(\"invalid_shape\", error.message);\n if (error instanceof TrustedUserIdentityPinContentionError)\n return new DatabaseUnavailableError(\n \"Trusted user identity pin store is busy\",\n );\n return error;\n}\n\n/**\n * A refused scope's answers are evicted, so a corrected retry reads the\n * endpoint again. An unpublished answer is unauthenticated even when `verify`\n * succeeded, since the caller's signature check may still refuse it: it stays\n * pending, readable only by a publishing scope that rechecks it, and any\n * other lookup reads the endpoint.\n */\nfunction settleScope(input: {\n readonly completed: boolean;\n readonly published: boolean;\n readonly fetched: ReadonlySet<string>;\n readonly staged: ReadonlyMap<string, ValidatedUserIdentityCandidate>;\n readonly scope: PinScope;\n readonly handoff: StagedIdentityHandoff;\n}): void {\n if (!input.completed) input.handoff.evict(input.fetched);\n else if (input.published) input.handoff.published(input.staged.keys());\n else input.handoff.retain(input.scope, input.staged);\n}\n\n/** Keep direct resolution unchanged; only structural verifiers opt into pins. */\nexport function withPinnedIdentityResolution(\n dependencies: TrustedUserIdentityServiceDependencies,\n resolve: TrustedUserIdentityResolver,\n firstSight: FirstSightIdentitySteps,\n handoff: StagedIdentityHandoff,\n): TrustedUserIdentityResolver {\n return Object.assign(resolve, {\n async withPinnedIdentities<T>(\n userIds: readonly string[],\n verify: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n ): Promise<T> {\n const captured = capturePinScope(dependencies);\n const scope: PinScope = {\n ...captured,\n assertCurrent() {\n captured.assertCurrent();\n options.assertCurrent?.();\n },\n };\n for (const userId of userIds) assertTrustedUserIdentityUserId(userId);\n // First sights stay in memory until `verify` succeeds for a projection\n // the caller has authenticated: a refusal leaves no durable trace.\n const fetched = new Set<string>();\n const staged = new Map<string, ValidatedUserIdentityCandidate>();\n let published = false;\n let completed = false;\n try {\n const pins = await loadTrustedUserIdentityPins({\n execSql: scope.execSql,\n identityTrustDomain: scope.identityTrustDomain,\n // Self always rechecks the authoritative local keys and provenance.\n userIds: userIds.filter((userId) => userId !== scope.localUserId),\n });\n scope.assertCurrent();\n const result = await verify(\n stagedResolver({\n fetched,\n firstSight,\n handoff,\n pins,\n publish: options.publish,\n resolve,\n scope,\n staged,\n }),\n );\n if (options.publish && staged.size > 0) {\n scope.assertCurrent();\n await firstSight.pinObserved(\n scope.execSql,\n [...staged.values()],\n scope.assertCurrent,\n );\n }\n scope.assertCurrent();\n published = options.publish;\n completed = true;\n return result;\n } catch (error) {\n throw pinStoreError(error);\n } finally {\n settleScope({ completed, published, fetched, staged, scope, handoff });\n }\n },\n });\n}\n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WAAW,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;YACzE,CAAC;QACH,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n type TrustedUserIdentityPin,\n TrustedUserIdentityPinCorruptError,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport type {\n HandoffScope,\n StagedIdentityHandoff,\n} from \"./stagedIdentityHandoff\";\nimport type {\n StagedUserIdentityOptions,\n StagedUserIdentityResolver,\n TrustedUserIdentityResolver,\n TrustedUserIdentityServiceDependencies,\n ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\n/** The gateway's own first-sight steps, split so a structural check can stage. */\nexport interface FirstSightIdentitySteps {\n /** The endpoint's validated candidate for a user; never pinned here. */\n readonly loadCandidate: (\n userId: string,\n identityTrustDomain: string,\n ) => Promise<ValidatedUserIdentityCandidate | null>;\n /**\n * Compare-or-insert candidates as `observed` pins in one write transaction:\n * a conflict on any of them, or a failed `assertCurrent` at COMMIT, commits\n * none, so a refused scope leaves no partial publication.\n */\n readonly pinObserved: (\n execSql: ExecSql,\n identities: readonly ValidatedUserIdentityCandidate[],\n assertCurrent: () => void,\n ) => Promise<unknown>;\n}\n\ninterface PinScope extends HandoffScope {\n readonly assertCurrent: () => void;\n}\n\n/** The trust store, account, and runtime generation one operation runs in. */\nfunction capturePinScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n): PinScope {\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (!identityTrustDomain)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n const execSql = dependencies.getExecSql();\n if (!execSql)\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n const localUserId = dependencies.getLocalUserId();\n const generation = dependencies.getScopeGeneration?.();\n return {\n execSql,\n generation,\n identityTrustDomain,\n localUserId,\n assertCurrent() {\n if (\n dependencies.getExecSql() !== execSql ||\n dependencies.getLocalUserId() !== localUserId ||\n dependencies.getScopeGeneration?.() !== generation\n )\n throw new DatabaseUnavailableError(\n \"The active identity changed while verifying pinned users.\",\n );\n },\n };\n}\n\n/**\n * Existing pins, self through ordinary resolution, and first sights staged in\n * memory; a publishing scope first takes an earlier unpublished scope's\n * handed-off answer. `fetched` records every such read so a failure evicts it.\n */\nfunction stagedResolver(input: {\n readonly fetched: Set<string>;\n readonly firstSight: FirstSightIdentitySteps;\n readonly handoff: StagedIdentityHandoff;\n readonly pins: ReadonlyMap<string, TrustedUserIdentityPin>;\n readonly publish: boolean;\n readonly resolve: TrustedUserIdentityResolver;\n readonly scope: PinScope;\n readonly staged: Map<string, ValidatedUserIdentityCandidate>;\n}): StagedUserIdentityResolver {\n const { scope } = input;\n return async (userId) => {\n scope.assertCurrent();\n if (userId === scope.localUserId) {\n const self = await input.resolve(userId);\n scope.assertCurrent();\n return self;\n }\n const pin = input.pins.get(userId);\n if (pin)\n return validateRemoteUserIdentity({\n candidate: pin,\n identityTrustDomain: scope.identityTrustDomain,\n requestedUserId: userId,\n });\n const known = input.staged.get(userId);\n if (known) return known;\n input.fetched.add(userId);\n const handed = input.publish\n ? input.handoff.take(scope, userId)\n : undefined;\n if (handed) {\n input.staged.set(userId, handed);\n return handed;\n }\n const candidate = await input.firstSight.loadCandidate(\n userId,\n scope.identityTrustDomain,\n );\n scope.assertCurrent();\n if (candidate) input.staged.set(userId, candidate);\n return candidate;\n };\n}\n\nfunction pinStoreError(error: unknown): unknown {\n if (error instanceof TrustedUserIdentityPinCorruptError)\n return new KeyingVerificationError(\"invalid_shape\", error.message);\n if (error instanceof TrustedUserIdentityPinContentionError)\n return new DatabaseUnavailableError(\n \"Trusted user identity pin store is busy\",\n );\n return error;\n}\n\n/**\n * A refused scope's answers are evicted, so a corrected retry reads the\n * endpoint again. An unpublished answer is unauthenticated even when `verify`\n * succeeded, since the caller's signature check may still refuse it: it stays\n * pending, readable only by a publishing scope that rechecks it, and any\n * other lookup reads the endpoint.\n */\nfunction settleScope(input: {\n readonly completed: boolean;\n readonly published: boolean;\n readonly fetched: ReadonlySet<string>;\n readonly staged: ReadonlyMap<string, ValidatedUserIdentityCandidate>;\n readonly scope: PinScope;\n readonly handoff: StagedIdentityHandoff;\n}): void {\n if (!input.completed) input.handoff.evict(input.fetched);\n else if (input.published) input.handoff.published(input.staged.keys());\n else input.handoff.retain(input.scope, input.staged);\n}\n\n/** Keep direct resolution unchanged; only structural verifiers opt into pins. */\nexport function withPinnedIdentityResolution(\n dependencies: TrustedUserIdentityServiceDependencies,\n resolve: TrustedUserIdentityResolver,\n firstSight: FirstSightIdentitySteps,\n handoff: StagedIdentityHandoff,\n): TrustedUserIdentityResolver {\n return Object.assign(resolve, {\n async withPinnedIdentities<T>(\n userIds: readonly string[],\n verify: (resolve: StagedUserIdentityResolver) => Promise<T>,\n options: StagedUserIdentityOptions,\n ): Promise<T> {\n const captured = capturePinScope(dependencies);\n const scope: PinScope = {\n ...captured,\n assertCurrent() {\n captured.assertCurrent();\n options.assertCurrent?.();\n },\n };\n for (const userId of userIds) assertTrustedUserIdentityUserId(userId);\n // First sights stay in memory until `verify` succeeds for a projection\n // the caller has authenticated: a refusal leaves no durable trace.\n const fetched = new Set<string>();\n const staged = new Map<string, ValidatedUserIdentityCandidate>();\n let published = false;\n let completed = false;\n try {\n const pins = await new TrustedUserIdentityPinRepository(\n scope.execSql,\n ).loadTrustedUserIdentityPins({\n identityTrustDomain: scope.identityTrustDomain,\n // Self always rechecks the authoritative local keys and provenance.\n userIds: userIds.filter((userId) => userId !== scope.localUserId),\n });\n scope.assertCurrent();\n const result = await verify(\n stagedResolver({\n fetched,\n firstSight,\n handoff,\n pins,\n publish: options.publish,\n resolve,\n scope,\n staged,\n }),\n );\n if (options.publish && staged.size > 0) {\n scope.assertCurrent();\n await firstSight.pinObserved(\n scope.execSql,\n [...staged.values()],\n scope.assertCurrent,\n );\n }\n scope.assertCurrent();\n published = options.publish;\n completed = true;\n return result;\n } catch (error) {\n throw pinStoreError(error);\n } finally {\n settleScope({ completed, published, fetched, staged, scope, handoff });\n }\n },\n });\n}\n"]}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { KeyingVerificationError } from "../../internal/crypto/index.js";
|
|
2
2
|
import { bytesToBase64 } from "../../internal/encoding/index.js";
|
|
3
3
|
import { TrustedUserIdentityPinCorruptError, TrustedUserIdentityPinMismatchError, } from "../persistence/identity/trustedUserIdentityPinModel.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { TrustedUserIdentityPinContentionError } from "../persistence/trustedUserIdentityPinTransaction.js";
|
|
4
|
+
import { TrustedUserIdentityPinRepository } from "../persistence/identity/trustedUserIdentityPinRepository.js";
|
|
5
|
+
import { TrustedUserIdentityPinContentionError } from "../persistence/identity/trustedUserIdentityPinTransaction.js";
|
|
7
6
|
import { DatabaseUnavailableError } from "../sync/databaseUnavailable.js";
|
|
8
7
|
import { UnverifiedUserIdentityError } from "./admission.js";
|
|
9
8
|
import { assertIdentityLinkMatches, createIdentityLink, parseIdentityLink, } from "./identityLink.js";
|
|
@@ -50,9 +49,8 @@ function durablePin(identity, provenance, firstSeenAt) {
|
|
|
50
49
|
async function compareWithDurablePins(input) {
|
|
51
50
|
const userIds = input.identities.map((identity) => identity.userId);
|
|
52
51
|
try {
|
|
53
|
-
await compareOrInsertTrustedUserIdentityPins({
|
|
52
|
+
await new TrustedUserIdentityPinRepository(input.execSql).compareOrInsertTrustedUserIdentityPins({
|
|
54
53
|
assertCurrent: input.assertCurrent,
|
|
55
|
-
execSql: input.execSql,
|
|
56
54
|
pins: input.identities.map((identity) => durablePin(identity, input.provenance, input.firstSeenAt)),
|
|
57
55
|
});
|
|
58
56
|
}
|
|
@@ -124,6 +122,14 @@ async function pinIdentity(input) {
|
|
|
124
122
|
});
|
|
125
123
|
return brandTrustedUserIdentity(input.identity);
|
|
126
124
|
}
|
|
125
|
+
/** The user this trust store already binds to a signing key, if any. */
|
|
126
|
+
async function boundUserId(dependencies, signingKeyFingerprint) {
|
|
127
|
+
const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
|
|
128
|
+
return new TrustedUserIdentityPinRepository(execSql).loadTrustedUserIdForSigningKey({
|
|
129
|
+
identityTrustDomain,
|
|
130
|
+
signingKeyFingerprint,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
127
133
|
/** Compares an independently received link before pinning it as `link`. */
|
|
128
134
|
async function verifyIdentityLink(dependencies, link) {
|
|
129
135
|
const expectation = parseIdentityLink(link);
|
|
@@ -227,14 +233,7 @@ export function createTrustedUserIdentityService(input) {
|
|
|
227
233
|
return identity ? createIdentityLink(identity, appUrl) : null;
|
|
228
234
|
},
|
|
229
235
|
verifyLink: (link) => verifyIdentityLink(dependencies, link),
|
|
230
|
-
|
|
231
|
-
const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
|
|
232
|
-
return loadTrustedUserIdForSigningKey({
|
|
233
|
-
execSql,
|
|
234
|
-
identityTrustDomain,
|
|
235
|
-
signingKeyFingerprint,
|
|
236
|
-
});
|
|
237
|
-
},
|
|
236
|
+
boundUserId: (signingKeyFingerprint) => boundUserId(dependencies, signingKeyFingerprint),
|
|
238
237
|
async pinLocal(userId, candidate) {
|
|
239
238
|
assertTrustedUserIdentityUserId(userId);
|
|
240
239
|
const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","sourceRoot":"","sources":["service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WAAW,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,CAClD,sBAAsB,CAAC;gBACrB,aAAa;gBACb,OAAO;gBACP,WAAW,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE;gBAC/D,UAAU;gBACV,UAAU,EAAE,UAAU;aACvB,CAAC;SACL,EACD,OAAO,CACR;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { loadTrustedUserIdForSigningKey } from \"../persistence/identity/trustedUserIdentitySigningKeyBinding\";\nimport {\n compareOrInsertTrustedUserIdentityPins,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/trustedUserIdentityPinPersistence\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/trustedUserIdentityPinTransaction\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport { UnverifiedUserIdentityError } from \"./admission\";\nimport {\n assertIdentityLinkMatches,\n createIdentityLink,\n parseIdentityLink,\n} from \"./identityLink\";\nimport { loadPin, loadPinnedUserIdentity } from \"./pinnedIdentity\";\nimport { withPinnedIdentityResolution } from \"./pinnedResolution\";\nimport { withStagedIdentityHandoff } from \"./stagedIdentityHandoff\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\nfunction requireTrustDomain(\n dependencies: TrustedUserIdentityServiceDependencies,\n): string {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n return dependencies.identityTrustDomain;\n}\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain };\n}\n\nfunction durablePin(\n identity: ValidatedUserIdentityCandidate,\n provenance: TrustedUserIdentityPinProvenance,\n firstSeenAt: string,\n) {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt,\n provenance,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: identity.identityTrustDomain,\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: identity.userId,\n };\n}\n\n/** Compare-or-insert every identity in one transaction: all pin, or none. */\nasync function compareWithDurablePins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identities: readonly ValidatedUserIdentityCandidate[];\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<void> {\n const userIds = input.identities.map((identity) => identity.userId);\n try {\n await compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n pins: input.identities.map((identity) =>\n durablePin(identity, input.provenance, input.firstSeenAt),\n ),\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${error.candidate.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${error.candidate.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${error.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${userIds.join(\", \")}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * The candidate for `userId` and where it came from: this device's own keys\n * (`self`) or the identity endpoint (`observed`). Provenance follows the\n * source, never the account that happens to be active once a lookup returns.\n */\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<{\n readonly identity: ValidatedUserIdentityCandidate;\n readonly source: \"self\" | \"observed\";\n} | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return {\n identity: await validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n }),\n source: \"self\",\n };\n }\n\n const identity = await loadRemoteCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n return identity ? { identity, source: \"observed\" } : null;\n}\n\nasync function loadRemoteCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\n/** The trust store and account a lookup started under must still be active. */\nfunction assertResolutionScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n scope: { readonly execSql: ExecSql; readonly localUserId: string | null },\n message: string,\n): void {\n if (\n dependencies.getExecSql() !== scope.execSql ||\n dependencies.getLocalUserId() !== scope.localUserId\n ) {\n throw new DatabaseUnavailableError(message);\n }\n}\n\nasync function pinIdentity(input: {\n /** Checked inside the pin's write transaction, before it commits. */\n readonly assertCurrent?: (() => void) | undefined;\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identities: [input.identity],\n provenance: input.provenance,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/** Compares an independently received link before pinning it as `link`. */\nasync function verifyIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n link: string,\n): Promise<TrustedUserIdentity> {\n const expectation = parseIdentityLink(link);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (expectation.identityTrustDomain !== identityTrustDomain) {\n throw new Error(\n \"This identity link belongs to a different Tearleads service.\",\n );\n }\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n expectation.userId,\n identityTrustDomain,\n );\n if (!candidate)\n throw new Error(\"The identity in this link is unavailable.\");\n await assertIdentityLinkMatches(expectation, candidate.identity);\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed. Open the identity link again.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source === \"self\" ? \"self\" : \"link\",\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(expectation.userId);\n throw error;\n }\n}\n\nfunction admissionScopeChanged(): DatabaseUnavailableError {\n return new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n}\n\n/** Reads that admit a user: only `self` and `link` pins qualify. */\nfunction verifiedPinReaders(\n dependencies: TrustedUserIdentityServiceDependencies,\n): Pick<\n TrustedUserIdentityService,\n \"loadAdmissionPin\" | \"resolveVerified\" | \"requireVerified\"\n> {\n const resolveVerified = async (userId: string) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin && pin.provenance !== \"observed\" ? pin.identity : null;\n };\n // The pin in the trust store of the database the admission captured.\n const loadAdmittingPin = async (\n userId: string,\n admittingExecSql: ExecSql | null,\n ) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (execSql !== admittingExecSql) throw admissionScopeChanged();\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin;\n };\n return {\n resolveVerified,\n async requireVerified(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n if (!pin || pin.provenance === \"observed\") {\n throw new UnverifiedUserIdentityError(userId);\n }\n return pin.identity;\n },\n async loadAdmissionPin(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n return pin\n ? { identity: pin.identity, verified: pin.provenance !== \"observed\" }\n : null;\n },\n };\n}\n\n/** This user's own link, derived exclusively from this device's local keys. */\nasync function createLocalIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n appUrl: string,\n): Promise<string> {\n const identityTrustDomain = requireTrustDomain(dependencies);\n const userId = dependencies.getLocalUserId();\n const candidate = userId ? dependencies.getLocalIdentity(userId) : null;\n if (!userId || !candidate) {\n throw new Error(\"Sign in before sharing your identity link.\");\n }\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return createIdentityLink(identity, appUrl);\n}\n\nexport function createTrustedUserIdentityService(\n input: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n const { dependencies, handoff } = withStagedIdentityHandoff(input);\n const verifiedReaders = verifiedPinReaders(dependencies);\n return {\n async resolvePinned(userId) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });\n },\n ...verifiedReaders,\n createLink: (appUrl) => createLocalIdentityLink(dependencies, appUrl),\n async createLinkFor(userId, appUrl) {\n if (\n userId === dependencies.getLocalUserId() &&\n dependencies.getLocalIdentity(userId)\n ) {\n return createLocalIdentityLink(dependencies, appUrl);\n }\n // Only a `link` or `self` pin: re-sharing an observed (TOFU) key as a\n // link would let its recipient pin an unverified key as `link`.\n const identity = await verifiedReaders.resolveVerified(userId);\n return identity ? createIdentityLink(identity, appUrl) : null;\n },\n verifyLink: (link) => verifyIdentityLink(dependencies, link),\n async boundUserId(signingKeyFingerprint) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadTrustedUserIdForSigningKey({\n execSql,\n identityTrustDomain,\n signingKeyFingerprint,\n });\n },\n async pinLocal(userId, candidate) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({\n dependencies,\n execSql,\n identity,\n provenance: \"self\",\n });\n },\n resolve: withPinnedIdentityResolution(\n dependencies,\n async (userId) => {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } =\n requireTrustStore(dependencies);\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!candidate) {\n return null;\n }\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed while resolving this user.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source,\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n {\n loadCandidate: (userId, identityTrustDomain) =>\n loadRemoteCandidate(dependencies, userId, identityTrustDomain),\n pinObserved: (execSql, identities, assertCurrent) =>\n compareWithDurablePins({\n assertCurrent,\n execSql,\n firstSeenAt: (dependencies.now?.() ?? new Date()).toISOString(),\n identities,\n provenance: \"observed\",\n }),\n },\n handoff,\n ),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kCAAkC,EAClC,mCAAmC,GAEpC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAC5G,OAAO,EAAE,qCAAqC,EAAE,MAAM,2DAA2D,CAAC;AAElH,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAE,4BAA4B,EAAE,MAAM,o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,SAAS,GAAG,MAAM,gBAAgB,CACtC,YAAY,EACZ,MAAM,EACN,mBAAmB,CACpB,CAAC;gBACF,IAAI,CAAC,SAAS,EAAE,CAAC;oBACf,OAAO,IAAI,CAAC;gBACd,CAAC;gBACD,MAAM,aAAa,GAAG,GAAG,EAAE,CACzB,qBAAqB,CACnB,YAAY,EACZ,EAAE,OAAO,EAAE,WAAW,EAAE,EACxB,wDAAwD,CACzD,CAAC;gBACJ,aAAa,EAAE,CAAC;gBAChB,OAAO,MAAM,WAAW,CAAC;oBACvB,aAAa;oBACb,YAAY;oBACZ,OAAO;oBACP,QAAQ,EAAE,SAAS,CAAC,QAAQ;oBAC5B,UAAU,EAAE,SAAS,CAAC,MAAM;iBAC7B,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,YAAY,CAAC,YAAY,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;gBAC7C,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC,EACD;YACE,aAAa,EAAE,CAAC,MAAM,EAAE,mBAAmB,EAAE,EAAE,CAC7C,mBAAmB,CAAC,YAAY,EAAE,MAAM,EAAE,mBAAmB,CAAC;YAChE,WAAW,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,CAClD,sBAAsB,CAAC;gBACrB,aAAa;gBACb,OAAO;gBACP,WAAW,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE;gBAC/D,UAAU;gBACV,UAAU,EAAE,UAAU;aACvB,CAAC;SACL,EACD,OAAO,CACR;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { DatabaseUnavailableError } from \"../sync/databaseUnavailable\";\nimport { UnverifiedUserIdentityError } from \"./admission\";\nimport {\n assertIdentityLinkMatches,\n createIdentityLink,\n parseIdentityLink,\n} from \"./identityLink\";\nimport { loadPin, loadPinnedUserIdentity } from \"./pinnedIdentity\";\nimport { withPinnedIdentityResolution } from \"./pinnedResolution\";\nimport { withStagedIdentityHandoff } from \"./stagedIdentityHandoff\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\nfunction requireTrustDomain(\n dependencies: TrustedUserIdentityServiceDependencies,\n): string {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n return dependencies.identityTrustDomain;\n}\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain };\n}\n\nfunction durablePin(\n identity: ValidatedUserIdentityCandidate,\n provenance: TrustedUserIdentityPinProvenance,\n firstSeenAt: string,\n) {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt,\n provenance,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: identity.identityTrustDomain,\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: identity.userId,\n };\n}\n\n/** Compare-or-insert every identity in one transaction: all pin, or none. */\nasync function compareWithDurablePins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identities: readonly ValidatedUserIdentityCandidate[];\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<void> {\n const userIds = input.identities.map((identity) => identity.userId);\n try {\n await new TrustedUserIdentityPinRepository(\n input.execSql,\n ).compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n pins: input.identities.map((identity) =>\n durablePin(identity, input.provenance, input.firstSeenAt),\n ),\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${error.candidate.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${error.candidate.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${error.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${userIds.join(\", \")}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * The candidate for `userId` and where it came from: this device's own keys\n * (`self`) or the identity endpoint (`observed`). Provenance follows the\n * source, never the account that happens to be active once a lookup returns.\n */\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<{\n readonly identity: ValidatedUserIdentityCandidate;\n readonly source: \"self\" | \"observed\";\n} | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return {\n identity: await validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n }),\n source: \"self\",\n };\n }\n\n const identity = await loadRemoteCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n return identity ? { identity, source: \"observed\" } : null;\n}\n\nasync function loadRemoteCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\n/** The trust store and account a lookup started under must still be active. */\nfunction assertResolutionScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n scope: { readonly execSql: ExecSql; readonly localUserId: string | null },\n message: string,\n): void {\n if (\n dependencies.getExecSql() !== scope.execSql ||\n dependencies.getLocalUserId() !== scope.localUserId\n ) {\n throw new DatabaseUnavailableError(message);\n }\n}\n\nasync function pinIdentity(input: {\n /** Checked inside the pin's write transaction, before it commits. */\n readonly assertCurrent?: (() => void) | undefined;\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identities: [input.identity],\n provenance: input.provenance,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/** The user this trust store already binds to a signing key, if any. */\nasync function boundUserId(\n dependencies: TrustedUserIdentityServiceDependencies,\n signingKeyFingerprint: string,\n): Promise<string | null> {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return new TrustedUserIdentityPinRepository(\n execSql,\n ).loadTrustedUserIdForSigningKey({\n identityTrustDomain,\n signingKeyFingerprint,\n });\n}\n\n/** Compares an independently received link before pinning it as `link`. */\nasync function verifyIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n link: string,\n): Promise<TrustedUserIdentity> {\n const expectation = parseIdentityLink(link);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (expectation.identityTrustDomain !== identityTrustDomain) {\n throw new Error(\n \"This identity link belongs to a different Tearleads service.\",\n );\n }\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n expectation.userId,\n identityTrustDomain,\n );\n if (!candidate)\n throw new Error(\"The identity in this link is unavailable.\");\n await assertIdentityLinkMatches(expectation, candidate.identity);\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed. Open the identity link again.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source === \"self\" ? \"self\" : \"link\",\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(expectation.userId);\n throw error;\n }\n}\n\nfunction admissionScopeChanged(): DatabaseUnavailableError {\n return new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n}\n\n/** Reads that admit a user: only `self` and `link` pins qualify. */\nfunction verifiedPinReaders(\n dependencies: TrustedUserIdentityServiceDependencies,\n): Pick<\n TrustedUserIdentityService,\n \"loadAdmissionPin\" | \"resolveVerified\" | \"requireVerified\"\n> {\n const resolveVerified = async (userId: string) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin && pin.provenance !== \"observed\" ? pin.identity : null;\n };\n // The pin in the trust store of the database the admission captured.\n const loadAdmittingPin = async (\n userId: string,\n admittingExecSql: ExecSql | null,\n ) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (execSql !== admittingExecSql) throw admissionScopeChanged();\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin;\n };\n return {\n resolveVerified,\n async requireVerified(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n if (!pin || pin.provenance === \"observed\") {\n throw new UnverifiedUserIdentityError(userId);\n }\n return pin.identity;\n },\n async loadAdmissionPin(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n return pin\n ? { identity: pin.identity, verified: pin.provenance !== \"observed\" }\n : null;\n },\n };\n}\n\n/** This user's own link, derived exclusively from this device's local keys. */\nasync function createLocalIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n appUrl: string,\n): Promise<string> {\n const identityTrustDomain = requireTrustDomain(dependencies);\n const userId = dependencies.getLocalUserId();\n const candidate = userId ? dependencies.getLocalIdentity(userId) : null;\n if (!userId || !candidate) {\n throw new Error(\"Sign in before sharing your identity link.\");\n }\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return createIdentityLink(identity, appUrl);\n}\n\nexport function createTrustedUserIdentityService(\n input: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n const { dependencies, handoff } = withStagedIdentityHandoff(input);\n const verifiedReaders = verifiedPinReaders(dependencies);\n return {\n async resolvePinned(userId) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });\n },\n ...verifiedReaders,\n createLink: (appUrl) => createLocalIdentityLink(dependencies, appUrl),\n async createLinkFor(userId, appUrl) {\n if (\n userId === dependencies.getLocalUserId() &&\n dependencies.getLocalIdentity(userId)\n ) {\n return createLocalIdentityLink(dependencies, appUrl);\n }\n // Only a `link` or `self` pin: re-sharing an observed (TOFU) key as a\n // link would let its recipient pin an unverified key as `link`.\n const identity = await verifiedReaders.resolveVerified(userId);\n return identity ? createIdentityLink(identity, appUrl) : null;\n },\n verifyLink: (link) => verifyIdentityLink(dependencies, link),\n boundUserId: (signingKeyFingerprint) =>\n boundUserId(dependencies, signingKeyFingerprint),\n async pinLocal(userId, candidate) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({\n dependencies,\n execSql,\n identity,\n provenance: \"self\",\n });\n },\n resolve: withPinnedIdentityResolution(\n dependencies,\n async (userId) => {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } =\n requireTrustStore(dependencies);\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!candidate) {\n return null;\n }\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed while resolving this user.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source,\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n {\n loadCandidate: (userId, identityTrustDomain) =>\n loadRemoteCandidate(dependencies, userId, identityTrustDomain),\n pinObserved: (execSql, identities, assertCurrent) =>\n compareWithDurablePins({\n assertCurrent,\n execSql,\n firstSeenAt: (dependencies.now?.() ?? new Date()).toISOString(),\n identities,\n provenance: \"observed\",\n }),\n },\n handoff,\n ),\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
|
|
2
|
-
import {
|
|
2
|
+
import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
|
|
3
3
|
import { principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../../data/principals/organizationAuthorityDescriptor.js";
|
|
4
4
|
import { principalPolicyReferenceFromBundle } from "../../../data/principals/principalPolicyAdminSigners.js";
|
|
5
5
|
import { verifyDirectoryGroup } from "../groupNames/groupNameUniqueness.js";
|
|
@@ -9,7 +9,7 @@ import { assertMetadataRootBinding } from "./groupMetadataRootBinding.js";
|
|
|
9
9
|
export function createGroupMetadataContainerVerifier(input) {
|
|
10
10
|
return async (state) => {
|
|
11
11
|
assertProjectionVerificationCurrent(input.stillCurrent);
|
|
12
|
-
const cached = await
|
|
12
|
+
const cached = await new PrincipalPolicyBundleRepository(input.execSql).loadPrincipalPolicyBundle("organization", input.organizationId);
|
|
13
13
|
let authority = await loadGroupNameDirectoryAuthority({
|
|
14
14
|
...input,
|
|
15
15
|
organizationPolicyReference: cached
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupMetadataContainerAuthority.js","sourceRoot":"","sources":["groupMetadataContainerAuthority.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"groupMetadataContainerAuthority.js","sourceRoot":"","sources":["groupMetadataContainerAuthority.ts"],"names":[],"m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,CAAC,CAAC;QACpE,MAAM,UAAU,GAAG,4BAA4B,CAC7C,SAAS,CAAC,UAAU,EACpB,SAAS,CAAC,aAAa,CACxB,CAAC;QACF,MAAM,OAAO,GAAG,MAAM,oBAAoB,CACxC;YACE,GAAG,KAAK;YACR,UAAU,EAAE,SAAS,CAAC,UAAU;YAChC,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;SAC/C,EACD,UAAU,CACX,CAAC;QACF,yBAAyB,CAAC;YACxB,SAAS;YACT,OAAO;YACP,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,KAAK;SACN,CAAC,CAAC;QACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAC1D,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerAccessManifestState } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport { verifyDirectoryGroup } from \"../groupNames/groupNameUniqueness\";\nimport { loadGroupNameDirectoryAuthority } from \"../groupNames/organizationGroupNamePolicies\";\nimport { assertMetadataRootBinding } from \"./groupMetadataRootBinding\";\n\ntype Input = Omit<\n Parameters<typeof loadGroupNameDirectoryAuthority>[0],\n \"organizationPolicyReference\"\n> & { readonly reportSecurityIncident: SecurityIncidentReporter };\n\n/** A public system slot alone cannot bind a self-authorized root to an organization. */\nexport function createGroupMetadataContainerVerifier(input: Input) {\n return async (state: ContainerAccessManifestState): Promise<void> => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const cached = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n let authority = await loadGroupNameDirectoryAuthority({\n ...input,\n organizationPolicyReference: cached\n ? principalPolicyReferenceFromBundle(cached)\n : null,\n });\n if (\n cached &&\n authority &&\n state.referencedPrincipalHeads.some(\n (head) =>\n !authority?.descriptor.groupHeads.some((known) =>\n principalHeadMatchesReference(head, known),\n ),\n )\n ) {\n authority = await loadGroupNameDirectoryAuthority(input);\n }\n if (!authority)\n throw new Error(\"Organization metadata authority is unavailable\");\n const memberHead = requireOrganizationGroupHead(\n authority.descriptor,\n authority.memberGroupId,\n );\n const members = await verifyDirectoryGroup(\n {\n ...input,\n descriptor: authority.descriptor,\n externalAuthority: authority.externalAuthority,\n },\n memberHead,\n );\n assertMetadataRootBinding({\n authority,\n members,\n organizationId: input.organizationId,\n state,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n };\n}\n"]}
|