import assert from 'node:assert/strict'; import test from 'node:test'; import { execFileSync } from 'node:child_process'; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { activateCandidate, assertCurrentBranch, command, deploy, deploymentArguments, deploymentContext, deploymentTargets, pipelineVerified, prepareSourceArchive, requiredWorkflows, verifyCandidate, verifyPreviewDomainStaging, waitForVerification } from './tangled-deploy.mjs'; const sha = 'a'.repeat(40), repo = 'did:plc:repository'; const environment = { TANGLED_REF: 'refs/heads/dev', TANGLED_REF_NAME: 'dev', TANGLED_SHA: sha, TANGLED_PIPELINE_KIND: 'manual', TANGLED_PIPELINE_ID: '3mdeploy', TANGLED_REPO_REPO_DID: repo, TANGLED_INPUT_VERIFICATION_PIPELINE_ID: '3mverification', TANGLED_SPINDLE_URL: 'https://spindle.tangled.network', TANGLED_VERCEL_TOPOLOGY: 'split', VERCEL_WEB_PROJECT_ID: 'prj_web', VERCEL_APPVIEW_PROJECT_ID: 'prj_appview', VERCEL_ORG_ID: 'team_owner', }; const context = deploymentContext(environment); const brandingAsset = '/_next/static/media/icon.a12b34c5.png'; const loginHTML = `

The Social Wire

`; function pipeline(overrides = {}) { return { id: context.verificationPipeline, repo, commit: sha, trigger: { $type: 'org.tangled.event.push', repo, ref: 'refs/heads/dev', newSha: sha }, workflows: requiredWorkflows.map(id => ({ id, status: 'success', definition: { id, source: { $type: 'org.tangled.ci.defs#fileSource', repo, commit: sha, path: `.tangled/workflows/${id}` } } })), ...overrides }; } test('deployment context requires manual release, explicit verification selection and protected branch', () => { for (const override of [ { TANGLED_PIPELINE_KIND: 'push' }, { TANGLED_PIPELINE_KIND: 'pull_request' }, { TANGLED_PIPELINE_SOURCE: 'did:plc:fork' }, { TANGLED_REF: 'refs/tags/dev' }, { TANGLED_REF_NAME: 'feature/anything' }, { TANGLED_VERCEL_TOPOLOGY: undefined }, { TANGLED_SPINDLE_URL: 'http://spindle.example' }, { TANGLED_SPINDLE_URL: 'https://user:password@spindle.example' }, { TANGLED_SHA: 'HEAD' }, ...[undefined, '', 'other/pipeline', 'pipeline?repo=other', 'x'.repeat(129)].map(value => ({ TANGLED_INPUT_VERIFICATION_PIPELINE_ID: value })), ]) assert.throws(() => deploymentContext({ ...environment, ...override })); assert.equal(deploymentContext({ ...environment, TANGLED_REF: 'refs/heads/main', TANGLED_REF_NAME: 'main' }).target, 'production'); assert.equal(context.target, 'preview'); assert.equal(context.pipeline, '3mdeploy'); assert.equal(context.verificationPipeline, '3mverification'); }); test('requires every exact selected-pipeline file definition and successful status', () => { assert.equal(pipelineVerified(pipeline(), context), true); for (const override of [{ id: context.pipeline }, { id: 'other-pipeline' }, { repo: 'did:plc:other' }, { commit: 'b'.repeat(40) }, { sourceRepo: 'did:plc:fork' }, { trigger: { $type: 'org.tangled.event.pullRequest' } }, { workflows: [] }]) { assert.throws(() => pipelineVerified(pipeline(override), context)); } for (const modify of [ p => p.workflows.push(p.workflows[0]), p => { p.workflows[0].definition.source.repo = 'did:plc:fork'; }, p => { p.workflows[0].definition.source.commit = 'b'.repeat(40); }, p => { p.workflows[0].definition.source.path = '.tangled/workflows/weaker.yml'; }, p => { p.workflows[0].definition.source.$type = 'org.tangled.ci.defs#externalSource'; }, p => { p.workflows[0].definition.id = 'different'; }, ]) { const p = pipeline(); modify(p); assert.throws(() => pipelineVerified(p, context)); } for (const status of ['failed', 'blocked', 'timeout', 'cancelled', 'unknown']) { const p = pipeline(); p.workflows[0].status = status; assert.throws(() => pipelineVerified(p, context)); } for (const status of ['pending', 'scheduled', 'running']) { const p = pipeline(); p.workflows[0].status = status; assert.equal(pipelineVerified(p, context), false); } }); test('manual releases accept selected push or manual verification only for the same protected revision', () => { for (const trigger of [ { $type: 'org.tangled.event.push', repo, ref: 'refs/heads/dev', newSha: sha }, { $type: 'org.tangled.ci.trigger.manual', repo, ref: 'refs/heads/dev', commit: sha }, ]) { assert.equal(pipelineVerified(pipeline({ trigger }), context), true); for (const override of [{ ref: undefined }, { ref: 'refs/heads/main' }, { ref: 'refs/heads/feature/dev' }, { repo: 'did:plc:fork' }, { $type: 'org.tangled.event.pullRequest' }, trigger.newSha ? { newSha: 'b'.repeat(40) } : { commit: 'b'.repeat(40) }]) { assert.throws(() => pipelineVerified(pipeline({ trigger: { ...trigger, ...override } }), context)); } } }); test('verification polling is bounded, public and waits through pending checks', async () => { let requests = 0, sleeps = 0; const request = async (url, options) => { assert.equal(url.origin, 'https://spindle.tangled.network'); assert.equal(url.searchParams.get('pipeline'), context.verificationPipeline); assert.equal(url.searchParams.get('repo'), repo); assert.equal(options.redirect, 'error'); assert.deepEqual(options.headers, { Accept: 'application/json', Connection: 'close' }); const p = pipeline(); if (requests++ === 0) p.workflows[0].status = 'running'; return new Response(JSON.stringify(p)); }; await waitForVerification(context, { request, attempts: 2, intervalMS: 0, sleep: async () => { sleeps++; } }); assert.equal(requests, 2); assert.equal(sleeps, 1); await assert.rejects(waitForVerification(context, { attempts: 181 })); await assert.rejects(waitForVerification(context, { attempts: 1, request: async () => new Response('denied', { status: 401 }) })); await assert.rejects(waitForVerification(context, { attempts: 1, request: async () => new Response('x'.repeat(1024 * 1024 + 1)) })); const pending = pipeline(); pending.workflows[0].status = 'pending'; let pendingRequests = 0; await assert.rejects(waitForVerification(context, { attempts: 1, request: async () => { pendingRequests++; return new Response(JSON.stringify(pending)); }, sleep: async () => assert.fail('An incomplete selected pipeline must not be waited on during release.') }), /not completed/); assert.equal(pendingRequests, 1); }); test('verification retries transport failures without retrying rejected pipeline evidence', async () => { let requests = 0; await waitForVerification(context, { attempts: 1, sleep: async ms => assert.equal(ms, 200), request: async () => { if (++requests === 1) throw new TypeError('fetch failed'); return new Response(JSON.stringify(pipeline())); } }); assert.equal(requests, 2); requests = 0; await assert.rejects(waitForVerification(context, { attempts: 1, sleep: async () => {}, request: async () => { requests++; throw new Error('private transport detail', { cause: { code: 'ECONNRESET' } }); } }), /^Error: Spindle verification request failed \(code ECONNRESET\)\.$/); assert.equal(requests, 2); for (const response of [new Response('', { status: 401 }), new Response(JSON.stringify(pipeline({ commit: 'b'.repeat(40) })))]) { requests = 0; await assert.rejects(waitForVerification(context, { attempts: 1, request: async () => { requests++; return response; }, sleep: async () => assert.fail('Rejected evidence must not be retried.') })); assert.equal(requests, 1); } }); test('stale branch revision cannot deploy', () => { assertCurrentBranch(context, () => `${sha}\trefs/heads/dev\n`); for (const response of ['', `${'b'.repeat(40)}\trefs/heads/dev`, `${sha}\trefs/heads/main`, `${sha}\trefs/heads/dev\n${sha}\trefs/heads/main`]) { assert.throws(() => assertCurrentBranch(context, () => response)); } }); test('release checks the selected completed verification once before any Vercel action', async () => { const cwd = mkdtempSync(join(tmpdir(), 'tangled-release-gate-')); const git = args => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); try { git(['init', '-q']); git(['config', 'user.email', 'ci@example.invalid']); git(['config', 'user.name', 'CI Fixture']); mkdirSync(join(cwd, 'scripts')); writeFileSync(join(cwd, 'vercel.ts'), 'export default {};\n'); writeFileSync(join(cwd, 'scripts/render-vercel-config.ts'), 'console.log("{}");\n'); git(['add', '.']); git(['commit', '-qm', 'fixture']); const exactSha = git(['rev-parse', 'HEAD']); let waits = 0; const commands = []; await assert.rejects(deploy({ cwd, environment: { ...environment, TANGLED_SHA: exactSha, TANGLED_VERCEL_TOPOLOGY: 'consolidated', VERCEL_WEB_TOKEN: 'fixture' }, execute: (tool, args) => { commands.push(tool); assert.equal(tool, 'git'); return `${exactSha}\trefs/heads/dev`; }, wait: async (selected, options) => { waits++; assert.equal(selected.pipeline, '3mdeploy'); assert.equal(selected.verificationPipeline, '3mverification'); assert.deepEqual(options, { attempts: 1, intervalMS: 0 }); const pending = pipeline({ commit: exactSha, trigger: { $type: 'org.tangled.event.push', repo, ref: 'refs/heads/dev', newSha: exactSha } }); for (const workflow of pending.workflows) workflow.definition.source.commit = exactSha; pending.workflows[0].status = 'running'; await waitForVerification(selected, { ...options, request: async () => new Response(JSON.stringify(pending)), sleep: async () => assert.fail('Release must fail immediately for pending verification.') }); }, }), /not completed/); assert.equal(waits, 1); assert.deepEqual(commands, ['git']); } finally { rmSync(cwd, { recursive: true, force: true }); } }); test('split deployment requires old split config and cannot activate root consolidation', () => { const targets = deploymentTargets(context, environment, { exists: () => true }); assert.deepEqual(targets.map(t => t.project), ['prj_appview', 'prj_web']); assert.throws(() => deploymentTargets(context, environment, { exists: () => false }), /do not activate consolidation implicitly/); assert.throws(() => deploymentTargets(context, { ...environment, VERCEL_APPVIEW_PROJECT_ID: 'prj_web' }, { exists: () => true })); assert.deepEqual(deploymentTargets({ ...context, topology: 'consolidated' }, environment, { exists: () => true }).map(t => t.project), ['prj_web']); }); test('consolidated Development staging requires independently verified frozen domain bindings', () => { const consolidated = { ...context, topology: 'consolidated' }; const target = deploymentTargets(consolidated, environment, { exists: () => true })[0]; const calls = []; const request = (_tool, args) => { calls.push(args); const domain = new URL(args[1], 'https://api.vercel.com').pathname.split('/domains/')[1]; return JSON.stringify({ name: domain, projectId: target.project, verified: true, gitBranch: 'chore/remove-editorial-feeds' }); }; verifyPreviewDomainStaging(target, consolidated, environment, request); assert.deepEqual(calls.map(args => args[1]), target.domains.map(domain => `/v9/projects/prj_web/domains/${domain}?teamId=team_owner`)); for (const override of [{ name: 'other.example' }, { projectId: 'prj_other' }, { verified: false }, ...[undefined, null, 'dev', 'main'].map(gitBranch => ({ gitBranch }))]) { assert.throws(() => verifyPreviewDomainStaging(target, consolidated, environment, () => JSON.stringify({ name: target.domains[0], projectId: target.project, verified: true, gitBranch: 'chore/remove-editorial-feeds', ...override, })), /before staging/); } for (const excluded of [context, { ...consolidated, branch: 'main', target: 'production' }]) { verifyPreviewDomainStaging(target, excluded, environment, () => assert.fail('Split and Production releases do not use Preview domain staging.')); } }); test('misbound Development domains prevent every build or deployment command', async () => { const cwd = mkdtempSync(join(tmpdir(), 'tangled-domain-staging-')); const git = args => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); try { git(['init', '-q']); git(['config', 'user.email', 'ci@example.invalid']); git(['config', 'user.name', 'CI Fixture']); mkdirSync(join(cwd, 'scripts')); writeFileSync(join(cwd, 'vercel.ts'), 'export default {};\n'); writeFileSync(join(cwd, 'scripts/render-vercel-config.ts'), 'console.log("{}");\n'); git(['add', '.']); git(['commit', '-qm', 'fixture']); const exactSha = git(['rev-parse', 'HEAD']); const requests = []; await assert.rejects(deploy({ cwd, environment: { ...environment, TANGLED_SHA: exactSha, TANGLED_VERCEL_TOPOLOGY: 'consolidated', VERCEL_WEB_TOKEN: 'fixture' }, wait: async () => {}, execute: (tool, args) => { if (tool === 'git') { assert.equal(args[0], 'ls-remote'); return `${exactSha}\trefs/heads/dev`; } assert.equal(tool, 'vercel'); assert.equal(args[0], 'api'); requests.push(args); return JSON.stringify({ name: 'testing.thesocialwire.app', projectId: 'prj_web', verified: true, gitBranch: 'dev' }); }, }), /before staging/); assert.deepEqual(requests, [['api', '/v9/projects/prj_web/domains/testing.thesocialwire.app?teamId=team_owner', '--method', 'GET']]); } finally { rmSync(cwd, { recursive: true, force: true }); } }); test('deployment arguments preserve target and metadata while disabling schema initialization', () => { const args = deploymentArguments(context, { project: 'prj_web' }); assert.ok(!args.includes('--skip-domain')); assert.ok(args.includes('preview')); assert.ok(args.includes(`tangledCommitSha=${sha}`)); assert.ok(args.includes(`tangledPipelineId=${context.pipeline}`)); assert.ok(args.includes(`tangledVerificationPipelineId=${context.verificationPipeline}`)); assert.ok(args.includes('githubDeployment=1')); assert.ok(args.includes('githubCommitRef=dev')); assert.ok(!args.includes('--git-source')); assert.ok(args.includes('APP_ENV=dev')); assert.ok(args.includes('VERCEL_GIT_COMMIT_REF=dev')); assert.equal(args.filter(arg => arg === 'DEPLOY_SCHEMA_INITIALIZATION=false').length, 2); assert.ok(!args.some(arg => /TOKEN|SECRET/.test(arg))); const productionArgs = deploymentArguments({ ...context, target: 'production', appEnv: 'prod', branch: 'main' }, { project: 'prj_web' }); assert.ok(productionArgs.includes('--skip-domain')); assert.ok(!productionArgs.some(arg => /githubDeployment|githubCommitRef/.test(arg))); }); test('command execution supports inherited output and fails without leaking child diagnostics', () => { assert.equal(command(process.execPath, ['-e', 'process.exit(0)']), ''); assert.equal(command(process.execPath, ['-e', 'process.stdout.write("captured")'], { capture: true }), 'captured'); assert.throws(() => command(process.execPath, ['-e', 'process.stderr.write("private diagnostic");process.exit(1)'], { capture: true }), error => !error.message.includes('private diagnostic')); }); test('private source clone preserves generic Git branch and exact source revision', () => { const directory = mkdtempSync(join(tmpdir(), 'tangled-deploy-git-')); const source = join(directory, 'source'), archive = join(directory, 'archive'); const git = (args, cwd = directory) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); const execute = (tool, args, options = {}) => command(tool, args, { ...options, capture: true }); try { git(['init', '-q', source]); git(['config', 'user.email', 'ci@example.invalid'], source); git(['config', 'user.name', 'CI Fixture'], source); git(['remote', 'add', 'origin', 'https://tangled.org/example.test/repo'], source); writeFileSync(join(source, 'tracked.txt'), 'source\n'); git(['add', 'tracked.txt'], source); git(['commit', '-qm', 'fixture'], source); const expected = git(['rev-parse', 'HEAD'], source); prepareSourceArchive(source, archive, { sha: expected, branch: 'dev' }, process.env, execute); assert.equal(git(['rev-parse', '--abbrev-ref', 'HEAD'], archive), 'dev'); assert.equal(git(['rev-parse', 'HEAD'], archive), expected); assert.equal(git(['rev-parse', 'HEAD^{tree}'], archive), git(['rev-parse', 'HEAD^{tree}'], source)); assert.equal(git(['remote', 'get-url', 'origin'], archive), 'https://tangled.org/example.test/repo'); } finally { rmSync(directory, { recursive: true, force: true }); } }); test('candidate smoke requires provider readiness, exact generic Git metadata and same-origin OAuth', () => { const candidate = { name: 'web', project: 'prj_web', url: 'https://candidate.vercel.app', archive: '/private/archive', environment: { VERCEL_TOKEN: 'scoped', VERCEL_ORG_ID: 'team_owner' } }; const details = { id: 'dpl_verified', projectId: 'prj_web', readyState: 'READY', meta: { gitCommitRef: 'dev', gitCommitSha: sha } }; const calls = []; const execute = (tool, args, options) => { assert.equal(tool, 'vercel'); assert.equal(options.environment.VERCEL_TOKEN, 'scoped'); calls.push(args); if (args[0] === 'api') return JSON.stringify(details); if (args[1] === '/') return 'Web'; if (args[1] === '/login') return loginHTML; if (args[1] === brandingAsset) return '200 image/png'; return JSON.stringify({ client_id: `${candidate.url}/oauth-client-metadata.json`, redirect_uris: [`${candidate.url}/callback`] }); }; assert.equal(verifyCandidate(candidate, context, execute), 'dpl_verified'); assert.ok(calls.some(args => args[0] === 'curl' && args[1] === '/oauth-client-metadata.json')); assert.ok(calls.some(args => args[0] === 'curl' && args[1] === brandingAsset)); for (const override of [{ id: undefined }, { id: 'dpl_invalid/path' }, { projectId: 'prj_other' }, { readyState: 'ERROR' }, { target: 'production' }, { meta: { gitCommitRef: 'main', gitCommitSha: sha } }, { meta: { gitCommitRef: 'dev', gitCommitSha: 'b'.repeat(40) } }]) { assert.throws(() => verifyCandidate(candidate, context, () => JSON.stringify({ ...details, ...override }))); } assert.throws(() => verifyCandidate(candidate, { ...context, target: 'production' }, () => JSON.stringify(details))); assert.throws(() => verifyCandidate(candidate, context, (tool, args, options) => args[0] === 'api' ? JSON.stringify(details) : args[1] === '/' ? 'Web' : JSON.stringify({ client_id: 'https://production.example/oauth-client-metadata.json', redirect_uris: ['https://production.example/callback'] }))); }); test('login smoke loads each rendered branding resource once and never requests another origin', () => { const candidate = { name: 'web', project: 'prj_web', url: 'https://candidate.vercel.app', archive: '/private/archive', environment: { VERCEL_ORG_ID: 'team_owner' } }; const details = { id: 'dpl_verified', projectId: candidate.project, readyState: 'READY', meta: { gitCommitRef: 'dev', gitCommitSha: sha } }; const requests = []; const execute = (html, broken, imageStatus = '200 image/png') => (_tool, args) => { if (args[0] === 'api') return JSON.stringify(details); requests.push(args[1]); if (args[1] === '/oauth-client-metadata.json') return JSON.stringify({ client_id: `${candidate.url}/oauth-client-metadata.json`, redirect_uris: [`${candidate.url}/callback`] }); if (args[1] === '/login') return html; if (args[1] === broken) throw new Error('resource returned 404'); if (args[1] !== '/') { assert.deepEqual(args.slice(-4), ['--output', '/dev/null', '--write-out', '%{http_code} %{content_type}']); return imageStatus; } return 'fixture'; }; verifyCandidate(candidate, context, execute(loginHTML + loginHTML)); assert.equal(requests.filter(path => path === brandingAsset).length, 1); const optimized = `/_next/image?url=${encodeURIComponent(brandingAsset)}&w=128&q=75`; assert.throws(() => verifyCandidate(candidate, context, execute(``, optimized)), /resource returned 404/); assert.ok(requests.includes(optimized)); for (const response of ['302 image/png', '200 text/html', '200 application/octet-stream']) { assert.throws(() => verifyCandidate(candidate, context, execute(loginHTML, undefined, response)), /HTTP 200 with an image content type/); } for (const html of ['No logo', '', '', '', '']) { requests.length = 0; assert.throws(() => verifyCandidate(candidate, context, execute(html)), /branding image|candidate origin/); assert.ok(requests.every(path => ['/', '/oauth-client-metadata.json', '/login'].includes(path))); } }); test('missing login logo or broken rendered asset prevents the release from activating domains', async () => { const cwd = mkdtempSync(join(tmpdir(), 'tangled-login-smoke-')); const git = args => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); try { git(['init', '-q']); git(['config', 'user.email', 'ci@example.invalid']); git(['config', 'user.name', 'CI Fixture']); git(['remote', 'add', 'origin', 'https://tangled.org/example.test/repo']); mkdirSync(join(cwd, 'scripts')); writeFileSync(join(cwd, 'vercel.ts'), 'export default {};\n'); writeFileSync(join(cwd, 'scripts/render-vercel-config.ts'), 'console.log("{}");\n'); git(['add', '.']); git(['commit', '-qm', 'fixture']); const exactSha = git(['rev-parse', 'HEAD']); for (const missing of [true, false]) { const requests = []; await assert.rejects(deploy({ cwd, environment: { ...environment, TANGLED_SHA: exactSha, TANGLED_VERCEL_TOPOLOGY: 'consolidated', VERCEL_WEB_TOKEN: 'fixture' }, wait: async () => {}, execute: (tool, args, options) => { if (tool === 'git') return args[0] === 'ls-remote' ? `${exactSha}\trefs/heads/dev` : command(tool, args, { ...options, capture: true }); if (tool === 'bun') return '{}'; assert.equal(tool, 'vercel'); requests.push(args); if (args[0] === 'deploy') return 'https://candidate.vercel.app'; if (args[0] === 'api') { assert.equal(args[3], 'GET', 'Failed login asset smoke must not activate any alias or promotion.'); if (args[1].includes('/domains/')) return JSON.stringify({ name: new URL(args[1], 'https://api.vercel.com').pathname.split('/domains/')[1], projectId: 'prj_web', verified: true, gitBranch: 'chore/remove-editorial-feeds' }); if (args[1].startsWith('/v9/projects/')) return JSON.stringify({ id: 'prj_web', accountId: 'team_owner', rootDirectory: null }); return JSON.stringify({ id: 'dpl_candidate', projectId: 'prj_web', readyState: 'READY', meta: { gitCommitRef: 'dev', gitCommitSha: exactSha }, env: ['TURSO_DATABASE_URL', 'TURSO_AUTH_TOKEN', 'SCHEDULING_TURSO_DATABASE_URL', 'SCHEDULING_TURSO_AUTH_TOKEN', 'DATABASE_BACKEND', 'RUNTIME_MODE', 'JOBS_RUNNER_MODE', 'JOBS_SECRET', 'CRON_SECRET', 'PDS_ATTESTATION_RECEIPT_SECRET', 'SOCIAL_DRAFT_STORAGE_KEY', 'SCHEDULING_STORAGE_KEY', 'BLOB_READ_WRITE_TOKEN'] }); } assert.equal(args[0], 'curl'); if (args[1] === '/oauth-client-metadata.json') return JSON.stringify({ client_id: 'https://candidate.vercel.app/oauth-client-metadata.json', redirect_uris: ['https://candidate.vercel.app/callback'] }); if (args[1] === '/login') return missing ? 'Missing logo' : loginHTML; if (args[1] === brandingAsset) throw new Error('resource returned 404'); return 'fixture'; }, }), missing ? /branding image/ : /resource returned 404/); assert.equal(requests.filter(args => args[0] === 'deploy').length, 1); assert.equal(requests.filter(args => args[0] === 'api' && args[3] === 'POST').length, 0); } } finally { rmSync(cwd, { recursive: true, force: true }); } }); test('candidate aliases use the verified deployment ID, explicit team and private domain-only body files', async () => { const archive = mkdtempSync(join(tmpdir(), 'tangled-alias-')); mkdirSync(join(archive, '.vercel'), { mode: 0o700 }); const candidate = { id: 'dpl_verified', project: 'prj_web', archive, domains: ['testing.thesocialwire.app', 'api.testing.thesocialwire.app'], environment: { VERCEL_ORG_ID: 'team_owner', VERCEL_TOKEN: 'scoped' } }; const bodies = [], paths = []; let branchChecks = 0; try { await activateCandidate(candidate, context, (tool, args, options) => { assert.equal(tool, 'vercel'); assert.equal(options.environment.VERCEL_TOKEN, 'scoped'); assert.equal(options.cwd, archive); if (args[3] === 'GET') { const domain = new URL(args[1], 'https://api.vercel.com').pathname.slice('/v4/aliases/'.length); return JSON.stringify({ alias: domain, deploymentId: candidate.id, projectId: candidate.project }); } assert.deepEqual(args.slice(0, 4), ['api', '/v2/deployments/dpl_verified/aliases?teamId=team_owner', '--method', 'POST']); assert.equal(args[4], '--input'); const body = args[5]; paths.push(body); assert.equal(statSync(body).mode & 0o777, 0o600); bodies.push(JSON.parse(readFileSync(body, 'utf8'))); return '{}'; }, { beforeMutation: () => { branchChecks++; } }); assert.deepEqual(bodies, candidate.domains.map(alias => ({ alias }))); assert.equal(branchChecks, candidate.domains.length); for (const path of paths) assert.equal(existsSync(path), false); await assert.rejects(activateCandidate(candidate, context, () => { throw new Error('request failed'); }), /request failed/); assert.equal(existsSync(join(archive, '.vercel/alias-0.json')), false); await assert.rejects(activateCandidate(candidate, context, () => assert.fail('A moved branch cannot assign an alias.'), { beforeMutation: () => { throw new Error('branch moved'); }, }), /branch moved/); await activateCandidate(candidate, context, (_tool, args) => { if (args[3] === 'POST') throw new Error('already assigned'); const domain = new URL(args[1], 'https://api.vercel.com').pathname.slice('/v4/aliases/'.length); return JSON.stringify({ alias: domain, deploymentId: candidate.id, projectId: candidate.project }); }); for (const override of [{ deploymentId: 'dpl_other' }, { projectId: 'prj_other' }, { alias: 'other.example' }]) { await assert.rejects(activateCandidate(candidate, context, (_tool, args) => args[3] === 'POST' ? '{}' : JSON.stringify({ alias: candidate.domains[0], deploymentId: candidate.id, projectId: candidate.project, ...override, })), /does not point/); } } finally { rmSync(archive, { recursive: true, force: true }); } }); test('candidate promotion observes documented alias completion and actual Production mappings', async () => { const candidate = { id: 'dpl_verified', project: 'prj_web', archive: '/private/archive', environment: { VERCEL_ORG_ID: 'team_owner' } }; const production = { ...context, target: 'production', branch: 'main' }; const domains = ['thesocialwire.app', 'www.thesocialwire.app', 'api.thesocialwire.app']; const domainPage = { domains: [...domains.map(name => ({ name, projectId: candidate.project, verified: true, gitBranch: null })), { name: 'testing.thesocialwire.app', projectId: candidate.project, verified: true, gitBranch: 'chore/remove-editorial-feeds' }] }; // The actual project API exposes targets.production, with no lastAliasRequest. const project = { id: candidate.project, accountId: 'team_owner', targets: { production: { id: candidate.id, teamId: 'team_owner', target: 'production' }, } }; const complete = { aliases: domains.map(alias => ({ alias, id: `alias-${alias}`, status: 'completed' })), pagination: { next: null } }; const calls = []; let statusReads = 0, sleeps = 0; const response = (args, overrides = {}) => { if (args[1].includes('/domains?')) return JSON.stringify(overrides.domainPage ?? domainPage); if (args[3] === 'POST') return ''; if (args[1].includes('/promote/aliases?')) return JSON.stringify(overrides.status ?? complete); if (args[1].startsWith('/v4/aliases/')) { const alias = new URL(args[1], 'https://api.vercel.com').pathname.slice('/v4/aliases/'.length); return JSON.stringify({ alias, deploymentId: candidate.id, projectId: candidate.project, ...overrides.alias }); } return JSON.stringify(overrides.project ?? project); }; await activateCandidate(candidate, production, (tool, args) => { assert.equal(tool, 'vercel'); calls.push(args); if (args[1].includes('/promote/aliases?') && statusReads++ === 0) return response(args, { status: { aliases: domains.map(alias => ({ alias, status: 'pending' })) } }); return response(args); }, { attempts: 2, intervalMS: 0, sleep: async () => { sleeps++; } }); assert.deepEqual(calls[0], ['api', '/v9/projects/prj_web/domains?teamId=team_owner&limit=100', '--method', 'GET']); assert.deepEqual(calls[1], ['api', '/v10/projects/prj_web/promote/dpl_verified?teamId=team_owner', '--method', 'POST']); assert.equal(calls.filter(args => args[1] === '/v1/projects/prj_web/promote/aliases?teamId=team_owner&limit=100').length, 2); assert.deepEqual(calls.slice(-3).map(args => args[1]), domains.map(domain => `/v4/aliases/${domain}?teamId=team_owner`)); assert.equal(sleeps, 1); for (const overrides of [ { project: { ...project, id: 'prj_other' } }, { project: { ...project, accountId: 'team_other' } }, ...[{ id: 'dpl_other' }, { teamId: 'team_other' }, { target: 'preview' }].map(change => ({ project: { ...project, targets: { production: { ...project.targets.production, ...change } } } })), ...['pending', 'failed', 'unknown'].map(status => ({ status: { aliases: domains.map(alias => ({ alias, status })) } })), { status: { aliases: [] } }, { status: { ...complete, pagination: { next: 123 } } }, { status: { aliases: [...complete.aliases, { alias: 'generated.vercel.app', status: 'pending' }] } }, { status: { aliases: [...complete.aliases, complete.aliases[0]] } }, ...[{ deploymentId: 'dpl_other' }, { projectId: 'prj_other' }, { alias: 'other.example' }].map(alias => ({ alias })), { domainPage: { ...domainPage, pagination: { next: 123 } } }, { domainPage: { domains: [{ ...domainPage.domains[0], verified: false }] } }, ]) { await assert.rejects(activateCandidate(candidate, production, (_tool, args) => response(args, overrides), { attempts: 1, intervalMS: 0 })); } }); test('consolidated Preview aliases recheck frozen bindings before each explicit activation', async () => { const archive = mkdtempSync(join(tmpdir(), 'tangled-staged-alias-')); mkdirSync(join(archive, '.vercel'), { mode: 0o700 }); const consolidated = { ...context, topology: 'consolidated' }; const candidate = { ...deploymentTargets(consolidated, environment, { exists: () => true })[0], id: 'dpl_verified', archive, environment: { VERCEL_ORG_ID: 'team_owner', VERCEL_TOKEN: 'scoped' } }; try { const calls = []; const request = (_tool, args) => { calls.push(args); const path = new URL(args[1], 'https://api.vercel.com').pathname; if (path.includes('/domains/')) return JSON.stringify({ name: path.split('/domains/')[1], projectId: candidate.project, verified: true, gitBranch: 'chore/remove-editorial-feeds' }); if (args[3] === 'POST') { assert.deepEqual(JSON.parse(readFileSync(args[5], 'utf8')), { alias: candidate.domains[Math.floor(calls.length / 3)] }); return '{}'; } return JSON.stringify({ alias: path.slice('/v4/aliases/'.length), deploymentId: candidate.id, projectId: candidate.project }); }; await activateCandidate(candidate, consolidated, request); assert.deepEqual(calls.map(args => args[1]), candidate.domains.flatMap(domain => [ `/v9/projects/prj_web/domains/${domain}?teamId=team_owner`, '/v2/deployments/dpl_verified/aliases?teamId=team_owner', `/v4/aliases/${domain}?teamId=team_owner`, ])); let mutations = 0; calls.length = 0; await assert.rejects(activateCandidate(candidate, consolidated, (_tool, args) => { if (args[1].includes('/domains/api.testing.')) return JSON.stringify({ name: candidate.domains[1], projectId: candidate.project, verified: true, gitBranch: 'dev' }); if (args[3] === 'POST') mutations++; return request(_tool, args); }), /before staging/); assert.equal(mutations, 1); } finally { rmSync(archive, { recursive: true, force: true }); } }); test('invalid candidate identities prevent every alias or promotion request', async () => { const candidate = { id: 'dpl_verified', project: 'prj_web', environment: { VERCEL_ORG_ID: 'team_owner' } }; for (const target of ['preview', 'production']) { for (const override of [{ id: undefined }, { id: 'dpl_invalid/path' }, { project: 'prj_invalid?teamId=other' }, { environment: { VERCEL_ORG_ID: 'team_invalid/path' } }]) { await assert.rejects(activateCandidate({ ...candidate, ...override }, { ...context, target }, () => assert.fail('Invalid candidates cannot change aliases or production.'))); } } }); test('READY backend candidates missing branch-scoped runtime variables fail before protected smoke requests', () => { const required = ['TURSO_DATABASE_URL', 'TURSO_AUTH_TOKEN', 'SCHEDULING_TURSO_DATABASE_URL', 'SCHEDULING_TURSO_AUTH_TOKEN', 'DATABASE_BACKEND', 'RUNTIME_MODE', 'JOBS_RUNNER_MODE', 'JOBS_SECRET', 'CRON_SECRET', 'PDS_ATTESTATION_RECEIPT_SECRET', 'SOCIAL_DRAFT_STORAGE_KEY', 'SCHEDULING_STORAGE_KEY', 'BLOB_READ_WRITE_TOKEN']; for (const name of ['appview', 'consolidated']) { const candidate = { name, project: 'prj_backend', url: 'https://candidate.vercel.app', archive: '/private/archive', environment: { VERCEL_ORG_ID: 'team_owner' } }; const details = { id: 'dpl_verified', projectId: candidate.project, readyState: 'READY', meta: { gitCommitRef: 'dev', gitCommitSha: sha } }; for (const env of [undefined, { TURSO_AUTH_TOKEN: 'private-value-must-not-be-read' }, ['APP_ENV', 'DATABASE_BACKEND', 'RUNTIME_MODE'], ...required.map(missing => required.filter(key => key !== missing))]) { const calls = []; const execute = (_tool, args) => { calls.push(args); return JSON.stringify({ ...details, env }); }; assert.throws(() => verifyCandidate(candidate, context, execute), error => /missing required environment variable names/.test(error.message) && !error.message.includes('private-value')); assert.equal(calls.length, 1); assert.equal(calls[0][0], 'api'); } const smokePaths = []; verifyCandidate(candidate, context, (_tool, args) => { if (args[0] === 'api') return JSON.stringify({ ...details, env: required }); smokePaths.push(args[1]); if (args[1] === '/login') return loginHTML; if (args[1] === brandingAsset) return '200 image/png'; return args[1] === '/oauth-client-metadata.json' ? JSON.stringify({ client_id: `${candidate.url}/oauth-client-metadata.json`, redirect_uris: [`${candidate.url}/callback`] }) : 'ready'; }); assert.deepEqual(smokePaths, name === 'appview' ? ['/readyz'] : ['/readyz', '/', '/oauth-client-metadata.json', '/login', brandingAsset]); } }); const artifactProject = 'prj_LvFeZ9T0TFKITd8TmARy0a0sj8nV', artifactTeam = 'team_bkhdFggoSZpUiLHe0aLuShOR'; const artifactDigest = `sha256:${'c'.repeat(64)}`; const artifactImage = `vcr.vercel.com/sam-clemente-s-team/the-social-wire-web/social-wire-appview@${artifactDigest}`; const artifactPlatformImage = artifactImage.replace('/social-wire-appview@', '/integrations@'); const artifactNative = { regions: ['sfo1'], env: { RUNTIME_MODE: 'serverless', DATABASE_BACKEND: 'turso', JOBS_RUNNER_MODE: 'external' }, services: { web: { framework: 'nextjs' }, reader: { framework: 'go' }, integrations: { root: 'services/appview', framework: 'go', entrypoint: 'cmd/integrations/main.go', buildCommand: 'native build', functions: { 'cmd/integrations/main.go': { maxDuration: 300, regions: ['sfo1'] } } } }, rewrites: [{ source: '/v1/semble/(.*)', destination: { service: 'integrations' } }], schedules: { maintenance: { schedule: '*/15 * * * *' } } }; const artifactRuntimeEnv = ['TURSO_DATABASE_URL', 'TURSO_AUTH_TOKEN', 'SCHEDULING_TURSO_DATABASE_URL', 'SCHEDULING_TURSO_AUTH_TOKEN', 'DATABASE_BACKEND', 'RUNTIME_MODE', 'JOBS_RUNNER_MODE', 'JOBS_SECRET', 'CRON_SECRET', 'PDS_ATTESTATION_RECEIPT_SECRET', 'SOCIAL_DRAFT_STORAGE_KEY', 'SCHEDULING_STORAGE_KEY', 'BLOB_READ_WRITE_TOKEN']; const appUnauthorized = '{"error":{"message":"Missing Authorization header"}}\n401 application/json'; const xrpcUnauthorized = '{"error":"AuthRequired","message":"Missing Authorization header"}\n401 application/json'; function artifactReleaseFixture({ branch = 'dev', withArtifact = true, artifactInput = false, developmentOverride = {}, routeResponse = appUnauthorized, xrpcResponse = xrpcUnauthorized, wrongArtifactMetadata = false } = {}) { const cwd = mkdtempSync(join(tmpdir(), 'tangled-artifact-release-')); const git = args => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); const write = (path, value) => { mkdirSync(join(cwd, path, '..'), { recursive: true }); writeFileSync(join(cwd, path), value); }; git(['init', '-q']); git(['config', 'user.email', 'ci@example.invalid']); git(['config', 'user.name', 'Fixture']); git(['remote', 'add', 'origin', 'https://tangled.org/samclemente.me/the-social-wire']); write('vercel.ts', 'source config\n'); write('scripts/render-vercel-config.ts', 'renderer\n'); write('scripts/ci/development-parity.mjs', 'trusted guard fixture\n'); write('services/appview/internal/source.go', 'image source\n'); git(['add', '.']); git(['commit', '-qm', 'accepted artifact source']); const sourceCommit = git(['rev-parse', 'HEAD']), sourceTree = git(['rev-parse', 'HEAD^{tree}']); const manifest = { version: 1, service: 'integrations', repository: 'did:plc:akmh2xiv3o33rhjl6v3iyn6n', source: { commit: sourceCommit, tree: sourceTree, pipeline: 'accepted-pilot' }, atcr: { image: `atcr.io/samclemente.me/social-wire-appview@${artifactDigest}`, digest: artifactDigest }, vcr: { image: artifactImage, digest: artifactDigest }, development: { deploymentId: 'dpl_accepted', url: 'https://accepted.vercel.app', projectId: artifactProject, commit: sourceCommit, branch: 'dev', target: 'preview', readyState: 'READY', vcrImage: artifactImage, integrationsHealthy: true } }; write(withArtifact && !artifactInput ? 'config/integrations-artifact.json' : 'release-note.txt', withArtifact && !artifactInput ? JSON.stringify(manifest) : 'release record\n'); git(['add', '.']); git(['commit', '-qm', 'reviewed release record']); const releaseCommit = git(['rev-parse', 'HEAD']); git(['update-ref', 'refs/remotes/origin/dev', releaseCommit]); git(['update-ref', 'refs/remotes/origin/main', sourceCommit]); const env = { ...environment, TANGLED_SHA: releaseCommit, TANGLED_REF_NAME: branch, TANGLED_REF: `refs/heads/${branch}`, TANGLED_REPO_REPO_DID: manifest.repository, TANGLED_VERCEL_TOPOLOGY: 'consolidated', VERCEL_WEB_PROJECT_ID: artifactProject, VERCEL_ORG_ID: artifactTeam, VERCEL_WEB_TOKEN: 'fixture-token', ...(artifactInput ? { TANGLED_INPUT_INTEGRATIONS_ARTIFACT: JSON.stringify(manifest) } : {}) }; const calls = []; let promoted = false; const execute = (tool, args, options = {}) => { calls.push({ tool, args, options }); if (tool === 'git') { if (args[0] === 'ls-remote') return `${releaseCommit}\trefs/heads/${branch}`; if (args[0] === 'fetch') return ''; return command(tool, args, { ...options, capture: true }); } if (tool === process.execPath) return ''; // Existing parity guard invocation is asserted below. if (tool === 'bun') return JSON.stringify(artifactNative); assert.equal(tool, 'vercel'); if (args[0] === 'build') { const config = JSON.parse(readFileSync(join(options.cwd, 'vercel.json'), 'utf8')); assert.equal(config.services.integrations.entrypoint, 'Dockerfile.integrations.accepted'); assert.equal(readFileSync(join(options.cwd, 'services/appview/Dockerfile.integrations.accepted'), 'utf8'), `FROM ${artifactImage}\n`); assert.deepEqual(config.schedules, artifactNative.schedules); assert.deepEqual(config.services.reader, artifactNative.services.reader); const path = join(options.cwd, '.vercel/output/services/integrations/functions/container.func'); mkdirSync(path, { recursive: true }); writeFileSync(join(path, '.vc-config.json'), JSON.stringify({ runtime: 'container', handler: artifactPlatformImage, maxDuration: 300, regions: ['sfo1'] })); return ''; } if (args[0] === 'deploy') return 'https://candidate.vercel.app'; if (args[0] === 'pull') return ''; if (args[0] === 'curl') { if (args[1] === '/v1/semble/collections') return routeResponse; if (args[1] === '/xrpc/link.latr.bookmarks.listBookmarks') return xrpcResponse; if (args[1] === '/oauth-client-metadata.json') return JSON.stringify({ client_id: 'https://candidate.vercel.app/oauth-client-metadata.json', redirect_uris: ['https://candidate.vercel.app/callback'] }); if (args[1] === '/login') return loginHTML; if (args[1] === brandingAsset) return '200 image/png'; return 'ready'; } assert.equal(args[0], 'api'); const path = args[1]; if (path.startsWith('/v13/deployments/dpl_accepted?')) return JSON.stringify({ id: 'dpl_accepted', projectId: artifactProject, url: 'accepted.vercel.app', target: null, readyState: 'READY', meta: { gitCommitRef: 'dev', gitCommitSha: sourceCommit, integrationsImageSourceCommit: sourceCommit, integrationsAtcrDigest: wrongArtifactMetadata ? `sha256:${'f'.repeat(64)}` : artifactDigest, integrationsVcrDigest: artifactDigest }, ...developmentOverride }); if (path.startsWith('/v13/deployments/')) return JSON.stringify({ id: 'dpl_candidate', projectId: artifactProject, readyState: 'READY', target: branch === 'main' ? 'production' : null, meta: { gitCommitRef: branch, gitCommitSha: releaseCommit }, env: artifactRuntimeEnv }); if (path.includes('/domains/')) return JSON.stringify({ name: new URL(path, 'https://api.vercel.com').pathname.split('/domains/')[1], projectId: artifactProject, verified: true, gitBranch: 'chore/remove-editorial-feeds' }); if (path.includes('/domains?')) return JSON.stringify({ domains: [{ name: 'thesocialwire.app', projectId: artifactProject, verified: true, gitBranch: null }] }); if (path.includes(`/promote/dpl_candidate`)) { promoted = true; return '{}'; } if (path.includes('/promote/aliases?')) return JSON.stringify({ aliases: [{ alias: 'thesocialwire.app', status: 'completed' }] }); if (path.startsWith('/v9/projects/')) return JSON.stringify({ id: artifactProject, accountId: artifactTeam, rootDirectory: null, ...(promoted ? { targets: { production: { id: 'dpl_candidate', teamId: artifactTeam, target: 'production' } } } : {}) }); if (path.startsWith('/v4/aliases/')) return JSON.stringify({ alias: new URL(path, 'https://api.vercel.com').pathname.slice('/v4/aliases/'.length), deploymentId: 'dpl_candidate', projectId: artifactProject }); if (path.includes('/aliases?')) return '{}'; assert.fail(`Unexpected API ${path}`); }; const verifyImport = (accepted, image, options) => { calls.push({ tool: 'verify-import', args: [] }); assert.equal(accepted.commit, sourceCommit); assert.equal(image, artifactPlatformImage); assert.equal(options.releaseSource.releaseCommit, releaseCommit); return { platformImage: artifactPlatformImage, platformDigest: artifactDigest, platformImportVerified: true, applicationRebuilt: false }; }; return { cwd, env, calls, manifest, sourceCommit, releaseCommit, execute, verifyImport, cleanup: () => rmSync(cwd, { recursive: true, force: true }) }; } test('reviewed artifact dispatch prebuilds the same integrations digest for both release environments and preserves activation gates', async () => { for (const branch of ['dev', 'main']) { const fixture = artifactReleaseFixture({ branch, artifactInput: branch === 'main' }); try { const receipt = await deploy({ cwd: fixture.cwd, environment: fixture.env, execute: fixture.execute, verifyImport: fixture.verifyImport, wait: async () => fixture.calls.push({ tool: 'checks', args: [] }) }); assert.equal(receipt.integrationsArtifact.vcr.image, artifactImage); assert.equal(receipt.deployments[0].platformImport.platformImage, artifactPlatformImage); assert.equal(receipt.integrationsArtifact.source.sourceCommit, fixture.sourceCommit); assert.equal(receipt.integrationsArtifact.source.releaseCommit, fixture.releaseCommit); const pull = fixture.calls.find(call => call.args[0] === 'pull'); assert.ok(pull.args.includes(branch === 'dev' ? 'preview' : 'production')); assert.equal(pull.args.includes('--git-branch'), branch === 'dev'); const deployed = fixture.calls.find(call => call.args[0] === 'deploy'); assert.ok(deployed.args.includes('--prebuilt')); assert.ok(deployed.args.includes('PORT=8081')); assert.equal(deployed.args.includes('--skip-domain'), branch === 'main'); assert.ok(deployed.args.includes(`integrationsImageSourceCommit=${fixture.sourceCommit}`)); const owned = fixture.calls.filter(call => call.args[0] === 'curl' && call.args[1] === '/v1/semble/collections'); assert.equal(owned.length, 2, 'Previous Development and new candidate must both answer their owned routes.'); assert.ok(fixture.calls.findIndex(call => call.tool === 'checks') < fixture.calls.findIndex(call => call.args[0] === 'pull')); if (branch === 'main') assert.ok(fixture.calls.some(call => call.tool === process.execPath), 'Production parity remains enforced.'); } finally { fixture.cleanup(); } } }); test('failed Development source/readiness or non-application auth responses stop artifact release before any build or deployment', async () => { for (const options of [{ developmentOverride: { readyState: 'ERROR' } }, { developmentOverride: { meta: { gitCommitRef: 'main', gitCommitSha: sha } } }, { wrongArtifactMetadata: true }, { xrpcResponse: appUnauthorized }, { routeResponse: 'Deployment protection\n401 text/html' }, { routeResponse: '{"error":"Unauthorized"}\n401 application/json' }]) { const fixture = artifactReleaseFixture(options); try { await assert.rejects(deploy({ cwd: fixture.cwd, environment: fixture.env, execute: fixture.execute, verifyImport: fixture.verifyImport, wait: async () => {} })); assert.ok(!fixture.calls.some(call => ['pull', 'build', 'deploy'].includes(call.args[0]))); } finally { fixture.cleanup(); } } }); test('absent reviewed artifact retains native source deployment without prebuild or prior-Development artifact reads', async () => { const fixture = artifactReleaseFixture({ withArtifact: false }); try { const receipt = await deploy({ cwd: fixture.cwd, environment: fixture.env, execute: fixture.execute, verifyImport: fixture.verifyImport, wait: async () => {} }); assert.equal(receipt.integrationsArtifact, undefined); assert.ok(!fixture.calls.some(call => ['pull', 'build'].includes(call.args[0]))); assert.ok(!fixture.calls.find(call => call.args[0] === 'deploy').args.includes('--prebuilt')); assert.ok(!fixture.calls.some(call => call.args[1]?.startsWith('/v13/deployments/dpl_accepted'))); } finally { fixture.cleanup(); } });