feat(ql3): establish 3.0 incubation baseline

This commit is contained in:
whyour committed 2026-08-12 00:25:26 +08:00
1 parent 4bf92dcfeb
commit c699c32461
2817 files changed
+779642 -653

No files matched your search

@@ -0,0 +1,202 @@
import { createHash } from 'node:crypto';
import type {
PluginPackagePlanOperation,
PluginPackageRisk,
} from '../../pluginPackage';
import {
InvalidPluginPackageLockError,
InvalidPluginPackageInstallError,
} from './contracts';
export const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
export const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
export const PACKAGE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
export const OCI_LOCATOR_PATTERN =
/^oci:\/\/([^/?#]+)\/([a-z0-9]+(?:[._-][a-z0-9]+)*(?:\/[a-z0-9]+(?:[._-][a-z0-9]+)*)*)@sha256:([0-9a-f]{64})$/;
export const OCI_REGISTRY_PATTERN =
/^([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*)(?::([1-9][0-9]{0,4}))?$/;
export const OFFLINE_LOCATOR_PATTERN = /^offline:sha256:([0-9a-f]{64})$/;
export const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
export const PLAN_RISKS: readonly PluginPackageRisk[] = ['low', 'medium', 'high'];
export const PLAN_OPERATIONS: readonly PluginPackagePlanOperation[] = [
'install',
'reinstall',
'upgrade',
'rollback',
];
export const PLAN_FINDING_CODES = new Set([
'architecture_unsupported',
'deployment_profile_unsupported',
'disk_insufficient',
'memory_below_recommendation',
'qinglong_version_unsupported',
'runtime_missing',
'runtime_version_unsupported',
]);
export function exactKeys(
value: object,
required: readonly string[],
optional: readonly string[],
label: string,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): void {
const actual = Object.keys(value).sort();
const allowed = new Set([...required, ...optional]);
if (
required.some((key) => !actual.includes(key)) ||
actual.some((key) => !allowed.has(key))
) {
throw new ErrorType(`${label} shape is invalid`);
}
}
export function lockObject(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageLockError(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
export function installObject(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageInstallError(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
export function identifier(
value: unknown,
label: string,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new ErrorType(`${label} is invalid`);
}
return value;
}
export function boundedText(
value: unknown,
label: string,
maximumBytes: number,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): string {
if (
typeof value !== 'string' ||
value.length === 0 ||
CONTROL_PATTERN.test(value) ||
Buffer.byteLength(value, 'utf8') > maximumBytes
) {
throw new ErrorType(`${label} is invalid`);
}
return value;
}
export function digest(
value: unknown,
label: string,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new ErrorType(`${label} is invalid`);
}
return value;
}
export function timestamp(
value: unknown,
label: string,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new ErrorType(`${label} is invalid`);
}
return value as number;
}
export function positiveInteger(
value: unknown,
label: string,
maximum: number,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > maximum
) {
throw new ErrorType(`${label} is invalid`);
}
return value as number;
}
export function nonNegativeInteger(
value: unknown,
label: string,
maximum: number,
ErrorType:
| typeof InvalidPluginPackageLockError
| typeof InvalidPluginPackageInstallError,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 0 ||
(value as number) > maximum
) {
throw new ErrorType(`${label} is invalid`);
}
return value as number;
}
export function canonicalJson(value: unknown): string {
if (value === null || typeof value === 'boolean')
return JSON.stringify(value);
if (typeof value === 'number') {
if (!Number.isFinite(value)) {
throw new InvalidPluginPackageLockError(
'digest input contains an invalid number',
);
}
return JSON.stringify(Object.is(value, -0) ? 0 : value);
}
if (typeof value === 'string') return JSON.stringify(value);
if (Array.isArray(value)) {
return `[${value.map((entry) => canonicalJson(entry)).join(',')}]`;
}
const record = lockObject(value, 'digest input');
const entries = Object.keys(record)
.sort()
.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`);
return `{${entries.join(',')}}`;
}
export function contentDigest(value: unknown): string {
return createHash('sha256').update(canonicalJson(value)).digest('hex');
}
@@ -0,0 +1,360 @@
import type {
PluginPackageArchitecture,
PluginPackageDeploymentProfile,
PluginPackageInstallEnvironment,
PluginPackageInstallPlan,
PluginPackageManifest,
PluginPackagePlanOperation,
} from '../../pluginPackage';
import type {
SecurityPolicyFence,
SecuritySubject,
} from '../../../security/security';
import type { PluginPackageResourceReference } from '../../pluginPackageResourceGeneration';
export const PLUGIN_PACKAGE_LOCK_SCHEMA =
'qinglong/plugin-package-lock@v2' as const;
export const PLUGIN_PACKAGE_INSTALL_SCHEMA =
'qinglong/plugin-package-install@v1' as const;
export const PLUGIN_PACKAGE_INSTALL_ACTION_SCHEMA =
'qinglong/plugin-package-install-action@v1' as const;
export const MAX_PLUGIN_PACKAGE_SOURCE_BYTES = 1024 ** 4;
export const MAX_PLUGIN_PACKAGE_INSTALL_VERSION = 2_147_483_647;
export const MAX_PLUGIN_PACKAGE_INSTALL_RECOVERY_PAGE_SIZE = 64;
export const MAX_PLUGIN_PACKAGE_INSTALL_INVENTORY_PAGE_SIZE = 64;
export const PLUGIN_PACKAGE_SOURCE_KINDS = ['oci', 'offline'] as const;
export const PLUGIN_PACKAGE_INSTALL_STATES = [
'queued',
'staged',
'activating',
'active',
'failed',
] as const;
export const PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS = [
'source_unavailable',
'source_mismatch',
'stage_failed',
'activation_failed',
'activation_fact_conflict',
'approval_expired',
'policy_fence_changed',
'resource_exhausted',
] as const;
export const PLUGIN_PACKAGE_INSTALL_RECOVERY_ACTIONS = [
'resume_stage',
'resume_activation',
'inspect_activation',
'none',
] as const;
export type PluginPackageSourceKind =
(typeof PLUGIN_PACKAGE_SOURCE_KINDS)[number];
export type PluginPackageInstallState =
(typeof PLUGIN_PACKAGE_INSTALL_STATES)[number];
export type PluginPackageInstallFailureReason =
(typeof PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS)[number];
export type PluginPackageInstallRecoveryAction =
(typeof PLUGIN_PACKAGE_INSTALL_RECOVERY_ACTIONS)[number];
export interface PluginPackageSourceLock {
readonly kind: PluginPackageSourceKind;
readonly locator: string;
readonly artifactDigest: string;
readonly artifactBytes: number;
readonly contentDigest: string;
}
export interface PluginPackageApprovalLock {
readonly requestId: string;
readonly requestVersion: number;
readonly dispatchId: string;
readonly actionDigest: string;
readonly previewDigest: string;
readonly approvedBy: Readonly<SecuritySubject>;
readonly approvedAtMs: number;
readonly expiresAtMs: number;
readonly fence: Readonly<SecurityPolicyFence>;
}
export interface CreatePluginPackageLockInput {
readonly lockId: string;
readonly projectId: string;
readonly manifest: PluginPackageManifest;
readonly plan: PluginPackageInstallPlan;
readonly environment: PluginPackageInstallEnvironment;
readonly previousManifest?: PluginPackageManifest;
readonly source: PluginPackageSourceLock;
readonly approval: PluginPackageApprovalLock;
readonly architecture: PluginPackageArchitecture;
readonly deploymentProfile: PluginPackageDeploymentProfile;
readonly targetGeneration: number;
readonly previousLockDigest?: string;
readonly createdAtMs: number;
}
export type PluginPackageInstallActionInput = Omit<
CreatePluginPackageLockInput,
'approval' | 'createdAtMs'
>;
export interface PluginPackageLock {
readonly schema: typeof PLUGIN_PACKAGE_LOCK_SCHEMA;
readonly lockId: string;
readonly projectId: string;
readonly packageName: string;
readonly packageVersion: string;
readonly operation: PluginPackagePlanOperation;
readonly source: Readonly<PluginPackageSourceLock>;
readonly manifestDigest: string;
readonly resources: readonly Readonly<PluginPackageResourceReference>[];
readonly planDigest: string;
readonly environmentDigest: string;
readonly actionDigest: string;
readonly approval: Readonly<PluginPackageApprovalLock>;
readonly architecture: PluginPackageArchitecture;
readonly deploymentProfile: PluginPackageDeploymentProfile;
readonly targetGeneration: number;
readonly previousLockDigest?: string;
readonly createdAtMs: number;
readonly lockDigest: string;
}
export interface PluginPackageStageReceipt {
readonly stageRef: string;
readonly artifactDigest: string;
readonly manifestDigest: string;
readonly contentDigest: string;
readonly evidenceDigest: string;
readonly stagedAtMs: number;
readonly receiptDigest: string;
}
export interface PluginPackageActivationReceipt {
readonly activationRef: string;
readonly intentDigest: string;
readonly generation: number;
readonly contentDigest: string;
readonly activatedAtMs: number;
readonly receiptDigest: string;
}
export type CreatePluginPackageActivationReceiptInput = Omit<
PluginPackageActivationReceipt,
'receiptDigest'
>;
export interface PluginPackageInstallFailure {
readonly reason: PluginPackageInstallFailureReason;
readonly failedFrom: Exclude<PluginPackageInstallState, 'active' | 'failed'>;
readonly failedAtMs: number;
}
export interface PluginPackageInstallRecord {
readonly schema: typeof PLUGIN_PACKAGE_INSTALL_SCHEMA;
readonly installationId: string;
readonly projectId: string;
readonly packageName: string;
readonly packageVersion: string;
readonly operation: PluginPackagePlanOperation;
readonly lockDigest: string;
readonly targetGeneration: number;
readonly previousActiveLockDigest: string | null;
readonly activeLockDigest: string | null;
readonly state: PluginPackageInstallState;
readonly version: number;
readonly lastMutationId: string;
readonly lastMutationDigest: string;
readonly stageReceipt: Readonly<PluginPackageStageReceipt> | null;
readonly activationReceipt: Readonly<PluginPackageActivationReceipt> | null;
readonly failure: Readonly<PluginPackageInstallFailure> | null;
readonly createdAtMs: number;
readonly updatedAtMs: number;
readonly recordDigest: string;
}
export interface CreatePluginPackageInstallInput {
readonly installationId: string;
readonly mutationId: string;
readonly occurredAtMs: number;
}
export type PluginPackageInstallEvent =
| Readonly<{
type: 'stage_completed';
mutationId: string;
occurredAtMs: number;
stageRef: string;
artifactDigest: string;
manifestDigest: string;
contentDigest: string;
evidenceDigest: string;
}>
| Readonly<{
type: 'activation_started';
mutationId: string;
occurredAtMs: number;
}>
| Readonly<{
type: 'activation_committed';
mutationId: string;
occurredAtMs: number;
activationRef: string;
intentDigest: string;
generation: number;
contentDigest: string;
}>
| Readonly<{
type: 'failed';
mutationId: string;
occurredAtMs: number;
reason: PluginPackageInstallFailureReason;
}>;
export interface PluginPackageInstallCommit {
readonly installationId: string;
readonly expectedVersion: number;
readonly expectedRecordDigest: string;
readonly mutationId: string;
readonly mutationDigest: string;
readonly record: Readonly<PluginPackageInstallRecord>;
}
export interface PluginPackageInstallHeadExpectation {
readonly installationId: string;
readonly version: number;
readonly recordDigest: string;
}
export interface PluginPackageInstallCreate {
readonly installationId: string;
readonly mutationId: string;
readonly mutationDigest: string;
readonly expectedHead: Readonly<PluginPackageInstallHeadExpectation> | null;
readonly lock: Readonly<PluginPackageLock>;
readonly record: Readonly<PluginPackageInstallRecord>;
}
export interface PluginPackageInstallRecoveryCursor {
readonly packageName: string;
readonly installationId: string;
}
export interface PluginPackageInstallRecoveryPage {
readonly records: readonly Readonly<PluginPackageInstallRecord>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageInstallRecoveryCursor>;
}
export interface PluginPackageInstallInventoryCursor {
readonly packageName: string;
}
export interface PluginPackageInstallInventoryQuarantine {
readonly eventDigest: string;
readonly reasonCode: 'suspected_key_compromise' | 'confirmed_key_compromise';
readonly authorizationMode: 'dual_control' | 'break_glass';
readonly occurredAtMs: number;
readonly capabilityStatus: 'not_active' | 'withdrawn';
readonly receiptDigest: string;
readonly committedAtMs: number;
}
export interface PluginPackageInstallInventoryItem {
readonly record: Readonly<PluginPackageInstallRecord>;
readonly quarantine: Readonly<PluginPackageInstallInventoryQuarantine> | null;
}
export interface PluginPackageInstallInventoryPage {
readonly items: readonly Readonly<PluginPackageInstallInventoryItem>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageInstallInventoryCursor>;
}
/**
* Read-only product query boundary for the current install head of each package.
* It stays separate from the mutation/recovery repository so management
* surfaces cannot accidentally acquire write authority.
*/
export interface PluginPackageInstallInventoryRepository {
findCurrent(
projectId: string,
packageName: string,
): Promise<Readonly<PluginPackageInstallInventoryItem> | null>;
listCurrentPage(options: {
readonly projectId: string;
readonly limit: number;
readonly after?: Readonly<PluginPackageInstallInventoryCursor>;
}): Promise<Readonly<PluginPackageInstallInventoryPage>>;
}
export interface PluginPackageInstallRepository {
find(
projectId: string,
packageName: string,
): Promise<Readonly<PluginPackageInstallRecord> | null>;
findLock(lockDigest: string): Promise<Readonly<PluginPackageLock> | null>;
create(command: Readonly<PluginPackageInstallCreate>): Promise<
Readonly<{
status: 'created' | 'existing';
record: Readonly<PluginPackageInstallRecord>;
}>
>;
commit(command: Readonly<PluginPackageInstallCommit>): Promise<
Readonly<{
status: 'committed' | 'existing';
record: Readonly<PluginPackageInstallRecord>;
}>
>;
listRecoveryPage(options: {
readonly limit: number;
readonly after?: Readonly<PluginPackageInstallRecoveryCursor>;
}): Promise<Readonly<PluginPackageInstallRecoveryPage>>;
}
export class InvalidPluginPackageLockError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_LOCK_INVALID';
constructor(message: string) {
super(`Plugin Package lock is invalid: ${message}`);
this.name = 'InvalidPluginPackageLockError';
}
}
export class InvalidPluginPackageInstallError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_INSTALL_INVALID';
constructor(message: string) {
super(`Plugin Package install is invalid: ${message}`);
this.name = 'InvalidPluginPackageInstallError';
}
}
export class PluginPackageInstallTransitionConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_TRANSITION_CONFLICT';
constructor() {
super('Plugin Package install transition conflicts with durable state');
this.name = 'PluginPackageInstallTransitionConflictError';
}
}
export class PluginPackageInstallMutationConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_MUTATION_CONFLICT';
constructor() {
super(
'Plugin Package install mutation conflicts with its previous request',
);
this.name = 'PluginPackageInstallMutationConflictError';
}
}
export class PluginPackageInstallUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package install storage is unavailable', options);
this.name = 'PluginPackageInstallUnavailableError';
}
}
@@ -0,0 +1,930 @@
import { createHash } from 'node:crypto';
import {
PLUGIN_PACKAGE_ARCHITECTURES,
PLUGIN_PACKAGE_DEPLOYMENT_PROFILES,
type PluginPackageArchitecture,
type PluginPackageDeploymentProfile,
type PluginPackageInstallEnvironment,
type PluginPackageInstallPlan,
type PluginPackageManifest,
type PluginPackagePlanOperation,
type PluginPackageRisk,
normalizePluginPackageManifest,
normalizePluginPackageInstallEnvironment,
planPluginPackageInstall,
} from '../../pluginPackage';
import {
SECURITY_SUBJECT_TYPES,
type SecurityPolicyFence,
type SecuritySubject,
} from '../../../security/security';
import {
createPluginPackageResourceGenerationFromReferences,
normalizePluginPackageResourceReferences,
pluginPackageResourceReferencesFromContents,
type PluginPackageResourceReference,
} from '../../pluginPackageResourceGeneration';
import { semver } from '../../../versioning/pinnedSemver';
import {
PLUGIN_PACKAGE_LOCK_SCHEMA,
PLUGIN_PACKAGE_INSTALL_ACTION_SCHEMA,
MAX_PLUGIN_PACKAGE_SOURCE_BYTES,
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
PLUGIN_PACKAGE_SOURCE_KINDS,
InvalidPluginPackageLockError,
type PluginPackageSourceKind,
type PluginPackageSourceLock,
type PluginPackageApprovalLock,
type CreatePluginPackageLockInput,
type PluginPackageInstallActionInput,
type PluginPackageLock,
} from './contracts';
import {
PACKAGE_NAME_PATTERN,
OCI_LOCATOR_PATTERN,
OCI_REGISTRY_PATTERN,
OFFLINE_LOCATOR_PATTERN,
PLAN_RISKS,
PLAN_OPERATIONS,
PLAN_FINDING_CODES,
exactKeys,
lockObject,
identifier,
boundedText,
digest,
timestamp,
positiveInteger,
nonNegativeInteger,
canonicalJson,
contentDigest,
} from './codec';
export function serializePluginPackageManifest(
value: PluginPackageManifest,
): string {
return canonicalJson(normalizePluginPackageManifest(value));
}
export function pluginPackageManifestDigest(
value: PluginPackageManifest,
): string {
return createHash('sha256')
.update(serializePluginPackageManifest(value), 'utf8')
.digest('hex');
}
export function normalizeSource(value: unknown): Readonly<PluginPackageSourceLock> {
const source = lockObject(value, 'source');
exactKeys(
source,
['kind', 'locator', 'artifactDigest', 'artifactBytes', 'contentDigest'],
[],
'source',
InvalidPluginPackageLockError,
);
if (
!PLUGIN_PACKAGE_SOURCE_KINDS.includes(
source.kind as PluginPackageSourceKind,
)
) {
throw new InvalidPluginPackageLockError('source kind is invalid');
}
const kind = source.kind as PluginPackageSourceKind;
const locator = boundedText(
source.locator,
'source locator',
512,
InvalidPluginPackageLockError,
);
const artifactDigest = digest(
source.artifactDigest,
'source artifact digest',
InvalidPluginPackageLockError,
);
const locatorMatch =
kind === 'oci'
? locator.match(OCI_LOCATOR_PATTERN)
: locator.match(OFFLINE_LOCATOR_PATTERN);
if (!locatorMatch) {
throw new InvalidPluginPackageLockError('source locator is not immutable');
}
if (kind === 'oci') {
const registryMatch = locatorMatch[1]?.match(OCI_REGISTRY_PATTERN);
if (
!registryMatch ||
Buffer.byteLength(registryMatch[1]!, 'utf8') > 253 ||
(registryMatch[2] !== undefined && Number(registryMatch[2]) > 65_535)
) {
throw new InvalidPluginPackageLockError(
'source OCI registry is not canonical',
);
}
} else if (locatorMatch.at(-1) !== artifactDigest) {
throw new InvalidPluginPackageLockError(
'offline source locator does not match its artifact digest',
);
}
return Object.freeze({
kind,
locator,
artifactDigest,
artifactBytes: positiveInteger(
source.artifactBytes,
'source artifact bytes',
MAX_PLUGIN_PACKAGE_SOURCE_BYTES,
InvalidPluginPackageLockError,
),
contentDigest: digest(
source.contentDigest,
'source content digest',
InvalidPluginPackageLockError,
),
});
}
export function normalizeSubject(value: unknown): Readonly<SecuritySubject> {
const subject = lockObject(value, 'approval subject');
exactKeys(
subject,
['type', 'id'],
[],
'approval subject',
InvalidPluginPackageLockError,
);
if (
!SECURITY_SUBJECT_TYPES.includes(subject.type as SecuritySubject['type'])
) {
throw new InvalidPluginPackageLockError('approval subject type is invalid');
}
return Object.freeze({
type: subject.type as SecuritySubject['type'],
id: boundedText(
subject.id,
'approval subject id',
255,
InvalidPluginPackageLockError,
),
});
}
export function normalizeFence(value: unknown): Readonly<SecurityPolicyFence> {
const fence = lockObject(value, 'approval fence');
exactKeys(
fence,
['projectVersion', 'bindingVersion'],
[],
'approval fence',
InvalidPluginPackageLockError,
);
return Object.freeze({
projectVersion: positiveInteger(
fence.projectVersion,
'approval project version',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageLockError,
),
bindingVersion:
fence.bindingVersion === null
? null
: positiveInteger(
fence.bindingVersion,
'approval binding version',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageLockError,
),
});
}
export function normalizeApproval(
value: unknown,
createdAtMs: number,
): Readonly<PluginPackageApprovalLock> {
const approval = lockObject(value, 'approval');
exactKeys(
approval,
[
'requestId',
'requestVersion',
'dispatchId',
'actionDigest',
'previewDigest',
'approvedBy',
'approvedAtMs',
'expiresAtMs',
'fence',
],
[],
'approval',
InvalidPluginPackageLockError,
);
const approvedAtMs = timestamp(
approval.approvedAtMs,
'approval time',
InvalidPluginPackageLockError,
);
const expiresAtMs = timestamp(
approval.expiresAtMs,
'approval expiry',
InvalidPluginPackageLockError,
);
if (approvedAtMs > createdAtMs || expiresAtMs <= createdAtMs) {
throw new InvalidPluginPackageLockError(
'approval is not active when the lock is created',
);
}
const approvedBy = normalizeSubject(approval.approvedBy);
if (approvedBy.type !== 'user') {
throw new InvalidPluginPackageLockError(
'package installation requires a human approval',
);
}
return Object.freeze({
requestId: identifier(
approval.requestId,
'approval request id',
InvalidPluginPackageLockError,
),
requestVersion: positiveInteger(
approval.requestVersion,
'approval request version',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageLockError,
),
dispatchId: identifier(
approval.dispatchId,
'approval dispatch id',
InvalidPluginPackageLockError,
),
actionDigest: digest(
approval.actionDigest,
'approval action digest',
InvalidPluginPackageLockError,
),
previewDigest: digest(
approval.previewDigest,
'approval preview digest',
InvalidPluginPackageLockError,
),
approvedBy,
approvedAtMs,
expiresAtMs,
fence: normalizeFence(approval.fence),
});
}
export function normalizeStringArray(
value: unknown,
label: string,
): readonly string[] {
if (!Array.isArray(value) || value.length > 256) {
throw new InvalidPluginPackageLockError(`${label} is invalid`);
}
const normalized = value.map((entry) =>
boundedText(entry, label, 512, InvalidPluginPackageLockError),
);
if (
new Set(normalized).size !== normalized.length ||
normalized.some(
(entry, index) => index > 0 && normalized[index - 1]! > entry,
)
) {
throw new InvalidPluginPackageLockError(
`${label} must be unique and sorted`,
);
}
return Object.freeze(normalized);
}
export function normalizePlan(value: unknown): Readonly<PluginPackageInstallPlan> {
const plan = lockObject(value, 'install plan');
exactKeys(
plan,
[
'package',
'operation',
'compatible',
'risk',
'approvalRequired',
'permissionReapprovalRequired',
'permissionDelta',
'resources',
'contents',
'findings',
],
[],
'install plan',
InvalidPluginPackageLockError,
);
if (
plan.compatible !== true ||
plan.approvalRequired !== true ||
typeof plan.permissionReapprovalRequired !== 'boolean' ||
!PLAN_RISKS.includes(plan.risk as PluginPackageRisk) ||
!PLAN_OPERATIONS.includes(plan.operation as PluginPackagePlanOperation)
) {
throw new InvalidPluginPackageLockError(
'install plan is not compatible or has invalid policy fields',
);
}
const packageValue = lockObject(plan.package, 'install plan package');
exactKeys(
packageValue,
['name', 'toVersion'],
['fromVersion'],
'install plan package',
InvalidPluginPackageLockError,
);
const packageName = boundedText(
packageValue.name,
'install plan package name',
64,
InvalidPluginPackageLockError,
);
if (!PACKAGE_NAME_PATTERN.test(packageName)) {
throw new InvalidPluginPackageLockError(
'install plan package name is invalid',
);
}
const toVersion = boundedText(
packageValue.toVersion,
'install plan target version',
128,
InvalidPluginPackageLockError,
);
if (semver().valid(toVersion) !== toVersion) {
throw new InvalidPluginPackageLockError(
'install plan target version is invalid',
);
}
const operation = plan.operation as PluginPackagePlanOperation;
const fromVersion =
packageValue.fromVersion === undefined
? undefined
: boundedText(
packageValue.fromVersion,
'install plan source version',
128,
InvalidPluginPackageLockError,
);
if (
fromVersion !== undefined &&
semver().valid(fromVersion) !== fromVersion
) {
throw new InvalidPluginPackageLockError(
'install plan source version is invalid',
);
}
if (
(operation === 'install' && fromVersion !== undefined) ||
(operation !== 'install' && fromVersion === undefined)
) {
throw new InvalidPluginPackageLockError(
'install plan operation does not match its package versions',
);
}
const delta = lockObject(plan.permissionDelta, 'permission delta');
exactKeys(
delta,
['added', 'removed'],
[],
'permission delta',
InvalidPluginPackageLockError,
);
const resources = lockObject(plan.resources, 'install resources');
exactKeys(
resources,
['memoryRecommendedBytes', 'diskInstallBytes', 'diskWorkingBytes'],
[],
'install resources',
InvalidPluginPackageLockError,
);
const contents = lockObject(plan.contents, 'install contents');
exactKeys(
contents,
['tasks', 'workflows', 'prompts', 'tools'],
[],
'install contents',
InvalidPluginPackageLockError,
);
if (!Array.isArray(plan.findings) || plan.findings.length > 32) {
throw new InvalidPluginPackageLockError('install findings are invalid');
}
const findings = plan.findings.map((entry) => {
const finding = lockObject(entry, 'install finding');
exactKeys(
finding,
['code', 'severity', 'subject'],
[],
'install finding',
InvalidPluginPackageLockError,
);
if (
!PLAN_FINDING_CODES.has(finding.code as string) ||
finding.severity !== 'warning'
) {
throw new InvalidPluginPackageLockError(
'compatible install plan contains an invalid finding',
);
}
return Object.freeze({
code: finding.code as PluginPackageInstallPlan['findings'][number]['code'],
severity: 'warning' as const,
subject: boundedText(
finding.subject,
'install finding subject',
512,
InvalidPluginPackageLockError,
),
});
});
return Object.freeze({
package: Object.freeze({
name: packageName,
...(fromVersion === undefined ? {} : { fromVersion }),
toVersion,
}),
operation,
compatible: true,
risk: plan.risk as PluginPackageRisk,
approvalRequired: true,
permissionReapprovalRequired: plan.permissionReapprovalRequired as boolean,
permissionDelta: Object.freeze({
added: normalizeStringArray(delta.added, 'added permission'),
removed: normalizeStringArray(delta.removed, 'removed permission'),
}),
resources: Object.freeze({
memoryRecommendedBytes: positiveInteger(
resources.memoryRecommendedBytes,
'recommended memory bytes',
MAX_PLUGIN_PACKAGE_SOURCE_BYTES,
InvalidPluginPackageLockError,
),
diskInstallBytes: positiveInteger(
resources.diskInstallBytes,
'install disk bytes',
MAX_PLUGIN_PACKAGE_SOURCE_BYTES,
InvalidPluginPackageLockError,
),
diskWorkingBytes: positiveInteger(
resources.diskWorkingBytes,
'working disk bytes',
MAX_PLUGIN_PACKAGE_SOURCE_BYTES,
InvalidPluginPackageLockError,
),
}),
contents: Object.freeze({
tasks: nonNegativeInteger(
contents.tasks,
'task count',
256,
InvalidPluginPackageLockError,
),
workflows: nonNegativeInteger(
contents.workflows,
'workflow count',
256,
InvalidPluginPackageLockError,
),
prompts: nonNegativeInteger(
contents.prompts,
'prompt count',
256,
InvalidPluginPackageLockError,
),
tools: nonNegativeInteger(
contents.tools,
'tool count',
256,
InvalidPluginPackageLockError,
),
}),
findings: Object.freeze(findings),
});
}
export function lockActionPayload(
input: Readonly<{
lockId: string;
projectId: string;
packageName: string;
packageVersion: string;
operation: PluginPackagePlanOperation;
source: Readonly<PluginPackageSourceLock>;
manifestDigest: string;
resources: readonly Readonly<PluginPackageResourceReference>[];
planDigest: string;
environmentDigest: string;
architecture: PluginPackageArchitecture;
deploymentProfile: PluginPackageDeploymentProfile;
targetGeneration: number;
previousLockDigest?: string;
}>,
): Readonly<Record<string, unknown>> {
return Object.freeze({
schema: PLUGIN_PACKAGE_INSTALL_ACTION_SCHEMA,
lockId: input.lockId,
projectId: input.projectId,
packageName: input.packageName,
packageVersion: input.packageVersion,
operation: input.operation,
source: input.source,
manifestDigest: input.manifestDigest,
resources: input.resources,
planDigest: input.planDigest,
environmentDigest: input.environmentDigest,
architecture: input.architecture,
deploymentProfile: input.deploymentProfile,
targetGeneration: input.targetGeneration,
...(input.previousLockDigest === undefined
? {}
: { previousLockDigest: input.previousLockDigest }),
});
}
export function pluginPackageInstallActionDigest(
input: Omit<CreatePluginPackageLockInput, 'approval' | 'createdAtMs'>,
): string {
const value = lockObject(input, 'install action input');
exactKeys(
value,
[
'lockId',
'projectId',
'manifest',
'plan',
'environment',
'source',
'architecture',
'deploymentProfile',
'targetGeneration',
],
['previousLockDigest', 'previousManifest'],
'install action input',
InvalidPluginPackageLockError,
);
const prepared = prepareLockFields({
...input,
createdAtMs: 0,
});
return contentDigest(lockActionPayload(prepared));
}
export function pluginPackageInstallPlanDigest(
value: PluginPackageInstallPlan,
): string {
return contentDigest(normalizePlan(value));
}
export function normalizePluginPackageInstallActionInput(
input: PluginPackageInstallActionInput,
): Readonly<PluginPackageInstallActionInput> {
const value = lockObject(input, 'install action input');
exactKeys(
value,
[
'lockId',
'projectId',
'manifest',
'plan',
'environment',
'source',
'architecture',
'deploymentProfile',
'targetGeneration',
],
['previousLockDigest', 'previousManifest'],
'install action input',
InvalidPluginPackageLockError,
);
const prepared = prepareLockFields({
...input,
createdAtMs: 0,
});
const previousManifest =
input.previousManifest === undefined
? undefined
: normalizePluginPackageManifest(input.previousManifest);
return Object.freeze({
lockId: prepared.lockId,
projectId: prepared.projectId,
manifest: normalizePluginPackageManifest(input.manifest),
plan: normalizePlan(input.plan),
environment: normalizePluginPackageInstallEnvironment(input.environment),
...(previousManifest === undefined ? {} : { previousManifest }),
source: prepared.source,
architecture: prepared.architecture,
deploymentProfile: prepared.deploymentProfile,
targetGeneration: prepared.targetGeneration,
...(prepared.previousLockDigest === undefined
? {}
: { previousLockDigest: prepared.previousLockDigest }),
});
}
export function prepareLockFields(
input: Omit<CreatePluginPackageLockInput, 'approval'>,
): Readonly<{
lockId: string;
projectId: string;
packageName: string;
packageVersion: string;
operation: PluginPackagePlanOperation;
source: Readonly<PluginPackageSourceLock>;
manifestDigest: string;
resources: readonly Readonly<PluginPackageResourceReference>[];
planDigest: string;
environmentDigest: string;
architecture: PluginPackageArchitecture;
deploymentProfile: PluginPackageDeploymentProfile;
targetGeneration: number;
previousLockDigest?: string;
createdAtMs: number;
}> {
const manifest = normalizePluginPackageManifest(input.manifest);
const environment = normalizePluginPackageInstallEnvironment(
input.environment,
);
const previousManifest =
input.previousManifest === undefined
? undefined
: normalizePluginPackageManifest(input.previousManifest);
const plan = normalizePlan(input.plan);
const expectedPlan = normalizePlan(
planPluginPackageInstall(manifest, environment, previousManifest),
);
if (
manifest.metadata.name !== plan.package.name ||
manifest.metadata.version !== plan.package.toVersion ||
contentDigest(plan) !== contentDigest(expectedPlan)
) {
throw new InvalidPluginPackageLockError(
'manifest, environment or previous manifest does not match the install plan',
);
}
if (!PLUGIN_PACKAGE_ARCHITECTURES.includes(input.architecture)) {
throw new InvalidPluginPackageLockError('target architecture is invalid');
}
if (!PLUGIN_PACKAGE_DEPLOYMENT_PROFILES.includes(input.deploymentProfile)) {
throw new InvalidPluginPackageLockError(
'target deployment profile is invalid',
);
}
if (
input.architecture !== environment.architecture ||
input.deploymentProfile !== environment.deploymentProfile
) {
throw new InvalidPluginPackageLockError(
'target architecture or profile does not match the install environment',
);
}
const targetGeneration = positiveInteger(
input.targetGeneration,
'target generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageLockError,
);
const previousLockDigest =
input.previousLockDigest === undefined
? undefined
: digest(
input.previousLockDigest,
'previous lock digest',
InvalidPluginPackageLockError,
);
if (
(plan.operation === 'install' &&
(targetGeneration !== 1 || previousLockDigest !== undefined)) ||
(plan.operation !== 'install' &&
(targetGeneration < 2 || previousLockDigest === undefined))
) {
throw new InvalidPluginPackageLockError(
'operation does not match the target generation or previous lock',
);
}
return Object.freeze({
lockId: identifier(input.lockId, 'lock id', InvalidPluginPackageLockError),
projectId: boundedText(
input.projectId,
'project id',
128,
InvalidPluginPackageLockError,
),
packageName: manifest.metadata.name,
packageVersion: manifest.metadata.version,
operation: plan.operation,
source: normalizeSource(input.source),
manifestDigest: pluginPackageManifestDigest(manifest),
resources: pluginPackageResourceReferencesFromContents(
manifest.spec.contents,
),
planDigest: contentDigest(plan),
environmentDigest: contentDigest(environment),
architecture: input.architecture,
deploymentProfile: input.deploymentProfile,
targetGeneration,
...(previousLockDigest === undefined ? {} : { previousLockDigest }),
createdAtMs: timestamp(
input.createdAtMs,
'lock creation time',
InvalidPluginPackageLockError,
),
});
}
export function createPluginPackageLock(
input: CreatePluginPackageLockInput,
): Readonly<PluginPackageLock> {
const value = lockObject(input, 'lock input');
exactKeys(
value,
[
'lockId',
'projectId',
'manifest',
'plan',
'environment',
'source',
'approval',
'architecture',
'deploymentProfile',
'targetGeneration',
'createdAtMs',
],
['previousLockDigest', 'previousManifest'],
'lock input',
InvalidPluginPackageLockError,
);
const fields = prepareLockFields(input);
const actionDigest = contentDigest(lockActionPayload(fields));
const approval = normalizeApproval(input.approval, fields.createdAtMs);
if (
approval.actionDigest !== actionDigest ||
approval.previewDigest !== fields.planDigest
) {
throw new InvalidPluginPackageLockError(
'approval is not bound to this action and preview',
);
}
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_LOCK_SCHEMA,
...fields,
actionDigest,
approval,
});
return Object.freeze({
...unsigned,
lockDigest: contentDigest(unsigned),
});
}
export function normalizePluginPackageLock(
value: PluginPackageLock,
): Readonly<PluginPackageLock> {
const lock = lockObject(value, 'lock');
exactKeys(
lock,
[
'schema',
'lockId',
'projectId',
'packageName',
'packageVersion',
'operation',
'source',
'manifestDigest',
'resources',
'planDigest',
'environmentDigest',
'actionDigest',
'approval',
'architecture',
'deploymentProfile',
'targetGeneration',
'createdAtMs',
'lockDigest',
],
['previousLockDigest'],
'lock',
InvalidPluginPackageLockError,
);
if (
lock.schema !== PLUGIN_PACKAGE_LOCK_SCHEMA ||
!PLAN_OPERATIONS.includes(lock.operation as PluginPackagePlanOperation) ||
!PLUGIN_PACKAGE_ARCHITECTURES.includes(
lock.architecture as PluginPackageArchitecture,
) ||
!PLUGIN_PACKAGE_DEPLOYMENT_PROFILES.includes(
lock.deploymentProfile as PluginPackageDeploymentProfile,
)
) {
throw new InvalidPluginPackageLockError('lock vocabulary is invalid');
}
const targetGeneration = positiveInteger(
lock.targetGeneration,
'target generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageLockError,
);
const previousLockDigest =
lock.previousLockDigest === undefined
? undefined
: digest(
lock.previousLockDigest,
'previous lock digest',
InvalidPluginPackageLockError,
);
if (
(lock.operation === 'install' &&
(targetGeneration !== 1 || previousLockDigest !== undefined)) ||
(lock.operation !== 'install' &&
(targetGeneration < 2 || previousLockDigest === undefined))
) {
throw new InvalidPluginPackageLockError(
'operation does not match lock generation',
);
}
const createdAtMs = timestamp(
lock.createdAtMs,
'lock creation time',
InvalidPluginPackageLockError,
);
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_LOCK_SCHEMA,
lockId: identifier(lock.lockId, 'lock id', InvalidPluginPackageLockError),
projectId: boundedText(
lock.projectId,
'project id',
128,
InvalidPluginPackageLockError,
),
packageName: boundedText(
lock.packageName,
'package name',
64,
InvalidPluginPackageLockError,
),
packageVersion: boundedText(
lock.packageVersion,
'package version',
128,
InvalidPluginPackageLockError,
),
operation: lock.operation as PluginPackagePlanOperation,
source: normalizeSource(lock.source),
manifestDigest: digest(
lock.manifestDigest,
'manifest digest',
InvalidPluginPackageLockError,
),
resources: normalizePluginPackageResourceReferences(lock.resources),
planDigest: digest(
lock.planDigest,
'plan digest',
InvalidPluginPackageLockError,
),
environmentDigest: digest(
lock.environmentDigest,
'environment digest',
InvalidPluginPackageLockError,
),
actionDigest: digest(
lock.actionDigest,
'action digest',
InvalidPluginPackageLockError,
),
approval: normalizeApproval(lock.approval, createdAtMs),
architecture: lock.architecture as PluginPackageArchitecture,
deploymentProfile: lock.deploymentProfile as PluginPackageDeploymentProfile,
targetGeneration,
...(previousLockDigest === undefined ? {} : { previousLockDigest }),
createdAtMs,
});
if (
!PACKAGE_NAME_PATTERN.test(unsigned.packageName) ||
semver().valid(unsigned.packageVersion) !== unsigned.packageVersion ||
unsigned.approval.approvedBy.type !== 'user'
) {
throw new InvalidPluginPackageLockError(
'lock package identity or human approval is invalid',
);
}
if (
unsigned.approval.actionDigest !== unsigned.actionDigest ||
unsigned.approval.previewDigest !== unsigned.planDigest ||
contentDigest(lockActionPayload(unsigned)) !== unsigned.actionDigest
) {
throw new InvalidPluginPackageLockError('lock approval binding is invalid');
}
const lockDigest = digest(
lock.lockDigest,
'lock digest',
InvalidPluginPackageLockError,
);
if (contentDigest(unsigned) !== lockDigest) {
throw new InvalidPluginPackageLockError('lock digest does not match');
}
return Object.freeze({ ...unsigned, lockDigest });
}
@@ -0,0 +1,560 @@
import type { PluginPackagePlanOperation } from '../../pluginPackage';
import { semver } from '../../../versioning/pinnedSemver';
import {
PLUGIN_PACKAGE_INSTALL_SCHEMA,
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
PLUGIN_PACKAGE_INSTALL_STATES,
PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS,
InvalidPluginPackageInstallError,
PluginPackageInstallTransitionConflictError,
type PluginPackageInstallState,
type PluginPackageInstallFailureReason,
type PluginPackageLock,
type PluginPackageStageReceipt,
type PluginPackageActivationReceipt,
type CreatePluginPackageActivationReceiptInput,
type PluginPackageInstallFailure,
type PluginPackageInstallRecord,
type CreatePluginPackageInstallInput,
} from './contracts';
import {
PACKAGE_NAME_PATTERN,
PLAN_OPERATIONS,
exactKeys,
installObject,
identifier,
boundedText,
digest,
timestamp,
positiveInteger,
contentDigest,
} from './codec';
import { normalizePluginPackageLock } from './lock';
export function initialMutationDigest(
lockDigest: string,
input: Readonly<CreatePluginPackageInstallInput>,
): string {
return contentDigest({
type: 'install_created',
lockDigest,
installationId: input.installationId,
mutationId: input.mutationId,
occurredAtMs: input.occurredAtMs,
});
}
export function recordWithoutDigest(
value: Omit<PluginPackageInstallRecord, 'recordDigest'>,
): Omit<PluginPackageInstallRecord, 'recordDigest'> {
return Object.freeze(value);
}
export function withRecordDigest(
value: Omit<PluginPackageInstallRecord, 'recordDigest'>,
): Readonly<PluginPackageInstallRecord> {
const normalized = recordWithoutDigest(value);
return Object.freeze({
...normalized,
recordDigest: contentDigest(normalized),
});
}
export function createPluginPackageInstall(
lockValue: PluginPackageLock,
input: CreatePluginPackageInstallInput,
): Readonly<PluginPackageInstallRecord> {
const lock = normalizePluginPackageLock(lockValue);
const value = installObject(input, 'create input');
exactKeys(
value,
['installationId', 'mutationId', 'occurredAtMs'],
[],
'create input',
InvalidPluginPackageInstallError,
);
const occurredAtMs = timestamp(
input.occurredAtMs,
'creation time',
InvalidPluginPackageInstallError,
);
if (
occurredAtMs < lock.createdAtMs ||
occurredAtMs >= lock.approval.expiresAtMs
) {
throw new InvalidPluginPackageInstallError(
'creation time is outside the approved action lifetime',
);
}
const normalizedInput = Object.freeze({
installationId: identifier(
input.installationId,
'installation id',
InvalidPluginPackageInstallError,
),
mutationId: identifier(
input.mutationId,
'mutation id',
InvalidPluginPackageInstallError,
),
occurredAtMs,
});
const previousActiveLockDigest = lock.previousLockDigest ?? null;
return withRecordDigest({
schema: PLUGIN_PACKAGE_INSTALL_SCHEMA,
installationId: normalizedInput.installationId,
projectId: lock.projectId,
packageName: lock.packageName,
packageVersion: lock.packageVersion,
operation: lock.operation,
lockDigest: lock.lockDigest,
targetGeneration: lock.targetGeneration,
previousActiveLockDigest,
activeLockDigest: previousActiveLockDigest,
state: 'queued',
version: 1,
lastMutationId: normalizedInput.mutationId,
lastMutationDigest: initialMutationDigest(lock.lockDigest, normalizedInput),
stageReceipt: null,
activationReceipt: null,
failure: null,
createdAtMs: occurredAtMs,
updatedAtMs: occurredAtMs,
});
}
export function normalizeStageReceipt(
value: unknown,
): Readonly<PluginPackageStageReceipt> {
const receipt = installObject(value, 'stage receipt');
exactKeys(
receipt,
[
'stageRef',
'artifactDigest',
'manifestDigest',
'contentDigest',
'evidenceDigest',
'stagedAtMs',
'receiptDigest',
],
[],
'stage receipt',
InvalidPluginPackageInstallError,
);
const unsigned = Object.freeze({
stageRef: identifier(
receipt.stageRef,
'stage reference',
InvalidPluginPackageInstallError,
),
artifactDigest: digest(
receipt.artifactDigest,
'staged artifact digest',
InvalidPluginPackageInstallError,
),
manifestDigest: digest(
receipt.manifestDigest,
'staged manifest digest',
InvalidPluginPackageInstallError,
),
contentDigest: digest(
receipt.contentDigest,
'staged content digest',
InvalidPluginPackageInstallError,
),
evidenceDigest: digest(
receipt.evidenceDigest,
'staged evidence digest',
InvalidPluginPackageInstallError,
),
stagedAtMs: timestamp(
receipt.stagedAtMs,
'staged time',
InvalidPluginPackageInstallError,
),
});
const receiptDigest = digest(
receipt.receiptDigest,
'stage receipt digest',
InvalidPluginPackageInstallError,
);
if (contentDigest(unsigned) !== receiptDigest) {
throw new InvalidPluginPackageInstallError(
'stage receipt digest does not match',
);
}
return Object.freeze({ ...unsigned, receiptDigest });
}
export function normalizePluginPackageActivationReceipt(
value: unknown,
): Readonly<PluginPackageActivationReceipt> {
const receipt = installObject(value, 'activation receipt');
exactKeys(
receipt,
[
'activationRef',
'intentDigest',
'generation',
'contentDigest',
'activatedAtMs',
'receiptDigest',
],
[],
'activation receipt',
InvalidPluginPackageInstallError,
);
const unsigned = Object.freeze({
activationRef: identifier(
receipt.activationRef,
'activation reference',
InvalidPluginPackageInstallError,
),
intentDigest: digest(
receipt.intentDigest,
'activation intent digest',
InvalidPluginPackageInstallError,
),
generation: positiveInteger(
receipt.generation,
'activation generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
),
contentDigest: digest(
receipt.contentDigest,
'activated content digest',
InvalidPluginPackageInstallError,
),
activatedAtMs: timestamp(
receipt.activatedAtMs,
'activation time',
InvalidPluginPackageInstallError,
),
});
const receiptDigest = digest(
receipt.receiptDigest,
'activation receipt digest',
InvalidPluginPackageInstallError,
);
if (contentDigest(unsigned) !== receiptDigest) {
throw new InvalidPluginPackageInstallError(
'activation receipt digest does not match',
);
}
return Object.freeze({ ...unsigned, receiptDigest });
}
export function createPluginPackageActivationReceipt(
value: CreatePluginPackageActivationReceiptInput,
): Readonly<PluginPackageActivationReceipt> {
const receipt = installObject(value, 'activation receipt input');
exactKeys(
receipt,
[
'activationRef',
'intentDigest',
'generation',
'contentDigest',
'activatedAtMs',
],
[],
'activation receipt input',
InvalidPluginPackageInstallError,
);
const unsigned = Object.freeze({
activationRef: identifier(
value.activationRef,
'activation reference',
InvalidPluginPackageInstallError,
),
intentDigest: digest(
value.intentDigest,
'activation intent digest',
InvalidPluginPackageInstallError,
),
generation: positiveInteger(
value.generation,
'activation generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
),
contentDigest: digest(
value.contentDigest,
'activated content digest',
InvalidPluginPackageInstallError,
),
activatedAtMs: timestamp(
value.activatedAtMs,
'activated time',
InvalidPluginPackageInstallError,
),
});
return Object.freeze({
...unsigned,
receiptDigest: contentDigest(unsigned),
});
}
export function normalizeFailure(
value: unknown,
): Readonly<PluginPackageInstallFailure> {
const failure = installObject(value, 'failure');
exactKeys(
failure,
['reason', 'failedFrom', 'failedAtMs'],
[],
'failure',
InvalidPluginPackageInstallError,
);
if (
!PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS.includes(
failure.reason as PluginPackageInstallFailureReason,
) ||
!['queued', 'staged', 'activating'].includes(failure.failedFrom as string)
) {
throw new InvalidPluginPackageInstallError('failure vocabulary is invalid');
}
return Object.freeze({
reason: failure.reason as PluginPackageInstallFailureReason,
failedFrom: failure.failedFrom as PluginPackageInstallFailure['failedFrom'],
failedAtMs: timestamp(
failure.failedAtMs,
'failure time',
InvalidPluginPackageInstallError,
),
});
}
export function normalizePluginPackageInstallRecord(
value: PluginPackageInstallRecord,
): Readonly<PluginPackageInstallRecord> {
const record = installObject(value, 'record');
exactKeys(
record,
[
'schema',
'installationId',
'projectId',
'packageName',
'packageVersion',
'operation',
'lockDigest',
'targetGeneration',
'previousActiveLockDigest',
'activeLockDigest',
'state',
'version',
'lastMutationId',
'lastMutationDigest',
'stageReceipt',
'activationReceipt',
'failure',
'createdAtMs',
'updatedAtMs',
'recordDigest',
],
[],
'record',
InvalidPluginPackageInstallError,
);
if (
record.schema !== PLUGIN_PACKAGE_INSTALL_SCHEMA ||
!PLAN_OPERATIONS.includes(record.operation as PluginPackagePlanOperation) ||
!PLUGIN_PACKAGE_INSTALL_STATES.includes(
record.state as PluginPackageInstallState,
)
) {
throw new InvalidPluginPackageInstallError('record vocabulary is invalid');
}
const createdAtMs = timestamp(
record.createdAtMs,
'creation time',
InvalidPluginPackageInstallError,
);
const updatedAtMs = timestamp(
record.updatedAtMs,
'update time',
InvalidPluginPackageInstallError,
);
if (updatedAtMs < createdAtMs) {
throw new InvalidPluginPackageInstallError('record timestamps are invalid');
}
const previousActiveLockDigest =
record.previousActiveLockDigest === null
? null
: digest(
record.previousActiveLockDigest,
'previous active lock digest',
InvalidPluginPackageInstallError,
);
const activeLockDigest =
record.activeLockDigest === null
? null
: digest(
record.activeLockDigest,
'active lock digest',
InvalidPluginPackageInstallError,
);
const state = record.state as PluginPackageInstallState;
const lockDigest = digest(
record.lockDigest,
'lock digest',
InvalidPluginPackageInstallError,
);
const targetGeneration = positiveInteger(
record.targetGeneration,
'target generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
);
if (
(record.operation === 'install' &&
(targetGeneration !== 1 || previousActiveLockDigest !== null)) ||
(record.operation !== 'install' &&
(targetGeneration < 2 || previousActiveLockDigest === null))
) {
throw new InvalidPluginPackageInstallError(
'record operation does not match its generation',
);
}
if (
(state === 'active' && activeLockDigest !== lockDigest) ||
(state !== 'active' && activeLockDigest !== previousActiveLockDigest)
) {
throw new InvalidPluginPackageInstallError(
'active lock pointer does not match install state',
);
}
const stageReceipt =
record.stageReceipt === null
? null
: normalizeStageReceipt(record.stageReceipt);
const activationReceipt =
record.activationReceipt === null
? null
: normalizePluginPackageActivationReceipt(record.activationReceipt);
const failure =
record.failure === null ? null : normalizeFailure(record.failure);
if (
((state === 'queued' || state === 'failed') &&
state !== 'failed' &&
stageReceipt !== null) ||
((state === 'staged' || state === 'activating' || state === 'active') &&
stageReceipt === null) ||
(state === 'active' && activationReceipt === null) ||
(state !== 'active' && activationReceipt !== null) ||
(state === 'failed' ? failure === null : failure !== null)
) {
throw new InvalidPluginPackageInstallError(
'record receipts do not match install state',
);
}
if (
failure &&
((failure.failedFrom === 'queued' && stageReceipt !== null) ||
(failure.failedFrom !== 'queued' && stageReceipt === null))
) {
throw new InvalidPluginPackageInstallError(
'failure receipts do not match the failed state',
);
}
const unsigned = recordWithoutDigest({
schema: PLUGIN_PACKAGE_INSTALL_SCHEMA,
installationId: identifier(
record.installationId,
'installation id',
InvalidPluginPackageInstallError,
),
projectId: boundedText(
record.projectId,
'project id',
128,
InvalidPluginPackageInstallError,
),
packageName: boundedText(
record.packageName,
'package name',
64,
InvalidPluginPackageInstallError,
),
packageVersion: boundedText(
record.packageVersion,
'package version',
128,
InvalidPluginPackageInstallError,
),
operation: record.operation as PluginPackagePlanOperation,
lockDigest,
targetGeneration,
previousActiveLockDigest,
activeLockDigest,
state,
version: positiveInteger(
record.version,
'record version',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
),
lastMutationId: identifier(
record.lastMutationId,
'last mutation id',
InvalidPluginPackageInstallError,
),
lastMutationDigest: digest(
record.lastMutationDigest,
'last mutation digest',
InvalidPluginPackageInstallError,
),
stageReceipt,
activationReceipt,
failure,
createdAtMs,
updatedAtMs,
});
if (
!PACKAGE_NAME_PATTERN.test(unsigned.packageName) ||
semver().valid(unsigned.packageVersion) !== unsigned.packageVersion
) {
throw new InvalidPluginPackageInstallError(
'record package identity is invalid',
);
}
const recordDigest = digest(
record.recordDigest,
'record digest',
InvalidPluginPackageInstallError,
);
if (contentDigest(unsigned) !== recordDigest) {
throw new InvalidPluginPackageInstallError('record digest does not match');
}
return Object.freeze({ ...unsigned, recordDigest });
}
export function assertRecordMatchesLock(
record: Readonly<PluginPackageInstallRecord>,
lock: Readonly<PluginPackageLock>,
): void {
if (
record.projectId !== lock.projectId ||
record.packageName !== lock.packageName ||
record.packageVersion !== lock.packageVersion ||
record.operation !== lock.operation ||
record.lockDigest !== lock.lockDigest ||
record.targetGeneration !== lock.targetGeneration ||
record.previousActiveLockDigest !== (lock.previousLockDigest ?? null)
) {
throw new PluginPackageInstallTransitionConflictError();
}
}
export function assertPluginPackageInstallMatchesLock(
lockValue: PluginPackageLock,
recordValue: PluginPackageInstallRecord,
): void {
const lock = normalizePluginPackageLock(lockValue);
const record = normalizePluginPackageInstallRecord(recordValue);
assertRecordMatchesLock(record, lock);
}
@@ -0,0 +1,295 @@
import {
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
MAX_PLUGIN_PACKAGE_INSTALL_RECOVERY_PAGE_SIZE,
MAX_PLUGIN_PACKAGE_INSTALL_INVENTORY_PAGE_SIZE,
InvalidPluginPackageInstallError,
PluginPackageInstallTransitionConflictError,
type PluginPackageInstallRecoveryAction,
type PluginPackageLock,
type PluginPackageInstallRecord,
type PluginPackageInstallHeadExpectation,
type PluginPackageInstallCreate,
type PluginPackageInstallRecoveryCursor,
type PluginPackageInstallInventoryCursor,
} from './contracts';
import {
PACKAGE_NAME_PATTERN,
exactKeys,
installObject,
identifier,
boundedText,
digest,
positiveInteger,
contentDigest,
} from './codec';
import {
normalizePluginPackageLock,
} from './lock';
import {
initialMutationDigest,
normalizePluginPackageInstallRecord,
assertRecordMatchesLock,
} from './record';
export function normalizePluginPackageInstallHeadExpectation(
value: PluginPackageInstallHeadExpectation,
): Readonly<PluginPackageInstallHeadExpectation> {
const expectation = installObject(value, 'head expectation');
exactKeys(
expectation,
['installationId', 'version', 'recordDigest'],
[],
'head expectation',
InvalidPluginPackageInstallError,
);
return Object.freeze({
installationId: identifier(
value.installationId,
'head installation id',
InvalidPluginPackageInstallError,
),
version: positiveInteger(
value.version,
'head version',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
),
recordDigest: digest(
value.recordDigest,
'head record digest',
InvalidPluginPackageInstallError,
),
});
}
export function normalizePluginPackageInstallCreate(
value: PluginPackageInstallCreate,
): Readonly<PluginPackageInstallCreate> {
const command = installObject(value, 'create command');
exactKeys(
command,
[
'installationId',
'mutationId',
'mutationDigest',
'expectedHead',
'lock',
'record',
],
[],
'create command',
InvalidPluginPackageInstallError,
);
const lock = normalizePluginPackageLock(value.lock);
const record = normalizePluginPackageInstallRecord(value.record);
assertRecordMatchesLock(record, lock);
const expectedHead =
value.expectedHead === null
? null
: normalizePluginPackageInstallHeadExpectation(value.expectedHead);
const installationId = identifier(
value.installationId,
'installation id',
InvalidPluginPackageInstallError,
);
const mutationId = identifier(
value.mutationId,
'mutation id',
InvalidPluginPackageInstallError,
);
const mutationDigest = digest(
value.mutationDigest,
'create mutation digest',
InvalidPluginPackageInstallError,
);
if (
installationId !== record.installationId ||
mutationId !== record.lastMutationId ||
mutationDigest !==
contentDigest({
type: 'install_create_commit',
installationId,
mutationId,
lockDigest: lock.lockDigest,
recordDigest: record.recordDigest,
expectedHead,
})
) {
throw new InvalidPluginPackageInstallError(
'create command is detached from its record or head',
);
}
return Object.freeze({
installationId,
mutationId,
mutationDigest,
expectedHead,
lock,
record,
});
}
export function pluginPackageInstallRecoveryAction(
value: PluginPackageInstallRecord,
): PluginPackageInstallRecoveryAction {
const record = normalizePluginPackageInstallRecord(value);
switch (record.state) {
case 'queued':
return 'resume_stage';
case 'staged':
return 'resume_activation';
case 'activating':
return 'inspect_activation';
case 'active':
case 'failed':
return 'none';
}
}
export function assertPluginPackageInstallRecoveryPageSize(
value: number,
): void {
positiveInteger(
value,
'recovery page size',
MAX_PLUGIN_PACKAGE_INSTALL_RECOVERY_PAGE_SIZE,
InvalidPluginPackageInstallError,
);
}
export function assertPluginPackageInstallInventoryPageSize(
value: number,
): void {
positiveInteger(
value,
'inventory page size',
MAX_PLUGIN_PACKAGE_INSTALL_INVENTORY_PAGE_SIZE,
InvalidPluginPackageInstallError,
);
}
export function normalizePluginPackageInstallInventoryCursor(
value: PluginPackageInstallInventoryCursor,
): Readonly<PluginPackageInstallInventoryCursor> {
const cursor = installObject(value, 'inventory cursor');
exactKeys(
cursor,
['packageName'],
[],
'inventory cursor',
InvalidPluginPackageInstallError,
);
const normalizedPackageName = boundedText(
value.packageName,
'package name',
253,
InvalidPluginPackageInstallError,
);
if (!PACKAGE_NAME_PATTERN.test(normalizedPackageName)) {
throw new InvalidPluginPackageInstallError('package name is invalid');
}
return Object.freeze({ packageName: normalizedPackageName });
}
export function normalizePluginPackageInstallRecoveryCursor(
value: PluginPackageInstallRecoveryCursor,
): Readonly<PluginPackageInstallRecoveryCursor> {
const cursor = installObject(value, 'recovery cursor');
exactKeys(
cursor,
['packageName', 'installationId'],
[],
'recovery cursor',
InvalidPluginPackageInstallError,
);
const normalizedPackageName = boundedText(
value.packageName,
'package name',
253,
InvalidPluginPackageInstallError,
);
if (!PACKAGE_NAME_PATTERN.test(normalizedPackageName)) {
throw new InvalidPluginPackageInstallError('package name is invalid');
}
return Object.freeze({
packageName: normalizedPackageName,
installationId: identifier(
value.installationId,
'installation id',
InvalidPluginPackageInstallError,
),
});
}
export function pluginPackageInstallCreate(
lockValue: PluginPackageLock,
recordValue: PluginPackageInstallRecord,
previousHeadValue: PluginPackageInstallRecord | null,
): Readonly<PluginPackageInstallCreate> {
const lock = normalizePluginPackageLock(lockValue);
const record = normalizePluginPackageInstallRecord(recordValue);
assertRecordMatchesLock(record, lock);
const previousHead =
previousHeadValue === null
? null
: normalizePluginPackageInstallRecord(previousHeadValue);
if (
record.state !== 'queued' ||
record.version !== 1 ||
record.createdAtMs !== record.updatedAtMs ||
record.stageReceipt !== null ||
record.activationReceipt !== null ||
record.failure !== null ||
record.activeLockDigest !== record.previousActiveLockDigest ||
record.lastMutationDigest !==
initialMutationDigest(record.lockDigest, {
installationId: record.installationId,
mutationId: record.lastMutationId,
occurredAtMs: record.createdAtMs,
})
) {
throw new InvalidPluginPackageInstallError(
'initial install record is invalid',
);
}
if (previousHead === null) {
if (
record.previousActiveLockDigest !== null ||
record.operation !== 'install' ||
record.targetGeneration !== 1
) {
throw new PluginPackageInstallTransitionConflictError();
}
} else if (
previousHead.projectId !== record.projectId ||
previousHead.packageName !== record.packageName ||
previousHead.installationId === record.installationId ||
!['active', 'failed'].includes(previousHead.state) ||
previousHead.activeLockDigest !== record.previousActiveLockDigest
) {
throw new PluginPackageInstallTransitionConflictError();
}
const expectedHead =
previousHead === null
? null
: Object.freeze({
installationId: previousHead.installationId,
version: previousHead.version,
recordDigest: previousHead.recordDigest,
});
return normalizePluginPackageInstallCreate({
installationId: record.installationId,
mutationId: record.lastMutationId,
mutationDigest: contentDigest({
type: 'install_create_commit',
installationId: record.installationId,
mutationId: record.lastMutationId,
lockDigest: lock.lockDigest,
recordDigest: record.recordDigest,
expectedHead,
}),
expectedHead,
lock,
record,
});
}
@@ -0,0 +1,396 @@
import { createPluginPackageResourceGenerationFromReferences } from '../../pluginPackageResourceGeneration';
import {
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS,
InvalidPluginPackageInstallError,
PluginPackageInstallTransitionConflictError,
PluginPackageInstallMutationConflictError,
type PluginPackageInstallState,
type PluginPackageInstallFailureReason,
type PluginPackageLock,
type PluginPackageStageReceipt,
type PluginPackageActivationReceipt,
type PluginPackageInstallFailure,
type PluginPackageInstallRecord,
type PluginPackageInstallEvent,
type PluginPackageInstallCommit,
} from './contracts';
import {
exactKeys,
installObject,
identifier,
digest,
timestamp,
positiveInteger,
contentDigest,
} from './codec';
import { normalizePluginPackageLock } from './lock';
import {
initialMutationDigest,
withRecordDigest,
normalizePluginPackageInstallRecord,
assertRecordMatchesLock,
} from './record';
export function normalizeEvent(
value: PluginPackageInstallEvent,
): Readonly<PluginPackageInstallEvent> {
const event = installObject(value, 'event');
if (
![
'stage_completed',
'activation_started',
'activation_committed',
'failed',
].includes(event.type as string)
) {
throw new InvalidPluginPackageInstallError('event type is invalid');
}
const common = {
type: event.type,
mutationId: identifier(
event.mutationId,
'mutation id',
InvalidPluginPackageInstallError,
),
occurredAtMs: timestamp(
event.occurredAtMs,
'event time',
InvalidPluginPackageInstallError,
),
};
switch (event.type) {
case 'stage_completed':
exactKeys(
event,
[
'type',
'mutationId',
'occurredAtMs',
'stageRef',
'artifactDigest',
'manifestDigest',
'contentDigest',
'evidenceDigest',
],
[],
'stage event',
InvalidPluginPackageInstallError,
);
return Object.freeze({
...common,
type: 'stage_completed',
stageRef: identifier(
event.stageRef,
'stage reference',
InvalidPluginPackageInstallError,
),
artifactDigest: digest(
event.artifactDigest,
'staged artifact digest',
InvalidPluginPackageInstallError,
),
manifestDigest: digest(
event.manifestDigest,
'staged manifest digest',
InvalidPluginPackageInstallError,
),
contentDigest: digest(
event.contentDigest,
'staged content digest',
InvalidPluginPackageInstallError,
),
evidenceDigest: digest(
event.evidenceDigest,
'staged evidence digest',
InvalidPluginPackageInstallError,
),
});
case 'activation_started':
exactKeys(
event,
['type', 'mutationId', 'occurredAtMs'],
[],
'activation start event',
InvalidPluginPackageInstallError,
);
return Object.freeze({ ...common, type: 'activation_started' });
case 'activation_committed':
exactKeys(
event,
[
'type',
'mutationId',
'occurredAtMs',
'activationRef',
'intentDigest',
'generation',
'contentDigest',
],
[],
'activation commit event',
InvalidPluginPackageInstallError,
);
return Object.freeze({
...common,
type: 'activation_committed',
activationRef: identifier(
event.activationRef,
'activation reference',
InvalidPluginPackageInstallError,
),
intentDigest: digest(
event.intentDigest,
'activation intent digest',
InvalidPluginPackageInstallError,
),
generation: positiveInteger(
event.generation,
'activation generation',
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
InvalidPluginPackageInstallError,
),
contentDigest: digest(
event.contentDigest,
'activated content digest',
InvalidPluginPackageInstallError,
),
});
case 'failed':
exactKeys(
event,
['type', 'mutationId', 'occurredAtMs', 'reason'],
[],
'failure event',
InvalidPluginPackageInstallError,
);
if (
!PLUGIN_PACKAGE_INSTALL_FAILURE_REASONS.includes(
event.reason as PluginPackageInstallFailureReason,
)
) {
throw new InvalidPluginPackageInstallError('failure reason is invalid');
}
return Object.freeze({
...common,
type: 'failed',
reason: event.reason as PluginPackageInstallFailureReason,
});
default:
throw new InvalidPluginPackageInstallError('event type is invalid');
}
}
export function eventDigest(event: Readonly<PluginPackageInstallEvent>): string {
return contentDigest(event);
}
export function makeStageReceipt(
event: Extract<PluginPackageInstallEvent, { type: 'stage_completed' }>,
): Readonly<PluginPackageStageReceipt> {
const unsigned = Object.freeze({
stageRef: event.stageRef,
artifactDigest: event.artifactDigest,
manifestDigest: event.manifestDigest,
contentDigest: event.contentDigest,
evidenceDigest: event.evidenceDigest,
stagedAtMs: event.occurredAtMs,
});
return Object.freeze({
...unsigned,
receiptDigest: contentDigest(unsigned),
});
}
export function makeActivationReceipt(
event: Extract<PluginPackageInstallEvent, { type: 'activation_committed' }>,
): Readonly<PluginPackageActivationReceipt> {
const unsigned = Object.freeze({
activationRef: event.activationRef,
intentDigest: event.intentDigest,
generation: event.generation,
contentDigest: event.contentDigest,
activatedAtMs: event.occurredAtMs,
});
return Object.freeze({
...unsigned,
receiptDigest: contentDigest(unsigned),
});
}
export function activationIntentDigest(
lock: Readonly<PluginPackageLock>,
record: Readonly<PluginPackageInstallRecord>,
): string {
if (record.state !== 'activating' || record.stageReceipt === null) {
throw new PluginPackageInstallTransitionConflictError();
}
const resourceGeneration =
createPluginPackageResourceGenerationFromReferences({
installationId: record.installationId,
projectId: record.projectId,
packageName: record.packageName,
lockDigest: lock.lockDigest,
generation: lock.targetGeneration,
previousActiveLockDigest: record.previousActiveLockDigest,
contentDigest: lock.source.contentDigest,
resources: lock.resources,
});
return contentDigest({
type: 'plugin_package_activation_intent',
installationId: record.installationId,
projectId: record.projectId,
packageName: record.packageName,
lockDigest: lock.lockDigest,
targetGeneration: lock.targetGeneration,
previousActiveLockDigest: record.previousActiveLockDigest,
stageRef: record.stageReceipt.stageRef,
stageReceiptDigest: record.stageReceipt.receiptDigest,
stageEvidenceDigest: record.stageReceipt.evidenceDigest,
contentDigest: lock.source.contentDigest,
resourceGenerationDigest: resourceGeneration.generationDigest,
});
}
export function pluginPackageActivationIntentDigest(
lockValue: PluginPackageLock,
recordValue: PluginPackageInstallRecord,
): string {
const lock = normalizePluginPackageLock(lockValue);
const record = normalizePluginPackageInstallRecord(recordValue);
assertRecordMatchesLock(record, lock);
return activationIntentDigest(lock, record);
}
export function transitionPluginPackageInstall(
lockValue: PluginPackageLock,
recordValue: PluginPackageInstallRecord,
eventValue: PluginPackageInstallEvent,
): Readonly<PluginPackageInstallRecord> {
const lock = normalizePluginPackageLock(lockValue);
const record = normalizePluginPackageInstallRecord(recordValue);
const event = normalizeEvent(eventValue);
assertRecordMatchesLock(record, lock);
const mutationDigest = eventDigest(event);
if (record.lastMutationId === event.mutationId) {
if (record.lastMutationDigest !== mutationDigest) {
throw new PluginPackageInstallMutationConflictError();
}
return record;
}
if (
event.occurredAtMs < record.updatedAtMs ||
record.version >= MAX_PLUGIN_PACKAGE_INSTALL_VERSION
) {
throw new PluginPackageInstallTransitionConflictError();
}
if (
event.type === 'stage_completed' &&
(record.state !== 'queued' ||
event.artifactDigest !== lock.source.artifactDigest ||
event.manifestDigest !== lock.manifestDigest ||
event.contentDigest !== lock.source.contentDigest)
) {
throw new PluginPackageInstallTransitionConflictError();
}
if (event.type === 'activation_started' && record.state !== 'staged') {
throw new PluginPackageInstallTransitionConflictError();
}
if (
event.type === 'activation_committed' &&
(record.state !== 'activating' ||
event.intentDigest !== activationIntentDigest(lock, record) ||
event.generation !== lock.targetGeneration ||
event.contentDigest !== lock.source.contentDigest)
) {
throw new PluginPackageInstallTransitionConflictError();
}
if (
event.type === 'failed' &&
!['queued', 'staged', 'activating'].includes(record.state)
) {
throw new PluginPackageInstallTransitionConflictError();
}
let state: PluginPackageInstallState;
let stageReceipt = record.stageReceipt;
let activationReceipt = record.activationReceipt;
let failure = record.failure;
let activeLockDigest = record.activeLockDigest;
switch (event.type) {
case 'stage_completed':
state = 'staged';
stageReceipt = makeStageReceipt(event);
break;
case 'activation_started':
state = 'activating';
break;
case 'activation_committed':
state = 'active';
activationReceipt = makeActivationReceipt(event);
activeLockDigest = lock.lockDigest;
break;
case 'failed':
state = 'failed';
failure = Object.freeze({
reason: event.reason,
failedFrom: record.state as PluginPackageInstallFailure['failedFrom'],
failedAtMs: event.occurredAtMs,
});
break;
}
const { recordDigest: _previousRecordDigest, ...recordFields } = record;
return withRecordDigest({
...recordFields,
state,
version: record.version + 1,
lastMutationId: event.mutationId,
lastMutationDigest: mutationDigest,
stageReceipt,
activationReceipt,
failure,
activeLockDigest,
updatedAtMs: event.occurredAtMs,
});
}
export function pluginPackageInstallCommit(
previousValue: PluginPackageInstallRecord,
nextValue: PluginPackageInstallRecord,
): Readonly<PluginPackageInstallCommit> {
const previous = normalizePluginPackageInstallRecord(previousValue);
const next = normalizePluginPackageInstallRecord(nextValue);
const validNextStates: Readonly<
Record<PluginPackageInstallState, readonly PluginPackageInstallState[]>
> = {
queued: ['staged', 'failed'],
staged: ['activating', 'failed'],
activating: ['active', 'failed'],
active: [],
failed: [],
};
if (
next.installationId !== previous.installationId ||
next.version !== previous.version + 1 ||
next.createdAtMs !== previous.createdAtMs ||
next.projectId !== previous.projectId ||
next.packageName !== previous.packageName ||
next.packageVersion !== previous.packageVersion ||
next.operation !== previous.operation ||
next.lockDigest !== previous.lockDigest ||
next.targetGeneration !== previous.targetGeneration ||
next.previousActiveLockDigest !== previous.previousActiveLockDigest ||
!validNextStates[previous.state].includes(next.state)
) {
throw new PluginPackageInstallTransitionConflictError();
}
return Object.freeze({
installationId: next.installationId,
expectedVersion: previous.version,
expectedRecordDigest: previous.recordDigest,
mutationId: next.lastMutationId,
mutationDigest: next.lastMutationDigest,
record: next,
});
}
@@ -0,0 +1,615 @@
import {
InvalidPluginPackageInstallError,
MAX_PLUGIN_PACKAGE_INSTALL_VERSION,
PluginPackageInstallTransitionConflictError,
PluginPackageInstallUnavailableError,
assertPluginPackageInstallMatchesLock,
normalizePluginPackageActivationReceipt,
normalizePluginPackageInstallRecord,
normalizePluginPackageLock,
pluginPackageActivationIntentDigest,
pluginPackageInstallCommit,
transitionPluginPackageInstall,
type PluginPackageActivationReceipt,
type PluginPackageInstallRecord,
type PluginPackageInstallRepository,
type PluginPackageLock,
} from './pluginPackageInstall';
import {
createPluginPackageResourceGenerationFromReferences,
normalizePluginPackageResourceGeneration,
type PluginPackageResourceGeneration,
} from '../pluginPackageResourceGeneration';
export const PLUGIN_PACKAGE_ACTIVATION_INTENT_SCHEMA =
'qinglong/plugin-package-activation-intent@v2' as const;
export interface PluginPackageActivationIntent {
readonly schema: typeof PLUGIN_PACKAGE_ACTIVATION_INTENT_SCHEMA;
readonly installationId: string;
readonly projectId: string;
readonly packageName: string;
readonly lockDigest: string;
readonly targetGeneration: number;
readonly previousActiveLockDigest: string | null;
readonly stageRef: string;
readonly stageReceiptDigest: string;
readonly stageEvidenceDigest: string;
readonly contentDigest: string;
readonly resourceGeneration: Readonly<PluginPackageResourceGeneration>;
readonly intentDigest: string;
}
export type PluginPackageActivationObservation =
| Readonly<{ status: 'not_published' }>
| Readonly<{
status: 'published';
receipt: Readonly<PluginPackageActivationReceipt>;
}>;
export interface PluginPackageActivationPublisher {
inspect(
intent: Readonly<PluginPackageActivationIntent>,
): Promise<Readonly<PluginPackageActivationObservation>>;
publish(
intent: Readonly<PluginPackageActivationIntent>,
): Promise<Readonly<PluginPackageActivationReceipt>>;
}
export interface ActivatePluginPackageOptions {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly activationStartedMutationId: string;
readonly activationCommittedMutationId: string;
readonly startedAtMs: number;
}
export interface InspectPluginPackageActivationOptions {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly activationCommittedMutationId: string;
readonly activationFailedMutationId: string;
readonly observedAtMs: number;
}
export class PluginPackageActivationConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_ACTIVATION_CONFLICT';
constructor() {
super('Plugin Package activation fact conflicts with durable intent');
this.name = 'PluginPackageActivationConflictError';
}
}
export class PluginPackageActivationUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_ACTIVATION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package activation authority is unavailable', options);
this.name = 'PluginPackageActivationUnavailableError';
}
}
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PACKAGE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageInstallError(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
throw new InvalidPluginPackageInstallError(
`${label} must contain enumerable data properties`,
);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageInstallError(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value as number;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value;
}
function normalizeIdentity(value: {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
}): Readonly<{
projectId: string;
packageName: string;
installationId: string;
}> {
const projectId = identifier(value.projectId, 'project id');
const packageName = value.packageName;
if (
typeof packageName !== 'string' ||
!PACKAGE_NAME_PATTERN.test(packageName)
) {
throw new InvalidPluginPackageInstallError('package name is invalid');
}
return Object.freeze({
projectId,
packageName,
installationId: identifier(value.installationId, 'installation id'),
});
}
export function createPluginPackageActivationIntent(
lockValue: PluginPackageLock,
recordValue: PluginPackageInstallRecord,
): Readonly<PluginPackageActivationIntent> {
const lock = normalizePluginPackageLock(lockValue);
const record = normalizePluginPackageInstallRecord(recordValue);
const intentDigest = pluginPackageActivationIntentDigest(lock, record);
if (record.stageReceipt === null) {
throw new PluginPackageInstallTransitionConflictError();
}
const resourceGeneration =
createPluginPackageResourceGenerationFromReferences({
installationId: record.installationId,
projectId: record.projectId,
packageName: record.packageName,
lockDigest: lock.lockDigest,
generation: lock.targetGeneration,
previousActiveLockDigest: record.previousActiveLockDigest,
contentDigest: lock.source.contentDigest,
resources: lock.resources,
});
return Object.freeze({
schema: PLUGIN_PACKAGE_ACTIVATION_INTENT_SCHEMA,
installationId: record.installationId,
projectId: record.projectId,
packageName: record.packageName,
lockDigest: lock.lockDigest,
targetGeneration: lock.targetGeneration,
previousActiveLockDigest: record.previousActiveLockDigest,
stageRef: record.stageReceipt.stageRef,
stageReceiptDigest: record.stageReceipt.receiptDigest,
stageEvidenceDigest: record.stageReceipt.evidenceDigest,
contentDigest: lock.source.contentDigest,
resourceGeneration,
intentDigest,
});
}
export function normalizePluginPackageActivationIntent(
value: unknown,
): Readonly<PluginPackageActivationIntent> {
const intent = dataRecord(value, 'activation intent');
exactKeys(
intent,
[
'schema',
'installationId',
'projectId',
'packageName',
'lockDigest',
'targetGeneration',
'previousActiveLockDigest',
'stageRef',
'stageReceiptDigest',
'stageEvidenceDigest',
'contentDigest',
'resourceGeneration',
'intentDigest',
],
'activation intent',
);
if (intent.schema !== PLUGIN_PACKAGE_ACTIVATION_INTENT_SCHEMA) {
throw new InvalidPluginPackageInstallError(
'activation intent schema is invalid',
);
}
const identity = normalizeIdentity({
projectId: intent.projectId as string,
packageName: intent.packageName as string,
installationId: intent.installationId as string,
});
const targetGeneration = timestamp(
intent.targetGeneration,
'activation target generation',
);
if (
targetGeneration < 1 ||
targetGeneration > MAX_PLUGIN_PACKAGE_INSTALL_VERSION
) {
throw new InvalidPluginPackageInstallError(
'activation target generation is invalid',
);
}
const previousActiveLockDigest =
intent.previousActiveLockDigest === null
? null
: digest(
intent.previousActiveLockDigest,
'activation previous lock digest',
);
const lockDigest = digest(intent.lockDigest, 'activation lock digest');
const contentDigest = digest(
intent.contentDigest,
'activation content digest',
);
const resourceGeneration = normalizePluginPackageResourceGeneration(
intent.resourceGeneration,
);
if (
resourceGeneration.installationId !== identity.installationId ||
resourceGeneration.projectId !== identity.projectId ||
resourceGeneration.packageName !== identity.packageName ||
resourceGeneration.lockDigest !== lockDigest ||
resourceGeneration.generation !== targetGeneration ||
resourceGeneration.previousActiveLockDigest !== previousActiveLockDigest ||
resourceGeneration.contentDigest !== contentDigest
) {
throw new InvalidPluginPackageInstallError(
'activation resource generation does not match its intent',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_ACTIVATION_INTENT_SCHEMA,
...identity,
lockDigest,
targetGeneration,
previousActiveLockDigest,
stageRef: identifier(intent.stageRef, 'activation stage reference'),
stageReceiptDigest: digest(
intent.stageReceiptDigest,
'activation stage receipt digest',
),
stageEvidenceDigest: digest(
intent.stageEvidenceDigest,
'activation stage evidence digest',
),
contentDigest,
resourceGeneration,
intentDigest: digest(intent.intentDigest, 'activation intent digest'),
});
}
function normalizePublishedReceipt(
intent: Readonly<PluginPackageActivationIntent>,
value: PluginPackageActivationReceipt,
): Readonly<PluginPackageActivationReceipt> {
const receipt = normalizePluginPackageActivationReceipt(value);
if (
receipt.intentDigest !== intent.intentDigest ||
receipt.generation !== intent.targetGeneration ||
receipt.contentDigest !== intent.contentDigest
) {
throw new PluginPackageActivationConflictError();
}
return receipt;
}
function normalizeObservation(
intent: Readonly<PluginPackageActivationIntent>,
value: PluginPackageActivationObservation,
): Readonly<PluginPackageActivationObservation> {
const observation = dataRecord(value, 'activation observation');
if (observation.status === 'not_published') {
exactKeys(observation, ['status'], 'activation observation');
return Object.freeze({ status: 'not_published' });
}
if (observation.status === 'published') {
exactKeys(observation, ['status', 'receipt'], 'activation observation');
return Object.freeze({
status: 'published',
receipt: normalizePublishedReceipt(
intent,
(
value as Extract<
PluginPackageActivationObservation,
{ status: 'published' }
>
).receipt,
),
});
}
throw new InvalidPluginPackageInstallError(
'activation observation status is invalid',
);
}
function unavailable(error: unknown): PluginPackageActivationUnavailableError {
if (error instanceof PluginPackageActivationUnavailableError) return error;
return new PluginPackageActivationUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
export class PluginPackageActivationCoordinator {
readonly #repository: PluginPackageInstallRepository;
readonly #publisher: PluginPackageActivationPublisher;
constructor(options: {
readonly repository: PluginPackageInstallRepository;
readonly publisher: PluginPackageActivationPublisher;
}) {
const value = dataRecord(options, 'activation coordinator options');
exactKeys(
value,
['repository', 'publisher'],
'activation coordinator options',
);
if (
!options.repository ||
typeof options.repository.find !== 'function' ||
typeof options.repository.findLock !== 'function' ||
typeof options.repository.commit !== 'function' ||
!options.publisher ||
typeof options.publisher.inspect !== 'function' ||
typeof options.publisher.publish !== 'function'
) {
throw new InvalidPluginPackageInstallError(
'activation coordinator authority is invalid',
);
}
this.#repository = options.repository;
this.#publisher = options.publisher;
}
async #load(
identity: Readonly<{
projectId: string;
packageName: string;
installationId: string;
}>,
): Promise<
Readonly<{
lock: Readonly<PluginPackageLock>;
record: Readonly<PluginPackageInstallRecord>;
}>
> {
const record = await this.#repository.find(
identity.projectId,
identity.packageName,
);
if (!record || record.installationId !== identity.installationId) {
throw new PluginPackageInstallTransitionConflictError();
}
const lock = await this.#repository.findLock(record.lockDigest);
if (!lock) throw new PluginPackageInstallUnavailableError();
assertPluginPackageInstallMatchesLock(lock, record);
return Object.freeze({ lock, record });
}
async #commitPublished(
lock: Readonly<PluginPackageLock>,
record: Readonly<PluginPackageInstallRecord>,
receipt: Readonly<PluginPackageActivationReceipt>,
mutationId: string,
): Promise<Readonly<PluginPackageInstallRecord>> {
const next = transitionPluginPackageInstall(lock, record, {
type: 'activation_committed',
mutationId,
occurredAtMs: receipt.activatedAtMs,
activationRef: receipt.activationRef,
intentDigest: receipt.intentDigest,
generation: receipt.generation,
contentDigest: receipt.contentDigest,
});
return (
await this.#repository.commit(pluginPackageInstallCommit(record, next))
).record;
}
async #commitFailure(
lock: Readonly<PluginPackageLock>,
record: Readonly<PluginPackageInstallRecord>,
mutationId: string,
occurredAtMs: number,
reason: 'activation_failed' | 'activation_fact_conflict',
): Promise<Readonly<PluginPackageInstallRecord>> {
const next = transitionPluginPackageInstall(lock, record, {
type: 'failed',
mutationId,
occurredAtMs,
reason,
});
return (
await this.#repository.commit(pluginPackageInstallCommit(record, next))
).record;
}
async activate(
options: ActivatePluginPackageOptions,
): Promise<Readonly<PluginPackageInstallRecord>> {
const value = dataRecord(options, 'activation options');
exactKeys(
value,
[
'projectId',
'packageName',
'installationId',
'activationStartedMutationId',
'activationCommittedMutationId',
'startedAtMs',
],
'activation options',
);
const identity = normalizeIdentity(options);
const activationStartedMutationId = identifier(
options.activationStartedMutationId,
'activation started mutation id',
);
const activationCommittedMutationId = identifier(
options.activationCommittedMutationId,
'activation committed mutation id',
);
const startedAtMs = timestamp(options.startedAtMs, 'activation start time');
const loaded = await this.#load(identity);
if (loaded.record.state !== 'staged') {
if (
loaded.record.state === 'active' ||
loaded.record.state === 'failed'
) {
return loaded.record;
}
throw new PluginPackageInstallTransitionConflictError();
}
const activating = transitionPluginPackageInstall(
loaded.lock,
loaded.record,
{
type: 'activation_started',
mutationId: activationStartedMutationId,
occurredAtMs: startedAtMs,
},
);
const durable = (
await this.#repository.commit(
pluginPackageInstallCommit(loaded.record, activating),
)
).record;
if (durable.state === 'active' || durable.state === 'failed')
return durable;
if (durable.state !== 'activating') {
throw new PluginPackageInstallTransitionConflictError();
}
const intent = createPluginPackageActivationIntent(loaded.lock, durable);
let receipt: Readonly<PluginPackageActivationReceipt>;
try {
receipt = normalizePublishedReceipt(
intent,
await this.#publisher.publish(intent),
);
} catch (error) {
if (error instanceof PluginPackageActivationConflictError) {
return this.#commitFailure(
loaded.lock,
durable,
activationCommittedMutationId,
startedAtMs,
'activation_fact_conflict',
);
}
throw unavailable(error);
}
return this.#commitPublished(
loaded.lock,
durable,
receipt,
activationCommittedMutationId,
);
}
async inspect(
options: InspectPluginPackageActivationOptions,
): Promise<Readonly<PluginPackageInstallRecord>> {
const value = dataRecord(options, 'activation inspection options');
exactKeys(
value,
[
'projectId',
'packageName',
'installationId',
'activationCommittedMutationId',
'activationFailedMutationId',
'observedAtMs',
],
'activation inspection options',
);
const identity = normalizeIdentity(options);
const activationCommittedMutationId = identifier(
options.activationCommittedMutationId,
'activation committed mutation id',
);
const activationFailedMutationId = identifier(
options.activationFailedMutationId,
'activation failed mutation id',
);
const observedAtMs = timestamp(options.observedAtMs, 'observation time');
const loaded = await this.#load(identity);
if (loaded.record.state === 'active' || loaded.record.state === 'failed') {
return loaded.record;
}
if (loaded.record.state !== 'activating') {
throw new PluginPackageInstallTransitionConflictError();
}
const intent = createPluginPackageActivationIntent(
loaded.lock,
loaded.record,
);
let observation: Readonly<PluginPackageActivationObservation>;
try {
observation = normalizeObservation(
intent,
await this.#publisher.inspect(intent),
);
} catch (error) {
if (error instanceof PluginPackageActivationConflictError) {
return this.#commitFailure(
loaded.lock,
loaded.record,
activationFailedMutationId,
observedAtMs,
'activation_fact_conflict',
);
}
throw unavailable(error);
}
if (observation.status === 'not_published') {
return this.#commitFailure(
loaded.lock,
loaded.record,
activationFailedMutationId,
observedAtMs,
'activation_failed',
);
}
return this.#commitPublished(
loaded.lock,
loaded.record,
observation.receipt,
activationCommittedMutationId,
);
}
}
@@ -0,0 +1,524 @@
import { createHash } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import {
approvedActionDispatchDigest,
normalizeApprovedActionDispatchRecord,
type ApprovedActionDispatchRecord,
} from '../../approved-action/approvedAction';
import {
normalizeApprovedActionExecutionRecord,
type ApprovedActionExecutionRecord,
} from '../../approved-action/approvedActionExecution';
import {
createPluginPackageInstall,
normalizePluginPackageInstallCreate,
normalizePluginPackageInstallRecord,
normalizePluginPackageLock,
pluginPackageInstallCreate,
type PluginPackageInstallCreate,
type PluginPackageInstallRecord,
type PluginPackageInstallRepository,
type PluginPackageLock,
} from './pluginPackageInstall';
import {
normalizePluginPackageInstallProposal,
resolvePluginPackageInstallProposal,
type PluginPackageInstallProposal,
} from '../pluginPackageProposal';
import {
normalizeSecurityAuditRecord,
type SecurityAuditRecord,
} from '../../security/audit/securityAudit';
export const PLUGIN_PACKAGE_INSTALL_ACTION_TYPE =
'plugin_package.install' as const;
export const PLUGIN_PACKAGE_ADMISSION_RECEIPT_SCHEMA =
'qinglong/plugin-package-admission-receipt@v1' as const;
export const PLUGIN_PACKAGE_ADMISSION_AUDIT_OPERATION =
'plugin_package.admit' as const;
export const PLUGIN_PACKAGE_ADMISSION_AUDIT_REASON =
'approved_action' as const;
export interface PluginPackageAdmissionRequest {
readonly lock: PluginPackageLock;
readonly proposalDigest: string;
readonly execution: ApprovedActionExecutionRecord;
readonly installationId: string;
readonly mutationId: string;
readonly admittedAtMs: number;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageAdmissionReceipt {
readonly schema: typeof PLUGIN_PACKAGE_ADMISSION_RECEIPT_SCHEMA;
readonly dispatchId: string;
readonly dispatchDigest: string;
readonly approvalRequestId: string;
readonly actionRef: string;
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly lockDigest: string;
readonly recordDigest: string;
readonly mutationId: string;
readonly mutationDigest: string;
readonly auditEventId: string;
readonly admittedAtMs: number;
readonly receiptDigest: string;
}
export interface BoundPluginPackageAdmission {
readonly create: Readonly<PluginPackageInstallCreate>;
readonly receipt: Readonly<PluginPackageAdmissionReceipt>;
}
export interface PluginPackageAdmissionResult {
readonly status: 'admitted' | 'existing';
readonly record: Readonly<PluginPackageInstallRecord>;
readonly receipt: Readonly<PluginPackageAdmissionReceipt>;
}
export interface PluginPackageAdmissionRepository
extends PluginPackageInstallRepository {
findAdmissionReceipt(
dispatchId: string,
): Promise<Readonly<PluginPackageAdmissionReceipt> | null>;
admit(
request: PluginPackageAdmissionRequest,
): Promise<Readonly<PluginPackageAdmissionResult>>;
}
export class InvalidPluginPackageAdmissionError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_ADMISSION_INVALID';
constructor(message: string) {
super(`Plugin Package admission is invalid: ${message}`);
this.name = 'InvalidPluginPackageAdmissionError';
}
}
export class PluginPackageAdmissionBindingConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_ADMISSION_BINDING_CONFLICT';
constructor() {
super('Plugin Package admission does not match its approved dispatch');
this.name = 'PluginPackageAdmissionBindingConflictError';
}
}
export class PluginPackageAdmissionReceiptConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_ADMISSION_RECEIPT_CONFLICT';
constructor() {
super('Plugin Package admission conflicts with its durable receipt');
this.name = 'PluginPackageAdmissionReceiptConflictError';
}
}
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const PACKAGE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageAdmissionError(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageAdmissionError(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new InvalidPluginPackageAdmissionError(`${label} is invalid`);
}
return value;
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
throw new InvalidPluginPackageAdmissionError(
'approved action reference is invalid',
);
}
return value;
}
function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME_PATTERN.test(value)) {
throw new InvalidPluginPackageAdmissionError('package name is invalid');
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidPluginPackageAdmissionError(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidPluginPackageAdmissionError(`${label} is invalid`);
}
return value as number;
}
function same(left: unknown, right: unknown): boolean {
return isDeepStrictEqual(left, right);
}
function contractDigest(domain: string, value: unknown): string {
return createHash('sha256')
.update(domain)
.update('\0')
.update(JSON.stringify(value))
.digest('hex');
}
function receiptWithoutDigest(
value: Omit<PluginPackageAdmissionReceipt, 'receiptDigest'>,
): Omit<PluginPackageAdmissionReceipt, 'receiptDigest'> {
return Object.freeze(value);
}
function withReceiptDigest(
value: Omit<PluginPackageAdmissionReceipt, 'receiptDigest'>,
): Readonly<PluginPackageAdmissionReceipt> {
const normalized = receiptWithoutDigest(value);
return Object.freeze({
...normalized,
receiptDigest: contractDigest(
'qinglong/plugin-package-admission-receipt-digest@v1',
normalized,
),
});
}
function assertAuditBinding(
dispatch: Readonly<ApprovedActionDispatchRecord>,
audit: Readonly<SecurityAuditRecord>,
admittedAtMs: number,
): void {
if (
audit.requestId !== dispatch.id ||
audit.operationId !== PLUGIN_PACKAGE_ADMISSION_AUDIT_OPERATION ||
audit.projectId !== dispatch.projectId ||
audit.subject?.type !== dispatch.consumedBy.type ||
audit.subject.id !== dispatch.consumedBy.id ||
audit.authenticationId === null ||
audit.outcome !== 'allowed' ||
!same(audit.reasons, [PLUGIN_PACKAGE_ADMISSION_AUDIT_REASON]) ||
audit.fence?.projectVersion !== dispatch.approvalFence.projectVersion ||
audit.fence.bindingVersion !== dispatch.approvalFence.bindingVersion ||
audit.occurredAtMs !== admittedAtMs
) {
throw new PluginPackageAdmissionBindingConflictError();
}
}
function assertDispatchBinding(
dispatch: Readonly<ApprovedActionDispatchRecord>,
lock: Readonly<PluginPackageLock>,
admittedAtMs: number,
): void {
const approval = lock.approval;
if (
dispatch.id !== approval.dispatchId ||
dispatch.approvalRequestId !== approval.requestId ||
approval.requestVersion !== 3 ||
dispatch.projectId !== lock.projectId ||
dispatch.action.permission !== 'package.manage' ||
dispatch.action.actionType !== PLUGIN_PACKAGE_INSTALL_ACTION_TYPE ||
dispatch.action.actionDigest !== lock.actionDigest ||
dispatch.action.previewDigest !== lock.planDigest ||
dispatch.action.actionDigest !== approval.actionDigest ||
dispatch.action.previewDigest !== approval.previewDigest ||
dispatch.approvedBy.type !== approval.approvedBy.type ||
dispatch.approvedBy.id !== approval.approvedBy.id ||
dispatch.approvedAtMs !== approval.approvedAtMs ||
dispatch.expiresAtMs !== approval.expiresAtMs ||
dispatch.approvalFence.projectVersion !==
approval.fence.projectVersion ||
dispatch.approvalFence.bindingVersion !==
approval.fence.bindingVersion ||
admittedAtMs < dispatch.createdAtMs ||
admittedAtMs < lock.createdAtMs ||
admittedAtMs >= dispatch.expiresAtMs
) {
throw new PluginPackageAdmissionBindingConflictError();
}
}
function assertProposalBinding(
dispatch: Readonly<ApprovedActionDispatchRecord>,
proposalValue: PluginPackageInstallProposal,
request: Readonly<PluginPackageAdmissionRequest>,
): void {
const proposal = normalizePluginPackageInstallProposal(proposalValue);
let resolved: Readonly<PluginPackageLock>;
try {
resolved = resolvePluginPackageInstallProposal(
proposal,
dispatch,
request.lock.createdAtMs,
);
} catch {
throw new PluginPackageAdmissionBindingConflictError();
}
if (
proposal.proposalDigest !== request.proposalDigest ||
!same(resolved, request.lock)
) {
throw new PluginPackageAdmissionBindingConflictError();
}
}
function assertExecutionBinding(
dispatch: Readonly<ApprovedActionDispatchRecord>,
currentExecutionValue: ApprovedActionExecutionRecord,
request: Readonly<PluginPackageAdmissionRequest>,
observedAtMs: number,
): void {
const currentExecution = normalizeApprovedActionExecutionRecord(
currentExecutionValue,
);
const expectedExecution = request.execution;
if (
!same(currentExecution, expectedExecution) ||
currentExecution.dispatchId !== dispatch.id ||
currentExecution.dispatchDigest !== approvedActionDispatchDigest(dispatch) ||
currentExecution.projectId !== dispatch.projectId ||
currentExecution.status !== 'executing' ||
currentExecution.startedAtMs === null ||
currentExecution.leaseOwner === null ||
currentExecution.leaseToken === null ||
currentExecution.leaseExpiresAtMs === null ||
request.admittedAtMs < currentExecution.startedAtMs ||
request.admittedAtMs >= currentExecution.leaseExpiresAtMs ||
observedAtMs < currentExecution.startedAtMs ||
observedAtMs >= currentExecution.leaseExpiresAtMs
) {
throw new PluginPackageAdmissionBindingConflictError();
}
}
export function normalizePluginPackageAdmissionRequest(
value: PluginPackageAdmissionRequest,
): Readonly<PluginPackageAdmissionRequest> {
const request = dataRecord(value, 'request');
exactKeys(
request,
[
'lock',
'proposalDigest',
'execution',
'installationId',
'mutationId',
'admittedAtMs',
'audit',
],
'request',
);
const execution = normalizeApprovedActionExecutionRecord(value.execution);
if (execution.status !== 'executing') {
throw new InvalidPluginPackageAdmissionError(
'execution has not crossed the start barrier',
);
}
return Object.freeze({
lock: normalizePluginPackageLock(value.lock),
proposalDigest: digest(value.proposalDigest, 'proposal digest'),
execution,
installationId: identifier(value.installationId, 'installation id'),
mutationId: identifier(value.mutationId, 'mutation id'),
admittedAtMs: timestamp(value.admittedAtMs, 'admission time'),
audit: normalizeSecurityAuditRecord(value.audit),
});
}
export function bindPluginPackageAdmission(
dispatchValue: ApprovedActionDispatchRecord,
proposalValue: PluginPackageInstallProposal,
currentExecutionValue: ApprovedActionExecutionRecord,
requestValue: PluginPackageAdmissionRequest,
previousHeadValue: PluginPackageInstallRecord | null,
observedAtMsValue: number,
): Readonly<BoundPluginPackageAdmission> {
const dispatch = normalizeApprovedActionDispatchRecord(dispatchValue);
const request = normalizePluginPackageAdmissionRequest(requestValue);
const observedAtMs = timestamp(observedAtMsValue, 'observed admission time');
const previousHead =
previousHeadValue === null
? null
: normalizePluginPackageInstallRecord(previousHeadValue);
assertDispatchBinding(dispatch, request.lock, request.admittedAtMs);
assertProposalBinding(dispatch, proposalValue, request);
assertExecutionBinding(
dispatch,
currentExecutionValue,
request,
observedAtMs,
);
assertAuditBinding(dispatch, request.audit, request.admittedAtMs);
const record = createPluginPackageInstall(request.lock, {
installationId: request.installationId,
mutationId: request.mutationId,
occurredAtMs: request.admittedAtMs,
});
const create = pluginPackageInstallCreate(
request.lock,
record,
previousHead,
);
return Object.freeze({
create,
receipt: withReceiptDigest({
schema: PLUGIN_PACKAGE_ADMISSION_RECEIPT_SCHEMA,
dispatchId: dispatch.id,
dispatchDigest: approvedActionDispatchDigest(dispatch),
approvalRequestId: dispatch.approvalRequestId,
actionRef: dispatch.action.actionRef,
projectId: record.projectId,
packageName: record.packageName,
installationId: record.installationId,
lockDigest: record.lockDigest,
recordDigest: record.recordDigest,
mutationId: create.mutationId,
mutationDigest: create.mutationDigest,
auditEventId: request.audit.eventId,
admittedAtMs: request.admittedAtMs,
}),
});
}
export function normalizePluginPackageAdmissionReceipt(
value: PluginPackageAdmissionReceipt,
): Readonly<PluginPackageAdmissionReceipt> {
const receipt = dataRecord(value, 'receipt');
exactKeys(
receipt,
[
'schema',
'dispatchId',
'dispatchDigest',
'approvalRequestId',
'actionRef',
'projectId',
'packageName',
'installationId',
'lockDigest',
'recordDigest',
'mutationId',
'mutationDigest',
'auditEventId',
'admittedAtMs',
'receiptDigest',
],
'receipt',
);
if (value.schema !== PLUGIN_PACKAGE_ADMISSION_RECEIPT_SCHEMA) {
throw new InvalidPluginPackageAdmissionError(
'receipt schema is invalid',
);
}
const normalized = withReceiptDigest({
schema: PLUGIN_PACKAGE_ADMISSION_RECEIPT_SCHEMA,
dispatchId: identifier(value.dispatchId, 'dispatch id'),
dispatchDigest: digest(value.dispatchDigest, 'dispatch digest'),
approvalRequestId: identifier(
value.approvalRequestId,
'approval request id',
),
actionRef: actionRef(value.actionRef),
projectId: identifier(value.projectId, 'project id'),
packageName: packageName(value.packageName),
installationId: identifier(value.installationId, 'installation id'),
lockDigest: digest(value.lockDigest, 'lock digest'),
recordDigest: digest(value.recordDigest, 'record digest'),
mutationId: identifier(value.mutationId, 'mutation id'),
mutationDigest: digest(value.mutationDigest, 'mutation digest'),
auditEventId: identifier(value.auditEventId, 'audit event id'),
admittedAtMs: timestamp(value.admittedAtMs, 'admission time'),
});
if (normalized.receiptDigest !== value.receiptDigest) {
throw new InvalidPluginPackageAdmissionError(
'receipt digest does not match',
);
}
return normalized;
}
export function pluginPackageAdmissionReceiptDigest(
value: PluginPackageAdmissionReceipt,
): string {
return normalizePluginPackageAdmissionReceipt(value).receiptDigest;
}
export function assertPluginPackageAdmissionReplay(
dispatchValue: ApprovedActionDispatchRecord,
proposalValue: PluginPackageInstallProposal,
requestValue: PluginPackageAdmissionRequest,
receiptValue: PluginPackageAdmissionReceipt,
durableRecordValue: PluginPackageInstallRecord,
): void {
const dispatch = normalizeApprovedActionDispatchRecord(dispatchValue);
const request = normalizePluginPackageAdmissionRequest(requestValue);
const receipt = normalizePluginPackageAdmissionReceipt(receiptValue);
const durableRecord = normalizePluginPackageInstallRecord(
durableRecordValue,
);
assertDispatchBinding(dispatch, request.lock, receipt.admittedAtMs);
assertProposalBinding(dispatch, proposalValue, request);
assertAuditBinding(dispatch, request.audit, receipt.admittedAtMs);
if (
receipt.dispatchId !== dispatch.id ||
receipt.dispatchDigest !== approvedActionDispatchDigest(dispatch) ||
receipt.approvalRequestId !== dispatch.approvalRequestId ||
receipt.actionRef !== dispatch.action.actionRef ||
receipt.projectId !== request.lock.projectId ||
receipt.packageName !== request.lock.packageName ||
receipt.installationId !== request.installationId ||
receipt.lockDigest !== request.lock.lockDigest ||
receipt.mutationId !== request.mutationId ||
receipt.auditEventId !== request.audit.eventId ||
receipt.admittedAtMs !== request.admittedAtMs ||
durableRecord.installationId !== receipt.installationId ||
durableRecord.projectId !== receipt.projectId ||
durableRecord.packageName !== receipt.packageName ||
durableRecord.lockDigest !== receipt.lockDigest ||
durableRecord.createdAtMs !== receipt.admittedAtMs
) {
throw new PluginPackageAdmissionReceiptConflictError();
}
const initial = createPluginPackageInstall(request.lock, {
installationId: request.installationId,
mutationId: request.mutationId,
occurredAtMs: request.admittedAtMs,
});
if (initial.recordDigest !== receipt.recordDigest) {
throw new PluginPackageAdmissionReceiptConflictError();
}
}
@@ -0,0 +1,32 @@
export * from './plugin-package-install/contracts';
export {
createPluginPackageLock,
normalizePluginPackageInstallActionInput,
normalizePluginPackageLock,
pluginPackageInstallActionDigest,
pluginPackageInstallPlanDigest,
pluginPackageManifestDigest,
serializePluginPackageManifest,
} from './plugin-package-install/lock';
export {
assertPluginPackageInstallMatchesLock,
createPluginPackageActivationReceipt,
createPluginPackageInstall,
normalizePluginPackageActivationReceipt,
normalizePluginPackageInstallRecord,
} from './plugin-package-install/record';
export {
pluginPackageActivationIntentDigest,
pluginPackageInstallCommit,
transitionPluginPackageInstall,
} from './plugin-package-install/transition';
export {
assertPluginPackageInstallInventoryPageSize,
assertPluginPackageInstallRecoveryPageSize,
normalizePluginPackageInstallCreate,
normalizePluginPackageInstallInventoryCursor,
normalizePluginPackageInstallRecoveryCursor,
pluginPackageInstallCreate,
pluginPackageInstallRecoveryAction,
} from './plugin-package-install/repository';
@@ -0,0 +1,311 @@
import {
PluginPackageActivationCoordinator,
type PluginPackageActivationPublisher,
} from './pluginPackageActivation';
import {
InvalidPluginPackageInstallError,
PluginPackageInstallTransitionConflictError,
normalizePluginPackageLock,
pluginPackageInstallCommit,
transitionPluginPackageInstall,
type PluginPackageInstallRecord,
type PluginPackageLock,
} from './pluginPackageInstall';
import type { PluginPackageAdmissionRepository } from './pluginPackageAdmission';
import type { ApprovedActionExecutionRecord } from '../../approved-action/approvedActionExecution';
import type { SecurityAuditRecord } from '../../security/audit/securityAudit';
export interface PluginPackageStageEvidence {
readonly stageRef: string;
readonly artifactDigest: string;
readonly manifestDigest: string;
readonly contentDigest: string;
readonly evidenceDigest: string;
}
export interface PluginPackageStageProvider {
/**
* Produces or re-opens one exact content-addressed stage. A thrown
* availability error leaves the durable install queued for explicit retry.
*/
stage(
lock: Readonly<PluginPackageLock>,
): Promise<Readonly<PluginPackageStageEvidence>>;
}
export interface InstallPluginPackageOptions {
readonly lock: PluginPackageLock;
readonly proposalDigest: string;
readonly execution: ApprovedActionExecutionRecord;
readonly installationId: string;
readonly createMutationId: string;
readonly createdAtMs: number;
readonly stageMutationId: string;
readonly stagedAtMs: number;
readonly activationStartedMutationId: string;
readonly activationCommittedMutationId: string;
readonly activationFailedMutationId: string;
readonly activationStartedAtMs: number;
readonly activationObservedAtMs: number;
readonly admissionAudit: SecurityAuditRecord;
}
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageInstallError(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageInstallError(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value as number;
}
function normalizeStageEvidence(
value: PluginPackageStageEvidence,
): Readonly<PluginPackageStageEvidence> {
const evidence = dataRecord(value, 'stage evidence');
exactKeys(
evidence,
[
'stageRef',
'artifactDigest',
'manifestDigest',
'contentDigest',
'evidenceDigest',
],
'stage evidence',
);
const stageRef = identifier(value.stageRef, 'stage reference');
for (const [label, candidate] of [
['artifact digest', value.artifactDigest],
['manifest digest', value.manifestDigest],
['content digest', value.contentDigest],
['evidence digest', value.evidenceDigest],
] as const) {
if (typeof candidate !== 'string' || !DIGEST_PATTERN.test(candidate)) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
}
return Object.freeze({
stageRef,
artifactDigest: value.artifactDigest,
manifestDigest: value.manifestDigest,
contentDigest: value.contentDigest,
evidenceDigest: value.evidenceDigest,
});
}
export function normalizePluginPackageStageEvidence(
value: PluginPackageStageEvidence,
): Readonly<PluginPackageStageEvidence> {
return normalizeStageEvidence(value);
}
export class PluginPackageInstallationCoordinator {
readonly #repository: PluginPackageAdmissionRepository;
readonly #activation: PluginPackageActivationCoordinator;
constructor(options: {
readonly repository: PluginPackageAdmissionRepository;
readonly publisher: PluginPackageActivationPublisher;
}) {
const value = dataRecord(options, 'installation coordinator options');
exactKeys(
value,
['repository', 'publisher'],
'installation coordinator options',
);
if (
!options.repository ||
typeof options.repository.find !== 'function' ||
typeof options.repository.findLock !== 'function' ||
typeof options.repository.create !== 'function' ||
typeof options.repository.commit !== 'function' ||
typeof options.repository.admit !== 'function' ||
typeof options.repository.findAdmissionReceipt !== 'function'
) {
throw new InvalidPluginPackageInstallError(
'installation coordinator authority is invalid',
);
}
this.#repository = options.repository;
this.#activation = new PluginPackageActivationCoordinator({
repository: options.repository,
publisher: options.publisher,
});
}
async #convergeActivation(
record: Readonly<PluginPackageInstallRecord>,
options: Readonly<{
activationStartedMutationId: string;
activationCommittedMutationId: string;
activationFailedMutationId: string;
activationStartedAtMs: number;
activationObservedAtMs: number;
}>,
): Promise<Readonly<PluginPackageInstallRecord>> {
const identity = {
projectId: record.projectId,
packageName: record.packageName,
installationId: record.installationId,
};
if (record.state === 'staged') {
return this.#activation.activate({
...identity,
activationStartedMutationId: options.activationStartedMutationId,
activationCommittedMutationId: options.activationCommittedMutationId,
startedAtMs: options.activationStartedAtMs,
});
}
if (record.state === 'activating') {
return this.#activation.inspect({
...identity,
activationCommittedMutationId: options.activationCommittedMutationId,
activationFailedMutationId: options.activationFailedMutationId,
observedAtMs: options.activationObservedAtMs,
});
}
if (record.state === 'active' || record.state === 'failed') return record;
throw new PluginPackageInstallTransitionConflictError();
}
async install(
options: InstallPluginPackageOptions,
stageProvider: PluginPackageStageProvider,
): Promise<Readonly<PluginPackageInstallRecord>> {
const value = dataRecord(options, 'installation options');
exactKeys(
value,
[
'lock',
'proposalDigest',
'execution',
'installationId',
'createMutationId',
'createdAtMs',
'stageMutationId',
'stagedAtMs',
'activationStartedMutationId',
'activationCommittedMutationId',
'activationFailedMutationId',
'activationStartedAtMs',
'activationObservedAtMs',
'admissionAudit',
],
'installation options',
);
if (!stageProvider || typeof stageProvider.stage !== 'function') {
throw new InvalidPluginPackageInstallError('stage provider is invalid');
}
const lock = normalizePluginPackageLock(options.lock);
const installationId = identifier(
options.installationId,
'installation id',
);
const createMutationId = identifier(
options.createMutationId,
'create mutation id',
);
const stageMutationId = identifier(
options.stageMutationId,
'stage mutation id',
);
const activationStartedMutationId = identifier(
options.activationStartedMutationId,
'activation started mutation id',
);
const activationCommittedMutationId = identifier(
options.activationCommittedMutationId,
'activation committed mutation id',
);
const activationFailedMutationId = identifier(
options.activationFailedMutationId,
'activation failed mutation id',
);
const createdAtMs = timestamp(options.createdAtMs, 'creation time');
const stagedAtMs = timestamp(options.stagedAtMs, 'staged time');
const activationStartedAtMs = timestamp(
options.activationStartedAtMs,
'activation start time',
);
const activationObservedAtMs = timestamp(
options.activationObservedAtMs,
'activation observation time',
);
let record: Readonly<PluginPackageInstallRecord> = (
await this.#repository.admit({
lock,
proposalDigest: options.proposalDigest,
execution: options.execution,
installationId,
mutationId: createMutationId,
admittedAtMs: createdAtMs,
audit: options.admissionAudit,
})
).record;
if (record.state !== 'queued') {
return this.#convergeActivation(record, {
activationStartedMutationId,
activationCommittedMutationId,
activationFailedMutationId,
activationStartedAtMs,
activationObservedAtMs,
});
}
const evidence = normalizeStageEvidence(await stageProvider.stage(lock));
const staged = transitionPluginPackageInstall(lock, record, {
type: 'stage_completed',
mutationId: stageMutationId,
occurredAtMs: stagedAtMs,
...evidence,
});
record = (
await this.#repository.commit(pluginPackageInstallCommit(record, staged))
).record;
return this.#convergeActivation(record, {
activationStartedMutationId,
activationCommittedMutationId,
activationFailedMutationId,
activationStartedAtMs,
activationObservedAtMs,
});
}
}
@@ -0,0 +1,523 @@
import { createHash } from 'node:crypto';
import {
PluginPackageActivationCoordinator,
PluginPackageActivationUnavailableError,
type PluginPackageActivationPublisher,
} from './pluginPackageActivation';
import {
InvalidPluginPackageInstallError,
MAX_PLUGIN_PACKAGE_INSTALL_RECOVERY_PAGE_SIZE,
PluginPackageInstallMutationConflictError,
PluginPackageInstallTransitionConflictError,
PluginPackageInstallUnavailableError,
assertPluginPackageInstallMatchesLock,
assertPluginPackageInstallRecoveryPageSize,
normalizePluginPackageInstallRecord,
normalizePluginPackageInstallRecoveryCursor,
pluginPackageInstallCommit,
pluginPackageInstallRecoveryAction,
transitionPluginPackageInstall,
type PluginPackageInstallRecord,
type PluginPackageInstallRecoveryAction,
type PluginPackageInstallRecoveryCursor,
type PluginPackageInstallRecoveryPage,
type PluginPackageInstallRepository,
} from './pluginPackageInstall';
import {
normalizePluginPackageStageEvidence,
type PluginPackageStageProvider,
} from './pluginPackageInstallation';
/** Bounds one recovery cycle independently of the deployment profile. */
export const MAX_PLUGIN_PACKAGE_RECOVERY_PAGES = 64;
export const PLUGIN_PACKAGE_RECOVERY_ITEM_STATUSES = [
'settled',
'retry',
'manual_required',
'superseded',
] as const;
export type PluginPackageRecoveryItemStatus =
(typeof PLUGIN_PACKAGE_RECOVERY_ITEM_STATUSES)[number];
export interface PluginPackageRecoveryItemResult {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly action: Exclude<PluginPackageInstallRecoveryAction, 'none'>;
readonly status: PluginPackageRecoveryItemStatus;
readonly state: PluginPackageInstallRecord['state'];
}
export interface PluginPackageRecoveryPageResult {
readonly items: readonly Readonly<PluginPackageRecoveryItemResult>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageInstallRecoveryCursor>;
}
export interface PluginPackageRecoveryCycleResult {
readonly pages: number;
readonly scanned: number;
readonly settled: number;
readonly retry: number;
readonly manualRequired: number;
readonly superseded: number;
readonly remaining: boolean;
readonly safeToAdmit: boolean;
}
const RECOVERABLE_STATES = new Set(['queued', 'staged', 'activating']);
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageInstallError(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
throw new InvalidPluginPackageInstallError(
`${label} must contain enumerable data properties`,
);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
required: readonly string[],
optional: readonly string[],
label: string,
): void {
const actual = Object.keys(value);
if (
required.some((key) => !actual.includes(key)) ||
actual.some((key) => !required.includes(key) && !optional.includes(key))
) {
throw new InvalidPluginPackageInstallError(`${label} shape is invalid`);
}
}
function positiveInteger(
value: unknown,
maximum: number,
label: string,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > maximum
) {
throw new InvalidPluginPackageInstallError(`${label} is invalid`);
}
return value as number;
}
function timestamp(value: unknown): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new PluginPackageInstallUnavailableError();
}
return value as number;
}
function compareRecords(
left: Readonly<PluginPackageInstallRecord>,
right: Readonly<PluginPackageInstallRecord>,
): number {
return (
left.packageName.localeCompare(right.packageName) ||
left.installationId.localeCompare(right.installationId)
);
}
function normalizePage(
value: PluginPackageInstallRecoveryPage,
limit: number,
): Readonly<PluginPackageInstallRecoveryPage> {
const page = dataRecord(value, 'recovery page');
exactKeys(page, ['records', 'truncated'], ['next'], 'recovery page');
if (
!Array.isArray(value.records) ||
value.records.length > limit ||
typeof value.truncated !== 'boolean'
) {
throw new InvalidPluginPackageInstallError('recovery page is invalid');
}
const records = Object.freeze(
value.records.map((record) => normalizePluginPackageInstallRecord(record)),
);
if (
records.some((record) => !RECOVERABLE_STATES.has(record.state)) ||
records.some(
(record, index) =>
index > 0 && compareRecords(records[index - 1]!, record) >= 0,
)
) {
throw new InvalidPluginPackageInstallError(
'recovery page records are invalid',
);
}
const next =
value.next === undefined
? undefined
: normalizePluginPackageInstallRecoveryCursor(value.next);
const last = records.at(-1);
if (
value.truncated !== (next !== undefined) ||
(next &&
(!last ||
next.packageName !== last.packageName ||
next.installationId !== last.installationId))
) {
throw new InvalidPluginPackageInstallError(
'recovery page continuation is invalid',
);
}
return Object.freeze({
records,
truncated: value.truncated,
...(next ? { next } : {}),
});
}
function mutationId(
kind: string,
record: Readonly<PluginPackageInstallRecord>,
occurredAtMs: number,
): string {
const digest = createHash('sha256')
.update('qinglong/plugin-package-recovery-mutation@v1\0', 'utf8')
.update(
JSON.stringify({
kind,
installationId: record.installationId,
version: record.version,
recordDigest: record.recordDigest,
occurredAtMs,
}),
'utf8',
)
.digest('hex');
return `recovery-${kind}:${digest}`;
}
function result(
source: Readonly<PluginPackageInstallRecord>,
action: Exclude<PluginPackageInstallRecoveryAction, 'none'>,
status: PluginPackageRecoveryItemStatus,
current: Readonly<PluginPackageInstallRecord> = source,
): Readonly<PluginPackageRecoveryItemResult> {
return Object.freeze({
projectId: source.projectId,
packageName: source.packageName,
installationId: source.installationId,
action,
status,
state: current.state,
});
}
export class PluginPackageRecoveryCoordinator {
readonly #repository: PluginPackageInstallRepository;
readonly #stageProvider: PluginPackageStageProvider;
readonly #activation: PluginPackageActivationCoordinator;
readonly #now: () => number | Promise<number>;
constructor(options: {
readonly repository: PluginPackageInstallRepository;
readonly stageProvider: PluginPackageStageProvider;
readonly publisher: PluginPackageActivationPublisher;
readonly now: () => number | Promise<number>;
}) {
const value = dataRecord(options, 'recovery coordinator options');
exactKeys(
value,
['repository', 'stageProvider', 'publisher', 'now'],
[],
'recovery coordinator options',
);
if (
!options.repository ||
typeof options.repository.find !== 'function' ||
typeof options.repository.findLock !== 'function' ||
typeof options.repository.commit !== 'function' ||
typeof options.repository.listRecoveryPage !== 'function' ||
!options.stageProvider ||
typeof options.stageProvider.stage !== 'function' ||
typeof options.now !== 'function'
) {
throw new InvalidPluginPackageInstallError(
'recovery coordinator authority is invalid',
);
}
this.#repository = options.repository;
this.#stageProvider = options.stageProvider;
this.#activation = new PluginPackageActivationCoordinator({
repository: options.repository,
publisher: options.publisher,
});
this.#now = options.now;
}
async #current(
source: Readonly<PluginPackageInstallRecord>,
): Promise<Readonly<PluginPackageInstallRecord> | null> {
const record = await this.#repository.find(
source.projectId,
source.packageName,
);
return record ? normalizePluginPackageInstallRecord(record) : null;
}
async #convergeActivation(
record: Readonly<PluginPackageInstallRecord>,
occurredAtMs: number,
): Promise<Readonly<PluginPackageInstallRecord>> {
const identity = {
projectId: record.projectId,
packageName: record.packageName,
installationId: record.installationId,
};
if (record.state === 'staged') {
return this.#activation.activate({
...identity,
activationStartedMutationId: mutationId(
'activation-start',
record,
occurredAtMs,
),
activationCommittedMutationId: mutationId(
'activation-commit',
record,
occurredAtMs,
),
startedAtMs: occurredAtMs,
});
}
if (record.state === 'activating') {
return this.#activation.inspect({
...identity,
activationCommittedMutationId: mutationId(
'activation-observed',
record,
occurredAtMs,
),
activationFailedMutationId: mutationId(
'activation-failed',
record,
occurredAtMs,
),
observedAtMs: occurredAtMs,
});
}
return record;
}
async #recoverRecord(
sourceValue: Readonly<PluginPackageInstallRecord>,
): Promise<Readonly<PluginPackageRecoveryItemResult>> {
const source = normalizePluginPackageInstallRecord(sourceValue);
const action = pluginPackageInstallRecoveryAction(source);
if (action === 'none') {
throw new InvalidPluginPackageInstallError(
'terminal record appeared in recovery page',
);
}
let current = source;
try {
const occurredAtMs = timestamp(await this.#now());
if (source.state === 'queued') {
const lock = await this.#repository.findLock(source.lockDigest);
if (!lock) throw new PluginPackageInstallUnavailableError();
assertPluginPackageInstallMatchesLock(lock, source);
const evidence = normalizePluginPackageStageEvidence(
await this.#stageProvider.stage(lock),
);
const staged = transitionPluginPackageInstall(lock, source, {
type: 'stage_completed',
mutationId: mutationId('stage', source, occurredAtMs),
occurredAtMs,
...evidence,
});
const committed = normalizePluginPackageInstallRecord(
(
await this.#repository.commit(
pluginPackageInstallCommit(source, staged),
)
).record,
);
if (committed.installationId !== source.installationId) {
return result(source, action, 'superseded', committed);
}
if (committed.state === 'active' || committed.state === 'failed') {
return result(source, action, 'settled', committed);
}
if (
committed.state !== 'staged' ||
committed.recordDigest !== staged.recordDigest
) {
return result(source, action, 'retry', committed);
}
current = committed;
}
current = await this.#convergeActivation(current, occurredAtMs);
if (current.state === 'active' || current.state === 'failed') {
return result(source, action, 'settled', current);
}
return result(source, action, 'retry', current);
} catch (error) {
if (
error instanceof InvalidPluginPackageInstallError ||
error instanceof PluginPackageInstallMutationConflictError
) {
return result(source, action, 'manual_required', current);
}
if (error instanceof PluginPackageInstallTransitionConflictError) {
try {
const durable = await this.#current(source);
if (!durable || durable.installationId !== source.installationId) {
return result(source, action, 'superseded');
}
if (durable.state === 'active' || durable.state === 'failed') {
return result(source, action, 'settled', durable);
}
if (durable.recordDigest !== source.recordDigest) {
return result(source, action, 'retry', durable);
}
} catch {
return result(source, action, 'retry', current);
}
return result(source, action, 'manual_required', current);
}
if (
error instanceof PluginPackageInstallUnavailableError ||
error instanceof PluginPackageActivationUnavailableError
) {
try {
const durable = await this.#current(source);
if (!durable || durable.installationId !== source.installationId) {
return result(source, action, 'superseded');
}
if (durable.state === 'active' || durable.state === 'failed') {
return result(source, action, 'settled', durable);
}
return result(source, action, 'retry', durable);
} catch {
return result(source, action, 'retry', current);
}
}
return result(source, action, 'retry', current);
}
}
async recoverPage(options: {
readonly limit: number;
readonly after?: Readonly<PluginPackageInstallRecoveryCursor>;
}): Promise<Readonly<PluginPackageRecoveryPageResult>> {
const value = dataRecord(options, 'recovery page options');
exactKeys(value, ['limit'], ['after'], 'recovery page options');
assertPluginPackageInstallRecoveryPageSize(options.limit);
const after =
options.after === undefined
? undefined
: normalizePluginPackageInstallRecoveryCursor(options.after);
const page = normalizePage(
await this.#repository.listRecoveryPage({
limit: options.limit,
...(after ? { after } : {}),
}),
options.limit,
);
const items: Readonly<PluginPackageRecoveryItemResult>[] = [];
for (const record of page.records) {
items.push(await this.#recoverRecord(record));
}
return Object.freeze({
items: Object.freeze(items),
truncated: page.truncated,
...(page.next ? { next: page.next } : {}),
});
}
async recover(
options: {
readonly pageSize?: number;
readonly maxPages?: number;
} = {},
): Promise<Readonly<PluginPackageRecoveryCycleResult>> {
const value = dataRecord(options, 'recovery cycle options');
exactKeys(value, [], ['pageSize', 'maxPages'], 'recovery cycle options');
const pageSize = positiveInteger(
options.pageSize ?? 16,
MAX_PLUGIN_PACKAGE_INSTALL_RECOVERY_PAGE_SIZE,
'recovery page size',
);
const maxPages = positiveInteger(
options.maxPages ?? 16,
MAX_PLUGIN_PACKAGE_RECOVERY_PAGES,
'recovery page count',
);
const counts = {
pages: 0,
scanned: 0,
settled: 0,
retry: 0,
manualRequired: 0,
superseded: 0,
};
let after: Readonly<PluginPackageInstallRecoveryCursor> | undefined;
let exhausted = false;
while (counts.pages < maxPages) {
const page = await this.recoverPage({
limit: pageSize,
...(after ? { after } : {}),
});
counts.pages += 1;
counts.scanned += page.items.length;
for (const item of page.items) {
switch (item.status) {
case 'settled':
counts.settled += 1;
break;
case 'retry':
counts.retry += 1;
break;
case 'manual_required':
counts.manualRequired += 1;
break;
case 'superseded':
counts.superseded += 1;
break;
}
}
if (!page.truncated) {
exhausted = true;
break;
}
after = page.next;
}
const probe = normalizePage(
await this.#repository.listRecoveryPage({ limit: 1 }),
1,
);
const remaining = !exhausted || probe.records.length > 0;
return Object.freeze({
...counts,
remaining,
safeToAdmit: !remaining && counts.manualRequired === 0,
});
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,268 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageLifecycleImpact,
type PluginPackageLifecycleImpact,
} from './pluginPackageLifecycle';
import type { SecuritySubject } from '../../security/security';
export const PLUGIN_PACKAGE_LIFECYCLE_PLAN_SCHEMA =
'qinglong/plugin-package-lifecycle-plan@v1' as const;
export const MAX_PLUGIN_PACKAGE_LIFECYCLE_PLAN_LIFETIME_MS = 15 * 60 * 1000;
export const MAX_PLUGIN_PACKAGE_LIFECYCLE_PLAN_BYTES = 96 * 1024;
export interface PluginPackageLifecyclePlan {
readonly schema: typeof PLUGIN_PACKAGE_LIFECYCLE_PLAN_SCHEMA;
readonly actionRef: string;
readonly impact: Readonly<PluginPackageLifecycleImpact>;
readonly requestedBy: Readonly<SecuritySubject>;
readonly plannedAtMs: number;
readonly expiresAtMs: number;
readonly planDigest: string;
}
export interface CreatePluginPackageLifecyclePlanInput {
readonly actionRef: string;
readonly impact: PluginPackageLifecycleImpact;
readonly requestedBy: SecuritySubject;
readonly plannedAtMs: number;
readonly expiresAtMs: number;
}
export interface CreatePluginPackageLifecyclePlanResult {
readonly status: 'created' | 'existing';
readonly plan: Readonly<PluginPackageLifecyclePlan>;
}
export interface PluginPackageLifecyclePlanRepository {
create(
plan: Readonly<PluginPackageLifecyclePlan>,
): Promise<Readonly<CreatePluginPackageLifecyclePlanResult>>;
findByActionRef(
actionRef: string,
): Promise<Readonly<PluginPackageLifecyclePlan> | null>;
}
export class InvalidPluginPackageLifecyclePlanError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_LIFECYCLE_PLAN_INVALID';
constructor(message: string) {
super(`Plugin Package lifecycle plan is invalid: ${message}`);
this.name = 'InvalidPluginPackageLifecyclePlanError';
}
}
export class PluginPackageLifecyclePlanConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_LIFECYCLE_PLAN_CONFLICT';
constructor(message: string) {
super(
`Plugin Package lifecycle plan conflicts with durable state: ${message}`,
);
this.name = 'PluginPackageLifecyclePlanConflictError';
}
}
export class PluginPackageLifecyclePlanUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_LIFECYCLE_PLAN_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package lifecycle plan is unavailable', options);
this.name = 'PluginPackageLifecyclePlanUnavailableError';
}
}
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const SUBJECT_CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
const PLAN_DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const PLAN_DIGEST_DOMAIN =
'qinglong/plugin-package-lifecycle-plan-digest@v1\0';
function invalid(message: string): never {
throw new InvalidPluginPackageLifecyclePlanError(message);
}
function record(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const keys = Reflect.ownKeys(value);
const canonical = [...expected].sort();
if (
keys.some((key) => typeof key !== 'string') ||
keys.length !== canonical.length ||
keys
.map(String)
.sort()
.some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
return invalid('actionRef is invalid');
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function userSubject(value: SecuritySubject): Readonly<SecuritySubject> {
const candidate = record(value, 'requestedBy');
exactKeys(candidate, ['id', 'type'], 'requestedBy');
if (
value.type !== 'user' ||
typeof value.id !== 'string' ||
value.id.length < 1 ||
Buffer.byteLength(value.id, 'utf8') > 255 ||
SUBJECT_CONTROL_PATTERN.test(value.id)
) {
return invalid('requestedBy must be a User subject');
}
return Object.freeze({ type: 'user', id: value.id });
}
function fields(
value: Omit<PluginPackageLifecyclePlan, 'planDigest'>,
): object {
return {
schema: value.schema,
actionRef: value.actionRef,
impact: value.impact,
requestedBy: value.requestedBy,
plannedAtMs: value.plannedAtMs,
expiresAtMs: value.expiresAtMs,
};
}
export function pluginPackageLifecyclePlanDigest(
value: Omit<PluginPackageLifecyclePlan, 'planDigest'>,
): string {
return createHash('sha256')
.update(PLAN_DIGEST_DOMAIN)
.update(JSON.stringify(fields(value)))
.digest('hex');
}
function normalizedWithoutDigest(
value: Omit<PluginPackageLifecyclePlan, 'planDigest'>,
): Omit<PluginPackageLifecyclePlan, 'planDigest'> {
if (value.schema !== PLUGIN_PACKAGE_LIFECYCLE_PLAN_SCHEMA) {
return invalid('schema is invalid');
}
const plannedAtMs = timestamp(value.plannedAtMs, 'plannedAtMs');
const expiresAtMs = timestamp(value.expiresAtMs, 'expiresAtMs');
if (
expiresAtMs <= plannedAtMs ||
expiresAtMs - plannedAtMs >
MAX_PLUGIN_PACKAGE_LIFECYCLE_PLAN_LIFETIME_MS
) {
return invalid('lifetime is invalid');
}
return Object.freeze({
schema: PLUGIN_PACKAGE_LIFECYCLE_PLAN_SCHEMA,
actionRef: actionRef(value.actionRef),
impact: normalizePluginPackageLifecycleImpact(value.impact),
requestedBy: userSubject(value.requestedBy),
plannedAtMs,
expiresAtMs,
});
}
function boundedPlan(
value: Readonly<PluginPackageLifecyclePlan>,
): Readonly<PluginPackageLifecyclePlan> {
if (
Buffer.byteLength(JSON.stringify(value), 'utf8') >
MAX_PLUGIN_PACKAGE_LIFECYCLE_PLAN_BYTES
) {
return invalid('encoded plan exceeds the size limit');
}
return value;
}
export function createPluginPackageLifecyclePlan(
input: CreatePluginPackageLifecyclePlanInput,
): Readonly<PluginPackageLifecyclePlan> {
const value = record(input, 'lifecycle plan input');
exactKeys(
value,
['actionRef', 'expiresAtMs', 'impact', 'plannedAtMs', 'requestedBy'],
'lifecycle plan input',
);
const unsigned = normalizedWithoutDigest({
schema: PLUGIN_PACKAGE_LIFECYCLE_PLAN_SCHEMA,
actionRef: input.actionRef,
impact: input.impact,
requestedBy: input.requestedBy,
plannedAtMs: input.plannedAtMs,
expiresAtMs: input.expiresAtMs,
});
return boundedPlan(
Object.freeze({
...unsigned,
planDigest: pluginPackageLifecyclePlanDigest(unsigned),
}),
);
}
export function normalizePluginPackageLifecyclePlan(
value: PluginPackageLifecyclePlan,
): Readonly<PluginPackageLifecyclePlan> {
const candidate = record(value, 'lifecycle plan');
exactKeys(
candidate,
[
'actionRef',
'expiresAtMs',
'impact',
'planDigest',
'plannedAtMs',
'requestedBy',
'schema',
],
'lifecycle plan',
);
const unsigned = normalizedWithoutDigest(value);
const planDigest = pluginPackageLifecyclePlanDigest(unsigned);
if (
typeof value.planDigest !== 'string' ||
!PLAN_DIGEST_PATTERN.test(value.planDigest) ||
value.planDigest !== planDigest
) {
return invalid('planDigest does not match lifecycle plan');
}
return boundedPlan(Object.freeze({ ...unsigned, planDigest }));
}
@@ -0,0 +1,709 @@
import { createHash } from 'node:crypto';
import { SECURITY_SUBJECT_TYPES, type SecuritySubject } from '../../security/security';
export const PLUGIN_PACKAGE_QUARANTINE_EVENT_SCHEMA =
'qinglong/plugin-package-quarantine-event@v1' as const;
export const PLUGIN_PACKAGE_WITHDRAWAL_RECEIPT_SCHEMA =
'qinglong/plugin-package-withdrawal-receipt@v1' as const;
export const MAX_PLUGIN_PACKAGE_QUARANTINE_TASK_WITHDRAWALS = 128;
export const MAX_PLUGIN_PACKAGE_QUARANTINE_RETAINED_SOURCES = 128;
export type PluginPackageQuarantineInstallState =
| 'queued'
| 'staged'
| 'activating'
| 'active';
export type PluginPackageQuarantineAuthorizationMode =
| 'dual_control'
| 'break_glass';
export type PluginPackageQuarantineReason =
| 'suspected_key_compromise'
| 'confirmed_key_compromise';
export interface PluginPackageQuarantineTarget {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly lockDigest: string;
readonly installState: PluginPackageQuarantineInstallState;
readonly installVersion: number;
readonly installRecordDigest: string;
readonly activeLockDigest: string | null;
}
export interface PluginPackageQuarantineEvent {
readonly schema: typeof PLUGIN_PACKAGE_QUARANTINE_EVENT_SCHEMA;
readonly mutationId: string;
readonly revocationReceiptDigest: string;
readonly impactDigest: string;
readonly target: Readonly<PluginPackageQuarantineTarget>;
readonly proposer: Readonly<SecuritySubject>;
readonly confirmer: Readonly<SecuritySubject>;
readonly authorizationMode: PluginPackageQuarantineAuthorizationMode;
readonly reasonCode: PluginPackageQuarantineReason;
readonly occurredAtMs: number;
readonly eventDigest: string;
}
export type CreatePluginPackageQuarantineEventInput = Omit<
PluginPackageQuarantineEvent,
'eventDigest' | 'schema'
>;
export interface PluginPackageQuarantineTaskWithdrawal {
readonly taskId: string;
readonly previousRevision: number;
readonly disabledRevision: number;
readonly previousContentDigest: string;
readonly disabledContentDigest: string;
}
export interface PluginPackageQuarantineInactiveCapabilityDisposition {
readonly status: 'not_active';
readonly taskWithdrawals: readonly [];
readonly previousActiveVectorDigest: null;
readonly currentActiveVectorDigest: null;
readonly currentToolSnapshotDigest: null;
readonly retainedSourceCount: 0;
}
export interface PluginPackageQuarantineWithdrawnCapabilityDisposition {
readonly status: 'withdrawn';
readonly taskWithdrawals: readonly Readonly<PluginPackageQuarantineTaskWithdrawal>[];
readonly previousActiveVectorDigest: string;
readonly currentActiveVectorDigest: string;
readonly currentToolSnapshotDigest: string;
readonly retainedSourceCount: number;
}
export type PluginPackageQuarantineCapabilityDisposition =
| Readonly<PluginPackageQuarantineInactiveCapabilityDisposition>
| Readonly<PluginPackageQuarantineWithdrawnCapabilityDisposition>;
export interface PluginPackageWithdrawalReceipt {
readonly schema: typeof PLUGIN_PACKAGE_WITHDRAWAL_RECEIPT_SCHEMA;
readonly eventDigest: string;
readonly target: Readonly<PluginPackageQuarantineTarget>;
readonly capability: PluginPackageQuarantineCapabilityDisposition;
readonly committedAtMs: number;
readonly receiptDigest: string;
}
export type CreatePluginPackageWithdrawalReceiptInput = Omit<
PluginPackageWithdrawalReceipt,
'receiptDigest' | 'schema'
>;
export interface PluginPackageQuarantineRepository {
findTargetsByLockDigest(
lockDigest: string,
): Promise<readonly Readonly<PluginPackageQuarantineTarget>[]>;
findByEventDigest(
eventDigest: string,
): Promise<Readonly<PluginPackageWithdrawalReceipt> | null>;
quarantine(
event: Readonly<PluginPackageQuarantineEvent>,
confirmAuthorization: () => void | Promise<void>,
): Promise<
Readonly<{
status: 'created' | 'existing';
receipt: Readonly<PluginPackageWithdrawalReceipt>;
}>
>;
}
export class InvalidPluginPackageQuarantineError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_QUARANTINE_INVALID';
constructor(message: string) {
super(`Plugin Package quarantine is invalid: ${message}`);
this.name = 'InvalidPluginPackageQuarantineError';
}
}
export class PluginPackageQuarantineConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_QUARANTINE_CONFLICT';
constructor(message: string) {
super(`Plugin Package quarantine conflicts with durable state: ${message}`);
this.name = 'PluginPackageQuarantineConflictError';
}
}
export class PluginPackageQuarantineUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_QUARANTINE_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package quarantine is unavailable', options);
this.name = 'PluginPackageQuarantineUnavailableError';
}
}
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PACKAGE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const SUBJECT_CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
const EVENT_DIGEST_DOMAIN =
'qinglong/plugin-package-quarantine-event-digest@v1\0';
const RECEIPT_DIGEST_DOMAIN =
'qinglong/plugin-package-withdrawal-receipt-digest@v1\0';
const TASK_MUTATION_ID_DOMAIN =
'qinglong/plugin-package-quarantine-task-mutation-id@v1\0';
const QUARANTINE_MUTATION_ID_DOMAIN =
'qinglong/plugin-package-quarantine-mutation-id@v1\0';
function invalid(message: string): never {
throw new InvalidPluginPackageQuarantineError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const sorted = [...expected].sort();
if (
actual.some((key) => typeof key !== 'string') ||
actual.length !== sorted.length ||
actual
.map(String)
.sort()
.some((key, index) => key !== sorted[index])
) {
invalid(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function positiveVersion(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 1) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function subject(
value: SecuritySubject,
label: string,
): Readonly<SecuritySubject> {
const record = dataRecord(value, label);
exactKeys(record, ['id', 'type'], label);
if (
typeof value.type !== 'string' ||
!SECURITY_SUBJECT_TYPES.includes(
value.type as (typeof SECURITY_SUBJECT_TYPES)[number],
) ||
typeof value.id !== 'string' ||
value.id.length < 1 ||
Buffer.byteLength(value.id, 'utf8') > 255 ||
SUBJECT_CONTROL_PATTERN.test(value.id)
) {
return invalid(`${label} is invalid`);
}
return Object.freeze({
type: value.type as (typeof SECURITY_SUBJECT_TYPES)[number],
id: value.id,
});
}
function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
function normalizeTarget(
value: PluginPackageQuarantineTarget,
): Readonly<PluginPackageQuarantineTarget> {
const target = dataRecord(value, 'target');
exactKeys(
target,
[
'activeLockDigest',
'installationId',
'installRecordDigest',
'installState',
'installVersion',
'lockDigest',
'packageName',
'projectId',
],
'target',
);
if (
typeof value.projectId !== 'string' ||
value.projectId.length < 1 ||
Buffer.byteLength(value.projectId, 'utf8') > 128 ||
value.projectId.includes('\0') ||
typeof value.packageName !== 'string' ||
!PACKAGE_NAME_PATTERN.test(value.packageName) ||
!['queued', 'staged', 'activating', 'active'].includes(value.installState)
) {
return invalid('target identity or state is invalid');
}
const lockDigest = digest(value.lockDigest, 'target lockDigest');
const activeLockDigest =
value.activeLockDigest === null
? null
: digest(value.activeLockDigest, 'target activeLockDigest');
if (
(value.installState === 'active' && activeLockDigest !== lockDigest) ||
(value.installState !== 'active' && activeLockDigest === lockDigest)
) {
return invalid('target active lock does not match install state');
}
return Object.freeze({
projectId: value.projectId,
packageName: value.packageName,
installationId: identifier(value.installationId, 'target installationId'),
lockDigest,
installState: value.installState,
installVersion: positiveVersion(
value.installVersion,
'target installVersion',
),
installRecordDigest: digest(
value.installRecordDigest,
'target installRecordDigest',
),
activeLockDigest,
});
}
function eventFields(
value: Omit<PluginPackageQuarantineEvent, 'eventDigest'>,
): object {
return {
schema: value.schema,
mutationId: value.mutationId,
revocationReceiptDigest: value.revocationReceiptDigest,
impactDigest: value.impactDigest,
target: value.target,
proposer: value.proposer,
confirmer: value.confirmer,
authorizationMode: value.authorizationMode,
reasonCode: value.reasonCode,
occurredAtMs: value.occurredAtMs,
};
}
export function pluginPackageQuarantineEventDigest(
value: Omit<PluginPackageQuarantineEvent, 'eventDigest'>,
): string {
return createHash('sha256')
.update(EVENT_DIGEST_DOMAIN)
.update(JSON.stringify(eventFields(value)))
.digest('hex');
}
export function normalizePluginPackageQuarantineEvent(
value: PluginPackageQuarantineEvent,
): Readonly<PluginPackageQuarantineEvent> {
const event = dataRecord(value, 'event');
exactKeys(
event,
[
'authorizationMode',
'confirmer',
'eventDigest',
'impactDigest',
'mutationId',
'occurredAtMs',
'proposer',
'reasonCode',
'revocationReceiptDigest',
'schema',
'target',
],
'event',
);
if (
value.schema !== PLUGIN_PACKAGE_QUARANTINE_EVENT_SCHEMA ||
(value.authorizationMode !== 'dual_control' &&
value.authorizationMode !== 'break_glass') ||
(value.reasonCode !== 'suspected_key_compromise' &&
value.reasonCode !== 'confirmed_key_compromise')
) {
return invalid('event schema or classification is invalid');
}
const proposer = subject(value.proposer, 'proposer');
const confirmer = subject(value.confirmer, 'confirmer');
if (
value.authorizationMode === 'dual_control' &&
sameSubject(proposer, confirmer)
) {
return invalid('dual-control requires distinct subjects');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_QUARANTINE_EVENT_SCHEMA,
mutationId: identifier(value.mutationId, 'mutationId'),
revocationReceiptDigest: digest(
value.revocationReceiptDigest,
'revocationReceiptDigest',
),
impactDigest: digest(value.impactDigest, 'impactDigest'),
target: normalizeTarget(value.target),
proposer,
confirmer,
authorizationMode: value.authorizationMode,
reasonCode: value.reasonCode,
occurredAtMs: timestamp(value.occurredAtMs, 'occurredAtMs'),
});
const eventDigest = pluginPackageQuarantineEventDigest(normalized);
if (value.eventDigest !== eventDigest) {
return invalid('eventDigest does not match event');
}
return Object.freeze({ ...normalized, eventDigest });
}
export function createPluginPackageQuarantineEvent(
input: CreatePluginPackageQuarantineEventInput,
): Readonly<PluginPackageQuarantineEvent> {
const value = dataRecord(input, 'event input');
exactKeys(
value,
[
'authorizationMode',
'confirmer',
'impactDigest',
'mutationId',
'occurredAtMs',
'proposer',
'reasonCode',
'revocationReceiptDigest',
'target',
],
'event input',
);
if (
(input.authorizationMode !== 'dual_control' &&
input.authorizationMode !== 'break_glass') ||
(input.reasonCode !== 'suspected_key_compromise' &&
input.reasonCode !== 'confirmed_key_compromise')
) {
return invalid('event classification is invalid');
}
const proposer = subject(input.proposer, 'proposer');
const confirmer = subject(input.confirmer, 'confirmer');
if (
input.authorizationMode === 'dual_control' &&
sameSubject(proposer, confirmer)
) {
return invalid('dual-control requires distinct subjects');
}
const unsigned: Omit<PluginPackageQuarantineEvent, 'eventDigest'> = {
schema: PLUGIN_PACKAGE_QUARANTINE_EVENT_SCHEMA,
mutationId: identifier(input.mutationId, 'mutationId'),
revocationReceiptDigest: digest(
input.revocationReceiptDigest,
'revocationReceiptDigest',
),
impactDigest: digest(input.impactDigest, 'impactDigest'),
target: normalizeTarget(input.target),
proposer,
confirmer,
authorizationMode: input.authorizationMode,
reasonCode: input.reasonCode,
occurredAtMs: timestamp(input.occurredAtMs, 'occurredAtMs'),
};
return normalizePluginPackageQuarantineEvent({
...unsigned,
eventDigest: pluginPackageQuarantineEventDigest(unsigned),
});
}
function normalizeTaskWithdrawal(
value: PluginPackageQuarantineTaskWithdrawal,
): Readonly<PluginPackageQuarantineTaskWithdrawal> {
const task = dataRecord(value, 'task withdrawal');
exactKeys(
task,
[
'disabledContentDigest',
'disabledRevision',
'previousContentDigest',
'previousRevision',
'taskId',
],
'task withdrawal',
);
const previousRevision = positiveVersion(
value.previousRevision,
'task previousRevision',
);
const disabledRevision = positiveVersion(
value.disabledRevision,
'task disabledRevision',
);
if (disabledRevision !== previousRevision + 1) {
return invalid('task disabled revision is not consecutive');
}
return Object.freeze({
taskId: identifier(value.taskId, 'taskId'),
previousRevision,
disabledRevision,
previousContentDigest: digest(
value.previousContentDigest,
'task previousContentDigest',
),
disabledContentDigest: digest(
value.disabledContentDigest,
'task disabledContentDigest',
),
});
}
function normalizeCapability(
value: PluginPackageQuarantineCapabilityDisposition,
target: Readonly<PluginPackageQuarantineTarget>,
): PluginPackageQuarantineCapabilityDisposition {
const capability = dataRecord(value, 'capability');
exactKeys(
capability,
[
'currentActiveVectorDigest',
'currentToolSnapshotDigest',
'previousActiveVectorDigest',
'retainedSourceCount',
'status',
'taskWithdrawals',
],
'capability',
);
if (!Array.isArray(value.taskWithdrawals)) {
return invalid('task withdrawals must be an array');
}
if (value.status === 'not_active') {
if (
target.installState === 'active' ||
value.taskWithdrawals.length !== 0 ||
value.previousActiveVectorDigest !== null ||
value.currentActiveVectorDigest !== null ||
value.currentToolSnapshotDigest !== null ||
value.retainedSourceCount !== 0
) {
return invalid('inactive capability disposition is inconsistent');
}
return Object.freeze({
status: 'not_active',
taskWithdrawals: Object.freeze([]) as readonly [],
previousActiveVectorDigest: null,
currentActiveVectorDigest: null,
currentToolSnapshotDigest: null,
retainedSourceCount: 0,
});
}
if (
value.status !== 'withdrawn' ||
target.installState !== 'active' ||
value.taskWithdrawals.length >
MAX_PLUGIN_PACKAGE_QUARANTINE_TASK_WITHDRAWALS ||
!Number.isSafeInteger(value.retainedSourceCount) ||
value.retainedSourceCount < 0 ||
value.retainedSourceCount > MAX_PLUGIN_PACKAGE_QUARANTINE_RETAINED_SOURCES
) {
return invalid('withdrawn capability disposition is invalid');
}
const taskWithdrawals = Object.freeze(
value.taskWithdrawals.map(normalizeTaskWithdrawal),
);
if (
taskWithdrawals.some(
(task, index) =>
index > 0 &&
Buffer.compare(
Buffer.from(taskWithdrawals[index - 1]!.taskId, 'utf8'),
Buffer.from(task.taskId, 'utf8'),
) >= 0,
)
) {
return invalid('task withdrawals must be unique and sorted');
}
const previousActiveVectorDigest = digest(
value.previousActiveVectorDigest,
'previousActiveVectorDigest',
);
const currentActiveVectorDigest = digest(
value.currentActiveVectorDigest,
'currentActiveVectorDigest',
);
if (previousActiveVectorDigest === currentActiveVectorDigest) {
return invalid('active vector did not change');
}
return Object.freeze({
status: 'withdrawn',
taskWithdrawals,
previousActiveVectorDigest,
currentActiveVectorDigest,
currentToolSnapshotDigest: digest(
value.currentToolSnapshotDigest,
'currentToolSnapshotDigest',
),
retainedSourceCount: value.retainedSourceCount,
});
}
function receiptFields(
value: Omit<PluginPackageWithdrawalReceipt, 'receiptDigest'>,
): object {
return {
schema: value.schema,
eventDigest: value.eventDigest,
target: value.target,
capability: value.capability,
committedAtMs: value.committedAtMs,
};
}
export function pluginPackageWithdrawalReceiptDigest(
value: Omit<PluginPackageWithdrawalReceipt, 'receiptDigest'>,
): string {
return createHash('sha256')
.update(RECEIPT_DIGEST_DOMAIN)
.update(JSON.stringify(receiptFields(value)))
.digest('hex');
}
export function normalizePluginPackageWithdrawalReceipt(
value: PluginPackageWithdrawalReceipt,
): Readonly<PluginPackageWithdrawalReceipt> {
const receipt = dataRecord(value, 'withdrawal receipt');
exactKeys(
receipt,
[
'capability',
'committedAtMs',
'eventDigest',
'receiptDigest',
'schema',
'target',
],
'withdrawal receipt',
);
if (value.schema !== PLUGIN_PACKAGE_WITHDRAWAL_RECEIPT_SCHEMA) {
return invalid('withdrawal receipt schema is invalid');
}
const target = normalizeTarget(value.target);
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_WITHDRAWAL_RECEIPT_SCHEMA,
eventDigest: digest(value.eventDigest, 'eventDigest'),
target,
capability: normalizeCapability(value.capability, target),
committedAtMs: timestamp(value.committedAtMs, 'committedAtMs'),
});
const receiptDigest = pluginPackageWithdrawalReceiptDigest(normalized);
if (value.receiptDigest !== receiptDigest) {
return invalid('receiptDigest does not match withdrawal receipt');
}
return Object.freeze({ ...normalized, receiptDigest });
}
export function createPluginPackageWithdrawalReceipt(
input: CreatePluginPackageWithdrawalReceiptInput,
): Readonly<PluginPackageWithdrawalReceipt> {
const value = dataRecord(input, 'withdrawal receipt input');
exactKeys(
value,
['capability', 'committedAtMs', 'eventDigest', 'target'],
'withdrawal receipt input',
);
const target = normalizeTarget(input.target);
const unsigned: Omit<PluginPackageWithdrawalReceipt, 'receiptDigest'> = {
schema: PLUGIN_PACKAGE_WITHDRAWAL_RECEIPT_SCHEMA,
eventDigest: digest(input.eventDigest, 'eventDigest'),
target,
capability: normalizeCapability(input.capability, target),
committedAtMs: timestamp(input.committedAtMs, 'committedAtMs'),
};
return normalizePluginPackageWithdrawalReceipt({
...unsigned,
receiptDigest: pluginPackageWithdrawalReceiptDigest(unsigned),
});
}
export function assertPluginPackageWithdrawalMatchesEvent(
eventValue: PluginPackageQuarantineEvent,
receiptValue: PluginPackageWithdrawalReceipt,
): void {
const event = normalizePluginPackageQuarantineEvent(eventValue);
const receipt = normalizePluginPackageWithdrawalReceipt(receiptValue);
if (
receipt.eventDigest !== event.eventDigest ||
JSON.stringify(receipt.target) !== JSON.stringify(event.target) ||
receipt.committedAtMs < event.occurredAtMs
) {
invalid('withdrawal receipt does not match quarantine event');
}
}
export function pluginPackageQuarantineTaskMutationId(
eventDigestValue: string,
taskIdValue: string,
): string {
const eventDigest = digest(eventDigestValue, 'eventDigest');
const taskId = identifier(taskIdValue, 'taskId');
const value = createHash('sha256')
.update(TASK_MUTATION_ID_DOMAIN)
.update(eventDigest)
.update('\0')
.update(taskId)
.digest('hex');
return `${value.slice(0, 8)}-${value.slice(8, 12)}-4${value.slice(
13,
16,
)}-a${value.slice(17, 20)}-${value.slice(20, 32)}`;
}
export function pluginPackageQuarantineMutationId(
revocationReceiptDigestValue: string,
targetValue: PluginPackageQuarantineTarget,
): string {
const revocationReceiptDigest = digest(
revocationReceiptDigestValue,
'revocationReceiptDigest',
);
const target = normalizeTarget(targetValue);
const value = createHash('sha256')
.update(QUARANTINE_MUTATION_ID_DOMAIN)
.update(revocationReceiptDigest)
.update('\0')
.update(JSON.stringify(target))
.digest('hex');
return `quarantine:${value}`;
}
@@ -0,0 +1,851 @@
import { semver } from '../versioning/pinnedSemver';
export const PLUGIN_PACKAGE_API_VERSION = 'qinglong.io/v1alpha1';
export const PLUGIN_PACKAGE_KIND = 'Package';
export const MAX_PLUGIN_PACKAGE_MANIFEST_BYTES = 64 * 1024;
export const MAX_PLUGIN_PACKAGE_RUNTIMES = 8;
export const MAX_PLUGIN_PACKAGE_NETWORK_HOSTS = 32;
export const MAX_PLUGIN_PACKAGE_SECRETS = 64;
export const MAX_PLUGIN_PACKAGE_TOOL_PERMISSIONS = 64;
export const MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES = 256;
export const MAX_PLUGIN_PACKAGE_CONTENT_PATH_BYTES = 255;
export const MAX_PLUGIN_PACKAGE_RESOURCE_BYTES = 1024 ** 4;
export const PLUGIN_PACKAGE_ARCHITECTURES = [
'amd64',
'arm64',
'arm/v7',
'ppc64le',
's390x',
] as const;
export const PLUGIN_PACKAGE_DEPLOYMENT_PROFILES = [
'edge',
'standalone',
'cluster-control',
'worker',
] as const;
export const PLUGIN_PACKAGE_TOOL_PERMISSIONS = [
'artifact.read',
'dependency.install',
'filesystem.read',
'filesystem.write',
'mcp.tool.call',
'model.invoke',
'network.connect',
'notification.send',
'run.read',
'run.start',
'run.stop',
'run.retry',
'secret.use',
'system.command',
'task.read',
'task.update',
'background.service',
] as const;
export type PluginPackageArchitecture =
(typeof PLUGIN_PACKAGE_ARCHITECTURES)[number];
export type PluginPackageDeploymentProfile =
(typeof PLUGIN_PACKAGE_DEPLOYMENT_PROFILES)[number];
export type PluginPackageToolPermission =
(typeof PLUGIN_PACKAGE_TOOL_PERMISSIONS)[number];
export type PluginPackageRisk = 'low' | 'medium' | 'high';
export type PluginPackagePlanOperation =
| 'install'
| 'reinstall'
| 'upgrade'
| 'rollback';
export type PluginPackageFindingSeverity = 'warning' | 'error';
export interface PluginPackageManifestMetadata {
readonly name: string;
readonly displayName: string;
readonly version: string;
readonly description: string;
readonly license: string;
}
export interface PluginPackageRuntimeRequirement {
readonly name: string;
readonly version: string;
}
export interface PluginPackageSecretRequirement {
readonly name: string;
readonly required: boolean;
}
export interface PluginPackageContents {
readonly tasks: readonly string[];
readonly workflows: readonly string[];
readonly prompts: readonly string[];
readonly tools: readonly string[];
}
export interface PluginPackageManifest {
readonly apiVersion: typeof PLUGIN_PACKAGE_API_VERSION;
readonly kind: typeof PLUGIN_PACKAGE_KIND;
readonly metadata: Readonly<PluginPackageManifestMetadata>;
readonly spec: Readonly<{
compatibility: Readonly<{
qinglong: string;
architectures: readonly PluginPackageArchitecture[];
deploymentProfiles: readonly PluginPackageDeploymentProfile[];
}>;
runtimes: readonly Readonly<PluginPackageRuntimeRequirement>[];
resources: Readonly<{
memory: Readonly<{ recommended: string }>;
disk: Readonly<{ install: string; working: string }>;
}>;
permissions: Readonly<{
network: Readonly<{ allowedHosts: readonly string[] }>;
secrets: readonly Readonly<PluginPackageSecretRequirement>[];
tools: readonly PluginPackageToolPermission[];
}>;
contents: Readonly<PluginPackageContents>;
}>;
}
export interface PluginPackageRuntimeEnvironment {
readonly name: string;
readonly version: string;
}
export interface PluginPackageInstallEnvironment {
readonly qinglongVersion: string;
readonly architecture: PluginPackageArchitecture;
readonly deploymentProfile: PluginPackageDeploymentProfile;
readonly runtimes: readonly Readonly<PluginPackageRuntimeEnvironment>[];
readonly availableMemoryBytes: number;
readonly availableDiskBytes: number;
}
export interface PluginPackagePlanFinding {
readonly code:
| 'architecture_unsupported'
| 'deployment_profile_unsupported'
| 'disk_insufficient'
| 'memory_below_recommendation'
| 'qinglong_version_unsupported'
| 'runtime_missing'
| 'runtime_version_unsupported';
readonly severity: PluginPackageFindingSeverity;
readonly subject: string;
}
export interface PluginPackageInstallPlan {
readonly package: Readonly<{
name: string;
fromVersion?: string;
toVersion: string;
}>;
readonly operation: PluginPackagePlanOperation;
readonly compatible: boolean;
readonly risk: PluginPackageRisk;
readonly approvalRequired: true;
readonly permissionReapprovalRequired: boolean;
readonly permissionDelta: Readonly<{
added: readonly string[];
removed: readonly string[];
}>;
readonly resources: Readonly<{
memoryRecommendedBytes: number;
diskInstallBytes: number;
diskWorkingBytes: number;
}>;
readonly contents: Readonly<{
tasks: number;
workflows: number;
prompts: number;
tools: number;
}>;
readonly findings: readonly Readonly<PluginPackagePlanFinding>[];
}
export class InvalidPluginPackageManifestError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_MANIFEST_INVALID';
constructor(message: string) {
super(`Plugin Package manifest is invalid: ${message}`);
this.name = 'InvalidPluginPackageManifestError';
}
}
export class InvalidPluginPackageInstallEnvironmentError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_INSTALL_ENVIRONMENT_INVALID';
constructor(message: string) {
super(`Plugin Package install environment is invalid: ${message}`);
this.name = 'InvalidPluginPackageInstallEnvironmentError';
}
}
const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
const PACKAGE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const RUNTIME_NAME_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
const SECRET_NAME_PATTERN = /^[A-Z_][A-Z0-9_]{0,127}$/;
const RESOURCE_PATTERN = /^([1-9][0-9]{0,6})(Ki|Mi|Gi)$/;
const HOST_PATTERN =
/^(?=.{1,253}$)[a-z0-9](?:(?:[a-z0-9-]{0,61})?[a-z0-9])?(?:\.[a-z0-9](?:(?:[a-z0-9-]{0,61})?[a-z0-9])?)*$/;
function record(value: unknown, label: string): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidPluginPackageManifestError(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: Record<string, unknown>,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageManifestError(`${label} shape is invalid`);
}
}
function boundedText(
value: unknown,
label: string,
maximumBytes: number,
): string {
if (
typeof value !== 'string' ||
value.length === 0 ||
CONTROL_PATTERN.test(value) ||
Buffer.byteLength(value, 'utf8') > maximumBytes
) {
throw new InvalidPluginPackageManifestError(`${label} is invalid`);
}
return value;
}
function canonicalVersion(value: unknown, label: string): string {
const version = boundedText(value, label, 128);
if (semver().valid(version) !== version) {
throw new InvalidPluginPackageManifestError(`${label} is invalid`);
}
return version;
}
function versionRange(value: unknown, label: string): string {
const range = boundedText(value, label, 256);
if (!semver().validRange(range)) {
throw new InvalidPluginPackageManifestError(`${label} is invalid`);
}
return range;
}
function uniqueSortedAllowed<T extends string>(
value: unknown,
allowed: readonly T[],
maximum: number,
label: string,
allowEmpty = false,
): readonly T[] {
if (
!Array.isArray(value) ||
value.length > maximum ||
(!allowEmpty && value.length === 0)
) {
throw new InvalidPluginPackageManifestError(`${label} is invalid`);
}
const entries = new Set<T>();
for (const item of value) {
if (
typeof item !== 'string' ||
!allowed.includes(item as T) ||
entries.has(item as T)
) {
throw new InvalidPluginPackageManifestError(
`${label} contains an invalid or duplicate value`,
);
}
entries.add(item as T);
}
return Object.freeze([...entries].sort());
}
function normalizeRuntimes(
value: unknown,
): readonly Readonly<PluginPackageRuntimeRequirement>[] {
if (!Array.isArray(value) || value.length > MAX_PLUGIN_PACKAGE_RUNTIMES) {
throw new InvalidPluginPackageManifestError('runtimes are invalid');
}
const names = new Set<string>();
const runtimes = value.map((item) => {
const runtime = record(item, 'runtime');
exactKeys(runtime, ['name', 'version'], 'runtime');
const name = boundedText(runtime.name, 'runtime name', 32);
if (!RUNTIME_NAME_PATTERN.test(name) || names.has(name)) {
throw new InvalidPluginPackageManifestError(
'runtime name is invalid or duplicated',
);
}
names.add(name);
return Object.freeze({
name,
version: versionRange(runtime.version, 'runtime version range'),
});
});
runtimes.sort((left, right) => left.name.localeCompare(right.name));
return Object.freeze(runtimes);
}
function resourceBytes(value: unknown, label: string): number {
const quantity = boundedText(value, label, 16);
const match = RESOURCE_PATTERN.exec(quantity);
if (!match) {
throw new InvalidPluginPackageManifestError(`${label} is invalid`);
}
const amount = Number(match[1]);
const unit = match[2];
const multiplier =
unit === 'Ki' ? 1024 : unit === 'Mi' ? 1024 ** 2 : 1024 ** 3;
const bytes = amount * multiplier;
if (
!Number.isSafeInteger(bytes) ||
bytes > MAX_PLUGIN_PACKAGE_RESOURCE_BYTES
) {
throw new InvalidPluginPackageManifestError(`${label} is out of range`);
}
return bytes;
}
function normalizeResourceQuantity(value: unknown, label: string): string {
const quantity = boundedText(value, label, 16);
resourceBytes(quantity, label);
return quantity;
}
function normalizeHosts(value: unknown): readonly string[] {
if (
!Array.isArray(value) ||
value.length > MAX_PLUGIN_PACKAGE_NETWORK_HOSTS
) {
throw new InvalidPluginPackageManifestError(
'network allowedHosts are invalid',
);
}
const hosts = new Set<string>();
for (const item of value) {
const host = boundedText(item, 'network host', 253);
if (!HOST_PATTERN.test(host) || host.includes('*') || hosts.has(host)) {
throw new InvalidPluginPackageManifestError(
'network host is invalid or duplicated',
);
}
hosts.add(host);
}
return Object.freeze([...hosts].sort());
}
function normalizeSecrets(
value: unknown,
): readonly Readonly<PluginPackageSecretRequirement>[] {
if (!Array.isArray(value) || value.length > MAX_PLUGIN_PACKAGE_SECRETS) {
throw new InvalidPluginPackageManifestError(
'secret requirements are invalid',
);
}
const names = new Set<string>();
const secrets = value.map((item) => {
const secret = record(item, 'secret requirement');
exactKeys(secret, ['name', 'required'], 'secret requirement');
const name = boundedText(secret.name, 'secret name', 128);
if (
!SECRET_NAME_PATTERN.test(name) ||
names.has(name) ||
typeof secret.required !== 'boolean'
) {
throw new InvalidPluginPackageManifestError(
'secret requirement is invalid or duplicated',
);
}
names.add(name);
return Object.freeze({ name, required: secret.required });
});
secrets.sort((left, right) => left.name.localeCompare(right.name));
return Object.freeze(secrets);
}
function normalizeContentPath(value: unknown, directory: string): string {
const path = boundedText(
value,
`${directory} content path`,
MAX_PLUGIN_PACKAGE_CONTENT_PATH_BYTES,
);
const segments = path.split('/');
if (
path.startsWith('/') ||
path.includes('\\') ||
segments.length < 2 ||
segments[0] !== directory ||
segments.some(
(segment) => segment.length === 0 || segment === '.' || segment === '..',
)
) {
throw new InvalidPluginPackageManifestError(
`${directory} content path is invalid`,
);
}
return path;
}
function normalizeContents(value: unknown): Readonly<PluginPackageContents> {
const contents = record(value, 'contents');
exactKeys(contents, ['prompts', 'tasks', 'tools', 'workflows'], 'contents');
const seen = new Set<string>();
let total = 0;
const normalize = (
directory: string,
entries: unknown,
): readonly string[] => {
if (
!Array.isArray(entries) ||
entries.length > MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES
) {
throw new InvalidPluginPackageManifestError(
`${directory} contents are invalid`,
);
}
total += entries.length;
if (total > MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES) {
throw new InvalidPluginPackageManifestError(
'content entry budget exceeded',
);
}
const paths = entries.map((entry) => {
const path = normalizeContentPath(entry, directory);
if (seen.has(path)) {
throw new InvalidPluginPackageManifestError(
'content path is duplicated',
);
}
seen.add(path);
return path;
});
paths.sort();
return Object.freeze(paths);
};
return Object.freeze({
tasks: normalize('tasks', contents.tasks),
workflows: normalize('workflows', contents.workflows),
prompts: normalize('prompts', contents.prompts),
tools: normalize('tools', contents.tools),
});
}
export function normalizePluginPackageManifest(
value: unknown,
): Readonly<PluginPackageManifest> {
const manifest = record(value, 'manifest');
exactKeys(manifest, ['apiVersion', 'kind', 'metadata', 'spec'], 'manifest');
if (
manifest.apiVersion !== PLUGIN_PACKAGE_API_VERSION ||
manifest.kind !== PLUGIN_PACKAGE_KIND
) {
throw new InvalidPluginPackageManifestError(
'apiVersion or kind is unsupported',
);
}
const metadata = record(manifest.metadata, 'metadata');
exactKeys(
metadata,
['description', 'displayName', 'license', 'name', 'version'],
'metadata',
);
const name = boundedText(metadata.name, 'metadata name', 63);
if (!PACKAGE_NAME_PATTERN.test(name)) {
throw new InvalidPluginPackageManifestError(
'metadata name must be a lowercase DNS label',
);
}
const spec = record(manifest.spec, 'spec');
exactKeys(
spec,
['compatibility', 'contents', 'permissions', 'resources', 'runtimes'],
'spec',
);
const compatibility = record(spec.compatibility, 'compatibility');
exactKeys(
compatibility,
['architectures', 'deploymentProfiles', 'qinglong'],
'compatibility',
);
const resources = record(spec.resources, 'resources');
exactKeys(resources, ['disk', 'memory'], 'resources');
const memory = record(resources.memory, 'memory resources');
exactKeys(memory, ['recommended'], 'memory resources');
const disk = record(resources.disk, 'disk resources');
exactKeys(disk, ['install', 'working'], 'disk resources');
const permissions = record(spec.permissions, 'permissions');
exactKeys(permissions, ['network', 'secrets', 'tools'], 'permissions');
const network = record(permissions.network, 'network permissions');
exactKeys(network, ['allowedHosts'], 'network permissions');
const normalized: PluginPackageManifest = Object.freeze({
apiVersion: PLUGIN_PACKAGE_API_VERSION,
kind: PLUGIN_PACKAGE_KIND,
metadata: Object.freeze({
name,
displayName: boundedText(metadata.displayName, 'displayName', 128),
version: canonicalVersion(metadata.version, 'metadata version'),
description: boundedText(metadata.description, 'description', 4096),
license: boundedText(metadata.license, 'license', 128),
}),
spec: Object.freeze({
compatibility: Object.freeze({
qinglong: versionRange(
compatibility.qinglong,
'QingLong compatibility range',
),
architectures: uniqueSortedAllowed(
compatibility.architectures,
PLUGIN_PACKAGE_ARCHITECTURES,
PLUGIN_PACKAGE_ARCHITECTURES.length,
'architectures',
),
deploymentProfiles: uniqueSortedAllowed(
compatibility.deploymentProfiles,
PLUGIN_PACKAGE_DEPLOYMENT_PROFILES,
PLUGIN_PACKAGE_DEPLOYMENT_PROFILES.length,
'deployment profiles',
),
}),
runtimes: normalizeRuntimes(spec.runtimes),
resources: Object.freeze({
memory: Object.freeze({
recommended: normalizeResourceQuantity(
memory.recommended,
'recommended memory',
),
}),
disk: Object.freeze({
install: normalizeResourceQuantity(disk.install, 'install disk'),
working: normalizeResourceQuantity(disk.working, 'working disk'),
}),
}),
permissions: Object.freeze({
network: Object.freeze({
allowedHosts: normalizeHosts(network.allowedHosts),
}),
secrets: normalizeSecrets(permissions.secrets),
tools: uniqueSortedAllowed(
permissions.tools,
PLUGIN_PACKAGE_TOOL_PERMISSIONS,
MAX_PLUGIN_PACKAGE_TOOL_PERMISSIONS,
'tool permissions',
true,
),
}),
contents: normalizeContents(spec.contents),
}),
});
if (
Buffer.byteLength(JSON.stringify(normalized), 'utf8') >
MAX_PLUGIN_PACKAGE_MANIFEST_BYTES
) {
throw new InvalidPluginPackageManifestError(
'canonical manifest byte budget exceeded',
);
}
return normalized;
}
export function normalizePluginPackageInstallEnvironment(
value: PluginPackageInstallEnvironment,
): Readonly<PluginPackageInstallEnvironment> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidPluginPackageInstallEnvironmentError(
'environment must be an object',
);
}
const raw = value as unknown as Record<string, unknown>;
const expected = [
'architecture',
'availableDiskBytes',
'availableMemoryBytes',
'deploymentProfile',
'qinglongVersion',
'runtimes',
];
const actual = Object.keys(raw).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageInstallEnvironmentError(
'environment shape is invalid',
);
}
if (
typeof value.qinglongVersion !== 'string' ||
semver().valid(value.qinglongVersion) !== value.qinglongVersion ||
!PLUGIN_PACKAGE_ARCHITECTURES.includes(value.architecture) ||
!PLUGIN_PACKAGE_DEPLOYMENT_PROFILES.includes(value.deploymentProfile) ||
!Number.isSafeInteger(value.availableMemoryBytes) ||
value.availableMemoryBytes < 0 ||
!Number.isSafeInteger(value.availableDiskBytes) ||
value.availableDiskBytes < 0 ||
!Array.isArray(value.runtimes) ||
value.runtimes.length > MAX_PLUGIN_PACKAGE_RUNTIMES
) {
throw new InvalidPluginPackageInstallEnvironmentError(
'environment value is invalid',
);
}
const names = new Set<string>();
const runtimes = value.runtimes.map((item) => {
if (!item || typeof item !== 'object' || Array.isArray(item)) {
throw new InvalidPluginPackageInstallEnvironmentError(
'runtime is invalid',
);
}
const runtime = item as unknown as Record<string, unknown>;
if (
Object.keys(runtime).sort().join(',') !== 'name,version' ||
typeof item.name !== 'string' ||
!RUNTIME_NAME_PATTERN.test(item.name) ||
names.has(item.name) ||
typeof item.version !== 'string' ||
semver().valid(item.version) !== item.version
) {
throw new InvalidPluginPackageInstallEnvironmentError(
'runtime is invalid or duplicated',
);
}
names.add(item.name);
return Object.freeze({ name: item.name, version: item.version });
});
runtimes.sort((left, right) => left.name.localeCompare(right.name));
return Object.freeze({
qinglongVersion: value.qinglongVersion,
architecture: value.architecture,
deploymentProfile: value.deploymentProfile,
runtimes: Object.freeze(runtimes),
availableMemoryBytes: value.availableMemoryBytes,
availableDiskBytes: value.availableDiskBytes,
});
}
function permissionSet(
manifest: Readonly<PluginPackageManifest>,
): ReadonlySet<string> {
const permissions = new Set<string>();
for (const host of manifest.spec.permissions.network.allowedHosts) {
permissions.add(`network:${host}`);
}
for (const secret of manifest.spec.permissions.secrets) {
permissions.add(
`secret:${secret.name}:${secret.required ? 'required' : 'optional'}`,
);
}
for (const permission of manifest.spec.permissions.tools) {
permissions.add(`tool:${permission}`);
}
return permissions;
}
function packageRisk(
manifest: Readonly<PluginPackageManifest>,
): PluginPackageRisk {
const tools = new Set(manifest.spec.permissions.tools);
if (
tools.has('background.service') ||
tools.has('dependency.install') ||
tools.has('system.command')
) {
return 'high';
}
if (
manifest.spec.permissions.network.allowedHosts.length > 0 ||
manifest.spec.permissions.secrets.length > 0 ||
tools.has('filesystem.write') ||
tools.has('model.invoke') ||
tools.has('mcp.tool.call') ||
tools.has('run.start') ||
tools.has('run.stop') ||
tools.has('run.retry') ||
tools.has('task.update')
) {
return 'medium';
}
return 'low';
}
export function planPluginPackageInstall(
manifestValue: unknown,
environmentValue: PluginPackageInstallEnvironment,
previousManifestValue?: unknown,
): Readonly<PluginPackageInstallPlan> {
const manifest = normalizePluginPackageManifest(manifestValue);
const environment =
normalizePluginPackageInstallEnvironment(environmentValue);
const previous =
previousManifestValue === undefined
? undefined
: normalizePluginPackageManifest(previousManifestValue);
if (previous && previous.metadata.name !== manifest.metadata.name) {
throw new InvalidPluginPackageManifestError(
'previous and candidate package names differ',
);
}
const findings: PluginPackagePlanFinding[] = [];
const addFinding = (
code: PluginPackagePlanFinding['code'],
severity: PluginPackageFindingSeverity,
subject: string,
): void => {
findings.push(Object.freeze({ code, severity, subject }));
};
if (
!semver().satisfies(
environment.qinglongVersion,
manifest.spec.compatibility.qinglong,
{ includePrerelease: true },
)
) {
addFinding(
'qinglong_version_unsupported',
'error',
environment.qinglongVersion,
);
}
if (
!manifest.spec.compatibility.architectures.includes(
environment.architecture,
)
) {
addFinding('architecture_unsupported', 'error', environment.architecture);
}
if (
!manifest.spec.compatibility.deploymentProfiles.includes(
environment.deploymentProfile,
)
) {
addFinding(
'deployment_profile_unsupported',
'error',
environment.deploymentProfile,
);
}
const availableRuntimes = new Map(
environment.runtimes.map((runtime) => [runtime.name, runtime.version]),
);
for (const requirement of manifest.spec.runtimes) {
const actual = availableRuntimes.get(requirement.name);
if (!actual) {
addFinding('runtime_missing', 'error', requirement.name);
} else if (
!semver().satisfies(actual, requirement.version, {
includePrerelease: true,
})
) {
addFinding(
'runtime_version_unsupported',
'error',
`${requirement.name}@${actual}`,
);
}
}
const memoryRecommendedBytes = resourceBytes(
manifest.spec.resources.memory.recommended,
'recommended memory',
);
const diskInstallBytes = resourceBytes(
manifest.spec.resources.disk.install,
'install disk',
);
const diskWorkingBytes = resourceBytes(
manifest.spec.resources.disk.working,
'working disk',
);
if (environment.availableMemoryBytes < memoryRecommendedBytes) {
addFinding(
'memory_below_recommendation',
'warning',
String(environment.availableMemoryBytes),
);
}
if (environment.availableDiskBytes < diskInstallBytes + diskWorkingBytes) {
addFinding(
'disk_insufficient',
'error',
String(environment.availableDiskBytes),
);
}
const candidatePermissions = permissionSet(manifest);
const previousPermissions = previous
? permissionSet(previous)
: new Set<string>();
const added = [...candidatePermissions]
.filter((permission) => !previousPermissions.has(permission))
.sort();
const removed = [...previousPermissions]
.filter((permission) => !candidatePermissions.has(permission))
.sort();
let operation: PluginPackagePlanOperation = 'install';
if (previous) {
const comparison = semver().compare(
manifest.metadata.version,
previous.metadata.version,
);
operation =
comparison > 0 ? 'upgrade' : comparison < 0 ? 'rollback' : 'reinstall';
}
findings.sort(
(left, right) =>
left.severity.localeCompare(right.severity) ||
left.code.localeCompare(right.code) ||
left.subject.localeCompare(right.subject),
);
return Object.freeze({
package: Object.freeze({
name: manifest.metadata.name,
...(previous ? { fromVersion: previous.metadata.version } : {}),
toVersion: manifest.metadata.version,
}),
operation,
compatible: findings.every((finding) => finding.severity !== 'error'),
risk: packageRisk(manifest),
approvalRequired: true,
permissionReapprovalRequired: previous ? added.length > 0 : true,
permissionDelta: Object.freeze({
added: Object.freeze(added),
removed: Object.freeze(removed),
}),
resources: Object.freeze({
memoryRecommendedBytes,
diskInstallBytes,
diskWorkingBytes,
}),
contents: Object.freeze({
tasks: manifest.spec.contents.tasks.length,
workflows: manifest.spec.contents.workflows.length,
prompts: manifest.spec.contents.prompts.length,
tools: manifest.spec.contents.tools.length,
}),
findings: Object.freeze(findings),
});
}
@@ -0,0 +1,226 @@
import { createHash } from 'node:crypto';
import {
PLUGIN_PACKAGE_ADMISSION_AUDIT_OPERATION,
PLUGIN_PACKAGE_ADMISSION_AUDIT_REASON,
PLUGIN_PACKAGE_INSTALL_ACTION_TYPE,
PluginPackageAdmissionBindingConflictError,
PluginPackageAdmissionReceiptConflictError,
assertPluginPackageAdmissionReplay,
type PluginPackageAdmissionRepository,
type PluginPackageAdmissionRequest,
} from './installation/pluginPackageAdmission';
import type {
ApprovedActionHandler,
ApprovedActionHandlerExecutionContext,
ApprovedActionHandlerInspection,
ApprovedActionHandlerResult,
} from '../approved-action/approvedActionDispatcher';
import {
PluginPackageInstallProposalBindingConflictError,
normalizePluginPackageInstallProposal,
resolvePluginPackageInstallProposal,
type PluginPackageInstallProposalRepository,
} from './pluginPackageProposal';
import type { SecurityAuditRecord } from '../security/audit/securityAudit';
function stableDigest(domain: string, dispatchId: string): string {
return createHash('sha256')
.update(domain)
.update('\0')
.update(dispatchId)
.digest('hex');
}
function stableIdentifier(domain: string, dispatchId: string): string {
return `ppa-${stableDigest(domain, dispatchId)}`;
}
function stableAuditEventId(dispatchId: string): string {
const bytes = Buffer.from(
stableDigest('qinglong/plugin-package-admission-audit-id@v1', dispatchId),
'hex',
);
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
const hex = bytes.toString('hex');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(
12,
16,
)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
}
export class PluginPackageApprovedActionHandler
implements ApprovedActionHandler
{
readonly actionType = PLUGIN_PACKAGE_INSTALL_ACTION_TYPE;
constructor(
readonly proposals: PluginPackageInstallProposalRepository,
readonly admissions: PluginPackageAdmissionRepository,
) {
if (
!proposals ||
typeof proposals.findProposalByActionRef !== 'function' ||
!admissions ||
typeof admissions.admit !== 'function' ||
typeof admissions.findAdmissionReceipt !== 'function' ||
typeof admissions.find !== 'function'
) {
throw new TypeError('Plugin Package Approved Action authority is invalid');
}
}
async inspect(
dispatch: ApprovedActionHandlerExecutionContext['dispatch'],
): Promise<ApprovedActionHandlerInspection> {
let proposal;
try {
proposal = await this.proposals.findProposalByActionRef(
dispatch.action.actionRef,
);
} catch {
return Object.freeze({
status: 'retry',
resultCode: 'package_proposal_unavailable',
});
}
if (!proposal) {
return Object.freeze({
status: 'blocked',
resultCode: 'package_proposal_missing',
});
}
try {
const normalized = normalizePluginPackageInstallProposal(proposal);
resolvePluginPackageInstallProposal(
normalized,
dispatch,
dispatch.createdAtMs,
);
return Object.freeze({
status: 'ready',
actionDigest: normalized.actionDigest,
});
} catch {
return Object.freeze({
status: 'blocked',
resultCode: 'package_proposal_rejected',
});
}
}
async execute(
context: Readonly<ApprovedActionHandlerExecutionContext>,
): Promise<Readonly<ApprovedActionHandlerResult>> {
const startedAtMs = context.execution.startedAtMs;
if (
context.execution.status !== 'executing' ||
startedAtMs === null ||
context.execution.leaseOwner !== context.fence.owner ||
context.execution.leaseToken !== context.fence.leaseToken ||
context.execution.version !== context.fence.version
) {
return Object.freeze({
outcome: 'failed',
resultCode: 'package_execution_rejected',
});
}
const proposal = await this.proposals.findProposalByActionRef(
context.dispatch.action.actionRef,
);
if (!proposal) {
return Object.freeze({
outcome: 'failed',
resultCode: 'package_proposal_missing',
});
}
let lock;
try {
lock = resolvePluginPackageInstallProposal(
proposal,
context.dispatch,
startedAtMs,
);
} catch (error) {
if (error instanceof PluginPackageInstallProposalBindingConflictError) {
return Object.freeze({
outcome: 'failed',
resultCode: 'package_proposal_rejected',
});
}
throw error;
}
const installationId = stableIdentifier(
'qinglong/plugin-package-admission-installation-id@v1',
context.dispatch.id,
);
const mutationId = stableIdentifier(
'qinglong/plugin-package-admission-mutation-id@v1',
context.dispatch.id,
);
const audit: SecurityAuditRecord = Object.freeze({
eventId: stableAuditEventId(context.dispatch.id),
requestId: context.dispatch.id,
operationId: PLUGIN_PACKAGE_ADMISSION_AUDIT_OPERATION,
projectId: context.dispatch.projectId,
subject: context.dispatch.consumedBy,
authenticationId: context.dispatch.approvalAuthenticationId,
outcome: 'allowed',
reasons: Object.freeze([PLUGIN_PACKAGE_ADMISSION_AUDIT_REASON]),
fence: context.dispatch.approvalFence,
occurredAtMs: startedAtMs,
});
const request: PluginPackageAdmissionRequest = Object.freeze({
lock,
proposalDigest: proposal.proposalDigest,
execution: context.execution,
installationId,
mutationId,
admittedAtMs: startedAtMs,
audit,
});
try {
const result = await this.admissions.admit(request);
return Object.freeze({
outcome: 'succeeded',
resultCode: 'package_admitted',
resultDigest: result.receipt.receiptDigest,
});
} catch (error) {
if (
error instanceof PluginPackageAdmissionBindingConflictError ||
error instanceof PluginPackageAdmissionReceiptConflictError
) {
return Object.freeze({
outcome: 'failed',
resultCode: 'package_admission_rejected',
});
}
const receipt = await this.admissions.findAdmissionReceipt(
context.dispatch.id,
);
if (!receipt) throw error;
const record = await this.admissions.find(
lock.projectId,
lock.packageName,
);
if (!record || record.installationId !== installationId) throw error;
assertPluginPackageAdmissionReplay(
context.dispatch,
proposal,
request,
receipt,
record,
);
return Object.freeze({
outcome: 'succeeded',
resultCode: 'package_admitted',
resultDigest: receipt.receiptDigest,
});
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,874 @@
import {
MAX_APPROVAL_LIFETIME_MS,
createApprovalRequest,
normalizeApprovalRequestRecord,
type ApprovalDecision,
type ApprovalDecisionMode,
type ApprovalRequestRecord,
type ApprovalRequestRepository,
type ApprovalRisk,
type CreateApprovalRequestResult,
type DecideApprovalRequestResult,
type ConsumeDurableApprovalRequestResult,
} from '../approved-action/approvedAction';
import type { ApprovedActionDispatchBatchSummary } from '../approved-action/approvedActionDispatcher';
import {
createPluginPackageInstallProposal,
normalizePluginPackageInstallProposal,
type CreatePluginPackageInstallProposalResult,
type PluginPackageInstallProposal,
type PluginPackageInstallProposalRepository,
} from './pluginPackageProposal';
import {
normalizePluginPackageInstallActionInput,
type PluginPackageInstallActionInput,
} from './installation/pluginPackageInstall';
import {
ProjectPolicyEngine,
type ProjectPolicyRequest,
} from '../security/project-policy/projectPolicy';
import {
normalizeSecurityPrincipal,
type SecurityPrincipal,
type SecuritySubject,
} from '../security/security';
import type { SecurityAuditRecord } from '../security/audit/securityAudit';
const DEFAULT_APPROVAL_LIFETIME_MS = 15 * 60 * 1000;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const REASON_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
const AUTHENTICATION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
export interface PluginPackageManagementDispatchPort {
dispatchBatch(
options?: Readonly<{ limit?: number }>,
): Promise<Readonly<ApprovedActionDispatchBatchSummary>>;
}
export const PLUGIN_PACKAGE_MANAGEMENT_QUOTA_OPERATIONS = [
'plugin-package.propose',
'plugin-package.decide',
'plugin-package.inspect',
] as const;
export type PluginPackageManagementQuotaOperation =
(typeof PLUGIN_PACKAGE_MANAGEMENT_QUOTA_OPERATIONS)[number];
export interface ConsumePluginPackageManagementQuotaCommand {
readonly projectId: string;
readonly subject: SecuritySubject;
readonly operation: PluginPackageManagementQuotaOperation;
readonly idempotencyKey: string;
}
export interface PluginPackageManagementQuotaResult {
readonly remaining: number;
readonly resetAtMs: number;
readonly observedAtMs: number;
}
export interface PluginPackageManagementQuotaPort {
consume(
command: ConsumePluginPackageManagementQuotaCommand,
): Promise<Readonly<PluginPackageManagementQuotaResult>>;
}
export interface PluginPackageManagementOptions {
readonly decisionMode: ApprovalDecisionMode;
readonly consumer: Readonly<{
subject: SecuritySubject;
authenticationId: string;
}>;
readonly approvalLifetimeMs?: number;
readonly risk?: ApprovalRisk;
readonly now?: () => number;
readonly quota?: PluginPackageManagementQuotaPort;
}
export interface ProposePluginPackageInstallRequest {
readonly actionRef: string;
readonly approvalRequestId: string;
readonly proposalAuditEventId: string;
readonly approvalAuditEventId: string;
readonly requestedAtMs: number;
readonly actionInput: PluginPackageInstallActionInput;
readonly principal: SecurityPrincipal;
}
export interface ProposePluginPackageInstallResult {
readonly proposalStatus: CreatePluginPackageInstallProposalResult['status'];
readonly approvalStatus: CreateApprovalRequestResult['status'];
readonly proposal: Readonly<PluginPackageInstallProposal>;
readonly approvalRequest: Readonly<ApprovalRequestRecord>;
}
export interface DecidePluginPackageInstallRequest {
readonly approvalRequestId: string;
readonly expectedVersion: number;
readonly decisionId: string;
readonly auditEventId: string;
readonly decision: ApprovalDecision;
readonly reasonCode: string;
readonly decidedAtMs: number;
readonly principal: SecurityPrincipal;
}
export interface ConsumePluginPackageInstallRequest {
readonly approvalRequestId: string;
readonly expectedVersion: number;
readonly consumptionId: string;
readonly dispatchId: string;
readonly auditEventId: string;
readonly consumedAtMs: number;
}
export interface InspectPluginPackageInstallResult {
readonly proposal: Readonly<PluginPackageInstallProposal> | null;
readonly approvalRequest: Readonly<ApprovalRequestRecord> | null;
}
export interface PluginPackageManagementService {
propose(
request: ProposePluginPackageInstallRequest,
): Promise<Readonly<ProposePluginPackageInstallResult>>;
decide(
request: DecidePluginPackageInstallRequest,
): Promise<Readonly<DecideApprovalRequestResult>>;
consume(
request: ConsumePluginPackageInstallRequest,
): Promise<Readonly<ConsumeDurableApprovalRequestResult>>;
inspect(
actionRef: string,
approvalRequestId: string,
): Promise<Readonly<InspectPluginPackageInstallResult>>;
dispatch(
limit?: number,
): Promise<Readonly<ApprovedActionDispatchBatchSummary>>;
}
export class PluginPackageManagementConfigurationError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_CONFIGURATION_INVALID';
constructor(message: string) {
super(`Plugin Package management configuration is invalid: ${message}`);
this.name = 'PluginPackageManagementConfigurationError';
}
}
export class PluginPackageManagementRequestError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_REQUEST_INVALID';
constructor(message: string) {
super(`Plugin Package management request is invalid: ${message}`);
this.name = 'PluginPackageManagementRequestError';
}
}
export class PluginPackageManagementAuthorizationError extends Error {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_FORBIDDEN';
constructor() {
super('Plugin Package management is not authorized');
this.name = 'PluginPackageManagementAuthorizationError';
}
}
export class PluginPackageManagementConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_CONFLICT';
constructor(message = 'Plugin Package management state conflicts') {
super(message);
this.name = 'PluginPackageManagementConflictError';
}
}
export class PluginPackageManagementUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package management is unavailable', options);
this.name = 'PluginPackageManagementUnavailableError';
}
}
export class PluginPackageManagementQuotaExceededError extends Error {
readonly code = 'PLUGIN_PACKAGE_MANAGEMENT_QUOTA_EXCEEDED';
constructor(readonly retryAfterMs: number) {
if (
!Number.isSafeInteger(retryAfterMs) ||
retryAfterMs < 1 ||
retryAfterMs > 5 * 60_000
) {
throw new TypeError(
'Plugin Package management quota retry delay is invalid',
);
}
super('Plugin Package management quota is exhausted');
this.name = 'PluginPackageManagementQuotaExceededError';
}
}
function exactObject(
value: unknown,
expectedKeys: readonly string[],
label: string,
): asserts value is Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new PluginPackageManagementRequestError(`${label} must be an object`);
}
const actual = Object.keys(value).sort();
const expected = [...expectedKeys].sort();
if (
actual.length !== expected.length ||
actual.some((key, index) => key !== expected[index])
) {
throw new PluginPackageManagementRequestError(`${label} shape is invalid`);
}
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
throw new PluginPackageManagementRequestError(`${label} is invalid`);
}
return value;
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
throw new PluginPackageManagementRequestError(
'action reference is invalid',
);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new PluginPackageManagementRequestError(`${label} is invalid`);
}
return value as number;
}
function positiveInteger(
value: unknown,
label: string,
maximum: number,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > maximum
) {
throw new PluginPackageManagementRequestError(`${label} is invalid`);
}
return value as number;
}
function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
function sameProposal(
stored: Readonly<PluginPackageInstallProposal>,
expected: Readonly<PluginPackageInstallProposal>,
): boolean {
return stored.proposalDigest === expected.proposalDigest;
}
function sameApprovalRequest(
stored: Readonly<ApprovalRequestRecord>,
expected: Readonly<ApprovalRequestRecord>,
): boolean {
return (
stored.id === expected.id &&
stored.projectId === expected.projectId &&
stored.action.actionRef === expected.action.actionRef &&
stored.action.actionType === expected.action.actionType &&
stored.action.permission === expected.action.permission &&
stored.action.actionDigest === expected.action.actionDigest &&
stored.action.previewDigest === expected.action.previewDigest &&
stored.risk === expected.risk &&
stored.decisionMode === expected.decisionMode &&
sameSubject(stored.requestedBy, expected.requestedBy) &&
stored.requestedAtMs === expected.requestedAtMs &&
stored.expiresAtMs === expected.expiresAtMs
);
}
function allowedPolicy(
effect: 'allow' | 'deny' | 'require_approval',
allowApproval: boolean,
): boolean {
return effect === 'allow' || (allowApproval && effect === 'require_approval');
}
function audit(
eventId: string,
requestId: string,
operationId: string,
projectId: string,
subject: Readonly<SecuritySubject>,
authenticationId: string,
outcome: 'allowed' | 'approval_required',
reasons: readonly string[],
fence: Readonly<{ projectVersion: number; bindingVersion: number | null }>,
occurredAtMs: number,
): SecurityAuditRecord {
return {
eventId,
requestId,
operationId,
projectId,
subject,
authenticationId,
outcome,
reasons,
fence,
occurredAtMs,
};
}
export function createPluginPackageManagementService(
policy: ProjectPolicyEngine,
proposals: PluginPackageInstallProposalRepository,
approvals: ApprovalRequestRepository,
dispatcher: PluginPackageManagementDispatchPort,
options: PluginPackageManagementOptions,
): PluginPackageManagementService {
if (
!policy ||
typeof policy.authorize !== 'function' ||
typeof policy.decide !== 'function'
) {
throw new PluginPackageManagementConfigurationError(
'Project policy is invalid',
);
}
if (
!proposals ||
typeof proposals.findProposalByActionRef !== 'function' ||
typeof proposals.createProposal !== 'function'
) {
throw new PluginPackageManagementConfigurationError(
'proposal repository is invalid',
);
}
if (
!approvals ||
typeof approvals.findById !== 'function' ||
typeof approvals.create !== 'function' ||
typeof approvals.decide !== 'function' ||
typeof approvals.consume !== 'function'
) {
throw new PluginPackageManagementConfigurationError(
'approval repository is invalid',
);
}
if (!dispatcher || typeof dispatcher.dispatchBatch !== 'function') {
throw new PluginPackageManagementConfigurationError(
'dispatcher is invalid',
);
}
if (!options || typeof options !== 'object' || Array.isArray(options)) {
throw new PluginPackageManagementConfigurationError('options are invalid');
}
const optionKeys = Object.keys(options);
if (
optionKeys.some(
(key) =>
key !== 'decisionMode' &&
key !== 'consumer' &&
key !== 'approvalLifetimeMs' &&
key !== 'risk' &&
key !== 'now' &&
key !== 'quota',
)
) {
throw new PluginPackageManagementConfigurationError(
'options shape is invalid',
);
}
if (
options.decisionMode !== 'human_confirmation' &&
options.decisionMode !== 'separation_of_duty'
) {
throw new PluginPackageManagementConfigurationError(
'decision mode is invalid',
);
}
if (
!options.consumer ||
typeof options.consumer !== 'object' ||
Array.isArray(options.consumer) ||
Object.keys(options.consumer).length !== 2 ||
!Object.hasOwn(options.consumer, 'subject') ||
!Object.hasOwn(options.consumer, 'authenticationId') ||
options.consumer.subject?.type !== 'system' ||
typeof options.consumer.subject.id !== 'string' ||
options.consumer.subject.id.length < 1 ||
options.consumer.subject.id.length > 255 ||
!AUTHENTICATION_ID_PATTERN.test(options.consumer.authenticationId)
) {
throw new PluginPackageManagementConfigurationError(
'consumer authority is invalid',
);
}
const approvalLifetimeMs =
options.approvalLifetimeMs ?? DEFAULT_APPROVAL_LIFETIME_MS;
if (
!Number.isSafeInteger(approvalLifetimeMs) ||
approvalLifetimeMs < 1_000 ||
approvalLifetimeMs > MAX_APPROVAL_LIFETIME_MS
) {
throw new PluginPackageManagementConfigurationError(
'approval lifetime is invalid',
);
}
const risk = options.risk ?? 'high';
if (!['low', 'medium', 'high', 'critical'].includes(risk)) {
throw new PluginPackageManagementConfigurationError('risk is invalid');
}
if (options.now !== undefined && typeof options.now !== 'function') {
throw new PluginPackageManagementConfigurationError('clock is invalid');
}
if (
options.quota !== undefined &&
(!options.quota ||
typeof options.quota !== 'object' ||
Array.isArray(options.quota) ||
typeof options.quota.consume !== 'function')
) {
throw new PluginPackageManagementConfigurationError('quota is invalid');
}
const now = options.now ?? Date.now;
const consumer = Object.freeze({
subject: Object.freeze({
type: 'system' as const,
id: options.consumer.subject.id,
}),
authenticationId: options.consumer.authenticationId,
});
const currentTime = (): number => {
const value = now();
if (!Number.isSafeInteger(value) || value < 0) {
throw new PluginPackageManagementUnavailableError();
}
return value;
};
const authorizePrincipal = async (
principalValue: SecurityPrincipal,
projectId: string,
permission: 'package.manage' | 'approval.decide',
observedAtMs: number,
allowApproval: boolean,
) => {
let principal: Readonly<SecurityPrincipal>;
try {
principal = normalizeSecurityPrincipal(principalValue, observedAtMs);
} catch {
throw new PluginPackageManagementAuthorizationError();
}
let decision;
try {
decision = await policy.authorize(principal, projectId, permission);
} catch (error) {
throw new PluginPackageManagementUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
if (
!allowedPolicy(decision.effect, allowApproval) ||
decision.fence === null
) {
throw new PluginPackageManagementAuthorizationError();
}
return Object.freeze({ principal, fence: decision.fence });
};
const consumeQuota = async (
projectId: string,
principal: Readonly<SecurityPrincipal>,
operation: PluginPackageManagementQuotaOperation,
idempotencyKey: string,
): Promise<void> => {
if (!options.quota) return;
try {
await options.quota.consume({
projectId,
subject: principal.subject,
operation,
idempotencyKey,
});
} catch (error) {
if (error instanceof PluginPackageManagementQuotaExceededError) {
throw error;
}
throw new PluginPackageManagementUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
};
const propose = async (
request: ProposePluginPackageInstallRequest,
): Promise<Readonly<ProposePluginPackageInstallResult>> => {
exactObject(
request,
[
'actionRef',
'approvalRequestId',
'proposalAuditEventId',
'approvalAuditEventId',
'requestedAtMs',
'actionInput',
'principal',
],
'proposal request',
);
const requestedActionRef = actionRef(request.actionRef);
const approvalRequestId = identifier(
request.approvalRequestId,
'approval request id',
);
const requestedAtMs = timestamp(request.requestedAtMs, 'request time');
const observedAtMs = currentTime();
if (
requestedAtMs > observedAtMs ||
observedAtMs >= requestedAtMs + approvalLifetimeMs
) {
throw new PluginPackageManagementRequestError(
'request time is outside the approval lifetime',
);
}
let normalizedActionInput: Readonly<PluginPackageInstallActionInput>;
try {
normalizedActionInput = normalizePluginPackageInstallActionInput(
request.actionInput,
);
} catch {
throw new PluginPackageManagementRequestError(
'install action input is invalid',
);
}
const { principal, fence } = await authorizePrincipal(
request.principal,
normalizedActionInput.projectId,
'package.manage',
observedAtMs,
true,
);
await consumeQuota(
normalizedActionInput.projectId,
principal,
'plugin-package.propose',
requestedActionRef,
);
const expectedProposal = createPluginPackageInstallProposal({
actionRef: requestedActionRef,
actionInput: normalizedActionInput,
proposedBy: principal.subject,
proposalFence: fence,
createdAtMs: requestedAtMs,
});
let proposalResult: Readonly<CreatePluginPackageInstallProposalResult>;
const existingProposal = await proposals.findProposalByActionRef(
requestedActionRef,
);
if (existingProposal) {
const normalized =
normalizePluginPackageInstallProposal(existingProposal);
if (!sameProposal(normalized, expectedProposal)) {
throw new PluginPackageManagementConflictError(
'Plugin Package proposal identity already has different content',
);
}
proposalResult = Object.freeze({
status: 'existing' as const,
proposal: normalized,
});
} else {
proposalResult = await proposals.createProposal({
proposal: expectedProposal,
audit: audit(
identifier(request.proposalAuditEventId, 'proposal audit event id'),
requestedActionRef,
'plugin_package.propose',
expectedProposal.projectId,
principal.subject,
principal.authenticationId,
'allowed',
['package_proposal'],
fence,
requestedAtMs,
),
});
}
const proposal = normalizePluginPackageInstallProposal(
proposalResult.proposal,
);
const approval = createApprovalRequest({
id: approvalRequestId,
projectId: proposal.projectId,
action: {
permission: proposal.permission,
actionType: proposal.actionType,
actionRef: proposal.actionRef,
actionDigest: proposal.actionDigest,
previewDigest: proposal.previewDigest,
},
risk,
decisionMode: options.decisionMode,
requestedBy: principal.subject,
requestedAtMs,
expiresAtMs: requestedAtMs + approvalLifetimeMs,
requestFence: fence,
});
let approvalResult: Readonly<CreateApprovalRequestResult>;
const existingApproval = await approvals.findById(approvalRequestId);
if (existingApproval) {
const normalized = normalizeApprovalRequestRecord(existingApproval);
if (!sameApprovalRequest(normalized, approval)) {
throw new PluginPackageManagementConflictError(
'Approval request identity already has different content',
);
}
approvalResult = Object.freeze({
status: 'existing' as const,
request: normalized,
});
} else {
approvalResult = await approvals.create({
request: approval,
audit: audit(
identifier(request.approvalAuditEventId, 'approval audit event id'),
approvalRequestId,
'approval.request',
proposal.projectId,
principal.subject,
principal.authenticationId,
'approval_required',
['package_review'],
fence,
requestedAtMs,
),
});
}
return Object.freeze({
proposalStatus: proposalResult.status,
approvalStatus: approvalResult.status,
proposal,
approvalRequest: approvalResult.request,
});
};
const decide = async (
request: DecidePluginPackageInstallRequest,
): Promise<Readonly<DecideApprovalRequestResult>> => {
exactObject(
request,
[
'approvalRequestId',
'expectedVersion',
'decisionId',
'auditEventId',
'decision',
'reasonCode',
'decidedAtMs',
'principal',
],
'decision request',
);
const approvalRequestId = identifier(
request.approvalRequestId,
'approval request id',
);
const expectedVersion = positiveInteger(
request.expectedVersion,
'expected version',
2_147_483_647,
);
const decisionId = identifier(request.decisionId, 'decision id');
if (request.decision !== 'approved' && request.decision !== 'rejected') {
throw new PluginPackageManagementRequestError('decision is invalid');
}
if (
typeof request.reasonCode !== 'string' ||
!REASON_PATTERN.test(request.reasonCode)
) {
throw new PluginPackageManagementRequestError(
'decision reason is invalid',
);
}
const decidedAtMs = timestamp(request.decidedAtMs, 'decision time');
const observedAtMs = currentTime();
if (decidedAtMs > observedAtMs) {
throw new PluginPackageManagementRequestError(
'decision time is in the future',
);
}
const current = await approvals.findById(approvalRequestId);
if (!current) {
throw new PluginPackageManagementConflictError(
'Approval request does not exist',
);
}
const approval = normalizeApprovalRequestRecord(current);
const { principal, fence } = await authorizePrincipal(
request.principal,
approval.projectId,
'approval.decide',
observedAtMs,
false,
);
await consumeQuota(
approval.projectId,
principal,
'plugin-package.decide',
decisionId,
);
return approvals.decide({
requestId: approvalRequestId,
expectedVersion,
decisionId,
decision: request.decision,
reasonCode: request.reasonCode,
principal,
decidedAtMs,
authorizationFence: fence,
audit: audit(
identifier(request.auditEventId, 'decision audit event id'),
approvalRequestId,
'approval.decide',
approval.projectId,
principal.subject,
principal.authenticationId,
'allowed',
['package_review'],
fence,
decidedAtMs,
),
});
};
const consume = async (
request: ConsumePluginPackageInstallRequest,
): Promise<Readonly<ConsumeDurableApprovalRequestResult>> => {
exactObject(
request,
[
'approvalRequestId',
'expectedVersion',
'consumptionId',
'dispatchId',
'auditEventId',
'consumedAtMs',
],
'consumption request',
);
const approvalRequestId = identifier(
request.approvalRequestId,
'approval request id',
);
const expectedVersion = positiveInteger(
request.expectedVersion,
'expected version',
2_147_483_647,
);
const consumptionId = identifier(request.consumptionId, 'consumption id');
const dispatchId = identifier(request.dispatchId, 'dispatch id');
const consumedAtMs = timestamp(request.consumedAtMs, 'consumption time');
const observedAtMs = currentTime();
if (consumedAtMs > observedAtMs) {
throw new PluginPackageManagementRequestError(
'consumption time is in the future',
);
}
const current = await approvals.findById(approvalRequestId);
if (!current) {
throw new PluginPackageManagementConflictError(
'Approval request does not exist',
);
}
const approval = normalizeApprovalRequestRecord(current);
let policyDecision;
try {
const policyRequest: ProjectPolicyRequest = {
subject: approval.requestedBy,
projectId: approval.projectId,
permission: 'package.manage',
};
policyDecision = await policy.decide(policyRequest);
} catch (error) {
throw new PluginPackageManagementUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
if (!allowedPolicy(policyDecision.effect, true) || !policyDecision.fence) {
throw new PluginPackageManagementAuthorizationError();
}
const fence = policyDecision.fence;
return approvals.consume({
requestId: approvalRequestId,
expectedVersion,
consumptionId,
dispatchId,
action: approval.action,
requestedBy: approval.requestedBy,
consumedBy: consumer.subject,
consumedAtMs,
authorizationFence: fence,
audit: audit(
identifier(request.auditEventId, 'consumption audit event id'),
approvalRequestId,
'approval.consume',
approval.projectId,
consumer.subject,
consumer.authenticationId,
'allowed',
['package_review'],
fence,
consumedAtMs,
),
});
};
return Object.freeze({
propose,
decide,
consume,
async inspect(requestedActionRef: string, approvalRequestIdValue: string) {
const normalizedActionRef = actionRef(requestedActionRef);
const approvalRequestId = identifier(
approvalRequestIdValue,
'approval request id',
);
const [proposal, approvalRequest] = await Promise.all([
proposals.findProposalByActionRef(normalizedActionRef),
approvals.findById(approvalRequestId),
]);
return Object.freeze({
proposal: proposal
? normalizePluginPackageInstallProposal(proposal)
: null,
approvalRequest: approvalRequest
? normalizeApprovalRequestRecord(approvalRequest)
: null,
});
},
dispatch(limit?: number) {
return dispatcher.dispatchBatch(
limit === undefined
? undefined
: { limit: positiveInteger(limit, 'dispatch limit', 64) },
);
},
});
}
@@ -0,0 +1,318 @@
import { createHash } from 'node:crypto';
import {
normalizeApprovedActionDispatchRecord,
normalizeApprovedActionFence,
type ApprovedActionDispatchRecord,
} from '../approved-action/approvedAction';
import {
createPluginPackageLock,
normalizePluginPackageInstallActionInput,
pluginPackageInstallActionDigest,
pluginPackageInstallPlanDigest,
type PluginPackageInstallActionInput,
type PluginPackageLock,
} from './installation/pluginPackageInstall';
import {
normalizeProjectPolicySubject,
} from '../security/project-policy/projectPolicy';
import type {
SecurityPolicyFence,
SecuritySubject,
} from '../security/security';
import type { SecurityAuditRecord } from '../security/audit/securityAudit';
export const PLUGIN_PACKAGE_INSTALL_PROPOSAL_SCHEMA =
'qinglong/plugin-package-install-proposal@v1' as const;
export const PLUGIN_PACKAGE_INSTALL_ACTION_TYPE =
'plugin_package.install' as const;
export const PLUGIN_PACKAGE_INSTALL_PERMISSION = 'package.manage' as const;
export interface PluginPackageInstallProposal {
readonly schema: typeof PLUGIN_PACKAGE_INSTALL_PROPOSAL_SCHEMA;
readonly actionRef: string;
readonly projectId: string;
readonly actionType: typeof PLUGIN_PACKAGE_INSTALL_ACTION_TYPE;
readonly permission: typeof PLUGIN_PACKAGE_INSTALL_PERMISSION;
readonly actionInput: Readonly<PluginPackageInstallActionInput>;
readonly actionDigest: string;
readonly previewDigest: string;
readonly proposedBy: Readonly<SecuritySubject>;
readonly proposalFence: Readonly<SecurityPolicyFence>;
readonly createdAtMs: number;
readonly proposalDigest: string;
}
export interface CreatePluginPackageInstallProposalInput {
readonly actionRef: string;
readonly actionInput: PluginPackageInstallActionInput;
readonly proposedBy: SecuritySubject;
readonly proposalFence: SecurityPolicyFence;
readonly createdAtMs: number;
}
export interface PluginPackageInstallProposalRepository {
findProposalByActionRef(
actionRef: string,
): Promise<Readonly<PluginPackageInstallProposal> | null>;
createProposal(
command: CreatePluginPackageInstallProposalCommand,
): Promise<Readonly<CreatePluginPackageInstallProposalResult>>;
}
export interface CreatePluginPackageInstallProposalCommand {
readonly proposal: PluginPackageInstallProposal;
readonly audit: SecurityAuditRecord;
}
export interface CreatePluginPackageInstallProposalResult {
readonly status: 'created' | 'existing';
readonly proposal: Readonly<PluginPackageInstallProposal>;
}
export class InvalidPluginPackageInstallProposalError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_INSTALL_PROPOSAL_INVALID';
constructor(message: string) {
super(`Plugin Package install proposal is invalid: ${message}`);
this.name = 'InvalidPluginPackageInstallProposalError';
}
}
export class PluginPackageInstallProposalBindingConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_PROPOSAL_BINDING_CONFLICT';
constructor() {
super('Plugin Package install proposal does not match its dispatch');
this.name = 'PluginPackageInstallProposalBindingConflictError';
}
}
export class PluginPackageInstallProposalConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_PROPOSAL_CONFLICT';
constructor() {
super('Plugin Package install proposal conflicts with durable authority');
this.name = 'PluginPackageInstallProposalConflictError';
}
}
export class PluginPackageInstallProposalUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_INSTALL_PROPOSAL_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package install proposal authority is unavailable', options);
this.name = 'PluginPackageInstallProposalUnavailableError';
}
}
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
throw new InvalidPluginPackageInstallProposalError(
`${label} must be an object`,
);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key, index) => key !== canonical[index])
) {
throw new InvalidPluginPackageInstallProposalError(
`${label} shape is invalid`,
);
}
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
throw new InvalidPluginPackageInstallProposalError(
'action reference is invalid',
);
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
throw new InvalidPluginPackageInstallProposalError(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidPluginPackageInstallProposalError(`${label} is invalid`);
}
return value as number;
}
function contractDigest(domain: string, value: unknown): string {
return createHash('sha256')
.update(domain)
.update('\0')
.update(JSON.stringify(value))
.digest('hex');
}
function withoutProposalDigest(
value: Omit<PluginPackageInstallProposal, 'proposalDigest'>,
): Omit<PluginPackageInstallProposal, 'proposalDigest'> {
return Object.freeze(value);
}
function withProposalDigest(
value: Omit<PluginPackageInstallProposal, 'proposalDigest'>,
): Readonly<PluginPackageInstallProposal> {
const normalized = withoutProposalDigest(value);
return Object.freeze({
...normalized,
proposalDigest: contractDigest(
'qinglong/plugin-package-install-proposal-digest@v1',
normalized,
),
});
}
export function createPluginPackageInstallProposal(
inputValue: CreatePluginPackageInstallProposalInput,
): Readonly<PluginPackageInstallProposal> {
const input = dataRecord(inputValue, 'proposal input');
exactKeys(
input,
[
'actionRef',
'actionInput',
'proposedBy',
'proposalFence',
'createdAtMs',
],
'proposal input',
);
const actionInput = normalizePluginPackageInstallActionInput(
inputValue.actionInput,
);
const proposedBy = normalizeProjectPolicySubject(inputValue.proposedBy);
return withProposalDigest({
schema: PLUGIN_PACKAGE_INSTALL_PROPOSAL_SCHEMA,
actionRef: actionRef(inputValue.actionRef),
projectId: actionInput.projectId,
actionType: PLUGIN_PACKAGE_INSTALL_ACTION_TYPE,
permission: PLUGIN_PACKAGE_INSTALL_PERMISSION,
actionInput,
actionDigest: pluginPackageInstallActionDigest(actionInput),
previewDigest: pluginPackageInstallPlanDigest(actionInput.plan),
proposedBy,
proposalFence: normalizeApprovedActionFence(inputValue.proposalFence),
createdAtMs: timestamp(inputValue.createdAtMs, 'creation time'),
});
}
export function normalizePluginPackageInstallProposal(
value: PluginPackageInstallProposal,
): Readonly<PluginPackageInstallProposal> {
const proposal = dataRecord(value, 'proposal');
exactKeys(
proposal,
[
'schema',
'actionRef',
'projectId',
'actionType',
'permission',
'actionInput',
'actionDigest',
'previewDigest',
'proposedBy',
'proposalFence',
'createdAtMs',
'proposalDigest',
],
'proposal',
);
if (
value.schema !== PLUGIN_PACKAGE_INSTALL_PROPOSAL_SCHEMA ||
value.actionType !== PLUGIN_PACKAGE_INSTALL_ACTION_TYPE ||
value.permission !== PLUGIN_PACKAGE_INSTALL_PERMISSION
) {
throw new InvalidPluginPackageInstallProposalError(
'schema or action authority is invalid',
);
}
const normalized = createPluginPackageInstallProposal({
actionRef: actionRef(value.actionRef),
actionInput: value.actionInput,
proposedBy: value.proposedBy,
proposalFence: value.proposalFence,
createdAtMs: timestamp(value.createdAtMs, 'creation time'),
});
const proposalDigest = digest(value.proposalDigest, 'proposal digest');
if (
value.projectId !== normalized.projectId ||
value.actionDigest !== normalized.actionDigest ||
value.previewDigest !== normalized.previewDigest ||
proposalDigest !== normalized.proposalDigest
) {
throw new InvalidPluginPackageInstallProposalError(
'proposal digest or derived binding is invalid',
);
}
return normalized;
}
export function resolvePluginPackageInstallProposal(
proposalValue: PluginPackageInstallProposal,
dispatchValue: ApprovedActionDispatchRecord,
createdAtMsValue: number,
): Readonly<PluginPackageLock> {
const proposal = normalizePluginPackageInstallProposal(proposalValue);
const dispatch = normalizeApprovedActionDispatchRecord(dispatchValue);
const createdAtMs = timestamp(createdAtMsValue, 'lock creation time');
if (
dispatch.projectId !== proposal.projectId ||
dispatch.action.actionRef !== proposal.actionRef ||
dispatch.action.actionType !== proposal.actionType ||
dispatch.action.permission !== proposal.permission ||
dispatch.action.actionDigest !== proposal.actionDigest ||
dispatch.action.previewDigest !== proposal.previewDigest ||
dispatch.requestedBy.type !== proposal.proposedBy.type ||
dispatch.requestedBy.id !== proposal.proposedBy.id ||
dispatch.createdAtMs < proposal.createdAtMs ||
createdAtMs < dispatch.createdAtMs ||
createdAtMs >= dispatch.expiresAtMs
) {
throw new PluginPackageInstallProposalBindingConflictError();
}
return createPluginPackageLock({
...proposal.actionInput,
approval: {
requestId: dispatch.approvalRequestId,
requestVersion: dispatch.approvalRequestVersion,
dispatchId: dispatch.id,
actionDigest: dispatch.action.actionDigest,
previewDigest: dispatch.action.previewDigest,
approvedBy: dispatch.approvedBy,
approvedAtMs: dispatch.approvedAtMs,
expiresAtMs: dispatch.expiresAtMs,
fence: dispatch.approvalFence,
},
createdAtMs,
});
}
@@ -0,0 +1,445 @@
import { createHash } from 'node:crypto';
import {
MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES,
MAX_PLUGIN_PACKAGE_CONTENT_PATH_BYTES,
type PluginPackageContents,
} from './pluginPackage';
export const PLUGIN_PACKAGE_RESOURCE_GENERATION_SCHEMA =
'qinglong/plugin-package-resource-generation@v1' as const;
export const PLUGIN_PACKAGE_RESOURCE_KINDS = [
'prompt',
'task',
'tool',
'workflow',
] as const;
export const MAX_PLUGIN_PACKAGE_RESOURCE_PATH_BYTES =
MAX_PLUGIN_PACKAGE_CONTENT_PATH_BYTES;
export const MAX_PLUGIN_PACKAGE_RESOURCE_GENERATION = 2_147_483_647;
export type PluginPackageResourceKind =
(typeof PLUGIN_PACKAGE_RESOURCE_KINDS)[number];
export interface PluginPackageResourceReference {
readonly kind: PluginPackageResourceKind;
readonly path: string;
}
export interface PluginPackageResourceGeneration {
readonly schema: typeof PLUGIN_PACKAGE_RESOURCE_GENERATION_SCHEMA;
readonly installationId: string;
readonly projectId: string;
readonly packageName: string;
readonly lockDigest: string;
readonly generation: number;
readonly previousActiveLockDigest: string | null;
readonly contentDigest: string;
readonly resources: readonly Readonly<PluginPackageResourceReference>[];
readonly generationDigest: string;
}
export interface CreatePluginPackageResourceGenerationInput {
readonly installationId: string;
readonly projectId: string;
readonly packageName: string;
readonly lockDigest: string;
readonly generation: number;
readonly previousActiveLockDigest: string | null;
readonly contentDigest: string;
readonly contents: Readonly<PluginPackageContents>;
}
export interface CreatePluginPackageResourceGenerationFromReferencesInput {
readonly installationId: string;
readonly projectId: string;
readonly packageName: string;
readonly lockDigest: string;
readonly generation: number;
readonly previousActiveLockDigest: string | null;
readonly contentDigest: string;
readonly resources: readonly Readonly<PluginPackageResourceReference>[];
}
export interface PluginPackageResourceGenerationSource {
findActiveResourceGeneration(
projectId: string,
packageName: string,
): Promise<Readonly<PluginPackageResourceGeneration> | null>;
}
export class InvalidPluginPackageResourceGenerationError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_RESOURCE_GENERATION_INVALID';
constructor(message: string) {
super(`Plugin Package resource generation is invalid: ${message}`);
this.name = 'InvalidPluginPackageResourceGenerationError';
}
}
const IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PACKAGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const DIGEST = /^[0-9a-f]{64}$/;
const RESOURCE_DIRECTORY = Object.freeze({
prompt: 'prompts',
task: 'tasks',
tool: 'tools',
workflow: 'workflows',
} satisfies Readonly<Record<PluginPackageResourceKind, string>>);
const GENERATION_DIGEST_DOMAIN = Buffer.from(
'qinglong/plugin-package-resource-generation-digest@v1\0',
'utf8',
);
function invalid(message: string): never {
throw new InvalidPluginPackageResourceGenerationError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const stringKeys = actual.filter(
(key): key is string => typeof key === 'string',
);
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
stringKeys.length !== canonical.length ||
stringKeys.sort().some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function boundedDenseArray(value: unknown, label: string): readonly unknown[] {
if (
!Array.isArray(value) ||
value.length > MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES
) {
return invalid(`${label} is invalid`);
}
const keys = Object.keys(value);
const ownKeys = Reflect.ownKeys(value);
if (
ownKeys.length !== value.length + 1 ||
!ownKeys.includes('length') ||
keys.length !== value.length ||
keys.some((key, index) => key !== String(index))
) {
return invalid(`${label} must be a dense data array`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
keys.some((key) => {
const descriptor = descriptors[key];
return (
descriptor === undefined ||
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true
);
})
) {
return invalid(`${label} must be a dense data array`);
}
return value;
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME.test(value)) {
return invalid('package name is invalid');
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function generation(value: unknown): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > MAX_PLUGIN_PACKAGE_RESOURCE_GENERATION
) {
return invalid('generation is invalid');
}
return value as number;
}
function resourcePath(value: unknown, kind: PluginPackageResourceKind): string {
if (
typeof value !== 'string' ||
value.length === 0 ||
Buffer.byteLength(value, 'utf8') > MAX_PLUGIN_PACKAGE_RESOURCE_PATH_BYTES ||
value.startsWith('/') ||
value.includes('\\') ||
value.includes('\0')
) {
return invalid('resource path is invalid');
}
const segments = value.split('/');
if (
segments.length < 2 ||
segments[0] !== RESOURCE_DIRECTORY[kind] ||
segments.some(
(segment) => segment.length === 0 || segment === '.' || segment === '..',
)
) {
return invalid('resource path is invalid');
}
return value;
}
function compareResourceReferences(
left: Readonly<PluginPackageResourceReference>,
right: Readonly<PluginPackageResourceReference>,
): number {
const kind = left.kind.localeCompare(right.kind);
return kind === 0 ? left.path.localeCompare(right.path) : kind;
}
export function normalizePluginPackageResourceReferences(
value: unknown,
): readonly Readonly<PluginPackageResourceReference>[] {
const entries = boundedDenseArray(value, 'resources');
const seen = new Set<string>();
const resources = entries.map((entryValue) => {
const entry = dataRecord(entryValue, 'resource reference');
exactKeys(entry, ['kind', 'path'], 'resource reference');
if (
!PLUGIN_PACKAGE_RESOURCE_KINDS.includes(
entry.kind as PluginPackageResourceKind,
)
) {
return invalid('resource kind is invalid');
}
const kind = entry.kind as PluginPackageResourceKind;
const path = resourcePath(entry.path, kind);
if (seen.has(path)) return invalid('resource path is duplicated');
seen.add(path);
return Object.freeze({ kind, path });
});
const sorted = [...resources].sort(compareResourceReferences);
if (
resources.some(
(resource, index) =>
resource.kind !== sorted[index]?.kind ||
resource.path !== sorted[index]?.path,
)
) {
return invalid('resources are not in canonical order');
}
return Object.freeze(resources);
}
export function pluginPackageResourceReferencesFromContents(
value: Readonly<PluginPackageContents>,
): readonly Readonly<PluginPackageResourceReference>[] {
const contents = dataRecord(value, 'contents');
exactKeys(contents, ['prompts', 'tasks', 'tools', 'workflows'], 'contents');
const references: PluginPackageResourceReference[] = [];
const append = (kind: PluginPackageResourceKind, paths: unknown): void => {
const entries = boundedDenseArray(paths, `${kind} contents`);
if (
references.length + entries.length >
MAX_PLUGIN_PACKAGE_CONTENT_ENTRIES
) {
return invalid('resource budget is exceeded');
}
for (const path of entries) {
references.push(Object.freeze({ kind, path: resourcePath(path, kind) }));
}
};
append('prompt', contents.prompts);
append('task', contents.tasks);
append('tool', contents.tools);
append('workflow', contents.workflows);
references.sort(compareResourceReferences);
return normalizePluginPackageResourceReferences(references);
}
function unsignedGeneration(
value: Omit<PluginPackageResourceGeneration, 'generationDigest'>,
): Omit<PluginPackageResourceGeneration, 'generationDigest'> {
return value;
}
function resourceGenerationDigest(
value: Omit<PluginPackageResourceGeneration, 'generationDigest'>,
): string {
return createHash('sha256')
.update(GENERATION_DIGEST_DOMAIN)
.update(JSON.stringify(value), 'utf8')
.digest('hex');
}
function createWithResources(
input: Record<string, unknown>,
resources: readonly Readonly<PluginPackageResourceReference>[],
): Readonly<PluginPackageResourceGeneration> {
const previousActiveLockDigest =
input.previousActiveLockDigest === null
? null
: digest(input.previousActiveLockDigest, 'previous active lock digest');
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_RESOURCE_GENERATION_SCHEMA,
installationId: identifier(input.installationId, 'installation id'),
projectId: identifier(input.projectId, 'project id'),
packageName: packageName(input.packageName),
lockDigest: digest(input.lockDigest, 'lock digest'),
generation: generation(input.generation),
previousActiveLockDigest,
contentDigest: digest(input.contentDigest, 'content digest'),
resources,
});
return Object.freeze({
...unsigned,
generationDigest: resourceGenerationDigest(unsignedGeneration(unsigned)),
});
}
export function createPluginPackageResourceGeneration(
value: CreatePluginPackageResourceGenerationInput,
): Readonly<PluginPackageResourceGeneration> {
const input = dataRecord(value, 'generation input');
exactKeys(
input,
[
'installationId',
'projectId',
'packageName',
'lockDigest',
'generation',
'previousActiveLockDigest',
'contentDigest',
'contents',
],
'generation input',
);
return createWithResources(
input,
pluginPackageResourceReferencesFromContents(
input.contents as Readonly<PluginPackageContents>,
),
);
}
export function createPluginPackageResourceGenerationFromReferences(
value: CreatePluginPackageResourceGenerationFromReferencesInput,
): Readonly<PluginPackageResourceGeneration> {
const input = dataRecord(value, 'generation input');
exactKeys(
input,
[
'installationId',
'projectId',
'packageName',
'lockDigest',
'generation',
'previousActiveLockDigest',
'contentDigest',
'resources',
],
'generation input',
);
return createWithResources(
input,
normalizePluginPackageResourceReferences(input.resources),
);
}
export function normalizePluginPackageResourceGeneration(
value: unknown,
): Readonly<PluginPackageResourceGeneration> {
const generationValue = dataRecord(value, 'generation');
exactKeys(
generationValue,
[
'schema',
'installationId',
'projectId',
'packageName',
'lockDigest',
'generation',
'previousActiveLockDigest',
'contentDigest',
'resources',
'generationDigest',
],
'generation',
);
if (generationValue.schema !== PLUGIN_PACKAGE_RESOURCE_GENERATION_SCHEMA) {
return invalid('schema is invalid');
}
const previousActiveLockDigest =
generationValue.previousActiveLockDigest === null
? null
: digest(
generationValue.previousActiveLockDigest,
'previous active lock digest',
);
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_RESOURCE_GENERATION_SCHEMA,
installationId: identifier(
generationValue.installationId,
'installation id',
),
projectId: identifier(generationValue.projectId, 'project id'),
packageName: packageName(generationValue.packageName),
lockDigest: digest(generationValue.lockDigest, 'lock digest'),
generation: generation(generationValue.generation),
previousActiveLockDigest,
contentDigest: digest(generationValue.contentDigest, 'content digest'),
resources: normalizePluginPackageResourceReferences(
generationValue.resources,
),
});
const generationDigest = digest(
generationValue.generationDigest,
'generation digest',
);
if (
generationDigest !== resourceGenerationDigest(unsignedGeneration(unsigned))
) {
return invalid('generation digest does not match its payload');
}
return Object.freeze({ ...unsigned, generationDigest });
}
@@ -0,0 +1,612 @@
import {
InvalidPluginPackageResourceMaterializationError,
PluginPackageResourceMaterializationConflictError,
PluginPackageResourceMaterializationUnavailableError,
materializeActivePluginPackageResources,
normalizePluginPackageMaterializedRevision,
type PluginPackageMaterializedRevisionRepository,
type PluginPackageResourceByteSource,
type PluginPackageResourceLockSource,
} from './pluginPackageResourceMaterialization';
import type { PluginPackageResourceGenerationSource } from './pluginPackageResourceGeneration';
import {
InvalidPluginPackageTaskReconciliationError,
PluginPackageTaskReconciliationConflictError,
PluginPackageTaskReconciliationUnavailableError,
type PluginPackageTaskReconciliationReceipt,
type PluginPackageTaskReconciliationRepository,
} from './pluginPackageTaskReconciliation';
import { TaskSpecSemanticRegistry } from '../task-definition/taskSpecSemantic';
export const MAX_PLUGIN_PACKAGE_TASK_PUBLICATION_RECOVERY_PAGE_SIZE = 64;
export const MAX_PLUGIN_PACKAGE_TASK_PUBLICATION_RECOVERY_PAGES = 64;
export interface PluginPackageTaskPublicationPendingCandidate {
readonly projectId: string;
readonly packageName: string;
}
export interface PluginPackageTaskPublicationRecoveryCursor {
readonly projectId: string;
readonly packageName: string;
}
export interface PluginPackageTaskPublicationRecoveryPage {
readonly candidates: readonly Readonly<PluginPackageTaskPublicationPendingCandidate>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageTaskPublicationRecoveryCursor>;
}
export interface PluginPackageTaskPublicationRecoverySource {
listPendingPage(options: {
readonly limit: number;
readonly after?: Readonly<PluginPackageTaskPublicationRecoveryCursor>;
}): Promise<Readonly<PluginPackageTaskPublicationRecoveryPage>>;
}
export interface PluginPackageTaskPublicationCurrentResult {
readonly status: 'current';
readonly materialized: 'created' | 'existing';
readonly reconciled: 'created' | 'existing';
readonly generationDigest: string;
readonly revisionDigest: string;
readonly receipt: Readonly<PluginPackageTaskReconciliationReceipt>;
}
export interface PluginPackageTaskPublicationAbsentResult {
readonly status: 'absent';
}
export interface PluginPackageTaskPublicationSupersededResult {
readonly status: 'superseded';
readonly generationDigest: string;
}
export type PluginPackageTaskPublicationResult =
| Readonly<PluginPackageTaskPublicationCurrentResult>
| Readonly<PluginPackageTaskPublicationAbsentResult>
| Readonly<PluginPackageTaskPublicationSupersededResult>;
export type PluginPackageTaskPublicationRecoveryItemStatus =
| 'manual_required'
| 'retry'
| 'settled'
| 'superseded';
export interface PluginPackageTaskPublicationRecoveryItem {
readonly projectId: string;
readonly packageName: string;
readonly status: PluginPackageTaskPublicationRecoveryItemStatus;
}
export interface PluginPackageTaskPublicationRecoveryCycleResult {
readonly pages: number;
readonly scanned: number;
readonly settled: number;
readonly retry: number;
readonly manualRequired: number;
readonly superseded: number;
readonly remaining: boolean;
readonly safeToAdmit: boolean;
}
export class InvalidPluginPackageTaskPublicationError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_TASK_PUBLICATION_INVALID';
constructor(message: string) {
super(`Plugin Package Task publication is invalid: ${message}`);
this.name = 'InvalidPluginPackageTaskPublicationError';
}
}
export class PluginPackageTaskPublicationConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_TASK_PUBLICATION_CONFLICT';
constructor(message: string, options?: ErrorOptions) {
super(`Plugin Package Task publication conflicts with state: ${message}`, options);
this.name = 'PluginPackageTaskPublicationConflictError';
}
}
export class PluginPackageTaskPublicationUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_TASK_PUBLICATION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package Task publication is unavailable', options);
this.name = 'PluginPackageTaskPublicationUnavailableError';
}
}
const PACKAGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
function invalid(message: string): never {
throw new InvalidPluginPackageTaskPublicationError(message);
}
function record(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
required: readonly string[],
optional: readonly string[],
label: string,
): void {
const keys = Reflect.ownKeys(value);
const allowed = new Set([...required, ...optional]);
if (
keys.some((key) => typeof key !== 'string') ||
required.some((key) => !keys.includes(key)) ||
keys.some((key) => typeof key === 'string' && !allowed.has(key))
) {
invalid(`${label} shape is invalid`);
}
}
function projectId(value: unknown): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.includes('\0') ||
Buffer.byteLength(value, 'utf8') > 128
) {
return invalid('projectId is invalid');
}
return value;
}
function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME.test(value)) {
return invalid('packageName is invalid');
}
return value;
}
function positiveInteger(value: unknown, maximum: number, label: string): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > maximum
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function normalizeCandidate(
value: PluginPackageTaskPublicationPendingCandidate,
): Readonly<PluginPackageTaskPublicationPendingCandidate> {
const candidate = record(value, 'pending candidate');
exactKeys(candidate, ['packageName', 'projectId'], [], 'pending candidate');
return Object.freeze({
projectId: projectId(value.projectId),
packageName: packageName(value.packageName),
});
}
export function normalizePluginPackageTaskPublicationRecoveryCursor(
value: PluginPackageTaskPublicationRecoveryCursor,
): Readonly<PluginPackageTaskPublicationRecoveryCursor> {
const cursor = record(value, 'recovery cursor');
exactKeys(cursor, ['packageName', 'projectId'], [], 'recovery cursor');
return Object.freeze({
projectId: projectId(value.projectId),
packageName: packageName(value.packageName),
});
}
export function assertPluginPackageTaskPublicationRecoveryPageSize(
value: number,
): void {
positiveInteger(
value,
MAX_PLUGIN_PACKAGE_TASK_PUBLICATION_RECOVERY_PAGE_SIZE,
'recovery page size',
);
}
function compareCandidates(
left: Readonly<PluginPackageTaskPublicationPendingCandidate>,
right: Readonly<PluginPackageTaskPublicationPendingCandidate>,
): number {
return (
left.projectId.localeCompare(right.projectId) ||
left.packageName.localeCompare(right.packageName)
);
}
function normalizePage(
value: PluginPackageTaskPublicationRecoveryPage,
limit: number,
): Readonly<PluginPackageTaskPublicationRecoveryPage> {
const page = record(value, 'recovery page');
exactKeys(page, ['candidates', 'truncated'], ['next'], 'recovery page');
if (
!Array.isArray(value.candidates) ||
value.candidates.length > limit ||
typeof value.truncated !== 'boolean'
) {
return invalid('recovery page is invalid');
}
const candidates = Object.freeze(value.candidates.map(normalizeCandidate));
if (
candidates.some(
(candidate, index) =>
index > 0 &&
compareCandidates(candidates[index - 1]!, candidate) >= 0,
)
) {
return invalid('recovery candidates must be uniquely sorted');
}
const next =
value.next === undefined
? undefined
: normalizePluginPackageTaskPublicationRecoveryCursor(value.next);
const last = candidates.at(-1);
if (
value.truncated !== (next !== undefined) ||
(next &&
(!last ||
next.projectId !== last.projectId ||
next.packageName !== last.packageName))
) {
return invalid('recovery continuation is invalid');
}
return Object.freeze({
candidates,
truncated: value.truncated,
...(next ? { next } : {}),
});
}
function publicationAuthorities(options: {
readonly generationSource: PluginPackageResourceGenerationSource;
readonly lockSource: PluginPackageResourceLockSource;
readonly byteSource: PluginPackageResourceByteSource;
readonly materializedRepository: PluginPackageMaterializedRevisionRepository;
readonly reconciliationRepository: PluginPackageTaskReconciliationRepository;
readonly taskSpecSemanticRegistry: TaskSpecSemanticRegistry;
}): void {
const value = record(options, 'publication coordinator options');
exactKeys(
value,
[
'byteSource',
'generationSource',
'lockSource',
'materializedRepository',
'reconciliationRepository',
'taskSpecSemanticRegistry',
],
[],
'publication coordinator options',
);
if (
!options.generationSource ||
typeof options.generationSource.findActiveResourceGeneration !== 'function' ||
!options.lockSource ||
typeof options.lockSource.findLock !== 'function' ||
!options.byteSource ||
typeof options.byteSource.open !== 'function' ||
!options.materializedRepository ||
typeof options.materializedRepository.find !== 'function' ||
typeof options.materializedRepository.publish !== 'function' ||
!options.reconciliationRepository ||
typeof options.reconciliationRepository.find !== 'function' ||
typeof options.reconciliationRepository.reconcile !== 'function' ||
!(options.taskSpecSemanticRegistry instanceof TaskSpecSemanticRegistry)
) {
invalid('publication coordinator authority is invalid');
}
}
export class PluginPackageTaskPublicationCoordinator {
readonly #generationSource: PluginPackageResourceGenerationSource;
readonly #lockSource: PluginPackageResourceLockSource;
readonly #byteSource: PluginPackageResourceByteSource;
readonly #materializedRepository: PluginPackageMaterializedRevisionRepository;
readonly #reconciliationRepository: PluginPackageTaskReconciliationRepository;
readonly #registry: TaskSpecSemanticRegistry;
constructor(options: {
readonly generationSource: PluginPackageResourceGenerationSource;
readonly lockSource: PluginPackageResourceLockSource;
readonly byteSource: PluginPackageResourceByteSource;
readonly materializedRepository: PluginPackageMaterializedRevisionRepository;
readonly reconciliationRepository: PluginPackageTaskReconciliationRepository;
readonly taskSpecSemanticRegistry: TaskSpecSemanticRegistry;
}) {
publicationAuthorities(options);
this.#generationSource = options.generationSource;
this.#lockSource = options.lockSource;
this.#byteSource = options.byteSource;
this.#materializedRepository = options.materializedRepository;
this.#reconciliationRepository = options.reconciliationRepository;
this.#registry = options.taskSpecSemanticRegistry;
}
async publishActive(
projectIdValue: string,
packageNameValue: string,
): Promise<Readonly<PluginPackageTaskPublicationResult>> {
const identity = {
projectId: projectId(projectIdValue),
packageName: packageName(packageNameValue),
};
try {
const first = await this.#generationSource.findActiveResourceGeneration(
identity.projectId,
identity.packageName,
);
if (first === null) return Object.freeze({ status: 'absent' });
if (
first.projectId !== identity.projectId ||
first.packageName !== identity.packageName
) {
throw new PluginPackageTaskPublicationConflictError(
'generation source returned another Package identity',
);
}
let revision = await this.#materializedRepository.find(
first.generationDigest,
);
let materialized: 'created' | 'existing' = 'existing';
if (revision === null) {
const materializedValue = await materializeActivePluginPackageResources({
...identity,
generationSource: this.#generationSource,
lockSource: this.#lockSource,
byteSource: this.#byteSource,
taskSpecSemanticRegistry: this.#registry,
});
if (materializedValue === null) {
return Object.freeze({
status: 'superseded',
generationDigest: first.generationDigest,
});
}
if (materializedValue.generation.generationDigest !== first.generationDigest) {
return Object.freeze({
status: 'superseded',
generationDigest: first.generationDigest,
});
}
const publication = await this.#materializedRepository.publish(
materializedValue,
);
materialized = publication.status;
revision = publication.revision;
}
const normalizedRevision = normalizePluginPackageMaterializedRevision(
revision,
this.#registry,
);
if (
normalizedRevision.generation.generationDigest !==
first.generationDigest ||
normalizedRevision.generation.projectId !== identity.projectId ||
normalizedRevision.generation.packageName !== identity.packageName
) {
throw new PluginPackageTaskPublicationConflictError(
'durable materialized revision does not match the active generation',
);
}
const reconciliation = await this.#reconciliationRepository.reconcile(
normalizedRevision,
this.#generationSource,
);
const finalGeneration =
await this.#generationSource.findActiveResourceGeneration(
identity.projectId,
identity.packageName,
);
if (
finalGeneration === null ||
finalGeneration.generationDigest !== first.generationDigest
) {
return Object.freeze({
status: 'superseded',
generationDigest: first.generationDigest,
});
}
return Object.freeze({
status: 'current',
materialized,
reconciled: reconciliation.status,
generationDigest: first.generationDigest,
revisionDigest: normalizedRevision.revisionDigest,
receipt: reconciliation.receipt,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageTaskPublicationError ||
error instanceof PluginPackageTaskPublicationConflictError ||
error instanceof PluginPackageTaskPublicationUnavailableError
) {
throw error;
}
if (
error instanceof InvalidPluginPackageResourceMaterializationError ||
error instanceof InvalidPluginPackageTaskReconciliationError
) {
throw new InvalidPluginPackageTaskPublicationError(error.message);
}
if (
error instanceof PluginPackageResourceMaterializationConflictError ||
error instanceof PluginPackageTaskReconciliationConflictError
) {
throw new PluginPackageTaskPublicationConflictError(
'active generation publication fence changed',
{ cause: error },
);
}
if (
error instanceof PluginPackageResourceMaterializationUnavailableError ||
error instanceof PluginPackageTaskReconciliationUnavailableError
) {
throw new PluginPackageTaskPublicationUnavailableError({ cause: error });
}
throw new PluginPackageTaskPublicationUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
}
}
export class PluginPackageTaskPublicationRecoveryCoordinator {
readonly #source: PluginPackageTaskPublicationRecoverySource;
readonly #publisher: PluginPackageTaskPublicationCoordinator;
constructor(options: {
readonly source: PluginPackageTaskPublicationRecoverySource;
readonly publisher: PluginPackageTaskPublicationCoordinator;
}) {
const value = record(options, 'recovery coordinator options');
exactKeys(value, ['publisher', 'source'], [], 'recovery coordinator options');
if (
!options.source ||
typeof options.source.listPendingPage !== 'function' ||
!(options.publisher instanceof PluginPackageTaskPublicationCoordinator)
) {
invalid('recovery coordinator authority is invalid');
}
this.#source = options.source;
this.#publisher = options.publisher;
}
async recoverPage(options: {
readonly limit: number;
readonly after?: Readonly<PluginPackageTaskPublicationRecoveryCursor>;
}): Promise<
Readonly<{
items: readonly Readonly<PluginPackageTaskPublicationRecoveryItem>[];
truncated: boolean;
next?: Readonly<PluginPackageTaskPublicationRecoveryCursor>;
}>
> {
const value = record(options, 'recovery page options');
exactKeys(value, ['limit'], ['after'], 'recovery page options');
assertPluginPackageTaskPublicationRecoveryPageSize(options.limit);
const after =
options.after === undefined
? undefined
: normalizePluginPackageTaskPublicationRecoveryCursor(options.after);
let page: Readonly<PluginPackageTaskPublicationRecoveryPage>;
try {
page = normalizePage(
await this.#source.listPendingPage({
limit: options.limit,
...(after ? { after } : {}),
}),
options.limit,
);
} catch (error) {
if (error instanceof InvalidPluginPackageTaskPublicationError) throw error;
throw new PluginPackageTaskPublicationUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
const items: Readonly<PluginPackageTaskPublicationRecoveryItem>[] = [];
for (const candidate of page.candidates) {
let status: PluginPackageTaskPublicationRecoveryItemStatus;
try {
const published = await this.#publisher.publishActive(
candidate.projectId,
candidate.packageName,
);
status =
published.status === 'current'
? 'settled'
: published.status === 'superseded'
? 'superseded'
: 'manual_required';
} catch (error) {
status =
error instanceof InvalidPluginPackageTaskPublicationError ||
error instanceof PluginPackageTaskPublicationConflictError
? 'manual_required'
: 'retry';
}
items.push(Object.freeze({ ...candidate, status }));
}
return Object.freeze({
items: Object.freeze(items),
truncated: page.truncated,
...(page.next ? { next: page.next } : {}),
});
}
async recover(
options: {
readonly pageSize?: number;
readonly maxPages?: number;
} = {},
): Promise<Readonly<PluginPackageTaskPublicationRecoveryCycleResult>> {
const value = record(options, 'recovery cycle options');
exactKeys(value, [], ['maxPages', 'pageSize'], 'recovery cycle options');
const pageSize = positiveInteger(
options.pageSize ?? 8,
MAX_PLUGIN_PACKAGE_TASK_PUBLICATION_RECOVERY_PAGE_SIZE,
'recovery page size',
);
const maxPages = positiveInteger(
options.maxPages ?? 8,
MAX_PLUGIN_PACKAGE_TASK_PUBLICATION_RECOVERY_PAGES,
'recovery page count',
);
const counts = {
pages: 0,
scanned: 0,
settled: 0,
retry: 0,
manualRequired: 0,
superseded: 0,
};
let after: Readonly<PluginPackageTaskPublicationRecoveryCursor> | undefined;
let exhausted = false;
while (counts.pages < maxPages) {
const page = await this.recoverPage({
limit: pageSize,
...(after ? { after } : {}),
});
counts.pages += 1;
counts.scanned += page.items.length;
for (const item of page.items) {
if (item.status === 'settled') counts.settled += 1;
else if (item.status === 'retry') counts.retry += 1;
else if (item.status === 'manual_required') counts.manualRequired += 1;
else counts.superseded += 1;
}
if (!page.truncated) {
exhausted = true;
break;
}
after = page.next;
}
let probe: Readonly<PluginPackageTaskPublicationRecoveryPage>;
try {
probe = normalizePage(await this.#source.listPendingPage({ limit: 1 }), 1);
} catch (error) {
throw new PluginPackageTaskPublicationUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
const remaining = !exhausted || probe.candidates.length > 0;
return Object.freeze({
...counts,
remaining,
safeToAdmit:
!remaining && counts.retry === 0 && counts.manualRequired === 0,
});
}
}
@@ -0,0 +1,611 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageMaterializedRevision,
pluginPackageTaskDefinitionDrafts,
type PluginPackageMaterializedRevision,
type PluginPackageTaskDefinitionDraft,
} from './pluginPackageResourceMaterialization';
import type { PluginPackageResourceGenerationSource } from './pluginPackageResourceGeneration';
import {
createTaskDefinitionRecord,
normalizeTaskDefinitionRecord,
taskDefinitionContentDigest,
type AppendTaskDefinitionRevisionCommand,
type TaskDefinitionRecord,
} from '../task-definition/taskDefinition';
import { TaskSpecSemanticRegistry } from '../task-definition/taskSpecSemantic';
export const PLUGIN_PACKAGE_TASK_RECONCILIATION_SCHEMA =
'qinglong/plugin-package-task-reconciliation@v1' as const;
export const MAX_PLUGIN_PACKAGE_TASK_RECONCILIATION_ITEMS = 512;
export type PluginPackageTaskReconciliationDisposition =
| 'already_disabled'
| 'created'
| 'disabled'
| 'retained'
| 'updated';
export interface PluginPackageTaskOwnershipFact {
readonly taskId: string;
readonly packageName: string | null;
readonly current: Readonly<TaskDefinitionRecord> | null;
}
export interface PluginPackageTaskReconciliationItem {
readonly taskId: string;
readonly revision: number;
readonly disposition: PluginPackageTaskReconciliationDisposition;
readonly contentDigest: string;
}
export interface PluginPackageTaskReconciliationReceipt {
readonly schema: typeof PLUGIN_PACKAGE_TASK_RECONCILIATION_SCHEMA;
readonly projectId: string;
readonly packageName: string;
readonly generation: number;
readonly generationDigest: string;
readonly materializedRevisionDigest: string;
readonly lockDigest: string;
readonly previousLockDigest: string | null;
readonly committedAtMs: number;
readonly items: readonly Readonly<PluginPackageTaskReconciliationItem>[];
readonly receiptDigest: string;
}
export interface PluginPackageTaskReconciliationWrite {
readonly command: Readonly<AppendTaskDefinitionRevisionCommand>;
readonly definition: Readonly<TaskDefinitionRecord>;
}
export interface PluginPackageTaskReconciliationPlan {
readonly receipt: Readonly<PluginPackageTaskReconciliationReceipt>;
readonly writes: readonly Readonly<PluginPackageTaskReconciliationWrite>[];
}
export interface PlanPluginPackageTaskReconciliationInput {
readonly revision: Readonly<PluginPackageMaterializedRevision>;
readonly previousReceipt: Readonly<PluginPackageTaskReconciliationReceipt> | null;
readonly facts: readonly Readonly<PluginPackageTaskOwnershipFact>[];
readonly committedAtMs: number;
readonly taskSpecSemanticRegistry: TaskSpecSemanticRegistry;
}
export interface PluginPackageTaskReconciliationRepository {
find(
generationDigest: string,
): Promise<Readonly<PluginPackageTaskReconciliationReceipt> | null>;
reconcile(
revision: Readonly<PluginPackageMaterializedRevision>,
activeGenerationSource: PluginPackageResourceGenerationSource,
): Promise<
Readonly<{
status: 'created' | 'existing';
receipt: Readonly<PluginPackageTaskReconciliationReceipt>;
}>
>;
}
export class InvalidPluginPackageTaskReconciliationError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_TASK_RECONCILIATION_INVALID';
constructor(message: string) {
super(`Plugin Package Task reconciliation is invalid: ${message}`);
this.name = 'InvalidPluginPackageTaskReconciliationError';
}
}
export class PluginPackageTaskReconciliationConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_TASK_RECONCILIATION_CONFLICT';
constructor(message: string) {
super(`Plugin Package Task reconciliation conflicts with state: ${message}`);
this.name = 'PluginPackageTaskReconciliationConflictError';
}
}
export class PluginPackageTaskReconciliationUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_TASK_RECONCILIATION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package Task reconciliation is unavailable', options);
this.name = 'PluginPackageTaskReconciliationUnavailableError';
}
}
const DIGEST = /^[0-9a-f]{64}$/;
const PACKAGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const ITEM_DISPOSITIONS = Object.freeze([
'already_disabled',
'created',
'disabled',
'retained',
'updated',
] as const);
const RECEIPT_DIGEST_DOMAIN = Buffer.from(
'qinglong/plugin-package-task-reconciliation-receipt@v1\0',
'utf8',
);
const MUTATION_ID_DOMAIN = Buffer.from(
'qinglong/plugin-package-task-reconciliation-mutation@v1\0',
'utf8',
);
function invalid(message: string): never {
throw new InvalidPluginPackageTaskReconciliationError(message);
}
function conflict(message: string): never {
throw new PluginPackageTaskReconciliationConflictError(message);
}
function identifier(value: unknown, label: string): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.includes('\0') ||
Buffer.byteLength(value, 'utf8') > 128
) {
return invalid(`${label} is invalid`);
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function integer(value: unknown, label: string, minimum: number): number {
if (!Number.isSafeInteger(value) || (value as number) < minimum) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function exactKeys(
value: object,
required: readonly string[],
optional: readonly string[],
label: string,
): void {
const keys = Reflect.ownKeys(value);
const allowed = new Set([...required, ...optional]);
if (
keys.some((key) => typeof key !== 'string') ||
required.some((key) => !keys.includes(key)) ||
keys.some((key) => typeof key === 'string' && !allowed.has(key))
) {
invalid(`${label} shape is invalid`);
}
}
function denseItems(value: unknown): readonly unknown[] {
if (
!Array.isArray(value) ||
value.length > MAX_PLUGIN_PACKAGE_TASK_RECONCILIATION_ITEMS ||
Object.keys(value).some((key, index) => key !== String(index))
) {
return invalid('items are invalid');
}
return value;
}
function unsignedReceipt(
value: Omit<PluginPackageTaskReconciliationReceipt, 'receiptDigest'>,
): object {
return {
schema: value.schema,
projectId: value.projectId,
packageName: value.packageName,
generation: value.generation,
generationDigest: value.generationDigest,
materializedRevisionDigest: value.materializedRevisionDigest,
lockDigest: value.lockDigest,
previousLockDigest: value.previousLockDigest,
committedAtMs: value.committedAtMs,
items: value.items,
};
}
export function pluginPackageTaskReconciliationReceiptDigest(
value: Omit<PluginPackageTaskReconciliationReceipt, 'receiptDigest'>,
): string {
return createHash('sha256')
.update(RECEIPT_DIGEST_DOMAIN)
.update(JSON.stringify(unsignedReceipt(value)))
.digest('hex');
}
function mutationId(
generationDigest: string,
taskId: string,
disposition: 'created' | 'disabled' | 'updated',
): string {
const value = createHash('sha256')
.update(MUTATION_ID_DOMAIN)
.update(generationDigest)
.update('\0')
.update(taskId)
.update('\0')
.update(disposition)
.digest('hex')
.slice(0, 32);
return `${value.slice(0, 8)}-${value.slice(8, 12)}-4${value.slice(13, 16)}-a${value.slice(17, 20)}-${value.slice(20)}`;
}
function normalizeItem(
value: PluginPackageTaskReconciliationItem,
): Readonly<PluginPackageTaskReconciliationItem> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('item must be an object');
}
exactKeys(
value,
['contentDigest', 'disposition', 'revision', 'taskId'],
[],
'item',
);
if (!ITEM_DISPOSITIONS.includes(value.disposition)) {
return invalid('item disposition is invalid');
}
return Object.freeze({
taskId: identifier(value.taskId, 'item.taskId'),
revision: integer(value.revision, 'item.revision', 1),
disposition: value.disposition,
contentDigest: digest(value.contentDigest, 'item.contentDigest'),
});
}
export function normalizePluginPackageTaskReconciliationReceipt(
value: PluginPackageTaskReconciliationReceipt,
): Readonly<PluginPackageTaskReconciliationReceipt> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('receipt must be an object');
}
exactKeys(
value,
[
'committedAtMs',
'generation',
'generationDigest',
'items',
'lockDigest',
'materializedRevisionDigest',
'packageName',
'previousLockDigest',
'projectId',
'receiptDigest',
'schema',
],
[],
'receipt',
);
if (value.schema !== PLUGIN_PACKAGE_TASK_RECONCILIATION_SCHEMA) {
return invalid('receipt schema is invalid');
}
if (typeof value.packageName !== 'string' || !PACKAGE_NAME.test(value.packageName)) {
return invalid('packageName is invalid');
}
const items = denseItems(value.items).map((item) =>
normalizeItem(item as PluginPackageTaskReconciliationItem),
);
if (
items.some(
(item, index) =>
index > 0 && items[index - 1]!.taskId.localeCompare(item.taskId) >= 0,
)
) {
return invalid('items must be uniquely sorted by taskId');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_TASK_RECONCILIATION_SCHEMA,
projectId: identifier(value.projectId, 'projectId'),
packageName: value.packageName,
generation: integer(value.generation, 'generation', 1),
generationDigest: digest(value.generationDigest, 'generationDigest'),
materializedRevisionDigest: digest(
value.materializedRevisionDigest,
'materializedRevisionDigest',
),
lockDigest: digest(value.lockDigest, 'lockDigest'),
previousLockDigest:
value.previousLockDigest === null
? null
: digest(value.previousLockDigest, 'previousLockDigest'),
committedAtMs: integer(value.committedAtMs, 'committedAtMs', 0),
items: Object.freeze(items),
receiptDigest: digest(value.receiptDigest, 'receiptDigest'),
});
if (
normalized.receiptDigest !==
pluginPackageTaskReconciliationReceiptDigest(normalized)
) {
return invalid('receipt digest did not match');
}
return normalized;
}
function semanticDigest(
draft: Readonly<PluginPackageTaskDefinitionDraft>,
revision: number,
): string {
return taskDefinitionContentDigest({
projectId: draft.projectId,
taskId: draft.taskId,
revision,
name: draft.name,
...(draft.description === undefined
? {}
: { description: draft.description }),
kind: draft.kind,
spec: draft.spec,
labels: draft.labels,
enabled: draft.enabled,
});
}
function writeForDraft(
draft: Readonly<PluginPackageTaskDefinitionDraft>,
current: Readonly<TaskDefinitionRecord> | null,
generationDigest: string,
committedAtMs: number,
disposition: 'created' | 'updated',
): Readonly<PluginPackageTaskReconciliationWrite> {
const command = Object.freeze({
projectId: draft.projectId,
taskId: draft.taskId,
expectedRevision: current?.revision ?? null,
mutationId: mutationId(generationDigest, draft.taskId, disposition),
name: draft.name,
...(draft.description === undefined
? {}
: { description: draft.description }),
kind: draft.kind,
spec: draft.spec,
labels: draft.labels,
enabled: draft.enabled,
occurredAtMs: committedAtMs,
});
return Object.freeze({
command,
definition: createTaskDefinitionRecord(command, current?.createdAtMs ?? committedAtMs),
});
}
function disableWrite(
current: Readonly<TaskDefinitionRecord>,
generationDigest: string,
committedAtMs: number,
): Readonly<PluginPackageTaskReconciliationWrite> {
const command = Object.freeze({
projectId: current.projectId,
taskId: current.taskId,
expectedRevision: current.revision,
mutationId: mutationId(generationDigest, current.taskId, 'disabled'),
name: current.name,
...(current.description === undefined
? {}
: { description: current.description }),
kind: current.kind,
spec: current.spec,
labels: current.labels,
enabled: false,
occurredAtMs: committedAtMs,
});
return Object.freeze({
command,
definition: createTaskDefinitionRecord(command, current.createdAtMs),
});
}
export function pluginPackageTaskReconciliationTaskIds(
revisionValue: Readonly<PluginPackageMaterializedRevision>,
previousReceipt: Readonly<PluginPackageTaskReconciliationReceipt> | null,
registry: TaskSpecSemanticRegistry,
): readonly string[] {
const revision = normalizePluginPackageMaterializedRevision(revisionValue, registry);
const previous =
previousReceipt === null
? null
: normalizePluginPackageTaskReconciliationReceipt(previousReceipt);
return Object.freeze(
[...new Set([
...pluginPackageTaskDefinitionDrafts(revision, registry).map(
(draft) => draft.taskId,
),
...(previous?.items.map((item) => item.taskId) ?? []),
])].sort(),
);
}
export function planPluginPackageTaskReconciliation(
input: PlanPluginPackageTaskReconciliationInput,
): Readonly<PluginPackageTaskReconciliationPlan> {
if (
!input ||
typeof input !== 'object' ||
Array.isArray(input) ||
!(input.taskSpecSemanticRegistry instanceof TaskSpecSemanticRegistry)
) {
return invalid('plan input is invalid');
}
const revision = normalizePluginPackageMaterializedRevision(
input.revision,
input.taskSpecSemanticRegistry,
);
const generation = revision.generation;
const previous =
input.previousReceipt === null
? null
: normalizePluginPackageTaskReconciliationReceipt(input.previousReceipt);
const committedAtMs = integer(input.committedAtMs, 'committedAtMs', 0);
if (
(generation.generation === 1 && previous !== null) ||
(generation.generation > 1 &&
(previous === null ||
previous.projectId !== generation.projectId ||
previous.packageName !== generation.packageName ||
previous.generation !== generation.generation - 1 ||
previous.lockDigest !== generation.previousActiveLockDigest))
) {
return conflict('previous generation receipt chain is incomplete');
}
if (!Array.isArray(input.facts)) return invalid('facts are invalid');
const drafts = pluginPackageTaskDefinitionDrafts(
revision,
input.taskSpecSemanticRegistry,
);
const taskIds = pluginPackageTaskReconciliationTaskIds(
revision,
previous,
input.taskSpecSemanticRegistry,
);
if (taskIds.length > MAX_PLUGIN_PACKAGE_TASK_RECONCILIATION_ITEMS) {
return invalid('task set exceeds its item budget');
}
const facts = new Map<string, Readonly<PluginPackageTaskOwnershipFact>>();
for (const value of input.facts) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('fact is invalid');
}
exactKeys(value, ['current', 'packageName', 'taskId'], [], 'fact');
const taskId = identifier(value.taskId, 'fact.taskId');
if (facts.has(taskId) || !taskIds.includes(taskId)) {
return invalid('facts must exactly and uniquely cover the task set');
}
if (
value.packageName !== null &&
(typeof value.packageName !== 'string' ||
!PACKAGE_NAME.test(value.packageName))
) {
return invalid('fact packageName is invalid');
}
const current =
value.current === null ? null : normalizeTaskDefinitionRecord(value.current);
if (
current !== null &&
(current.projectId !== generation.projectId || current.taskId !== taskId)
) {
return invalid('fact current definition identity is invalid');
}
facts.set(taskId, Object.freeze({ taskId, packageName: value.packageName, current }));
}
if (facts.size !== taskIds.length) {
return invalid('facts do not exactly cover the task set');
}
const draftById = new Map(drafts.map((draft) => [draft.taskId, draft]));
const previousById = new Map(previous?.items.map((item) => [item.taskId, item]) ?? []);
const items: PluginPackageTaskReconciliationItem[] = [];
const writes: PluginPackageTaskReconciliationWrite[] = [];
for (const taskId of taskIds) {
const fact = facts.get(taskId)!;
const draft = draftById.get(taskId);
const previousItem = previousById.get(taskId);
if (fact.packageName !== null && fact.packageName !== generation.packageName) {
return conflict(`TaskDefinition ${taskId} belongs to another Package`);
}
if (fact.current !== null && fact.packageName === null) {
return conflict(`TaskDefinition ${taskId} exists without Package ownership`);
}
if (
previousItem &&
(fact.current === null ||
fact.packageName !== generation.packageName ||
fact.current.revision !== previousItem.revision ||
fact.current.contentDigest !== previousItem.contentDigest)
) {
return conflict(`TaskDefinition ${taskId} changed outside reconciliation`);
}
if (draft) {
if (fact.current === null) {
const write = writeForDraft(
draft,
null,
generation.generationDigest,
committedAtMs,
'created',
);
writes.push(write);
items.push({
taskId,
revision: write.definition.revision,
disposition: 'created',
contentDigest: write.definition.contentDigest,
});
} else if (
semanticDigest(draft, fact.current.revision) === fact.current.contentDigest
) {
items.push({
taskId,
revision: fact.current.revision,
disposition: 'retained',
contentDigest: fact.current.contentDigest,
});
} else {
const write = writeForDraft(
draft,
fact.current,
generation.generationDigest,
committedAtMs,
'updated',
);
writes.push(write);
items.push({
taskId,
revision: write.definition.revision,
disposition: 'updated',
contentDigest: write.definition.contentDigest,
});
}
} else if (fact.current === null || !fact.current.enabled) {
if (fact.current !== null) {
items.push({
taskId,
revision: fact.current.revision,
disposition: 'already_disabled',
contentDigest: fact.current.contentDigest,
});
}
} else {
const write = disableWrite(
fact.current,
generation.generationDigest,
committedAtMs,
);
writes.push(write);
items.push({
taskId,
revision: write.definition.revision,
disposition: 'disabled',
contentDigest: write.definition.contentDigest,
});
}
}
items.sort((left, right) => left.taskId.localeCompare(right.taskId));
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_TASK_RECONCILIATION_SCHEMA,
projectId: generation.projectId,
packageName: generation.packageName,
generation: generation.generation,
generationDigest: generation.generationDigest,
materializedRevisionDigest: revision.revisionDigest,
lockDigest: generation.lockDigest,
previousLockDigest: generation.previousActiveLockDigest,
committedAtMs,
items: Object.freeze(items.map((item) => Object.freeze(item))),
});
return Object.freeze({
receipt: normalizePluginPackageTaskReconciliationReceipt(
Object.freeze({
...unsigned,
receiptDigest: pluginPackageTaskReconciliationReceiptDigest(unsigned),
}),
),
writes: Object.freeze(writes),
});
}
@@ -0,0 +1,722 @@
import { createHash } from 'node:crypto';
import type { PluginPackagePublisherSignatureEvidence } from '../pluginPackageBundle';
import {
SECURITY_SUBJECT_TYPES,
type SecuritySubject,
} from '../../security/security';
export const PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_SCHEMA =
'qinglong/plugin-package-publisher-provenance@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_REVOCATION_RECEIPT_SCHEMA =
'qinglong/plugin-package-publisher-key-revocation-receipt@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_SCHEMA =
'qinglong/plugin-package-publisher-key-revocation-impact@v1' as const;
export const MAX_PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_ITEMS = 4096;
export interface PluginPackagePublisherProvenance {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_SCHEMA;
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly lockDigest: string;
readonly artifactDigest: string;
readonly manifestDigest: string;
readonly contentDigest: string;
readonly stageEvidenceDigest: string;
readonly publisher: string;
readonly keyId: string;
readonly signatureDigest: string;
readonly keyNotBeforeMs: number;
readonly keyNotAfterMs: number;
readonly verifiedAtMs: number;
readonly provenanceDigest: string;
}
export interface CreatePluginPackagePublisherProvenanceInput {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly lockDigest: string;
readonly artifactDigest: string;
readonly manifestDigest: string;
readonly contentDigest: string;
readonly stageEvidenceDigest: string;
readonly signature: Readonly<PluginPackagePublisherSignatureEvidence>;
}
export type PluginPackagePublisherRevocationAuthorizationMode =
| 'dual_control'
| 'break_glass';
export type PluginPackagePublisherRevocationReason =
| 'suspected_key_compromise'
| 'confirmed_key_compromise';
export interface PluginPackagePublisherRevocationReceipt {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_REVOCATION_RECEIPT_SCHEMA;
readonly mutationId: string;
readonly publisher: string;
readonly keyId: string;
readonly previousTrustDigest: string;
readonly currentTrustDigest: string;
readonly proposer: Readonly<SecuritySubject>;
readonly confirmer: Readonly<SecuritySubject>;
readonly authorizationMode: PluginPackagePublisherRevocationAuthorizationMode;
readonly reasonCode: PluginPackagePublisherRevocationReason;
readonly revokedAtMs: number;
readonly receiptDigest: string;
}
export type CreatePluginPackagePublisherRevocationReceiptInput = Omit<
PluginPackagePublisherRevocationReceipt,
'receiptDigest' | 'schema'
>;
export interface PluginPackagePublisherRevocationImpactItem {
readonly projectId: string;
readonly packageName: string;
readonly installationId: string;
readonly lockDigest: string;
readonly provenanceDigest: string;
}
export interface PluginPackagePublisherRevocationImpact {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_SCHEMA;
readonly revocationReceiptDigest: string;
readonly items: readonly Readonly<PluginPackagePublisherRevocationImpactItem>[];
readonly generatedAtMs: number;
readonly impactDigest: string;
}
export type CreatePluginPackagePublisherRevocationImpactInput = Omit<
PluginPackagePublisherRevocationImpact,
'impactDigest' | 'schema'
>;
export class InvalidPluginPackagePublisherProvenanceError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_INVALID';
constructor(message: string) {
super(`Plugin Package publisher provenance is invalid: ${message}`);
this.name = 'InvalidPluginPackagePublisherProvenanceError';
}
}
export class PluginPackagePublisherProvenanceConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_CONFLICT';
constructor(message: string) {
super(`Plugin Package publisher provenance conflicts with durable state: ${message}`);
this.name = 'PluginPackagePublisherProvenanceConflictError';
}
}
export class PluginPackagePublisherProvenanceUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package publisher provenance is unavailable', options);
this.name = 'PluginPackagePublisherProvenanceUnavailableError';
}
}
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PACKAGE_NAME_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const PUBLISHER_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
const SUBJECT_CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
const PROVENANCE_DIGEST_DOMAIN =
'qinglong/plugin-package-publisher-provenance-digest@v1\0';
const REVOCATION_RECEIPT_DIGEST_DOMAIN =
'qinglong/plugin-package-publisher-key-revocation-receipt-digest@v1\0';
const REVOCATION_IMPACT_DIGEST_DOMAIN =
'qinglong/plugin-package-publisher-key-revocation-impact-digest@v1\0';
function invalid(message: string): never {
throw new InvalidPluginPackagePublisherProvenanceError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const canonical = [...expected].sort();
if (
actual.some((key) => typeof key !== 'string') ||
actual.length !== canonical.length ||
actual
.map(String)
.sort()
.some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function projectId(value: unknown): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
Buffer.byteLength(value, 'utf8') > 128 ||
value.includes('\0')
) {
return invalid('projectId is invalid');
}
return value;
}
function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME_PATTERN.test(value)) {
return invalid('packageName is invalid');
}
return value;
}
function publisher(value: unknown): string {
if (
typeof value !== 'string' ||
Buffer.byteLength(value, 'utf8') > 253 ||
!PUBLISHER_PATTERN.test(value)
) {
return invalid('publisher is invalid');
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function subject(
value: SecuritySubject,
label: string,
): Readonly<SecuritySubject> {
const record = dataRecord(value, label);
exactKeys(record, ['id', 'type'], label);
if (
typeof value.type !== 'string' ||
!SECURITY_SUBJECT_TYPES.includes(
value.type as (typeof SECURITY_SUBJECT_TYPES)[number],
) ||
typeof value.id !== 'string' ||
value.id.length < 1 ||
Buffer.byteLength(value.id, 'utf8') > 255 ||
SUBJECT_CONTROL_PATTERN.test(value.id)
) {
return invalid(`${label} is invalid`);
}
return Object.freeze({
type: value.type as (typeof SECURITY_SUBJECT_TYPES)[number],
id: value.id,
});
}
function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
function provenanceFields(
value: Omit<PluginPackagePublisherProvenance, 'provenanceDigest'>,
): object {
return {
schema: value.schema,
projectId: value.projectId,
packageName: value.packageName,
installationId: value.installationId,
lockDigest: value.lockDigest,
artifactDigest: value.artifactDigest,
manifestDigest: value.manifestDigest,
contentDigest: value.contentDigest,
stageEvidenceDigest: value.stageEvidenceDigest,
publisher: value.publisher,
keyId: value.keyId,
signatureDigest: value.signatureDigest,
keyNotBeforeMs: value.keyNotBeforeMs,
keyNotAfterMs: value.keyNotAfterMs,
verifiedAtMs: value.verifiedAtMs,
};
}
export function pluginPackagePublisherProvenanceDigest(
value: Omit<PluginPackagePublisherProvenance, 'provenanceDigest'>,
): string {
return createHash('sha256')
.update(PROVENANCE_DIGEST_DOMAIN)
.update(JSON.stringify(provenanceFields(value)))
.digest('hex');
}
export function normalizePluginPackagePublisherProvenance(
value: PluginPackagePublisherProvenance,
): Readonly<PluginPackagePublisherProvenance> {
const record = dataRecord(value, 'provenance');
exactKeys(
record,
[
'artifactDigest',
'contentDigest',
'installationId',
'keyId',
'keyNotAfterMs',
'keyNotBeforeMs',
'lockDigest',
'manifestDigest',
'packageName',
'projectId',
'provenanceDigest',
'publisher',
'schema',
'signatureDigest',
'stageEvidenceDigest',
'verifiedAtMs',
],
'provenance',
);
if (value.schema !== PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_SCHEMA) {
return invalid('provenance schema is invalid');
}
const keyNotBeforeMs = timestamp(value.keyNotBeforeMs, 'keyNotBeforeMs');
const keyNotAfterMs = timestamp(value.keyNotAfterMs, 'keyNotAfterMs');
const verifiedAtMs = timestamp(value.verifiedAtMs, 'verifiedAtMs');
if (
keyNotAfterMs <= keyNotBeforeMs ||
verifiedAtMs < keyNotBeforeMs ||
verifiedAtMs >= keyNotAfterMs
) {
return invalid('signature verification time is outside key validity');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_SCHEMA,
projectId: projectId(value.projectId),
packageName: packageName(value.packageName),
installationId: identifier(value.installationId, 'installationId'),
lockDigest: digest(value.lockDigest, 'lockDigest'),
artifactDigest: digest(value.artifactDigest, 'artifactDigest'),
manifestDigest: digest(value.manifestDigest, 'manifestDigest'),
contentDigest: digest(value.contentDigest, 'contentDigest'),
stageEvidenceDigest: digest(
value.stageEvidenceDigest,
'stageEvidenceDigest',
),
publisher: publisher(value.publisher),
keyId: identifier(value.keyId, 'keyId'),
signatureDigest: digest(value.signatureDigest, 'signatureDigest'),
keyNotBeforeMs,
keyNotAfterMs,
verifiedAtMs,
});
const provenanceDigest = pluginPackagePublisherProvenanceDigest(normalized);
if (value.provenanceDigest !== provenanceDigest) {
return invalid('provenanceDigest does not match provenance');
}
return Object.freeze({ ...normalized, provenanceDigest });
}
export function createPluginPackagePublisherProvenance(
input: CreatePluginPackagePublisherProvenanceInput,
): Readonly<PluginPackagePublisherProvenance> {
const value = dataRecord(input, 'provenance input');
exactKeys(
value,
[
'artifactDigest',
'contentDigest',
'installationId',
'lockDigest',
'manifestDigest',
'packageName',
'projectId',
'signature',
'stageEvidenceDigest',
],
'provenance input',
);
const signature = dataRecord(input.signature, 'signature evidence');
exactKeys(
signature,
[
'keyId',
'keyNotAfterMs',
'keyNotBeforeMs',
'publisher',
'signatureDigest',
'verifiedAtMs',
],
'signature evidence',
);
const unsigned: Omit<
PluginPackagePublisherProvenance,
'provenanceDigest'
> = {
schema: PLUGIN_PACKAGE_PUBLISHER_PROVENANCE_SCHEMA,
projectId: projectId(input.projectId),
packageName: packageName(input.packageName),
installationId: identifier(input.installationId, 'installationId'),
lockDigest: digest(input.lockDigest, 'lockDigest'),
artifactDigest: digest(input.artifactDigest, 'artifactDigest'),
manifestDigest: digest(input.manifestDigest, 'manifestDigest'),
contentDigest: digest(input.contentDigest, 'contentDigest'),
stageEvidenceDigest: digest(
input.stageEvidenceDigest,
'stageEvidenceDigest',
),
publisher: publisher(input.signature.publisher),
keyId: identifier(input.signature.keyId, 'keyId'),
signatureDigest: digest(
input.signature.signatureDigest,
'signatureDigest',
),
keyNotBeforeMs: timestamp(
input.signature.keyNotBeforeMs,
'keyNotBeforeMs',
),
keyNotAfterMs: timestamp(
input.signature.keyNotAfterMs,
'keyNotAfterMs',
),
verifiedAtMs: timestamp(input.signature.verifiedAtMs, 'verifiedAtMs'),
};
return normalizePluginPackagePublisherProvenance({
...unsigned,
provenanceDigest: pluginPackagePublisherProvenanceDigest(unsigned),
});
}
function revocationReceiptFields(
value: Omit<PluginPackagePublisherRevocationReceipt, 'receiptDigest'>,
): object {
return {
schema: value.schema,
mutationId: value.mutationId,
publisher: value.publisher,
keyId: value.keyId,
previousTrustDigest: value.previousTrustDigest,
currentTrustDigest: value.currentTrustDigest,
proposer: value.proposer,
confirmer: value.confirmer,
authorizationMode: value.authorizationMode,
reasonCode: value.reasonCode,
revokedAtMs: value.revokedAtMs,
};
}
export function pluginPackagePublisherRevocationReceiptDigest(
value: Omit<PluginPackagePublisherRevocationReceipt, 'receiptDigest'>,
): string {
return createHash('sha256')
.update(REVOCATION_RECEIPT_DIGEST_DOMAIN)
.update(JSON.stringify(revocationReceiptFields(value)))
.digest('hex');
}
export function normalizePluginPackagePublisherRevocationReceipt(
value: PluginPackagePublisherRevocationReceipt,
): Readonly<PluginPackagePublisherRevocationReceipt> {
const record = dataRecord(value, 'revocation receipt');
exactKeys(
record,
[
'authorizationMode',
'confirmer',
'currentTrustDigest',
'keyId',
'mutationId',
'previousTrustDigest',
'proposer',
'publisher',
'reasonCode',
'receiptDigest',
'revokedAtMs',
'schema',
],
'revocation receipt',
);
if (
value.schema !== PLUGIN_PACKAGE_PUBLISHER_REVOCATION_RECEIPT_SCHEMA ||
(value.authorizationMode !== 'dual_control' &&
value.authorizationMode !== 'break_glass') ||
(value.reasonCode !== 'suspected_key_compromise' &&
value.reasonCode !== 'confirmed_key_compromise')
) {
return invalid('revocation receipt classification is invalid');
}
const proposer = subject(value.proposer, 'proposer');
const confirmer = subject(value.confirmer, 'confirmer');
if (
value.authorizationMode === 'dual_control' &&
sameSubject(proposer, confirmer)
) {
return invalid('dual-control requires distinct subjects');
}
const previousTrustDigest = digest(
value.previousTrustDigest,
'previousTrustDigest',
);
const currentTrustDigest = digest(
value.currentTrustDigest,
'currentTrustDigest',
);
if (previousTrustDigest === currentTrustDigest) {
return invalid('revocation must change the publisher trust digest');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_RECEIPT_SCHEMA,
mutationId: identifier(value.mutationId, 'mutationId'),
publisher: publisher(value.publisher),
keyId: identifier(value.keyId, 'keyId'),
previousTrustDigest,
currentTrustDigest,
proposer,
confirmer,
authorizationMode: value.authorizationMode,
reasonCode: value.reasonCode,
revokedAtMs: timestamp(value.revokedAtMs, 'revokedAtMs'),
});
const receiptDigest =
pluginPackagePublisherRevocationReceiptDigest(normalized);
if (value.receiptDigest !== receiptDigest) {
return invalid('receiptDigest does not match revocation receipt');
}
return Object.freeze({ ...normalized, receiptDigest });
}
export function createPluginPackagePublisherRevocationReceipt(
input: CreatePluginPackagePublisherRevocationReceiptInput,
): Readonly<PluginPackagePublisherRevocationReceipt> {
const value = dataRecord(input, 'revocation receipt input');
exactKeys(
value,
[
'authorizationMode',
'confirmer',
'currentTrustDigest',
'keyId',
'mutationId',
'previousTrustDigest',
'proposer',
'publisher',
'reasonCode',
'revokedAtMs',
],
'revocation receipt input',
);
const unsigned: Omit<
PluginPackagePublisherRevocationReceipt,
'receiptDigest'
> = {
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_RECEIPT_SCHEMA,
mutationId: input.mutationId,
publisher: input.publisher,
keyId: input.keyId,
previousTrustDigest: input.previousTrustDigest,
currentTrustDigest: input.currentTrustDigest,
proposer: input.proposer,
confirmer: input.confirmer,
authorizationMode: input.authorizationMode,
reasonCode: input.reasonCode,
revokedAtMs: input.revokedAtMs,
};
return normalizePluginPackagePublisherRevocationReceipt({
...unsigned,
receiptDigest: pluginPackagePublisherRevocationReceiptDigest(unsigned),
});
}
function compareImpactItems(
left: Readonly<PluginPackagePublisherRevocationImpactItem>,
right: Readonly<PluginPackagePublisherRevocationImpactItem>,
): number {
return (
Buffer.compare(
Buffer.from(left.projectId, 'utf8'),
Buffer.from(right.projectId, 'utf8'),
) ||
Buffer.compare(
Buffer.from(left.packageName, 'utf8'),
Buffer.from(right.packageName, 'utf8'),
) ||
Buffer.compare(
Buffer.from(left.installationId, 'utf8'),
Buffer.from(right.installationId, 'utf8'),
) ||
left.lockDigest.localeCompare(right.lockDigest)
);
}
function normalizeImpactItem(
value: PluginPackagePublisherRevocationImpactItem,
): Readonly<PluginPackagePublisherRevocationImpactItem> {
const record = dataRecord(value, 'impact item');
exactKeys(
record,
[
'installationId',
'lockDigest',
'packageName',
'projectId',
'provenanceDigest',
],
'impact item',
);
return Object.freeze({
projectId: projectId(value.projectId),
packageName: packageName(value.packageName),
installationId: identifier(value.installationId, 'installationId'),
lockDigest: digest(value.lockDigest, 'lockDigest'),
provenanceDigest: digest(value.provenanceDigest, 'provenanceDigest'),
});
}
function impactFields(
value: Omit<PluginPackagePublisherRevocationImpact, 'impactDigest'>,
): object {
return {
schema: value.schema,
revocationReceiptDigest: value.revocationReceiptDigest,
items: value.items,
generatedAtMs: value.generatedAtMs,
};
}
export function pluginPackagePublisherRevocationImpactDigest(
value: Omit<PluginPackagePublisherRevocationImpact, 'impactDigest'>,
): string {
return createHash('sha256')
.update(REVOCATION_IMPACT_DIGEST_DOMAIN)
.update(JSON.stringify(impactFields(value)))
.digest('hex');
}
export function normalizePluginPackagePublisherRevocationImpact(
value: PluginPackagePublisherRevocationImpact,
): Readonly<PluginPackagePublisherRevocationImpact> {
const record = dataRecord(value, 'revocation impact');
exactKeys(
record,
[
'generatedAtMs',
'impactDigest',
'items',
'revocationReceiptDigest',
'schema',
],
'revocation impact',
);
if (
value.schema !== PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_SCHEMA ||
!Array.isArray(value.items) ||
value.items.length > MAX_PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_ITEMS ||
Object.keys(value.items).some((key, index) => key !== String(index))
) {
return invalid('revocation impact schema or items are invalid');
}
const items = Object.freeze(value.items.map(normalizeImpactItem));
if (
items.some(
(item, index) =>
index > 0 && compareImpactItems(items[index - 1]!, item) >= 0,
) ||
new Set(items.map((item) => item.provenanceDigest)).size !== items.length ||
new Set(items.map((item) => item.installationId)).size !== items.length
) {
return invalid('revocation impact items must be unique and sorted');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_SCHEMA,
revocationReceiptDigest: digest(
value.revocationReceiptDigest,
'revocationReceiptDigest',
),
items,
generatedAtMs: timestamp(value.generatedAtMs, 'generatedAtMs'),
});
const impactDigest =
pluginPackagePublisherRevocationImpactDigest(normalized);
if (value.impactDigest !== impactDigest) {
return invalid('impactDigest does not match revocation impact');
}
return Object.freeze({ ...normalized, impactDigest });
}
export function createPluginPackagePublisherRevocationImpact(
input: CreatePluginPackagePublisherRevocationImpactInput,
): Readonly<PluginPackagePublisherRevocationImpact> {
const value = dataRecord(input, 'revocation impact input');
exactKeys(
value,
['generatedAtMs', 'items', 'revocationReceiptDigest'],
'revocation impact input',
);
if (
!Array.isArray(input.items) ||
input.items.length >
MAX_PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_ITEMS ||
Object.keys(input.items).some((key, index) => key !== String(index))
) {
return invalid('revocation impact items are invalid');
}
const items = Object.freeze(
input.items.map(normalizeImpactItem).sort(compareImpactItems),
);
const unsigned: Omit<
PluginPackagePublisherRevocationImpact,
'impactDigest'
> = {
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_IMPACT_SCHEMA,
revocationReceiptDigest: input.revocationReceiptDigest,
items,
generatedAtMs: input.generatedAtMs,
};
return normalizePluginPackagePublisherRevocationImpact({
...unsigned,
impactDigest: pluginPackagePublisherRevocationImpactDigest(unsigned),
});
}
@@ -0,0 +1,589 @@
import { createHash } from 'node:crypto';
import {
normalizeApprovedActionDispatchRecord,
normalizeApprovedActionFence,
type ApprovedActionDispatchRecord,
} from '../../approved-action/approvedAction';
import {
createPluginPackagePublisherRevocationReceipt,
type PluginPackagePublisherRevocationAuthorizationMode,
type PluginPackagePublisherRevocationReason,
type PluginPackagePublisherRevocationReceipt,
} from './pluginPackagePublisherProvenance';
import {
normalizePluginPackagePublisherTrustSnapshot,
pluginPackagePublisherTrustRevokedDigest,
type PluginPackagePublisherTrustSnapshot,
} from './pluginPackagePublisherTrust';
import { normalizeProjectPolicySubject } from '../../security/project-policy/projectPolicy';
import {
SECURITY_AUTHENTICATION_ASSURANCES,
type SecurityAuthenticationAssurance,
type SecurityPolicyFence,
type SecuritySubject,
} from '../../security/security';
import type { SecurityAuditRecord } from '../../security/audit/securityAudit';
export const PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_SCHEMA =
'qinglong/plugin-package-publisher-key-revocation-proposal@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE =
'plugin_package.publisher_key.revoke' as const;
export const PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PERMISSION =
'package.manage' as const;
export interface PluginPackagePublisherRevocationActionInput {
readonly authorityProjectId: string;
readonly trustAuthorityId: string;
readonly trustGeneration: number;
readonly publisher: string;
readonly keyId: string;
readonly previousTrustDigest: string;
readonly currentTrustDigest: string;
readonly authorizationMode: PluginPackagePublisherRevocationAuthorizationMode;
readonly reasonCode: PluginPackagePublisherRevocationReason;
}
export interface PluginPackagePublisherRevocationProposal {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_SCHEMA;
readonly actionRef: string;
readonly projectId: string;
readonly actionType: typeof PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE;
readonly permission: typeof PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PERMISSION;
readonly actionInput: Readonly<PluginPackagePublisherRevocationActionInput>;
readonly actionDigest: string;
readonly previewDigest: string;
readonly proposedBy: Readonly<SecuritySubject>;
readonly proposerAssurance: SecurityAuthenticationAssurance;
readonly proposalFence: Readonly<SecurityPolicyFence>;
readonly createdAtMs: number;
readonly proposalDigest: string;
}
export interface CreatePluginPackagePublisherRevocationProposalInput {
readonly actionRef: string;
readonly authorityProjectId: string;
readonly trustAuthorityId: string;
readonly trustGeneration: number;
readonly trustSnapshot: PluginPackagePublisherTrustSnapshot;
readonly publisher: string;
readonly keyId: string;
readonly authorizationMode: PluginPackagePublisherRevocationAuthorizationMode;
readonly reasonCode: PluginPackagePublisherRevocationReason;
readonly proposedBy: SecuritySubject;
readonly proposerAssurance: SecurityAuthenticationAssurance;
readonly proposalFence: SecurityPolicyFence;
readonly createdAtMs: number;
}
export interface CreatePluginPackagePublisherRevocationProposalCommand {
readonly proposal: PluginPackagePublisherRevocationProposal;
readonly audit: SecurityAuditRecord;
}
export interface CreatePluginPackagePublisherRevocationProposalResult {
readonly status: 'created' | 'existing';
readonly proposal: Readonly<PluginPackagePublisherRevocationProposal>;
}
export interface PluginPackagePublisherRevocationProposalRepository {
findProposalByActionRef(
actionRef: string,
): Promise<Readonly<PluginPackagePublisherRevocationProposal> | null>;
createProposal(
command: CreatePluginPackagePublisherRevocationProposalCommand,
): Promise<
Readonly<CreatePluginPackagePublisherRevocationProposalResult>
>;
}
export class InvalidPluginPackagePublisherRevocationProposalError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_INVALID';
constructor(message: string) {
super(
`Plugin Package publisher revocation proposal is invalid: ${message}`,
);
this.name =
'InvalidPluginPackagePublisherRevocationProposalError';
}
}
export class PluginPackagePublisherRevocationProposalBindingConflictError extends Error {
readonly code =
'PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_BINDING_CONFLICT';
constructor() {
super(
'Plugin Package publisher revocation proposal does not match its dispatch',
);
this.name =
'PluginPackagePublisherRevocationProposalBindingConflictError';
}
}
export class PluginPackagePublisherRevocationProposalConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_CONFLICT';
constructor() {
super(
'Plugin Package publisher revocation proposal conflicts with durable authority',
);
this.name =
'PluginPackagePublisherRevocationProposalConflictError';
}
}
export class PluginPackagePublisherRevocationProposalUnavailableError extends Error {
readonly code =
'PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super(
'Plugin Package publisher revocation proposal authority is unavailable',
options,
);
this.name =
'PluginPackagePublisherRevocationProposalUnavailableError';
}
}
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PUBLISHER_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function invalid(message: string): never {
throw new InvalidPluginPackagePublisherRevocationProposalError(message);
}
function dataRecord(
value: unknown,
label: string,
): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const canonical = [...expected].sort();
if (
actual.some((key) => typeof key !== 'string') ||
actual.length !== canonical.length ||
actual
.map(String)
.sort()
.some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
return invalid('actionRef is invalid');
}
return value;
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function publisher(value: unknown): string {
if (
typeof value !== 'string' ||
Buffer.byteLength(value, 'utf8') > 253 ||
!PUBLISHER_PATTERN.test(value)
) {
return invalid('publisher is invalid');
}
return value;
}
function projectId(value: unknown): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
Buffer.byteLength(value, 'utf8') > 128 ||
value.includes('\0')
) {
return invalid('authorityProjectId is invalid');
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function positiveInteger(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 1) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function authorizationMode(
value: unknown,
): PluginPackagePublisherRevocationAuthorizationMode {
if (value !== 'dual_control' && value !== 'break_glass') {
return invalid('authorizationMode is invalid');
}
return value;
}
function reasonCode(
value: unknown,
): PluginPackagePublisherRevocationReason {
if (
value !== 'suspected_key_compromise' &&
value !== 'confirmed_key_compromise'
) {
return invalid('reasonCode is invalid');
}
return value;
}
function assurance(value: unknown): SecurityAuthenticationAssurance {
if (
typeof value !== 'string' ||
!SECURITY_AUTHENTICATION_ASSURANCES.includes(
value as SecurityAuthenticationAssurance,
)
) {
return invalid('proposerAssurance is invalid');
}
return value as SecurityAuthenticationAssurance;
}
function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
function contractDigest(domain: string, value: unknown): string {
return createHash('sha256')
.update(domain)
.update('\0')
.update(JSON.stringify(value))
.digest('hex');
}
function normalizeActionInput(
value: PluginPackagePublisherRevocationActionInput,
): Readonly<PluginPackagePublisherRevocationActionInput> {
const record = dataRecord(value, 'action input');
exactKeys(
record,
[
'authorityProjectId',
'trustAuthorityId',
'trustGeneration',
'publisher',
'keyId',
'previousTrustDigest',
'currentTrustDigest',
'authorizationMode',
'reasonCode',
],
'action input',
);
const previousTrustDigest = digest(
value.previousTrustDigest,
'previousTrustDigest',
);
const currentTrustDigest = digest(
value.currentTrustDigest,
'currentTrustDigest',
);
if (previousTrustDigest === currentTrustDigest) {
return invalid('revocation must change the trust digest');
}
return Object.freeze({
authorityProjectId: projectId(value.authorityProjectId),
trustAuthorityId: identifier(
value.trustAuthorityId,
'trustAuthorityId',
),
trustGeneration: positiveInteger(
value.trustGeneration,
'trustGeneration',
),
publisher: publisher(value.publisher),
keyId: identifier(value.keyId, 'keyId'),
previousTrustDigest,
currentTrustDigest,
authorizationMode: authorizationMode(value.authorizationMode),
reasonCode: reasonCode(value.reasonCode),
});
}
export function pluginPackagePublisherRevocationActionDigest(
value: PluginPackagePublisherRevocationActionInput,
): string {
return contractDigest(
'qinglong/plugin-package-publisher-key-revocation-action-digest@v1',
normalizeActionInput(value),
);
}
export function pluginPackagePublisherRevocationPreviewDigest(
value: PluginPackagePublisherRevocationActionInput,
): string {
const input = normalizeActionInput(value);
return contractDigest(
'qinglong/plugin-package-publisher-key-revocation-preview-digest@v1',
{
authorityProjectId: input.authorityProjectId,
trustAuthorityId: input.trustAuthorityId,
trustGeneration: input.trustGeneration,
publisher: input.publisher,
keyId: input.keyId,
previousTrustDigest: input.previousTrustDigest,
currentTrustDigest: input.currentTrustDigest,
authorizationMode: input.authorizationMode,
reasonCode: input.reasonCode,
},
);
}
function withProposalDigest(
value: Omit<
PluginPackagePublisherRevocationProposal,
'proposalDigest'
>,
): Readonly<PluginPackagePublisherRevocationProposal> {
const normalized = Object.freeze(value);
return Object.freeze({
...normalized,
proposalDigest: contractDigest(
'qinglong/plugin-package-publisher-key-revocation-proposal-digest@v1',
normalized,
),
});
}
export function createPluginPackagePublisherRevocationProposal(
inputValue: CreatePluginPackagePublisherRevocationProposalInput,
): Readonly<PluginPackagePublisherRevocationProposal> {
const input = dataRecord(inputValue, 'proposal input');
exactKeys(
input,
[
'actionRef',
'authorityProjectId',
'trustAuthorityId',
'trustGeneration',
'trustSnapshot',
'publisher',
'keyId',
'authorizationMode',
'reasonCode',
'proposedBy',
'proposerAssurance',
'proposalFence',
'createdAtMs',
],
'proposal input',
);
const trustSnapshot = normalizePluginPackagePublisherTrustSnapshot(
inputValue.trustSnapshot,
);
const actionInput = normalizeActionInput({
authorityProjectId: inputValue.authorityProjectId,
trustAuthorityId: inputValue.trustAuthorityId,
trustGeneration: inputValue.trustGeneration,
publisher: inputValue.publisher,
keyId: inputValue.keyId,
previousTrustDigest: trustSnapshot.snapshotDigest,
currentTrustDigest: pluginPackagePublisherTrustRevokedDigest(
trustSnapshot,
inputValue.publisher,
inputValue.keyId,
),
authorizationMode: inputValue.authorizationMode,
reasonCode: inputValue.reasonCode,
});
const proposerAssurance = assurance(inputValue.proposerAssurance);
if (
actionInput.authorizationMode === 'break_glass' &&
proposerAssurance !== 'hardware'
) {
return invalid('break-glass proposer must use hardware assurance');
}
const proposedBy = normalizeProjectPolicySubject(inputValue.proposedBy);
return withProposalDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_SCHEMA,
actionRef: actionRef(inputValue.actionRef),
projectId: actionInput.authorityProjectId,
actionType: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE,
permission: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PERMISSION,
actionInput,
actionDigest:
pluginPackagePublisherRevocationActionDigest(actionInput),
previewDigest:
pluginPackagePublisherRevocationPreviewDigest(actionInput),
proposedBy,
proposerAssurance,
proposalFence: normalizeApprovedActionFence(
inputValue.proposalFence,
),
createdAtMs: timestamp(inputValue.createdAtMs, 'createdAtMs'),
});
}
export function normalizePluginPackagePublisherRevocationProposal(
value: PluginPackagePublisherRevocationProposal,
): Readonly<PluginPackagePublisherRevocationProposal> {
const record = dataRecord(value, 'proposal');
exactKeys(
record,
[
'schema',
'actionRef',
'projectId',
'actionType',
'permission',
'actionInput',
'actionDigest',
'previewDigest',
'proposedBy',
'proposerAssurance',
'proposalFence',
'createdAtMs',
'proposalDigest',
],
'proposal',
);
if (
value.schema !==
PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_SCHEMA ||
value.actionType !==
PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE ||
value.permission !==
PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PERMISSION
) {
return invalid('schema or action authority is invalid');
}
const actionInput = normalizeActionInput(value.actionInput);
const proposedBy = normalizeProjectPolicySubject(value.proposedBy);
const proposerAssurance = assurance(value.proposerAssurance);
if (
actionInput.authorizationMode === 'break_glass' &&
proposerAssurance !== 'hardware'
) {
return invalid('break-glass proposer must use hardware assurance');
}
const normalized = withProposalDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PROPOSAL_SCHEMA,
actionRef: actionRef(value.actionRef),
projectId: projectId(value.projectId),
actionType: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE,
permission: PLUGIN_PACKAGE_PUBLISHER_REVOCATION_PERMISSION,
actionInput,
actionDigest:
pluginPackagePublisherRevocationActionDigest(actionInput),
previewDigest:
pluginPackagePublisherRevocationPreviewDigest(actionInput),
proposedBy,
proposerAssurance,
proposalFence: normalizeApprovedActionFence(value.proposalFence),
createdAtMs: timestamp(value.createdAtMs, 'createdAtMs'),
});
if (
normalized.projectId !== actionInput.authorityProjectId ||
digest(value.actionDigest, 'actionDigest') !==
normalized.actionDigest ||
digest(value.previewDigest, 'previewDigest') !==
normalized.previewDigest ||
digest(value.proposalDigest, 'proposalDigest') !==
normalized.proposalDigest
) {
return invalid('proposal digest or derived binding is invalid');
}
return normalized;
}
export function resolvePluginPackagePublisherRevocationProposal(
proposalValue: PluginPackagePublisherRevocationProposal,
dispatchValue: ApprovedActionDispatchRecord,
revokedAtMsValue: number,
): Readonly<PluginPackagePublisherRevocationReceipt> {
const proposal =
normalizePluginPackagePublisherRevocationProposal(proposalValue);
const dispatch = normalizeApprovedActionDispatchRecord(dispatchValue);
const revokedAtMs = timestamp(revokedAtMsValue, 'revokedAtMs');
const action = proposal.actionInput;
if (
dispatch.projectId !== proposal.projectId ||
dispatch.action.actionRef !== proposal.actionRef ||
dispatch.action.actionType !== proposal.actionType ||
dispatch.action.permission !== proposal.permission ||
dispatch.action.actionDigest !== proposal.actionDigest ||
dispatch.action.previewDigest !== proposal.previewDigest ||
!sameSubject(dispatch.requestedBy, proposal.proposedBy) ||
dispatch.createdAtMs < proposal.createdAtMs ||
revokedAtMs < dispatch.createdAtMs ||
revokedAtMs >= dispatch.expiresAtMs ||
(action.authorizationMode === 'dual_control' &&
sameSubject(dispatch.requestedBy, dispatch.approvedBy)) ||
(action.authorizationMode === 'break_glass' &&
(proposal.proposerAssurance !== 'hardware' ||
dispatch.approvalAssurance !== 'hardware'))
) {
throw new PluginPackagePublisherRevocationProposalBindingConflictError();
}
return createPluginPackagePublisherRevocationReceipt({
mutationId: dispatch.id,
publisher: action.publisher,
keyId: action.keyId,
previousTrustDigest: action.previousTrustDigest,
currentTrustDigest: action.currentTrustDigest,
proposer: proposal.proposedBy,
confirmer: dispatch.approvedBy,
authorizationMode: action.authorizationMode,
reasonCode: action.reasonCode,
revokedAtMs,
});
}
@@ -0,0 +1,604 @@
import { createHash, createPublicKey } from 'node:crypto';
import {
MAX_PLUGIN_PACKAGE_PUBLISHER_KEYS,
PluginPackagePublisherTrustRegistry,
type PluginPackagePublisherKeyDefinition,
} from '../pluginPackageBundle';
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA =
'qinglong/plugin-package-publisher-trust-snapshot@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA =
'qinglong/plugin-package-publisher-trust-head@v1' as const;
export interface PluginPackagePublisherTrustSnapshotKey {
readonly publisher: string;
readonly keyId: string;
readonly publicKeyDigest: string;
readonly notBeforeMs: number;
readonly notAfterMs: number;
}
export interface PluginPackagePublisherTrustSnapshot {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA;
readonly keys: readonly Readonly<PluginPackagePublisherTrustSnapshotKey>[];
readonly snapshotDigest: string;
}
export interface PluginPackagePublisherTrustKeyRef {
readonly publisher: string;
readonly keyId: string;
}
export interface PluginPackagePublisherTrustHead {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA;
readonly authorityId: string;
readonly generation: number;
readonly baseSnapshotDigest: string;
readonly effectiveTrustDigest: string;
readonly updatedAtMs: number;
readonly headDigest: string;
}
export interface PluginPackagePublisherTrustAuthorityState {
readonly head: Readonly<PluginPackagePublisherTrustHead>;
readonly effectiveSnapshot: Readonly<PluginPackagePublisherTrustSnapshot>;
}
export interface ObservePluginPackagePublisherTrustSnapshotInput {
readonly authorityId: string;
readonly snapshot: PluginPackagePublisherTrustSnapshot;
readonly observedBy: string;
readonly observedAtMs: number;
}
export interface ObservePluginPackagePublisherTrustSnapshotResult
extends PluginPackagePublisherTrustAuthorityState {
readonly status: 'created' | 'existing' | 'candidate';
}
export interface PluginPackagePublisherTrustAuthorityRepository {
findAuthority(
authorityId: string,
): Promise<Readonly<PluginPackagePublisherTrustAuthorityState> | null>;
observeSnapshot(
input: ObservePluginPackagePublisherTrustSnapshotInput,
): Promise<Readonly<ObservePluginPackagePublisherTrustSnapshotResult>>;
}
export class InvalidPluginPackagePublisherTrustSnapshotError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_INVALID';
constructor(message: string) {
super(`Plugin Package publisher trust snapshot is invalid: ${message}`);
this.name = 'InvalidPluginPackagePublisherTrustSnapshotError';
}
}
export class PluginPackagePublisherTrustAuthorityConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_TRUST_AUTHORITY_CONFLICT';
constructor() {
super(
'Plugin Package publisher trust snapshot conflicts with durable authority',
);
this.name = 'PluginPackagePublisherTrustAuthorityConflictError';
}
}
export class PluginPackagePublisherTrustAuthorityUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_TRUST_AUTHORITY_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package publisher trust authority is unavailable', options);
this.name = 'PluginPackagePublisherTrustAuthorityUnavailableError';
}
}
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PUBLISHER_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
const TRUST_DIGEST_DOMAIN =
'qinglong/plugin-package-publisher-trust-keyset-digest@v1\0';
const TRUST_HEAD_DIGEST_DOMAIN =
'qinglong/plugin-package-publisher-trust-head-digest@v1\0';
function invalid(message: string): never {
throw new InvalidPluginPackagePublisherTrustSnapshotError(message);
}
function exactObject(
value: unknown,
keys: readonly string[],
label: string,
): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const actual = Reflect.ownKeys(value);
const expected = [...keys].sort();
if (
actual.some((key) => typeof key !== 'string') ||
actual.length !== expected.length ||
actual
.map(String)
.sort()
.some((key, index) => key !== expected[index])
) {
return invalid(`${label} shape is invalid`);
}
return value as Record<string, unknown>;
}
function publisher(value: unknown): string {
if (
typeof value !== 'string' ||
Buffer.byteLength(value, 'utf8') > 253 ||
!PUBLISHER_PATTERN.test(value)
) {
return invalid('publisher is invalid');
}
return value;
}
function keyId(value: unknown): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
return invalid('keyId is invalid');
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function positiveInteger(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 1) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function compareKeys(
left: Readonly<PluginPackagePublisherTrustSnapshotKey>,
right: Readonly<PluginPackagePublisherTrustSnapshotKey>,
): number {
return (
Buffer.compare(
Buffer.from(left.publisher, 'utf8'),
Buffer.from(right.publisher, 'utf8'),
) ||
Buffer.compare(
Buffer.from(left.keyId, 'utf8'),
Buffer.from(right.keyId, 'utf8'),
)
);
}
function normalizeKey(
value: PluginPackagePublisherTrustSnapshotKey,
): Readonly<PluginPackagePublisherTrustSnapshotKey> {
exactObject(
value,
[
'publisher',
'keyId',
'publicKeyDigest',
'notBeforeMs',
'notAfterMs',
],
'snapshot key',
);
const notBeforeMs = timestamp(value.notBeforeMs, 'notBeforeMs');
const notAfterMs = timestamp(value.notAfterMs, 'notAfterMs');
if (notAfterMs <= notBeforeMs) {
return invalid('key lifetime is invalid');
}
return Object.freeze({
publisher: publisher(value.publisher),
keyId: keyId(value.keyId),
publicKeyDigest: digest(value.publicKeyDigest, 'publicKeyDigest'),
notBeforeMs,
notAfterMs,
});
}
export function pluginPackagePublisherTrustKeysetDigest(
keysValue: readonly Readonly<PluginPackagePublisherTrustSnapshotKey>[],
): string {
if (
!Array.isArray(keysValue) ||
Object.keys(keysValue).some((key, index) => key !== String(index))
) {
return invalid('keyset is invalid');
}
const keys = keysValue.map(normalizeKey);
if (
keys.some(
(key, index) => index > 0 && compareKeys(keys[index - 1]!, key) >= 0,
)
) {
return invalid('keyset must be unique and sorted');
}
return createHash('sha256')
.update(TRUST_DIGEST_DOMAIN)
.update(JSON.stringify(keys))
.digest('hex');
}
export function normalizePluginPackagePublisherTrustSnapshot(
value: PluginPackagePublisherTrustSnapshot,
): Readonly<PluginPackagePublisherTrustSnapshot> {
exactObject(value, ['schema', 'keys', 'snapshotDigest'], 'snapshot');
if (
value.schema !== PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA ||
!Array.isArray(value.keys) ||
value.keys.length > MAX_PLUGIN_PACKAGE_PUBLISHER_KEYS ||
Object.keys(value.keys).some((key, index) => key !== String(index))
) {
return invalid('snapshot schema or keys are invalid');
}
const keys = Object.freeze(value.keys.map(normalizeKey));
const snapshotDigest = pluginPackagePublisherTrustKeysetDigest(keys);
if (value.snapshotDigest !== snapshotDigest) {
return invalid('snapshotDigest does not match keys');
}
return Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA,
keys,
snapshotDigest,
});
}
export function createPluginPackagePublisherTrustSnapshot(
definitions: readonly Readonly<PluginPackagePublisherKeyDefinition>[],
): Readonly<PluginPackagePublisherTrustSnapshot> {
try {
new PluginPackagePublisherTrustRegistry(definitions);
} catch {
return invalid('publisher key definitions are invalid');
}
const keys = Object.freeze(
definitions
.map((definition) => {
let publicKeyDigest: string;
try {
publicKeyDigest = createHash('sha256')
.update(
createPublicKey(definition.publicKeyPem).export({
type: 'spki',
format: 'der',
}),
)
.digest('hex');
} catch {
return invalid('publisher public key is invalid');
}
return normalizeKey({
publisher: definition.publisher,
keyId: definition.keyId,
publicKeyDigest,
notBeforeMs: definition.notBeforeMs,
notAfterMs: definition.notAfterMs,
});
})
.sort(compareKeys),
);
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA,
keys,
});
return normalizePluginPackagePublisherTrustSnapshot({
...unsigned,
snapshotDigest: pluginPackagePublisherTrustKeysetDigest(keys),
});
}
/**
* Treats the mounted document as public-key material only and lets the durable
* effective snapshot decide which identities are trusted. Extra candidate
* keys in the document are deliberately excluded.
*/
export function createPluginPackagePublisherEffectiveTrustRegistry(
definitions: readonly Readonly<PluginPackagePublisherKeyDefinition>[],
effectiveSnapshotValue: PluginPackagePublisherTrustSnapshot,
): PluginPackagePublisherTrustRegistry {
const materialSnapshot =
createPluginPackagePublisherTrustSnapshot(definitions);
const effectiveSnapshot =
normalizePluginPackagePublisherTrustSnapshot(effectiveSnapshotValue);
const definitionsByIdentity = new Map(
definitions.map((definition) => [
`${definition.publisher}\0${definition.keyId}`,
definition,
]),
);
const materialKeys = new Map(
materialSnapshot.keys.map((key) => [
`${key.publisher}\0${key.keyId}`,
Object.freeze({
key,
definition: definitionsByIdentity.get(
`${key.publisher}\0${key.keyId}`,
),
}),
]),
);
const selected: PluginPackagePublisherKeyDefinition[] = [];
for (const effectiveKey of effectiveSnapshot.keys) {
const material = materialKeys.get(
`${effectiveKey.publisher}\0${effectiveKey.keyId}`,
);
if (
!material ||
JSON.stringify(material.key) !== JSON.stringify(effectiveKey) ||
!material.definition
) {
return invalid(
'effective trust snapshot is not backed by mounted key material',
);
}
selected.push({ ...material.definition });
}
if (selected.length < 1) {
return invalid('effective trust snapshot must contain one key');
}
return new PluginPackagePublisherTrustRegistry(selected);
}
function trustSnapshotFromKeys(
keys: readonly Readonly<PluginPackagePublisherTrustSnapshotKey>[],
): Readonly<PluginPackagePublisherTrustSnapshot> {
const canonical = Object.freeze([...keys].sort(compareKeys));
return normalizePluginPackagePublisherTrustSnapshot({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA,
keys: canonical,
snapshotDigest: pluginPackagePublisherTrustKeysetDigest(canonical),
});
}
export function createPluginPackagePublisherTrustOverlapAdditionSnapshot(
currentValue: PluginPackagePublisherTrustSnapshot,
candidateValue: PluginPackagePublisherTrustSnapshot,
publisherValue: string,
keyIdValue: string,
observedAtMsValue: number,
): Readonly<PluginPackagePublisherTrustSnapshot> {
const current =
normalizePluginPackagePublisherTrustSnapshot(currentValue);
const candidate =
normalizePluginPackagePublisherTrustSnapshot(candidateValue);
const targetPublisher = publisher(publisherValue);
const targetKeyId = keyId(keyIdValue);
const observedAtMs = timestamp(observedAtMsValue, 'observedAtMs');
const currentKeys = new Map(
current.keys.map((key) => [`${key.publisher}\0${key.keyId}`, key]),
);
const added = candidate.keys.filter(
(key) => !currentKeys.has(`${key.publisher}\0${key.keyId}`),
);
if (
candidate.keys.length !== current.keys.length + 1 ||
current.keys.some((key) => {
const next = candidate.keys.find(
(candidateKey) =>
candidateKey.publisher === key.publisher &&
candidateKey.keyId === key.keyId,
);
return !next || JSON.stringify(next) !== JSON.stringify(key);
}) ||
added.length !== 1 ||
added[0]!.publisher !== targetPublisher ||
added[0]!.keyId !== targetKeyId ||
added[0]!.notBeforeMs > observedAtMs ||
observedAtMs >= added[0]!.notAfterMs
) {
return invalid(
'overlap addition must preserve every key and add one active target',
);
}
return candidate;
}
export function createPluginPackagePublisherTrustRetirementSnapshot(
currentValue: PluginPackagePublisherTrustSnapshot,
publisherValue: string,
keyIdValue: string,
observedAtMsValue: number,
): Readonly<PluginPackagePublisherTrustSnapshot> {
const current =
normalizePluginPackagePublisherTrustSnapshot(currentValue);
const targetPublisher = publisher(publisherValue);
const targetKeyId = keyId(keyIdValue);
const observedAtMs = timestamp(observedAtMsValue, 'observedAtMs');
const remaining = current.keys.filter(
(key) =>
key.publisher !== targetPublisher || key.keyId !== targetKeyId,
);
if (
remaining.length !== current.keys.length - 1 ||
!remaining.some(
(key) =>
key.publisher === targetPublisher &&
key.notBeforeMs <= observedAtMs &&
observedAtMs < key.notAfterMs,
)
) {
return invalid(
'retirement must remove one target and retain an active publisher key',
);
}
return trustSnapshotFromKeys(remaining);
}
export function createPluginPackagePublisherEffectiveTrustSnapshot(
snapshotValue: PluginPackagePublisherTrustSnapshot,
revokedValue: readonly Readonly<PluginPackagePublisherTrustKeyRef>[],
): Readonly<PluginPackagePublisherTrustSnapshot> {
const snapshot =
normalizePluginPackagePublisherTrustSnapshot(snapshotValue);
if (
!Array.isArray(revokedValue) ||
Object.keys(revokedValue).some((key, index) => key !== String(index))
) {
return invalid('revoked key references are invalid');
}
const revoked = new Set<string>();
for (const value of revokedValue) {
exactObject(value, ['publisher', 'keyId'], 'revoked key reference');
const identity = `${publisher(value.publisher)}\0${keyId(value.keyId)}`;
if (revoked.has(identity)) {
return invalid('revoked key references must be unique');
}
revoked.add(identity);
}
const keys = Object.freeze(
snapshot.keys.filter(
(key) => !revoked.has(`${key.publisher}\0${key.keyId}`),
),
);
return normalizePluginPackagePublisherTrustSnapshot({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_SNAPSHOT_SCHEMA,
keys,
snapshotDigest: pluginPackagePublisherTrustKeysetDigest(keys),
});
}
function trustHeadDigest(
value: Omit<PluginPackagePublisherTrustHead, 'headDigest'>,
): string {
return createHash('sha256')
.update(TRUST_HEAD_DIGEST_DOMAIN)
.update(JSON.stringify(value))
.digest('hex');
}
export function normalizePluginPackagePublisherTrustHead(
value: PluginPackagePublisherTrustHead,
): Readonly<PluginPackagePublisherTrustHead> {
exactObject(
value,
[
'schema',
'authorityId',
'generation',
'baseSnapshotDigest',
'effectiveTrustDigest',
'updatedAtMs',
'headDigest',
],
'trust head',
);
if (value.schema !== PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA) {
return invalid('trust head schema is invalid');
}
const normalized = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA,
authorityId: keyId(value.authorityId),
generation: positiveInteger(value.generation, 'generation'),
baseSnapshotDigest: digest(
value.baseSnapshotDigest,
'baseSnapshotDigest',
),
effectiveTrustDigest: digest(
value.effectiveTrustDigest,
'effectiveTrustDigest',
),
updatedAtMs: timestamp(value.updatedAtMs, 'updatedAtMs'),
});
const headDigest = trustHeadDigest(normalized);
if (value.headDigest !== headDigest) {
return invalid('headDigest does not match trust head');
}
return Object.freeze({ ...normalized, headDigest });
}
export function createPluginPackagePublisherTrustHead(
authorityIdValue: string,
snapshotValue: PluginPackagePublisherTrustSnapshot,
updatedAtMsValue: number,
): Readonly<PluginPackagePublisherTrustHead> {
const snapshot =
normalizePluginPackagePublisherTrustSnapshot(snapshotValue);
if (snapshot.keys.length < 1) {
return invalid('base trust snapshot must contain one key');
}
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA,
authorityId: keyId(authorityIdValue),
generation: 1,
baseSnapshotDigest: snapshot.snapshotDigest,
effectiveTrustDigest: snapshot.snapshotDigest,
updatedAtMs: timestamp(updatedAtMsValue, 'updatedAtMs'),
});
return normalizePluginPackagePublisherTrustHead({
...unsigned,
headDigest: trustHeadDigest(unsigned),
});
}
export function advancePluginPackagePublisherTrustHead(
headValue: PluginPackagePublisherTrustHead,
effectiveSnapshotValue: PluginPackagePublisherTrustSnapshot,
updatedAtMsValue: number,
): Readonly<PluginPackagePublisherTrustHead> {
const head = normalizePluginPackagePublisherTrustHead(headValue);
const effectiveSnapshot =
normalizePluginPackagePublisherTrustSnapshot(effectiveSnapshotValue);
const updatedAtMs = timestamp(updatedAtMsValue, 'updatedAtMs');
if (
effectiveSnapshot.snapshotDigest === head.effectiveTrustDigest ||
updatedAtMs < head.updatedAtMs ||
head.generation >= 2_147_483_647
) {
return invalid('trust head transition is invalid');
}
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_HEAD_SCHEMA,
authorityId: head.authorityId,
generation: head.generation + 1,
baseSnapshotDigest: head.baseSnapshotDigest,
effectiveTrustDigest: effectiveSnapshot.snapshotDigest,
updatedAtMs,
});
return normalizePluginPackagePublisherTrustHead({
...unsigned,
headDigest: trustHeadDigest(unsigned),
});
}
export function pluginPackagePublisherTrustRevokedDigest(
snapshotValue: PluginPackagePublisherTrustSnapshot,
publisherValue: string,
keyIdValue: string,
): string {
const snapshot =
normalizePluginPackagePublisherTrustSnapshot(snapshotValue);
const targetPublisher = publisher(publisherValue);
const targetKeyId = keyId(keyIdValue);
const remaining = snapshot.keys.filter(
(key) =>
key.publisher !== targetPublisher || key.keyId !== targetKeyId,
);
if (remaining.length === snapshot.keys.length) {
return invalid('revoked key is absent from the trust snapshot');
}
return pluginPackagePublisherTrustKeysetDigest(remaining);
}
@@ -0,0 +1,708 @@
import { createHash } from 'node:crypto';
import {
normalizeApprovedActionDispatchRecord,
normalizeApprovedActionFence,
type ApprovedActionDispatchRecord,
} from '../../approved-action/approvedAction';
import {
createPluginPackagePublisherTrustOverlapAdditionSnapshot,
createPluginPackagePublisherTrustRetirementSnapshot,
normalizePluginPackagePublisherTrustSnapshot,
type PluginPackagePublisherTrustSnapshot,
} from './pluginPackagePublisherTrust';
import { normalizeProjectPolicySubject } from '../../security/project-policy/projectPolicy';
import {
type SecurityAuthenticationAssurance,
type SecurityPolicyFence,
type SecuritySubject,
} from '../../security/security';
import type { SecurityAuditRecord } from '../../security/audit/securityAudit';
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PROPOSAL_SCHEMA =
'qinglong/plugin-package-publisher-trust-transition-proposal@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_RECEIPT_SCHEMA =
'qinglong/plugin-package-publisher-trust-transition-receipt@v1' as const;
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PERMISSION =
'package.manage' as const;
export const PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES =
Object.freeze({
overlap_add: 'plugin_package.publisher_key.overlap_add',
safe_retire: 'plugin_package.publisher_key.safe_retire',
} as const);
export type PluginPackagePublisherTrustTransitionMode =
keyof typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES;
export type PluginPackagePublisherTrustTransitionActionType =
(typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES)[PluginPackagePublisherTrustTransitionMode];
export interface PluginPackagePublisherTrustTransitionActionInput {
readonly authorityProjectId: string;
readonly trustAuthorityId: string;
readonly trustGeneration: number;
readonly mode: PluginPackagePublisherTrustTransitionMode;
readonly publisher: string;
readonly keyId: string;
readonly previousTrustDigest: string;
readonly currentTrustDigest: string;
}
export interface PluginPackagePublisherTrustTransitionProposal {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PROPOSAL_SCHEMA;
readonly actionRef: string;
readonly projectId: string;
readonly actionType: PluginPackagePublisherTrustTransitionActionType;
readonly permission: typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PERMISSION;
readonly actionInput: Readonly<PluginPackagePublisherTrustTransitionActionInput>;
readonly actionDigest: string;
readonly previewDigest: string;
readonly proposedBy: Readonly<SecuritySubject>;
readonly proposerAssurance: Extract<
SecurityAuthenticationAssurance,
'multi_factor' | 'hardware'
>;
readonly proposalFence: Readonly<SecurityPolicyFence>;
readonly createdAtMs: number;
readonly proposalDigest: string;
}
export interface PluginPackagePublisherTrustTransitionReceipt {
readonly schema: typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_RECEIPT_SCHEMA;
readonly mutationId: string;
readonly proposalDigest: string;
readonly trustAuthorityId: string;
readonly previousGeneration: number;
readonly currentGeneration: number;
readonly mode: PluginPackagePublisherTrustTransitionMode;
readonly publisher: string;
readonly keyId: string;
readonly previousTrustDigest: string;
readonly currentTrustDigest: string;
readonly proposer: Readonly<SecuritySubject>;
readonly confirmer: Readonly<SecuritySubject>;
readonly retirementMatchingInstallations: 0 | null;
readonly executedAtMs: number;
readonly receiptDigest: string;
}
export type CreatePluginPackagePublisherTrustTransitionProposalInput =
Readonly<{
actionRef: string;
authorityProjectId: string;
trustAuthorityId: string;
trustGeneration: number;
mode: PluginPackagePublisherTrustTransitionMode;
trustSnapshot: PluginPackagePublisherTrustSnapshot;
materialSnapshot?: PluginPackagePublisherTrustSnapshot;
publisher: string;
keyId: string;
proposedBy: SecuritySubject;
proposerAssurance: SecurityAuthenticationAssurance;
proposalFence: SecurityPolicyFence;
createdAtMs: number;
}>;
export interface CreatePluginPackagePublisherTrustTransitionProposalCommand {
readonly proposal: PluginPackagePublisherTrustTransitionProposal;
readonly candidateSnapshot: PluginPackagePublisherTrustSnapshot;
readonly audit: SecurityAuditRecord;
}
export interface CreatePluginPackagePublisherTrustTransitionProposalResult {
readonly status: 'created' | 'existing';
readonly proposal: Readonly<PluginPackagePublisherTrustTransitionProposal>;
}
export interface PluginPackagePublisherTrustTransitionProposalRepository {
findProposalByActionRef(
actionRef: string,
): Promise<Readonly<PluginPackagePublisherTrustTransitionProposal> | null>;
createProposal(
command: CreatePluginPackagePublisherTrustTransitionProposalCommand,
): Promise<
Readonly<CreatePluginPackagePublisherTrustTransitionProposalResult>
>;
}
export class InvalidPluginPackagePublisherTrustTransitionError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_INVALID';
constructor(message: string) {
super(`Plugin Package publisher trust transition is invalid: ${message}`);
this.name = 'InvalidPluginPackagePublisherTrustTransitionError';
}
}
export class PluginPackagePublisherTrustTransitionBindingConflictError extends Error {
readonly code =
'PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_BINDING_CONFLICT';
constructor() {
super(
'Plugin Package publisher trust transition does not match its dispatch',
);
this.name =
'PluginPackagePublisherTrustTransitionBindingConflictError';
}
}
export class PluginPackagePublisherTrustTransitionConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_CONFLICT';
constructor() {
super(
'Plugin Package publisher trust transition conflicts with durable authority',
);
this.name = 'PluginPackagePublisherTrustTransitionConflictError';
}
}
export class PluginPackagePublisherTrustTransitionUnavailableError extends Error {
readonly code =
'PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super(
'Plugin Package publisher trust transition authority is unavailable',
options,
);
this.name = 'PluginPackagePublisherTrustTransitionUnavailableError';
}
}
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PUBLISHER_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
function invalid(message: string): never {
throw new InvalidPluginPackagePublisherTrustTransitionError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
({ get, set, enumerable }) =>
get !== undefined || set !== undefined || enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const canonical = [...expected].sort();
if (
actual.some((key) => typeof key !== 'string') ||
actual.length !== canonical.length ||
actual
.map(String)
.sort()
.some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function actionRef(value: unknown): string {
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
return invalid('actionRef is invalid');
}
return value;
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function publisher(value: unknown): string {
if (
typeof value !== 'string' ||
Buffer.byteLength(value, 'utf8') > 253 ||
!PUBLISHER_PATTERN.test(value)
) {
return invalid('publisher is invalid');
}
return value;
}
function projectId(value: unknown): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
Buffer.byteLength(value, 'utf8') > 128 ||
value.includes('\0')
) {
return invalid('authorityProjectId is invalid');
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function timestamp(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function positiveInteger(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 1) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function mode(value: unknown): PluginPackagePublisherTrustTransitionMode {
if (value !== 'overlap_add' && value !== 'safe_retire') {
return invalid('mode is invalid');
}
return value;
}
function strongAssurance(
value: unknown,
): 'multi_factor' | 'hardware' {
if (value !== 'multi_factor' && value !== 'hardware') {
return invalid('proposerAssurance must be multi_factor or hardware');
}
return value;
}
function userSubject(
value: SecuritySubject,
label: string,
): Readonly<SecuritySubject> {
const normalized = normalizeProjectPolicySubject(value);
if (normalized.type !== 'user') {
return invalid(`${label} must be a User`);
}
return normalized;
}
function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
function contractDigest(domain: string, value: unknown): string {
return createHash('sha256')
.update(domain)
.update('\0')
.update(JSON.stringify(value))
.digest('hex');
}
function normalizeActionInput(
value: PluginPackagePublisherTrustTransitionActionInput,
): Readonly<PluginPackagePublisherTrustTransitionActionInput> {
const record = dataRecord(value, 'action input');
exactKeys(
record,
[
'authorityProjectId',
'trustAuthorityId',
'trustGeneration',
'mode',
'publisher',
'keyId',
'previousTrustDigest',
'currentTrustDigest',
],
'action input',
);
const previousTrustDigest = digest(
value.previousTrustDigest,
'previousTrustDigest',
);
const currentTrustDigest = digest(
value.currentTrustDigest,
'currentTrustDigest',
);
if (previousTrustDigest === currentTrustDigest) {
return invalid('transition must change the trust digest');
}
return Object.freeze({
authorityProjectId: projectId(value.authorityProjectId),
trustAuthorityId: identifier(
value.trustAuthorityId,
'trustAuthorityId',
),
trustGeneration: positiveInteger(
value.trustGeneration,
'trustGeneration',
),
mode: mode(value.mode),
publisher: publisher(value.publisher),
keyId: identifier(value.keyId, 'keyId'),
previousTrustDigest,
currentTrustDigest,
});
}
export function pluginPackagePublisherTrustTransitionActionDigest(
value: PluginPackagePublisherTrustTransitionActionInput,
): string {
return contractDigest(
'qinglong/plugin-package-publisher-trust-transition-action-digest@v1',
normalizeActionInput(value),
);
}
export function pluginPackagePublisherTrustTransitionPreviewDigest(
value: PluginPackagePublisherTrustTransitionActionInput,
): string {
return contractDigest(
'qinglong/plugin-package-publisher-trust-transition-preview-digest@v1',
normalizeActionInput(value),
);
}
function withProposalDigest(
value: Omit<
PluginPackagePublisherTrustTransitionProposal,
'proposalDigest'
>,
): Readonly<PluginPackagePublisherTrustTransitionProposal> {
const normalized = Object.freeze(value);
return Object.freeze({
...normalized,
proposalDigest: contractDigest(
'qinglong/plugin-package-publisher-trust-transition-proposal-digest@v1',
normalized,
),
});
}
export function createPluginPackagePublisherTrustTransitionProposal(
inputValue: CreatePluginPackagePublisherTrustTransitionProposalInput,
): Readonly<{
proposal: Readonly<PluginPackagePublisherTrustTransitionProposal>;
candidateSnapshot: Readonly<PluginPackagePublisherTrustSnapshot>;
}> {
const input = dataRecord(inputValue, 'proposal input');
const optional = Object.hasOwn(input, 'materialSnapshot')
? ['materialSnapshot']
: [];
exactKeys(
input,
[
'actionRef',
'authorityProjectId',
'trustAuthorityId',
'trustGeneration',
'mode',
'trustSnapshot',
'publisher',
'keyId',
'proposedBy',
'proposerAssurance',
'proposalFence',
'createdAtMs',
...optional,
],
'proposal input',
);
const transitionMode = mode(inputValue.mode);
const trustSnapshot = normalizePluginPackagePublisherTrustSnapshot(
inputValue.trustSnapshot,
);
const candidateSnapshot =
transitionMode === 'overlap_add'
? createPluginPackagePublisherTrustOverlapAdditionSnapshot(
trustSnapshot,
inputValue.materialSnapshot ??
invalid('overlap addition requires materialSnapshot'),
inputValue.publisher,
inputValue.keyId,
inputValue.createdAtMs,
)
: (() => {
if (inputValue.materialSnapshot !== undefined) {
return invalid('retirement cannot accept materialSnapshot');
}
return createPluginPackagePublisherTrustRetirementSnapshot(
trustSnapshot,
inputValue.publisher,
inputValue.keyId,
inputValue.createdAtMs,
);
})();
const actionInput = normalizeActionInput({
authorityProjectId: inputValue.authorityProjectId,
trustAuthorityId: inputValue.trustAuthorityId,
trustGeneration: inputValue.trustGeneration,
mode: transitionMode,
publisher: inputValue.publisher,
keyId: inputValue.keyId,
previousTrustDigest: trustSnapshot.snapshotDigest,
currentTrustDigest: candidateSnapshot.snapshotDigest,
});
const proposal = withProposalDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PROPOSAL_SCHEMA,
actionRef: actionRef(inputValue.actionRef),
projectId: actionInput.authorityProjectId,
actionType:
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES[
transitionMode
],
permission: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PERMISSION,
actionInput,
actionDigest:
pluginPackagePublisherTrustTransitionActionDigest(actionInput),
previewDigest:
pluginPackagePublisherTrustTransitionPreviewDigest(actionInput),
proposedBy: userSubject(inputValue.proposedBy, 'proposedBy'),
proposerAssurance: strongAssurance(inputValue.proposerAssurance),
proposalFence: normalizeApprovedActionFence(inputValue.proposalFence),
createdAtMs: timestamp(inputValue.createdAtMs, 'createdAtMs'),
});
return Object.freeze({ proposal, candidateSnapshot });
}
export function normalizePluginPackagePublisherTrustTransitionProposal(
value: PluginPackagePublisherTrustTransitionProposal,
): Readonly<PluginPackagePublisherTrustTransitionProposal> {
const record = dataRecord(value, 'proposal');
exactKeys(
record,
[
'schema',
'actionRef',
'projectId',
'actionType',
'permission',
'actionInput',
'actionDigest',
'previewDigest',
'proposedBy',
'proposerAssurance',
'proposalFence',
'createdAtMs',
'proposalDigest',
],
'proposal',
);
const actionInput = normalizeActionInput(value.actionInput);
if (
value.schema !==
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PROPOSAL_SCHEMA ||
value.permission !==
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PERMISSION ||
value.actionType !==
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES[
actionInput.mode
]
) {
return invalid('schema or action authority is invalid');
}
const normalized = withProposalDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PROPOSAL_SCHEMA,
actionRef: actionRef(value.actionRef),
projectId: projectId(value.projectId),
actionType: value.actionType,
permission: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_PERMISSION,
actionInput,
actionDigest:
pluginPackagePublisherTrustTransitionActionDigest(actionInput),
previewDigest:
pluginPackagePublisherTrustTransitionPreviewDigest(actionInput),
proposedBy: userSubject(value.proposedBy, 'proposedBy'),
proposerAssurance: strongAssurance(value.proposerAssurance),
proposalFence: normalizeApprovedActionFence(value.proposalFence),
createdAtMs: timestamp(value.createdAtMs, 'createdAtMs'),
});
if (
normalized.projectId !== actionInput.authorityProjectId ||
digest(value.actionDigest, 'actionDigest') !==
normalized.actionDigest ||
digest(value.previewDigest, 'previewDigest') !==
normalized.previewDigest ||
digest(value.proposalDigest, 'proposalDigest') !==
normalized.proposalDigest
) {
return invalid('proposal digest or derived binding is invalid');
}
return normalized;
}
function withReceiptDigest(
value: Omit<
PluginPackagePublisherTrustTransitionReceipt,
'receiptDigest'
>,
): Readonly<PluginPackagePublisherTrustTransitionReceipt> {
const normalized = Object.freeze(value);
return Object.freeze({
...normalized,
receiptDigest: contractDigest(
'qinglong/plugin-package-publisher-trust-transition-receipt-digest@v1',
normalized,
),
});
}
export function normalizePluginPackagePublisherTrustTransitionReceipt(
value: PluginPackagePublisherTrustTransitionReceipt,
): Readonly<PluginPackagePublisherTrustTransitionReceipt> {
const record = dataRecord(value, 'transition receipt');
exactKeys(
record,
[
'schema',
'mutationId',
'proposalDigest',
'trustAuthorityId',
'previousGeneration',
'currentGeneration',
'mode',
'publisher',
'keyId',
'previousTrustDigest',
'currentTrustDigest',
'proposer',
'confirmer',
'retirementMatchingInstallations',
'executedAtMs',
'receiptDigest',
],
'transition receipt',
);
const transitionMode = mode(value.mode);
if (
value.schema !==
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_RECEIPT_SCHEMA ||
(transitionMode === 'overlap_add' &&
value.retirementMatchingInstallations !== null) ||
(transitionMode === 'safe_retire' &&
value.retirementMatchingInstallations !== 0)
) {
return invalid('transition receipt mode or retirement proof is invalid');
}
const previousGeneration = positiveInteger(
value.previousGeneration,
'previousGeneration',
);
const normalized = withReceiptDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_RECEIPT_SCHEMA,
mutationId: identifier(value.mutationId, 'mutationId'),
proposalDigest: digest(value.proposalDigest, 'proposalDigest'),
trustAuthorityId: identifier(
value.trustAuthorityId,
'trustAuthorityId',
),
previousGeneration,
currentGeneration: positiveInteger(
value.currentGeneration,
'currentGeneration',
),
mode: transitionMode,
publisher: publisher(value.publisher),
keyId: identifier(value.keyId, 'keyId'),
previousTrustDigest: digest(
value.previousTrustDigest,
'previousTrustDigest',
),
currentTrustDigest: digest(
value.currentTrustDigest,
'currentTrustDigest',
),
proposer: userSubject(value.proposer, 'proposer'),
confirmer: userSubject(value.confirmer, 'confirmer'),
retirementMatchingInstallations:
value.retirementMatchingInstallations,
executedAtMs: timestamp(value.executedAtMs, 'executedAtMs'),
});
if (
normalized.currentGeneration !== previousGeneration + 1 ||
normalized.previousTrustDigest === normalized.currentTrustDigest ||
sameSubject(normalized.proposer, normalized.confirmer) ||
digest(value.receiptDigest, 'receiptDigest') !==
normalized.receiptDigest
) {
return invalid('transition receipt derived binding is invalid');
}
return normalized;
}
export function resolvePluginPackagePublisherTrustTransitionProposal(
proposalValue: PluginPackagePublisherTrustTransitionProposal,
dispatchValue: ApprovedActionDispatchRecord,
executedAtMsValue: number,
retirementMatchingInstallationsValue: 0 | null,
): Readonly<PluginPackagePublisherTrustTransitionReceipt> {
const proposal =
normalizePluginPackagePublisherTrustTransitionProposal(proposalValue);
const dispatch = normalizeApprovedActionDispatchRecord(dispatchValue);
const executedAtMs = timestamp(executedAtMsValue, 'executedAtMs');
const action = proposal.actionInput;
if (
dispatch.projectId !== proposal.projectId ||
dispatch.action.actionRef !== proposal.actionRef ||
dispatch.action.actionType !== proposal.actionType ||
dispatch.action.permission !== proposal.permission ||
dispatch.action.actionDigest !== proposal.actionDigest ||
dispatch.action.previewDigest !== proposal.previewDigest ||
!sameSubject(dispatch.requestedBy, proposal.proposedBy) ||
sameSubject(dispatch.requestedBy, dispatch.approvedBy) ||
(dispatch.approvalAssurance !== 'multi_factor' &&
dispatch.approvalAssurance !== 'hardware') ||
dispatch.createdAtMs < proposal.createdAtMs ||
executedAtMs < dispatch.createdAtMs ||
executedAtMs >= dispatch.expiresAtMs ||
(action.mode === 'overlap_add' &&
retirementMatchingInstallationsValue !== null) ||
(action.mode === 'safe_retire' &&
retirementMatchingInstallationsValue !== 0)
) {
throw new PluginPackagePublisherTrustTransitionBindingConflictError();
}
return normalizePluginPackagePublisherTrustTransitionReceipt(
withReceiptDigest({
schema: PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_RECEIPT_SCHEMA,
mutationId: dispatch.id,
proposalDigest: proposal.proposalDigest,
trustAuthorityId: action.trustAuthorityId,
previousGeneration: action.trustGeneration,
currentGeneration: action.trustGeneration + 1,
mode: action.mode,
publisher: action.publisher,
keyId: action.keyId,
previousTrustDigest: action.previousTrustDigest,
currentTrustDigest: action.currentTrustDigest,
proposer: proposal.proposedBy,
confirmer: dispatch.approvedBy,
retirementMatchingInstallations:
retirementMatchingInstallationsValue,
executedAtMs,
}),
);
}
@@ -0,0 +1,265 @@
import type {
SecurityPolicyFence,
SecuritySubject,
} from '../../../security/security';
import type { SecurityAuditRecord } from '../../../security/audit/securityAudit';
import type { RunCancellationReason, RunStatus } from '../../../run/run';
import type { StepRunKind, StepRunStatus } from '../../../run/stepRun';
import type {
PluginPackageWorkflowAdmissionReceipt,
PluginPackageWorkflowExecutionPlan,
} from '../pluginPackageWorkflowExecutionPlan';
export interface AuthorizedPluginPackageWorkflowAdmission {
readonly plan: PluginPackageWorkflowExecutionPlan;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowAdministrationRepository {
findPlanByPlanId(
planId: string,
): Promise<Readonly<PluginPackageWorkflowExecutionPlan> | null>;
admitAuthorized(admission: AuthorizedPluginPackageWorkflowAdmission): Promise<
Readonly<{
status: 'created' | 'existing';
receipt: Readonly<PluginPackageWorkflowAdmissionReceipt>;
}>
>;
}
export const PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_STATUSES = [
'accepted',
'existing',
'already_requested',
'already_terminal',
] as const;
export type PluginPackageWorkflowCancellationStatus =
(typeof PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_STATUSES)[number];
export interface AuthorizedPluginPackageWorkflowCancellation {
readonly projectId: string;
readonly packageName: string;
readonly runId: string;
readonly mutationId: string;
readonly runEventId: string;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowCancellationResult {
readonly status: PluginPackageWorkflowCancellationStatus;
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly runStatus: RunStatus;
readonly runVersion: number;
readonly eventSequence: number;
readonly cancelRequestedAtMs?: number;
readonly cancelReason?: RunCancellationReason;
}
export interface PluginPackageWorkflowCancellationRepository {
requestUserCancellation(
cancellation: AuthorizedPluginPackageWorkflowCancellation,
): Promise<Readonly<PluginPackageWorkflowCancellationResult>>;
}
export const PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA =
'qinglong/plugin-package-workflow-run-inspection@v1' as const;
export interface AuthorizedPluginPackageWorkflowRunInspection {
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowRunInspectionResult {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA;
readonly found: boolean;
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly run: Readonly<{
status: RunStatus;
version: number;
eventSequence: number;
createdAtMs: number;
queuedAtMs: number | null;
startedAtMs: number | null;
finishedAtMs: number | null;
cancelRequestedAtMs: number | null;
cancelReason: RunCancellationReason | null;
}> | null;
readonly stepCount: number | null;
readonly stepStatusCounts: Readonly<Record<StepRunStatus, number>> | null;
}
export interface PluginPackageWorkflowRunInspectionRepository {
inspectRunAuthorized(
inspection: AuthorizedPluginPackageWorkflowRunInspection,
): Promise<Readonly<PluginPackageWorkflowRunInspectionResult>>;
}
export const PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_SCHEMA =
'qinglong/plugin-package-workflow-run-list@v1' as const;
export const DEFAULT_PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_PAGE_SIZE = 32;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_PAGE_SIZE = 64;
export interface PluginPackageWorkflowRunListCursor {
readonly admittedAtMs: number;
readonly runId: string;
}
export interface AuthorizedPluginPackageWorkflowRunList {
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly limit: number;
readonly after: Readonly<PluginPackageWorkflowRunListCursor> | null;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowRunListItem {
readonly runId: string;
readonly status: RunStatus;
readonly version: number;
readonly eventSequence: number;
readonly stepCount: number;
readonly admittedAtMs: number;
readonly queuedAtMs: number | null;
readonly startedAtMs: number | null;
readonly finishedAtMs: number | null;
readonly cancelRequestedAtMs: number | null;
readonly cancelReason: RunCancellationReason | null;
}
export interface PluginPackageWorkflowRunListResult {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_SCHEMA;
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly after: Readonly<PluginPackageWorkflowRunListCursor> | null;
readonly runs: readonly Readonly<PluginPackageWorkflowRunListItem>[];
readonly truncated: boolean;
readonly next: Readonly<PluginPackageWorkflowRunListCursor> | null;
}
export interface PluginPackageWorkflowRunListRepository {
listRunsAuthorized(
query: AuthorizedPluginPackageWorkflowRunList,
): Promise<Readonly<PluginPackageWorkflowRunListResult>>;
}
export const PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA =
'qinglong/plugin-package-workflow-step-run-list@v1' as const;
export const DEFAULT_PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_PAGE_SIZE = 32;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_PAGE_SIZE = 64;
export interface PluginPackageWorkflowStepRunCursor {
readonly stepKey: string;
readonly id: string;
}
export interface AuthorizedPluginPackageWorkflowStepRunList {
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly limit: number;
readonly after: Readonly<PluginPackageWorkflowStepRunCursor> | null;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowStepRunListItem {
readonly id: string;
readonly parentStepRunId: string | null;
readonly stepKey: string;
readonly kind: StepRunKind;
readonly required: boolean;
readonly status: StepRunStatus;
readonly version: number;
readonly attemptCount: number;
readonly readyAtMs: number | null;
readonly startedAtMs: number | null;
readonly finishedAtMs: number | null;
readonly resultCode: string | null;
readonly createdAtMs: number;
readonly updatedAtMs: number;
}
export interface PluginPackageWorkflowStepRunListResult {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA;
readonly found: boolean;
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly stepRuns: readonly Readonly<PluginPackageWorkflowStepRunListItem>[];
readonly truncated: boolean;
readonly next: Readonly<PluginPackageWorkflowStepRunCursor> | null;
}
export interface PluginPackageWorkflowStepRunListRepository {
listStepRunsAuthorized(
query: AuthorizedPluginPackageWorkflowStepRunList,
): Promise<Readonly<PluginPackageWorkflowStepRunListResult>>;
}
export const PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA =
'qinglong/plugin-package-workflow-run-event-list@v1' as const;
export const DEFAULT_PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_PAGE_SIZE = 32;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_PAGE_SIZE = 64;
export interface AuthorizedPluginPackageWorkflowRunEventList {
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly limit: number;
readonly afterSequence: number;
readonly actor: SecuritySubject;
readonly fence: SecurityPolicyFence;
readonly audit: SecurityAuditRecord;
}
export interface PluginPackageWorkflowRunEventListItem {
readonly id: string;
readonly sequence: number;
readonly type: string;
readonly stepRunId: string | null;
readonly createdAtMs: number;
}
export interface PluginPackageWorkflowRunEventListResult {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA;
readonly found: boolean;
readonly projectId: string;
readonly packageName: string;
readonly workflowId: string;
readonly runId: string;
readonly afterSequence: number;
readonly headSequence: number | null;
readonly events: readonly Readonly<PluginPackageWorkflowRunEventListItem>[];
readonly truncated: boolean;
readonly nextAfterSequence: number | null;
}
export interface PluginPackageWorkflowRunEventListRepository {
listRunEventsAuthorized(
query: AuthorizedPluginPackageWorkflowRunEventList,
): Promise<Readonly<PluginPackageWorkflowRunEventListResult>>;
}
@@ -0,0 +1,41 @@
export class InvalidPluginPackageWorkflowAdministrationMutationError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMINISTRATION_MUTATION_INVALID';
constructor(message: string) {
super(
`Plugin Package Workflow administration mutation is invalid: ${message}`,
);
this.name = 'InvalidPluginPackageWorkflowAdministrationMutationError';
}
}
export class PluginPackageWorkflowAdministrationAuthorizationFenceConflictError extends Error {
readonly code =
'PLUGIN_PACKAGE_WORKFLOW_ADMINISTRATION_AUTHORIZATION_FENCE_CONFLICT';
constructor() {
super('Plugin Package Workflow administration authorization fence changed');
this.name =
'PluginPackageWorkflowAdministrationAuthorizationFenceConflictError';
}
}
export class PluginPackageWorkflowAdministrationMutationConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMINISTRATION_MUTATION_CONFLICT';
constructor() {
super(
'Plugin Package Workflow administration conflicts with durable state',
);
this.name = 'PluginPackageWorkflowAdministrationMutationConflictError';
}
}
export class PluginPackageWorkflowCancellationNotFoundError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_NOT_FOUND';
constructor() {
super('Plugin Package Workflow cancellation target does not exist');
this.name = 'PluginPackageWorkflowCancellationNotFoundError';
}
}
@@ -0,0 +1,206 @@
import { normalizeProjectPolicySubject } from '../../../security/project-policy/projectPolicy';
import { normalizeSecurityAuditRecord } from '../../../security/audit/securityAudit';
import { RUN_STATUSES } from '../../../run/run';
import { normalizePluginPackageWorkflowExecutionPlan } from '../pluginPackageWorkflowExecutionPlan';
import {
PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_STATUSES,
type AuthorizedPluginPackageWorkflowAdmission,
type AuthorizedPluginPackageWorkflowCancellation,
type PluginPackageWorkflowCancellationResult,
} from './contracts';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
import {
exactKeys,
identifier,
normalizeFence,
packageName,
sameSubject,
} from './support';
export function normalizeAuthorizedPluginPackageWorkflowAdmission(
value: AuthorizedPluginPackageWorkflowAdmission,
): Readonly<AuthorizedPluginPackageWorkflowAdmission> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['actor', 'audit', 'fence', 'plan'])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'admission shape is invalid',
);
}
try {
const plan = normalizePluginPackageWorkflowExecutionPlan(value.plan);
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.start' ||
audit.projectId !== plan.target.projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
audit.occurredAtMs !== plan.plannedAtMs ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'audit binding is invalid',
);
}
return Object.freeze({ plan, actor, fence, audit });
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'admission value is invalid',
);
}
}
export function normalizeAuthorizedPluginPackageWorkflowCancellation(
value: AuthorizedPluginPackageWorkflowCancellation,
): Readonly<AuthorizedPluginPackageWorkflowCancellation> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'actor',
'audit',
'fence',
'mutationId',
'packageName',
'projectId',
'runEventId',
'runId',
])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'cancellation shape is invalid',
);
}
try {
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const runId = identifier(value.runId, 'runId');
const mutationId = identifier(value.mutationId, 'mutationId');
const runEventId = identifier(value.runEventId, 'runEventId');
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.cancel' ||
audit.projectId !== projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'cancellation audit binding is invalid',
);
}
return Object.freeze({
projectId,
packageName: normalizedPackageName,
runId,
mutationId,
runEventId,
actor,
fence,
audit,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'cancellation value is invalid',
);
}
}
export function normalizePluginPackageWorkflowCancellationResult(
value: PluginPackageWorkflowCancellationResult,
): Readonly<PluginPackageWorkflowCancellationResult> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'cancellation result is invalid',
);
}
const hasCancellation = value.cancelRequestedAtMs !== undefined;
if (
!exactKeys(
value,
hasCancellation
? [
'cancelReason',
'cancelRequestedAtMs',
'eventSequence',
'packageName',
'projectId',
'runId',
'runStatus',
'runVersion',
'status',
'workflowId',
]
: [
'eventSequence',
'packageName',
'projectId',
'runId',
'runStatus',
'runVersion',
'status',
'workflowId',
],
) ||
!PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_STATUSES.includes(value.status) ||
!RUN_STATUSES.includes(value.runStatus) ||
!Number.isSafeInteger(value.runVersion) ||
value.runVersion < 1 ||
!Number.isSafeInteger(value.eventSequence) ||
value.eventSequence < 0 ||
(hasCancellation &&
(!Number.isSafeInteger(value.cancelRequestedAtMs) ||
(value.cancelRequestedAtMs as number) < 0 ||
!['user', 'policy', 'shutdown', 'reconcile', 'timeout'].includes(
value.cancelReason ?? '',
))) ||
(!hasCancellation && value.cancelReason !== undefined)
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'cancellation result state is invalid',
);
}
return Object.freeze({
status: value.status,
projectId: identifier(value.projectId, 'projectId'),
packageName: packageName(value.packageName),
workflowId: identifier(value.workflowId, 'workflowId'),
runId: identifier(value.runId, 'runId'),
runStatus: value.runStatus,
runVersion: value.runVersion,
eventSequence: value.eventSequence,
...(hasCancellation
? {
cancelRequestedAtMs: value.cancelRequestedAtMs!,
cancelReason: value.cancelReason!,
}
: {}),
});
}
@@ -0,0 +1,254 @@
import { normalizeProjectPolicySubject } from '../../../security/project-policy/projectPolicy';
import { normalizeSecurityAuditRecord } from '../../../security/audit/securityAudit';
import {
MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_PAGE_SIZE,
PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA,
type AuthorizedPluginPackageWorkflowRunEventList,
type PluginPackageWorkflowRunEventListItem,
type PluginPackageWorkflowRunEventListResult,
} from './contracts';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
import {
exactKeys,
identifier,
normalizeFence,
packageName,
resourceId,
sameSubject,
} from './support';
export function normalizeAuthorizedPluginPackageWorkflowRunEventList(
value: AuthorizedPluginPackageWorkflowRunEventList,
): Readonly<AuthorizedPluginPackageWorkflowRunEventList> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'actor',
'afterSequence',
'audit',
'fence',
'limit',
'packageName',
'projectId',
'runId',
'workflowId',
])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list shape is invalid',
);
}
try {
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
if (
!Number.isSafeInteger(value.limit) ||
value.limit < 1 ||
value.limit > MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_PAGE_SIZE ||
!Number.isSafeInteger(value.afterSequence) ||
value.afterSequence < 0
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list page is invalid',
);
}
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.event.list' ||
audit.projectId !== projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list audit binding is invalid',
);
}
return Object.freeze({
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
limit: value.limit,
afterSequence: value.afterSequence,
actor,
fence,
audit,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list value is invalid',
);
}
}
const RUN_EVENT_TYPE = /^[a-z][a-z0-9_.-]{0,127}$/;
function normalizeWorkflowRunEventListItem(
value: PluginPackageWorkflowRunEventListItem,
): Readonly<PluginPackageWorkflowRunEventListItem> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['createdAtMs', 'id', 'sequence', 'stepRunId', 'type']) ||
!Number.isSafeInteger(value.sequence) ||
value.sequence < 1 ||
typeof value.type !== 'string' ||
!RUN_EVENT_TYPE.test(value.type) ||
!Number.isSafeInteger(value.createdAtMs) ||
value.createdAtMs < 0
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list item is invalid',
);
}
return Object.freeze({
id: identifier(value.id, 'RunEvent id'),
sequence: value.sequence,
type: value.type,
stepRunId:
value.stepRunId === null
? null
: identifier(value.stepRunId, 'RunEvent StepRun id'),
createdAtMs: value.createdAtMs,
});
}
export function normalizePluginPackageWorkflowRunEventListResult(
value: PluginPackageWorkflowRunEventListResult,
): Readonly<PluginPackageWorkflowRunEventListResult> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'afterSequence',
'events',
'found',
'headSequence',
'nextAfterSequence',
'packageName',
'projectId',
'runId',
'schema',
'truncated',
'workflowId',
]) ||
value.schema !== PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA ||
typeof value.found !== 'boolean' ||
typeof value.truncated !== 'boolean' ||
!Number.isSafeInteger(value.afterSequence) ||
value.afterSequence < 0 ||
!Array.isArray(value.events) ||
value.events.length > MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_PAGE_SIZE
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list result shape is invalid',
);
}
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
if (!value.found) {
if (
value.headSequence !== null ||
value.events.length !== 0 ||
value.truncated ||
value.nextAfterSequence !== null
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'missing RunEvent list result is invalid',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA,
found: false,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
afterSequence: value.afterSequence,
headSequence: null,
events: Object.freeze([]),
truncated: false,
nextAfterSequence: null,
});
}
if (
!Number.isSafeInteger(value.headSequence) ||
(value.headSequence as number) < 0 ||
value.afterSequence > (value.headSequence as number)
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list head is invalid',
);
}
const headSequence = value.headSequence as number;
const events = value.events.map(normalizeWorkflowRunEventListItem);
const ids = new Set<string>();
for (let index = 0; index < events.length; index += 1) {
const event = events[index]!;
if (
ids.has(event.id) ||
event.sequence !== value.afterSequence + index + 1 ||
event.sequence > headSequence
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list sequence is invalid',
);
}
ids.add(event.id);
}
const lastSequence = events.at(-1)?.sequence ?? value.afterSequence;
let nextAfterSequence: number | null = null;
if (value.truncated) {
if (
events.length === 0 ||
lastSequence >= headSequence ||
value.nextAfterSequence !== lastSequence
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list continuation is invalid',
);
}
nextAfterSequence = lastSequence;
} else if (
value.nextAfterSequence !== null ||
lastSequence !== headSequence
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'RunEvent list terminal page is invalid',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_RUN_EVENT_LIST_SCHEMA,
found: true,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
afterSequence: value.afterSequence,
headSequence,
events: Object.freeze(events),
truncated: value.truncated,
nextAfterSequence,
});
}
@@ -0,0 +1,225 @@
import { normalizeProjectPolicySubject } from '../../../security/project-policy/projectPolicy';
import { normalizeSecurityAuditRecord } from '../../../security/audit/securityAudit';
import { RUN_CANCELLATION_REASONS, RUN_STATUSES } from '../../../run/run';
import { STEP_RUN_STATUSES, type StepRunStatus } from '../../../run/stepRun';
import {
PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA,
type AuthorizedPluginPackageWorkflowRunInspection,
type PluginPackageWorkflowRunInspectionResult,
} from './contracts';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
import {
exactKeys,
identifier,
normalizeFence,
nullableTimestamp,
packageName,
resourceId,
sameSubject,
} from './support';
export function normalizeAuthorizedPluginPackageWorkflowRunInspection(
value: AuthorizedPluginPackageWorkflowRunInspection,
): Readonly<AuthorizedPluginPackageWorkflowRunInspection> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'actor',
'audit',
'fence',
'packageName',
'projectId',
'runId',
'workflowId',
])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection shape is invalid',
);
}
try {
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.run.read' ||
audit.projectId !== projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection audit binding is invalid',
);
}
return Object.freeze({
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
actor,
fence,
audit,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection value is invalid',
);
}
}
export function normalizePluginPackageWorkflowRunInspectionResult(
value: PluginPackageWorkflowRunInspectionResult,
): Readonly<PluginPackageWorkflowRunInspectionResult> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'found',
'packageName',
'projectId',
'run',
'runId',
'schema',
'stepCount',
'stepStatusCounts',
'workflowId',
]) ||
value.schema !== PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA ||
typeof value.found !== 'boolean'
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection result shape is invalid',
);
}
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
if (!value.found) {
if (
value.run !== null ||
value.stepCount !== null ||
value.stepStatusCounts !== null
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'missing run inspection result is invalid',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA,
found: false,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
run: null,
stepCount: null,
stepStatusCounts: null,
});
}
if (
!value.run ||
typeof value.run !== 'object' ||
Array.isArray(value.run) ||
!exactKeys(value.run, [
'cancelReason',
'cancelRequestedAtMs',
'createdAtMs',
'eventSequence',
'finishedAtMs',
'queuedAtMs',
'startedAtMs',
'status',
'version',
]) ||
!RUN_STATUSES.includes(value.run.status) ||
!Number.isSafeInteger(value.run.version) ||
value.run.version < 1 ||
!Number.isSafeInteger(value.run.eventSequence) ||
value.run.eventSequence < 0 ||
!Number.isSafeInteger(value.run.createdAtMs) ||
value.run.createdAtMs < 0 ||
!Number.isSafeInteger(value.stepCount) ||
(value.stepCount as number) < 1 ||
(value.stepCount as number) > 128 ||
!value.stepStatusCounts ||
typeof value.stepStatusCounts !== 'object' ||
Array.isArray(value.stepStatusCounts) ||
!exactKeys(value.stepStatusCounts, STEP_RUN_STATUSES)
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'found run inspection result is invalid',
);
}
const queuedAtMs = nullableTimestamp(value.run.queuedAtMs);
const startedAtMs = nullableTimestamp(value.run.startedAtMs);
const finishedAtMs = nullableTimestamp(value.run.finishedAtMs);
const cancelRequestedAtMs = nullableTimestamp(value.run.cancelRequestedAtMs);
const cancelReason = value.run.cancelReason;
if (
(cancelRequestedAtMs === null) !== (cancelReason === null) ||
(cancelReason !== null && !RUN_CANCELLATION_REASONS.includes(cancelReason))
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection cancellation state is invalid',
);
}
const counts = Object.fromEntries(
STEP_RUN_STATUSES.map((status) => {
const count = value.stepStatusCounts![status];
if (!Number.isSafeInteger(count) || count < 0 || count > 128) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection StepRun counts are invalid',
);
}
return [status, count];
}),
) as Record<StepRunStatus, number>;
if (
Object.values(counts).reduce((total, count) => total + count, 0) !==
value.stepCount
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection StepRun count is inconsistent',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_RUN_INSPECTION_SCHEMA,
found: true,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
run: Object.freeze({
status: value.run.status,
version: value.run.version,
eventSequence: value.run.eventSequence,
createdAtMs: value.run.createdAtMs,
queuedAtMs,
startedAtMs,
finishedAtMs,
cancelRequestedAtMs,
cancelReason,
}),
stepCount: value.stepCount,
stepStatusCounts: Object.freeze(counts),
});
}
@@ -0,0 +1,282 @@
import { normalizeProjectPolicySubject } from '../../../security/project-policy/projectPolicy';
import { normalizeSecurityAuditRecord } from '../../../security/audit/securityAudit';
import { RUN_CANCELLATION_REASONS, RUN_STATUSES } from '../../../run/run';
import {
MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_PAGE_SIZE,
PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_SCHEMA,
type AuthorizedPluginPackageWorkflowRunList,
type PluginPackageWorkflowRunListCursor,
type PluginPackageWorkflowRunListItem,
type PluginPackageWorkflowRunListResult,
} from './contracts';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
import {
exactKeys,
identifier,
normalizeFence,
nullableTimestamp,
packageName,
resourceId,
sameSubject,
} from './support';
function normalizeWorkflowRunListCursor(
value: PluginPackageWorkflowRunListCursor,
label: string,
): Readonly<PluginPackageWorkflowRunListCursor> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['admittedAtMs', 'runId']) ||
!Number.isSafeInteger(value.admittedAtMs) ||
value.admittedAtMs < 0
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
`${label} is invalid`,
);
}
return Object.freeze({
admittedAtMs: value.admittedAtMs,
runId: identifier(value.runId, `${label}.runId`),
});
}
function workflowRunListPositionBefore(
left: Readonly<PluginPackageWorkflowRunListCursor>,
right: Readonly<PluginPackageWorkflowRunListCursor>,
): boolean {
return (
left.admittedAtMs < right.admittedAtMs ||
(left.admittedAtMs === right.admittedAtMs && left.runId < right.runId)
);
}
export function normalizeAuthorizedPluginPackageWorkflowRunList(
value: AuthorizedPluginPackageWorkflowRunList,
): Readonly<AuthorizedPluginPackageWorkflowRunList> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'actor',
'after',
'audit',
'fence',
'limit',
'packageName',
'projectId',
'workflowId',
])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list shape is invalid',
);
}
try {
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
if (
!Number.isSafeInteger(value.limit) ||
value.limit < 1 ||
value.limit > MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_PAGE_SIZE
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list limit is invalid',
);
}
const after =
value.after === null
? null
: normalizeWorkflowRunListCursor(value.after, 'run list cursor');
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.run.list' ||
audit.projectId !== projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list audit binding is invalid',
);
}
return Object.freeze({
projectId,
packageName: normalizedPackageName,
workflowId,
limit: value.limit,
after,
actor,
fence,
audit,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list value is invalid',
);
}
}
function normalizeWorkflowRunListItem(
value: PluginPackageWorkflowRunListItem,
): Readonly<PluginPackageWorkflowRunListItem> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'admittedAtMs',
'cancelReason',
'cancelRequestedAtMs',
'eventSequence',
'finishedAtMs',
'queuedAtMs',
'runId',
'startedAtMs',
'status',
'stepCount',
'version',
]) ||
!RUN_STATUSES.includes(value.status) ||
!Number.isSafeInteger(value.version) ||
value.version < 1 ||
!Number.isSafeInteger(value.eventSequence) ||
value.eventSequence < 0 ||
!Number.isSafeInteger(value.stepCount) ||
value.stepCount < 1 ||
value.stepCount > 128 ||
!Number.isSafeInteger(value.admittedAtMs) ||
value.admittedAtMs < 0
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list item is invalid',
);
}
const queuedAtMs = nullableTimestamp(value.queuedAtMs);
const startedAtMs = nullableTimestamp(value.startedAtMs);
const finishedAtMs = nullableTimestamp(value.finishedAtMs);
const cancelRequestedAtMs = nullableTimestamp(value.cancelRequestedAtMs);
if (
(cancelRequestedAtMs === null) !== (value.cancelReason === null) ||
(value.cancelReason !== null &&
!RUN_CANCELLATION_REASONS.includes(value.cancelReason))
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list cancellation state is invalid',
);
}
return Object.freeze({
runId: identifier(value.runId, 'run list runId'),
status: value.status,
version: value.version,
eventSequence: value.eventSequence,
stepCount: value.stepCount,
admittedAtMs: value.admittedAtMs,
queuedAtMs,
startedAtMs,
finishedAtMs,
cancelRequestedAtMs,
cancelReason: value.cancelReason,
});
}
export function normalizePluginPackageWorkflowRunListResult(
value: PluginPackageWorkflowRunListResult,
): Readonly<PluginPackageWorkflowRunListResult> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'after',
'next',
'packageName',
'projectId',
'runs',
'schema',
'truncated',
'workflowId',
]) ||
value.schema !== PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_SCHEMA ||
!Array.isArray(value.runs) ||
value.runs.length > MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_PAGE_SIZE ||
typeof value.truncated !== 'boolean'
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list result shape is invalid',
);
}
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const after =
value.after === null
? null
: normalizeWorkflowRunListCursor(value.after, 'run list result cursor');
const runs = value.runs.map(normalizeWorkflowRunListItem);
const ids = new Set<string>();
for (let index = 0; index < runs.length; index += 1) {
const run = runs[index]!;
const position = { admittedAtMs: run.admittedAtMs, runId: run.runId };
if (ids.has(run.runId)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list identities are not unique',
);
}
ids.add(run.runId);
const previous = index === 0 ? after : runs[index - 1]!;
if (
previous !== null &&
!workflowRunListPositionBefore(position, {
admittedAtMs: previous.admittedAtMs,
runId: previous.runId,
})
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list order is invalid',
);
}
}
const next =
value.next === null
? null
: normalizeWorkflowRunListCursor(value.next, 'run list next cursor');
const last = runs.at(-1);
if (
(value.truncated &&
(!last ||
!next ||
next.admittedAtMs !== last.admittedAtMs ||
next.runId !== last.runId)) ||
(!value.truncated && next !== null)
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run list continuation is invalid',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_RUN_LIST_SCHEMA,
projectId,
packageName: normalizedPackageName,
workflowId,
after,
runs: Object.freeze(runs),
truncated: value.truncated,
next,
});
}
@@ -0,0 +1,339 @@
import { normalizeProjectPolicySubject } from '../../../security/project-policy/projectPolicy';
import { normalizeSecurityAuditRecord } from '../../../security/audit/securityAudit';
import { STEP_RUN_KINDS, STEP_RUN_STATUSES } from '../../../run/stepRun';
import {
MAX_PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_PAGE_SIZE,
PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA,
type AuthorizedPluginPackageWorkflowStepRunList,
type PluginPackageWorkflowStepRunCursor,
type PluginPackageWorkflowStepRunListItem,
type PluginPackageWorkflowStepRunListResult,
} from './contracts';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
import {
exactKeys,
identifier,
normalizeFence,
nullableTimestamp,
packageName,
resourceId,
sameSubject,
} from './support';
export function normalizeAuthorizedPluginPackageWorkflowStepRunList(
value: AuthorizedPluginPackageWorkflowStepRunList,
): Readonly<AuthorizedPluginPackageWorkflowStepRunList> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'actor',
'after',
'audit',
'fence',
'limit',
'packageName',
'projectId',
'runId',
'workflowId',
])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list shape is invalid',
);
}
try {
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
if (
!Number.isSafeInteger(value.limit) ||
value.limit < 1 ||
value.limit > MAX_PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_PAGE_SIZE
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list limit is invalid',
);
}
let after: Readonly<PluginPackageWorkflowStepRunCursor> | null = null;
if (value.after !== null) {
if (
!value.after ||
typeof value.after !== 'object' ||
Array.isArray(value.after) ||
!exactKeys(value.after, ['id', 'stepKey'])
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list cursor is invalid',
);
}
after = Object.freeze({
stepKey: resourceId(value.after.stepKey, 'after.stepKey'),
id: identifier(value.after.id, 'after.id'),
});
}
const actor = normalizeProjectPolicySubject(value.actor);
const fence = normalizeFence(value.fence);
const audit = normalizeSecurityAuditRecord(value.audit);
if (
audit.operationId !== 'workflow.step.list' ||
audit.projectId !== projectId ||
audit.outcome !== 'allowed' ||
!audit.subject ||
!sameSubject(audit.subject, actor) ||
audit.authenticationId === null ||
!audit.fence ||
audit.fence.projectVersion !== fence.projectVersion ||
audit.fence.bindingVersion !== fence.bindingVersion
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list audit binding is invalid',
);
}
return Object.freeze({
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
limit: value.limit,
after,
actor,
fence,
audit,
});
} catch (error) {
if (
error instanceof InvalidPluginPackageWorkflowAdministrationMutationError
) {
throw error;
}
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list value is invalid',
);
}
}
const STEP_RUN_RESULT_CODE = /^[a-z][a-z0-9_]{0,63}$/;
function normalizeWorkflowStepRunListItem(
value: PluginPackageWorkflowStepRunListItem,
): Readonly<PluginPackageWorkflowStepRunListItem> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'attemptCount',
'createdAtMs',
'finishedAtMs',
'id',
'kind',
'parentStepRunId',
'readyAtMs',
'required',
'resultCode',
'startedAtMs',
'status',
'stepKey',
'updatedAtMs',
'version',
]) ||
!STEP_RUN_KINDS.includes(value.kind) ||
!STEP_RUN_STATUSES.includes(value.status) ||
typeof value.required !== 'boolean' ||
!Number.isSafeInteger(value.version) ||
value.version < 1 ||
value.version > 2_147_483_647 ||
!Number.isSafeInteger(value.attemptCount) ||
value.attemptCount < 0 ||
value.attemptCount > 64 ||
!Number.isSafeInteger(value.createdAtMs) ||
value.createdAtMs < 0 ||
!Number.isSafeInteger(value.updatedAtMs) ||
value.updatedAtMs < value.createdAtMs
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list item is invalid',
);
}
const id = identifier(value.id, 'StepRun id');
const parentStepRunId =
value.parentStepRunId === null
? null
: identifier(value.parentStepRunId, 'parent StepRun id');
if (parentStepRunId === id) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list parent is invalid',
);
}
const stepKey = resourceId(value.stepKey, 'StepRun stepKey');
const readyAtMs = nullableTimestamp(value.readyAtMs);
const startedAtMs = nullableTimestamp(value.startedAtMs);
const finishedAtMs = nullableTimestamp(value.finishedAtMs);
const resultCode = value.resultCode;
if (
(resultCode !== null &&
(typeof resultCode !== 'string' ||
!STEP_RUN_RESULT_CODE.test(resultCode))) ||
(readyAtMs !== null &&
(readyAtMs < value.createdAtMs || readyAtMs > value.updatedAtMs)) ||
(startedAtMs !== null &&
(readyAtMs === null ||
startedAtMs < readyAtMs ||
startedAtMs > value.updatedAtMs)) ||
(finishedAtMs !== null &&
(finishedAtMs < value.createdAtMs ||
finishedAtMs > value.updatedAtMs ||
(readyAtMs !== null && finishedAtMs < readyAtMs) ||
(startedAtMs !== null && finishedAtMs < startedAtMs))) ||
(value.status === 'pending' &&
(readyAtMs !== null || startedAtMs !== null || finishedAtMs !== null)) ||
((value.status === 'ready' || value.status === 'waiting_approval') &&
(readyAtMs === null || startedAtMs !== null || finishedAtMs !== null)) ||
((value.status === 'running' || value.status === 'lost') &&
(readyAtMs === null || startedAtMs === null || finishedAtMs !== null)) ||
(['succeeded', 'failed', 'skipped', 'cancelled', 'timed_out'].includes(
value.status,
) &&
finishedAtMs === null) ||
(value.status === 'succeeded' && resultCode !== null) ||
(['failed', 'skipped', 'cancelled', 'timed_out', 'lost'].includes(
value.status,
) &&
resultCode === null) ||
(['pending', 'ready', 'waiting_approval', 'running'].includes(
value.status,
) &&
resultCode !== null)
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list item state is invalid',
);
}
return Object.freeze({
id,
parentStepRunId,
stepKey,
kind: value.kind,
required: value.required,
status: value.status,
version: value.version,
attemptCount: value.attemptCount,
readyAtMs,
startedAtMs,
finishedAtMs,
resultCode,
createdAtMs: value.createdAtMs,
updatedAtMs: value.updatedAtMs,
});
}
export function normalizePluginPackageWorkflowStepRunListResult(
value: PluginPackageWorkflowStepRunListResult,
): Readonly<PluginPackageWorkflowStepRunListResult> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, [
'found',
'next',
'packageName',
'projectId',
'runId',
'schema',
'stepRuns',
'truncated',
'workflowId',
]) ||
value.schema !== PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA ||
typeof value.found !== 'boolean' ||
typeof value.truncated !== 'boolean' ||
!Array.isArray(value.stepRuns) ||
value.stepRuns.length > MAX_PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_PAGE_SIZE
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list result shape is invalid',
);
}
const projectId = identifier(value.projectId, 'projectId');
const normalizedPackageName = packageName(value.packageName);
const workflowId = resourceId(value.workflowId, 'workflowId');
const runId = identifier(value.runId, 'runId');
if (!value.found) {
if (value.stepRuns.length !== 0 || value.truncated || value.next !== null) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'missing StepRun list result is invalid',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA,
found: false,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
stepRuns: Object.freeze([]),
truncated: false,
next: null,
});
}
const stepRuns = value.stepRuns.map(normalizeWorkflowStepRunListItem);
const identities = new Set<string>();
for (let index = 0; index < stepRuns.length; index += 1) {
const item = stepRuns[index]!;
if (identities.has(item.id) || identities.has(`step:${item.stepKey}`)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list identities are duplicated',
);
}
identities.add(item.id);
identities.add(`step:${item.stepKey}`);
const previous = stepRuns[index - 1];
if (
previous &&
(previous.stepKey > item.stepKey ||
(previous.stepKey === item.stepKey && previous.id >= item.id))
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list order is invalid',
);
}
}
let next: Readonly<PluginPackageWorkflowStepRunCursor> | null = null;
if (value.truncated) {
const last = stepRuns.at(-1);
if (
!last ||
!value.next ||
typeof value.next !== 'object' ||
Array.isArray(value.next) ||
!exactKeys(value.next, ['id', 'stepKey']) ||
value.next.id !== last.id ||
value.next.stepKey !== last.stepKey
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list continuation is invalid',
);
}
next = Object.freeze({ id: last.id, stepKey: last.stepKey });
} else if (value.next !== null) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'StepRun list continuation is unexpected',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_STEP_RUN_LIST_SCHEMA,
found: true,
projectId,
packageName: normalizedPackageName,
workflowId,
runId,
stepRuns: Object.freeze(stepRuns),
truncated: value.truncated,
next,
});
}
@@ -0,0 +1,86 @@
import type {
SecurityPolicyFence,
SecuritySubject,
} from '../../../security/security';
import { InvalidPluginPackageWorkflowAdministrationMutationError } from './errors';
export function exactKeys(value: object, expected: readonly string[]): boolean {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
return (
actual.length === canonical.length &&
actual.every((key, index) => key === canonical[index])
);
}
export function sameSubject(
left: Readonly<SecuritySubject>,
right: Readonly<SecuritySubject>,
): boolean {
return left.type === right.type && left.id === right.id;
}
export function normalizeFence(
value: SecurityPolicyFence,
): SecurityPolicyFence {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['bindingVersion', 'projectVersion']) ||
!Number.isSafeInteger(value.projectVersion) ||
value.projectVersion < 1 ||
!Number.isSafeInteger(value.bindingVersion) ||
(value.bindingVersion as number) < 1
) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'authorization fence is invalid',
);
}
return Object.freeze({
projectVersion: value.projectVersion,
bindingVersion: value.bindingVersion,
});
}
const IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PACKAGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const RESOURCE_ID = /^[a-z][a-z0-9-]{0,62}$/;
export function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER.test(value)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
`${label} is invalid`,
);
}
return value;
}
export function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME.test(value)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'packageName is invalid',
);
}
return value;
}
export function resourceId(value: unknown, label: string): string {
if (typeof value !== 'string' || !RESOURCE_ID.test(value)) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
`${label} is invalid`,
);
}
return value;
}
export function nullableTimestamp(value: unknown): number | null {
if (value === null) return null;
if (!Number.isSafeInteger(value) || (value as number) < 0) {
throw new InvalidPluginPackageWorkflowAdministrationMutationError(
'run inspection timestamp is invalid',
);
}
return value as number;
}
@@ -0,0 +1,7 @@
export * from './plugin-package-workflow-administration/contracts';
export * from './plugin-package-workflow-administration/errors';
export * from './plugin-package-workflow-administration/runInspection';
export * from './plugin-package-workflow-administration/runList';
export * from './plugin-package-workflow-administration/stepRunList';
export * from './plugin-package-workflow-administration/runEventList';
export * from './plugin-package-workflow-administration/mutation';
@@ -0,0 +1,547 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt,
type PluginPackageWorkflowTaskAttemptAdmissionReceipt,
} from './pluginPackageWorkflowTaskAttemptAdmission';
import {
RUN_DISPATCH_LEASE_STATUSES,
type RunDispatchLeaseStatus,
} from '../../run/runDispatchLease';
import type {
RunAttemptRecord,
RunCancellationReason,
RunEventRecord,
RunRecord,
} from '../../run/run';
import {
MAX_STEP_RUNS_PER_RUN,
STEP_RUN_TERMINAL_STATUSES,
normalizeStepRunRecord,
transitionStepRunMutation,
type StepRunMutation,
type StepRunRecord,
} from '../../run/stepRun';
export const PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_CONVERGENCE_SCHEMA =
'qinglong/plugin-package-workflow-cancellation-convergence@v1' as const;
export interface PluginPackageWorkflowCancellationActiveAttempt {
readonly admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
readonly attempt: Readonly<RunAttemptRecord>;
readonly leaseStatus: RunDispatchLeaseStatus | null;
}
export interface PluginPackageWorkflowCancellationSnapshot {
readonly run: Readonly<RunRecord>;
readonly stepRuns: readonly Readonly<StepRunRecord>[];
readonly activeTaskAttempts:
readonly Readonly<PluginPackageWorkflowCancellationActiveAttempt>[];
readonly observedAtMs: number;
}
export interface PluginPackageWorkflowCancellationAttemptTransition {
readonly previousStatus: 'claimed';
readonly attempt: Readonly<RunAttemptRecord>;
readonly event: Readonly<RunEventRecord>;
}
export interface PluginPackageWorkflowCancellationTerminalTransition {
readonly expectedRunVersion: number;
readonly expectedRunEventSequence: number;
readonly status: 'cancelled' | 'timed_out';
readonly finishedAtMs: number;
readonly errorCode: 'EXECUTION_CANCELLED' | 'EXECUTION_TIMED_OUT';
readonly errorSummary: string;
readonly event: Readonly<RunEventRecord>;
}
export interface PluginPackageWorkflowCancellationResolution {
readonly schema:
typeof PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_CONVERGENCE_SCHEMA;
readonly expectedRunVersion: number;
readonly expectedRunEventSequence: number;
readonly run: Readonly<RunRecord>;
readonly attemptTransitions:
readonly Readonly<PluginPackageWorkflowCancellationAttemptTransition>[];
readonly stepMutations: readonly Readonly<StepRunMutation>[];
readonly blockedAttemptIds: readonly string[];
readonly blockedStepRunIds: readonly string[];
readonly terminalTransition:
Readonly<PluginPackageWorkflowCancellationTerminalTransition> | null;
readonly observedAtMs: number;
}
export class InvalidPluginPackageWorkflowCancellationConvergenceError
extends TypeError
{
readonly code =
'PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_CONVERGENCE_INVALID';
constructor(message: string) {
super(
`Plugin Package Workflow cancellation convergence is invalid: ${message}`,
);
this.name =
'InvalidPluginPackageWorkflowCancellationConvergenceError';
}
}
const ACTIVE_ATTEMPT_STATUSES = new Set(['claimed', 'starting', 'running']);
const TERMINAL_STEP_STATUSES = new Set(STEP_RUN_TERMINAL_STATUSES);
const ID_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-cancellation-convergence-id@v1\0',
'utf8',
);
function invalid(message: string): never {
throw new InvalidPluginPackageWorkflowCancellationConvergenceError(message);
}
function counter(value: unknown, label: string): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 0 ||
(value as number) > 2_147_483_647
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function timestamp(value: unknown, label: string): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 0
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function identity(
runId: string,
cancelRequestedAtMs: number,
kind: 'attempt' | 'step' | 'run',
targetId: string,
epoch: number,
): string {
return createHash('sha256')
.update(ID_DOMAIN)
.update(runId, 'utf8')
.update('\0', 'utf8')
.update(String(cancelRequestedAtMs), 'utf8')
.update('\0', 'utf8')
.update(kind, 'utf8')
.update('\0', 'utf8')
.update(targetId, 'utf8')
.update('\0', 'utf8')
.update(String(epoch), 'utf8')
.digest('hex')
.slice(0, 32);
}
function terminalMapping(reason: RunCancellationReason): Readonly<{
status: 'cancelled' | 'timed_out';
errorCode: 'EXECUTION_CANCELLED' | 'EXECUTION_TIMED_OUT';
errorSummary: string;
}> {
return reason === 'timeout'
? Object.freeze({
status: 'timed_out' as const,
errorCode: 'EXECUTION_TIMED_OUT' as const,
errorSummary: 'Execution exceeded its configured timeout',
})
: Object.freeze({
status: 'cancelled' as const,
errorCode: 'EXECUTION_CANCELLED' as const,
errorSummary: 'Execution was cancelled',
});
}
function validateRun(run: Readonly<RunRecord>): Readonly<{
cancelRequestedAtMs: number;
cancelReason: RunCancellationReason;
}> {
if (
!run ||
typeof run !== 'object' ||
Array.isArray(run) ||
run.triggerType !== 'plugin_package_workflow' ||
run.executionOrigin !== 'system' ||
run.executionOwner !== 'runtime' ||
run.status !== 'running' ||
run.cancelRequestedAtMs === undefined ||
run.cancelReason === undefined
) {
invalid('Run is not a cancelling runtime-owned Workflow aggregate');
}
counter(run.version, 'Run version');
counter(run.eventSequence, 'Run event sequence');
const cancelRequestedAtMs = timestamp(
run.cancelRequestedAtMs,
'Run cancellation time',
);
return Object.freeze({
cancelRequestedAtMs,
cancelReason: run.cancelReason,
});
}
function validateActiveAttempt(
run: Readonly<RunRecord>,
value: Readonly<PluginPackageWorkflowCancellationActiveAttempt>,
stepsById: ReadonlyMap<string, Readonly<StepRunRecord>>,
): Readonly<{
admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
attempt: Readonly<RunAttemptRecord>;
leaseStatus: RunDispatchLeaseStatus | null;
stepRun: Readonly<StepRunRecord>;
}> {
let admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
try {
admission =
normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt(
value.admission,
);
} catch {
return invalid('active Attempt admission is invalid');
}
const { attempt } = value;
if (
!attempt ||
typeof attempt !== 'object' ||
Array.isArray(attempt) ||
!ACTIVE_ATTEMPT_STATUSES.has(attempt.status) ||
attempt.id !== admission.attemptId ||
attempt.runId !== run.id ||
attempt.runId !== admission.runId ||
attempt.stepRunId !== admission.stepRunId ||
attempt.attempt !== admission.attemptNumber ||
attempt.executorType !== admission.executorType ||
attempt.createdAtMs !== admission.admittedAtMs
) {
invalid('active Attempt does not match its immutable admission');
}
counter(attempt.callbackSequence, 'Attempt callback sequence');
if (
value.leaseStatus !== null &&
!RUN_DISPATCH_LEASE_STATUSES.includes(value.leaseStatus)
) {
invalid('active Attempt lease status is invalid');
}
const stepRun = stepsById.get(admission.stepRunId);
if (!stepRun || stepRun.kind !== 'task') {
invalid('active Attempt StepRun is missing');
}
if (
attempt.status === 'claimed' ||
attempt.status === 'starting'
) {
if (
stepRun.status !== 'ready' ||
stepRun.version !== admission.stepRunVersion ||
stepRun.stepRunDigest !== admission.stepRunDigest ||
attempt.startedAtMs !== undefined
) {
invalid('pre-start Attempt crossed its admitted StepRun epoch');
}
} else if (
stepRun.status !== 'running' ||
stepRun.version !== admission.stepRunVersion + 1 ||
stepRun.startedAtMs === null ||
attempt.startedAtMs === undefined
) {
invalid('running Attempt does not match the canonical StepRun');
}
return Object.freeze({
admission,
attempt,
leaseStatus: value.leaseStatus,
stepRun,
});
}
/**
* Converges one cancelling Workflow snapshot without inventing completion for
* active execution. Unleased pre-start claims and non-executing StepRuns are
* settled immediately; leased/starting/running Attempts remain blocked until
* worker completion or recovery crosses their own authority fences.
*/
export function resolvePluginPackageWorkflowCancellation(
snapshot: Readonly<PluginPackageWorkflowCancellationSnapshot>,
): Readonly<PluginPackageWorkflowCancellationResolution> {
if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) {
invalid('snapshot is invalid');
}
const { cancelRequestedAtMs, cancelReason } = validateRun(snapshot.run);
const observedAtMs = timestamp(snapshot.observedAtMs, 'observation time');
if (observedAtMs < cancelRequestedAtMs) {
invalid('observation precedes cancellation intent');
}
if (
!Array.isArray(snapshot.stepRuns) ||
snapshot.stepRuns.length < 1 ||
snapshot.stepRuns.length > MAX_STEP_RUNS_PER_RUN ||
!Array.isArray(snapshot.activeTaskAttempts)
) {
invalid('Workflow StepRun or active Attempt collection is invalid');
}
const steps = snapshot.stepRuns.map((value) => {
try {
return normalizeStepRunRecord(value);
} catch {
return invalid('StepRun is invalid');
}
}).sort((left, right) =>
left.stepKey.localeCompare(right.stepKey) || left.id.localeCompare(right.id));
const stepsById = new Map<string, Readonly<StepRunRecord>>();
for (const stepRun of steps) {
if (
stepRun.runId !== snapshot.run.id ||
stepsById.has(stepRun.id) ||
observedAtMs < stepRun.updatedAtMs
) {
invalid('StepRun set is incomplete, duplicated or time-inconsistent');
}
stepsById.set(stepRun.id, stepRun);
}
const active = snapshot.activeTaskAttempts
.map((value) =>
validateActiveAttempt(snapshot.run, value, stepsById))
.sort((left, right) => left.attempt.id.localeCompare(right.attempt.id));
const activeByStepId = new Map<
string,
(typeof active)[number]
>();
for (const value of active) {
if (
activeByStepId.has(value.stepRun.id) ||
observedAtMs < value.attempt.createdAtMs ||
observedAtMs < (value.attempt.startedAtMs ?? 0)
) {
invalid('active Attempt set is duplicated or time-inconsistent');
}
activeByStepId.set(value.stepRun.id, value);
}
const terminal = terminalMapping(cancelReason);
const attemptTransitions:
PluginPackageWorkflowCancellationAttemptTransition[] = [];
const stepMutations: StepRunMutation[] = [];
const blockedAttemptIds: string[] = [];
const blockedStepRunIds = new Set<string>();
let runVersion = snapshot.run.version;
let runEventSequence = snapshot.run.eventSequence;
for (const value of active) {
const isBlocked =
value.attempt.status !== 'claimed' ||
value.leaseStatus === 'leased';
if (isBlocked) {
blockedAttemptIds.push(value.attempt.id);
blockedStepRunIds.add(value.stepRun.id);
continue;
}
if (
runVersion >= 2_147_483_647 ||
runEventSequence >= 2_147_483_647
) {
invalid('Run aggregate counter overflowed');
}
const digest = identity(
snapshot.run.id,
cancelRequestedAtMs,
'attempt',
value.attempt.id,
value.attempt.callbackSequence,
);
runVersion += 1;
runEventSequence += 1;
const attempt = Object.freeze({
...value.attempt,
status: terminal.status,
finishedAtMs: observedAtMs,
errorCode: terminal.errorCode,
errorSummary: terminal.errorSummary,
});
const event = Object.freeze({
id: `wca:${digest}`,
runId: snapshot.run.id,
sequence: runEventSequence,
type: `workflow.task_attempt.${terminal.status}`,
dedupeKey: `wca:${digest}`,
actorType: 'reconciler' as const,
actorId: 'runtime:cancellation',
attemptId: attempt.id,
stepRunId: value.stepRun.id,
payload: Object.freeze({
execution_scope: 'workflow_task',
attempt_id: attempt.id,
step_run_id: value.stepRun.id,
from_status: 'claimed',
to_status: terminal.status,
cancel_reason: cancelReason,
cancel_requested_at_ms: cancelRequestedAtMs,
error_code: terminal.errorCode,
version: runVersion,
}),
createdAtMs: observedAtMs,
} satisfies RunEventRecord);
attemptTransitions.push(Object.freeze({
previousStatus: 'claimed' as const,
attempt,
event,
}));
}
let projectedSteps = new Map(stepsById);
for (const current of steps) {
if (
TERMINAL_STEP_STATUSES.has(
current.status as (typeof STEP_RUN_TERMINAL_STATUSES)[number],
) ||
blockedStepRunIds.has(current.id)
) {
continue;
}
if (current.status === 'running') {
blockedStepRunIds.add(current.id);
continue;
}
const target =
cancelReason === 'timeout' &&
(current.status === 'ready' ||
current.status === 'waiting_approval')
? 'timed_out'
: 'cancelled';
if (
runVersion >= 2_147_483_647 ||
runEventSequence >= 2_147_483_647
) {
invalid('Run aggregate counter overflowed');
}
const digest = identity(
snapshot.run.id,
cancelRequestedAtMs,
'step',
current.id,
current.version,
);
const mutation = transitionStepRunMutation(
current,
{
expectedVersion: current.version,
expectedDigest: current.stepRunDigest,
mutationId: `wcm:${digest}`,
to: target,
atMs: observedAtMs,
resultCode:
target === 'timed_out'
? 'workflow_timed_out'
: 'workflow_cancelled',
...(target === 'timed_out'
? { errorSummary: terminal.errorSummary }
: {}),
},
{
expectedRunVersion: runVersion,
expectedRunEventSequence: runEventSequence,
eventId: `wcs:${digest}`,
dedupeKey: `wcs:${digest}`,
actor: {
type: 'reconciler',
id: 'runtime:cancellation',
},
},
);
stepMutations.push(mutation);
projectedSteps.set(current.id, mutation.stepRun);
runVersion += 1;
runEventSequence += 1;
}
const blockedSteps = [...blockedStepRunIds].sort();
const canTerminalize =
blockedSteps.length === 0 &&
[...projectedSteps.values()].every((stepRun) =>
TERMINAL_STEP_STATUSES.has(
stepRun.status as (typeof STEP_RUN_TERMINAL_STATUSES)[number],
));
let terminalTransition:
PluginPackageWorkflowCancellationTerminalTransition | null = null;
if (canTerminalize) {
if (
runVersion >= 2_147_483_647 ||
runEventSequence >= 2_147_483_647
) {
invalid('Run aggregate counter overflowed');
}
const digest = identity(
snapshot.run.id,
cancelRequestedAtMs,
'run',
snapshot.run.id,
runVersion,
);
terminalTransition = Object.freeze({
expectedRunVersion: runVersion,
expectedRunEventSequence: runEventSequence,
status: terminal.status,
finishedAtMs: observedAtMs,
errorCode: terminal.errorCode,
errorSummary: terminal.errorSummary,
event: Object.freeze({
id: `wcr:${digest}`,
runId: snapshot.run.id,
sequence: runEventSequence + 1,
type: `workflow.${terminal.status}`,
dedupeKey: `wcr:${digest}`,
actorType: 'reconciler',
actorId: 'runtime:cancellation',
payload: Object.freeze({
from_status: 'running',
to_status: terminal.status,
step_count: steps.length,
cancel_reason: cancelReason,
cancel_requested_at_ms: cancelRequestedAtMs,
error_code: terminal.errorCode,
version: runVersion + 1,
}),
createdAtMs: observedAtMs,
}),
});
runVersion += 1;
runEventSequence += 1;
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_CANCELLATION_CONVERGENCE_SCHEMA,
expectedRunVersion: snapshot.run.version,
expectedRunEventSequence: snapshot.run.eventSequence,
run: Object.freeze({
...snapshot.run,
version: runVersion,
eventSequence: runEventSequence,
...(terminalTransition === null
? {}
: {
status: terminalTransition.status,
finishedAtMs: terminalTransition.finishedAtMs,
errorCode: terminalTransition.errorCode,
errorSummary: terminalTransition.errorSummary,
}),
}),
attemptTransitions: Object.freeze(attemptTransitions),
stepMutations: Object.freeze(stepMutations),
blockedAttemptIds: Object.freeze(blockedAttemptIds),
blockedStepRunIds: Object.freeze(blockedSteps),
terminalTransition,
observedAtMs,
});
}
@@ -0,0 +1,963 @@
import { createHash } from 'node:crypto';
import {
MAX_PLUGIN_PACKAGE_AUTOMATION_WORKFLOWS,
normalizePluginPackageAutomationPublication,
type PluginPackageAutomationPublication,
type PluginPackageAutomationPublicationTarget,
} from '../pluginPackageAutomationPublication';
import {
MAX_PLUGIN_PACKAGE_WORKFLOW_STEPS,
normalizePluginPackageMaterializedRevision,
normalizePluginPackageWorkflowResource,
type PluginPackageMaterializedRevision,
type PluginPackageTaskResource,
type PluginPackageWorkflowResource,
} from '../pluginPackageResourceMaterialization';
import type { RunEventRecord, RunRecord } from '../../run/run';
import {
createStepRunMutation,
normalizeStepRunMutation,
type StepRunMutation,
} from '../../run/stepRun';
import { TaskSpecSemanticRegistry } from '../../task-definition/taskSpecSemantic';
export const PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_SCHEMA =
'qinglong/plugin-package-workflow-execution-plan@v1' as const;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_BYTES = 256 * 1024;
export const PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_SCHEMA =
'qinglong/plugin-package-workflow-admission-receipt@v1' as const;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_BYTES = 256 * 1024;
export interface PluginPackageWorkflowExecutionPlanTarget
extends PluginPackageAutomationPublicationTarget {
readonly publicationDigest: string;
readonly workflowId: string;
readonly workflowDefinitionDigest: string;
}
export interface PluginPackageWorkflowExecutionPlanStep {
readonly stepRunId: string;
readonly stepKey: string;
readonly taskId: string;
readonly taskDefinitionRef: string;
readonly taskDefinitionDigest: string;
readonly needs: readonly string[];
readonly initialStatus: 'pending' | 'ready';
readonly required: true;
}
export interface PluginPackageWorkflowExecutionPlan {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_SCHEMA;
readonly planId: string;
readonly runId: string;
readonly target: Readonly<PluginPackageWorkflowExecutionPlanTarget>;
readonly steps: readonly Readonly<PluginPackageWorkflowExecutionPlanStep>[];
readonly plannedAtMs: number;
readonly planDigest: string;
}
export interface CreatePluginPackageWorkflowExecutionPlanInput {
readonly planId: string;
readonly runId: string;
readonly workflowId: string;
readonly stepRunIds: Readonly<Record<string, string>>;
readonly publication: Readonly<PluginPackageAutomationPublication>;
readonly revision: Readonly<PluginPackageMaterializedRevision>;
readonly taskSpecSemanticRegistry: TaskSpecSemanticRegistry;
readonly plannedAtMs: number;
}
export interface PluginPackageWorkflowAdmissionReceiptStep {
readonly stepKey: string;
readonly stepRunId: string;
readonly stepRunDigest: string;
readonly mutationId: string;
readonly eventId: string;
}
export interface PluginPackageWorkflowAdmissionReceipt {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_SCHEMA;
readonly planId: string;
readonly planDigest: string;
readonly runId: string;
readonly publicationDigest: string;
readonly workflowId: string;
readonly steps: readonly Readonly<PluginPackageWorkflowAdmissionReceiptStep>[];
readonly finalRunVersion: number;
readonly finalRunEventSequence: number;
readonly admittedAtMs: number;
readonly receiptDigest: string;
}
export interface PluginPackageWorkflowAdmissionBundle {
readonly plan: Readonly<PluginPackageWorkflowExecutionPlan>;
readonly run: Readonly<RunRecord>;
readonly admissionEvent: Readonly<RunEventRecord>;
readonly stepMutations: readonly Readonly<StepRunMutation>[];
readonly receipt: Readonly<PluginPackageWorkflowAdmissionReceipt>;
}
export interface PluginPackageWorkflowAdmissionRepository {
findByPlanId(
planId: string,
): Promise<Readonly<PluginPackageWorkflowAdmissionReceipt> | null>;
findByRunId(
runId: string,
): Promise<Readonly<PluginPackageWorkflowAdmissionReceipt> | null>;
admit(plan: Readonly<PluginPackageWorkflowExecutionPlan>): Promise<
Readonly<{
status: 'created' | 'existing';
receipt: Readonly<PluginPackageWorkflowAdmissionReceipt>;
}>
>;
}
export class InvalidPluginPackageWorkflowExecutionPlanError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_INVALID';
constructor(message: string) {
super(`Plugin Package Workflow execution plan is invalid: ${message}`);
this.name = 'InvalidPluginPackageWorkflowExecutionPlanError';
}
}
export class PluginPackageWorkflowExecutionPlanConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_CONFLICT';
constructor(message: string) {
super(`Plugin Package Workflow cannot be planned: ${message}`);
this.name = 'PluginPackageWorkflowExecutionPlanConflictError';
}
}
export class InvalidPluginPackageWorkflowAdmissionReceiptError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_INVALID';
constructor(message: string) {
super(`Plugin Package Workflow admission receipt is invalid: ${message}`);
this.name = 'InvalidPluginPackageWorkflowAdmissionReceiptError';
}
}
export class PluginPackageWorkflowAdmissionConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMISSION_CONFLICT';
constructor(message: string) {
super(`Plugin Package Workflow admission conflicts with state: ${message}`);
this.name = 'PluginPackageWorkflowAdmissionConflictError';
}
}
export class PluginPackageWorkflowAdmissionNotAllowedError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMISSION_NOT_ALLOWED';
constructor() {
super('Plugin Package Workflow admission is not allowed');
this.name = 'PluginPackageWorkflowAdmissionNotAllowedError';
}
}
export class PluginPackageWorkflowAdmissionUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_ADMISSION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package Workflow admission is unavailable', options);
this.name = 'PluginPackageWorkflowAdmissionUnavailableError';
}
}
const IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PORTABLE_RUN_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,35}$/;
const PACKAGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const RESOURCE_ID = /^[a-z][a-z0-9-]{0,62}$/;
const DIGEST = /^[0-9a-f]{64}$/;
const PLAN_DIGEST_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-execution-plan-digest@v1\0',
'utf8',
);
const WORKFLOW_DEFINITION_DIGEST_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-definition-digest@v1\0',
'utf8',
);
const WORKFLOW_ADMISSION_RECEIPT_DIGEST_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-admission-receipt-digest@v1\0',
'utf8',
);
function invalid(message: string): never {
throw new InvalidPluginPackageWorkflowExecutionPlanError(message);
}
function portableRunId(value: unknown, label: string): string {
if (typeof value !== 'string' || !PORTABLE_RUN_ID.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function conflict(message: string): never {
throw new PluginPackageWorkflowExecutionPlanConflictError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
(Object.getPrototypeOf(value) !== Object.prototype &&
Object.getPrototypeOf(value) !== null)
) {
return invalid(`${label} must be an object`);
}
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
Object.values(descriptors).some(
(descriptor) =>
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true,
)
) {
return invalid(`${label} must contain enumerable data properties`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
expected: readonly string[],
label: string,
): void {
const actual = Reflect.ownKeys(value);
const canonical = [...expected].sort();
if (
actual.length !== canonical.length ||
actual.some((key) => typeof key !== 'string') ||
actual
.map(String)
.sort()
.some((key, index) => key !== canonical[index])
) {
invalid(`${label} shape is invalid`);
}
}
function denseArray(
value: unknown,
maximum: number,
label: string,
minimum = 1,
): readonly unknown[] {
if (
!Array.isArray(value) ||
value.length < minimum ||
value.length > maximum
) {
return invalid(`${label} is invalid`);
}
const keys = Object.keys(value);
const ownKeys = Reflect.ownKeys(value);
const descriptors = Object.getOwnPropertyDescriptors(value);
if (
ownKeys.length !== value.length + 1 ||
!ownKeys.includes('length') ||
keys.length !== value.length ||
keys.some((key, index) => key !== String(index)) ||
keys.some((key) => {
const descriptor = descriptors[key];
return (
descriptor === undefined ||
descriptor.get !== undefined ||
descriptor.set !== undefined ||
descriptor.enumerable !== true
);
})
) {
return invalid(`${label} must be a dense data array`);
}
return value;
}
function identifier(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTIFIER.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function resourceId(value: unknown, label: string): string {
if (typeof value !== 'string' || !RESOURCE_ID.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function packageName(value: unknown): string {
if (typeof value !== 'string' || !PACKAGE_NAME.test(value)) {
return invalid('packageName is invalid');
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function positiveInteger(value: unknown, label: string): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < 1 ||
(value as number) > 2_147_483_647
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function timestamp(value: unknown): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid('plannedAtMs is invalid');
}
return value as number;
}
function hash(domain: Buffer, value: unknown): string {
return createHash('sha256')
.update(domain)
.update(JSON.stringify(value))
.digest('hex');
}
export function pluginPackageWorkflowDefinitionDigest(
value: PluginPackageWorkflowResource,
): string {
return hash(
WORKFLOW_DEFINITION_DIGEST_DOMAIN,
normalizePluginPackageWorkflowResource(value),
);
}
function target(
value: PluginPackageWorkflowExecutionPlanTarget,
): Readonly<PluginPackageWorkflowExecutionPlanTarget> {
const record = dataRecord(value, 'plan target');
exactKeys(
record,
[
'generation',
'generationDigest',
'installationId',
'lockDigest',
'materializedRevisionDigest',
'packageName',
'projectId',
'publicationDigest',
'workflowDefinitionDigest',
'workflowId',
],
'plan target',
);
return Object.freeze({
projectId: identifier(value.projectId, 'projectId'),
packageName: packageName(value.packageName),
installationId: identifier(value.installationId, 'installationId'),
lockDigest: digest(value.lockDigest, 'lockDigest'),
generation: positiveInteger(value.generation, 'generation'),
generationDigest: digest(value.generationDigest, 'generationDigest'),
materializedRevisionDigest: digest(
value.materializedRevisionDigest,
'materializedRevisionDigest',
),
publicationDigest: digest(value.publicationDigest, 'publicationDigest'),
workflowId: resourceId(value.workflowId, 'workflowId'),
workflowDefinitionDigest: digest(
value.workflowDefinitionDigest,
'workflowDefinitionDigest',
),
});
}
function taskDefinitionRef(
materializedRevisionDigest: string,
taskId: string,
): string {
return `plugin-package:${materializedRevisionDigest}:task:${taskId}`;
}
function normalizeStep(
value: PluginPackageWorkflowExecutionPlanStep,
planTarget: Readonly<PluginPackageWorkflowExecutionPlanTarget>,
): Readonly<PluginPackageWorkflowExecutionPlanStep> {
const step = dataRecord(value, 'plan step');
exactKeys(
step,
[
'initialStatus',
'needs',
'required',
'stepKey',
'stepRunId',
'taskDefinitionDigest',
'taskDefinitionRef',
'taskId',
],
'plan step',
);
if (
(value.initialStatus !== 'pending' && value.initialStatus !== 'ready') ||
value.required !== true
) {
return invalid('plan step status or required flag is invalid');
}
const stepKey = resourceId(value.stepKey, 'stepKey');
const taskId = resourceId(value.taskId, 'taskId');
const needs = denseArray(
value.needs,
MAX_PLUGIN_PACKAGE_WORKFLOW_STEPS,
'step needs',
0,
);
const normalizedNeeds = Object.freeze(
needs.map((need) => resourceId(need, 'step dependency')),
);
if (
new Set(normalizedNeeds).size !== normalizedNeeds.length ||
normalizedNeeds.includes(stepKey) ||
[...normalizedNeeds]
.sort()
.some((need, index) => need !== normalizedNeeds[index]) ||
(normalizedNeeds.length === 0) !== (value.initialStatus === 'ready')
) {
return invalid('step dependency or initial status is invalid');
}
const expectedReference = taskDefinitionRef(
planTarget.materializedRevisionDigest,
taskId,
);
if (value.taskDefinitionRef !== expectedReference) {
return invalid('taskDefinitionRef is not generation-bound');
}
return Object.freeze({
stepRunId: identifier(value.stepRunId, 'stepRunId'),
stepKey,
taskId,
taskDefinitionRef: expectedReference,
taskDefinitionDigest: digest(
value.taskDefinitionDigest,
'taskDefinitionDigest',
),
needs: normalizedNeeds,
initialStatus: value.initialStatus,
required: true,
});
}
export function pluginPackageWorkflowExecutionPlanDigest(
value:
| Omit<PluginPackageWorkflowExecutionPlan, 'planDigest'>
| PluginPackageWorkflowExecutionPlan,
): string {
return hash(PLAN_DIGEST_DOMAIN, {
schema: value.schema,
planId: value.planId,
runId: value.runId,
target: value.target,
steps: value.steps,
plannedAtMs: value.plannedAtMs,
});
}
function bounded(
value: Readonly<PluginPackageWorkflowExecutionPlan>,
): Readonly<PluginPackageWorkflowExecutionPlan> {
if (
Buffer.byteLength(JSON.stringify(value), 'utf8') >
MAX_PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_BYTES
) {
return invalid('encoded plan exceeds its size limit');
}
return value;
}
function assertDag(
steps: readonly Readonly<PluginPackageWorkflowExecutionPlanStep>[],
): void {
const byKey = new Map(steps.map((step) => [step.stepKey, step]));
if (
byKey.size !== steps.length ||
new Set(steps.map(({ stepRunId }) => stepRunId)).size !== steps.length ||
steps.some(({ needs }) => needs.some((need) => !byKey.has(need)))
) {
invalid('plan step identity or dependency is invalid');
}
const pending = new Map(
steps.map((step) => [step.stepKey, new Set(step.needs)]),
);
const ready = [...pending.entries()]
.filter(([, needs]) => needs.size === 0)
.map(([stepKey]) => stepKey);
let visited = 0;
while (ready.length > 0) {
const current = ready.pop()!;
if (!pending.delete(current)) continue;
visited += 1;
for (const [stepKey, needs] of pending) {
if (needs.delete(current) && needs.size === 0) ready.push(stepKey);
}
}
if (visited !== steps.length) invalid('plan graph contains a cycle');
}
export function normalizePluginPackageWorkflowExecutionPlan(
value: PluginPackageWorkflowExecutionPlan,
): Readonly<PluginPackageWorkflowExecutionPlan> {
const plan = dataRecord(value, 'plan');
exactKeys(
plan,
[
'planDigest',
'planId',
'plannedAtMs',
'runId',
'schema',
'steps',
'target',
],
'plan',
);
if (value.schema !== PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_SCHEMA) {
return invalid('plan schema is invalid');
}
const normalizedTarget = target(value.target);
const steps = denseArray(
value.steps,
MAX_PLUGIN_PACKAGE_WORKFLOW_STEPS,
'plan steps',
)
.map((step) =>
normalizeStep(
step as PluginPackageWorkflowExecutionPlanStep,
normalizedTarget,
),
)
.sort((left, right) => left.stepKey.localeCompare(right.stepKey));
if (
steps.some(
(step, index) => index > 0 && steps[index - 1]!.stepKey === step.stepKey,
)
) {
return invalid('plan step identity is duplicated');
}
assertDag(steps);
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_SCHEMA,
planId: identifier(value.planId, 'planId'),
runId: portableRunId(value.runId, 'runId'),
target: normalizedTarget,
steps: Object.freeze(steps),
plannedAtMs: timestamp(value.plannedAtMs),
});
const planDigest = digest(value.planDigest, 'planDigest');
if (pluginPackageWorkflowExecutionPlanDigest(unsigned) !== planDigest) {
return invalid('planDigest does not match plan');
}
return bounded(Object.freeze({ ...unsigned, planDigest }));
}
function assertPublicationRevisionBinding(
publication: Readonly<PluginPackageAutomationPublication>,
revision: Readonly<PluginPackageMaterializedRevision>,
): void {
const generation = revision.generation;
if (
publication.state !== 'active' ||
publication.target.projectId !== generation.projectId ||
publication.target.packageName !== generation.packageName ||
publication.target.installationId !== generation.installationId ||
publication.target.lockDigest !== generation.lockDigest ||
publication.target.generation !== generation.generation ||
publication.target.generationDigest !== generation.generationDigest ||
publication.target.materializedRevisionDigest !== revision.revisionDigest
) {
conflict('publication is not the active definition of this revision');
}
}
export function createPluginPackageWorkflowExecutionPlan(
value: CreatePluginPackageWorkflowExecutionPlanInput,
): Readonly<PluginPackageWorkflowExecutionPlan> {
const input = dataRecord(value, 'create input');
exactKeys(
input,
[
'planId',
'plannedAtMs',
'publication',
'revision',
'runId',
'stepRunIds',
'taskSpecSemanticRegistry',
'workflowId',
],
'create input',
);
if (!(value.taskSpecSemanticRegistry instanceof TaskSpecSemanticRegistry)) {
return invalid('TaskSpec semantic registry is invalid');
}
const publication = normalizePluginPackageAutomationPublication(
value.publication,
);
const revision = normalizePluginPackageMaterializedRevision(
value.revision,
value.taskSpecSemanticRegistry,
);
assertPublicationRevisionBinding(publication, revision);
const workflowId = resourceId(value.workflowId, 'workflowId');
const publicationWorkflow = publication.definitions.workflows.find(
(workflow) => workflow.id === workflowId,
);
const revisionWorkflowResource = revision.resources.find(
(resource) =>
resource.kind === 'workflow' &&
(resource.value as PluginPackageWorkflowResource).id === workflowId,
);
if (!publicationWorkflow || !revisionWorkflowResource) {
return conflict('Workflow is not present in the exact publication');
}
const revisionWorkflow = normalizePluginPackageWorkflowResource(
revisionWorkflowResource.value,
);
const workflowDefinitionDigest =
pluginPackageWorkflowDefinitionDigest(publicationWorkflow);
if (
workflowDefinitionDigest !==
pluginPackageWorkflowDefinitionDigest(revisionWorkflow) ||
!publicationWorkflow.enabled
) {
return conflict('Workflow definition drifted or is disabled');
}
if (
publication.definitions.workflows.length >
MAX_PLUGIN_PACKAGE_AUTOMATION_WORKFLOWS
) {
return invalid('publication Workflow count exceeds the limit');
}
const tasks = new Map(
revision.resources
.filter(({ kind }) => kind === 'task')
.map((resource) => [
(resource.value as PluginPackageTaskResource).id,
resource,
]),
);
const stepRunIds = dataRecord(value.stepRunIds, 'stepRunIds');
exactKeys(
stepRunIds,
publicationWorkflow.steps.map(({ id }) => id),
'stepRunIds',
);
if (publicationWorkflow.steps.length < 1) {
return conflict('Workflow has no executable steps');
}
const planTarget = target({
...publication.target,
publicationDigest: publication.publicationDigest,
workflowId,
workflowDefinitionDigest,
});
const steps = publicationWorkflow.steps.map((step) => {
const taskResource = tasks.get(step.task);
if (!taskResource) {
return conflict('Workflow Task is absent from the exact revision');
}
const task = taskResource.value as PluginPackageTaskResource;
if (!task.enabled) {
return conflict('Workflow Task is disabled');
}
return normalizeStep(
{
stepRunId: stepRunIds[step.id] as string,
stepKey: step.id,
taskId: step.task,
taskDefinitionRef: taskDefinitionRef(
revision.revisionDigest,
step.task,
),
taskDefinitionDigest: taskResource.sourceDigest,
needs: step.needs,
initialStatus: step.needs.length === 0 ? 'ready' : 'pending',
required: true,
},
planTarget,
);
});
assertDag(steps);
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_EXECUTION_PLAN_SCHEMA,
planId: identifier(value.planId, 'planId'),
runId: portableRunId(value.runId, 'runId'),
target: planTarget,
steps: Object.freeze(
[...steps].sort((left, right) =>
left.stepKey.localeCompare(right.stepKey),
),
),
plannedAtMs: timestamp(value.plannedAtMs),
});
const result = Object.freeze({
...unsigned,
planDigest: pluginPackageWorkflowExecutionPlanDigest(unsigned),
});
return normalizePluginPackageWorkflowExecutionPlan(result);
}
function admissionIdentity(
prefix: 'wfa' | 'wfe' | 'wfm',
planDigest: string,
index?: number,
): string {
if (index === undefined) return `${prefix}:${planDigest.slice(0, 32)}`;
const digestLength = prefix === 'wfe' ? 27 : 56;
return `${prefix}:${planDigest.slice(0, digestLength)}:${index}`;
}
function receiptStep(
value: PluginPackageWorkflowAdmissionReceiptStep,
): Readonly<PluginPackageWorkflowAdmissionReceiptStep> {
const step = dataRecord(value, 'receipt step');
exactKeys(
step,
['eventId', 'mutationId', 'stepKey', 'stepRunDigest', 'stepRunId'],
'receipt step',
);
return Object.freeze({
stepKey: resourceId(value.stepKey, 'receipt stepKey'),
stepRunId: identifier(value.stepRunId, 'receipt stepRunId'),
stepRunDigest: digest(value.stepRunDigest, 'receipt stepRunDigest'),
mutationId: identifier(value.mutationId, 'receipt mutationId'),
eventId: identifier(value.eventId, 'receipt eventId'),
});
}
function workflowAdmissionReceiptFields(
value:
| Omit<PluginPackageWorkflowAdmissionReceipt, 'receiptDigest'>
| PluginPackageWorkflowAdmissionReceipt,
): Omit<PluginPackageWorkflowAdmissionReceipt, 'receiptDigest'> {
return {
schema: value.schema,
planId: value.planId,
planDigest: value.planDigest,
runId: value.runId,
publicationDigest: value.publicationDigest,
workflowId: value.workflowId,
steps: value.steps,
finalRunVersion: value.finalRunVersion,
finalRunEventSequence: value.finalRunEventSequence,
admittedAtMs: value.admittedAtMs,
};
}
export function pluginPackageWorkflowAdmissionReceiptDigest(
value:
| Omit<PluginPackageWorkflowAdmissionReceipt, 'receiptDigest'>
| PluginPackageWorkflowAdmissionReceipt,
): string {
return hash(
WORKFLOW_ADMISSION_RECEIPT_DIGEST_DOMAIN,
workflowAdmissionReceiptFields(value),
);
}
export function normalizePluginPackageWorkflowAdmissionReceipt(
value: PluginPackageWorkflowAdmissionReceipt,
): Readonly<PluginPackageWorkflowAdmissionReceipt> {
const receipt = dataRecord(value, 'admission receipt');
exactKeys(
receipt,
[
'admittedAtMs',
'finalRunEventSequence',
'finalRunVersion',
'planDigest',
'planId',
'publicationDigest',
'receiptDigest',
'runId',
'schema',
'steps',
'workflowId',
],
'admission receipt',
);
if (value.schema !== PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_SCHEMA) {
throw new InvalidPluginPackageWorkflowAdmissionReceiptError(
'schema is invalid',
);
}
const steps = denseArray(
value.steps,
MAX_PLUGIN_PACKAGE_WORKFLOW_STEPS,
'receipt steps',
)
.map((step) =>
receiptStep(step as PluginPackageWorkflowAdmissionReceiptStep),
)
.sort((left, right) => left.stepKey.localeCompare(right.stepKey));
if (
new Set(steps.map(({ stepKey }) => stepKey)).size !== steps.length ||
new Set(steps.map(({ stepRunId }) => stepRunId)).size !== steps.length ||
new Set(steps.map(({ mutationId }) => mutationId)).size !== steps.length ||
new Set(steps.map(({ eventId }) => eventId)).size !== steps.length
) {
throw new InvalidPluginPackageWorkflowAdmissionReceiptError(
'step identity is duplicated',
);
}
const finalCounter = steps.length + 1;
if (
value.finalRunVersion !== finalCounter ||
value.finalRunEventSequence !== finalCounter
) {
throw new InvalidPluginPackageWorkflowAdmissionReceiptError(
'final Run counters are invalid',
);
}
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_SCHEMA,
planId: identifier(value.planId, 'receipt planId'),
planDigest: digest(value.planDigest, 'receipt planDigest'),
runId: portableRunId(value.runId, 'receipt runId'),
publicationDigest: digest(
value.publicationDigest,
'receipt publicationDigest',
),
workflowId: resourceId(value.workflowId, 'receipt workflowId'),
steps: Object.freeze(steps),
finalRunVersion: finalCounter,
finalRunEventSequence: finalCounter,
admittedAtMs: timestamp(value.admittedAtMs),
});
const receiptDigest = digest(value.receiptDigest, 'receiptDigest');
if (pluginPackageWorkflowAdmissionReceiptDigest(unsigned) !== receiptDigest) {
throw new InvalidPluginPackageWorkflowAdmissionReceiptError(
'receiptDigest does not match receipt',
);
}
const normalized = Object.freeze({ ...unsigned, receiptDigest });
if (
Buffer.byteLength(JSON.stringify(normalized), 'utf8') >
MAX_PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_BYTES
) {
throw new InvalidPluginPackageWorkflowAdmissionReceiptError(
'encoded receipt exceeds its size limit',
);
}
return normalized;
}
export function createPluginPackageWorkflowAdmissionBundle(
planValue: PluginPackageWorkflowExecutionPlan,
): Readonly<PluginPackageWorkflowAdmissionBundle> {
const plan = normalizePluginPackageWorkflowExecutionPlan(planValue);
const admissionEvent = Object.freeze({
id: admissionIdentity('wfa', plan.planDigest),
runId: plan.runId,
sequence: 1,
type: 'workflow.admitted',
dedupeKey: admissionIdentity('wfa', plan.planDigest),
actorType: 'system' as const,
payload: Object.freeze({
planId: plan.planId,
planDigest: plan.planDigest,
publicationDigest: plan.target.publicationDigest,
workflowId: plan.target.workflowId,
workflowDefinitionDigest: plan.target.workflowDefinitionDigest,
stepCount: plan.steps.length,
}),
createdAtMs: plan.plannedAtMs,
} satisfies RunEventRecord);
const stepMutations = plan.steps.map((step, index) =>
normalizeStepRunMutation(
createStepRunMutation(
{
id: step.stepRunId,
runId: plan.runId,
stepKey: step.stepKey,
kind: 'task',
definitionRef: step.taskDefinitionRef,
definitionDigest: step.taskDefinitionDigest,
required: true,
initialStatus: step.initialStatus,
mutationId: admissionIdentity('wfm', plan.planDigest, index + 1),
createdAtMs: plan.plannedAtMs,
},
{
expectedRunVersion: index + 1,
expectedRunEventSequence: index + 1,
eventId: admissionIdentity('wfe', plan.planDigest, index + 1),
dedupeKey: admissionIdentity('wfe', plan.planDigest, index + 1),
actor: { type: 'system' },
},
),
),
);
const finalCounter = stepMutations.length + 1;
const run = Object.freeze({
id: plan.runId,
projectId: plan.target.projectId,
taskId: plan.target.workflowId,
taskRevision: plan.target.publicationDigest,
taskSnapshotRef:
`plugin-package:${plan.target.publicationDigest}:workflow:` +
plan.target.workflowId,
triggerType: 'plugin_package_workflow',
executionOrigin: 'system' as const,
executionOwner: 'runtime' as const,
requestId: plan.planId,
status: 'running' as const,
version: finalCounter,
eventSequence: finalCounter,
priority: 0,
idempotencyKey: `plugin-package-workflow:${plan.planId}`,
createdAtMs: plan.plannedAtMs,
startedAtMs: plan.plannedAtMs,
} satisfies RunRecord);
const receiptUnsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_ADMISSION_RECEIPT_SCHEMA,
planId: plan.planId,
planDigest: plan.planDigest,
runId: plan.runId,
publicationDigest: plan.target.publicationDigest,
workflowId: plan.target.workflowId,
steps: Object.freeze(
stepMutations.map((mutation) =>
Object.freeze({
stepKey: mutation.stepRun.stepKey,
stepRunId: mutation.stepRun.id,
stepRunDigest: mutation.stepRun.stepRunDigest,
mutationId: mutation.mutationId,
eventId: mutation.event.id,
}),
),
),
finalRunVersion: finalCounter,
finalRunEventSequence: finalCounter,
admittedAtMs: plan.plannedAtMs,
});
const receipt = normalizePluginPackageWorkflowAdmissionReceipt({
...receiptUnsigned,
receiptDigest: pluginPackageWorkflowAdmissionReceiptDigest(receiptUnsigned),
});
return Object.freeze({
plan,
run,
admissionEvent,
stepMutations: Object.freeze(stepMutations),
receipt,
});
}
@@ -0,0 +1,430 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageWorkflowExecutionPlan,
type PluginPackageWorkflowExecutionPlan,
} from './pluginPackageWorkflowExecutionPlan';
import type { RunEventRecord, RunRecord, RunStatus } from '../../run/run';
import {
STEP_RUN_TERMINAL_STATUSES,
normalizeStepRunRecord,
transitionStepRunMutation,
type StepRunMutation,
type StepRunRecord,
type StepRunStatus,
} from '../../run/stepRun';
export const PLUGIN_PACKAGE_WORKFLOW_FRONTIER_SCHEMA =
'qinglong/plugin-package-workflow-frontier@v1' as const;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_FRONTIER_PAGE_SIZE = 64;
export type PluginPackageWorkflowTerminalStatus = Extract<
RunStatus,
'succeeded' | 'failed' | 'cancelled' | 'timed_out'
>;
export interface PluginPackageWorkflowFrontierSnapshot {
readonly plan: Readonly<PluginPackageWorkflowExecutionPlan>;
readonly run: Readonly<RunRecord>;
readonly stepRuns: readonly Readonly<StepRunRecord>[];
readonly observedAtMs: number;
}
export interface PluginPackageWorkflowFrontierResolution {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_FRONTIER_SCHEMA;
readonly runId: string;
readonly planDigest: string;
readonly expectedRunVersion: number;
readonly expectedRunEventSequence: number;
readonly stepMutations: readonly Readonly<StepRunMutation>[];
readonly readyStepRunIds: readonly string[];
readonly terminalStatus: PluginPackageWorkflowTerminalStatus | null;
readonly terminalTransition: Readonly<PluginPackageWorkflowTerminalTransition> | null;
readonly observedAtMs: number;
}
export interface PluginPackageWorkflowTerminalTransition {
readonly expectedRunVersion: number;
readonly expectedRunEventSequence: number;
readonly status: PluginPackageWorkflowTerminalStatus;
readonly finishedAtMs: number;
readonly errorCode: string | null;
readonly event: Readonly<RunEventRecord>;
}
export interface PluginPackageWorkflowFrontierCursor {
readonly admittedAtMs: number;
readonly planDigest: string;
}
export interface PluginPackageWorkflowFrontierCandidate
extends PluginPackageWorkflowFrontierCursor {
readonly runId: string;
}
export interface PluginPackageWorkflowFrontierPage {
readonly candidates: readonly Readonly<PluginPackageWorkflowFrontierCandidate>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageWorkflowFrontierCursor>;
}
export interface PluginPackageWorkflowFrontierAdvanceResult {
readonly status: 'advanced' | 'unchanged' | 'terminal' | 'settled';
readonly runId: string;
readonly planDigest: string;
readonly stepMutationCount: number;
readonly readyStepRunIds: readonly string[];
readonly terminalStatus: PluginPackageWorkflowTerminalStatus | null;
readonly runVersion: number;
readonly runEventSequence: number;
readonly observedAtMs: number;
}
export interface PluginPackageWorkflowFrontierRepository {
listCandidates(query: Readonly<{
limit: number;
after?: Readonly<PluginPackageWorkflowFrontierCursor>;
}>): Promise<Readonly<PluginPackageWorkflowFrontierPage>>;
advance(
runId: string,
): Promise<Readonly<PluginPackageWorkflowFrontierAdvanceResult>>;
}
export class InvalidPluginPackageWorkflowFrontierError extends TypeError {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_FRONTIER_INVALID';
constructor(message: string) {
super(`Plugin Package Workflow frontier is invalid: ${message}`);
this.name = 'InvalidPluginPackageWorkflowFrontierError';
}
}
export class PluginPackageWorkflowFrontierConflictError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_FRONTIER_CONFLICT';
constructor() {
super('Plugin Package Workflow frontier changed concurrently');
this.name = 'PluginPackageWorkflowFrontierConflictError';
}
}
export class PluginPackageWorkflowFrontierUnavailableError extends Error {
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_FRONTIER_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package Workflow frontier is unavailable', options);
this.name = 'PluginPackageWorkflowFrontierUnavailableError';
}
}
const FRONTIER_ID_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-frontier-id@v1\0',
'utf8',
);
const BLOCKING_TERMINAL_STATUSES = new Set<StepRunStatus>([
'failed',
'skipped',
'cancelled',
'timed_out',
]);
const TERMINAL_STATUSES = new Set<StepRunStatus>(
STEP_RUN_TERMINAL_STATUSES,
);
function invalid(message: string): never {
throw new InvalidPluginPackageWorkflowFrontierError(message);
}
function timestamp(value: unknown): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid('observation time is invalid');
}
return value as number;
}
function counter(value: unknown, label: string): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function frontierIdentity(
planDigest: string,
stepRun: Readonly<StepRunRecord>,
target: 'ready' | 'skipped',
): Readonly<{ eventId: string; mutationId: string }> {
const digest = createHash('sha256')
.update(FRONTIER_ID_DOMAIN)
.update(planDigest, 'utf8')
.update('\0', 'utf8')
.update(stepRun.id, 'utf8')
.update('\0', 'utf8')
.update(String(stepRun.version), 'utf8')
.update('\0', 'utf8')
.update(target, 'utf8')
.digest('hex');
return Object.freeze({
eventId: `wff:${digest.slice(0, 32)}`,
mutationId: `workflow-frontier:${digest}`,
});
}
function terminalIdentity(
planDigest: string,
runVersion: number,
status: PluginPackageWorkflowTerminalStatus,
): string {
const digest = createHash('sha256')
.update(FRONTIER_ID_DOMAIN)
.update(planDigest, 'utf8')
.update('\0terminal\0', 'utf8')
.update(String(runVersion), 'utf8')
.update('\0', 'utf8')
.update(status, 'utf8')
.digest('hex');
return `wft:${digest.slice(0, 32)}`;
}
function terminalErrorCode(
status: PluginPackageWorkflowTerminalStatus,
): string | null {
if (status === 'succeeded') return null;
if (status === 'failed') return 'workflow_step_failed';
if (status === 'timed_out') return 'workflow_step_timed_out';
return 'workflow_step_cancelled';
}
function validateRun(
plan: Readonly<PluginPackageWorkflowExecutionPlan>,
run: Readonly<RunRecord>,
): void {
if (
!run ||
typeof run !== 'object' ||
Array.isArray(run) ||
run.id !== plan.runId ||
run.projectId !== plan.target.projectId ||
run.taskId !== plan.target.workflowId ||
run.taskRevision !== plan.target.publicationDigest ||
run.triggerType !== 'plugin_package_workflow' ||
run.executionOrigin !== 'system' ||
run.executionOwner !== 'runtime' ||
run.requestId !== plan.planId ||
run.idempotencyKey !== `plugin-package-workflow:${plan.planId}` ||
run.status !== 'running' ||
run.cancelRequestedAtMs !== undefined
) {
invalid('Run does not match the admitted Workflow');
}
counter(run.version, 'Run version');
counter(run.eventSequence, 'Run event sequence');
}
function validateStepRuns(
plan: Readonly<PluginPackageWorkflowExecutionPlan>,
stepRunValues: readonly Readonly<StepRunRecord>[],
): ReadonlyMap<string, Readonly<StepRunRecord>> {
if (
!Array.isArray(stepRunValues) ||
stepRunValues.length !== plan.steps.length
) {
return invalid('StepRun set is incomplete');
}
const byKey = new Map<string, Readonly<StepRunRecord>>();
for (const value of stepRunValues) {
let stepRun: Readonly<StepRunRecord>;
try {
stepRun = normalizeStepRunRecord(value);
} catch {
return invalid('StepRun record is invalid');
}
const step = plan.steps.find(({ stepKey }) => stepKey === stepRun.stepKey);
if (
!step ||
byKey.has(step.stepKey) ||
stepRun.id !== step.stepRunId ||
stepRun.runId !== plan.runId ||
stepRun.parentStepRunId !== null ||
stepRun.kind !== 'task' ||
stepRun.definitionRef !== step.taskDefinitionRef ||
stepRun.definitionDigest !== step.taskDefinitionDigest ||
stepRun.required !== step.required
) {
return invalid('StepRun does not match the immutable plan');
}
byKey.set(step.stepKey, stepRun);
}
return byKey;
}
function dependencyCannotSucceed(
stepKey: string,
plan: Readonly<PluginPackageWorkflowExecutionPlan>,
stepRuns: ReadonlyMap<string, Readonly<StepRunRecord>>,
memo: Map<string, boolean>,
visiting: Set<string>,
): boolean {
const memoized = memo.get(stepKey);
if (memoized !== undefined) return memoized;
if (visiting.has(stepKey)) {
return invalid('Workflow dependency graph is cyclic');
}
const step = plan.steps.find((candidate) => candidate.stepKey === stepKey);
const stepRun = stepRuns.get(stepKey);
if (!step || !stepRun) return invalid('Workflow dependency is missing');
if (BLOCKING_TERMINAL_STATUSES.has(stepRun.status)) {
memo.set(stepKey, true);
return true;
}
if (stepRun.status !== 'pending') {
memo.set(stepKey, false);
return false;
}
visiting.add(stepKey);
const blocked = step.needs.some((dependency) =>
dependencyCannotSucceed(
dependency,
plan,
stepRuns,
memo,
visiting,
),
);
visiting.delete(stepKey);
memo.set(stepKey, blocked);
return blocked;
}
function terminalStatus(
statuses: readonly StepRunStatus[],
): PluginPackageWorkflowTerminalStatus | null {
if (!statuses.every((status) => TERMINAL_STATUSES.has(status))) return null;
if (statuses.includes('failed') || statuses.includes('skipped')) {
return 'failed';
}
if (statuses.includes('timed_out')) return 'timed_out';
if (statuses.includes('cancelled')) return 'cancelled';
return 'succeeded';
}
export function resolvePluginPackageWorkflowFrontier(
value: PluginPackageWorkflowFrontierSnapshot,
): Readonly<PluginPackageWorkflowFrontierResolution> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('snapshot is invalid');
}
const plan = normalizePluginPackageWorkflowExecutionPlan(value.plan);
validateRun(plan, value.run);
const observedAtMs = timestamp(value.observedAtMs);
const byKey = validateStepRuns(plan, value.stepRuns);
if (
[...byKey.values()].some(
(stepRun) => observedAtMs < stepRun.updatedAtMs,
)
) {
return invalid('observation time precedes StepRun state');
}
const blockedMemo = new Map<string, boolean>();
const projectedStatuses = new Map(
[...byKey].map(([stepKey, stepRun]) => [stepKey, stepRun.status]),
);
const mutations: Readonly<StepRunMutation>[] = [];
let runVersion = value.run.version;
let runEventSequence = value.run.eventSequence;
for (const step of plan.steps) {
const stepRun = byKey.get(step.stepKey)!;
if (stepRun.status !== 'pending') continue;
const blocked = dependencyCannotSucceed(
step.stepKey,
plan,
byKey,
blockedMemo,
new Set(),
);
const allDependenciesSucceeded = step.needs.every(
(dependency) => byKey.get(dependency)!.status === 'succeeded',
);
if (!blocked && !allDependenciesSucceeded) continue;
const target = blocked ? 'skipped' : 'ready';
const identity = frontierIdentity(plan.planDigest, stepRun, target);
const mutation = transitionStepRunMutation(
stepRun,
{
expectedVersion: stepRun.version,
expectedDigest: stepRun.stepRunDigest,
mutationId: identity.mutationId,
to: target,
atMs: observedAtMs,
...(target === 'skipped'
? { resultCode: 'dependency_not_succeeded' }
: {}),
},
{
expectedRunVersion: runVersion,
expectedRunEventSequence: runEventSequence,
eventId: identity.eventId,
dedupeKey: identity.eventId,
actor: { type: 'reconciler' },
},
);
mutations.push(mutation);
projectedStatuses.set(step.stepKey, target);
runVersion += 1;
runEventSequence += 1;
}
const readyStepRunIds = plan.steps
.filter((step) => projectedStatuses.get(step.stepKey) === 'ready')
.map((step) => step.stepRunId);
const aggregateStatus = terminalStatus(
plan.steps.map((step) => projectedStatuses.get(step.stepKey)!),
);
const terminalTransition =
aggregateStatus === null
? null
: (() => {
const eventId = terminalIdentity(
plan.planDigest,
runVersion,
aggregateStatus,
);
return Object.freeze({
expectedRunVersion: runVersion,
expectedRunEventSequence: runEventSequence,
status: aggregateStatus,
finishedAtMs: observedAtMs,
errorCode: terminalErrorCode(aggregateStatus),
event: Object.freeze({
id: eventId,
runId: plan.runId,
sequence: runEventSequence + 1,
type: `workflow.${aggregateStatus}`,
dedupeKey: eventId,
actorType: 'reconciler',
payload: Object.freeze({
planDigest: plan.planDigest,
workflowId: plan.target.workflowId,
stepCount: plan.steps.length,
status: aggregateStatus,
}),
createdAtMs: observedAtMs,
}),
} satisfies PluginPackageWorkflowTerminalTransition);
})();
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_FRONTIER_SCHEMA,
runId: plan.runId,
planDigest: plan.planDigest,
expectedRunVersion: value.run.version,
expectedRunEventSequence: value.run.eventSequence,
stepMutations: Object.freeze(mutations),
readyStepRunIds: Object.freeze(readyStepRunIds),
terminalStatus: aggregateStatus,
terminalTransition,
observedAtMs,
});
}
@@ -0,0 +1,688 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageTaskReconciliationReceipt,
type PluginPackageTaskReconciliationReceipt,
} from '../pluginPackageTaskReconciliation';
import {
normalizePluginPackageWorkflowExecutionPlan,
type PluginPackageWorkflowExecutionPlan,
} from './pluginPackageWorkflowExecutionPlan';
import {
normalizeClusterTaskExecutionRevision,
type ClusterTaskExecutionRevision,
} from '../../task-definition/clusterExecutionRevision';
import {
normalizeLocalTaskExecutionRevision,
type LocalTaskExecutionRevision,
} from '../../local-runtime/localDispatch';
import type { RunAttemptRecord, RunEventRecord, RunRecord } from '../../run/run';
import {
MAX_STEP_RUN_ATTEMPTS,
normalizeStepRunRecord,
type StepRunRecord,
} from '../../run/stepRun';
export const PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_SCHEMA =
'qinglong/plugin-package-workflow-task-attempt-admission@v1' as const;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_PAGE_SIZE = 64;
export const MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_ATTEMPTS =
128 * MAX_STEP_RUN_ATTEMPTS;
export type PluginPackageWorkflowTaskExecutorType =
| 'local_process'
| 'remote_worker';
export interface PluginPackageWorkflowTaskExecutionBinding {
readonly projectId: string;
readonly taskId: string;
readonly taskRevision: string;
readonly taskDefinitionDigest: string;
readonly executorType: PluginPackageWorkflowTaskExecutorType;
readonly executionDigest: string;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionReceipt {
readonly schema:
typeof PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_SCHEMA;
readonly attemptId: string;
readonly planDigest: string;
readonly runId: string;
readonly stepRunId: string;
readonly stepRunVersion: number;
readonly stepRunDigest: string;
readonly resourceTaskId: string;
readonly taskReconciliationReceiptDigest: string;
readonly taskId: string;
readonly taskRevision: string;
readonly taskDefinitionDigest: string;
readonly executorType: PluginPackageWorkflowTaskExecutorType;
readonly executionDigest: string;
readonly attemptNumber: number;
readonly eventId: string;
readonly runVersion: number;
readonly runEventSequence: number;
readonly admittedAtMs: number;
readonly receiptDigest: string;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionBundle {
readonly receipt: Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
readonly attempt: Readonly<RunAttemptRecord>;
readonly event: Readonly<RunEventRecord>;
readonly run: Readonly<RunRecord>;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionCursor {
readonly readyAtMs: number;
readonly stepRunId: string;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionCandidate
extends PluginPackageWorkflowTaskAttemptAdmissionCursor {
readonly runId: string;
readonly planDigest: string;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionPage {
readonly candidates: readonly Readonly<PluginPackageWorkflowTaskAttemptAdmissionCandidate>[];
readonly truncated: boolean;
readonly next?: Readonly<PluginPackageWorkflowTaskAttemptAdmissionCursor>;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionResult {
readonly status: 'created' | 'existing';
readonly receipt: Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
}
export interface PluginPackageWorkflowTaskAttemptAdmissionRepository {
listCandidates(query: Readonly<{
limit: number;
after?: Readonly<PluginPackageWorkflowTaskAttemptAdmissionCursor>;
}>): Promise<
Readonly<PluginPackageWorkflowTaskAttemptAdmissionPage>
>;
admit(
runId: string,
stepRunId: string,
): Promise<
Readonly<PluginPackageWorkflowTaskAttemptAdmissionResult>
>;
}
export interface CreatePluginPackageWorkflowTaskAttemptAdmissionInput {
readonly plan: Readonly<PluginPackageWorkflowExecutionPlan>;
readonly run: Readonly<RunRecord>;
readonly stepRun: Readonly<StepRunRecord>;
readonly taskReconciliation:
Readonly<PluginPackageTaskReconciliationReceipt>;
readonly execution: Readonly<
LocalTaskExecutionRevision | ClusterTaskExecutionRevision
>;
readonly attemptNumber: number;
readonly admittedAtMs: number;
}
export class InvalidPluginPackageWorkflowTaskAttemptAdmissionError
extends TypeError
{
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_INVALID';
constructor(message: string) {
super(
`Plugin Package Workflow Task Attempt admission is invalid: ${message}`,
);
this.name =
'InvalidPluginPackageWorkflowTaskAttemptAdmissionError';
}
}
export class PluginPackageWorkflowTaskAttemptAdmissionConflictError
extends Error
{
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_CONFLICT';
constructor() {
super('Plugin Package Workflow Task Attempt admission conflicts with state');
this.name =
'PluginPackageWorkflowTaskAttemptAdmissionConflictError';
}
}
export class PluginPackageWorkflowTaskAttemptAdmissionUnavailableError
extends Error
{
readonly code =
'PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Plugin Package Workflow Task Attempt admission is unavailable', {
cause: options?.cause,
});
this.name =
'PluginPackageWorkflowTaskAttemptAdmissionUnavailableError';
}
}
const DIGEST = /^[0-9a-f]{64}$/;
const IDENTITY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const TASK_REVISION = /^qltd:v1:([1-9][0-9]{0,9}):([0-9a-f]{64})$/;
const ACTIVE_RECONCILIATION_DISPOSITIONS = new Set([
'created',
'retained',
'updated',
]);
const ID_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-task-attempt-id@v1\0',
'utf8',
);
const RECEIPT_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-task-attempt-receipt@v1\0',
'utf8',
);
function invalid(message: string): never {
throw new InvalidPluginPackageWorkflowTaskAttemptAdmissionError(message);
}
function dataRecord(value: unknown, label: string): Record<string, unknown> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
Object.getPrototypeOf(value) !== Object.prototype
) {
return invalid(`${label} must be an object`);
}
return value as Record<string, unknown>;
}
function exactKeys(
value: object,
required: readonly string[],
optional: readonly string[],
label: string,
): void {
const keys = Reflect.ownKeys(value);
const allowed = new Set([...required, ...optional]);
if (
keys.some((key) => typeof key !== 'string') ||
required.some((key) => !keys.includes(key)) ||
keys.some((key) => typeof key === 'string' && !allowed.has(key))
) {
invalid(`${label} shape is invalid`);
}
}
function identity(value: unknown, label: string): string {
if (typeof value !== 'string' || !IDENTITY.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function digest(value: unknown, label: string): string {
if (typeof value !== 'string' || !DIGEST.test(value)) {
return invalid(`${label} is invalid`);
}
return value;
}
function integer(
value: unknown,
minimum: number,
maximum: number,
label: string,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < minimum ||
(value as number) > maximum
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function timestamp(value: unknown, label: string): number {
return integer(value, 0, Number.MAX_SAFE_INTEGER, label);
}
function taskIdentity(packageName: string, resourceTaskId: string): string {
return identity(
`pkg:${packageName}:${resourceTaskId}`,
'runtime Task identity',
);
}
function executionBinding(
value: Readonly<
LocalTaskExecutionRevision | ClusterTaskExecutionRevision
>,
): Readonly<PluginPackageWorkflowTaskExecutionBinding> {
let normalized:
| Readonly<LocalTaskExecutionRevision>
| Readonly<ClusterTaskExecutionRevision>;
try {
normalized =
value?.executorType === 'local_process'
? normalizeLocalTaskExecutionRevision(
value as LocalTaskExecutionRevision,
)
: value?.executorType === 'remote_worker'
? normalizeClusterTaskExecutionRevision(
value as ClusterTaskExecutionRevision,
)
: invalid('execution revision executorType is invalid');
} catch (error) {
if (
error instanceof
InvalidPluginPackageWorkflowTaskAttemptAdmissionError
) {
throw error;
}
return invalid('execution revision is invalid');
}
const taskRevision = identity(
normalized.taskRevision,
'execution revision taskRevision',
);
const revisionMatch = TASK_REVISION.exec(taskRevision);
if (!revisionMatch) {
invalid('execution revision Task identity is inconsistent');
}
const taskDefinitionDigest = revisionMatch[2]!;
return Object.freeze({
projectId: identity(normalized.projectId, 'execution revision projectId'),
taskId: identity(normalized.taskId, 'execution revision taskId'),
taskRevision,
taskDefinitionDigest,
executorType: normalized.executorType,
executionDigest: digest(
normalized.contentDigest,
'execution revision contentDigest',
),
});
}
function admissionIdentity(
planDigest: string,
stepRunId: string,
stepRunVersion: number,
): Readonly<{ attemptId: string; eventId: string }> {
const value = createHash('sha256')
.update(ID_DOMAIN)
.update(planDigest, 'utf8')
.update('\0', 'utf8')
.update(stepRunId, 'utf8')
.update('\0', 'utf8')
.update(String(stepRunVersion), 'utf8')
.digest('hex');
return Object.freeze({
attemptId: `wta:${value.slice(0, 32)}`,
eventId: `wte:${value.slice(0, 32)}`,
});
}
function unsignedReceipt(
value: Omit<
PluginPackageWorkflowTaskAttemptAdmissionReceipt,
'receiptDigest'
>,
): object {
return {
schema: value.schema,
attemptId: value.attemptId,
planDigest: value.planDigest,
runId: value.runId,
stepRunId: value.stepRunId,
stepRunVersion: value.stepRunVersion,
stepRunDigest: value.stepRunDigest,
resourceTaskId: value.resourceTaskId,
taskReconciliationReceiptDigest:
value.taskReconciliationReceiptDigest,
taskId: value.taskId,
taskRevision: value.taskRevision,
taskDefinitionDigest: value.taskDefinitionDigest,
executorType: value.executorType,
executionDigest: value.executionDigest,
attemptNumber: value.attemptNumber,
eventId: value.eventId,
runVersion: value.runVersion,
runEventSequence: value.runEventSequence,
admittedAtMs: value.admittedAtMs,
};
}
export function pluginPackageWorkflowTaskAttemptAdmissionReceiptDigest(
value: Omit<
PluginPackageWorkflowTaskAttemptAdmissionReceipt,
'receiptDigest'
>,
): string {
return createHash('sha256')
.update(RECEIPT_DOMAIN)
.update(JSON.stringify(unsignedReceipt(value)), 'utf8')
.digest('hex');
}
export function normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt(
value: PluginPackageWorkflowTaskAttemptAdmissionReceipt,
): Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt> {
const receipt = dataRecord(value, 'admission receipt');
exactKeys(
receipt,
[
'admittedAtMs',
'attemptId',
'attemptNumber',
'eventId',
'executionDigest',
'executorType',
'planDigest',
'receiptDigest',
'resourceTaskId',
'runEventSequence',
'runId',
'runVersion',
'schema',
'stepRunDigest',
'stepRunId',
'stepRunVersion',
'taskDefinitionDigest',
'taskId',
'taskReconciliationReceiptDigest',
'taskRevision',
],
[],
'admission receipt',
);
if (
value.schema !==
PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_SCHEMA
) {
invalid('admission receipt schema is invalid');
}
const executorType = value.executorType;
if (executorType !== 'local_process' && executorType !== 'remote_worker') {
invalid('admission receipt executorType is invalid');
}
const taskDefinitionDigest = digest(
value.taskDefinitionDigest,
'admission receipt taskDefinitionDigest',
);
const taskRevision = identity(
value.taskRevision,
'admission receipt taskRevision',
);
const revisionMatch = TASK_REVISION.exec(taskRevision);
if (!revisionMatch || revisionMatch[2] !== taskDefinitionDigest) {
invalid('admission receipt Task revision is inconsistent');
}
const runVersion = integer(
value.runVersion,
1,
2_147_483_647,
'admission receipt Run version',
);
const runEventSequence = integer(
value.runEventSequence,
1,
2_147_483_647,
'admission receipt Run event sequence',
);
if (runVersion !== runEventSequence) {
invalid('admission receipt Run counters are inconsistent');
}
const unsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_SCHEMA,
attemptId: identity(value.attemptId, 'admission receipt attemptId'),
planDigest: digest(value.planDigest, 'admission receipt planDigest'),
runId: identity(value.runId, 'admission receipt runId'),
stepRunId: identity(value.stepRunId, 'admission receipt stepRunId'),
stepRunVersion: integer(
value.stepRunVersion,
1,
2_147_483_647,
'admission receipt StepRun version',
),
stepRunDigest: digest(
value.stepRunDigest,
'admission receipt StepRun digest',
),
resourceTaskId: identity(
value.resourceTaskId,
'admission receipt resourceTaskId',
),
taskReconciliationReceiptDigest: digest(
value.taskReconciliationReceiptDigest,
'admission receipt Task reconciliation digest',
),
taskId: identity(value.taskId, 'admission receipt taskId'),
taskRevision,
taskDefinitionDigest,
executorType,
executionDigest: digest(
value.executionDigest,
'admission receipt executionDigest',
),
attemptNumber: integer(
value.attemptNumber,
1,
MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_ATTEMPTS,
'admission receipt attemptNumber',
),
eventId: identity(value.eventId, 'admission receipt eventId'),
runVersion,
runEventSequence,
admittedAtMs: timestamp(
value.admittedAtMs,
'admission receipt admittedAtMs',
),
});
const receiptDigest = digest(
value.receiptDigest,
'admission receipt receiptDigest',
);
if (
pluginPackageWorkflowTaskAttemptAdmissionReceiptDigest(unsigned) !==
receiptDigest
) {
invalid('admission receipt digest does not match');
}
return Object.freeze({ ...unsigned, receiptDigest });
}
export function createPluginPackageWorkflowTaskAttemptAdmission(
value: CreatePluginPackageWorkflowTaskAttemptAdmissionInput,
): Readonly<PluginPackageWorkflowTaskAttemptAdmissionBundle> {
const input = dataRecord(value, 'admission input');
exactKeys(
input,
[
'admittedAtMs',
'attemptNumber',
'execution',
'plan',
'run',
'stepRun',
'taskReconciliation',
],
[],
'admission input',
);
let plan: Readonly<PluginPackageWorkflowExecutionPlan>;
let stepRun: Readonly<StepRunRecord>;
let taskReconciliation:
Readonly<PluginPackageTaskReconciliationReceipt>;
try {
plan = normalizePluginPackageWorkflowExecutionPlan(value.plan);
stepRun = normalizeStepRunRecord(value.stepRun);
taskReconciliation =
normalizePluginPackageTaskReconciliationReceipt(
value.taskReconciliation,
);
} catch {
return invalid('durable Workflow evidence is invalid');
}
const execution = executionBinding(value.execution);
const attemptNumber = integer(
value.attemptNumber,
1,
MAX_PLUGIN_PACKAGE_WORKFLOW_RUN_ATTEMPTS,
'attemptNumber',
);
const admittedAtMs = timestamp(value.admittedAtMs, 'admittedAtMs');
const run = value.run;
if (
!run ||
typeof run !== 'object' ||
Array.isArray(run) ||
run.id !== plan.runId ||
run.projectId !== plan.target.projectId ||
run.taskId !== plan.target.workflowId ||
run.taskRevision !== plan.target.publicationDigest ||
run.triggerType !== 'plugin_package_workflow' ||
run.executionOrigin !== 'system' ||
run.executionOwner !== 'runtime' ||
run.requestId !== plan.planId ||
run.idempotencyKey !== `plugin-package-workflow:${plan.planId}` ||
run.status !== 'running' ||
run.cancelRequestedAtMs !== undefined ||
!Number.isSafeInteger(run.version) ||
run.version < 1 ||
run.version !== run.eventSequence
) {
invalid('Run does not match the admitted Workflow aggregate');
}
const planStep = plan.steps.find(
({ stepRunId }) => stepRunId === stepRun.id,
);
if (
!planStep ||
stepRun.runId !== run.id ||
stepRun.stepKey !== planStep.stepKey ||
stepRun.kind !== 'task' ||
stepRun.definitionRef !== planStep.taskDefinitionRef ||
stepRun.definitionDigest !== planStep.taskDefinitionDigest ||
stepRun.required !== planStep.required ||
stepRun.status !== 'ready' ||
stepRun.attemptCount >= MAX_STEP_RUN_ATTEMPTS
) {
invalid('StepRun is not one exact ready Task from the plan');
}
if (
taskReconciliation.projectId !== plan.target.projectId ||
taskReconciliation.packageName !== plan.target.packageName ||
taskReconciliation.generation !== plan.target.generation ||
taskReconciliation.generationDigest !== plan.target.generationDigest ||
taskReconciliation.materializedRevisionDigest !==
plan.target.materializedRevisionDigest ||
taskReconciliation.lockDigest !== plan.target.lockDigest
) {
invalid('Task reconciliation does not match the immutable plan');
}
const expectedTaskId = taskIdentity(
plan.target.packageName,
planStep.taskId,
);
const item = taskReconciliation.items.find(
({ taskId }) => taskId === expectedTaskId,
);
if (
!item ||
!ACTIVE_RECONCILIATION_DISPOSITIONS.has(item.disposition) ||
execution.projectId !== plan.target.projectId ||
execution.taskId !== item.taskId ||
execution.taskDefinitionDigest !== item.contentDigest ||
execution.taskRevision !==
`qltd:v1:${item.revision}:${item.contentDigest}`
) {
invalid('execution binding is not the reconciled Task revision');
}
if (
admittedAtMs < plan.plannedAtMs ||
admittedAtMs < taskReconciliation.committedAtMs ||
admittedAtMs < stepRun.updatedAtMs
) {
invalid('admission time precedes durable evidence');
}
if (
run.version >= 2_147_483_647 ||
run.eventSequence >= 2_147_483_647
) {
invalid('Run counters overflowed');
}
const ids = admissionIdentity(
plan.planDigest,
stepRun.id,
stepRun.version,
);
const nextRun = Object.freeze({
...run,
version: run.version + 1,
eventSequence: run.eventSequence + 1,
});
const attempt = Object.freeze({
id: ids.attemptId,
runId: run.id,
stepRunId: stepRun.id,
attempt: attemptNumber,
status: 'claimed' as const,
executorType: execution.executorType,
callbackSequence: 0,
createdAtMs: admittedAtMs,
} satisfies RunAttemptRecord);
const event = Object.freeze({
id: ids.eventId,
runId: run.id,
sequence: nextRun.eventSequence,
type: 'workflow.task_attempt_admitted',
dedupeKey: ids.eventId,
actorType: 'system' as const,
attemptId: attempt.id,
stepRunId: stepRun.id,
payload: Object.freeze({
planDigest: plan.planDigest,
stepRunId: stepRun.id,
stepRunVersion: stepRun.version,
resourceTaskId: planStep.taskId,
taskId: execution.taskId,
taskRevision: execution.taskRevision,
executorType: execution.executorType,
executionDigest: execution.executionDigest,
attemptNumber,
}),
createdAtMs: admittedAtMs,
} satisfies RunEventRecord);
const receiptUnsigned = Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_TASK_ATTEMPT_ADMISSION_SCHEMA,
attemptId: attempt.id,
planDigest: plan.planDigest,
runId: run.id,
stepRunId: stepRun.id,
stepRunVersion: stepRun.version,
stepRunDigest: stepRun.stepRunDigest,
resourceTaskId: planStep.taskId,
taskReconciliationReceiptDigest: taskReconciliation.receiptDigest,
taskId: execution.taskId,
taskRevision: execution.taskRevision,
taskDefinitionDigest: execution.taskDefinitionDigest,
executorType: execution.executorType,
executionDigest: execution.executionDigest,
attemptNumber,
eventId: event.id,
runVersion: nextRun.version,
runEventSequence: nextRun.eventSequence,
admittedAtMs,
});
const receipt =
normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt({
...receiptUnsigned,
receiptDigest:
pluginPackageWorkflowTaskAttemptAdmissionReceiptDigest(
receiptUnsigned,
),
});
return Object.freeze({ receipt, attempt, event, run: nextRun });
}
@@ -0,0 +1,391 @@
import { createHash } from 'node:crypto';
import {
normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt,
type PluginPackageWorkflowTaskAttemptAdmissionReceipt,
} from './pluginPackageWorkflowTaskAttemptAdmission';
import type { RunAttemptRecord, RunEventRecord, RunRecord } from '../../run/run';
import {
normalizeStepRunRecord,
transitionStepRunMutation,
type StepRunMutation,
type StepRunRecord,
} from '../../run/stepRun';
export const PLUGIN_PACKAGE_WORKFLOW_TASK_RECOVERY_SCHEMA =
'qinglong/plugin-package-workflow-task-recovery@v1' as const;
export type PluginPackageWorkflowTaskRecoveryReason =
| 'unstarted_claim_expired'
| 'execution_not_running';
export interface PluginPackageWorkflowTaskRecoveryInput {
readonly admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
readonly run: Readonly<RunRecord>;
readonly attempt: Readonly<RunAttemptRecord>;
readonly stepRun: Readonly<StepRunRecord>;
readonly reason: PluginPackageWorkflowTaskRecoveryReason;
readonly observedAtMs: number;
}
export interface PluginPackageWorkflowTaskRecoveryBundle {
readonly schema: typeof PLUGIN_PACKAGE_WORKFLOW_TASK_RECOVERY_SCHEMA;
readonly disposition: 'requeued' | 'failed';
readonly run: Readonly<RunRecord>;
readonly attempt: Readonly<RunAttemptRecord>;
readonly attemptEvent: Readonly<RunEventRecord>;
readonly stepMutations: readonly Readonly<StepRunMutation>[];
}
export class InvalidPluginPackageWorkflowTaskRecoveryError
extends TypeError
{
readonly code = 'PLUGIN_PACKAGE_WORKFLOW_TASK_RECOVERY_INVALID';
constructor(message: string) {
super(`Plugin Package Workflow Task recovery is invalid: ${message}`);
this.name = 'InvalidPluginPackageWorkflowTaskRecoveryError';
}
}
const ACTIVE_ATTEMPT_STATUSES = new Set(['claimed', 'starting', 'running']);
const ID_DOMAIN = Buffer.from(
'qinglong/plugin-package-workflow-task-recovery-id@v1\0',
'utf8',
);
const LOST_ERROR_CODE = Object.freeze({
unstarted_claim_expired:
'CLUSTER_RECOVERY_UNSTARTED_CLAIM_EXPIRED',
execution_not_running:
'CLUSTER_RECOVERY_EXECUTION_NOT_RUNNING',
});
const LOST_ERROR_SUMMARY = Object.freeze({
unstarted_claim_expired:
'The Workflow Task Attempt claim expired before execution started',
execution_not_running:
'Trusted execution evidence proved that the Workflow Task Attempt is not running',
});
function invalid(message: string): never {
throw new InvalidPluginPackageWorkflowTaskRecoveryError(message);
}
function safeInteger(
value: unknown,
minimum: number,
maximum: number,
label: string,
): number {
if (
!Number.isSafeInteger(value) ||
(value as number) < minimum ||
(value as number) > maximum
) {
return invalid(`${label} is invalid`);
}
return value as number;
}
function identity(
attempt: Readonly<RunAttemptRecord>,
stepRun: Readonly<StepRunRecord>,
reason: PluginPackageWorkflowTaskRecoveryReason,
): Readonly<{
attemptEventId: string;
requeueMutationId: string;
requeueEventId: string;
lostMutationId: string;
lostEventId: string;
failedMutationId: string;
failedEventId: string;
}> {
const digest = createHash('sha256')
.update(ID_DOMAIN)
.update(attempt.runId, 'utf8')
.update('\0', 'utf8')
.update(attempt.id, 'utf8')
.update('\0', 'utf8')
.update(String(attempt.callbackSequence), 'utf8')
.update('\0', 'utf8')
.update(stepRun.id, 'utf8')
.update('\0', 'utf8')
.update(String(stepRun.version), 'utf8')
.update('\0', 'utf8')
.update(reason, 'utf8')
.digest('hex')
.slice(0, 32);
return Object.freeze({
attemptEventId: `wra:${digest}`,
requeueMutationId: `wrq:${digest}`,
requeueEventId: `wqe:${digest}`,
lostMutationId: `wrl:${digest}`,
lostEventId: `wle:${digest}`,
failedMutationId: `wrf:${digest}`,
failedEventId: `wfe:${digest}`,
});
}
function validateAuthority(
input: Readonly<PluginPackageWorkflowTaskRecoveryInput>,
admission: Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>,
stepRun: Readonly<StepRunRecord>,
): void {
const { run, attempt, reason } = input;
if (
!run ||
typeof run !== 'object' ||
Array.isArray(run) ||
run.id !== admission.runId ||
run.triggerType !== 'plugin_package_workflow' ||
run.executionOrigin !== 'system' ||
run.executionOwner !== 'runtime' ||
run.status !== 'running' ||
run.cancelRequestedAtMs !== undefined
) {
invalid('Run is not an active runtime-owned Workflow aggregate');
}
const runVersion = safeInteger(
run.version,
1,
2_147_483_644,
'Run version',
);
const runEventSequence = safeInteger(
run.eventSequence,
1,
2_147_483_644,
'Run event sequence',
);
if (
runVersion !== runEventSequence ||
admission.runVersion > runVersion ||
admission.runEventSequence > runEventSequence
) {
invalid('Run aggregate counters do not contain the admission event');
}
if (
!attempt ||
typeof attempt !== 'object' ||
Array.isArray(attempt) ||
attempt.id !== admission.attemptId ||
attempt.runId !== run.id ||
attempt.stepRunId !== admission.stepRunId ||
attempt.attempt !== admission.attemptNumber ||
attempt.executorType !== admission.executorType ||
attempt.createdAtMs !== admission.admittedAtMs ||
!ACTIVE_ATTEMPT_STATUSES.has(attempt.status)
) {
invalid('Attempt is not the active admission-bound Workflow Task Attempt');
}
safeInteger(
attempt.callbackSequence,
0,
2_147_483_647,
'Attempt callback sequence',
);
if (
stepRun.id !== admission.stepRunId ||
stepRun.runId !== run.id ||
stepRun.kind !== 'task'
) {
invalid('StepRun is not the admitted Workflow Task');
}
if (reason === 'unstarted_claim_expired') {
if (
attempt.status !== 'claimed' ||
attempt.startedAtMs !== undefined ||
stepRun.status !== 'ready' ||
stepRun.version !== admission.stepRunVersion ||
stepRun.stepRunDigest !== admission.stepRunDigest
) {
invalid('unstarted recovery crossed the Workflow Task start barrier');
}
} else if (attempt.status === 'starting') {
if (
stepRun.status !== 'ready' ||
stepRun.version !== admission.stepRunVersion ||
stepRun.stepRunDigest !== admission.stepRunDigest
) {
invalid('starting recovery does not match the admitted StepRun epoch');
}
} else if (
attempt.status !== 'running' ||
stepRun.status !== 'running' ||
stepRun.version !== admission.stepRunVersion + 1 ||
stepRun.startedAtMs === null
) {
invalid('running recovery does not match the canonical StepRun');
}
}
function transitionTime(
observedAtMs: number,
run: Readonly<RunRecord>,
attempt: Readonly<RunAttemptRecord>,
stepRun: Readonly<StepRunRecord>,
): number {
const atMs = safeInteger(
observedAtMs,
0,
Number.MAX_SAFE_INTEGER,
'recovery observation time',
);
const lowerBound = Math.max(
run.createdAtMs,
run.startedAtMs ?? 0,
attempt.createdAtMs,
attempt.startedAtMs ?? 0,
attempt.finishedAtMs ?? 0,
stepRun.createdAtMs,
stepRun.updatedAtMs,
stepRun.startedAtMs ?? 0,
stepRun.finishedAtMs ?? 0,
);
if (atMs < lowerBound) {
invalid('recovery observation precedes durable state');
}
return atMs;
}
/**
* Resolves only one immutable, admission-bound Workflow Task Attempt.
*
* An expired pre-start claim is safe to requeue by refreshing the exact
* `ready` StepRun epoch. Once the start barrier has been crossed, v1 fails the
* StepRun after trusted absence evidence instead of silently duplicating an
* external side effect. The Workflow aggregate Run remains `running`; its
* frontier owns final aggregation.
*/
export function buildPluginPackageWorkflowTaskRecovery(
input: Readonly<PluginPackageWorkflowTaskRecoveryInput>,
): Readonly<PluginPackageWorkflowTaskRecoveryBundle> {
let admission:
Readonly<PluginPackageWorkflowTaskAttemptAdmissionReceipt>;
let stepRun: Readonly<StepRunRecord>;
try {
admission =
normalizePluginPackageWorkflowTaskAttemptAdmissionReceipt(
input.admission,
);
stepRun = normalizeStepRunRecord(input.stepRun);
} catch {
return invalid('durable admission or StepRun evidence is invalid');
}
if (
input.reason !== 'unstarted_claim_expired' &&
input.reason !== 'execution_not_running'
) {
invalid('recovery reason is invalid');
}
validateAuthority(input, admission, stepRun);
const atMs = transitionTime(
input.observedAtMs,
input.run,
input.attempt,
stepRun,
);
const ids = identity(input.attempt, stepRun, input.reason);
const errorCode = LOST_ERROR_CODE[input.reason];
const errorSummary = LOST_ERROR_SUMMARY[input.reason];
let runVersion = input.run.version + 1;
let runEventSequence = input.run.eventSequence + 1;
const attempt = Object.freeze({
...input.attempt,
status: 'lost' as const,
finishedAtMs: atMs,
errorCode,
errorSummary,
});
const attemptEvent = Object.freeze({
id: ids.attemptEventId,
runId: input.run.id,
sequence: runEventSequence,
type: 'workflow.task_attempt.lost',
dedupeKey: ids.attemptEventId,
actorType: 'system' as const,
attemptId: attempt.id,
stepRunId: stepRun.id,
payload: Object.freeze({
execution_scope: 'workflow_task',
attempt_id: attempt.id,
step_run_id: stepRun.id,
from_status: input.attempt.status,
to_status: 'lost',
reason: input.reason,
error_code: errorCode,
version: runVersion,
}),
createdAtMs: atMs,
} satisfies RunEventRecord);
const stepMutations: Readonly<StepRunMutation>[] = [];
const transition = (
mutationId: string,
eventId: string,
to: 'ready' | 'lost' | 'failed',
): void => {
const mutation = transitionStepRunMutation(
stepRun,
{
expectedVersion: stepRun.version,
expectedDigest: stepRun.stepRunDigest,
mutationId,
to,
atMs,
...(to === 'ready'
? {}
: {
resultCode: 'cluster_recovery_execution_not_running',
errorSummary,
}),
},
{
expectedRunVersion: runVersion,
expectedRunEventSequence: runEventSequence,
eventId,
dedupeKey: eventId,
actor: { type: 'system' },
},
);
stepMutations.push(mutation);
stepRun = mutation.stepRun;
runVersion += 1;
runEventSequence += 1;
};
if (input.reason === 'unstarted_claim_expired') {
transition(
ids.requeueMutationId,
ids.requeueEventId,
'ready',
);
} else if (input.attempt.status === 'starting') {
transition(
ids.failedMutationId,
ids.failedEventId,
'failed',
);
} else {
transition(ids.lostMutationId, ids.lostEventId, 'lost');
transition(
ids.failedMutationId,
ids.failedEventId,
'failed',
);
}
return Object.freeze({
schema: PLUGIN_PACKAGE_WORKFLOW_TASK_RECOVERY_SCHEMA,
disposition:
input.reason === 'unstarted_claim_expired' ? 'requeued' : 'failed',
run: Object.freeze({
...input.run,
version: runVersion,
eventSequence: runEventSequence,
}),
attempt,
attemptEvent,
stepMutations: Object.freeze(stepMutations),
});
}