Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/lib/releases/pipeline.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2113 * Last Modified : 2026-11-2114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { createHash } from "node:crypto";44import { createWriteStream } from "node:fs";45import { mkdir, rename, rm, stat } from "node:fs/promises";46import { execFile } from "node:child_process";47import { join } from "node:path";48import { Readable } from "node:stream";49import { pipeline as pipe } from "node:stream/promises";50import { db, getSetting, now } from "../database/db";51import { env } from "../env";52import { audit } from "../audit";53import { isForgeAssetUrl, type FetchLike } from "../git/spbgit";54import { ApiError } from "../security/http";55import { releaseById, type Release, type Signature } from "./store";5657const MAX_BYTES = 4 * 1024 ** 3;58export const artifactsDir = () => join(env.dataDir, "artifacts");59export const artifactPath = (r: Pick<Release, "slug" | "id" | "asset_name">) => join(artifactsDir(), r.slug, String(r.id), r.asset_name);6061/** Publication policy: an image without verifiable notarization evidence is held, not published. */62export const requireNotarization = () => getSetting("publication.requireNotarization") !== "0";6364const run = (cmd: string, args: string[]) => new Promise<{ ok: boolean; out: string }>((resolve) => {65 execFile(cmd, args, { timeout: 120_000 }, (err, stdout, stderr) => resolve({ ok: !err, out: `${stdout}${stderr}`.trim().slice(0, 1500) }));66});6768/**69 * Signing / notarization evidence, gathered with Apple's own tools when the host is a Mac:70 * `stapler validate` (stapled notarization ticket), `spctl` (Gatekeeper assessment), `codesign` (authority, team).71 * On another platform nothing can be asserted and `notarized` stays null.72 */73export async function inspectSignature(file: string): Promise<Signature> {74 if (process.platform !== "darwin") return { platform: process.platform, notarized: null };75 const [stapler, gatekeeper, codesign] = await Promise.all([76 run("/usr/bin/xcrun", ["stapler", "validate", file]),77 run("/usr/sbin/spctl", ["-a", "-t", "open", "--context", "context:primary-signature", "-vv", file]),78 run("/usr/bin/codesign", ["-dv", "--verbose=2", file]),79 ]);80 const notarized = stapler.ok || (gatekeeper.ok && /Notarized Developer ID/.test(gatekeeper.out));81 return { platform: "darwin", notarized, stapler: stapler.out, gatekeeper: gatekeeper.out, codesign: codesign.out, teamId: /TeamIdentifier=(\w+)/.exec(codesign.out)?.[1] ?? null };82}8384async function fetchVerified(url: string, dest: string, expected: { size: number; sha256: string }, fetchImpl: FetchLike): Promise<{ sha256: string; bytes: number }> {85 const res = await fetchImpl(url, { redirect: "error", signal: AbortSignal.timeout(30 * 60_000) });86 if (!res.ok || !res.body) throw new ApiError(502, "download_failed", `The forge answered ${res.status} for the asset`);87 const hash = createHash("sha256"); let bytes = 0;88 const counter = new TransformStream<Uint8Array, Uint8Array>({ transform(chunk, c) {89 bytes += chunk.byteLength;90 if (bytes > MAX_BYTES || bytes > expected.size) { c.error(new ApiError(422, "size_mismatch", "The asset is larger than declared")); return; }91 hash.update(chunk); c.enqueue(chunk);92 } });93 await pipe(Readable.fromWeb(res.body.pipeThrough(counter) as import("node:stream/web").ReadableStream), createWriteStream(dest, { mode: 0o600 }));94 return { sha256: hash.digest("hex"), bytes };95}9697type Inspect = (file: string) => Promise<Signature>;9899/**100 * Administrator approval of a validated release:101 * mirror the image from the forge → recompute SHA-256 against the declared one → gather notarization evidence →102 * apply the publication policy → only then does the file become downloadable from this site.103 */104export async function approveRelease(id: number, actor: string, opts: { fetchImpl?: FetchLike; inspect?: Inspect } = {}): Promise<Release> {105 const r = releaseById(id);106 if (!r) throw new ApiError(404, "not_found", "Unknown release");107 if (!["validated", "held"].includes(r.state)) throw new ApiError(409, "bad_state", `A release in state "${r.state}" cannot be approved`);108 if (!r.sha256_declared || !r.asset_size) throw new ApiError(422, "missing_checksum", "No declared checksum");109 const dest = artifactPath(r), tmp = dest + ".part";110 await mkdir(join(artifactsDir(), r.slug, String(r.id)), { recursive: true, mode: 0o700 });111 const set = (state: string, reason: string | null, extra: Record<string, string | null> = {}) => {112 const cols = Object.keys(extra).map((k) => `, ${k} = ?`).join("");113 db().prepare(`UPDATE releases SET state = ?, reason = ?, approved_at = ?, approved_by = ?, checked_at = ?${cols} WHERE id = ?`).run(state, reason, now(), actor, now(), ...Object.values(extra), id);114 };115 try {116 if (r.source === "spbgit") {117 if (!r.repo || !r.source_url || !isForgeAssetUrl(r.source_url, r.repo)) throw new ApiError(422, "foreign_url", "The asset is not a release file of the expected repository");118 const got = await fetchVerified(r.source_url, tmp, { size: r.asset_size, sha256: r.sha256_declared }, opts.fetchImpl ?? fetch);119 if (got.bytes !== r.asset_size) throw new ApiError(422, "size_mismatch", `Downloaded ${got.bytes} bytes, ${r.asset_size} declared`);120 if (got.sha256 !== r.sha256_declared) {121 db().prepare("UPDATE releases SET sha256_computed = ? WHERE id = ?").run(got.sha256, id);122 throw new ApiError(422, "checksum_mismatch", "The downloaded image does not match the declared SHA-256");123 }124 await rename(tmp, dest);125 } else if (!(await stat(dest).catch(() => null))) throw new ApiError(422, "artifact_missing", "The ingested artifact is no longer on disk");126 } catch (e) {127 await rm(tmp, { force: true });128 const code = e instanceof ApiError ? e.code : "download_failed";129 set("invalid", code);130 audit("release.rejected", { actor, detail: { id, slug: r.slug, tag: r.tag, reason: code } });131 throw e instanceof ApiError ? e : new ApiError(502, "download_failed", "The asset could not be retrieved");132 }133 const sig = await (opts.inspect ?? inspectSignature)(dest);134 const held = requireNotarization() && sig.notarized !== true;135 set(held ? "held" : "published", held ? (sig.notarized === null ? "notarization_unverifiable" : "not_notarized") : null,136 { sha256_computed: r.sha256_declared, signature: JSON.stringify(sig), artifact: dest, published_at: held ? null : now() });137 audit(held ? "release.held" : "release.published", { actor, detail: { id, slug: r.slug, tag: r.tag, asset: r.asset_name, sha256: r.sha256_declared, notarized: sig.notarized } });138 return releaseById(id)!;139}140141/** Takes a published (or held) image offline. The previous published version becomes the default download again. */142export async function withdrawRelease(id: number, actor: string, reason = "withdrawn_by_admin"): Promise<Release> {143 const r = releaseById(id);144 if (!r) throw new ApiError(404, "not_found", "Unknown release");145 if (!["published", "held", "validated"].includes(r.state)) throw new ApiError(409, "bad_state", `A release in state "${r.state}" cannot be withdrawn`);146 db().prepare("UPDATE releases SET state = 'withdrawn', reason = ?, published_at = NULL WHERE id = ?").run(reason, id);147 if (r.artifact && r.source === "spbgit") await rm(r.artifact, { force: true });148 audit("release.withdrawn", { actor, detail: { id, slug: r.slug, tag: r.tag } });149 return releaseById(id)!;150}151152/** Puts a withdrawn forge release back in the review queue (it must be approved, and re-verified, again). */153export function requeueRelease(id: number, actor: string): Release {154 const r = releaseById(id);155 if (!r) throw new ApiError(404, "not_found", "Unknown release");156 if (r.state !== "withdrawn" || r.source !== "spbgit" || r.reason === "asset_changed_upstream") throw new ApiError(409, "bad_state", "Only a manually withdrawn forge release can be re-queued");157 db().prepare("UPDATE releases SET state = 'validated', reason = NULL, artifact = NULL WHERE id = ?").run(id);158 audit("release.requeued", { actor, detail: { id } });159 return releaseById(id)!;160}161162export function setReleaseNotes(id: number, notes: { en: string; fr: string }): void {163 db().prepare("UPDATE releases SET notes = ? WHERE id = ?").run(JSON.stringify(notes), id);164}165