diff --git a/infra/deploy-runner/build-engine-auth-redirect-recovery-artifact.mjs b/infra/deploy-runner/build-engine-auth-redirect-recovery-artifact.mjs new file mode 100644 index 0000000..f7692d0 --- /dev/null +++ b/infra/deploy-runner/build-engine-auth-redirect-recovery-artifact.mjs @@ -0,0 +1,154 @@ +#!/usr/bin/env node +import { createHash } from 'node:crypto' +import { spawnSync } from 'node:child_process' +import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const here = dirname(fileURLToPath(import.meta.url)) +const platformRoot = resolve(here, '../..') +const workspaceRoot = resolve(platformRoot, '..') +const engineRoot = resolve(workspaceRoot, 'NODEDC_ENGINE_INFRA') +const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || join(workspaceRoot, 'deploy-artifacts')) +const predecessorArtifact = resolve( + process.env.NODEDC_ENGINE_AUTH_RECOVERY_PREDECESSOR + || '/Volumes/docker/nodedc-deploy/applied/nodedc-engine-restart-safe-auth-20260719-001.tgz', +) +const [patchId = '', ...extra] = process.argv.slice(2) + +if (extra.length || !/^engine-auth-redirect-recovery-\d{8}-\d{3}$/.test(patchId)) { + throw new Error('usage: build-engine-auth-redirect-recovery-artifact.mjs engine-auth-redirect-recovery-YYYYMMDD-NNN') +} + +const predecessorArtifactSha256 = 'f6830046d7bd2bc32c1dbda8dce7ddf68d15c1e728f594c0f64ee8feec3911b8' +const predecessorManifest = 'id=engine-restart-safe-auth-20260719-001\ncomponent=engine\ntype=app-overlay\n' +const predecessorSha256 = Object.freeze({ + 'nodedc-source/src/platform/auth/access.ts': '9610dc1622a1c9b383eb3a1569347098002aa058dbbcbb23f096f2622d452222', + 'nodedc-source/src/platform/auth/sessionRecovery.ts': 'f931cbb45d64d5d6a2868194e8c73879a408dffca1fdd7e41acfa262441c50d7', + 'nodedc-source/dist/index.html': 'b031f6720683f6fb5ccfa59a01414ff2a3efcdf548b1c6aab33e1748ee3f003d', +}) +const entries = Object.freeze([ + 'nodedc-source/src/platform/auth/access.ts', + 'nodedc-source/src/platform/auth/sessionRecovery.ts', + 'nodedc-source/dist/index.html', + 'nodedc-source/dist/assets/index-DJ1CMfu4.js', +]) +const candidateSha256 = Object.freeze({ + 'nodedc-source/src/platform/auth/access.ts': 'c686db2568912a093ea8934e34889254ddd659594f7084025c280732ef627002', + 'nodedc-source/src/platform/auth/sessionRecovery.ts': '63f3e2379628dea3b119c4283bc0c3bb10e94199c673b9d9c579bac3c54be98f', + 'nodedc-source/dist/index.html': '8894f62ad590168862e81266bc4602410279634b666af72cb14ad80aeb71ea74', + 'nodedc-source/dist/assets/index-DJ1CMfu4.js': 'a0aaf72d2ed390142ff2ea03dbcfdd534637e5faefd80d8aa7d705a804abe065', +}) + +const predecessorInfo = await lstat(predecessorArtifact) +if (predecessorInfo.isSymbolicLink() || !predecessorInfo.isFile()) { + throw new Error('engine_auth_recovery_predecessor_unsafe') +} +if (digest(await readFile(predecessorArtifact)) !== predecessorArtifactSha256) { + throw new Error('engine_auth_recovery_predecessor_archive_mismatch') +} +run('python3', [ + '-c', verifyPredecessorScript(), predecessorArtifact, + predecessorArtifactSha256, predecessorManifest, JSON.stringify(predecessorSha256), +]) + +for (const rel of entries) { + const source = resolve(engineRoot, rel) + const info = await lstat(source) + if (info.isSymbolicLink() || !info.isFile()) throw new Error(`engine_auth_recovery_candidate_unsafe:${rel}`) + if (digest(await readFile(source)) !== candidateSha256[rel]) { + throw new Error(`engine_auth_recovery_candidate_sha256_mismatch:${rel}`) + } +} +const indexHtml = await readFile(resolve(engineRoot, 'nodedc-source/dist/index.html'), 'utf8') +if (!indexHtml.includes('/assets/index-DJ1CMfu4.js') || !indexHtml.includes('/assets/index-Bim2pv1P.css')) { + throw new Error('engine_auth_recovery_dist_entrypoint_mismatch') +} + +await mkdir(artifactRoot, { recursive: true }) +const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`) +await assertArtifactTargetFresh(artifact) +const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-auth-redirect-recovery-')) + +try { + await writeFile( + join(stage, 'manifest.env'), + `id=${patchId}\ncomponent=engine\ntype=app-overlay\n`, + 'utf8', + ) + await writeFile(join(stage, 'files.txt'), `${entries.join('\n')}\n`, 'utf8') + for (const rel of entries) { + const target = join(stage, 'payload', rel) + await mkdir(dirname(target), { recursive: true }) + await copyFile(resolve(engineRoot, rel), target) + } + run('python3', ['-c', canonicalTarScript(), artifact, stage]) + console.log(JSON.stringify({ + ok: true, + patchId, + artifact, + sha256: digest(await readFile(artifact)), + predecessorArtifact, + predecessorArtifactSha256, + predecessorSha256, + candidateSha256, + entries, + runtimeServices: ['nodedc-backend', 'app'], + }, null, 2)) +} finally { + await rm(stage, { recursive: true, force: true }) +} + +function verifyPredecessorScript() { + return [ + 'import hashlib,json,pathlib,sys,tarfile', + 'source=pathlib.Path(sys.argv[1]); expected_archive=sys.argv[2]', + 'expected_manifest=sys.argv[3].encode(); hashes=json.loads(sys.argv[4])', + "assert hashlib.sha256(source.read_bytes()).hexdigest()==expected_archive, 'archive-sha256'", + "with tarfile.open(source,'r:gz') as tar:", + " assert tar.extractfile('manifest.env').read()==expected_manifest, 'manifest'", + ' for rel,wanted in hashes.items():', + " data=tar.extractfile('payload/'+rel).read()", + " assert hashlib.sha256(data).hexdigest()==wanted, 'payload:'+rel", + ].join('\n') +} + +async function assertArtifactTargetFresh(target) { + try { + await lstat(target) + } catch (error) { + if (error?.code === 'ENOENT') return + throw error + } + throw new Error('engine_auth_recovery_artifact_already_exists') +} + +function canonicalTarScript() { + return [ + 'import gzip,io,pathlib,sys,tarfile', + 'root=pathlib.Path(sys.argv[2])', + "with open(sys.argv[1],'wb') as out:", + " with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:", + " with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:", + " for top in ('manifest.env','files.txt','payload'):", + " p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])", + ' for x in paths:', + " info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())", + " info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644", + " with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)", + ].join('\n') +} + +function run(command, args) { + const result = spawnSync(command, args, { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + maxBuffer: 128 * 1024 * 1024, + }) + if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`) +} + +function digest(bytes) { + return createHash('sha256').update(bytes).digest('hex') +} diff --git a/infra/deploy-runner/build-engine-restart-safe-auth-artifact.mjs b/infra/deploy-runner/build-engine-restart-safe-auth-artifact.mjs new file mode 100644 index 0000000..fc4964e --- /dev/null +++ b/infra/deploy-runner/build-engine-restart-safe-auth-artifact.mjs @@ -0,0 +1,148 @@ +#!/usr/bin/env node +import { createHash } from 'node:crypto' +import { spawnSync } from 'node:child_process' +import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const here = dirname(fileURLToPath(import.meta.url)) +const platformRoot = resolve(here, '../..') +const workspaceRoot = resolve(platformRoot, '..') +const engineRoot = resolve(workspaceRoot, 'NODEDC_ENGINE_INFRA') +const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || join(workspaceRoot, 'deploy-artifacts')) +const [patchId = '', ...extra] = process.argv.slice(2) + +if (extra.length || !/^engine-restart-safe-auth-\d{8}-\d{3}$/.test(patchId)) { + throw new Error('usage: build-engine-restart-safe-auth-artifact.mjs engine-restart-safe-auth-YYYYMMDD-NNN') +} + +const entries = Object.freeze([ + 'nodedc-source/server/auth/engineHandoffSession.js', + 'nodedc-source/server/index.js', + 'nodedc-source/src/App.tsx', + 'nodedc-source/src/platform/auth/access.ts', + 'nodedc-source/src/platform/auth/sessionRecovery.ts', + 'nodedc-source/dist/index.html', + 'nodedc-source/dist/assets/index-Bim2pv1P.css', + 'nodedc-source/dist/assets/index-4TenBzkg.js', +]) + +const candidateSha256 = Object.freeze({ + 'nodedc-source/server/auth/engineHandoffSession.js': '0cc5bf02b11cd5fc8cc8cad018091ca93efb13bc72616348ada61105af15bd8e', + 'nodedc-source/server/index.js': '0ac408e0e9a7bc5c8e13a00afc957b982b065e2bc414919839e0b0a11aa05ba4', + 'nodedc-source/src/App.tsx': 'd9bc0f23ceaaf4f5534ac9a9b1f97d84fd8eee4679c59b5999b5a75b8c77bb32', + 'nodedc-source/src/platform/auth/access.ts': '9610dc1622a1c9b383eb3a1569347098002aa058dbbcbb23f096f2622d452222', + 'nodedc-source/src/platform/auth/sessionRecovery.ts': 'f931cbb45d64d5d6a2868194e8c73879a408dffca1fdd7e41acfa262441c50d7', + 'nodedc-source/dist/index.html': 'b031f6720683f6fb5ccfa59a01414ff2a3efcdf548b1c6aab33e1748ee3f003d', + 'nodedc-source/dist/assets/index-Bim2pv1P.css': '18322addd45c126a7b8396f36b005f3085fddba3e9b346dd2c910f6fa6987ebf', + 'nodedc-source/dist/assets/index-4TenBzkg.js': 'a48fcacf3348c20a432cd6da2627b89c0c3e54bc989c727b620125dd3412538a', +}) + +const predecessorSha256 = Object.freeze({ + 'nodedc-source/server/index.js': 'b2b790b02839570d967a2ca68b00e2724485a99389ac9b3a589a1b22302a36b8', + 'nodedc-source/src/App.tsx': '2ea264a59c3e82f763be74f0312cb1aa6bce856644ba0bc7024d77e238e7eb41', + 'nodedc-source/src/platform/auth/access.ts': '4fb9c4d524765dff8a5360efa1c0acf1d203da1cc2c7fd3b98e1456261d43d41', + 'nodedc-source/src/platform/auth/sessionRecovery.ts': '997d3a18e439308d4650e3c7324710a8b17dea29976001c4275c84d96b18ccfe', +}) + +for (const [rel, expected] of Object.entries(predecessorSha256)) { + const result = spawnSync('git', ['-C', engineRoot, 'show', `HEAD:${rel}`], { + stdio: ['ignore', 'pipe', 'pipe'], + maxBuffer: 128 * 1024 * 1024, + }) + if (result.status !== 0 || digest(result.stdout) !== expected) { + throw new Error(`engine_auth_predecessor_mismatch:${rel}`) + } +} + +const newModulePath = 'nodedc-source/server/auth/engineHandoffSession.js' +const newModuleProbe = spawnSync('git', ['-C', engineRoot, 'cat-file', '-e', `HEAD:${newModulePath}`], { + stdio: 'ignore', +}) +if (newModuleProbe.status === 0) throw new Error('engine_auth_new_module_predecessor_unexpected') + +for (const rel of entries) { + const source = resolve(engineRoot, rel) + const info = await lstat(source) + if (info.isSymbolicLink() || !info.isFile()) throw new Error(`engine_auth_candidate_unsafe:${rel}`) + if (digest(await readFile(source)) !== candidateSha256[rel]) { + throw new Error(`engine_auth_candidate_sha256_mismatch:${rel}`) + } +} + +const indexHtml = await readFile(resolve(engineRoot, 'nodedc-source/dist/index.html'), 'utf8') +if (!indexHtml.includes('/assets/index-4TenBzkg.js') || !indexHtml.includes('/assets/index-Bim2pv1P.css')) { + throw new Error('engine_auth_dist_entrypoint_mismatch') +} + +await mkdir(artifactRoot, { recursive: true }) +const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`) +await assertArtifactTargetFresh(artifact) +const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-restart-safe-auth-')) + +try { + await writeFile( + join(stage, 'manifest.env'), + `id=${patchId}\ncomponent=engine\ntype=app-overlay\n`, + 'utf8', + ) + await writeFile(join(stage, 'files.txt'), `${entries.join('\n')}\n`, 'utf8') + for (const rel of entries) { + const target = join(stage, 'payload', rel) + await mkdir(dirname(target), { recursive: true }) + await copyFile(resolve(engineRoot, rel), target) + } + run('python3', ['-c', canonicalTarScript(), artifact, stage]) + console.log(JSON.stringify({ + ok: true, + patchId, + artifact, + sha256: digest(await readFile(artifact)), + entries, + predecessorSha256, + candidateSha256, + runtimeServices: ['nodedc-backend', 'app'], + }, null, 2)) +} finally { + await rm(stage, { recursive: true, force: true }) +} + +async function assertArtifactTargetFresh(target) { + try { + await lstat(target) + } catch (error) { + if (error?.code === 'ENOENT') return + throw error + } + throw new Error('engine_auth_artifact_already_exists') +} + +function canonicalTarScript() { + return [ + 'import gzip,io,pathlib,sys,tarfile', + 'root=pathlib.Path(sys.argv[2])', + "with open(sys.argv[1],'wb') as out:", + " with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:", + " with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:", + " for top in ('manifest.env','files.txt','payload'):", + " p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])", + ' for x in paths:', + " info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())", + " info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644", + " with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)", + ].join('\n') +} + +function run(command, args) { + const result = spawnSync(command, args, { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + maxBuffer: 128 * 1024 * 1024, + }) + if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`) +} + +function digest(bytes) { + return createHash('sha256').update(bytes).digest('hex') +}