diff --git a/.github/workflows/desktop-prerelease.yml b/.github/workflows/desktop-prerelease.yml index 7e1e5febb..5f31f42a5 100644 --- a/.github/workflows/desktop-prerelease.yml +++ b/.github/workflows/desktop-prerelease.yml @@ -164,11 +164,6 @@ jobs: LING_CUA_DRIVER_PACKAGE_PROVIDER: "0" LING_PLUGIN_EXTERNAL_ONLY: ${{ inputs.plugin_mode == 'on-demand' && '1' || '0' }} LING_CUA_DRIVER_CATALOG_MANAGED: ${{ inputs.catalog_managed_cua && '1' || '0' }} - LING_CUA_DARWIN_EXPECTED_TEAM_ID: ${{ inputs.catalog_managed_cua && vars.LING_CUA_DARWIN_EXPECTED_TEAM_ID || '' }} - LING_CUA_PROVIDER_SIGNER_SUBJECT: ${{ inputs.catalog_managed_cua && vars.LING_CUA_PROVIDER_SIGNER_SUBJECT || '' }} - LING_CUA_PROVIDER_SIGNER_SHA256: ${{ inputs.catalog_managed_cua && vars.LING_CUA_PROVIDER_SIGNER_SHA256 || '' }} - LING_CUA_CATALOG_SIGNER_SUBJECT: ${{ inputs.catalog_managed_cua && vars.LING_CUA_CATALOG_SIGNER_SUBJECT || '' }} - LING_CUA_CATALOG_SIGNER_SHA256: ${{ inputs.catalog_managed_cua && vars.LING_CUA_CATALOG_SIGNER_SHA256 || '' }} defaults: run: shell: bash @@ -186,7 +181,7 @@ jobs: with: node-version: 22.22.1 cache: pnpm - - name: Validate Cua Driver catalog signer configuration + - name: Validate the Cua Driver catalog runtime policy if: env.LING_CUA_DRIVER_CATALOG_MANAGED == '1' run: | node --input-type=module <<'NODE' @@ -195,13 +190,10 @@ jobs: packageAuthorityInputFromEnvironment, } from "./apps/desktop/scripts/cua-driver-package-runtime-policy.mjs"; const platform = process.env.DESKTOP_TARGET === "macos-arm64" ? "darwin" : "win32-x64"; - createCuaDriverPackageAuthorityDocuments(packageAuthorityInputFromEnvironment(platform, { - ...process.env, - LING_CUA_SIGNING_TIER: "production_signed", - LING_CUA_DISTRIBUTION_CHANNEL: "production", - LING_CUA_SIGNING_FIXTURE: "0", - LING_CUA_TEST_AUTHORITY_KIND: undefined, - })); + createCuaDriverPackageAuthorityDocuments({ + ...packageAuthorityInputFromEnvironment(platform), + providerSource: "official-cache", + }); NODE - uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 if: runner.os == 'Windows' && env.LING_PLUGIN_EXTERNAL_ONLY != '1' diff --git a/.github/workflows/plugin-release.yml b/.github/workflows/plugin-release.yml index e9bdceba1..5e1ca3357 100644 --- a/.github/workflows/plugin-release.yml +++ b/.github/workflows/plugin-release.yml @@ -10,7 +10,7 @@ on: type: choice options: [assemble, verify-keys] sources: - description: Stable Release tags, source commits and asset SHA-256 digests required for assembly + description: One or more stable Release pins per plugin with exact source commits and asset SHA-256 digests required: false type: string publish: diff --git a/apps/desktop/main/cua-driver/adapters/darwin-identity.ts b/apps/desktop/main/cua-driver/adapters/darwin-identity.ts index e5772c645..2e30c11f2 100644 --- a/apps/desktop/main/cua-driver/adapters/darwin-identity.ts +++ b/apps/desktop/main/cua-driver/adapters/darwin-identity.ts @@ -146,14 +146,17 @@ export function createDarwinExecFileCommandRunner(options: { }); } +export type DarwinCuaDriverSignaturePolicy = + | { readonly expectedTeamId: string; readonly signatureMode?: never } + | { readonly expectedTeamId?: never; readonly signatureMode: "ad-hoc" }; + export class DarwinCuaDriverIdentityVerifier implements CuaDriverPlatformIdentityVerifier { private readonly runner: DarwinIdentityCommandRunner; - constructor(private readonly options: { - readonly expectedTeamId: string; + constructor(private readonly options: DarwinCuaDriverSignaturePolicy & { readonly runner?: DarwinIdentityCommandRunner; }) { - if (!/^[A-Z0-9]{10}$/u.test(options.expectedTeamId)) { + if (options.signatureMode !== "ad-hoc" && !/^[A-Z0-9]{10}$/u.test(options.expectedTeamId)) { throw new Error("darwin_cua_driver_expected_team_id_invalid"); } this.runner = options.runner ?? createDarwinExecFileCommandRunner(); @@ -178,11 +181,13 @@ export class DarwinCuaDriverIdentityVerifier implements CuaDriverPlatformIdentit throw new Error("darwin_cua_driver_identity_platform_mismatch"); } const seal = input.seal; + const adHoc = this.options.signatureMode === "ad-hoc"; + const expectedTeamId = adHoc ? "not set" : this.options.expectedTeamId; const platformLock = platformLockFor(input.lock, "darwin"); if (platformLock.componentId !== "cua-driver-darwin") { throw new Error("darwin_cua_driver_lock_platform_mismatch"); } - if (seal.teamId !== this.options.expectedTeamId) { + if (seal.teamId !== expectedTeamId || seal.hardenedRuntime !== !adHoc) { throw new Error("darwin_cua_driver_seal_team_id_mismatch"); } @@ -217,9 +222,10 @@ export class DarwinCuaDriverIdentityVerifier implements CuaDriverPlatformIdentit args: ["--display", "--verbose=4", "--arch", architecture, input.paths.executablePath], }); const details = parseCodesignDetails(`${detailsResult.stdout}\n${detailsResult.stderr}`); - if (details.teamId !== this.options.expectedTeamId + if (details.teamId !== expectedTeamId || details.identifier !== seal.codeIdentifier - || details.hardenedRuntime !== true + || details.hardenedRuntime !== !adHoc + || details.adHoc !== adHoc || details.cdhash !== seal.cdhashes[architecture]) { throw new Error("darwin_cua_driver_codesign_identity_mismatch"); } @@ -234,6 +240,7 @@ export class DarwinCuaDriverIdentityVerifier implements CuaDriverPlatformIdentit }); const requirement = normalizeDesignatedRequirement( `${requirementResult.stdout}\n${requirementResult.stderr}`, + adHoc, ); if (requirement !== seal.designatedRequirement || sha256Utf8(requirement) !== seal.designatedRequirementSha256) { @@ -248,6 +255,14 @@ export class DarwinCuaDriverIdentityVerifier implements CuaDriverPlatformIdentit executable: DARWIN_SYSTEM_TOOLS.codesign, args: ["--display", "--entitlements", "-", "--xml", "--arch", architecture, input.paths.executablePath], }); + if (adHoc) { + const reportedEntitlements = `${entitlementsResult.stdout}\n${entitlementsResult.stderr}` + .split(/\r?\n/u).some((line) => line.trim() && !line.startsWith("Executable=")); + if (reportedEntitlements || seal.entitlementsCanonicalSha256 !== sha256Utf8("{}")) { + throw new Error("darwin_cua_driver_ad_hoc_entitlements_mismatch"); + } + continue; + } const entitlementsPlist = extractPlist(entitlementsResult.stdout, entitlementsResult.stderr); const entitlementsJson = await this.runner.run({ executable: DARWIN_SYSTEM_TOOLS.plutil, @@ -297,6 +312,7 @@ function parseCodesignDetails(output: string): { readonly teamId: string; readonly cdhash: string; readonly hardenedRuntime: boolean; + readonly adHoc: boolean; } { const lines = output.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean); const valueFor = (prefix: string): string | undefined => @@ -313,18 +329,19 @@ function parseCodesignDetails(output: string): { teamId, cdhash, hardenedRuntime: /(?:\(|,)runtime(?:\)|,)/u.test(codeDirectory), + adHoc: valueFor("Signature=") === "adhoc", }; } -function normalizeDesignatedRequirement(output: string): string { +function normalizeDesignatedRequirement(output: string, adHoc: boolean): string { const line = output .split(/\r?\n/u) .map((value) => value.trim()) - .find((value) => value.startsWith("designated =>")); + .find((value) => value.startsWith(adHoc ? "# designated =>" : "designated =>")); if (!line) { throw new Error("darwin_cua_driver_designated_requirement_missing"); } - return line.replace(/^designated\s*=>\s*/u, "").trim(); + return line.replace(/^(?:# )?designated\s*=>\s*/u, "").trim(); } function extractPlist(stdout: string, stderr: string): string { diff --git a/apps/desktop/main/cua-driver/adapters/darwin.ts b/apps/desktop/main/cua-driver/adapters/darwin.ts index 8d01eaaac..5c2b81cc5 100644 --- a/apps/desktop/main/cua-driver/adapters/darwin.ts +++ b/apps/desktop/main/cua-driver/adapters/darwin.ts @@ -1,6 +1,7 @@ import type { DarwinCuaDriverPlatformBinding } from "../platform-binding.js"; import { DarwinCuaDriverIdentityVerifier, + type DarwinCuaDriverSignaturePolicy, type DarwinIdentityCommandRunner, } from "./darwin-identity.js"; import { @@ -27,8 +28,7 @@ export interface DarwinCuaDriverAdapter { * and stop monitoring with requested enablement, then rotate the provider * generation from `onPermissionChanged`. */ -export function createDarwinCuaDriverAdapter(options: { - readonly expectedTeamId: string; +export function createDarwinCuaDriverAdapter(options: DarwinCuaDriverSignaturePolicy & { readonly identityCommandRunner?: DarwinIdentityCommandRunner; readonly spawn?: DarwinDirectSpawn; readonly permissionPort?: DarwinHostPermissionPort; @@ -51,7 +51,9 @@ export function createDarwinCuaDriverAdapter(options: { platform: "darwin", availability: Object.freeze({ status: "available" as const }), platformIdentityVerifier: new DarwinCuaDriverIdentityVerifier({ - expectedTeamId: options.expectedTeamId, + ...(options.signatureMode === "ad-hoc" + ? { signatureMode: "ad-hoc" as const } + : { expectedTeamId: options.expectedTeamId }), ...(options.identityCommandRunner ? { runner: options.identityCommandRunner } : {}), }), processLifecycle: createDarwinCuaDriverProcessLifecycle({ diff --git a/apps/desktop/main/cua-driver/coordinator.ts b/apps/desktop/main/cua-driver/coordinator.ts index 844e30fe4..e7c32327f 100644 --- a/apps/desktop/main/cua-driver/coordinator.ts +++ b/apps/desktop/main/cua-driver/coordinator.ts @@ -115,6 +115,8 @@ export interface CuaDriverCoordinatorOptions { readonly featureFlags?: CuaDriverFeatureFlags; readonly packaged?: boolean; readonly requireReleaseEvidence?: boolean; + readonly runtimeChecksums?: Readonly>; + readonly catalogSourceBuild?: boolean; /** Negotiated with the daemon; old daemons must not receive detail fields. */ readonly readinessDetailsV1?: boolean; /** Preferred production composition boundary for one coherent OS adapter. */ @@ -559,6 +561,8 @@ export class CuaDriverDesktopCoordinator { lock, platformIdentityVerifier: this.platformIdentityVerifier, requirePlatformIdentityVerification: this.options.packaged === true, + runtimeChecksums: this.options.runtimeChecksums, + catalogSourceBuild: this.options.catalogSourceBuild, }); this.assertHostNotDraining(); const stateRoot = await createCuaDriverStateRoot({ @@ -600,6 +604,8 @@ export class CuaDriverDesktopCoordinator { lock: liveLock, platformIdentityVerifier: this.platformIdentityVerifier, requirePlatformIdentityVerification: this.options.packaged === true, + runtimeChecksums: this.options.runtimeChecksums, + catalogSourceBuild: this.options.catalogSourceBuild, }); signal.throwIfAborted(); if ( diff --git a/apps/desktop/main/cua-driver/packaged-startup.ts b/apps/desktop/main/cua-driver/packaged-startup.ts index 3820e68ff..e8c137e28 100644 --- a/apps/desktop/main/cua-driver/packaged-startup.ts +++ b/apps/desktop/main/cua-driver/packaged-startup.ts @@ -21,6 +21,7 @@ export interface DesktopCuaDriverPackagedStartupAuthority { readonly runtimeEligible: boolean; readonly policy?: CuaDriverRuntimeTrustPolicyV1; readonly providerResourcesPath?: string; + readonly runtimeChecksums?: Readonly>; readonly failure?: unknown; } @@ -122,6 +123,7 @@ export async function resolveDesktopCuaDriverPackagedStartupAuthority( return Object.freeze({ authority, featureFlags, policy, runtimeEligible: true, providerResourcesPath: join(runtime.root, "runtime"), + runtimeChecksums: runtime.runtimeChecksums, }); } return Object.freeze({ authority, featureFlags, policy, runtimeEligible: true }); diff --git a/apps/desktop/main/cua-driver/platform-owner.ts b/apps/desktop/main/cua-driver/platform-owner.ts index fb1f5a441..8700420f7 100644 --- a/apps/desktop/main/cua-driver/platform-owner.ts +++ b/apps/desktop/main/cua-driver/platform-owner.ts @@ -90,7 +90,9 @@ export function createCuaDriverDesktopPlatformOwner( throw new CuaDriverDesktopPlatformOwnerError("platform_mismatch", options.platform); } const adapter = createDarwinCuaDriverAdapter({ - expectedTeamId: options.policy.expectedTeamId, + ...(options.policy.signatureMode === "ad-hoc" + ? { signatureMode: "ad-hoc" as const } + : { expectedTeamId: options.policy.expectedTeamId }), ...(options.identityCommandRunner ? { identityCommandRunner: options.identityCommandRunner } : {}), ...(options.spawn ? { spawn: options.spawn } : {}), ...(options.permissionPort ? { permissionPort: options.permissionPort } : {}), diff --git a/apps/desktop/main/cua-driver/provider-seal.ts b/apps/desktop/main/cua-driver/provider-seal.ts index 841c1a693..05f2a85ef 100644 --- a/apps/desktop/main/cua-driver/provider-seal.ts +++ b/apps/desktop/main/cua-driver/provider-seal.ts @@ -1,13 +1,15 @@ import { lstat, readFile, stat } from "node:fs/promises"; +import { relative, sep } from "node:path"; +import { isDeepStrictEqual } from "node:util"; import type { BundledCuaDriverDistributionLockV2, BundledCuaDriverPlatform, BundledCuaDriverProviderSeal, CuaDriverArchitecture, - DarwinBundledProviderSealV1, WindowsBundledProviderSealV2, } from "@ling-stack/contracts"; import { cuaDriverArtifactLayoutFor } from "../../shared/cua-driver-artifact-layout.mjs"; +import { validateCuaDriverCatalogSourceSeal } from "../../shared/cua-driver-catalog-source-seal.mjs"; import { sha256Bytes } from "./artifact-lock.js"; import type { CuaDriverResourcePaths } from "./resource-path.js"; import { assertCuaDriverResourceTree } from "./resource-path.js"; @@ -17,8 +19,8 @@ export const CUA_DRIVER_PROVIDER_SEAL_MAX_BYTES = 256 * 1024; export class CuaDriverProviderSealError extends Error { readonly code = "cua_driver_provider_seal_invalid" as const; - constructor(message: string, readonly path?: string) { - super(message); + constructor(message: string, readonly path?: string, cause?: unknown) { + super(message, cause === undefined ? undefined : { cause }); this.name = "CuaDriverProviderSealError"; } } @@ -60,6 +62,10 @@ export async function readCuaDriverProviderSeal( platform: BundledCuaDriverPlatform, maxBytes = CUA_DRIVER_PROVIDER_SEAL_MAX_BYTES, ): Promise { + return parseSealBytes(await readSealBytes(filePath, maxBytes), filePath, platform); +} + +async function readSealBytes(filePath: string, maxBytes = CUA_DRIVER_PROVIDER_SEAL_MAX_BYTES): Promise { const metadata = await stat(filePath); if (!metadata.isFile() || metadata.size > maxBytes) { throw new CuaDriverProviderSealError("provider_seal_oversized", filePath); @@ -68,6 +74,15 @@ export async function readCuaDriverProviderSeal( if (bytes.byteLength > maxBytes) { throw new CuaDriverProviderSealError("provider_seal_oversized", filePath); } + return bytes; +} + +function parseSealBytes( + bytes: Buffer, + filePath: string, + platform: BundledCuaDriverPlatform, + catalogSourceBuild = false, +): BundledCuaDriverProviderSeal { let parsed: unknown; try { parsed = JSON.parse(bytes.toString("utf8")) as unknown; @@ -75,7 +90,7 @@ export async function readCuaDriverProviderSeal( throw new CuaDriverProviderSealError("provider_seal_json_invalid", filePath); } try { - return validateCuaDriverProviderSeal(parsed, platform); + return validateCuaDriverProviderSeal(parsed, platform, catalogSourceBuild); } catch (error) { if (error instanceof CuaDriverProviderSealError) { throw new CuaDriverProviderSealError(error.message, filePath); @@ -87,13 +102,14 @@ export async function readCuaDriverProviderSeal( export function validateCuaDriverProviderSeal( value: unknown, platform: BundledCuaDriverPlatform, + catalogSourceBuild = false, ): BundledCuaDriverProviderSeal { if (!isRecord(value)) { throw new CuaDriverProviderSealError("provider_seal_not_object"); } assertCommonSeal(value); if (platform === "darwin") { - assertDarwinSeal(value); + assertDarwinSeal(value, catalogSourceBuild); } else { assertWindowsSeal(value); } @@ -108,6 +124,8 @@ export interface VerifyCuaDriverProviderArtifactsInput { readonly platformIdentityVerifier?: CuaDriverPlatformIdentityVerifier; /** Packaged gates set this true; fixture-only core tests may inspect bytes without native tools. */ readonly requirePlatformIdentityVerification?: boolean; + readonly runtimeChecksums?: Readonly>; + readonly catalogSourceBuild?: boolean; } /** @@ -117,23 +135,27 @@ export interface VerifyCuaDriverProviderArtifactsInput { export async function verifyCuaDriverProviderArtifacts( input: VerifyCuaDriverProviderArtifactsInput, ): Promise { - const seal = await readCuaDriverProviderSeal(input.paths.sealPath, input.platform); + if (input.catalogSourceBuild && (!input.runtimeChecksums || !input.platformIdentityVerifier)) { + throw new CuaDriverProviderSealError("catalog_source_build_authority_missing"); + } + const sealBytes = await readSealBytes(input.paths.sealPath); + const seal = parseSealBytes(sealBytes, input.paths.sealPath, input.platform, input.catalogSourceBuild); const windowsSeal = input.platform === "win32" ? seal as WindowsBundledProviderSealV2 : undefined; const requiresCatalog = windowsSeal !== undefined && windowsSeal.signingTier !== "unsigned_dev"; await assertCuaDriverResourceTree(input.paths, { requireCatalog: requiresCatalog }); if (windowsSeal?.signingTier === "unsigned_dev" && input.paths.catalogPath && await pathExists(input.paths.catalogPath)) { throw new CuaDriverProviderSealError("unsigned_provider_catalog_forbidden", input.paths.catalogPath); } - const [lockBytes, licenseBytes, noticesBytes, executableBytes, sealBytes, catalogBytes] = await Promise.all([ + const [lockBytes, licenseBytes, noticesBytes, executableBytes, catalogBytes] = await Promise.all([ readFile(input.paths.lockPath), readFile(input.paths.licensePath), readFile(input.paths.noticesPath), readFile(input.paths.executablePath), - readFile(input.paths.sealPath), requiresCatalog && input.paths.catalogPath ? readFile(input.paths.catalogPath) : Promise.resolve(undefined), ]); const lockDigest = sha256Bytes(lockBytes); - if (sha256Bytes(licenseBytes) !== input.lock.upstream.licenseSha256) { + const licenseDigest = sha256Bytes(licenseBytes); + if (licenseDigest !== input.lock.upstream.licenseSha256) { throw new CuaDriverProviderSealError("provider_license_digest_mismatch", input.paths.licensePath); } if (noticesBytes.byteLength === 0 || noticesBytes.byteLength > 4 * 1024 * 1024) { @@ -142,13 +164,41 @@ export async function verifyCuaDriverProviderArtifacts( const executableDigest = sha256Bytes(executableBytes); const sealDigest = sha256Bytes(sealBytes); const catalogDigest = catalogBytes ? sha256Bytes(catalogBytes) : undefined; + if (input.runtimeChecksums) { + const files = new Map([ + [input.paths.lockPath, lockDigest], [input.paths.licensePath, licenseDigest], + [input.paths.noticesPath, sha256Bytes(noticesBytes)], [input.paths.executablePath, executableDigest], + [input.paths.sealPath, sealDigest], + ]); + if (input.paths.catalogPath && catalogDigest) files.set(input.paths.catalogPath, catalogDigest); + for (const [path, digest] of files) { + const key = `runtime/${relative(input.paths.resourcesPath, path).split(sep).join("/")}`; + if (input.runtimeChecksums[key] !== digest) { + throw new CuaDriverProviderSealError("catalog_runtime_checksum_mismatch", path); + } + } + if (!isDeepStrictEqual(input.lock, JSON.parse(lockBytes.toString("utf8")))) { + throw new CuaDriverProviderSealError("catalog_runtime_lock_changed", input.paths.lockPath); + } + } + if (input.catalogSourceBuild) { + if (input.platform !== "darwin" && input.platform !== "win32") { + throw new CuaDriverProviderSealError("catalog_source_build_platform_invalid"); + } + try { + validateCuaDriverCatalogSourceSeal({ + platform: input.platform, lock: input.lock, lockDigest, executableDigest, seal, + }); + } catch (cause) { + throw new CuaDriverProviderSealError("catalog_source_build_seal_invalid", input.paths.sealPath, cause); + } + } if (seal.lockSha256 !== lockDigest) { throw new CuaDriverProviderSealError("provider_seal_lock_digest_mismatch", input.paths.sealPath); } if (input.platform === "darwin") { - const darwinSeal = seal as DarwinBundledProviderSealV1; - if (darwinSeal.executableSha256 !== executableDigest - || darwinSeal.executableRelativePath + if (seal.componentId !== "cua-driver-darwin" || seal.executableSha256 !== executableDigest + || seal.executableRelativePath !== cuaDriverArtifactLayoutFor("darwin").packagedExecutableName) { throw new CuaDriverProviderSealError("provider_seal_executable_digest_mismatch", input.paths.executablePath); } @@ -195,7 +245,7 @@ function assertCommonSeal(value: Readonly>): void { } } -function assertDarwinSeal(value: Readonly>): void { +function assertDarwinSeal(value: Readonly>, catalogSourceBuild: boolean): void { if (value.schemaVersion !== 1 || value.componentId !== "cua-driver-darwin" || value.executableRelativePath @@ -205,7 +255,7 @@ function assertDarwinSeal(value: Readonly>): void { if (!isSha256(value.executableSha256) || !Array.isArray(value.architectures) || value.architectures.join(",") !== "arm64") { throw new CuaDriverProviderSealError("provider_seal_darwin_binary_mismatch"); } - if (value.hardenedRuntime !== true || !hasText(value.codeIdentifier) || !hasText(value.teamId) || !hasText(value.designatedRequirement)) { + if (value.hardenedRuntime !== !catalogSourceBuild || !hasText(value.codeIdentifier) || !hasText(value.teamId) || !hasText(value.designatedRequirement)) { throw new CuaDriverProviderSealError("provider_seal_darwin_signing_mismatch"); } if (!isSha256(value.designatedRequirementSha256) || !isSha256(value.entitlementsCanonicalSha256)) { diff --git a/apps/desktop/main/cua-driver/runtime-trust-policy.ts b/apps/desktop/main/cua-driver/runtime-trust-policy.ts index 227c121f7..4541c98a3 100644 --- a/apps/desktop/main/cua-driver/runtime-trust-policy.ts +++ b/apps/desktop/main/cua-driver/runtime-trust-policy.ts @@ -26,11 +26,12 @@ interface CuaDriverRuntimeTrustPolicyBaseV1 { readonly platform: Exclude; } -export interface DarwinCuaDriverRuntimeTrustPolicyV1 - extends CuaDriverRuntimeTrustPolicyBaseV1 { - readonly platform: "darwin"; - readonly expectedTeamId: string; -} +export type DarwinCuaDriverRuntimeTrustPolicyV1 = CuaDriverRuntimeTrustPolicyBaseV1 + & { readonly platform: "darwin" } + & ( + | { readonly expectedTeamId: string; readonly signatureMode?: never } + | { readonly expectedTeamId?: never; readonly signatureMode: "ad-hoc" } + ); export interface Win32CuaDriverRuntimeTrustPolicyV1 extends CuaDriverRuntimeTrustPolicyBaseV1 { @@ -131,6 +132,12 @@ export async function loadCuaDriverRuntimeTrustPolicy( ) { throw new CuaDriverRuntimeTrustPolicyError("schema_invalid", resource.path); } + if (policy.platform === "darwin" && ( + (policy.signatureMode === "ad-hoc") + !== (options.authority.providerSource === "official-cache" && options.authority.signingTier === "unsigned_dev") + )) { + throw new CuaDriverRuntimeTrustPolicyError("schema_invalid", resource.path); + } return policy; } catch (error) { if (error instanceof CuaDriverRuntimeTrustPolicyError) { @@ -160,6 +167,16 @@ export function validateCuaDriverRuntimeTrustPolicy( } if (platform === "darwin") { + const common = { + schemaVersion: 1, + componentId: "cua-driver", + distributionRevision: CUA_DRIVER_DISTRIBUTION_REVISION, + platform: "darwin", + } as const; + if (value.signatureMode === "ad-hoc") { + assertExactKeys(value, [...Object.keys(common), "signatureMode"]); + return Object.freeze({ ...common, signatureMode: "ad-hoc" as const }); + } assertExactKeys(value, [ "schemaVersion", "componentId", @@ -171,10 +188,7 @@ export function validateCuaDriverRuntimeTrustPolicy( throw new CuaDriverRuntimeTrustPolicyError("schema_invalid"); } return Object.freeze({ - schemaVersion: 1, - componentId: "cua-driver", - distributionRevision: CUA_DRIVER_DISTRIBUTION_REVISION, - platform: "darwin", + ...common, expectedTeamId: value.expectedTeamId, }); } diff --git a/apps/desktop/main/desktop-runtime.ts b/apps/desktop/main/desktop-runtime.ts index b651456c2..e483ffc8f 100644 --- a/apps/desktop/main/desktop-runtime.ts +++ b/apps/desktop/main/desktop-runtime.ts @@ -114,6 +114,8 @@ export interface DesktopRuntimeOptions { readonly workspaceCwd: string; readonly resourcesRoot: string; readonly cuaDriverProviderResourcesPath?: string; + readonly cuaDriverRuntimeChecksums?: Readonly>; + readonly cuaDriverCatalogSourceBuild?: boolean; readonly userDataPath: string; readonly platform?: string; readonly architecture?: string; @@ -720,6 +722,8 @@ export class DesktopRuntime { platform, architecture, resourcesPath: this.options.cuaDriverProviderResourcesPath ?? this.resourcesRoot, + runtimeChecksums: this.options.cuaDriverRuntimeChecksums, + catalogSourceBuild: this.options.cuaDriverCatalogSourceBuild, userDataPath: this.userDataPath, workspaceCwd: this.workspaceCwd, daemonBaseUrl: this.options.daemonBaseUrl, diff --git a/apps/desktop/main/main.ts b/apps/desktop/main/main.ts index b4d0700c8..9b098a4c0 100644 --- a/apps/desktop/main/main.ts +++ b/apps/desktop/main/main.ts @@ -502,6 +502,10 @@ async function openMainWindowOnce(attempt: DesktopStartupOpenAttempt): Promise} */ +function isRecord(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +/** @param {string} value */ +function sha256(value) { + return createHash("sha256").update(value).digest("hex"); +} diff --git a/apps/desktop/shared/cua-driver-package-authority-contract.mjs b/apps/desktop/shared/cua-driver-package-authority-contract.mjs index e028751f4..070c48efb 100644 --- a/apps/desktop/shared/cua-driver-package-authority-contract.mjs +++ b/apps/desktop/shared/cua-driver-package-authority-contract.mjs @@ -86,7 +86,7 @@ export function validateCuaDriverPackageAuthority(value) { if (!validSigningPair(value.signingTier, value.distributionChannel)) { fail("cua_driver_package_authority_signing_pair_invalid"); } - if (value.providerSource === "official-cache" && value.signingTier !== "production_signed") { + if (value.providerSource === "official-cache" && value.signingTier === "test_signed_internal") { fail("cua_driver_package_authority_cache_signing_invalid"); } if (!isSha256(value.capabilitiesSha256) || !isSha256(value.runtimeTrustPolicySha256)) { diff --git a/apps/desktop/tests/cua-driver-darwin-adapter.test.mjs b/apps/desktop/tests/cua-driver-darwin-adapter.test.mjs index 1f31291a1..396531894 100644 --- a/apps/desktop/tests/cua-driver-darwin-adapter.test.mjs +++ b/apps/desktop/tests/cua-driver-darwin-adapter.test.mjs @@ -688,6 +688,7 @@ function createIdentityFixture(options = {}) { teamId: TEAM_ID, architectures: ["arm64"], codeIdentifier: IDENTIFIER, + hardenedRuntime: true, cdhashes: CDHASHES, designatedRequirement: REQUIREMENT, designatedRequirementSha256: sha256(REQUIREMENT), diff --git a/apps/desktop/tests/cua-driver-official-cache.test.ts b/apps/desktop/tests/cua-driver-official-cache.test.ts index 4d96792d9..10c27f709 100644 --- a/apps/desktop/tests/cua-driver-official-cache.test.ts +++ b/apps/desktop/tests/cua-driver-official-cache.test.ts @@ -1,7 +1,14 @@ import assert from "node:assert/strict"; -import { join } from "node:path"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join, relative, sep } from "node:path"; import test from "node:test"; +import { DarwinCuaDriverIdentityVerifier } from "../dist/main/cua-driver/adapters/darwin-identity.js"; +import { readCuaDriverProviderLock } from "../dist/main/cua-driver/artifact-lock.js"; import { resolveDesktopCuaDriverPackagedStartupAuthority } from "../dist/main/cua-driver/packaged-startup.js"; +import { verifyCuaDriverProviderArtifacts } from "../dist/main/cua-driver/provider-seal.js"; +import { resolveCuaDriverResourcePaths } from "../dist/main/cua-driver/resource-path.js"; const input = { packaged: true, @@ -55,14 +62,89 @@ test("official cache selection keeps the Desktop policy and never falls back to async readOfficialRuntime(request) { assert.equal(request.lingVersion, input.lingVersion); assert.equal(request.executable, "runtime/providers/cua-driver/0.8.3-ling.1/darwin/ling-cua-driver"); - return { root: cachedRoot, executablePath: join(cachedRoot, request.executable), version: "0.2.0" }; + return { + root: cachedRoot, executablePath: join(cachedRoot, request.executable), version: "0.2.0", + runtimeChecksums: { [request.executable]: "c".repeat(64) }, + }; }, }); assert.equal(selected.runtimeEligible, true); assert.equal(selected.policy, policy); assert.equal(selected.providerResourcesPath, join(cachedRoot, "runtime")); + assert.equal(Object.values(selected.runtimeChecksums ?? {})[0], "c".repeat(64)); }); +test("catalog source providers require both the verified runtime inventory and the observed ad-hoc identity", async (t) => { + const root = await mkdtemp(join(tmpdir(), "ling-cua-catalog-source-test-")); + t.after(() => rm(root, { force: true, recursive: true })); + const platform = "darwin" as const; + const architecture = "arm64" as const; + const paths = resolveCuaDriverResourcePaths({ resourcesPath: root, platform, architecture }); + const lockDocument = JSON.parse(await readFile(new URL( + "../resources/providers/cua-driver/0.8.3-ling.1/provider-lock.json", import.meta.url, + ), "utf8")); + const executable = "fixture"; + const license = "fixture license"; + lockDocument.platforms.darwin.sourceBuild.binarySha256BeforeSigning = sha256(executable); + lockDocument.upstream.licenseSha256 = sha256(license); + const lockBytes = JSON.stringify(lockDocument); + const cdhash = "c".repeat(40); + const requirement = `cdhash H"${cdhash}"`; + const seal = { + schemaVersion: 1, componentId: "cua-driver-darwin", platform, + signingTier: "unsigned_dev", distributionChannel: "development", productionEligible: false, + lockSha256: sha256(lockBytes), providerVersion: "0.8.3", distributionRevision: "ling.1", + executableRelativePath: "ling-cua-driver", executableSha256: sha256(executable), + architectures: ["arm64"], cdhashes: { arm64: cdhash }, codeIdentifier: "ling-cua-driver-presign", + teamId: "not set", designatedRequirement: requirement, designatedRequirementSha256: sha256(requirement), + hardenedRuntime: false, entitlementsCanonicalSha256: sha256("{}"), + serverInitializeProtocolVersion: "2025-06-18", healthSchemaVersion: "1", stateSchemaVersion: 1, + toolsListCanonicalSha256: lockDocument.platforms.darwin.compatibility.toolsListSha256, + }; + const files = new Map([ + [paths.lockPath, lockBytes], [paths.licensePath, license], [paths.noticesPath, "notices"], + [paths.executablePath, executable], [paths.sealPath, JSON.stringify(seal)], + ]); + await mkdir(dirname(paths.executablePath), { recursive: true }); + for (const [path, bytes] of files) await writeFile(path, bytes); + const lock = await readCuaDriverProviderLock(paths.lockPath, { platform, architecture }); + const runtimeChecksums = Object.fromEntries([...files].map(([path, bytes]) => [ + `runtime/${relative(root, path).split(sep).join("/")}`, sha256(bytes), + ])); + let hasEntitlements = false; + const platformIdentityVerifier = new DarwinCuaDriverIdentityVerifier({ + signatureMode: "ad-hoc", + runner: { async run({ executable, args }) { + if (executable.endsWith("/lipo")) return { stdout: "arm64", stderr: "" }; + if (executable.endsWith("/otool")) return { stdout: "Load command 1\n cmd LC_BUILD_VERSION\n minos 13.0\n", stderr: "" }; + if (args.includes("--requirements")) return { stdout: "", stderr: `# designated => ${requirement}` }; + if (args.includes("--entitlements")) { + return { stdout: hasEntitlements ? "" : "", stderr: `Executable=${paths.executablePath}` }; + } + if (args.includes("--verify")) return { stdout: "", stderr: "" }; + return { stdout: "", stderr: `Identifier=ling-cua-driver-presign\nTeamIdentifier=not set\nCDHash=${cdhash}\nCodeDirectory flags=0x2(adhoc)\nSignature=adhoc` }; + } }, + }); + const input = { platform, architecture, paths, lock, runtimeChecksums, platformIdentityVerifier }; + await assert.rejects(verifyCuaDriverProviderArtifacts(input), /provider_seal_darwin_signing_mismatch/u); + await assert.rejects(verifyCuaDriverProviderArtifacts({ + ...input, runtimeChecksums: undefined, catalogSourceBuild: true, + }), /catalog_source_build_authority_missing/u); + await verifyCuaDriverProviderArtifacts({ ...input, catalogSourceBuild: true }); + + hasEntitlements = true; + await assert.rejects(verifyCuaDriverProviderArtifacts({ ...input, catalogSourceBuild: true }), /platform_identity_invalid/u); + hasEntitlements = false; + await writeFile(paths.noticesPath, "changed notices"); + await assert.rejects(verifyCuaDriverProviderArtifacts({ + ...input, catalogSourceBuild: true, + }), /catalog_runtime_checksum_mismatch/u); +}); + +function sha256(value: string): string { + return createHash("sha256").update(value).digest("hex"); +} + test("an invalid Desktop policy prevents selecting a downloaded provider", async () => { const failure = new Error("policy digest changed"); const startup = await resolveDesktopCuaDriverPackagedStartupAuthority(input, { diff --git a/apps/desktop/tests/plugin-packaging-config.test.ts b/apps/desktop/tests/plugin-packaging-config.test.ts index 042f82a8b..79d10c6f6 100644 --- a/apps/desktop/tests/plugin-packaging-config.test.ts +++ b/apps/desktop/tests/plugin-packaging-config.test.ts @@ -63,8 +63,13 @@ test("candidate verification checks the catalog authority and its actual package }); const metadata = { [CUA_DRIVER_PACKAGE_AUTHORITY_METADATA_KEY]: hostAuthority }; const ordinaryMetadata = { [CUA_DRIVER_PACKAGE_AUTHORITY_METADATA_KEY]: createExternalOnlyCuaDriverPackageAuthority() }; - assert.equal(await verifyCandidateCuaDriverAuthority(ordinaryMetadata, resources, "darwin", false), "external-only"); - assert.equal(await verifyCandidateCuaDriverAuthority(metadata, resources, "darwin", true), "official-cache"); + assert.deepEqual(await verifyCandidateCuaDriverAuthority(ordinaryMetadata, resources, "darwin", false), { + cuaDriverProviderSource: "external-only", + }); + assert.deepEqual(await verifyCandidateCuaDriverAuthority(metadata, resources, "darwin", true, "production_signed"), { + cuaDriverProviderSource: "official-cache", cuaDriverProviderSigningTier: "production_signed", + }); + await assert.rejects(verifyCandidateCuaDriverAuthority(metadata, resources, "darwin", true, "unsigned_dev"), /signing tier/u); await assert.rejects(verifyCandidateCuaDriverAuthority(metadata, resources, "darwin", false), /requested build/u); await assert.rejects(verifyCandidateCuaDriverAuthority(metadata, resources, "win32", true), /requested build/u); await assert.rejects(verifyCandidateCuaDriverAuthority(ordinaryMetadata, resources, "darwin", true), /requested build/u); @@ -78,7 +83,35 @@ test("candidate verification checks the catalog authority and its actual package providerSource: "official-cache", signingProfile, providerSigner: winSigner, catalogSigner: winSigner, }); const winMetadata = { [CUA_DRIVER_PACKAGE_AUTHORITY_METADATA_KEY]: winAuthority }; - assert.equal(await verifyCandidateCuaDriverAuthority(winMetadata, winResources, "win32", true), "official-cache"); + assert.deepEqual(await verifyCandidateCuaDriverAuthority(winMetadata, winResources, "win32", true, "production_signed"), { + cuaDriverProviderSource: "official-cache", cuaDriverProviderSigningTier: "production_signed", + }); await writeFile(runtimeTrustPolicyPath, "{}"); await assert.rejects(verifyCandidateCuaDriverAuthority(winMetadata, winResources, "win32", true), /does not match app.asar/u); }); + +test("the catalog candidate creates a trust policy on both platforms without publisher certificates", async t => { + const root = await mkdtemp(join(tmpdir(), "ling-catalog-source-candidates-")); + t.after(() => rm(root, { recursive: true, force: true })); + for (const [platform, target] of [["darwin", "darwin"], ["win32-x64", "win32"]] as const) { + const resources = join(root, target); + const { hostAuthority, runtimeTrustPolicy } = await writeCuaDriverPackageAuthorityFiles({ + outputRoot: join(resources, "providers", "cua-driver"), platform, providerSource: "official-cache", + signingProfile: { signingTier: "unsigned_dev", distributionChannel: "development" }, + }); + assert.ok(hostAuthority.providerExpected); + assert.equal(hostAuthority.signingTier, "unsigned_dev"); + if (target === "darwin") { + assert.ok(runtimeTrustPolicy.platform === "darwin" && "signatureMode" in runtimeTrustPolicy); + assert.equal(runtimeTrustPolicy.signatureMode, "ad-hoc"); + } else { + assert.equal(runtimeTrustPolicy.platform, "win32"); + if (runtimeTrustPolicy.platform !== "win32") assert.fail("Windows policy required"); + assert.equal(runtimeTrustPolicy.signingPolicy.signingTier, "unsigned_dev"); + } + const metadata = { [CUA_DRIVER_PACKAGE_AUTHORITY_METADATA_KEY]: hostAuthority }; + assert.deepEqual(await verifyCandidateCuaDriverAuthority(metadata, resources, target, true, "unsigned_dev"), { + cuaDriverProviderSource: "official-cache", cuaDriverProviderSigningTier: "unsigned_dev", + }); + } +}); diff --git a/docs/design/integrations/plugin-independent-packaging.md b/docs/design/integrations/plugin-independent-packaging.md index 4934c938c..42c055745 100644 --- a/docs/design/integrations/plugin-independent-packaging.md +++ b/docs/design/integrations/plugin-independent-packaging.md @@ -2,7 +2,7 @@ ## state -The package sources, builds, and release documents are maintained according to runtime responsibility. This repository provides dual-platform development candidate archives for PDF Documents and Office Processing; Office Documents, Chrome, and Cua Driver maintain their native or extension sources and release processes in their respective repositories. Desktop also provides two-platform thin packages for manual trial. The official plug-in catalog is pending release, and the required macOS Developer ID signing and notarization, Windows Authenticode signing, and Cua Driver integrity catalog signing are not yet ready. Desktop uses compatible packaging by default, and will be switched after officially signed assets and the official catalog pass installation acceptance. +Office Documents, Ling for Chrome, and Cua Driver maintain their sources, builds, and release instructions in their own repositories. This repository provides macOS and Windows development archives for PDF Documents and Office Processing. Desktop has thin packages for manual trial and uses compatibility packaging by default until catalog installation and runtime acceptance pass on both platforms. The upstream installation, runtime integration, and built-in migration of gstack are documented by [gstack Optional Plug-in Design](../agents/gstack-optional-plugin.md), with status as proposal. @@ -33,7 +33,7 @@ The daemon verifies the archive signature and decompresses it to the staging dir Select records to save the current version and the previous version in the same atomic replacement. Recheck packages, platforms, and Ling versions before rolling back. When the user exits normally and then restarts Ling, Desktop verifies the selected version of the running file offline and takes over the new process. The workspace reads the version and rollback status of the same user-level signed package, and each saves the plug-in enablement status, authorization, and auditing. The plugin still needs to be enabled in the workspace after installing the package for the first time. -Office helper and Chrome Native Host preferentially use verified caches, and compatible builds can use in-package resources. The Cua Driver's on-demand mode is provided by the Desktop package to run the trust policy. It inherits platform code signing, system permissions, interactive sessions, process isolation, and lease checks. When Cua Driver has no cache, it retains the Desktop management boundary, and external processes cannot obtain the managed running rights. +The Office helper and Chrome Native Host prefer verified caches. Compatibility builds can also use their bundled copies. A Desktop build with the Cua Driver catalog policy validates the signed runtime inventory and keeps that inventory in memory. It rechecks the provider files against those digests before spawning. The macOS policy checks the binary's ad-hoc signature, architecture and deployment target. The Windows policy checks the standard x64 PE and requires an unsigned binary without a Windows integrity catalog. The provider still runs under Desktop's system permissions, interactive session, process isolation and leases. Without a verified cache, Desktop cannot start the managed Cua Driver. Desktop retains up to two generations of validated GStack runtimes. When the cache is full for two generations, Desktop starts and parses existing runtimes by summary of task and workspace records. Snapshot releases for third-generation packages are delayed, and uninitialized workspaces are also waiting. Older versions of Desktop can read the same cache. Before recycling, you need to confirm the repo-local workspace, rollback snapshots and frozen task references. Currently, there is no complete basis for recycling. Unknown directories, tampering, incomplete writes, and failed checksums will still prevent booting. [GStack Resource Retention Convention](../agents/gstack-bundled-client-upgrade.md#source-publication-and-upgrade) @@ -56,7 +56,9 @@ The default `assemble` operation downloads both platform ZIPs and their `.zip.js } ``` -Release records should include platform signatures, actual operation, third-party licenses and source code evidence. Cua Driver only accepts locked builds and production signed payloads that have been elevated for the corresponding platform, and saves the seal, lock file, and license with the package. Windows also requires a verified integrity catalog. +To retain an earlier version for installation followed by update and offline rollback, provide an array of distinct release pins for that plugin. Each pin must satisfy the same tag, source, and asset checks. All versions of Cua Driver in one catalog snapshot use the same provider signature policy. + +Release records include the observed OS signature status, runtime results, third-party licenses, and source evidence. The catalog verifies each Cua Driver archive against the lock at the pinned source commit. For the open-source distribution, the runtime seal records the locked ad-hoc macOS binary or unsigned Windows PE. Ling authenticates the catalog, the archive and the installed runtime inventory with Ed25519. A Cua Driver package with a production platform signature follows its separate publisher verification policy and includes the signed Windows integrity catalog on Windows. ## candidate build evidence @@ -75,7 +77,7 @@ Before downloading, you can check the source code submission, platform signature | [Ling for Chrome v0.1.1-dev.1](https://github.com/ling-stack-org/ling-plugin-chrome-browser/releases/tag/v0.1.1-dev.1) | `.ling-plugin.zip` | 290,624 | 189,875 | | [Cua Driver v0.2.0-dev.1](https://github.com/ling-stack-org/ling-plugin-cua-driver/releases/tag/v0.2.0-dev.1) | Before signing `.tar.gz` | 6,690,425 | 7,140,210 | -Development kits for Office and Chrome are available for trial use in source code environments. Cua Driver provides dual-platform pre-signing archiving for build reproduction and signature preparation. The official catalog uses platform-signed stable assets. +Development kits for Office and Chrome are available for trial use in source code environments. Cua Driver's pre-signing archives preserve the audited build inputs. The official catalog selects reviewed stable assets with matching producer sidecars. ### Desktop installation package comparison @@ -133,8 +135,8 @@ Both macOS profiles launched from a verified DMG copy, connected to their Desktop-managed daemon, and exited normally. Both Windows profiles passed installation, launch, same-version replacement, and uninstall. The public trial ships the on-demand archives and SHA-256 checksums for manual download. Official -catalog installation, native operations, update, and offline rollback still -require signed plugin releases and runtime acceptance. +catalog installation, native operations, updates and offline rollback require +separate acceptance with the Ed25519 catalog. [Desktop v0.1.0 pre-release](https://github.com/ling-stack-org/ling-stack/releases/tag/v0.1.0) ### macOS already has configuration switching @@ -162,7 +164,7 @@ The same three-stage process uses the public `v0.6.2-alpha.1` Setup as the third ## Thin package comparison and switching 1. Build thin packages that are compatible with the baseline and `LING_PLUGIN_EXTERNAL_ONLY=1` respectively, on the same independently reviewed source code commits and toolchains. Pre-publishing checks still need to be done through the platform's original Desktop. -2. Build the Cua Driver acceptance package with `catalog_managed_cua=true` and the reviewed platform signer identities. Confirm the package verification report records `cuaDriverProviderSource: official-cache`. [Desktop candidate workflow](../../release/github-actions.md#each-release) +2. Build the thin acceptance package with `catalog_managed_cua=true`. Confirm that the package report records `cuaDriverProviderSource: official-cache` and that the build uses the open-source catalog runtime policy. [Desktop candidate workflow](../../release/github-actions.md#each-release) 3. Verify offline boot and existing configuration migration on macOS arm64 and Windows x64 installations. Each platform downloads Office, Chrome and Cua Driver from the official signature directory for the first time. After restarting Desktop, perform Excel workbook operation, Chrome Native Messaging operation and Computer Use operation respectively. macOS's `office-local.node` is used by Desktop's file-level Office capabilities and is subject to the same set of independent reviews. 4. Each plugin verifies updates with a second signed version, and after a reboot checks the actual running version. Disconnect the network, roll back and restart, and recheck the actual call and workspace configuration of the previous version. Logs directory commits, platform signatures, version and SHA-256 of actual running files, first download size, DMG and EXE bytes. Desktop package reports provide `pluginMode` and `installedPayloadBytes`. 5. After the platform acceptance is passed, the default packaging will be switched, the duplicate native builds, resources and source codes of the three plug-ins will be cleaned up, and the Desktop release instructions will be updated. diff --git a/docs/release/github-actions.md b/docs/release/github-actions.md index 96c0ea406..02d033d45 100644 --- a/docs/release/github-actions.md +++ b/docs/release/github-actions.md @@ -65,15 +65,14 @@ pointed to by every published tag. manifest collects the native sources and licenses actually bundled for the selected mode, and archive verification checks that mode. - For Cua Driver acceptance, configure repository variables - `LING_CUA_DARWIN_EXPECTED_TEAM_ID`, `LING_CUA_PROVIDER_SIGNER_SUBJECT`, - `LING_CUA_PROVIDER_SIGNER_SHA256`, `LING_CUA_CATALOG_SIGNER_SUBJECT`, and - `LING_CUA_CATALOG_SIGNER_SHA256` with the reviewed provider signing identities. - These values are public certificate metadata. Run with `catalog_managed_cua=true`, - `plugin_mode=on-demand`, and `create_draft=false`. The development installer - embeds the provider trust policy and reports `cuaDriverProviderSource: official-cache`. - Verify installation and operation using the independently signed provider after - launch. + For open-source Cua Driver acceptance, run with `catalog_managed_cua=true`, + `plugin_mode=on-demand`, and `create_draft=false`. The installer embeds + the provider trust policy and reports `cuaDriverProviderSource: official-cache` + and `cuaDriverProviderSigningTier: unsigned_dev`. + Install the provider from the Ling Ed25519 catalog, restart Desktop and verify + the provider operation. The macOS provider uses ad-hoc signing and the Windows + provider has no Authenticode signature. No platform certificate variables are + required for this candidate. 4. Download and inspect the generated installer, per-platform verification JSON, distribution archive, and `checksums.txt`. Mac produces an arm64 DMG/ZIP; Windows produces an x64 Setup diff --git a/packages/contracts/src/cua-driver-bundled.ts b/packages/contracts/src/cua-driver-bundled.ts index 1ff52df69..b0cd7f399 100644 --- a/packages/contracts/src/cua-driver-bundled.ts +++ b/packages/contracts/src/cua-driver-bundled.ts @@ -357,7 +357,17 @@ export interface DarwinBundledProviderSealV1 { readonly stateSchemaVersion: 1; } -export type BundledCuaDriverProviderSeal = DarwinBundledProviderSealV1 | WindowsBundledProviderSealV2; +export interface DarwinCatalogSourceProviderSeal extends Omit { + readonly hardenedRuntime: false; + readonly signingTier: "unsigned_dev"; + readonly distributionChannel: "development"; + readonly productionEligible: false; +} + +export type BundledCuaDriverProviderSeal = + | DarwinBundledProviderSealV1 + | DarwinCatalogSourceProviderSeal + | WindowsBundledProviderSealV2; export interface BundledCuaDriverUpstreamV1 { readonly repository: "https://github.com/trycua/cua"; diff --git a/packages/core/src/official-plugin-runtime.ts b/packages/core/src/official-plugin-runtime.ts index 7d5994e9f..bb507fc25 100644 --- a/packages/core/src/official-plugin-runtime.ts +++ b/packages/core/src/official-plugin-runtime.ts @@ -95,7 +95,12 @@ export async function readVerifiedOfficialPluginRuntime(input: { readonly platform?: string; readonly arch?: string; readonly publicKey?: string; -}): Promise<{ readonly root: string; readonly executablePath: string; readonly version: string } | undefined> { +}): Promise<{ + readonly root: string; + readonly executablePath: string; + readonly version: string; + readonly runtimeChecksums: Readonly>; +} | undefined> { const cacheDir = input.cacheDir ?? resolveUserConfigPaths().pluginCacheDir; let pointer; try { @@ -144,13 +149,13 @@ export async function readVerifiedOfficialPluginRuntime(input: { throw new Error("Official plugin runtime does not match this Ling release and platform."); } const runtimeFiles = await listRuntimeFiles(root, join(root, "runtime")); - const expectedFiles = Object.keys(index.files).filter(safeRuntimePath); - if (runtimeFiles.length !== expectedFiles.length) throw new Error("Official plugin runtime file inventory changed."); + const runtimeChecksums = Object.fromEntries(Object.entries(index.files).filter(([path]) => safeRuntimePath(path))); + if (runtimeFiles.length !== Object.keys(runtimeChecksums).length) throw new Error("Official plugin runtime file inventory changed."); for (const key of runtimeFiles) { const path = join(root, key); - const expected = index.files[key]; + const expected = runtimeChecksums[key]; const info = await lstat(path); - if (!Object.hasOwn(index.files, key) || !digestPattern.test(expected ?? "") + if (!Object.hasOwn(runtimeChecksums, key) || !digestPattern.test(expected ?? "") || !info.isFile() || info.size > nativeFileLimit || await realpath(path) !== path) { throw new Error("Official plugin runtime file is invalid."); } @@ -162,7 +167,7 @@ export async function readVerifiedOfficialPluginRuntime(input: { if (platform === "darwin" && !((await lstat(executablePath)).mode & 0o100)) { throw new Error("Official plugin runtime executable mode is missing."); } - return { root, executablePath, version: pointer.version }; + return { root, executablePath, version: pointer.version, runtimeChecksums: Object.freeze(runtimeChecksums) }; } async function readMetadata(path: string): Promise { diff --git a/scripts/ci/plugin-catalog-collection.test.ts b/scripts/ci/plugin-catalog-collection.test.ts new file mode 100644 index 000000000..3d218dea6 --- /dev/null +++ b/scripts/ci/plugin-catalog-collection.test.ts @@ -0,0 +1,238 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { CUA_DRIVER_PACKAGE_REVISION } from "../../apps/desktop/scripts/cua-driver-package-staging-contract.mjs"; +import { readVerifiedReleaseAsset, reviewedReleasePins, verifyRuntimeMembers } from "../plugins/collect-official-releases.mjs"; + +const cuaRoot = `runtime/providers/cua-driver/${CUA_DRIVER_PACKAGE_REVISION}`; +const committedLock = new URL(`../../apps/desktop/resources/providers/cua-driver/${CUA_DRIVER_PACKAGE_REVISION}/provider-lock.json`, import.meta.url); +const winCatalog = `${cuaRoot}/win32-x64/provider-integrity.cat`; +const mainPe = "payload/ling-cua-driver.exe"; +const limits = ["elevated_pixel_input", "uwp_send_input"]; + +test("catalog inputs accept a single reviewed release or a unique sequence ordered by stable version", () => { + const pin = (tag: string) => ({ + tag, + sourceSha: "a".repeat(40), + sha256: { "darwin-arm64": sha256(`darwin ${tag}`), "win32-x64": sha256(`win32 ${tag}`) }, + }); + const old = pin("v0.9.9"); + const next = pin("v0.10.0"); + const newest = pin("v1.0.0"); + const pluginId = "official:cua-driver"; + assert.deepEqual(reviewedReleasePins(old, pluginId), [old]); + assert.deepEqual(reviewedReleasePins([next, newest, old], pluginId), [old, next, newest]); + assert.throws(() => reviewedReleasePins([old, old], pluginId), /Duplicate stable release pin/u); + assert.throws(() => reviewedReleasePins([old, pin("v0.10.0-dev.1")], pluginId), /stable tag/u); + assert.throws(() => reviewedReleasePins({ ...next, sha256: { "darwin-arm64": sha256("Darwin only") } }, pluginId), /asset digests/u); +}); + +test("collection requires downloaded bytes, GitHub metadata and the review pin to agree", async (t) => { + const root = await mkdtemp(join(tmpdir(), "ling-plugin-release-asset-")); + t.after(() => rm(root, { recursive: true, force: true })); + const archiveName = "official-cua-driver.ling-plugin.zip"; + const bytes = Buffer.from("the reviewed release asset"); + const digest = sha256(bytes); + const asset = { name: archiveName, state: "uploaded", size: bytes.length, digest: `sha256:${digest}` }; + await writeFile(join(root, archiveName), bytes); + assert.deepEqual(await readVerifiedReleaseAsset(root, [asset], archiveName, 1024, digest), bytes); + await assert.rejects(readVerifiedReleaseAsset(root, [asset], archiveName, 1024, sha256("another pin")), /GitHub release asset metadata/u); + await assert.rejects(readVerifiedReleaseAsset(root, [{ ...asset, digest: null }], archiveName, 1024), /GitHub release asset metadata/u); + bytes[0] ^= 1; + await writeFile(join(root, archiveName), bytes); + await assert.rejects(readVerifiedReleaseAsset(root, [asset], archiveName, 1024, digest), /Downloaded release asset digest/u); +}); + +test("macOS source packages require the pinned lock, source build and honest ad-hoc seal", async () => { + const { members, seal, lockDigest, sealPath, executablePath } = await providerFixture("darwin"); + await verifyProvider(members, "darwin", lockDigest); + await assert.rejects(verifyProvider(members, "darwin", sha256("another source lock")), /differs from the reviewed source commit/u); + await assert.rejects( + verifyProvider({ ...members, [sealPath]: JSON.stringify({ ...seal, teamId: "NotSigned", productionEligible: true }) }, "darwin", lockDigest), + /source seal does not match/u, + ); + const changedBinary = "a different provider binary"; + await assert.rejects( + verifyProvider({ ...members, [executablePath]: changedBinary, + [sealPath]: JSON.stringify({ ...seal, executableSha256: sha256(changedBinary) }) }, "darwin", lockDigest), + /does not describe the locked ad-hoc binary/u, + ); +}); + +test("Windows collection requires a production integrity catalog and rejects one for unsigned source packages", async () => { + const { members, seal, lockDigest, sealPath } = await providerFixture("win32"); + await verifyProvider(members, "win32", lockDigest); + await assert.rejects(verifyProvider({ ...members, [winCatalog]: "unexpected" }, "win32", lockDigest), /Unexpected Cua Driver runtime members/u); + await assert.rejects( + verifyProvider({ ...members, [`${cuaRoot}/win32-x64/payload/another.exe`]: "unexpected" }, "win32", lockDigest), + /Unexpected Cua Driver runtime members/u, + ); + const productionMembers = { + ...members, + [sealPath]: JSON.stringify({ + ...seal, + signingTier: "production_signed", + distributionChannel: "production", + productionEligible: true, + integrityCatalogRelativePath: "provider-integrity.cat", + }), + }; + await assert.rejects(verifyProvider(productionMembers, "win32", lockDigest), /requires an integrity catalog/u); + await verifyProvider({ ...productionMembers, [winCatalog]: "fixture catalog" }, "win32", lockDigest); +}); + +test("collection rejects a file missing from the signed checksum index", async () => { + const { members, lockDigest } = await providerFixture("win32"); + const { zip, index } = archiveFixture({ ...members, "extra.txt": "unindexed" }); + delete index.files["extra.txt"]; + await assert.rejects(verifyRuntimeMembers(zip, index, "official:cua-driver", "win32", lockDigest), /unexpected member extra\.txt/u); +}); + +async function verifyProvider(members: Record, platform: "darwin" | "win32", lockDigest: string) { + const { zip, index } = archiveFixture(members); + await verifyRuntimeMembers(zip, index, "official:cua-driver", platform, lockDigest); +} + +function archiveFixture(members: Record) { + const files = Object.fromEntries(Object.entries(members).map(([name, bytes]) => [name, { + name, + dir: false, + async async() { return Buffer.from(bytes); }, + }])); + const index = { + algorithm: "sha256", + files: Object.fromEntries(Object.entries(members).map(([name, bytes]) => [name, sha256(bytes)])), + }; + return { zip: { files, file: (path: string) => files[path] ?? null }, index }; +} + +async function providerFixture(platform: "darwin" | "win32") { + const license = "fixture license"; + const executable = "fixture source build"; + const executableDigest = sha256(executable); + const lock = JSON.parse(await readFile(committedLock, "utf8")); + lock.upstream.licenseSha256 = sha256(license); + const darwin = lock.platforms.darwin; + darwin.sourceBuild.binarySha256BeforeSigning = executableDigest; + if (platform === "win32") { + lock.enabledPlatforms = ["win32-x64"]; + lock.platforms = { win32X64: windowsLock(darwin, executableDigest) }; + } + const platformLock = platform === "darwin" ? darwin : lock.platforms.win32X64; + const lockBytes = JSON.stringify(lock); + const lockDigest = sha256(lockBytes); + const common = { + platform, + componentId: platformLock.componentId, + lockSha256: lockDigest, + distributionRevision: lock.distributionRevision, + providerVersion: lock.upstream.version, + toolsListCanonicalSha256: platformLock.compatibility.toolsListSha256, + serverInitializeProtocolVersion: platformLock.compatibility.serverInitializeProtocolVersion, + healthSchemaVersion: platformLock.compatibility.healthSchemaVersion, + stateSchemaVersion: platformLock.runtime.stateSchemaVersion, + signingTier: "unsigned_dev", + distributionChannel: "development", + productionEligible: false, + }; + const cdhash = "a".repeat(40); + const requirement = `cdhash H"${cdhash}"`; + const seal = platform === "darwin" ? { + ...common, + schemaVersion: 1, + executableRelativePath: "ling-cua-driver", + executableSha256: executableDigest, + architectures: ["arm64"], + cdhashes: { arm64: cdhash }, + codeIdentifier: "ling-cua-driver-presign", + teamId: "not set", + hardenedRuntime: false, + designatedRequirement: requirement, + designatedRequirementSha256: sha256(requirement), + entitlementsCanonicalSha256: sha256("{}"), + } : { + ...common, + schemaVersion: 2, + limitations: limits, + integrityCatalogRelativePath: null, + main: { + authenticodeStatus: "NotSigned", + architecture: "x86_64", + relativePath: mainPe, + peManifestCanonicalSha256: platformLock.binary.mainManifestCanonicalSha256, + sha256: executableDigest, + }, + }; + const executablePath = `${cuaRoot}/${platform === "darwin" ? "darwin/ling-cua-driver" : `win32-x64/${mainPe}`}`; + const sealPath = `${cuaRoot}/${platform === "darwin" ? "darwin" : "win32-x64/payload"}/provider-seal.json`; + const members = { + ".ling-plugin/plugin.json": "{}", + [`${cuaRoot}/provider-lock.json`]: lockBytes, + [`${cuaRoot}/LICENSE.md`]: license, + [`${cuaRoot}/THIRD_PARTY_NOTICES.md`]: "fixture notices", + [executablePath]: executable, + [sealPath]: JSON.stringify(seal), + }; + return { members, seal, lockDigest, sealPath, executablePath }; +} + +function windowsLock(darwin: Record, mainSha256: string) { + return { + ...darwin, + componentId: "cua-driver-win32-x64", + referenceReleaseArtifact: { + ...darwin.referenceReleaseArtifact, + authenticodeStatus: "unsigned-reference", + binaries: { + "cua-driver.exe": { sha256: sha256("reference main") }, + "cua-driver-uia.exe": { sha256: sha256("reference UIAccess") }, + }, + }, + sourceBuild: { + ...darwin.sourceBuild, + target: "x86_64-pc-windows-msvc", + windowsSdkVersion: "fixture SDK", + msvcToolsetVersion: "fixture MSVC", + binariesSha256BeforeSigning: { main: mainSha256, uiaAuditArtifact: sha256("fixture UIAccess") }, + }, + binary: { + ...darwin.binary, + architecture: "x86_64", + mainRelativePath: mainPe, + providerSealRelativePath: "payload/provider-seal.json", + mainManifestCanonicalSha256: sha256("fixture PE manifest"), + integrityCatalogRelativePathBySigningTier: { + unsigned_dev: null, + test_signed_internal: "provider-integrity.cat", + production_signed: "provider-integrity.cat", + }, + packagedFilesBySigningTier: { unsigned_dev: [mainPe, "payload/provider-seal.json"] }, + uiaAuditArtifact: { + packaged: false, + relativeBuildOutput: "cua-driver-uia.exe", + requestedExecutionLevel: "asInvoker", + uiAccess: true, + manifestCanonicalSha256: sha256("fixture UIAccess manifest"), + }, + }, + runtime: { + ...darwin.runtime, + limitations: limits, + requiredSession: "interactive-user", + rejectSessionZero: true, + managedReadinessMethod: "ling/managed_readiness", + managedReadinessChangedNotification: "ling/managed_readiness_changed", + childInstanceNonceEnvironmentVariable: "CUA_DRIVER_CHILD_INSTANCE_NONCE", + leaseGenerationEnvironmentVariable: "CUA_DRIVER_LEASE_GENERATION", + killOnJobCloseRequired: true, + defaultIntegrityCoverage: "standard", + }, + }; +} + +function sha256(bytes: string | Uint8Array) { + return createHash("sha256").update(bytes).digest("hex"); +} diff --git a/scripts/plugins/collect-official-releases.mjs b/scripts/plugins/collect-official-releases.mjs index 2c48709c9..f3e29ecd1 100644 --- a/scripts/plugins/collect-official-releases.mjs +++ b/scripts/plugins/collect-official-releases.mjs @@ -1,18 +1,10 @@ import { execFileSync } from "node:child_process"; import { createHash, sign } from "node:crypto"; -import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { lstat, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; -import { - validateLingPluginCatalog, - validateLingPluginPackageManifest, -} from "../../packages/plugin-sdk/dist/index.js"; -import { - OFFICIAL_PLUGIN_ARTIFACT_PUBLIC_KEY, - OFFICIAL_PLUGIN_RUNTIME_SIGNATURE_CONTEXT, -} from "../../packages/core/dist/official-plugin-runtime.js"; -import JSZip from "../../packages/daemon/node_modules/jszip/lib/index.js"; import { cuaDriverArtifactLayoutFor, cuaDriverArtifactPlatformForRuntime } from "../../apps/desktop/shared/cua-driver-artifact-layout.mjs"; +import { validateCuaDriverCatalogSourceSeal } from "../../apps/desktop/shared/cua-driver-catalog-source-seal.mjs"; import { validateCuaDriverProviderLockContract } from "../../apps/desktop/shared/cua-driver-provider-lock-contract.mjs"; import { CUA_DRIVER_PACKAGE_REVISION } from "../../apps/desktop/scripts/cua-driver-package-staging-contract.mjs"; import { verifyOfficialReleaseSidecar } from "./official-release-sidecar.mjs"; @@ -27,104 +19,153 @@ const targets = [["darwin", "arm64"], ["win32", "x64"]]; const manifestPath = ".ling-plugin/plugin.json"; const checksumsPath = ".ling-plugin/checksums.json"; const provenancePath = ".ling-plugin/provenance.json"; +const compareStableTags = new Intl.Collator("en", { numeric: true }).compare; -const sources = JSON.parse(process.env.LING_PLUGIN_RELEASE_SOURCES || "null"); -if (sources === null || typeof sources !== "object" || Array.isArray(sources) - || Object.keys(sources).length !== repositories.size - || [...repositories.keys()].some((id) => !Object.hasOwn(sources, id))) { - throw new Error("Release sources must identify each of the three official plugins."); -} -const key = requireOfficialSigningKey(process.env.LING_PLUGIN_ARTIFACT_PRIVATE_KEY, - OFFICIAL_PLUGIN_ARTIFACT_PUBLIC_KEY, "LING_PLUGIN_ARTIFACT_PRIVATE_KEY"); +if (import.meta.main) await collectOfficialReleases(); -const root = await mkdtemp(join(tmpdir(), "ling-plugin-releases-")); -try { - const plugins = []; - for (const [pluginId, repository] of repositories) { - const pin = sources[pluginId]; - if (!pin || !/^v\d+\.\d+\.\d+$/u.test(pin.tag) || !/^[a-f0-9]{40}$/u.test(pin.sourceSha) - || !pin.sha256 || targets.some(([platform, arch]) => !/^[a-f0-9]{64}$/u.test(pin.sha256[`${platform}-${arch}`]))) { - throw new Error(`A stable tag, exact source commit and reviewed asset digests are required for ${pluginId}.`); - } - const published = github(["release", "view", pin.tag, "--repo", repository, "--json", "tagName,isDraft,isPrerelease"]); - const commit = github(["api", `repos/${repository}/commits/${pin.tag}`]); - if (published.tagName !== pin.tag || published.isDraft || published.isPrerelease || commit.sha !== pin.sourceSha) { - throw new Error(`Release ${repository}@${pin.tag} does not match the reviewed source.`); - } - const slug = pluginId.replace(":", "-"); - const version = pin.tag.slice(1); - const artifacts = []; - let metadata; - for (const [platform, arch] of targets) { - const name = `${slug}-${version}-${platform}-${arch}.ling-plugin.zip`; - const path = join(root, name); - github(["release", "download", pin.tag, "--repo", repository, - "--pattern", name, "--pattern", `${name}.json`, "--dir", root], false); - const info = await stat(path); - if (info.size < 1 || info.size > 1024 ** 3) throw new Error(`Unexpected artifact size for ${name}.`); - const bytes = await readFile(path); - const digest = sha256(bytes); - if (digest !== pin.sha256[`${platform}-${arch}`]) throw new Error(`Reviewed artifact digest does not match ${name}.`); - const archive = await JSZip.loadAsync(bytes, { checkCRC32: true }); - const checksums = await readMember(archive, checksumsPath); - const manifest = JSON.parse((await readMember(archive, manifestPath)).toString("utf8")); - const provenance = JSON.parse((await readMember(archive, provenancePath)).toString("utf8")); - validateLingPluginPackageManifest(manifest); - const artifactId = `${pluginId}-${version}-${platform}-${arch}`; - if (manifest.id !== pluginId || manifest.version !== version || manifest.artifactId !== artifactId - || manifest.sourceKind !== "official-remote" || manifest.platform !== platform || manifest.arch !== arch - || provenance.schemaVersion !== 1 || provenance.artifactId !== artifactId || provenance.sourceSha !== pin.sourceSha) { - throw new Error(`Manifest or source identity does not match ${name}.`); +async function collectOfficialReleases() { + const { validateLingPluginCatalog, validateLingPluginPackageManifest } = + await import("../../packages/plugin-sdk/dist/index.js"); + const { OFFICIAL_PLUGIN_ARTIFACT_PUBLIC_KEY, OFFICIAL_PLUGIN_RUNTIME_SIGNATURE_CONTEXT } = + await import("../../packages/core/dist/official-plugin-runtime.js"); + const { default: JSZip } = await import("../../packages/daemon/node_modules/jszip/lib/index.js"); + + const sources = JSON.parse(process.env.LING_PLUGIN_RELEASE_SOURCES || "null"); + if (sources === null || typeof sources !== "object" || Array.isArray(sources) + || Object.keys(sources).length !== repositories.size + || [...repositories.keys()].some((id) => !Object.hasOwn(sources, id))) { + throw new Error("Release sources must identify each of the three official plugins."); + } + const key = requireOfficialSigningKey(process.env.LING_PLUGIN_ARTIFACT_PRIVATE_KEY, + OFFICIAL_PLUGIN_ARTIFACT_PUBLIC_KEY, "LING_PLUGIN_ARTIFACT_PRIVATE_KEY"); + const signature = (bytes) => `ed25519:${sign(null, bytes, key).toString("base64")}`; + + const root = await mkdtemp(join(tmpdir(), "ling-plugin-releases-")); + try { + const plugins = []; + for (const [pluginId, repository] of repositories) { + const pins = reviewedReleasePins(sources[pluginId], pluginId); + const artifacts = []; + const cuaTiers = new Set(); + let metadata; + for (const pin of pins) { + const release = await collectPluginRelease({ + root, pluginId, repository, pin, JSZip, validateLingPluginPackageManifest, signature, + runtimeSignatureContext: OFFICIAL_PLUGIN_RUNTIME_SIGNATURE_CONTEXT, + }); + metadata = release.metadata; + artifacts.push(...release.artifacts); + for (const tier of release.cuaTiers) cuaTiers.add(tier); } - const releaseArtifact = { - artifactId, pluginId, version, platform, arch, - url: `https://github.com/${repository}/releases/download/${pin.tag}/${name}`, - sizeBytes: bytes.length, - sha256: digest, - minLingVersion: manifest.minLingVersion, - maxLingVersion: manifest.maxLingVersion, - rollbackAllowed: manifest.rollbackAllowed, - }; - await verifyOfficialReleaseSidecar(`${path}.json`, releaseArtifact); - await verifyRuntimeMembers(archive, JSON.parse(checksums.toString("utf8")), pluginId, platform); - artifacts.push({ - ...releaseArtifact, - channel: "stable", - signature: signature(bytes), - runtimeChecksumSignature: signature(Buffer.concat([Buffer.from(OFFICIAL_PLUGIN_RUNTIME_SIGNATURE_CONTEXT), checksums])), + if (cuaTiers.size > 1) throw new Error("Cua Driver catalog entries must use a single provider signing tier."); + plugins.push({ + pluginId, + displayName: metadata.displayName, + description: metadata.description, + homepageUrl: `https://github.com/${repository}`, + trustSummary: metadata.trustSummary, + latestStableVersion: metadata.version, + manifest: { + contributions: metadata.contributions, + requiredSecrets: metadata.requiredSecrets, + defaultApprovals: metadata.defaultApprovals, + healthChecks: metadata.healthChecks, + }, + artifacts, }); - metadata ??= manifest; } - plugins.push({ - pluginId, - displayName: metadata.displayName, - description: metadata.description, - homepageUrl: `https://github.com/${repository}`, - trustSummary: metadata.trustSummary, - latestStableVersion: version, - manifest: { - contributions: metadata.contributions, - requiredSecrets: metadata.requiredSecrets, - defaultApprovals: metadata.defaultApprovals, - healthChecks: metadata.healthChecks, + const catalog = { + schemaVersion: 1, + source: { + repository: "ling-stack-org/ling-stack", + releaseTag: "official-plugin-catalog", + sourceSha: process.env.GITHUB_SHA, }, - artifacts, + generatedAt: new Date().toISOString(), + plugins, + }; + validateLingPluginCatalog(catalog); + await writeFile(resolve(process.argv[2] ?? "plugins/catalog.json"), JSON.stringify(catalog, null, 2) + "\n"); + } finally { + await rm(root, { recursive: true, force: true }); + } +} + +/** + * @param {unknown} input + * @param {string} pluginId + * @returns {ReadonlyArray<{ tag: string, sourceSha: string, sha256: Record }>} + */ +export function reviewedReleasePins(input, pluginId) { + const pins = Array.isArray(input) ? input : [input]; + if (pins.length === 0 || pins.some((pin) => !pin || typeof pin.tag !== "string" + || !/^v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u.test(pin.tag) + || pin.tag.slice(1).split(".").some((field) => !Number.isSafeInteger(Number(field))) + || typeof pin.sourceSha !== "string" || !/^[a-f0-9]{40}$/u.test(pin.sourceSha) + || targets.some(([platform, arch]) => { + const digest = pin.sha256?.[`${platform}-${arch}`]; + return typeof digest !== "string" || !/^[a-f0-9]{64}$/u.test(digest); + }))) { + throw new Error(`A stable tag, exact source commit and reviewed asset digests are required for ${pluginId}.`); + } + if (new Set(pins.map((pin) => pin.tag)).size !== pins.length) { + throw new Error(`Duplicate stable release pin for ${pluginId}.`); + } + return [...pins].sort((left, right) => compareStableTags(left.tag, right.tag)); +} + +async function collectPluginRelease({ root, pluginId, repository, pin, JSZip, validateLingPluginPackageManifest, signature, runtimeSignatureContext }) { + const published = github(["api", `repos/${repository}/releases/tags/${pin.tag}`]); + const commit = github(["api", `repos/${repository}/commits/${pin.tag}`, "--jq", "{sha}"]); + if (published.tag_name !== pin.tag || published.draft !== false || published.prerelease !== false || commit.sha !== pin.sourceSha) { + throw new Error(`Release ${repository}@${pin.tag} does not match the reviewed source.`); + } + const sourceLockDigest = pluginId === "official:cua-driver" ? readPinnedCuaLockDigest(repository, pin.sourceSha) : undefined; + const slug = pluginId.replace(":", "-"); + const version = pin.tag.slice(1); + const artifacts = []; + const cuaTiers = new Set(); + let metadata; + for (const [platform, arch] of targets) { + const name = `${slug}-${version}-${platform}-${arch}.ling-plugin.zip`; + const path = join(root, name); + github(["release", "download", pin.tag, "--repo", repository, + "--pattern", name, "--pattern", `${name}.json`, "--dir", root], false); + const digest = pin.sha256[`${platform}-${arch}`]; + const bytes = await readVerifiedReleaseAsset(root, published.assets, name, 1024 ** 3, digest); + await readVerifiedReleaseAsset(root, published.assets, `${name}.json`, 64 * 1024); + const archive = await JSZip.loadAsync(bytes, { checkCRC32: true }); + const checksums = await readMember(archive, checksumsPath); + const manifest = JSON.parse((await readMember(archive, manifestPath)).toString("utf8")); + const provenance = JSON.parse((await readMember(archive, provenancePath)).toString("utf8")); + validateLingPluginPackageManifest(manifest); + const artifactId = `${pluginId}-${version}-${platform}-${arch}`; + if (manifest.id !== pluginId || manifest.version !== version || manifest.artifactId !== artifactId + || manifest.sourceKind !== "official-remote" || manifest.platform !== platform || manifest.arch !== arch + || provenance.schemaVersion !== 1 || provenance.artifactId !== artifactId || provenance.sourceSha !== pin.sourceSha) { + throw new Error(`Manifest or source identity does not match ${name}.`); + } + const releaseArtifact = { + artifactId, pluginId, version, platform, arch, + url: `https://github.com/${repository}/releases/download/${pin.tag}/${name}`, + sizeBytes: bytes.length, + sha256: digest, + minLingVersion: manifest.minLingVersion, + maxLingVersion: manifest.maxLingVersion, + rollbackAllowed: manifest.rollbackAllowed, + }; + await verifyOfficialReleaseSidecar(`${path}.json`, releaseArtifact); + const tier = await verifyRuntimeMembers(archive, JSON.parse(checksums.toString("utf8")), pluginId, platform, sourceLockDigest); + if (tier) cuaTiers.add(tier); + artifacts.push({ + ...releaseArtifact, + channel: "stable", + signature: signature(bytes), + runtimeChecksumSignature: signature(Buffer.concat([Buffer.from(runtimeSignatureContext), checksums])), }); + metadata ??= manifest; } - const catalog = { - schemaVersion: 1, - source: { - repository: "ling-stack-org/ling-stack", - releaseTag: "official-plugin-catalog", - sourceSha: process.env.GITHUB_SHA, - }, - generatedAt: new Date().toISOString(), - plugins, - }; - validateLingPluginCatalog(catalog); - await writeFile(resolve(process.argv[2] ?? "plugins/catalog.json"), JSON.stringify(catalog, null, 2) + "\n"); -} finally { - await rm(root, { recursive: true, force: true }); + return { artifacts, metadata, cuaTiers }; } async function readMember(zip, path) { @@ -133,8 +174,58 @@ async function readMember(zip, path) { return entry.async("nodebuffer"); } -async function verifyRuntimeMembers(zip, index, pluginId, platform) { - if (index.algorithm !== "sha256" || !index.files || !Object.hasOwn(index.files, manifestPath)) { +/** + * @param {string} directory + * @param {readonly { name: string, state: string, size: number, digest: string | null }[]} assets + * @param {string} name + * @param {number} maxBytes + * @param {string} [reviewedDigest] + */ +export async function readVerifiedReleaseAsset(directory, assets, name, maxBytes, reviewedDigest) { + const matches = assets.filter((asset) => asset.name === name); + const [published] = matches; + if (matches.length !== 1 || published.state !== "uploaded" + || !Number.isSafeInteger(published.size) || published.size < 1 || published.size > maxBytes + || typeof published.digest !== "string" || !/^sha256:[a-f0-9]{64}$/u.test(published.digest) + || (reviewedDigest !== undefined && published.digest !== `sha256:${reviewedDigest}`)) { + throw new Error(`GitHub release asset metadata does not match ${name}.`); + } + const path = join(directory, name); + const info = await lstat(path); + if (!info.isFile() || info.size !== published.size) throw new Error(`Unexpected release asset size or type for ${name}.`); + const bytes = await readFile(path); + if (bytes.length !== published.size || published.digest !== `sha256:${sha256(bytes)}`) { + throw new Error(`Downloaded release asset digest does not match ${name}.`); + } + return bytes; +} + +function readPinnedCuaLockDigest(repository, sourceSha) { + const path = `provider/${CUA_DRIVER_PACKAGE_REVISION}/provider-lock.json`; + const file = github(["api", `repos/${repository}/contents/${path}?ref=${sourceSha}`]); + if (file.type !== "file" || file.path !== path || file.encoding !== "base64" + || typeof file.content !== "string" || !Number.isSafeInteger(file.size) + || file.size < 1 || file.size > 256 * 1024) { + throw new Error("The reviewed Cua Driver source commit must contain a regular provider lock."); + } + const bytes = Buffer.from(file.content, "base64"); + if (bytes.length !== file.size) throw new Error("The reviewed Cua Driver provider lock size does not match."); + return sha256(bytes); +} + +/** + * @param {{ file: (path: string) => { async: (type: "nodebuffer") => Promise } | null, + * files: Readonly> }} zip + * @param {{ algorithm: string, files: Readonly> }} index + * @param {string} pluginId + * @param {"darwin" | "win32"} platform + * @param {string} [sourceLockDigest] + */ +export async function verifyRuntimeMembers(zip, index, pluginId, platform, sourceLockDigest) { + if (index?.algorithm !== "sha256" || !index.files || typeof index.files !== "object" + || Array.isArray(index.files) || !Object.hasOwn(index.files, manifestPath)) { throw new Error("Plugin checksums do not cover the manifest."); } const names = Object.keys(index.files); @@ -152,7 +243,6 @@ async function verifyRuntimeMembers(zip, index, pluginId, platform) { : [ `${cuaRoot}/provider-lock.json`, `${cuaRoot}/LICENSE.md`, `${cuaRoot}/THIRD_PARTY_NOTICES.md`, `${cuaRoot}/${cuaLayout.packagedExecutableRelativePath}`, `${cuaRoot}/${cuaLayout.providerSealRelativePath}`, - ...(isWindows ? [`${cuaRoot}/win32-x64/provider-integrity.cat`] : []), ]; if (required.length === 0 || required.some((path) => !Object.hasOwn(index.files, path))) { throw new Error(`Plugin runtime is incomplete for ${pluginId} on ${platform}.`); @@ -165,26 +255,45 @@ async function verifyRuntimeMembers(zip, index, pluginId, platform) { } for (const entry of Object.values(zip.files)) { if (entry.dir) continue; - if ((entry.unsafeOriginalName ?? entry.name) !== entry.name - || !Object.hasOwn(index.files, entry.name) && entry.name !== checksumsPath && entry.name !== provenancePath) { + const type = typeof entry.unixPermissions === "number" ? (entry.unixPermissions & 0o170000) : 0; + if ((entry.unsafeOriginalName ?? entry.name) !== entry.name || (type !== 0 && type !== 0o100000) + || (!Object.hasOwn(index.files, entry.name) && entry.name !== checksumsPath && entry.name !== provenancePath)) { throw new Error(`Plugin archive contains an unexpected member ${entry.name}.`); } } if (pluginId === "official:cua-driver") { const lockPath = `${cuaRoot}/provider-lock.json`; + const lockDigest = index.files[lockPath]; + if (sourceLockDigest !== lockDigest) { + throw new Error("Cua Driver provider lock differs from the reviewed source commit."); + } const lock = validateCuaDriverProviderLockContract(JSON.parse((await readMember(zip, lockPath)).toString("utf8")), { platform, architecture: cuaLayout.architecture, requireReleaseEvidence: true, }); const seal = JSON.parse((await readMember(zip, `${cuaRoot}/${cuaLayout.providerSealRelativePath}`)).toString("utf8")); const executableDigest = index.files[`${cuaRoot}/${cuaLayout.packagedExecutableRelativePath}`]; - if (names.some((path) => path.startsWith("runtime/") && !required.includes(path)) - || lock.upstream.licenseSha256 !== index.files[`${cuaRoot}/LICENSE.md`] - || seal.platform !== platform || seal.signingTier !== "production_signed" - || seal.distributionChannel !== "production" || seal.productionEligible !== true - || seal.lockSha256 !== index.files[lockPath] + if (lock.upstream.licenseSha256 !== index.files[`${cuaRoot}/LICENSE.md`]) { + throw new Error("Cua Driver license differs from the reviewed source lock."); + } + const catalogPath = `${cuaRoot}/win32-x64/provider-integrity.cat`; + const catalogSourceBuild = seal?.signingTier === "unsigned_dev"; + if (isWindows && !catalogSourceBuild && !Object.hasOwn(index.files, catalogPath)) { + throw new Error("The production Windows provider requires an integrity catalog."); + } + const runtimeFiles = new Set(isWindows && !catalogSourceBuild ? [...required, catalogPath] : required); + if (names.some((path) => path.toLowerCase().startsWith("runtime/") && !runtimeFiles.has(path)) + || Object.values(zip.files).some((entry) => entry.dir && entry.name.toLowerCase().startsWith("runtime/") + && ![...runtimeFiles].some((path) => path.startsWith(entry.name)))) { + throw new Error(`Unexpected Cua Driver runtime members for ${platform}.`); + } + if (catalogSourceBuild) { + validateCuaDriverCatalogSourceSeal({ platform, lock, lockDigest, executableDigest, seal }); + } else if (seal?.platform !== platform || seal.signingTier !== "production_signed" + || seal.distributionChannel !== "production" || seal.productionEligible !== true || seal.lockSha256 !== lockDigest || (isWindows ? seal.main?.sha256 : seal.executableSha256) !== executableDigest) { throw new Error(`Cua Driver production lock, seal and runtime tree do not agree for ${platform}.`); } + return seal.signingTier; } } @@ -194,4 +303,3 @@ function github(args, json = true) { } function sha256(bytes) { return createHash("sha256").update(bytes).digest("hex"); } -function signature(bytes) { return `ed25519:${sign(null, bytes, key).toString("base64")}`; } diff --git a/scripts/release/desktop-prerequisites.mjs b/scripts/release/desktop-prerequisites.mjs index e487b4034..9f222d62c 100644 --- a/scripts/release/desktop-prerequisites.mjs +++ b/scripts/release/desktop-prerequisites.mjs @@ -111,7 +111,9 @@ export async function inspectDesktopPrerequisites() { const { readReviewedCodesignSource } = await import("../../apps/desktop/scripts/packaged-codesign-review-publication.mjs"); const { review } = readReviewedCodesignSource(); if (!runtimeObservation || !isDeepStrictEqual(runtimeObservation.runtime, review.runtime) - || !isDeepStrictEqual(runtimeObservation.os, review.os)) throw new Error("Restricted-command runtime/OS review does not match the observed Electron host"); + || ![review.os, ...(review.additionalOs ?? [])].some(os => isDeepStrictEqual(runtimeObservation.os, os))) { + throw new Error("Restricted-command runtime/OS review does not match the observed Electron host"); + } return { reviewId: review.reviewId }; }); } diff --git a/scripts/release/verify-desktop-package.mjs b/scripts/release/verify-desktop-package.mjs index ed0fed60e..7c844839b 100644 --- a/scripts/release/verify-desktop-package.mjs +++ b/scripts/release/verify-desktop-package.mjs @@ -46,12 +46,15 @@ function describePayloadDifference(actual, expected, limit = 20) { return { expectedCount: expected.length, actualCount: actual.length, missing, extra, changed }; } -export async function verifyCandidateCuaDriverAuthority(metadata, resources, platform, catalogManaged) { +export async function verifyCandidateCuaDriverAuthority(metadata, resources, platform, catalogManaged, expectedSigningTier) { const authority = validateCuaDriverPackageAuthority(metadata[CUA_DRIVER_PACKAGE_AUTHORITY_METADATA_KEY]); - if (!catalogManaged && !authority.providerExpected) return "external-only"; + if (!catalogManaged && !authority.providerExpected) return { cuaDriverProviderSource: "external-only" }; if (!catalogManaged || authority.providerSource !== "official-cache" || authority.platform !== platform) { throw new Error("Packaged Cua Driver authority does not match the requested build"); } + if (expectedSigningTier && authority.signingTier !== expectedSigningTier) { + throw new Error("Packaged Cua Driver signing tier does not match the requested build"); + } const policyRoot = join(resources, "providers", "cua-driver"); const [capabilities, policy] = await Promise.all([ fileRecord(join(policyRoot, CUA_DRIVER_PACKAGED_CAPABILITIES_FILENAME)), @@ -60,7 +63,7 @@ export async function verifyCandidateCuaDriverAuthority(metadata, resources, pla if (capabilities.sha256 !== authority.capabilitiesSha256 || policy.sha256 !== authority.runtimeTrustPolicySha256) { throw new Error("Packaged Cua Driver catalog policy does not match app.asar"); } - return authority.providerSource; + return { cuaDriverProviderSource: authority.providerSource, cuaDriverProviderSigningTier: authority.signingTier }; } async function inspectApplication(app, candidate, target, expectedDistribution) { @@ -77,8 +80,9 @@ async function inspectApplication(app, candidate, target, expectedDistribution) if (pluginMode !== "bundled" && pluginMode !== "on-demand") throw new Error("Unknown Desktop plugin resource mode"); const expectedPluginMode = process.env.LING_PLUGIN_EXTERNAL_ONLY === "1" ? "on-demand" : "bundled"; if (pluginMode !== expectedPluginMode) throw new Error("Packaged plugin resource mode does not match the requested build"); - const cuaDriverProviderSource = await verifyCandidateCuaDriverAuthority( + const cuaDriver = await verifyCandidateCuaDriverAuthority( metadata, resources, mac ? "darwin" : "win32", process.env.LING_CUA_DRIVER_CATALOG_MANAGED === "1", + process.env.LING_CUA_SIGNING_TIER || "unsigned_dev", ); execFileSync(process.execPath, [join(desktopRoot, "scripts/distribution/materials.mjs"), "verify", "--platform", mac ? "darwin-arm64" : "win32-x64", "--plugin-mode", pluginMode, "--resources", resources], { cwd: root, encoding: "utf8", timeout: 120_000, maxBuffer: 4 * 1024 * 1024 }); @@ -122,7 +126,7 @@ async function inspectApplication(app, candidate, target, expectedDistribution) || asar.listPackage(archive).some(name => /(?:^|[/\\])dist[/\\](?:office-driver|daemon[/\\]bundled)(?:[/\\]|$)/u.test(name)))) { throw new Error("Unexpected bundled plugin resource in the on-demand Desktop payload"); } - return { files, payload, pluginMode, cuaDriverProviderSource, installedPayloadBytes: payload.reduce((sum, file) => sum + (file.sizeBytes ?? 0), 0), + return { files, payload, pluginMode, ...cuaDriver, installedPayloadBytes: payload.reduce((sum, file) => sum + (file.sizeBytes ?? 0), 0), distributionFileCount: distribution.length }; }