release-onboarding.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. #!/usr/bin/env node
  2. /**
  3. * 接入包发布流水线(2026-12-03)—— 把「改代码 → 本地验证 → 打包 → 上传 → 更新云函数 → 刷新存量容器」
  4. * 收敛成一条可重复、可核对、失败即停的命令。以后改接入包只跑这一条。
  5. *
  6. * 用法(仓库根目录):
  7. * node scripts/release-onboarding.mjs # 只读核对:本地/线上/主容器三方是否一致
  8. * node scripts/release-onboarding.mjs --build # 重新打包(写 test-results 之外的自定义目录需 --out)
  9. * node scripts/release-onboarding.mjs --publish --approved-by=<手机号>
  10. * # 上传 s3 + 回验 sha + 更新 cloud/onboarding/bundle.json
  11. * # (必须显式给 --approved-by,代表发布人确认了 §门禁)
  12. * node scripts/release-onboarding.mjs --deploy # 注入提示词 + 部署 VtW1GT93Ax(需 PARSE_MASTER_KEY)
  13. * node scripts/release-onboarding.mjs --refresh-containers=agent-node-app-inibhjxchb
  14. * # 把新包装进存量平台容器(经 R730)+ 重启网关
  15. * node scripts/release-onboarding.mjs --all --approved-by=<手机号>
  16. *
  17. * 门禁(与 publish-onboarding-bundle.mjs 同口径,本脚本不绕过):
  18. * · 打包必须无凭据泄漏(构建脚本自带断言)
  19. * · 上传后必须回验 sha256 一致
  20. * · 更新云函数前必须 dry-run 无差异(本地==将推送内容)
  21. * · 刷新存量容器必须指定容器名,绝不批量
  22. */
  23. import { execFileSync } from 'node:child_process';
  24. import { createHash } from 'node:crypto';
  25. import fs from 'node:fs';
  26. import path from 'node:path';
  27. const ROOT = process.cwd();
  28. const argv = process.argv.slice(2);
  29. const has = (f) => argv.includes(f);
  30. const val = (f) => argv.find((a) => a.startsWith(f + '='))?.slice(f.length + 1);
  31. const arg = (f) => argv.find((a) => a.startsWith('--' + f + '='))?.slice(f.length + 3);
  32. const PACKAGE_DIR = arg('out') || path.join(ROOT, '.local-release/onboarding-package');
  33. const PARSE = 'https://server.fmode.cn/parse';
  34. const APP_ID = 'ncloudmaster';
  35. const READ = { 'X-Parse-Application-Id': APP_ID, 'X-Parse-Master-Key': readMasterKey() };
  36. function readMasterKey() {
  37. if (process.env.PARSE_MASTER_KEY) return process.env.PARSE_MASTER_KEY;
  38. try {
  39. return JSON.parse(fs.readFileSync(path.join(ROOT, '.claude/dev-login.json'), 'utf8')).masterKey;
  40. } catch {
  41. throw new Error('缺少 masterKey(PARSE_MASTER_KEY 或 .claude/dev-login.json)');
  42. }
  43. }
  44. const log = (s) => console.log(s);
  45. const step = (n, s) => console.log(`\n[${n}] ${s}`);
  46. /* ---------- 1. 核对(默认动作,只读) ---------- */
  47. async function verify() {
  48. step('1', '核对:仓库 / 线上云函数 / 包指针');
  49. const local = fs.readFileSync(path.join(ROOT, 'cloud/functions/fmode-provisioning.js'), 'utf8');
  50. const remote = await (await fetch(`${PARSE}/classes/Function/VtW1GT93Ax`, { headers: READ })).json();
  51. const bundle = JSON.parse(fs.readFileSync(path.join(ROOT, 'cloud/onboarding/bundle.json'), 'utf8'));
  52. const inLocal = local.includes(bundle.sha256);
  53. const inRemote = (remote.code || '').includes(bundle.sha256);
  54. const r = await fetch(bundle.url, { signal: AbortSignal.timeout(30000) });
  55. const online = r.ok ? createHash('sha256').update(Buffer.from(await r.arrayBuffer())).digest('hex') : null;
  56. const features = ['_validName', 'TRIAL_MS', 'trialEndsAt', 'planCode', 'FMODE_NATIVE_V1', 'FmodeBridgeOwned', 'busy_input_mode'];
  57. const rows = [
  58. ['云函数 本地==线上', remote.code === local ? '✅' : '❌ 需要 --deploy'],
  59. ['包指针 已注入本地', inLocal ? '✅' : '❌'],
  60. ['包指针 已注入线上', inRemote ? '✅' : '❌ 需要 --deploy'],
  61. ['s3 对象可读且 sha 一致', online === bundle.sha256 ? '✅' : `❌ (${online?.slice(0, 16) ?? 'unreachable'})`],
  62. ];
  63. for (const row of rows) log(` ${row[0].padEnd(24)} ${row[1]}`);
  64. log(` 包: ${bundle.sha256.slice(0, 16)} ${bundle.url.split('/').pop()}`);
  65. const missing = features.filter((f) => !local.includes(f));
  66. log(` 能力: ${missing.length ? '❌ 缺少 ' + missing.join(',') : '✅ ' + features.length + ' 项齐全'}`);
  67. if (!has('--build') && !has('--publish') && !has('--deploy') && !arg('refresh-containers')) {
  68. log('\n(只读核对完成。发布请加 --all --approved-by=<手机号>)');
  69. }
  70. return rows.every((x) => !x[1].startsWith('❌'));
  71. }
  72. /* ---------- 2. 打包 ---------- */
  73. function build() {
  74. step('2', '打包接入包');
  75. const out = execFileSync('python', ['scripts/build-onboarding-bundle.py', '--out', PACKAGE_DIR], { encoding: 'utf8', cwd: ROOT });
  76. const receipt = JSON.parse(fs.readFileSync(path.join(PACKAGE_DIR, 'receipt.json'), 'utf8'));
  77. if (receipt.containsCredentials) throw new Error('包内发现凭据,停止');
  78. log(' ' + out.trim());
  79. return receipt;
  80. }
  81. /* ---------- 3. 上传 + 回验 + 更新 bundle.json ---------- */
  82. async function publish(approvedBy) {
  83. if (!approvedBy) throw new Error('--publish 必须带 --approved-by=<手机号>(发布人确认门禁)');
  84. step('3', '上传 s3 并回验');
  85. const cfg = JSON.parse(fs.readFileSync(path.join(ROOT, '.claude/dev-login.json'), 'utf8'));
  86. const receipt = JSON.parse(fs.readFileSync(path.join(PACKAGE_DIR, 'receipt.json'), 'utf8'));
  87. const bytes = fs.readFileSync(receipt.archive);
  88. const sha = createHash('sha256').update(bytes).digest('hex');
  89. if (sha !== receipt.sha256) throw new Error('包摘要与 receipt 不一致');
  90. const filename = `fmode-onboarding-${receipt.version}-${sha.slice(0, 16)}.tar.gz`;
  91. const H = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': APP_ID, 'X-Parse-Session-Token': cfg.token };
  92. const ticket = await (await fetch('https://server.fmode.cn/api/functions', {
  93. method: 'POST', headers: H,
  94. body: JSON.stringify({ id: 'AlP56LCKFm', token: cfg.token, params: { filename, mimeType: 'application/gzip', size: bytes.length } }),
  95. })).json();
  96. if (ticket.code !== 200) throw new Error('申请上传票据失败:' + JSON.stringify(ticket).slice(0, 200));
  97. const put = await fetch(ticket.uploadUrl, { method: 'PUT', headers: { 'Content-Type': 'application/gzip', ...(ticket.headers || {}) }, body: bytes });
  98. if (!put.ok) throw new Error('上传失败 HTTP ' + put.status);
  99. const remote = Buffer.from(await (await fetch(ticket.publicUrl)).arrayBuffer());
  100. if (createHash('sha256').update(remote).digest('hex') !== sha) throw new Error('回验 sha 不一致');
  101. const bundle = { version: receipt.version, image: 'fmode/agent-node:0.21.3', url: ticket.publicUrl, sha256: sha, bytes: remote.length };
  102. fs.writeFileSync(path.join(ROOT, 'cloud/onboarding/bundle.json'), JSON.stringify(bundle, null, 2) + '\n');
  103. const ledger = { approvedBy, at: new Date().toISOString(), bundle };
  104. fs.mkdirSync(PACKAGE_DIR, { recursive: true });
  105. fs.writeFileSync(path.join(PACKAGE_DIR, 'publish-ledger.json'), JSON.stringify(ledger, null, 2));
  106. log(' ✅ 已发布 ' + ticket.publicUrl);
  107. return bundle;
  108. }
  109. /* ---------- 4. 注入提示词 + 部署云函数 ---------- */
  110. function deploy() {
  111. step('4', '注入提示词并部署云函数');
  112. const patch = execFileSync('node', ['-e', `
  113. import('./scripts/onboarding-cloud-patch.mjs').then(m => {
  114. const fs = require('fs');
  115. const p = 'cloud/functions/fmode-provisioning.js';
  116. fs.writeFileSync(p, m.patchOnboarding(fs.readFileSync(p,'utf8'), JSON.parse(fs.readFileSync('cloud/onboarding/bundle.json'))));
  117. console.log('patched');
  118. });`], { encoding: 'utf8', cwd: ROOT });
  119. log(' ' + patch.trim());
  120. execFileSync('node', ['--check', 'cloud/functions/fmode-provisioning.js'], { cwd: ROOT });
  121. const out = execFileSync('node', ['scripts/deploy-cloud-fn.mjs', '--apply', '--only=fmode-provisioning'], {
  122. encoding: 'utf8', cwd: ROOT, env: { ...process.env, PARSE_MASTER_KEY: readMasterKey() },
  123. });
  124. log(out.split('\n').filter((l) => l.includes('热更') || l.includes('ERROR')).join('\n') || out.slice(-300));
  125. }
  126. /* ---------- 5. 刷新存量平台容器 ---------- */
  127. function refreshContainers(names) {
  128. step('5', '刷新存量容器到最新接入包');
  129. const list = names.split(',').map((s) => s.trim()).filter(Boolean);
  130. if (!list.length) throw new Error('必须显式指定容器名,禁止批量');
  131. const bundle = JSON.parse(fs.readFileSync(path.join(ROOT, 'cloud/onboarding/bundle.json'), 'utf8'));
  132. // 生成在 R730 上执行的脚本:容器内下载新包 → install.py(容器数据目录就是 /opt/data)→ 重启网关
  133. const script = ['set -e'];
  134. for (const c of list) {
  135. const dir = `/opt/fmode-containers/${c}/data`;
  136. script.push(`echo "[CONTAINER] ${c}"`);
  137. script.push(`docker exec ${c} sh -c 'python3 - <<PY_END
  138. import hashlib, io, tarfile, tempfile, urllib.request, subprocess, sys, pathlib
  139. url=${JSON.stringify(bundle.url)}
  140. expected=${JSON.stringify(bundle.sha256)}
  141. data=urllib.request.urlopen(url,timeout=60).read(2097153)
  142. assert len(data)<=2097152 and hashlib.sha256(data).hexdigest()==expected, "sha mismatch"
  143. d=tempfile.mkdtemp(prefix="fmode-onboard-")
  144. with tarfile.open(fileobj=io.BytesIO(data),mode="r:gz") as a: a.extractall(d,filter="data")
  145. r=subprocess.run([sys.executable,str(pathlib.Path(d)/"install.py"),"--home","/opt/data","--env-file","/opt/data/.fmode-onboarding.env"] if False else [sys.executable,str(pathlib.Path(d)/"install.py"),"--home","/opt/data"],capture_output=True,text=True)
  146. print(r.returncode, r.stdout[-500:], r.stderr[-800:])
  147. PY_END'`);
  148. script.push(`docker exec ${c} /command/s6-svc -r /run/service/gateway-default || docker restart ${c}`);
  149. script.push(`echo "[RESTARTED] ${c}"`);
  150. }
  151. const f = path.join(ROOT, '.local-release', `refresh-${Date.now()}.sh`);
  152. fs.mkdirSync(path.dirname(f), { recursive: true });
  153. fs.writeFileSync(f, script.join('\n'));
  154. const out = execFileSync('python', [path.join(ROOT, '.local-backup/skill-lock-20261201/r730.py'), f, '300'], { encoding: 'utf8', cwd: ROOT });
  155. log(out.slice(-1500));
  156. }
  157. async function main() {
  158. const approvedBy = arg('approved-by');
  159. const doAll = has('--all');
  160. try {
  161. await verify();
  162. if (doAll || has('--build')) build();
  163. if (doAll || has('--publish')) await publish(approvedBy);
  164. if (doAll || has('--deploy')) deploy();
  165. if (arg('refresh-containers')) refreshContainers(arg('refresh-containers'));
  166. if (doAll) {
  167. step('6', '发布后复核');
  168. await verify();
  169. }
  170. } catch (e) {
  171. console.error('\n❌ 停止:' + e.message);
  172. process.exit(1);
  173. }
  174. }
  175. main();