|
|
@@ -0,0 +1,190 @@
|
|
|
+#!/usr/bin/env node
|
|
|
+/**
|
|
|
+ * 接入包发布流水线(2026-12-03)—— 把「改代码 → 本地验证 → 打包 → 上传 → 更新云函数 → 刷新存量容器」
|
|
|
+ * 收敛成一条可重复、可核对、失败即停的命令。以后改接入包只跑这一条。
|
|
|
+ *
|
|
|
+ * 用法(仓库根目录):
|
|
|
+ * node scripts/release-onboarding.mjs # 只读核对:本地/线上/主容器三方是否一致
|
|
|
+ * node scripts/release-onboarding.mjs --build # 重新打包(写 test-results 之外的自定义目录需 --out)
|
|
|
+ * node scripts/release-onboarding.mjs --publish --approved-by=<手机号>
|
|
|
+ * # 上传 s3 + 回验 sha + 更新 cloud/onboarding/bundle.json
|
|
|
+ * # (必须显式给 --approved-by,代表发布人确认了 §门禁)
|
|
|
+ * node scripts/release-onboarding.mjs --deploy # 注入提示词 + 部署 VtW1GT93Ax(需 PARSE_MASTER_KEY)
|
|
|
+ * node scripts/release-onboarding.mjs --refresh-containers=agent-node-app-inibhjxchb
|
|
|
+ * # 把新包装进存量平台容器(经 R730)+ 重启网关
|
|
|
+ * node scripts/release-onboarding.mjs --all --approved-by=<手机号>
|
|
|
+ *
|
|
|
+ * 门禁(与 publish-onboarding-bundle.mjs 同口径,本脚本不绕过):
|
|
|
+ * · 打包必须无凭据泄漏(构建脚本自带断言)
|
|
|
+ * · 上传后必须回验 sha256 一致
|
|
|
+ * · 更新云函数前必须 dry-run 无差异(本地==将推送内容)
|
|
|
+ * · 刷新存量容器必须指定容器名,绝不批量
|
|
|
+ */
|
|
|
+import { execFileSync } from 'node:child_process';
|
|
|
+import { createHash } from 'node:crypto';
|
|
|
+import fs from 'node:fs';
|
|
|
+import path from 'node:path';
|
|
|
+
|
|
|
+const ROOT = process.cwd();
|
|
|
+const argv = process.argv.slice(2);
|
|
|
+const has = (f) => argv.includes(f);
|
|
|
+const val = (f) => argv.find((a) => a.startsWith(f + '='))?.slice(f.length + 1);
|
|
|
+const arg = (f) => argv.find((a) => a.startsWith('--' + f + '='))?.slice(f.length + 3);
|
|
|
+
|
|
|
+const PACKAGE_DIR = arg('out') || path.join(ROOT, '.local-release/onboarding-package');
|
|
|
+const PARSE = 'https://server.fmode.cn/parse';
|
|
|
+const APP_ID = 'ncloudmaster';
|
|
|
+const READ = { 'X-Parse-Application-Id': APP_ID, 'X-Parse-Master-Key': readMasterKey() };
|
|
|
+
|
|
|
+function readMasterKey() {
|
|
|
+ if (process.env.PARSE_MASTER_KEY) return process.env.PARSE_MASTER_KEY;
|
|
|
+ try {
|
|
|
+ return JSON.parse(fs.readFileSync(path.join(ROOT, '.claude/dev-login.json'), 'utf8')).masterKey;
|
|
|
+ } catch {
|
|
|
+ throw new Error('缺少 masterKey(PARSE_MASTER_KEY 或 .claude/dev-login.json)');
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+const log = (s) => console.log(s);
|
|
|
+const step = (n, s) => console.log(`\n[${n}] ${s}`);
|
|
|
+
|
|
|
+/* ---------- 1. 核对(默认动作,只读) ---------- */
|
|
|
+async function verify() {
|
|
|
+ step('1', '核对:仓库 / 线上云函数 / 包指针');
|
|
|
+ const local = fs.readFileSync(path.join(ROOT, 'cloud/functions/fmode-provisioning.js'), 'utf8');
|
|
|
+ const remote = await (await fetch(`${PARSE}/classes/Function/VtW1GT93Ax`, { headers: READ })).json();
|
|
|
+ const bundle = JSON.parse(fs.readFileSync(path.join(ROOT, 'cloud/onboarding/bundle.json'), 'utf8'));
|
|
|
+ const inLocal = local.includes(bundle.sha256);
|
|
|
+ const inRemote = (remote.code || '').includes(bundle.sha256);
|
|
|
+
|
|
|
+ const r = await fetch(bundle.url, { signal: AbortSignal.timeout(30000) });
|
|
|
+ const online = r.ok ? createHash('sha256').update(Buffer.from(await r.arrayBuffer())).digest('hex') : null;
|
|
|
+
|
|
|
+ const features = ['_validName', 'TRIAL_MS', 'trialEndsAt', 'planCode', 'FMODE_NATIVE_V1', 'FmodeBridgeOwned', 'busy_input_mode'];
|
|
|
+ const rows = [
|
|
|
+ ['云函数 本地==线上', remote.code === local ? '✅' : '❌ 需要 --deploy'],
|
|
|
+ ['包指针 已注入本地', inLocal ? '✅' : '❌'],
|
|
|
+ ['包指针 已注入线上', inRemote ? '✅' : '❌ 需要 --deploy'],
|
|
|
+ ['s3 对象可读且 sha 一致', online === bundle.sha256 ? '✅' : `❌ (${online?.slice(0, 16) ?? 'unreachable'})`],
|
|
|
+ ];
|
|
|
+ for (const row of rows) log(` ${row[0].padEnd(24)} ${row[1]}`);
|
|
|
+ log(` 包: ${bundle.sha256.slice(0, 16)} ${bundle.url.split('/').pop()}`);
|
|
|
+ const missing = features.filter((f) => !local.includes(f));
|
|
|
+ log(` 能力: ${missing.length ? '❌ 缺少 ' + missing.join(',') : '✅ ' + features.length + ' 项齐全'}`);
|
|
|
+ if (!has('--build') && !has('--publish') && !has('--deploy') && !arg('refresh-containers')) {
|
|
|
+ log('\n(只读核对完成。发布请加 --all --approved-by=<手机号>)');
|
|
|
+ }
|
|
|
+ return rows.every((x) => !x[1].startsWith('❌'));
|
|
|
+}
|
|
|
+
|
|
|
+/* ---------- 2. 打包 ---------- */
|
|
|
+function build() {
|
|
|
+ step('2', '打包接入包');
|
|
|
+ const out = execFileSync('python', ['scripts/build-onboarding-bundle.py', '--out', PACKAGE_DIR], { encoding: 'utf8', cwd: ROOT });
|
|
|
+ const receipt = JSON.parse(fs.readFileSync(path.join(PACKAGE_DIR, 'receipt.json'), 'utf8'));
|
|
|
+ if (receipt.containsCredentials) throw new Error('包内发现凭据,停止');
|
|
|
+ log(' ' + out.trim());
|
|
|
+ return receipt;
|
|
|
+}
|
|
|
+
|
|
|
+/* ---------- 3. 上传 + 回验 + 更新 bundle.json ---------- */
|
|
|
+async function publish(approvedBy) {
|
|
|
+ if (!approvedBy) throw new Error('--publish 必须带 --approved-by=<手机号>(发布人确认门禁)');
|
|
|
+ step('3', '上传 s3 并回验');
|
|
|
+ const cfg = JSON.parse(fs.readFileSync(path.join(ROOT, '.claude/dev-login.json'), 'utf8'));
|
|
|
+ const receipt = JSON.parse(fs.readFileSync(path.join(PACKAGE_DIR, 'receipt.json'), 'utf8'));
|
|
|
+ const bytes = fs.readFileSync(receipt.archive);
|
|
|
+ const sha = createHash('sha256').update(bytes).digest('hex');
|
|
|
+ if (sha !== receipt.sha256) throw new Error('包摘要与 receipt 不一致');
|
|
|
+
|
|
|
+ const filename = `fmode-onboarding-${receipt.version}-${sha.slice(0, 16)}.tar.gz`;
|
|
|
+ const H = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': APP_ID, 'X-Parse-Session-Token': cfg.token };
|
|
|
+ const ticket = await (await fetch('https://server.fmode.cn/api/functions', {
|
|
|
+ method: 'POST', headers: H,
|
|
|
+ body: JSON.stringify({ id: 'AlP56LCKFm', token: cfg.token, params: { filename, mimeType: 'application/gzip', size: bytes.length } }),
|
|
|
+ })).json();
|
|
|
+ if (ticket.code !== 200) throw new Error('申请上传票据失败:' + JSON.stringify(ticket).slice(0, 200));
|
|
|
+
|
|
|
+ const put = await fetch(ticket.uploadUrl, { method: 'PUT', headers: { 'Content-Type': 'application/gzip', ...(ticket.headers || {}) }, body: bytes });
|
|
|
+ if (!put.ok) throw new Error('上传失败 HTTP ' + put.status);
|
|
|
+ const remote = Buffer.from(await (await fetch(ticket.publicUrl)).arrayBuffer());
|
|
|
+ if (createHash('sha256').update(remote).digest('hex') !== sha) throw new Error('回验 sha 不一致');
|
|
|
+
|
|
|
+ const bundle = { version: receipt.version, image: 'fmode/agent-node:0.21.3', url: ticket.publicUrl, sha256: sha, bytes: remote.length };
|
|
|
+ fs.writeFileSync(path.join(ROOT, 'cloud/onboarding/bundle.json'), JSON.stringify(bundle, null, 2) + '\n');
|
|
|
+ const ledger = { approvedBy, at: new Date().toISOString(), bundle };
|
|
|
+ fs.mkdirSync(PACKAGE_DIR, { recursive: true });
|
|
|
+ fs.writeFileSync(path.join(PACKAGE_DIR, 'publish-ledger.json'), JSON.stringify(ledger, null, 2));
|
|
|
+ log(' ✅ 已发布 ' + ticket.publicUrl);
|
|
|
+ return bundle;
|
|
|
+}
|
|
|
+
|
|
|
+/* ---------- 4. 注入提示词 + 部署云函数 ---------- */
|
|
|
+function deploy() {
|
|
|
+ step('4', '注入提示词并部署云函数');
|
|
|
+ const patch = execFileSync('node', ['-e', `
|
|
|
+ import('./scripts/onboarding-cloud-patch.mjs').then(m => {
|
|
|
+ const fs = require('fs');
|
|
|
+ const p = 'cloud/functions/fmode-provisioning.js';
|
|
|
+ fs.writeFileSync(p, m.patchOnboarding(fs.readFileSync(p,'utf8'), JSON.parse(fs.readFileSync('cloud/onboarding/bundle.json'))));
|
|
|
+ console.log('patched');
|
|
|
+ });`], { encoding: 'utf8', cwd: ROOT });
|
|
|
+ log(' ' + patch.trim());
|
|
|
+ execFileSync('node', ['--check', 'cloud/functions/fmode-provisioning.js'], { cwd: ROOT });
|
|
|
+ const out = execFileSync('node', ['scripts/deploy-cloud-fn.mjs', '--apply', '--only=fmode-provisioning'], {
|
|
|
+ encoding: 'utf8', cwd: ROOT, env: { ...process.env, PARSE_MASTER_KEY: readMasterKey() },
|
|
|
+ });
|
|
|
+ log(out.split('\n').filter((l) => l.includes('热更') || l.includes('ERROR')).join('\n') || out.slice(-300));
|
|
|
+}
|
|
|
+
|
|
|
+/* ---------- 5. 刷新存量平台容器 ---------- */
|
|
|
+function refreshContainers(names) {
|
|
|
+ step('5', '刷新存量容器到最新接入包');
|
|
|
+ const list = names.split(',').map((s) => s.trim()).filter(Boolean);
|
|
|
+ if (!list.length) throw new Error('必须显式指定容器名,禁止批量');
|
|
|
+ const bundle = JSON.parse(fs.readFileSync(path.join(ROOT, 'cloud/onboarding/bundle.json'), 'utf8'));
|
|
|
+ // 生成在 R730 上执行的脚本:容器内下载新包 → install.py(容器数据目录就是 /opt/data)→ 重启网关
|
|
|
+ const script = ['set -e'];
|
|
|
+ for (const c of list) {
|
|
|
+ const dir = `/opt/fmode-containers/${c}/data`;
|
|
|
+ script.push(`echo "[CONTAINER] ${c}"`);
|
|
|
+ script.push(`docker exec ${c} sh -c 'python3 - <<PY_END
|
|
|
+import hashlib, io, tarfile, tempfile, urllib.request, subprocess, sys, pathlib
|
|
|
+url=${JSON.stringify(bundle.url)}
|
|
|
+expected=${JSON.stringify(bundle.sha256)}
|
|
|
+data=urllib.request.urlopen(url,timeout=60).read(2097153)
|
|
|
+assert len(data)<=2097152 and hashlib.sha256(data).hexdigest()==expected, "sha mismatch"
|
|
|
+d=tempfile.mkdtemp(prefix="fmode-onboard-")
|
|
|
+with tarfile.open(fileobj=io.BytesIO(data),mode="r:gz") as a: a.extractall(d,filter="data")
|
|
|
+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)
|
|
|
+print(r.returncode, r.stdout[-500:], r.stderr[-800:])
|
|
|
+PY_END'`);
|
|
|
+ script.push(`docker exec ${c} /command/s6-svc -r /run/service/gateway-default || docker restart ${c}`);
|
|
|
+ script.push(`echo "[RESTARTED] ${c}"`);
|
|
|
+ }
|
|
|
+ const f = path.join(ROOT, '.local-release', `refresh-${Date.now()}.sh`);
|
|
|
+ fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
|
+ fs.writeFileSync(f, script.join('\n'));
|
|
|
+ const out = execFileSync('python', [path.join(ROOT, '.local-backup/skill-lock-20261201/r730.py'), f, '300'], { encoding: 'utf8', cwd: ROOT });
|
|
|
+ log(out.slice(-1500));
|
|
|
+}
|
|
|
+
|
|
|
+async function main() {
|
|
|
+ const approvedBy = arg('approved-by');
|
|
|
+ const doAll = has('--all');
|
|
|
+ try {
|
|
|
+ await verify();
|
|
|
+ if (doAll || has('--build')) build();
|
|
|
+ if (doAll || has('--publish')) await publish(approvedBy);
|
|
|
+ if (doAll || has('--deploy')) deploy();
|
|
|
+ if (arg('refresh-containers')) refreshContainers(arg('refresh-containers'));
|
|
|
+ if (doAll) {
|
|
|
+ step('6', '发布后复核');
|
|
|
+ await verify();
|
|
|
+ }
|
|
|
+ } catch (e) {
|
|
|
+ console.error('\n❌ 停止:' + e.message);
|
|
|
+ process.exit(1);
|
|
|
+ }
|
|
|
+}
|
|
|
+main();
|