Restore PROMPT branding, rename waterfall-wiki, and add system tag workflows
waterfall-wiki CI and deployment / verify-and-deploy (push) Has been cancelled
studio CI and deployment / verify-and-deploy (push) Successful in 9m15s

This commit is contained in:
2026-10-27 00:35:59 +08:00
parent 0c1ed2d292
commit ad398db781
178 changed files with 585 additions and 365 deletions
+81
View File
@@ -0,0 +1,81 @@
import { mkdirSync, writeFileSync, existsSync, renameSync, chmodSync, chownSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import assert from 'node:assert/strict';
import QRCode from 'qrcode';
import { authConfig, newAuthConfig, signSession, totp } from '../src/lib/auth';
import { db } from '../src/lib/db';
async function main() {
const command = process.argv[2];
const file = process.env.AUTH_CONFIG_FILE;
if (!file) throw Error('Set AUTH_CONFIG_FILE before running the server authentication tool');
if (command === 'init' || command === 'rotate') {
if (command === 'rotate' && !process.argv.includes('--confirm')) throw Error('Rotation invalidates all authenticators and sessions; pass --confirm to proceed');
if (command === 'init' && existsSync(file)) { authConfig(); console.log('Authentication configuration already exists; preserved'); return; }
mkdirSync(dirname(file),{recursive:true,mode:0o700});
const temporary = file + '.' + process.pid + '.tmp';
writeFileSync(temporary,JSON.stringify(newAuthConfig())+'\n',{mode:0o600,flag:'wx'});
if (process.getuid?.() === 0) { chownSync(dirname(file),1000,1000); chownSync(temporary,1000,1000); }
chmodSync(dirname(file),0o700); renameSync(temporary,file);
console.log('Authentication configuration saved privately. Use the qr command in an SSH terminal to bind.'); return;
}
const config = authConfig(); if (!config) throw Error('Authentication is not configured');
if (command === 'qr') {
if (!process.stdout.isTTY) throw Error('QR display requires an interactive SSH terminal (ssh -t, docker compose exec without -T). Never send QR output to CI logs.');
const uri = 'otpauth://totp/PROMPT:shared?'+new URLSearchParams({secret:config.secret,issuer:'PROMPT',algorithm:'SHA1',digits:'6',period:'30'});
console.log('Private binding QR — everyone scanning this uses the same authenticator key.');
console.log(await QRCode.toString(uri,{type:'terminal',small:true,errorCorrectionLevel:'M'}));
return;
}
if (command === 'token') {
if (!process.stdout.isTTY) throw Error('Tokens may only be displayed in an interactive SSH terminal');
console.log(signSession(config,undefined,3600)); return;
}
const base = process.env.AUTH_CHECK_BASE_URL || 'http://127.0.0.1:3000';
if (command === 'run') {
const script = process.argv[3]; if (!script) throw Error('Provide a server-side script path');
const original = globalThis.fetch; const token = signSession(config,undefined,600);
// Only attach the credential to the local application, never to remote fetches.
globalThis.fetch = (input,init) => {
const url = new URL(input instanceof Request ? input.url : String(input));
if (url.origin === new URL(base).origin) { const headers = new Headers(init?.headers || (input instanceof Request ? input.headers : undefined)); headers.set('Authorization','Bearer '+token); return original(input,{...init,headers}); }
return original(input,init);
};
await import(pathToFileURL(resolve(script)).href); return;
}
if (command === 'verify' || command === 'exercise') {
const request = (path:string,init:RequestInit={}) => fetch(base+path,{...init,redirect:'manual'});
for (const path of ['/','/library/import','/skills/shadow-puppet/egret-example.png','/studio','/_next/data/auth-test/index.json']) {
const response = await request(path); assert.equal(response.status,307,path); assert.match(response.headers.get('location') || '',/\/login\?/);
}
for (const path of ['/api/feed','/api/upload','/studio/api/export/test','/api/media/missing']) assert.equal((await request(path)).status,401,path);
assert.equal((await request('/api/posts',{method:'POST',body:'{}'})).status,401);
assert.equal((await request('/api/feed',{headers:{'x-middleware-subrequest':'proxy:proxy:proxy:proxy:proxy'}})).status,401);
const page = await request('/login'); assert.equal(page.status,200); const html = await page.text(); assert.ok(html.includes('输入动态码')); assert.ok(!html.includes(config.secret));
assert.equal((await request('/api/health')).status,200);
const headers = {Authorization:'Bearer '+signSession(config,undefined,600)};
assert.equal((await request('/api/feed',{headers})).status,200);
assert.equal((await request('/api/feed',{headers:{Authorization:headers.Authorization+'x'}})).status,401);
if (command === 'exercise') {
const origin = new URL(base).origin;
const login = (code:string,customOrigin=origin) => request('/api/auth/login',{method:'POST',headers:{'Content-Type':'application/json',Origin:customOrigin},body:JSON.stringify({code})});
assert.equal((await login('000000','https://untrusted.example')).status,403);
const code = totp(config.secret,Math.floor(Date.now()/30000));
const results = await Promise.all([login(code),login(code)]);
assert.deepEqual(results.map(r=>r.status).sort(),[200,401],'exactly one concurrent use succeeds');
const cookie = results.find(r=>r.status===200)!.headers.get('set-cookie')!;
assert.match(cookie,/HttpOnly/); assert.match(cookie,/SameSite=Lax/); assert.match(cookie,/Max-Age=604800/);
const session = cookie.split(';')[0];
assert.equal((await request('/api/feed',{headers:{Cookie:session}})).status,200);
assert.equal((await request('/api/posts',{method:'POST',headers:{Cookie:session,Origin:'https://untrusted.example'}})).status,403);
const logout = await request('/api/auth/logout',{method:'POST',headers:{Cookie:session,Origin:origin}}); assert.equal(logout.status,200); assert.match(logout.headers.get('set-cookie')!,/Max-Age=0/);
let status = 0; for (let i=0;i<21;i++) status=(await login('invalid')).status; assert.equal(status,429);
// Durable throttling remains even after this test process exits.
assert.equal((await login(code)).status,429);
}
console.log('Dynamic-code authentication '+command+' passed (no secrets displayed)'); return;
}
throw Error('Usage: auth-cli.cjs init | qr | rotate --confirm | token | run <script> | verify | exercise');
}
main().catch(error=>{console.error(error instanceof Error?error.message:'Authentication command failed');process.exitCode=1;}).finally(async()=>{if (process.env.DATABASE_URL) await db().end().catch(()=>{});});
+20
View File
@@ -0,0 +1,20 @@
import { readdir,readFile } from "node:fs/promises";
import { db } from "../src/lib/db";
import { ensureBucket } from "../src/lib/storage";
import { setTimeout } from "node:timers/promises";
async function main(){
for(let i=0;;i++){try{await db().query('SELECT 1');break;}catch(e){if(i>=60)throw e;await setTimeout(2000);}}
const client=await db().connect();
try{
await client.query('SELECT pg_advisory_lock(18131001)');
for(const name of (await readdir('db')).filter(n=>n.endsWith('.sql')).sort()){
const present=await client.query("SELECT to_regclass('public.schema_migrations') AS table");
if(present.rows[0].table && (await client.query('SELECT 1 FROM schema_migrations WHERE version=$1',[name.replace('.sql','')])).rowCount)continue;
await client.query(await readFile('db/'+name,'utf8'));console.log('Applied migration '+name);
}
}catch(error){await client.query('ROLLBACK');throw error;}
finally{await client.query('SELECT pg_advisory_unlock(18131001)');client.release();}
for(let i=0;;i++){try{await ensureBucket();break;}catch(e){if(i>=90)throw e;await setTimeout(2000);}}
console.log('PostgreSQL and S3 are ready');await db().end();
}
main().catch(error=>{console.error('Storage bootstrap failed:',error instanceof Error?error.message:'Unknown error');process.exit(1);});
@@ -0,0 +1,9 @@
try {
const port = process.env.PORT || '3000';
const [health, ready] = await Promise.all([
fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(5000) }),
fetch(`http://127.0.0.1:${port}/api/ready`, { signal: AbortSignal.timeout(5000) }),
]);
const data = await health.json();
if (!health.ok || !ready.ok || data.service !== 'prompt' || data.release !== (process.env.RELEASE_SHA || 'development')) process.exit(1);
} catch { process.exit(1); }
@@ -0,0 +1,29 @@
import {readFile,readdir} from 'node:fs/promises';
import {fileURLToPath} from 'node:url';
import {join,dirname} from 'node:path';
const root=join(dirname(fileURLToPath(import.meta.url)),'..','seed','characters');
const base=process.env.PROMPT_IMPORT_BASE_URL||'http://127.0.0.1:3000';
const packs=JSON.parse(await readFile(join(root,'packs.json'),'utf8'));
async function verify(pack){
const response=await fetch(`${base}/api/feed?section=images&q=${encodeURIComponent(pack.title)}`);
if(!response.ok)throw new Error(`Cannot verify feed: ${response.status}`);
const post=(await response.json()).posts.find(p=>p.slug===pack.slug);
const images=post?.assets.filter(a=>a.kind==='image');
if(images?.length!==pack.count)throw new Error(`Wrong image count for ${pack.slug}`);
for(const image of images){const media=await fetch(`${base}/api/media/${image.id}`,{method:'HEAD'});if(!media.ok||media.headers.get('content-type')!=='image/png')throw new Error(`Missing PNG ${image.id}`);}
console.log(`Verified: /p/${pack.slug} (${images.length} stored PNGs)`);
}
for(const pack of packs){
const existing=await fetch(`${base}/p/${pack.slug}`);
if(existing.ok){console.log(`Already imported: /p/${pack.slug}`);await verify(pack);continue;}
if(existing.status!==404)throw new Error(`Cannot check pack ${pack.slug}: ${existing.status}`);
const files=(await readdir(join(root,pack.directory))).filter(n=>n.endsWith('.png')).sort();
if(files.length!==pack.count)throw new Error(`Expected ${pack.count} PNGs for ${pack.slug}, got ${files.length}`);
const data=new FormData();data.set('title',pack.title);data.set('slug',pack.slug);data.set('description',pack.description);
for(const file of files)data.append('files',new Blob([await readFile(join(root,pack.directory,file))],{type:'image/png'}),file);
const response=await fetch(`${base}/api/skills/street-people`,{method:'POST',body:data});
if(response.status!==201&&response.status!==409)throw new Error(`Import ${pack.slug}: ${response.status} ${await response.text()}`);
if(response.status===409&&!(await fetch(`${base}/p/${pack.slug}`)).ok)throw new Error(`Conflicting import ${pack.slug}`);
console.log(`Imported: /p/${pack.slug} (${files.length} transparent PNGs)`);
await verify(pack);
}
@@ -0,0 +1,4 @@
import { cp,mkdir,access } from 'node:fs/promises';
await mkdir('.next/standalone/.next',{recursive:true});
await cp('.next/static','.next/standalone/.next/static',{recursive:true});
try{await access('public');await cp('public','.next/standalone/public',{recursive:true});}catch(e){if(e.code!=='ENOENT')throw e;}
@@ -0,0 +1,5 @@
import { db } from "../src/lib/db";
import { publishLearningSeries } from "../src/lib/publish-learning-series";
publishLearningSeries().then(result=>console.log(`Published learning series: ${result.published.join(", ")}; one shared cover: ${result.coverId}`))
.catch(error=>{console.error("Learning series publication failed:",error instanceof Error?error.message:"Unknown error");process.exitCode=1;})
.finally(()=>db().end());
+52
View File
@@ -0,0 +1,52 @@
import { spawn } from "node:child_process";
import assert from "node:assert/strict";
import { setTimeout } from "node:timers/promises";
import { createServer } from "node:net";
import { once } from "node:events";
async function availablePort() {
const server = createServer();
server.listen(0, "127.0.0.1");
await once(server, "listening");
const port = server.address().port;
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
return String(port);
}
const port = process.env.SMOKE_PORT || await availablePort();
const release = "smoke-test";
const child = spawn(process.execPath, [".next/standalone/server.js"], {
env: { ...process.env, PORT: port, HOSTNAME: "127.0.0.1", RELEASE_SHA: release },
stdio: "inherit",
});
try {
let ready = false;
for (let i = 0; i < 40; i++) {
if (child.exitCode !== null) throw new Error(`Server exited: ${child.exitCode}`);
try {
const response = await fetch(`http://127.0.0.1:${port}/api/health`);
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { status: "ok", service: "prompt", release });
ready = true;
break;
} catch { await setTimeout(500); }
}
assert.ok(ready, "Standalone production server must be healthy");
const response = await fetch(`http://127.0.0.1:${port}/api/health`, { method: "POST" });
assert.equal(response.status, 405);
const indexResponse=await fetch(`http://127.0.0.1:${port}/api/wiki-index`);
assert.equal(indexResponse.status,200);
const indexText=await indexResponse.text();
const id=indexText.match(/\/explore\/([a-f0-9]{24})/)?.[1];assert.ok(id);
const agent=await fetch(`http://127.0.0.1:${port}/explore/${id}?agent_mode=True`);
assert.equal(agent.status,200);assert.match(agent.headers.get('content-type'),/text\/plain/);const agentText=await agent.text();assert.match(agentText,/^# /);assert.doesNotMatch(agentText,/^\s*(?:<!doctype html|<html)/i);
const preview=await fetch(`http://127.0.0.1:${port}/api/preview?source=${encodeURIComponent('/skills/shadow-puppet/egret-example.png')}&width=480`);
assert.equal(preview.status,200);assert.match(preview.headers.get('content-type'),/image\/webp/);assert.ok((await preview.arrayBuffer()).byteLength<=100000);
console.log("Production smoke test passed");
} finally {
if (child.exitCode === null && child.signalCode === null) {
const exited = once(child, "exit");
child.kill("SIGTERM");
await exited;
}
}