@tearleads/client-sdk 0.1.11 → 0.1.14
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 +50 -9
- 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 +4 -1
- package/sqlite/sqlite3-licenses.md +38 -0
- package/sqlite/sqlite3.wasm +0 -0
- package/sqlite/worker.js +4 -0
- 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAE9F,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GAGjC,MAAM,6BAA6B,CAAC;AAcrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AA2DzE,MAAM,UAAU,aAAa,CAC3B,YAAyC;IAEzC,MAAM,0BAA0B,GAAG,gCAAgC,CAAC;QAClE,UAAU,EAAE,GAAG,EAAE,CACf,YAAY,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO;YACtC,CAAC,CAAC,YAAY,CAAC,QAAQ,CAAC,cAAc,CAAC,uBAAuB,CAAC;YAC/D,CAAC,CAAC,IAAI;QACV,gBAAgB,EAAE,GAAG,EAAE;YACrB,MAAM,oBAAoB,GAAG,YAAY,CAAC,QAAQ,CAAC,oBAAoB,CAAC;YACxE,MAAM,cAAc,GAAG,YAAY,CAAC,QAAQ,CAAC,cAAc,CAAC;YAC5D,IAAI,CAAC,oBAAoB,IAAI,CAAC,cAAc,EAAE,CAAC;gBAC7C,OAAO,IAAI,CAAC;YACd,CAAC;YACD,OAAO;gBACL,sBAAsB,EAAE,oBAAoB,CAAC,SAAS;gBACtD,qBAAqB,EAAE,YAAY,CAAC,QAAQ,CAAC,kBAAkB;gBAC/D,gBAAgB,EAAE,cAAc,CAAC,gBAAgB;aA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IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../data/documents/documentKinds\";\nimport type { DomainScope } from \"../data/domainScope\";\nimport { runWithSecurityIncidentReporting } from \"../data/keyingProjectionVerification/error\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { unavailableExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n type TrustedUserIdentityResolver,\n} from \"../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../workflows/container-contents/runtime\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../workflows/runtimeInput\";\nimport type { Blobs } from \"./blobs\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Identity } from \"./identity\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { acknowledgedSessionRoot } from \"./session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"./session/sessionTypes\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: ApiClient;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport interface InternalRuntime {\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null,\n getLocalIdentity: () => {\n const encapsulationKeyPair = dependencies.identity.encapsulationKeyPair;\n const signingKeyPair = dependencies.identity.signingKeyPair;\n if (!encapsulationKeyPair || !signingKeyPair) {\n return null;\n }\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: dependencies.identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n },\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n );\n\n return {\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n dependencies.database.subscribe(notifyListeners);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyListeners);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n }\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken ||\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: dependencies.api,\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAG9F,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GAGjC,MAAM,6BAA6B,CAAC;AAcrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAgEzE,MAAM,UAAU,aAAa,CAC3B,YAAyC;IAEzC,MAAM,0BAA0B,GAAG,gCAAgC,CAAC;QAClE,UAAU,EAAE,GAAG,EAAE,CACf,YAAY,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO;YACtC,CAAC,CAAC,YAAY,CAAC,QAAQ,CAAC,cAAc,CAAC,uBAAuB,CAAC;YAC/D,CAAC,CAAC,IAAI;QACV,gBAAgB,EAAE,GAAG,EAAE;YACrB,MAAM,oBAAoB,GAAG,YAAY,CAAC,QAAQ,CAAC,oBAAoB,CAAC;YACxE,MAAM,cAAc,GAAG,YAAY,CAAC,QAAQ,CAAC,cAAc,CAAC;YAC5D,IAAI,CAAC,oBAAoB,IAAI,CAAC,cAAc,EAAE,CAAC;gBAC7C,OAAO,IAAI,CAAC;YACd,CAAC;YACD,OAAO;gBACL,sBAAsB,EAAE,oBAAoB,CAAC,SAAS;gBACtD,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d,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../data/documents/documentKinds\";\nimport type { DomainScope } from \"../data/domainScope\";\nimport { runWithSecurityIncidentReporting } from \"../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../data/principals/principalHistoryProtection\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { unavailableExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n type TrustedUserIdentityResolver,\n} from \"../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../workflows/container-contents/runtime\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../workflows/runtimeInput\";\nimport type { Blobs } from \"./blobs\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Identity } from \"./identity\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { acknowledgedSessionRoot } from \"./session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"./session/sessionTypes\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: ApiClient;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null,\n getLocalIdentity: () => {\n const encapsulationKeyPair = dependencies.identity.encapsulationKeyPair;\n const signingKeyPair = dependencies.identity.signingKeyPair;\n if (!encapsulationKeyPair || !signingKeyPair) {\n return null;\n }\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: dependencies.identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n },\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n );\n\n return {\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken ||\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: dependencies.api,\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type AnyVerifiedPrincipalPolicy } from "../../../internal/crypto/index.js";
|
|
2
1
|
import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
|
|
2
|
+
import type { PrincipalPolicyCheckpointEvidence } from "../../principals/principalPolicyEvidence.js";
|
|
3
3
|
import type { ContainerMutationAuthor } from "./types.js";
|
|
4
4
|
export declare class ContainerAuthorAccessError extends Error {
|
|
5
5
|
readonly code = "unauthorized";
|
|
@@ -10,6 +10,6 @@ export declare class ContainerAuthorAccessError extends Error {
|
|
|
10
10
|
export declare function assertContainerAuthorAccess(input: {
|
|
11
11
|
author: ContainerMutationAuthor;
|
|
12
12
|
minimumAccess: "write" | "admin";
|
|
13
|
-
principalPolicies: readonly
|
|
13
|
+
principalPolicies: readonly PrincipalPolicyCheckpointEvidence[];
|
|
14
14
|
projection: ContainerWriterProjectionResponse;
|
|
15
15
|
}): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authorAccess.js","sourceRoot":"","sources":["authorAccess.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"authorAccess.js","sourceRoot":"","sources":["authorAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAGlD,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IAC1C,IAAI,GAAG,cAAc,CAAC;IACtB,MAAM,GAAG,GAAG,CAAC;IAEtB,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAC;IAC3C,CAAC;CACF;AAED,mFAAmF;AACnF,MAAM,UAAU,2BAA2B,CAAC,KAK3C;IACC,MAAM,MAAM,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IAC7D,IACE,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,cAAc,KAAK,KAAK,CAAC,MAAM,CAAC,cAAc,CAAC;QAE5E,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;IACJ,MAAM,MAAM,GAAG,wCAAwC,CAAC;QACtD,MAAM;QACN,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,YAAY;KAClC,CAAC,CAAC;IACH,IACE,MAAM,KAAK,OAAO;QAClB,CAAC,CAAC,KAAK,CAAC,aAAa,KAAK,OAAO,IAAI,MAAM,KAAK,OAAO,CAAC;QAExD,MAAM,IAAI,0BAA0B,CAClC,0BAA0B,KAAK,CAAC,aAAa,8BAA8B,CAC5E,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n resolveContainerStatePathUserAccessLevel,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { readContainerState } from \"./projection\";\nimport type { ContainerMutationAuthor } from \"./types\";\n\nexport class ContainerAuthorAccessError extends Error {\n readonly code = \"unauthorized\";\n readonly status = 403;\n\n constructor(message: string) {\n super(message);\n this.name = \"ContainerAuthorAccessError\";\n }\n}\n\n/** Call after verifying the path; readable keys alone do not authorize signing. */\nexport function assertContainerAuthorAccess(input: {\n author: ContainerMutationAuthor;\n minimumAccess: \"write\" | \"admin\";\n principalPolicies: readonly PrincipalPolicyCheckpointEvidence[];\n projection: ContainerWriterProjectionResponse;\n}): void {\n const states = input.projection.path.map(readContainerState);\n if (\n states.some((state) => state.organizationId !== input.author.organizationId)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Container author organization differs from the verified path\",\n );\n const access = resolveContainerStatePathUserAccessLevel({\n states,\n principalPolicies: input.principalPolicies,\n userId: input.author.signerUserId,\n });\n if (\n access !== \"admin\" &&\n !(input.minimumAccess === \"write\" && access === \"write\")\n )\n throw new ContainerAuthorAccessError(\n `Container signer lacks ${input.minimumAccess} access on the verified path`,\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"heldContainerHeads.js","sourceRoot":"","sources":["heldContainerHeads.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAgB,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAmB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OAAO,EAAE,KAAK,IAAI,EAAE,CAAC;QACnB,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,MAAM,IAAI,yBAAyB;YAAE,OAAO,IAAI,CAAC;QAC1E,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACb,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAC3B,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnB,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC;IACpC,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n AnyVerifiedPrincipalPolicy,\n ContainerAccessManifestState,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWire } from \"@tearleads/validators/request\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { readCanonicalRecord } from \"../../keyingCanonicalJson\";\nimport { type ExecSql, resolveCanonicalExecSql } from \"../../sqlite/sqlSchema\";\nimport type { AuthoredContainerMutationHead } from \"./mutationAcknowledgement\";\n\nexport interface HeldContainerHead {\n readonly bundle: AccessManifestBundleWire;\n readonly state: ContainerAccessManifestState;\n}\n\ninterface HeldContainers {\n readonly heads: Map<string, HeldContainerHead>;\n readonly policies: Map<\n string,\n {\n readonly organizationId: string;\n readonly policy: AnyVerifiedPrincipalPolicy;\n }\n >;\n}\n\n// Opportunistic, process-local evidence, not a persistent cache or freshness\n// oracle. No secret keys are retained. Eviction merely limits cascade coverage.\nconst heldByDatabase = new WeakMap<ExecSql, HeldContainers>();\n// Executor-wide limits: another organization's activity may evict evidence,\n// which only skips optional recitations and never changes durable checkpoints.\nconst MAX_HEADS = 256;\nconst MAX_POLICIES = 512;\n\nfunction heldContainers(execSql: ExecSql): HeldContainers {\n const canonical = resolveCanonicalExecSql(execSql);\n let held = heldByDatabase.get(canonical);\n if (!held) {\n held = { heads: new Map(), policies: new Map() };\n heldByDatabase.set(canonical, held);\n }\n return held;\n}\n\nfunction boundedSet<T>(\n map: Map<string, T>,\n key: string,\n value: T,\n max: number,\n) {\n map.delete(key);\n map.set(key, value);\n if (map.size > max) {\n const oldest = map.keys().next().value;\n if (oldest !== undefined) map.delete(oldest);\n }\n}\n\nfunction rememberHead(\n execSql: ExecSql,\n head: Pick<VerifiedContainerAccessManifest, \"state\" | \"manifestHash\">,\n build: () => HeldContainerHead,\n): void {\n const heads = heldContainers(execSql).heads;\n const previous = heads.get(head.state.containerId);\n if (previous && previous.state.epoch >= head.state.epoch) {\n if (previous.bundle.manifestHash === head.manifestHash) {\n boundedSet(heads, head.state.containerId, previous, MAX_HEADS);\n }\n return;\n }\n boundedSet(\n heads,\n head.state.containerId,\n structuredClone(build()),\n MAX_HEADS,\n );\n}\n\n/** Called only after the complete projection and its durable pins validate. */\nexport function rememberVerifiedContainerHeads(input: {\n readonly organizationId: string;\n readonly execSql: ExecSql;\n readonly heads: readonly VerifiedContainerAccessManifest[];\n readonly policies: readonly AnyVerifiedPrincipalPolicy[];\n}): void {\n for (const policy of input.policies) {\n if (\n policy.principalType === \"organization\" &&\n policy.principalId !== input.organizationId\n ) {\n throw new Error(\"Held principal policy belongs to another organization\");\n }\n }\n // Group signed states contain no organization ID. Their scope is supplied\n // by the already-verified projection/policy caller, not inferred here.\n for (const head of input.heads) {\n if (head.state.organizationId !== input.organizationId) {\n throw new Error(\"Held container head belongs to another organization\");\n }\n }\n for (const head of input.heads) {\n rememberHead(input.execSql, head, () => ({\n state: head.state,\n bundle: {\n event: readCanonicalRecord(head.event, \"Verified container event\"),\n manifest: readCanonicalRecord(\n head.manifest,\n \"Verified container manifest\",\n ),\n manifestHash: head.manifestHash,\n state: readCanonicalRecord(head.state, \"Verified container state\"),\n },\n }));\n }\n const policies = heldContainers(input.execSql).policies;\n for (const policy of input.policies) {\n const key = `${input.organizationId}:${policy.principalType}:${policy.principalId}`;\n const previous = policies.get(key);\n if (previous && previous.policy.version > policy.version) continue;\n if (\n previous?.policy.version === policy.version &&\n previous.policy.stateHash !== policy.stateHash\n )\n continue;\n boundedSet(\n policies,\n key,\n { organizationId: input.organizationId, policy: structuredClone(policy) },\n MAX_POLICIES,\n );\n }\n}\n\n/** Caller must first correlate the exact response and durably acknowledge it. */\nexport function rememberAcknowledgedContainerHead(\n execSql: ExecSql,\n plan: Pick<\n AuthoredContainerMutationHead,\n \"body\" | \"event\" | \"eventHash\" | \"manifest\" | \"manifestHash\" | \"state\"\n >,\n): HeldContainerHead {\n const head: HeldContainerHead = {\n state: plan.state,\n bundle: {\n event: readCanonicalRecord(\n {\n event: plan.event,\n eventHash: plan.eventHash,\n body: plan.body,\n },\n \"Acknowledged container event\",\n ),\n manifest: readCanonicalRecord(\n plan.manifest,\n \"Acknowledged container manifest\",\n ),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord(plan.state, \"Acknowledged container state\"),\n },\n };\n rememberHead(execSql, plan, () => head);\n return head;\n}\n\nexport function heldContainerSnapshot(\n execSql: ExecSql,\n organizationId: string,\n) {\n const held = heldContainers(execSql);\n return {\n heads: new Map(\n [...held.heads]\n .filter(([, head]) => head.state.organizationId === organizationId)\n .map(([id, head]) => [id, structuredClone(head)] as const),\n ),\n policies: [...held.policies.values()]\n .filter((entry) => entry.organizationId === organizationId)\n .map((entry) => structuredClone(entry.policy)),\n };\n}\n\n/** Resolve parent edges only; parentManifestHash is historical keying evidence. */\nexport function heldContainerPath(\n heads: ReadonlyMap<string, HeldContainerHead>,\n containerId: string,\n): HeldContainerHead[] | null {\n const path: HeldContainerHead[] = [];\n const seen = new Set<string>();\n let id: string | null = containerId;\n while (id !== null) {\n if (seen.has(id) || path.length >= MAX_CONTAINER_PATH_LENGTH) return null;\n seen.add(id);\n const head = heads.get(id);\n if (!head) return null;\n path.unshift(head);\n id = head.state.parentContainerId;\n }\n return path;\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AC,KAAK,CAAC,MAAM,CAAC,CAAC;KACjD,CAAC;AACJ,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,iBAAiB,CAC/B,KAA6C,EAC7C,WAAmB;IAEnB,MAAM,IAAI,GAAwB,EAAE,CAAC;IACrC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,IAAI,EAAE,GAAkB,WAAW,CAAC;IACpC,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC;QACnB,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,MAAM,IAAI,yBAAyB;YAAE,OAAO,IAAI,CAAC;QAC1E,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACb,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAC3B,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnB,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC;IACpC,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWire } from \"@tearleads/validators/request\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { readCanonicalRecord } from \"../../keyingCanonicalJson\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { type ExecSql, resolveCanonicalExecSql } from \"../../sqlite/sqlSchema\";\nimport type { AuthoredContainerMutationHead } from \"./mutationAcknowledgement\";\n\nexport interface HeldContainerHead {\n readonly bundle: AccessManifestBundleWire;\n readonly state: ContainerAccessManifestState;\n}\n\ninterface HeldContainers {\n readonly heads: Map<string, HeldContainerHead>;\n readonly policies: Map<\n string,\n {\n readonly organizationId: string;\n readonly policy: PrincipalPolicyCheckpointEvidence;\n }\n >;\n}\n\n// Opportunistic, process-local evidence, not a persistent cache or freshness\n// oracle. No secret keys are retained. Eviction merely limits cascade coverage.\nconst heldByDatabase = new WeakMap<ExecSql, HeldContainers>();\n// Executor-wide limits: another organization's activity may evict evidence,\n// which only skips optional recitations and never changes durable checkpoints.\nconst MAX_HEADS = 256;\nconst MAX_POLICIES = 512;\n\nfunction heldContainers(execSql: ExecSql): HeldContainers {\n const canonical = resolveCanonicalExecSql(execSql);\n let held = heldByDatabase.get(canonical);\n if (!held) {\n held = { heads: new Map(), policies: new Map() };\n heldByDatabase.set(canonical, held);\n }\n return held;\n}\n\nfunction boundedSet<T>(\n map: Map<string, T>,\n key: string,\n value: T,\n max: number,\n) {\n map.delete(key);\n map.set(key, value);\n if (map.size > max) {\n const oldest = map.keys().next().value;\n if (oldest !== undefined) map.delete(oldest);\n }\n}\n\nfunction rememberHead(\n execSql: ExecSql,\n head: Pick<VerifiedContainerAccessManifest, \"state\" | \"manifestHash\">,\n build: () => HeldContainerHead,\n): void {\n const heads = heldContainers(execSql).heads;\n const previous = heads.get(head.state.containerId);\n if (previous && previous.state.epoch >= head.state.epoch) {\n if (previous.bundle.manifestHash === head.manifestHash) {\n boundedSet(heads, head.state.containerId, previous, MAX_HEADS);\n }\n return;\n }\n boundedSet(\n heads,\n head.state.containerId,\n structuredClone(build()),\n MAX_HEADS,\n );\n}\n\n/** Called only after the complete projection and its durable pins validate. */\nexport function rememberVerifiedContainerHeads(input: {\n readonly organizationId: string;\n readonly execSql: ExecSql;\n readonly heads: readonly VerifiedContainerAccessManifest[];\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n}): void {\n for (const policy of input.policies) {\n if (\n policy.principalType === \"organization\" &&\n policy.principalId !== input.organizationId\n ) {\n throw new Error(\"Held principal policy belongs to another organization\");\n }\n }\n // Group signed states contain no organization ID. Their scope is supplied\n // by the already-verified projection/policy caller, not inferred here.\n for (const head of input.heads) {\n if (head.state.organizationId !== input.organizationId) {\n throw new Error(\"Held container head belongs to another organization\");\n }\n }\n for (const head of input.heads) {\n rememberHead(input.execSql, head, () => ({\n state: head.state,\n bundle: {\n event: readCanonicalRecord(head.event, \"Verified container event\"),\n manifest: readCanonicalRecord(\n head.manifest,\n \"Verified container manifest\",\n ),\n manifestHash: head.manifestHash,\n state: readCanonicalRecord(head.state, \"Verified container state\"),\n },\n }));\n }\n const policies = heldContainers(input.execSql).policies;\n for (const policy of input.policies) {\n const key = `${input.organizationId}:${policy.principalType}:${policy.principalId}`;\n const previous = policies.get(key);\n if (previous && previous.policy.version > policy.version) continue;\n if (\n previous?.policy.version === policy.version &&\n previous.policy.stateHash !== policy.stateHash\n )\n continue;\n boundedSet(\n policies,\n key,\n { organizationId: input.organizationId, policy: structuredClone(policy) },\n MAX_POLICIES,\n );\n }\n}\n\n/** Caller must first correlate the exact response and durably acknowledge it. */\nexport function rememberAcknowledgedContainerHead(\n execSql: ExecSql,\n plan: Pick<\n AuthoredContainerMutationHead,\n \"body\" | \"event\" | \"eventHash\" | \"manifest\" | \"manifestHash\" | \"state\"\n >,\n): HeldContainerHead {\n const head: HeldContainerHead = {\n state: plan.state,\n bundle: {\n event: readCanonicalRecord(\n {\n event: plan.event,\n eventHash: plan.eventHash,\n body: plan.body,\n },\n \"Acknowledged container event\",\n ),\n manifest: readCanonicalRecord(\n plan.manifest,\n \"Acknowledged container manifest\",\n ),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord(plan.state, \"Acknowledged container state\"),\n },\n };\n rememberHead(execSql, plan, () => head);\n return head;\n}\n\nexport function heldContainerSnapshot(\n execSql: ExecSql,\n organizationId: string,\n) {\n const held = heldContainers(execSql);\n return {\n heads: new Map(\n [...held.heads]\n .filter(([, head]) => head.state.organizationId === organizationId)\n .map(([id, head]) => [id, structuredClone(head)] as const),\n ),\n policies: [...held.policies.values()]\n .filter((entry) => entry.organizationId === organizationId)\n .map((entry) => structuredClone(entry.policy)),\n };\n}\n\n/** Resolve parent edges only; parentManifestHash is historical keying evidence. */\nexport function heldContainerPath(\n heads: ReadonlyMap<string, HeldContainerHead>,\n containerId: string,\n): HeldContainerHead[] | null {\n const path: HeldContainerHead[] = [];\n const seen = new Set<string>();\n let id: string | null = containerId;\n while (id !== null) {\n if (seen.has(id) || path.length >= MAX_CONTAINER_PATH_LENGTH) return null;\n seen.add(id);\n const head = heads.get(id);\n if (!head) return null;\n path.unshift(head);\n id = head.state.parentContainerId;\n }\n return path;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"principalPolicies.js","sourceRoot":"","sources":["principalPolicies.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"principalPolicies.js","sourceRoot":"","sources":["principalPolicies.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAMhE,MAAM,UAAU,4BAA4B,CAC1C,MAAyC,EACzC,KAAK,GAAG,4BAA4B;IAEpC,OAAO,mBAAmB,CACxB;QACE,aAAa,EAAE,MAAM,CAAC,aAAa;QACnC,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,KAAK,EAAE;YACL,GAAG,MAAM,CAAC,KAAK;YACf,SAAS,EAAE,MAAM,CAAC,SAAS;SAC5B;QACD,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,UAAU,EAAE,MAAM,CAAC,UAAU;KAC9B,EACD,KAAK,CACN,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CACzB,MAGC;IAED,OAAO;QACL,MAAM,CAAC,aAAa;QACpB,MAAM,CAAC,WAAW;QAClB,MAAM,CAAC,OAAO;QACd,MAAM,CAAC,QAAQ;QACf,MAAM,CAAC,SAAS;KACjB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;AAED,MAAM,UAAU,uBAAuB,CAErC,QAAsB;IACtB,MAAM,aAAa,GAAG,IAAI,GAAG,EAAa,CAAC;IAE3C,KAAK,MAAM,MAAM,IAAI,QAAQ,EAAE,CAAC;QAC9B,aAAa,CAAC,GAAG,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,CAAC;IACxD,CAAC;IAED,OAAO,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC,CAAC;AACrC,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport { readCanonicalRecord } from \"../../keyingCanonicalJson\";\nimport type {\n PrincipalPolicyCheckpointEvidence,\n PrincipalPolicyCurrentEvidence,\n} from \"../../principals/principalPolicyEvidence\";\n\nexport function principalPolicyRequestRecord(\n policy: PrincipalPolicyCheckpointEvidence,\n label = \"Container principal policy\",\n): Record<string, unknown> {\n return readCanonicalRecord(\n {\n principalType: policy.principalType,\n principalId: policy.principalId,\n version: policy.version,\n keyEpoch: policy.keyEpoch,\n stateHash: policy.stateHash,\n state: {\n ...policy.state,\n stateHash: policy.stateHash,\n },\n projection: policy.projection,\n grants: policy.grants,\n checkpoint: policy.checkpoint,\n },\n label,\n );\n}\n\nfunction principalPolicyKey(\n policy: Pick<\n VerifiedPrincipalPolicy,\n \"keyEpoch\" | \"principalId\" | \"principalType\" | \"stateHash\" | \"version\"\n >,\n): string {\n return [\n policy.principalType,\n policy.principalId,\n policy.version,\n policy.keyEpoch,\n policy.stateHash,\n ].join(\":\");\n}\n\nexport function uniquePrincipalPolicies<\n T extends PrincipalPolicyCurrentEvidence,\n>(policies: readonly T[]): T[] {\n const policiesByKey = new Map<string, T>();\n\n for (const policy of policies) {\n policiesByKey.set(principalPolicyKey(policy), policy);\n }\n\n return [...policiesByKey.values()];\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import type { AccessEvent, AccessManifest, ContainerAccessManifestState, ContainerCreateAccessEventBody, ContainerDirectGrant, ContainerGrantAccessEventBody, ContainerGrantPrincipalHead, ContainerKekKeyring, ContainerKekRecipientTarget, ContainerKeyEpoch, ContainerKeyWrap, ContainerMoveAccessEventBody, ContainerRekeyAccessEventBody, ContainerRevokeAccessEventBody, ContainerUserRecipientKey
|
|
1
|
+
import type { AccessEvent, AccessManifest, ContainerAccessManifestState, ContainerCreateAccessEventBody, ContainerDirectGrant, ContainerGrantAccessEventBody, ContainerGrantPrincipalHead, ContainerKekKeyring, ContainerKekRecipientTarget, ContainerKeyEpoch, ContainerKeyWrap, ContainerMoveAccessEventBody, ContainerRekeyAccessEventBody, ContainerRevokeAccessEventBody, ContainerUserRecipientKey } from "../../../internal/crypto/index.js";
|
|
2
2
|
import type { AccessManifestBundleWire, ContainerCreateWithMetadataDocumentRequest, ContainerMutationRequest, ContainerRotationRequest } from "../../../internal/validators/request/index.js";
|
|
3
3
|
import type { ContainerCreateWithMetadataDocumentResponse, ContainerKekResponse, ContainerMutationResponse, ContainerRotationResponse, ContainerWriterProjectionResponse, PrincipalPolicyBundleResponse } from "../../../internal/validators/response/index.js";
|
|
4
|
+
import type { PrincipalPolicyCurrentEvidence } from "../../principals/principalPolicyEvidence.js";
|
|
4
5
|
import type { ExecSql } from "../../sqlite/sqlSchema.js";
|
|
5
6
|
import type { ContainerMutationRequestOptions } from "./mutationRequestOptions.js";
|
|
6
7
|
import type { ContainerReciteApi } from "./reciteApi.js";
|
|
@@ -34,7 +35,7 @@ export interface BuildContainerCreatePlanInput {
|
|
|
34
35
|
metadataDocumentId?: string | undefined;
|
|
35
36
|
systemSlot?: string | null | undefined;
|
|
36
37
|
parentProjection: ContainerWriterProjectionResponse;
|
|
37
|
-
principalPolicies?: readonly
|
|
38
|
+
principalPolicies?: readonly PrincipalPolicyCurrentEvidence[] | undefined;
|
|
38
39
|
signedAt?: string | undefined;
|
|
39
40
|
}
|
|
40
41
|
export interface ContainerCreatePlan {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerAccessManifestState,\n ContainerCreateAccessEventBody,\n ContainerDirectGrant,\n ContainerGrantAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKekKeyring,\n ContainerKekRecipientTarget,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerMoveAccessEventBody,\n ContainerRekeyAccessEventBody,\n ContainerRevokeAccessEventBody,\n ContainerUserRecipientKey,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerCreateWithMetadataDocumentRequest,\n ContainerMutationRequest,\n ContainerRotationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerCreateWithMetadataDocumentResponse,\n ContainerKekResponse,\n ContainerMutationResponse,\n ContainerRotationResponse,\n ContainerWriterProjectionResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { ContainerMutationRequestOptions } from \"./mutationRequestOptions\";\nimport type { ContainerReciteApi } from \"./reciteApi\";\n\nexport interface ContainerMutationAuthor {\n organizationId: string;\n signerDeviceId: string;\n signerKeyFingerprint: string;\n signerPrivateKey: Uint8Array;\n signerUserId: string;\n}\n\nexport interface BuildContainerCreatePlanInput {\n author: ContainerMutationAuthor;\n containerId?: string | undefined;\n containerKey: Uint8Array;\n containerKeyEpochId?: string | undefined;\n eventId?: string | undefined;\n /**\n * Optional group grant to bake into the\n * create manifest, wrapping the new container key to that principal in\n * addition to the normal parent-inheritance wrap. Used to birth a child\n * container that is directly readable by a group — e.g. the org public\n * metadata container granted to the reserved Members group. The principal's\n * verified policy must also be supplied via `principalPolicies` so the server\n * can derive the recipient target.\n */\n managedPrincipalGrant?:\n | {\n accessLevel: ContainerDirectGrant[\"accessLevel\"];\n principalEncapsulationPublicKey: string;\n principalHead: ContainerGrantPrincipalHead;\n }\n | undefined;\n metadataDocumentId?: string | undefined;\n systemSlot?: string | null | undefined;\n parentProjection: ContainerWriterProjectionResponse;\n principalPolicies?: readonly VerifiedPrincipalPolicy[] | undefined;\n signedAt?: string | undefined;\n}\n\nexport interface ContainerCreatePlan {\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyEpochHash: string;\n keyTargetHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n metadataDocumentId: string;\n parentContainerId: string | null;\n parentManifestHash: string | null;\n recipientTargets: ContainerKekRecipientTarget[];\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerCreatePlan {\n containerKey: Uint8Array;\n plan: ContainerCreatePlan;\n}\n\nexport interface ContainerCreatePlanContext\n extends BuildContainerCreatePlanInput {\n containerKeyPublicKey: string;\n containerId: string;\n containerKeyEpochId: string;\n eventId: string;\n metadataDocumentId: string;\n parent: ParentContainerCreateContext;\n signedAt: string;\n}\n\nexport interface ContainerMutationSubmitFailure {\n readonly code?: string | undefined;\n readonly message: string;\n readonly ok: false;\n readonly report: () => void;\n readonly stalePrincipalPolicies?:\n | readonly PrincipalPolicyBundleResponse[]\n | undefined;\n readonly status: number | null;\n}\n\nexport type ContainerMutationSubmitResult<T> =\n | {\n readonly data: T;\n readonly ok: true;\n }\n | ContainerMutationSubmitFailure;\n\nexport interface ContainerCreateApi {\n createContainerResult(\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n createContainerWithMetadataDocumentResult(\n input: ContainerCreateWithMetadataDocumentRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<\n ContainerMutationSubmitResult<ContainerCreateWithMetadataDocumentResponse>\n >;\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n getCurrentPrincipalPolicy(\n principalType: \"group\" | \"organization\",\n principalId: string,\n ): Promise<PrincipalPolicyBundleResponse | null>;\n}\n\nexport interface ContainerShareApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n shareContainer(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationResponse | null>;\n}\n\n/**\n * A status-bearing rotation outcome. A refusal that names\n * `requiredContainerIds` is answerable: sign those descendant rekeys and\n * resubmit with them carried.\n */\nexport type ContainerRotationResult =\n | { readonly ok: true; readonly data: ContainerRotationResponse }\n | {\n readonly ok: false;\n readonly code?: string | undefined;\n /** Surface a failure that was submitted with `reportErrors: false`. */\n readonly report?: (() => void) | undefined;\n readonly requiredContainerIds?: readonly string[] | undefined;\n readonly status: number | null;\n };\n\nexport interface ContainerMoveApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n moveContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n moveContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerRevokeApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n revokeContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n revokeContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface CreateRemoteContainerResult {\n containerKey: Uint8Array;\n containerId: string;\n metadataDocumentId: string;\n plan: ContainerCreatePlan;\n response: ContainerMutationResponse;\n}\n\nexport interface ContainerSharePlan {\n body: ContainerGrantAccessEventBody;\n /** The unchanged epoch's stored keyring, echoed back by the server. */\n previousKeyring?: Record<string, unknown> | null | undefined;\n containerId: string;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n recipientTarget: ContainerKekRecipientTarget;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerSharePlan {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n}\n\nexport interface ContainerRevokePlan {\n body: ContainerRevokeAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRevokePlan {\n containerKey: Uint8Array;\n plan: ContainerRevokePlan;\n}\n\nexport interface ContainerRekeyPlan {\n body: ContainerRekeyAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRekeyPlan {\n containerKey: Uint8Array;\n plan: ContainerRekeyPlan;\n writerProjection: ContainerWriterProjectionResponse;\n}\n\nexport interface ContainerRekeyApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n rekeyContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; see DocumentSyncApi. */\n rekeyContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerMovePlan {\n body: ContainerMoveAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerMovePlan {\n containerKey: Uint8Array;\n plan: ContainerMovePlan;\n}\n\nexport interface BuildMaterializedContainerMovePlanInput {\n author: ContainerMutationAuthor;\n containerKeyEpochId?: string | undefined;\n destinationParentProjection: ContainerWriterProjectionResponse;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\nexport interface ParentContainerCreateContext {\n manifest: ContainerWriterProjectionResponse[\"path\"][number];\n kek: ContainerKekResponse;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerAccessManifestState,\n ContainerCreateAccessEventBody,\n ContainerDirectGrant,\n ContainerGrantAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKekKeyring,\n ContainerKekRecipientTarget,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerMoveAccessEventBody,\n ContainerRekeyAccessEventBody,\n ContainerRevokeAccessEventBody,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerCreateWithMetadataDocumentRequest,\n ContainerMutationRequest,\n ContainerRotationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerCreateWithMetadataDocumentResponse,\n ContainerKekResponse,\n ContainerMutationResponse,\n ContainerRotationResponse,\n ContainerWriterProjectionResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { ContainerMutationRequestOptions } from \"./mutationRequestOptions\";\nimport type { ContainerReciteApi } from \"./reciteApi\";\n\nexport interface ContainerMutationAuthor {\n organizationId: string;\n signerDeviceId: string;\n signerKeyFingerprint: string;\n signerPrivateKey: Uint8Array;\n signerUserId: string;\n}\n\nexport interface BuildContainerCreatePlanInput {\n author: ContainerMutationAuthor;\n containerId?: string | undefined;\n containerKey: Uint8Array;\n containerKeyEpochId?: string | undefined;\n eventId?: string | undefined;\n /**\n * Optional group grant to bake into the\n * create manifest, wrapping the new container key to that principal in\n * addition to the normal parent-inheritance wrap. Used to birth a child\n * container that is directly readable by a group — e.g. the org public\n * metadata container granted to the reserved Members group. The principal's\n * verified policy must also be supplied via `principalPolicies` so the server\n * can derive the recipient target.\n */\n managedPrincipalGrant?:\n | {\n accessLevel: ContainerDirectGrant[\"accessLevel\"];\n principalEncapsulationPublicKey: string;\n principalHead: ContainerGrantPrincipalHead;\n }\n | undefined;\n metadataDocumentId?: string | undefined;\n systemSlot?: string | null | undefined;\n parentProjection: ContainerWriterProjectionResponse;\n principalPolicies?: readonly PrincipalPolicyCurrentEvidence[] | undefined;\n signedAt?: string | undefined;\n}\n\nexport interface ContainerCreatePlan {\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyEpochHash: string;\n keyTargetHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n metadataDocumentId: string;\n parentContainerId: string | null;\n parentManifestHash: string | null;\n recipientTargets: ContainerKekRecipientTarget[];\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerCreatePlan {\n containerKey: Uint8Array;\n plan: ContainerCreatePlan;\n}\n\nexport interface ContainerCreatePlanContext\n extends BuildContainerCreatePlanInput {\n containerKeyPublicKey: string;\n containerId: string;\n containerKeyEpochId: string;\n eventId: string;\n metadataDocumentId: string;\n parent: ParentContainerCreateContext;\n signedAt: string;\n}\n\nexport interface ContainerMutationSubmitFailure {\n readonly code?: string | undefined;\n readonly message: string;\n readonly ok: false;\n readonly report: () => void;\n readonly stalePrincipalPolicies?:\n | readonly PrincipalPolicyBundleResponse[]\n | undefined;\n readonly status: number | null;\n}\n\nexport type ContainerMutationSubmitResult<T> =\n | {\n readonly data: T;\n readonly ok: true;\n }\n | ContainerMutationSubmitFailure;\n\nexport interface ContainerCreateApi {\n createContainerResult(\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n createContainerWithMetadataDocumentResult(\n input: ContainerCreateWithMetadataDocumentRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<\n ContainerMutationSubmitResult<ContainerCreateWithMetadataDocumentResponse>\n >;\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n getCurrentPrincipalPolicy(\n principalType: \"group\" | \"organization\",\n principalId: string,\n ): Promise<PrincipalPolicyBundleResponse | null>;\n}\n\nexport interface ContainerShareApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n shareContainer(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationResponse | null>;\n}\n\n/**\n * A status-bearing rotation outcome. A refusal that names\n * `requiredContainerIds` is answerable: sign those descendant rekeys and\n * resubmit with them carried.\n */\nexport type ContainerRotationResult =\n | { readonly ok: true; readonly data: ContainerRotationResponse }\n | {\n readonly ok: false;\n readonly code?: string | undefined;\n /** Surface a failure that was submitted with `reportErrors: false`. */\n readonly report?: (() => void) | undefined;\n readonly requiredContainerIds?: readonly string[] | undefined;\n readonly status: number | null;\n };\n\nexport interface ContainerMoveApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n moveContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n moveContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerRevokeApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n revokeContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n revokeContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface CreateRemoteContainerResult {\n containerKey: Uint8Array;\n containerId: string;\n metadataDocumentId: string;\n plan: ContainerCreatePlan;\n response: ContainerMutationResponse;\n}\n\nexport interface ContainerSharePlan {\n body: ContainerGrantAccessEventBody;\n /** The unchanged epoch's stored keyring, echoed back by the server. */\n previousKeyring?: Record<string, unknown> | null | undefined;\n containerId: string;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n recipientTarget: ContainerKekRecipientTarget;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerSharePlan {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n}\n\nexport interface ContainerRevokePlan {\n body: ContainerRevokeAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRevokePlan {\n containerKey: Uint8Array;\n plan: ContainerRevokePlan;\n}\n\nexport interface ContainerRekeyPlan {\n body: ContainerRekeyAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRekeyPlan {\n containerKey: Uint8Array;\n plan: ContainerRekeyPlan;\n writerProjection: ContainerWriterProjectionResponse;\n}\n\nexport interface ContainerRekeyApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n rekeyContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; see DocumentSyncApi. */\n rekeyContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerMovePlan {\n body: ContainerMoveAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerMovePlan {\n containerKey: Uint8Array;\n plan: ContainerMovePlan;\n}\n\nexport interface BuildMaterializedContainerMovePlanInput {\n author: ContainerMutationAuthor;\n containerKeyEpochId?: string | undefined;\n destinationParentProjection: ContainerWriterProjectionResponse;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\nexport interface ParentContainerCreateContext {\n manifest: ContainerWriterProjectionResponse[\"path\"][number];\n kek: ContainerKekResponse;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accessManifestCheckpointEnforcement.js","sourceRoot":"","sources":["accessManifestCheckpointEnforcement.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"accessManifestCheckpointEnforcement.js","sourceRoot":"","sources":["accessManifestCheckpointEnforcement.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAEL,kCAAkC,EAClC,mCAAmC,GACpC,MAAM,mDAAmD,CAAC;AAI3D,SAAS,SAAS,CAAC,QAAkD;IACnE,MAAM,EAAE,UAAU,EAAE,cAAc,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC,UAAU,CAAC;IACrE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,iBAAiB,CACxB,SA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,EAAE,EAAE,CAAC,QAAQ,CAAC,YAAY,KAAK,IAAI,CAAC,YAAY,CAAC,CAAC;QACpE,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;IACxC,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,iCAAiC,CAAC,KAMvD;IACC,MAAM,mCAAmC,CAAC;QACxC,MAAM,EAAE,gCAAgC,CAAC,KAAK,CAAC;QAC/C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CAAC,KAQtD;IACC,MAAM,kCAAkC,CAAC;QACvC,MAAM,EAAE,gCAAgC,CAAC,KAAK,CAAC;QAC/C,uBAAuB,EAAE,KAAK,CAAC,uBAAuB;QACtD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeCheckpoint } from \"../persistence/documentPurgeCheckpointPersistence\";\nimport {\n type AccessManifestCheckpointAdvance,\n advanceKeyingCheckpointsAtomically,\n validateKeyingCheckpointsAtomically,\n} from \"../persistence/keyingCheckpointAdvancePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\n\nfunction objectKey(manifest: VerifiedAccessManifestCheckpointEvidence): string {\n const { objectKind, organizationId, objectId } = manifest.checkpoint;\n return JSON.stringify([objectKind, organizationId, objectId]);\n}\n\nfunction manifestsByObject(\n manifests: readonly VerifiedAccessManifestCheckpointEvidence[],\n): Map<string, Map<string, VerifiedAccessManifestCheckpointEvidence>> {\n const byObject = new Map<\n string,\n Map<string, VerifiedAccessManifestCheckpointEvidence>\n >();\n for (const manifest of manifests) {\n const key = objectKey(manifest);\n let byHash = byObject.get(key);\n if (!byHash) {\n byHash = new Map();\n byObject.set(key, byHash);\n }\n byHash.set(manifest.manifestHash, manifest);\n }\n return byObject;\n}\n\nfunction accessManifestCheckpointAdvances(input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): AccessManifestCheckpointAdvance[] {\n const evidenceByObject = manifestsByObject(input.verifiedManifests);\n const headsByObject = manifestsByObject(input.verifiedHeads);\n const advances: AccessManifestCheckpointAdvance[] = [];\n\n for (const [key, headsByHash] of headsByObject) {\n if (headsByHash.size !== 1) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares conflicting access manifest heads for ${key}`,\n );\n }\n const head = headsByHash.values().next().value;\n if (!head) {\n continue;\n }\n const predecessors = [\n ...(evidenceByObject.get(key)?.values() ?? []),\n ].filter((manifest) => manifest.manifestHash !== head.manifestHash);\n advances.push({ head, predecessors });\n }\n\n return advances;\n}\n\nexport async function validateAccessManifestCheckpoints(input: {\n readonly execSql: ExecSql;\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): Promise<void> {\n await validateKeyingCheckpointsAtomically({\n access: accessManifestCheckpointAdvances(input),\n execSql: input.execSql,\n policies: input.policies,\n stillCurrent: input.stillCurrent,\n });\n}\n\nexport async function enforceAccessManifestCheckpoints(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): Promise<void> {\n await advanceKeyingCheckpointsAtomically({\n access: accessManifestCheckpointAdvances(input),\n documentPurgeCheckpoint: input.documentPurgeCheckpoint,\n execSql: input.execSql,\n organizationId: input.organizationId,\n policies: input.policies,\n stillCurrent: input.stillCurrent,\n });\n}\n"]}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { type AccessManifestCheckpoint, type
|
|
1
|
+
import { type AccessManifestCheckpoint, type VerifiedAccessManifestCheckpointEvidence, type VerifiedContainerAccessManifest } from "../../internal/crypto/index.js";
|
|
2
2
|
import type { DocumentPurgeCheckpoint } from "../persistence/documentPurgeCheckpointPersistence.js";
|
|
3
|
+
import type { PrincipalPolicyCheckpointEvidence } from "../principals/principalPolicyEvidence.js";
|
|
3
4
|
import type { ExecSql } from "../sqlite/sqlSchema.js";
|
|
4
5
|
export interface ProjectionCheckpointContext {
|
|
5
6
|
readonly heldContainerHeads: VerifiedContainerAccessManifest[];
|
|
6
7
|
readonly execSql: ExecSql;
|
|
7
8
|
readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;
|
|
8
9
|
organizationId?: string | undefined;
|
|
9
|
-
readonly policies:
|
|
10
|
+
readonly policies: PrincipalPolicyCheckpointEvidence[];
|
|
10
11
|
readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];
|
|
11
12
|
readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];
|
|
12
13
|
}
|
|
@@ -18,7 +19,7 @@ export declare function observeAccessManifestCheckpoints(context: ProjectionChec
|
|
|
18
19
|
readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];
|
|
19
20
|
readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];
|
|
20
21
|
}): void;
|
|
21
|
-
export declare function observePrincipalPolicy(context: ProjectionCheckpointContext, policy:
|
|
22
|
+
export declare function observePrincipalPolicy(context: ProjectionCheckpointContext, policy: PrincipalPolicyCheckpointEvidence, organizationId?: string | undefined): void;
|
|
22
23
|
export declare function commitProjectionCheckpoints(context: ProjectionCheckpointContext, input?: {
|
|
23
24
|
readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;
|
|
24
25
|
readonly execSql?: ExecSql | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,8BAA8B,EAAE,MAAM,yCAAyC,CAAC;AAIzF,OAAO,EACL,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,mCAAmC,EAAE,MAAM,SAAS,CAAC;AAa9D,MAAM,UAAU,iCAAiC,CAAC,KAGjD;IACC,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACxC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,oEAAoE,CACrE,CAAC;IACJ,CAAC;IAED,OAAO;QACL,kBAAkB,EAAE,EAAE;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,gBAAgB,EAAE,IAAI,GAAG,EAAE;QAC3B,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,EAAE;QACZ,aAAa,EAAE,EAAE;QACjB,iBAAiB,EAAE,EAAE;KACtB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,OAAoC,EACpC,KAGC;IAED,OAAO,C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AI,OAAO,CAAC,OAAO;QAC1C,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,YAAY,EAAE,KAAK,EAAE,YAAY;QACjC,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC7C,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;AAC3D,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAoC,EACpC,KAIC;IAED,IAAI,KAAK,CAAC,8BAA8B,KAAK,KAAK,EAAE,CAAC;QACnD,MAAM,6BAA6B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACpD,OAAO;IACT,CAAC;IACD,MAAM,2BAA2B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAClD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO;IAC7C,MAAM,cAAc,GAClB,OAAO,CAAC,cAAc;QACtB,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { rememberVerifiedContainerHeads } from \"../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../persistence/documentPurgeCheckpointPersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { assertProjectionVerificationCurrent } from \"./types\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n stillCurrent: input?.stillCurrent,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n stillCurrent: input?.stillCurrent,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerManifestVerification.js","sourceRoot":"","sources":["containerManifestVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,EACvB,+BAA+B,EAE/B,6BAA6B,GAC9B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EACL,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,gCAAgC,EAEhC,wBAAwB,GACzB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,2BAA2B,EAAE,MAAM,SAAS,CAAC;AACtD,OAAO,EACL,kCAAkC,EAClC,8BAA8B,GAC/B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,kCAAkC,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AAOzE,KAAK,UAAU,oCAAoC,CAAC,KAanD;IACC,MAAM,qBAAqB,GAAG,KAAK,CAAC,wBAAwB,CAAC,MAAM,CACjE,CAAC,SAAS,EAAE,EAAE,CACZ,CAAC,KAAK,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAC3C,+BAA+B,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CACvD,CACJ,CAAC;IACF,IAAI,KAAK,CAAC,4BAA4B,IAAI,qBAAqB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC3E,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,qDAAqD,CACtD,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,4BAA4B;QACpC,OAAO,CAAC,GAAG,KAAK,CAAC,qBAAqB,CAAC,C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ourcesContent":["import {\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n principalPolicyMatchesReference,\n type VerifiedContainerAccessManifest,\n verifyContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport { readCanonicalJson, readCanonicalRecord } from \"../keyingCanonicalJson\";\nimport {\n assertCanonicalEqual,\n verifyAccessEventBundle,\n} from \"./bundleVerification\";\nimport type { ProjectionCheckpointContext } from \"./checkpointContext\";\nimport {\n assertCitedAncestorsDoNotRegress,\n type CitedLineageInput,\n resolveCitedAncestorPath,\n} from \"./containerAncestorCitations\";\nimport { readKeyingVerificationShape } from \"./error\";\nimport {\n loadManifestCheckpointVerification,\n verifyCachedManifestCheckpoint,\n} from \"./manifestCheckpointVerification\";\nimport { collectReferencedPrincipalPolicies } from \"./principalPolicyVerification\";\nimport { readAccessManifest, readRecordNullableString } from \"./readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\n\nasync function collectManifestAuthorizationPolicies(input: {\n readonly authorizationEvidence: readonly AnyVerifiedPrincipalPolicy[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly organizationId: string;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly referencedPrincipalHeads: Parameters<\n typeof principalPolicyMatchesReference\n >[0][\"reference\"][];\n readonly requireAuthorizationEvidence: boolean;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}) {\n const missingPrincipalHeads = input.referencedPrincipalHeads.filter(\n (reference) =>\n !input.authorizationEvidence.some((policy) =>\n principalPolicyMatchesReference({ policy, reference }),\n ),\n );\n if (input.requireAuthorizationEvidence && missingPrincipalHeads.length > 0) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection omits required principal policy evidence\",\n );\n }\n if (input.requireAuthorizationEvidence)\n return [...input.authorizationEvidence];\n return [\n ...input.authorizationEvidence,\n ...(await collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references: missingPrincipalHeads,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n })),\n ];\n}\n\nexport async function verifyContainerManifestBundle(input: {\n readonly authorizationMembership?: \"current\" | \"referenced\" | undefined;\n readonly authorizationEvidence?:\n | readonly AnyVerifiedPrincipalPolicy[]\n | undefined;\n readonly bundle: AccessManifestBundleWireResponse;\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly enforceLocalCheckpoint: boolean;\n readonly label: string;\n readonly parentPath: readonly VerifiedContainerAccessManifest[];\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly requireAuthorizationEvidence?: boolean | undefined;\n readonly verifiedByHash: Map<string, VerifiedContainerAccessManifest>;\n // Manifest hashes whose verification is in progress up the call stack.\n // Previous manifests, pinned parents, and cited ancestors all recurse\n // before a bundle's own hash is checked, so served bundles that refer to\n // each other under claimed hashes would otherwise recurse without end.\n readonly verifying?: Set<string> | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<VerifiedContainerAccessManifest> {\n const parentPath =\n await resolveContainerManifestVerificationParentPath(input);\n const cached = input.verifiedByHash.get(input.bundle.manifestHash);\n if (cached) {\n assertContainerParentPathMatches({\n label: input.label,\n parentPath,\n verifiedManifest: cached,\n });\n if (input.enforceLocalCheckpoint) {\n await verifyCachedManifestCheckpoint({\n current: cached,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: input.verifiedByHash,\n });\n }\n return cached;\n }\n\n const verifying = input.verifying ?? new Set<string>();\n if (verifying.has(input.bundle.manifestHash)) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${input.label} refers back to a manifest whose verification it is part of`,\n );\n }\n verifying.add(input.bundle.manifestHash);\n try {\n return await verifyFreshContainerManifestBundle(\n { ...input, verifying },\n parentPath,\n );\n } finally {\n verifying.delete(input.bundle.manifestHash);\n }\n}\n\ntype CitedAncestorInput = Parameters<typeof verifyContainerManifestBundle>[0];\n\nasync function verifyFreshContainerManifestBundle(\n input: CitedAncestorInput,\n parentPath: readonly VerifiedContainerAccessManifest[],\n): Promise<VerifiedContainerAccessManifest> {\n const event = await verifyAccessEventBundle(input);\n const manifest = readAccessManifest(\n input.bundle.manifest,\n `${input.label} manifest`,\n );\n const authorization = await resolveContainerManifestAuthorization(\n input,\n event,\n parentPath,\n );\n const { citedAncestors, previousManifest, sourceAncestors } = authorization;\n const principalPolicies = await collectManifestAuthorizationPolicies({\n authorizationEvidence: input.authorizationEvidence ?? [],\n checkpointContext: input.checkpointContext,\n organizationId: event.event.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n referencedPrincipalHeads: [\n ...authorization.referencedPrincipalHeads,\n ...manifest.referencedPrincipalHeads,\n ],\n requireAuthorizationEvidence: input.requireAuthorizationEvidence ?? false,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const checkpointVerification = input.enforceLocalCheckpoint\n ? await loadManifestCheckpointVerification({\n current: manifest,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: input.verifiedByHash,\n })\n : null;\n\n const verified = await verifyContainerAccessManifest({\n // Served manifests were committed under their signed policy references.\n // Current membership still gates new writes in the API verifier.\n authorizationMembership: input.authorizationMembership ?? \"referenced\",\n destinationParentContainerPath: citedAncestors,\n event,\n expectedManifestHash: input.bundle.manifestHash,\n manifest,\n parentContainerPath: citedAncestors,\n principalPolicies,\n ...(checkpointVerification ?? {}),\n ...(previousManifest\n ? {\n previousContainerPath: [...sourceAncestors, previousManifest],\n previousManifest,\n }\n : { previousManifest: null }),\n });\n if (!verified.ok) {\n throw new KeyingVerificationError(\n verified.error.code,\n `${input.label} manifest verification failed: ${verified.error.message}`,\n );\n }\n\n assertCanonicalEqual({\n actual: input.bundle.state,\n expected: readCanonicalJson(verified.value.state, `${input.label} state`),\n label: `${input.label} state`,\n });\n input.verifiedByHash.set(input.bundle.manifestHash, verified.value);\n\n return verified.value;\n}\n\n/**\n * The paths a container event is authorized against: its previous manifest\n * and the ancestor heads its signed event cites, root to parent.\n */\nasync function resolveContainerManifestAuthorization(\n input: CitedAncestorInput,\n event: VerifiedContainerAccessManifest[\"event\"],\n parentPath: readonly VerifiedContainerAccessManifest[],\n) {\n const previousManifest =\n event.event.previousManifestHash === null\n ? null\n : await verifyPreviousContainerManifest({\n ...input,\n parentPath,\n previousManifestHash: event.event.previousManifestHash,\n });\n // Resolve the signed placement lineage, never the server-supplied wire state.\n // Rotations also resolve their new epoch's exact signed parent citation via\n // cited-ancestor verification below; that can differ from this previous path.\n const eventType = event.event.eventType;\n const { parentContainerId, parentManifestHash } =\n previousManifest && eventType !== \"container.move\"\n ? previousManifest.state\n : readContainerEventBodyParentReference(event, input.label);\n if (\n previousManifest === null &&\n parentManifestHash !== null &&\n !event.event.dependencyManifestHashes.includes(parentManifestHash)\n ) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} does not cite the parent manifest it was created under`,\n );\n }\n const lineage: CitedLineageInput = {\n bundlesByHash: input.bundlesByHash,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n };\n const citedAncestors = await resolveCitedAncestors(input, event, {\n parentContainerId,\n });\n assertCitedAncestorsDoNotRegress({\n ...lineage,\n citedAncestors,\n previousManifest,\n });\n // A move's source path leads to the previous manifest's parent, and the\n // move event cites that path too; the destination path is the one above.\n // The source path is held to the same no-regression rule.\n const sourceAncestors =\n eventType === \"container.move\" && previousManifest\n ? await resolveCitedAncestors(input, event, {\n parentContainerId: previousManifest.state.parentContainerId,\n })\n : citedAncestors;\n if (sourceAncestors !== citedAncestors) {\n assertCitedAncestorsDoNotRegress({\n ...lineage,\n citedAncestors: sourceAncestors,\n previousManifest,\n });\n }\n const ancestors = [\n ...parentPath,\n ...citedAncestors,\n ...(sourceAncestors === citedAncestors ? [] : sourceAncestors),\n ];\n return {\n citedAncestors,\n previousManifest,\n referencedPrincipalHeads: [\n ...ancestors.flatMap(\n (ancestor) => ancestor.state.referencedPrincipalHeads,\n ),\n ...(previousManifest?.state.referencedPrincipalHeads ?? []),\n ],\n sourceAncestors,\n };\n}\n\nfunction citedAncestorResolutionInput(input: CitedAncestorInput) {\n return {\n bundlesByHash: input.bundlesByHash,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n // A cited head older than the served one is history: authorize it at the\n // membership it referenced, as the previous manifest is.\n verifyHistoryBundle: (\n bundle: AccessManifestBundleWireResponse,\n label: string,\n ) =>\n verifyContainerManifestBundle({\n ...input,\n authorizationMembership: \"referenced\",\n bundle,\n enforceLocalCheckpoint: false,\n label,\n }),\n };\n}\n\nfunction resolveCitedAncestors(\n input: CitedAncestorInput,\n event: VerifiedContainerAccessManifest[\"event\"],\n reference: { readonly parentContainerId: string | null },\n): Promise<VerifiedContainerAccessManifest[]> {\n return resolveCitedAncestorPath({\n ...citedAncestorResolutionInput(input),\n event,\n parentContainerId: reference.parentContainerId,\n });\n}\n\nfunction assertContainerParentPathMatches(input: {\n readonly label: string;\n readonly parentPath: readonly VerifiedContainerAccessManifest[];\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n}): void {\n const actualParentManifestHash =\n input.parentPath.at(-1)?.manifestHash ?? null;\n if (\n actualParentManifestHash !== input.verifiedManifest.state.parentManifestHash\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${input.label} parent path mismatch`,\n );\n }\n}\n\ninterface ContainerParentReference {\n parentContainerId: string | null;\n parentManifestHash: string | null;\n}\n\nfunction readParentReference(\n value: unknown,\n label: string,\n): ContainerParentReference {\n return readKeyingVerificationShape(() => {\n const record = readCanonicalRecord(value, label);\n\n return {\n parentContainerId: readRecordNullableString(\n record,\n \"parentContainerId\",\n label,\n ),\n parentManifestHash: readRecordNullableString(\n record,\n \"parentManifestHash\",\n label,\n ),\n };\n });\n}\n\nfunction readContainerManifestParentReference(\n bundle: AccessManifestBundleWireResponse,\n label: string,\n): ContainerParentReference {\n return readParentReference(bundle.state, `${label} state`);\n}\n\n/** The parent a create or move body pins, read from the signed body. */\nfunction readContainerEventBodyParentReference(\n event: VerifiedContainerAccessManifest[\"event\"],\n label: string,\n): ContainerParentReference {\n return readParentReference(event.body, `${label} event body`);\n}\n\nasync function resolveContainerManifestVerificationParentPath(input: {\n readonly authorizationEvidence?:\n | readonly AnyVerifiedPrincipalPolicy[]\n | undefined;\n readonly bundle: AccessManifestBundleWireResponse;\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly label: string;\n readonly parentPath: readonly VerifiedContainerAccessManifest[];\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedByHash: Map<string, VerifiedContainerAccessManifest>;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<readonly VerifiedContainerAccessManifest[]> {\n // Descendants keep the parent manifest hash they were created or moved under;\n // a later parent share/rekey must not require rewriting descendant manifests.\n const { parentContainerId, parentManifestHash } =\n readContainerManifestParentReference(input.bundle, input.label);\n if (parentContainerId === null || parentManifestHash === null) {\n return [];\n }\n\n const parentPathIndex = input.parentPath.findIndex(\n (manifest) =>\n manifest.state.containerId === parentContainerId &&\n manifest.manifestHash === parentManifestHash,\n );\n if (parentPathIndex >= 0) {\n return input.parentPath.slice(0, parentPathIndex + 1);\n }\n\n const parentBundle = input.bundlesByHash.get(parentManifestHash);\n if (!parentBundle) {\n return input.parentPath;\n }\n\n const parentParentPath = await resolveContainerManifestVerificationParentPath(\n {\n ...input,\n bundle: parentBundle,\n label: `${input.label} parent manifest`,\n },\n );\n const verifiedParent = await verifyContainerManifestBundle({\n ...input,\n bundle: parentBundle,\n enforceLocalCheckpoint: false,\n label: `${input.label} parent manifest`,\n parentPath: parentParentPath,\n });\n if (verifiedParent.state.containerId !== parentContainerId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${input.label} parent manifest container mismatch`,\n );\n }\n\n return [...parentParentPath, verifiedParent];\n}\n\nasync function verifyPreviousContainerManifest(input: {\n readonly authorizationEvidence?:\n | readonly AnyVerifiedPrincipalPolicy[]\n | undefined;\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly label: string;\n readonly parentPath: readonly VerifiedContainerAccessManifest[];\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly previousManifestHash: string;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly requireAuthorizationEvidence?: boolean | undefined;\n readonly verifiedByHash: Map<string, VerifiedContainerAccessManifest>;\n readonly verifying?: Set<string> | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<VerifiedContainerAccessManifest> {\n const previousBundle = input.bundlesByHash.get(input.previousManifestHash);\n if (!previousBundle) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} previous manifest ${input.previousManifestHash} is missing`,\n );\n }\n const parentPath = await resolveContainerManifestVerificationParentPath({\n ...input,\n bundle: previousBundle,\n });\n\n return verifyContainerManifestBundle({\n authorizationMembership: \"referenced\",\n authorizationEvidence: input.authorizationEvidence,\n bundle: previousBundle,\n bundlesByHash: input.bundlesByHash,\n checkpointContext: input.checkpointContext,\n enforceLocalCheckpoint: false,\n label: `${input.label} previous manifest`,\n parentPath,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n requireAuthorizationEvidence: input.requireAuthorizationEvidence,\n verifiedByHash: input.verifiedByHash,\n verifying: input.verifying,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"containerManifestVerification.js","sourceRoot":"","sources":["containerManifestVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,+BAA+B,EAE/B,6BAA6B,GAC9B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAEhF,OAAO,EACL,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,gCAAgC,EAEhC,wBAAwB,GACzB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,2BAA2B,EAAE,MAAM,SAAS,CAAC;AACtD,OAAO,EACL,kCAAkC,EAClC,8BAA8B,GAC/B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,kCAAkC,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AAOzE,KAAK,UAAU,oCAAoC,CAAC,KAanD;IACC,MAAM,qBAAqB,GAAG,KAAK,CAAC,wBAAwB,CAAC,MAAM,CACjE,CAAC,SAAS,EAAE,EAAE,CACZ,CAAC,KAAK,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAC3C,+BAA+B,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CACvD,CACJ,CAAC;IACF,IAAI,KAAK,CAAC,4BAA4B,IAAI,qBAAqB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC3E,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,qDAAqD,CACtD,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,4BAA4B;QACpC,OAAO,CAAC,GAAG,KAAK,CAAC,qBA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AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n principalPolicyMatchesReference,\n type VerifiedContainerAccessManifest,\n verifyContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport { readCanonicalJson, readCanonicalRecord } from \"../keyingCanonicalJson\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport {\n assertCanonicalEqual,\n verifyAccessEventBundle,\n} from \"./bundleVerification\";\nimport type { ProjectionCheckpointContext } from \"./checkpointContext\";\nimport {\n assertCitedAncestorsDoNotRegress,\n type CitedLineageInput,\n resolveCitedAncestorPath,\n} from \"./containerAncestorCitations\";\nimport { readKeyingVerificationShape } from \"./error\";\nimport {\n loadManifestCheckpointVerification,\n verifyCachedManifestCheckpoint,\n} from \"./manifestCheckpointVerification\";\nimport { collectReferencedPrincipalPolicies } from \"./principalPolicyVerification\";\nimport { readAccessManifest, readRecordNullableString } from \"./readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\n\nasync function collectManifestAuthorizationPolicies(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyCheckpointEvidence[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly organizationId: string;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly referencedPrincipalHeads: Parameters<\n typeof principalPolicyMatchesReference\n >[0][\"reference\"][];\n readonly requireAuthorizationEvidence: boolean;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}) {\n const missingPrincipalHeads = input.referencedPrincipalHeads.filter(\n (reference) =>\n !input.authorizationEvidence.some((policy) =>\n principalPolicyMatchesReference({ policy, reference }),\n ),\n );\n if (input.requireAuthorizationEvidence && missingPrincipalHeads.length > 0) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection omits required principal policy evidence\",\n );\n }\n if (input.requireAuthorizationEvidence)\n return [...input.authorizationEvidence];\n return [\n ...input.authorizationEvidence,\n ...(await collectReferencedPrincipalPolicies({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n references: missingPrincipalHeads,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n })),\n ];\n}\n\nexport async function verifyContainerManifestBundle(input: {\n readonly authorizationMembership?: \"current\" | \"referenced\" | undefined;\n readonly authorizationEvidence?:\n | readonly PrincipalPolicyCheckpointEvidence[]\n | undefined;\n readonly bundle: AccessManifestBundleWireResponse;\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly enforceLocalCheckpoint: boolean;\n readonly label: string;\n readonly parentPath: readonly VerifiedContainerAccessManifest[];\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly requireAuthorizationEvidence?: boolean | undefined;\n readonly verifiedByHash: Map<string, VerifiedContainerAccessManifest>;\n // Manifest hashes whose verification is in progress up the call stack.\n // Previous manifests, pinned parents, and cited ancestors all recurse\n // before a bundle's own hash is checked, so served bundles that refer to\n // each other under claimed hashes would otherwise recurse without end.\n readonly verifying?: Set<string> | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<VerifiedContainerAccessManifest> {\n const parentPath =\n await resolveContainerManifestVerificationParentPath(input);\n const cached = input.verifiedByHash.get(input.bundle.manifestHash);\n if (cached) {\n assertContainerParentPathMatches({\n label: input.label,\n parentPath,\n verifiedManifest: cached,\n });\n if (input.enforceLocalCheckpoint) {\n await verifyCachedManifestCheckpoint({\n current: cached,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: input.verifiedByHash,\n });\n }\n return cached;\n }\n\n const verifying = input.verifying ?? new Set<string>();\n if (verifying.has(input.bundle.manifestHash)) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${input.label} refers back to a manifest whose verification it is part of`,\n );\n }\n verifying.add(input.bundle.manifestHash);\n try {\n return await verifyFreshContainerManifestBundle(\n { ...input, verifying },\n parentPath,\n );\n } finally {\n verifying.delete(input.bundle.manifestHash);\n }\n}\n\ntype CitedAncestorInput = Parameters<typeof verifyContainerManifestBundle>[0];\n\nasync function verifyFreshContainerManifestBundle(\n input: CitedAncestorInput,\n parentPath: readonly VerifiedContainerAccessManifest[],\n): Promise<VerifiedContainerAccessManifest> {\n const event = await verifyAccessEventBundle(input);\n const manifest = readAccessManifest(\n input.bundle.manifest,\n `${input.label} manifest`,\n );\n const authorization = await resolveContainerManifestAuthorization(\n input,\n event,\n parentPath,\n );\n const { citedAncestors, previousManifest, sourceAncestors } = authorization;\n const principalPolicies = await collectManifestAuthorizationPolicies({\n authorizationEvidence: input.authorizationEvidence ?? [],\n checkpointContext: input.checkpointContext,\n organizationId: event.event.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n referencedPrincipalHeads: [\n ...authorization.referencedPrincipalHeads,\n ...manifest.referencedPrincipalHeads,\n ],\n requireAuthorizationEvidence: input.requireAuthorizationEvidence ?? false,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const checkpointVerification = input.enforceLocalCheckpoint\n ? await loadManifestCheckpointVerification({\n current: manifest,\n execSql: input.checkpointContext.execSql,\n localCheckpoints: input.checkpointContext.localCheckpoints,\n verifiedManifests: input.verifiedByHash,\n })\n : null;\n\n const verified = await verifyContainerAccessManifest({\n // Served manifests were committed under their signed policy references.\n // Current membership still gates new writes in the API verifier.\n authorizationMembership: input.authorizationMembership ?? \"referenced\",\n destinationParentContainerPath: citedAncestors,\n event,\n expectedManifestHash: input.bundle.manifestHash,\n manifest,\n parentContainerPath: citedAncestors,\n principalPolicies,\n ...(checkpointVerification ?? {}),\n ...(previousManifest\n ? {\n previousContainerPath: [...sourceAncestors, previousManifest],\n previousManifest,\n }\n : { previousManifest: null }),\n });\n if (!verified.ok) {\n throw new KeyingVerificationError(\n verified.error.code,\n `${input.label} manifest verification failed: ${verified.error.message}`,\n );\n }\n\n assertCanonicalEqual({\n actual: input.bundle.state,\n expected: readCanonicalJson(verified.value.state, `${input.label} state`),\n label: `${input.label} state`,\n });\n input.verifiedByHash.set(input.bundle.manifestHash, verified.value);\n\n return verified.value;\n}\n\n/**\n * The paths a container event is authorized against: its previous manifest\n * and the ancestor heads its signed event cites, root to parent.\n */\nasync function resolveContainerManifestAuthorization(\n input: CitedAncestorInput,\n event: VerifiedContainerAccessManifest[\"event\"],\n parentPath: readonly VerifiedContainerAccessManifest[],\n) {\n const previousManifest =\n event.event.previousManifestHash === null\n ? null\n : await verifyPreviousContainerManifest({\n ...input,\n parentPath,\n previousManifestHash: event.event.previousManifestHash,\n });\n // Resolve the signed placement lineage, never the server-supplied wire state.\n // Rotations also resolve their new epoch's exact signed parent citation via\n // cited-ancestor verification below; that can differ from this previous path.\n const eventType = event.event.eventType;\n const { parentContainerId, parentManifestHash } =\n previousManifest && eventType !== \"container.move\"\n ? previousManifest.state\n : readContainerEventBodyParentReference(event, input.label);\n if (\n previousManifest === null &&\n parentManifestHash !== null &&\n !event.event.dependencyManifestHashes.includes(parentManifestHash)\n ) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} does not cite the parent manifest it was created under`,\n );\n }\n const lineage: CitedLineageInput = {\n bundlesByHash: input.bundlesByHash,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n };\n const citedAncestors = await resolveCitedAncestors(input, event, {\n parentContainerId,\n });\n assertCitedAncestorsDoNotRegress({\n ...lineage,\n citedAncestors,\n previousManifest,\n });\n // A move's source path leads to the previous manifest's parent, and the\n // move event cites that path too; the destination path is the one above.\n // The source path is held to the same no-regression rule.\n const sourceAncestors =\n eventType === \"container.move\" && previousManifest\n ? await resolveCitedAncestors(input, event, {\n parentContainerId: previousManifest.state.parentContainerId,\n })\n : citedAncestors;\n if (sourceAncestors !== citedAncestors) {\n assertCitedAncestorsDoNotRegress({\n ...lineage,\n citedAncestors: sourceAncestors,\n previousManifest,\n });\n }\n const ancestors = [\n ...parentPath,\n ...citedAncestors,\n ...(sourceAncestors === citedAncestors ? [] : sourceAncestors),\n ];\n return {\n citedAncestors,\n previousManifest,\n referencedPrincipalHeads: [\n ...ancestors.flatMap(\n (ancestor) => ancestor.state.referencedPrincipalHeads,\n ),\n ...(previousManifest?.state.referencedPrincipalHeads ?? []),\n ],\n sourceAncestors,\n };\n}\n\nfunction citedAncestorResolutionInput(input: CitedAncestorInput) {\n return {\n bundlesByHash: input.bundlesByHash,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n // A cited head older than the served one is history: authorize it at the\n // membership it referenced, as the previous manifest is.\n verifyHistoryBundle: (\n bundle: AccessManifestBundleWireResponse,\n label: string,\n ) =>\n verifyContainerManifestBundle({\n ...input,\n authorizationMembership: \"referenced\",\n bundle,\n enforceLocalCheckpoint: false,\n label,\n }),\n };\n}\n\nfunction resolveCitedAncestors(\n input: CitedAncestorInput,\n event: VerifiedContainerAccessManifest[\"event\"],\n reference: { readonly parentContainerId: string | null },\n): Promise<VerifiedContainerAccessManifest[]> {\n return resolveCitedAncestorPath({\n ...citedAncestorResolutionInput(input),\n event,\n parentContainerId: reference.parentContainerId,\n });\n}\n\nfunction assertContainerParentPathMatches(input: {\n readonly label: string;\n readonly parentPath: readonly VerifiedContainerAccessManifest[];\n readonly verifiedManifest: VerifiedContainerAccessManifest;\n}): void {\n const actualParentManifestHash =\n input.parentPath.at(-1)?.manifestHash ?? null;\n if (\n actualParentManifestHash !== input.verifiedManifest.state.parentManifestHash\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${input.label} parent path mismatch`,\n );\n }\n}\n\ninterface ContainerParentReference {\n parentContainerId: string | null;\n parentManifestHash: string | null;\n}\n\nfunction readParentReference(\n value: unknown,\n label: string,\n): ContainerParentReference {\n return readKeyingVerificationShape(() => {\n const record = readCanonicalRecord(value, label);\n\n return {\n parentContainerId: readRecordNullableString(\n record,\n \"parentContainerId\",\n label,\n ),\n parentManifestHash: readRecordNullableString(\n record,\n \"parentManifestHash\",\n label,\n ),\n };\n });\n}\n\nfunction readContainerManifestParentReference(\n bundle: AccessManifestBundleWireResponse,\n label: string,\n): ContainerParentReference {\n return readParentReference(bundle.state, `${label} state`);\n}\n\n/** The parent a create or move body pins, read from the signed body. */\nfunction readContainerEventBodyParentReference(\n event: VerifiedContainerAccessManifest[\"event\"],\n label: string,\n): ContainerParentReference {\n return readParentReference(event.body, `${label} event body`);\n}\n\nasync function resolveContainerManifestVerificationParentPath(input: {\n readonly authorizationEvidence?:\n | readonly PrincipalPolicyCheckpointEvidence[]\n | undefined;\n readonly bundle: AccessManifestBundleWireResponse;\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly label: string;\n readonly parentPath: readonly VerifiedContainerAccessManifest[];\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedByHash: Map<string, VerifiedContainerAccessManifest>;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<readonly VerifiedContainerAccessManifest[]> {\n // Descendants keep the parent manifest hash they were created or moved under;\n // a later parent share/rekey must not require rewriting descendant manifests.\n const { parentContainerId, parentManifestHash } =\n readContainerManifestParentReference(input.bundle, input.label);\n if (parentContainerId === null || parentManifestHash === null) {\n return [];\n }\n\n const parentPathIndex = input.parentPath.findIndex(\n (manifest) =>\n manifest.state.containerId === parentContainerId &&\n manifest.manifestHash === parentManifestHash,\n );\n if (parentPathIndex >= 0) {\n return input.parentPath.slice(0, parentPathIndex + 1);\n }\n\n const parentBundle = input.bundlesByHash.get(parentManifestHash);\n if (!parentBundle) {\n return input.parentPath;\n }\n\n const parentParentPath = await resolveContainerManifestVerificationParentPath(\n {\n ...input,\n bundle: parentBundle,\n label: `${input.label} parent manifest`,\n },\n );\n const verifiedParent = await verifyContainerManifestBundle({\n ...input,\n bundle: parentBundle,\n enforceLocalCheckpoint: false,\n label: `${input.label} parent manifest`,\n parentPath: parentParentPath,\n });\n if (verifiedParent.state.containerId !== parentContainerId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${input.label} parent manifest container mismatch`,\n );\n }\n\n return [...parentParentPath, verifiedParent];\n}\n\nasync function verifyPreviousContainerManifest(input: {\n readonly authorizationEvidence?:\n | readonly PrincipalPolicyCheckpointEvidence[]\n | undefined;\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly label: string;\n readonly parentPath: readonly VerifiedContainerAccessManifest[];\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly previousManifestHash: string;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly requireAuthorizationEvidence?: boolean | undefined;\n readonly verifiedByHash: Map<string, VerifiedContainerAccessManifest>;\n readonly verifying?: Set<string> | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<VerifiedContainerAccessManifest> {\n const previousBundle = input.bundlesByHash.get(input.previousManifestHash);\n if (!previousBundle) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} previous manifest ${input.previousManifestHash} is missing`,\n );\n }\n const parentPath = await resolveContainerManifestVerificationParentPath({\n ...input,\n bundle: previousBundle,\n });\n\n return verifyContainerManifestBundle({\n authorizationMembership: \"referenced\",\n authorizationEvidence: input.authorizationEvidence,\n bundle: previousBundle,\n bundlesByHash: input.bundlesByHash,\n checkpointContext: input.checkpointContext,\n enforceLocalCheckpoint: false,\n label: `${input.label} previous manifest`,\n parentPath,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n requireAuthorizationEvidence: input.requireAuthorizationEvidence,\n verifiedByHash: input.verifiedByHash,\n verifying: input.verifying,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerPathVerification.js","sourceRoot":"","sources":["containerPathVerification.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"containerPathVerification.js","sourceRoot":"","sources":["containerPathVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAI3B,OAAO,EAAE,yCAAyC,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,oCAAoC,EAAE,MAAM,8BAA8B,CAAC;AAOpF,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAkBjD;IACC,2EAA2E;IAC3E,wEAAwE;IACxE,MAAM,YAAY,GAAsC,EAAE,CAAC;IAC3D,KAAK,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;QACnD,MAAM,KAAK,GAAG,GAAG,KAAK,CAAC,KAAK,IAAI,KAAK,GAAG,CAAC;QACzC,MAAM,QAAQ,GAAG,MAAM,6BAA6B,CAAC;YACnD,uBAAuB,EAAE,KAAK,CAAC,uBAAuB;YACtD,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;YAClD,MAAM;YACN,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,sBAAsB,EAAE,KAAK,CAAC,uBAAuB;YACrD,KAAK;YACL,UAAU,EAAE,YAAY;YACxB,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;YAChD,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,4BAA4B,EAAE,KAAK,CAAC,4BAA4B;YAChE,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;SACvE,CAAC,CAAC;QACH,wEAAwE;QACxE,0EAA0E;QAC1E,+CAA+C;QAC/C,MAAM,gBAAgB,GAAG,YAAY,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,WAAW,IAAI,IAAI,CAAC;QACxE,IAAI,QAAQ,CAAC,KAAK,CAAC,iBAAiB,KAAK,gBAAgB,EAAE,CAAC;YAC1D,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,GAAG,KAAK,mDAAmD,CAC5D,CAAC;QACJ,CAAC;QACD,IAAI,KAAK,CAAC,eAAe,EAAE,CAAC;YAC1B,yCAAyC,CAAC;gBACxC,IAAI,EAAE,QAAQ;gBACd,KAAK;gBACL,eAAe,EAAE,YAAY;gBAC7B,cAAc,EAAE,KAAK,CAAC,cAAc;aACrC,CAAC,CAAC;QACL,CAAC;QACD,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC;IAED,MAAM,oCAAoC,CAAC;QACzC,OAAO,EAAE,KAAK,CAAC,iBAAiB,CAAC,OAAO;QACxC,QAAQ,EAAE,KAAK,CAAC,qBAAqB;QACrC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC;QACrB,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;IACH,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { ProjectionCheckpointContext } from \"./checkpointContext\";\nimport { assertServedAncestorsDescendFromCitations } from \"./containerAncestorCitations\";\nimport { verifyContainerManifestBundle } from \"./containerManifestVerification\";\nimport { rememberRootBoundOrganizationFounder } from \"./organizationFounderBinding\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\n\nexport async function verifyContainerManifestPath(input: {\n readonly authorizationMembership?: \"current\" | \"referenced\" | undefined;\n readonly authorizationEvidence?:\n | readonly PrincipalPolicyCheckpointEvidence[]\n | undefined;\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly enforceLocalCheckpoints: boolean;\n readonly servedAsCurrent: boolean;\n readonly label: string;\n readonly path: readonly AccessManifestBundleWireResponse[];\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly requireAuthorizationEvidence?: boolean | undefined;\n readonly verifiedByHash: Map<string, VerifiedContainerAccessManifest>;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<VerifiedContainerAccessManifest[]> {\n // Historical signer membership and current-path freshness are independent:\n // current heads may have been signed before a group member was removed.\n const verifiedPath: VerifiedContainerAccessManifest[] = [];\n for (const [index, bundle] of input.path.entries()) {\n const label = `${input.label}[${index}]`;\n const verified = await verifyContainerManifestBundle({\n authorizationMembership: input.authorizationMembership,\n authorizationEvidence: input.authorizationEvidence,\n bundle,\n bundlesByHash: input.bundlesByHash,\n checkpointContext: input.checkpointContext,\n enforceLocalCheckpoint: input.enforceLocalCheckpoints,\n label,\n parentPath: verifiedPath,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n requireAuthorizationEvidence: input.requireAuthorizationEvidence,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // Access along a path is the union of its elements' grants, so a served\n // path must be a genuine root-to-leaf ancestor chain: each element is the\n // parent of the next, and the first is a root.\n const expectedParentId = verifiedPath.at(-1)?.state.containerId ?? null;\n if (verified.state.parentContainerId !== expectedParentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${label} parent container does not precede it in the path`,\n );\n }\n if (input.servedAsCurrent) {\n assertServedAncestorsDescendFromCitations({\n head: verified,\n label,\n servedAncestors: verifiedPath,\n verifiedByHash: input.verifiedByHash,\n });\n }\n verifiedPath.push(verified);\n }\n\n await rememberRootBoundOrganizationFounder({\n execSql: input.checkpointContext.execSql,\n policies: input.authorizationEvidence,\n root: verifiedPath[0],\n verifiedByHash: input.verifiedByHash,\n });\n return verifiedPath;\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type VerifiedContainerAccessManifest } from "../../internal/crypto/index.js";
|
|
2
2
|
import type { AccessManifestBundleWireResponse, ContainerWriterProjectionResponse } from "../../internal/validators/response/index.js";
|
|
3
|
+
import type { PrincipalPolicyCheckpointEvidence, PrincipalPolicyCurrentEvidence } from "../principals/principalPolicyEvidence.js";
|
|
3
4
|
import type { ExecSql } from "../sqlite/sqlSchema.js";
|
|
4
5
|
import { type ProjectionCheckpointContext } from "./checkpointContext.js";
|
|
5
6
|
import type { PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "./types.js";
|
|
@@ -15,9 +16,9 @@ interface ContainerWriterProjectionVerificationInput {
|
|
|
15
16
|
}
|
|
16
17
|
export declare function verifiedContainerManifestsForBundles(bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>, verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>): VerifiedContainerAccessManifest[];
|
|
17
18
|
export declare function verifyContainerWriterProjectionWithContext(input: Omit<ContainerWriterProjectionVerificationInput, "execSql"> & {
|
|
18
|
-
readonly authorizationEvidence?: readonly
|
|
19
|
+
readonly authorizationEvidence?: readonly PrincipalPolicyCheckpointEvidence[];
|
|
19
20
|
}, checkpointContext: ProjectionCheckpointContext): Promise<VerifiedContainerAccessManifest[]>;
|
|
20
21
|
export declare function verifyContainerWriterProjection(input: ContainerWriterProjectionVerificationInput): Promise<VerifiedContainerAccessManifest[]>;
|
|
21
|
-
export declare function collectContainerWriterProjectionPrincipalPolicies(input: ContainerWriterProjectionVerificationInput): Promise<
|
|
22
|
+
export declare function collectContainerWriterProjectionPrincipalPolicies(input: ContainerWriterProjectionVerificationInput): Promise<PrincipalPolicyCurrentEvidence[]>;
|
|
22
23
|
export declare function addContainerWriterProjectionBundles(bundlesByHash: Map<string, AccessManifestBundleWireResponse>, projection: ContainerWriterProjectionResponse, label: string): void;
|
|
23
24
|
export {};
|