diff --git a/docs/project-starter.md b/docs/project-starter.md index efc3be0..21209e3 100644 --- a/docs/project-starter.md +++ b/docs/project-starter.md @@ -180,7 +180,10 @@ compiled code with source maps, docs — is ~340 KB unpacked (~4 % of 7.96 MB) a `_dev` database (MongoDB in its own Docker container) → `pnpm generate:types && pnpm build` → `SEED_ONLY="pages:kontakt" [SEED_DRY_RUN=1] pnpm seed` in production mode → a full seed in production refused → `pnpm start` with `/api/health`, `/pl`, report-only CSP, no `X-Powered-By`, `/llms.txt` → `ipal-doctor --strict` -(when shipped) → with the `nixpacks` CLI on PATH, the same seed inside the Nixpacks image. Needs Docker; +(when shipped) → with the `nixpacks` CLI on PATH, the same seed inside the Nixpacks image. Each run packs to a new +file name and calls `dlx` with `--config.dlx-cache-max-age=0` (pnpm's dlx cache is keyed by the spec, so a reused path +would run the previous build), then checks the new site's `.ipal/starter.json` → `source` (the bundle's sha256 and the +plugin commit `build:starter` recorded) and the installed plugin against the packed tarball. Needs Docker; `--keep` leaves `.starter-gate/` for inspection. ## Building blocks — `@intecion/ipal-kit/starter` diff --git a/scripts/build-starter.mjs b/scripts/build-starter.mjs index 6f00e3a..b37c9d9 100644 --- a/scripts/build-starter.mjs +++ b/scripts/build-starter.mjs @@ -3,6 +3,7 @@ // (dist/starter/template.json.gz): the kept files, the manifest and the lockfile without the plugin. // Runs in prepublishOnly after `pnpm build`; fails when the reference site breaks a manifest rule. +import { execFileSync } from 'node:child_process' import { mkdirSync, statSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' @@ -11,9 +12,20 @@ const root = join(dirname(fileURLToPath(import.meta.url)), '..') const { bundleFlags, collectBundle, packBundle } = await import(pathToFileURL(join(root, 'dist', 'exports', 'starter.js')).href) const bundle = collectBundle(join(root, 'reference')) +// provenance: the plugin commit this bundle was built from, so a generated site can be traced back (`-dirty` = uncommitted changes) +const git = (args) => { + try { + return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() + } catch { + return '' + } +} +const head = git(['rev-parse', 'HEAD']) +bundle.source = { commit: head ? `${head}${git(['status', '--porcelain']) ? '-dirty' : ''}` : null } const out = join(root, 'dist', 'starter', 'template.json.gz') mkdirSync(dirname(out), { recursive: true }) writeFileSync(out, packBundle(bundle)) const raw = Object.values(bundle.files).reduce((sum, text) => sum + Buffer.byteLength(text), 0) + Buffer.byteLength(bundle.lockfile) console.log(`starter bundle: ${Object.keys(bundle.files).length} files + lockfile, ${(raw / 1024).toFixed(0)} KB raw → ${(statSync(out).size / 1024).toFixed(0)} KB gzipped (${out.slice(root.length + 1)})`) console.log(`flags used by the reference site: ${bundleFlags(bundle).join(', ')}`) +console.log(`source: ${bundle.source.commit ?? 'not a Git checkout'}`) diff --git a/scripts/starter-gate.mjs b/scripts/starter-gate.mjs index 4a3da5a..e3a1f58 100644 --- a/scripts/starter-gate.mjs +++ b/scripts/starter-gate.mjs @@ -10,6 +10,7 @@ // PATH it also builds the site with Coolify's build pack and runs the seed inside that image. import { spawn, spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' @@ -80,11 +81,16 @@ async function main() { rmSync(work, { force: true, recursive: true }) mkdirSync(work, { recursive: true }) - // 1. the tarball exactly as it would be published + // 1. the tarball exactly as it would be published — a new file name every run: pnpm's dlx cache is keyed by the + // spec, so a reused path would silently run the PREVIOUS run's plugin sh(root, 'pnpm', ['pack', '--pack-destination', work]) const packed = readdirSync(work).find((f) => f.endsWith('.tgz')) - const tarball = join(work, 'ipal-kit.tgz') + const tarball = join(work, `ipal-kit-${Date.now().toString(36)}-${process.pid}.tgz`) sh(work, 'mv', [packed, tarball]) + const version = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version + const packedBundle = spawnSync('tar', ['-xOzf', tarball, 'package/dist/starter/template.json.gz'], { maxBuffer: 64 * 1024 * 1024 }).stdout + const bundleSha256 = createHash('sha256').update(packedBundle).digest('hex') + const commit = out('git', ['-C', root, 'rev-parse', 'HEAD']) // 2. MongoDB in its own container, like the Coolify database resource sh(root, 'docker', ['run', '-d', '--rm', '--name', mongoName, '-p', '127.0.0.1::27017', 'mongo:7']) @@ -96,9 +102,16 @@ async function main() { const answersFile = join(work, 'answers.json') writeFileSync(answersFile, JSON.stringify(answers, null, 2)) const started = Date.now() - const created = sh(work, 'pnpm', ['--config.auto-install-peers=false', 'dlx', tarball, 'create', domain, '--answers', answersFile, '--plugin-spec', `file:${tarball}`], {}, { allowFail: true }) + const created = sh(work, 'pnpm', ['--config.auto-install-peers=false', '--config.dlx-cache-max-age=0', 'dlx', tarball, 'create', domain, '--answers', answersFile, '--plugin-spec', `file:${tarball}`], {}, { allowFail: true }) check('ipal-kit create (install, skills, tokens, types, import map, typecheck, secret check, first commit)', created === 0, `${((Date.now() - started) / 1000).toFixed(0)} s`) const site = join(work, 'release-checkexample-web') + // the site was made by THIS tarball: the bundle hash and commit the generator recorded, and the plugin it installed + const made = JSON.parse(readFileSync(join(site, '.ipal', 'starter.json'), 'utf8')) + check('generated by this tarball (bundle sha256, plugin version)', made.source?.bundleSha256 === bundleSha256 && made.ipalKit === version, `${bundleSha256.slice(0, 12)} · ${version}`) + check('bundle built from this commit', (made.source?.commit ?? '').replace(/-dirty$/, '') === commit, made.source?.commit ?? 'none') + const installed = join(site, 'node_modules', '@intecion', 'ipal-kit') + const installedSha = createHash('sha256').update(readFileSync(join(installed, 'dist', 'starter', 'template.json.gz'))).digest('hex') + check('the site installed this tarball', installedSha === bundleSha256 && JSON.parse(readFileSync(join(installed, 'package.json'), 'utf8')).version === version) check('first commit, nothing left uncommitted', out('git', ['-C', site, 'status', '--porcelain']) === '' && out('git', ['-C', site, 'log', '--oneline']).split('\n').length === 1) // 4. what Coolify runs: frozen install from the committed lockfile, then build, then start diff --git a/src/modules/starter/bundle.ts b/src/modules/starter/bundle.ts index ada27fd..2dc1e44 100644 --- a/src/modules/starter/bundle.ts +++ b/src/modules/starter/bundle.ts @@ -19,6 +19,8 @@ export type StarterBundle = { lockfile: string manifest: StarterManifest schema: 1 + /** Where the bundle was built: the plugin commit (`-dirty` with uncommitted changes) — set by `pnpm build:starter`. */ + source?: { commit: null | string } } const MANIFEST = 'starter.manifest.json' diff --git a/src/modules/starter/cli.ts b/src/modules/starter/cli.ts index 49afe22..eb08d06 100644 --- a/src/modules/starter/cli.ts +++ b/src/modules/starter/cli.ts @@ -3,7 +3,7 @@ * convention (docs/project-starter.md). Run with `pnpm dlx @intecion/ipal-kit@ create `. */ import { spawnSync } from 'node:child_process' -import { randomBytes } from 'node:crypto' +import { createHash, randomBytes } from 'node:crypto' import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' import { dirname, join, relative, resolve } from 'node:path' import { domainToASCII, fileURLToPath } from 'node:url' @@ -12,7 +12,7 @@ import type { SiteContext } from './generate.js' import { databaseNamesFor } from '../env/databaseName.js' import { type StarterAnswers, validateAnswers } from './answers.js' -import { collectBundle, type StarterBundle, unpackBundle } from './bundle.js' +import { collectBundle, packBundle, type StarterBundle, unpackBundle } from './bundle.js' import { askInTerminal } from './prompts.js' import { renderSite } from './render.js' import { secretFindings } from './secrets.js' @@ -78,12 +78,20 @@ export function normalizeDomain(input: string): string { return ascii } -function loadBundle(): StarterBundle { +/** The bundle and the sha256 of its packed bytes (recorded in the new site, so a check can tell which code ran). */ +function loadBundle(): { bundle: StarterBundle; sha256: string } { const packed = join(pkgRoot, 'dist', 'starter', 'template.json.gz') - if (existsSync(packed)) {return unpackBundle(readFileSync(packed))} + const sha = (data: Buffer) => createHash('sha256').update(data).digest('hex') + if (existsSync(packed)) { + const data = readFileSync(packed) + return { bundle: unpackBundle(data), sha256: sha(data) } + } // a checkout of the plugin repo: read the reference site directly const reference = join(pkgRoot, 'reference') - if (existsSync(join(reference, 'starter.manifest.json'))) {return collectBundle(reference)} + if (existsSync(join(reference, 'starter.manifest.json'))) { + const bundle = collectBundle(reference) + return { bundle, sha256: sha(packBundle(bundle)) } + } throw new Error('no starter templates in this ipal-kit (dist/starter/template.json.gz) — use a released version') } @@ -166,7 +174,9 @@ export async function runCreateCli(args: string[], log: Log = (line) => process. } let files: Record try { - files = renderSite(loadBundle(), answers, ctx) + const { bundle, sha256 } = loadBundle() + ctx.source = { bundleSha256: sha256, commit: bundle.source?.commit ?? null } + files = renderSite(bundle, answers, ctx) } catch (error) { log(`ipal-kit create: ${(error as Error).message}`) return 1 diff --git a/src/modules/starter/generate.ts b/src/modules/starter/generate.ts index e8345ad..7570ced 100644 --- a/src/modules/starter/generate.ts +++ b/src/modules/starter/generate.ts @@ -13,6 +13,8 @@ export type SiteContext = { /** The exact ipal-kit version written into package.json. */ pluginVersion: string serverUrl: string + /** Which starter bundle made the site (recorded in `.ipal/starter.json`; the release gate compares it). */ + source?: { bundleSha256: string; commit: null | string } } const q = (value: string) => `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'` diff --git a/src/modules/starter/render.ts b/src/modules/starter/render.ts index 8680811..46f59de 100644 --- a/src/modules/starter/render.ts +++ b/src/modules/starter/render.ts @@ -89,6 +89,6 @@ export function renderSite(bundle: StarterBundle, a: StarterAnswers, ctx: SiteCo } if (problems.length) {throw new Error(`rendering the site:\n ${problems.join('\n ')}`)} out['pnpm-lock.yaml'] = bundle.lockfile - out['.ipal/starter.json'] = `${JSON.stringify({ answers: a, createdAt: ctx.date, domain: ctx.domain, ipalKit: ctx.pluginVersion }, null, 2)}\n` + out['.ipal/starter.json'] = `${JSON.stringify({ answers: a, createdAt: ctx.date, domain: ctx.domain, ipalKit: ctx.pluginVersion, ...(ctx.source ? { source: ctx.source } : {}) }, null, 2)}\n` return out } diff --git a/test/starter.test.ts b/test/starter.test.ts index 7d66db9..076d086 100644 --- a/test/starter.test.ts +++ b/test/starter.test.ts @@ -221,6 +221,8 @@ describe.runIf(existsSync(path.join(reference, 'starter.manifest.json')))('start expect(files['AGENTS.md']).toMatch(/## Project decisions\n- Languages: pl, en/) expect(files['src/seed/base.ts']).toContain("email: 'biuro@acme-test.pl'") expect(files['pnpm-lock.yaml']).not.toContain('@intecion/ipal-kit') + const traced = renderSite(bundle, answers(), { ...ctx, source: { bundleSha256: 'abc', commit: 'def' } }) + expect(JSON.parse(traced['.ipal/starter.json'] ?? '')).toMatchObject({ ipalKit: '1.15.0', source: { bundleSha256: 'abc', commit: 'def' } }) const doctor = JSON.parse(files['ipal-doctor.json'] ?? '') as { rules: Record } expect(Object.keys(doctor.rules).sort()).toEqual(['audit:collections-present', 'csp', 'i18n-literals']) expect((JSON.parse(files['package.json'] ?? '') as { packageManager?: string }).packageManager).toMatch(/^pnpm@\d/)