mirror of
https://github.com/XiaoDaiGua-Ray/ray-template.git
synced 2026-11-17 16:13:36 +08:00
Enforce live session grants for runtime routes and support profile and credential updates in both the backend and demo modes. Add the account settings workspace and document fullstack setup and PC acceptance.
403 lines
11 KiB
JavaScript
403 lines
11 KiB
JavaScript
import { spawn } from 'node:child_process'
|
|
import { randomBytes } from 'node:crypto'
|
|
import {
|
|
appendFileSync,
|
|
chmodSync,
|
|
existsSync,
|
|
readFileSync,
|
|
writeFileSync,
|
|
} from 'node:fs'
|
|
import { createServer } from 'node:net'
|
|
import { setTimeout as delay } from 'node:timers/promises'
|
|
import { fileURLToPath } from 'node:url'
|
|
import { parseEnv } from 'node:util'
|
|
|
|
const root = fileURLToPath(new URL('../', import.meta.url))
|
|
const envFile = new URL('../apps/server/.env.local', import.meta.url)
|
|
const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'
|
|
const [action, ...flags] = process.argv.slice(2)
|
|
|
|
if (
|
|
!['setup', 'dev', 'up', 'stop'].includes(action) ||
|
|
(flags.length > 0 && (action !== 'setup' || flags.join(' ') !== '--external'))
|
|
) {
|
|
console.error(
|
|
'Use pnpm fullstack:setup [--external], pnpm dev:full, pnpm fullstack:up, or pnpm fullstack:stop.',
|
|
)
|
|
process.exit(1)
|
|
}
|
|
|
|
function run(command, args, env = process.env) {
|
|
return new Promise((resolve, reject) => {
|
|
const child = spawn(command, args, {
|
|
cwd: root,
|
|
env,
|
|
stdio: 'inherit',
|
|
shell: process.platform === 'win32' && command === pnpm,
|
|
})
|
|
|
|
child.once('error', () =>
|
|
reject(
|
|
new Error(
|
|
`${command} could not start. Install it or use pnpm fullstack:setup --external with existing PostgreSQL and Redis.`,
|
|
),
|
|
),
|
|
)
|
|
child.once('exit', (code) =>
|
|
code === 0
|
|
? resolve()
|
|
: reject(new Error(`${command} exited with code ${code}.`)),
|
|
)
|
|
})
|
|
}
|
|
|
|
function configuration() {
|
|
if (!existsSync(envFile))
|
|
throw new Error(
|
|
'Run pnpm fullstack:setup first (or pnpm fullstack:setup --external with DATABASE_URL and REDIS_URL).',
|
|
)
|
|
|
|
return { ...parseEnv(readFileSync(envFile, 'utf8')), ...process.env }
|
|
}
|
|
|
|
function compose(env) {
|
|
const project = env.RAY_COMPOSE_PROJECT ?? 'ray-template'
|
|
|
|
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(project))
|
|
throw new Error('RAY_COMPOSE_PROJECT must be a valid Compose project name.')
|
|
|
|
return [
|
|
'compose',
|
|
'--project-name',
|
|
project,
|
|
'--env-file',
|
|
fileURLToPath(envFile),
|
|
'-f',
|
|
'deploy/compose.yaml',
|
|
]
|
|
}
|
|
|
|
function portFrom(env, key, fallback) {
|
|
const port = env[key] ?? fallback
|
|
|
|
if (!/^\d{1,5}$/u.test(port) || Number(port) < 1 || Number(port) > 65535)
|
|
throw new Error(`${key} must be a port between 1 and 65535.`)
|
|
|
|
return String(Number(port))
|
|
}
|
|
|
|
const devOrigins = (port) => [
|
|
new URL(`http://127.0.0.1:${port}`).origin,
|
|
new URL(`http://localhost:${port}`).origin,
|
|
]
|
|
|
|
async function verifyBackendPort(port) {
|
|
await new Promise((resolve, reject) => {
|
|
const probe = createServer()
|
|
|
|
probe.once('error', () =>
|
|
reject(new Error(`Backend port ${port} is not available on 127.0.0.1.`)),
|
|
)
|
|
probe.listen(Number(port), '127.0.0.1', () => probe.close(resolve))
|
|
})
|
|
}
|
|
|
|
async function dev(env) {
|
|
const port = portFrom(env, 'PORT', '3000')
|
|
const adminPort = portFrom(env, 'ADMIN_DEV_PORT', '9527')
|
|
|
|
if (port === adminPort)
|
|
throw new Error('PORT and ADMIN_DEV_PORT must differ.')
|
|
|
|
await verifyBackendPort(port)
|
|
|
|
const target = `http://127.0.0.1:${port}`
|
|
const serverEnv = {
|
|
...env,
|
|
HOST: '127.0.0.1',
|
|
PORT: port,
|
|
CORS_ORIGINS: [
|
|
...new Set([
|
|
...(env.CORS_ORIGINS?.split(',')
|
|
.map((value) => value.trim())
|
|
.filter(Boolean) ?? []),
|
|
...devOrigins(adminPort),
|
|
]),
|
|
].join(','),
|
|
}
|
|
const controller = new AbortController()
|
|
const { signal } = controller
|
|
const children = new Set()
|
|
const windows = process.platform === 'win32'
|
|
|
|
const terminate = (child, killSignal) => {
|
|
if (!child.pid) return
|
|
|
|
if (windows) {
|
|
const killer = spawn(
|
|
'taskkill',
|
|
['/pid', String(child.pid), '/t', '/f'],
|
|
{
|
|
stdio: 'ignore',
|
|
},
|
|
)
|
|
|
|
killer.once('error', () => child.kill())
|
|
|
|
return
|
|
}
|
|
|
|
try {
|
|
process.kill(-child.pid, killSignal)
|
|
} catch (error) {
|
|
if (error.code !== 'ESRCH') throw error
|
|
}
|
|
}
|
|
const stop = (reason) => {
|
|
if (signal.aborted) return
|
|
|
|
controller.abort()
|
|
|
|
if (reason) {
|
|
console.error(reason)
|
|
process.exitCode = 1
|
|
}
|
|
|
|
const running = [...children]
|
|
|
|
for (const child of running) terminate(child, 'SIGTERM')
|
|
|
|
if (running.length && !windows) {
|
|
setTimeout(() => {
|
|
for (const child of running) terminate(child, 'SIGKILL')
|
|
}, 6000).unref()
|
|
}
|
|
}
|
|
const start = (label, args, processEnv, persistent = false) =>
|
|
new Promise((resolve) => {
|
|
// pnpm 会再启动脚本进程,退出时需要回收完整进程树。
|
|
const child = spawn(pnpm, args, {
|
|
cwd: root,
|
|
env: processEnv,
|
|
stdio: 'inherit',
|
|
detached: !windows,
|
|
shell: windows,
|
|
})
|
|
|
|
children.add(child)
|
|
const finish = (code) => {
|
|
if (!signal.aborted && (persistent || code !== 0))
|
|
stop(`${label} stopped unexpectedly.`)
|
|
|
|
children.delete(child)
|
|
resolve()
|
|
}
|
|
|
|
child.once('error', () => finish(1))
|
|
child.once('exit', finish)
|
|
})
|
|
const interrupt = () => stop()
|
|
|
|
process.on('SIGINT', interrupt)
|
|
process.on('SIGTERM', interrupt)
|
|
|
|
try {
|
|
await start(
|
|
'Prisma generation',
|
|
['--filter', '@ray-template/server', 'db:generate'],
|
|
serverEnv,
|
|
)
|
|
|
|
if (signal.aborted) return
|
|
|
|
const backend = start('Backend', ['server:dev'], serverEnv, true)
|
|
let ready = false
|
|
const deadline = Date.now() + 30000
|
|
|
|
while (!signal.aborted && Date.now() < deadline) {
|
|
try {
|
|
const response = await fetch(`${target}/api/health/ready`, {
|
|
signal: AbortSignal.any([signal, AbortSignal.timeout(1000)]),
|
|
})
|
|
|
|
if (response.ok) {
|
|
ready = true
|
|
break
|
|
}
|
|
} catch {
|
|
/* 启动时允许后端尚未监听。 */
|
|
}
|
|
|
|
await delay(300, void 0, { signal }).catch(() => {})
|
|
}
|
|
|
|
if (!ready || signal.aborted) {
|
|
if (!signal.aborted)
|
|
stop(
|
|
'Backend readiness timed out. Verify PostgreSQL, Redis and database initialization with pnpm fullstack:setup.',
|
|
)
|
|
|
|
await backend
|
|
|
|
return
|
|
}
|
|
|
|
await Promise.all([
|
|
backend,
|
|
start(
|
|
'Admin',
|
|
['dev', '--port', adminPort, '--strictPort'],
|
|
{
|
|
...process.env,
|
|
VITE_API_MOCK: 'false',
|
|
VITE_API_BASE_URL: '/api/',
|
|
VITE_API_AUTH_TRANSPORT: 'cookie',
|
|
RAY_API_PROXY_TARGET: target,
|
|
},
|
|
true,
|
|
),
|
|
])
|
|
} finally {
|
|
process.off('SIGINT', interrupt)
|
|
process.off('SIGTERM', interrupt)
|
|
}
|
|
}
|
|
|
|
try {
|
|
if (action === 'setup' || action === 'up') {
|
|
const external = flags.includes('--external')
|
|
|
|
if (!existsSync(envFile)) {
|
|
if (external && (!process.env.DATABASE_URL || !process.env.REDIS_URL))
|
|
throw new Error('External setup requires DATABASE_URL and REDIS_URL.')
|
|
|
|
const password = randomBytes(24).toString('base64url')
|
|
const redisPassword = randomBytes(24).toString('base64url')
|
|
const postgresPort = portFrom(process.env, 'POSTGRES_PORT', '5432')
|
|
const redisPort = portFrom(process.env, 'REDIS_PORT', '6379')
|
|
const adminPort = portFrom(process.env, 'ADMIN_DEV_PORT', '9527')
|
|
const values = {
|
|
NODE_ENV: 'development',
|
|
RAY_FULLSTACK_SERVICES: external ? 'external' : 'compose',
|
|
RAY_COMPOSE_PROJECT: process.env.RAY_COMPOSE_PROJECT || 'ray-template',
|
|
HOST: '127.0.0.1',
|
|
PORT: portFrom(process.env, 'PORT', '3000'),
|
|
ADMIN_DEV_PORT: adminPort,
|
|
POSTGRES_USER: 'ray',
|
|
POSTGRES_DB: 'ray_template',
|
|
POSTGRES_PASSWORD: password,
|
|
POSTGRES_PORT: postgresPort,
|
|
REDIS_PASSWORD: redisPassword,
|
|
REDIS_PORT: redisPort,
|
|
APP_PORT: portFrom(process.env, 'APP_PORT', '8080'),
|
|
APP_PROXY_NETWORK: process.env.APP_PROXY_NETWORK || '172.30.67',
|
|
DATABASE_URL: external
|
|
? process.env.DATABASE_URL
|
|
: `postgresql://ray:${password}@127.0.0.1:${postgresPort}/ray_template`,
|
|
REDIS_URL: external
|
|
? process.env.REDIS_URL
|
|
: `redis://:${redisPassword}@127.0.0.1:${redisPort}`,
|
|
ADMIN_USERNAME: process.env.ADMIN_USERNAME || 'admin',
|
|
ADMIN_EMAIL: process.env.ADMIN_EMAIL || 'admin@example.com',
|
|
ADMIN_PASSWORD:
|
|
process.env.ADMIN_PASSWORD || randomBytes(18).toString('base64url'),
|
|
CORS_ORIGINS: devOrigins(adminPort).join(','),
|
|
TRUST_PROXY: 'false',
|
|
DEMO_ENABLED: 'true',
|
|
JWT_SECRET: randomBytes(32).toString('base64url'),
|
|
}
|
|
|
|
// 配置只创建一次,避免重复初始化覆盖用户配置和已修改的凭据。
|
|
writeFileSync(
|
|
envFile,
|
|
Object.entries(values)
|
|
.map(([key, value]) => `${key}=${JSON.stringify(value)}`)
|
|
.join('\n') + '\n',
|
|
{ flag: 'wx', mode: 0o600 },
|
|
)
|
|
console.log(
|
|
'Created apps/server/.env.local. Initial administrator credentials are stored there; keep this file private.',
|
|
)
|
|
} else {
|
|
const saved = parseEnv(readFileSync(envFile, 'utf8'))
|
|
const additions = []
|
|
|
|
// 升级时只补缺少的字段,保留已有连接和管理员配置。
|
|
if (!('JWT_SECRET' in saved))
|
|
additions.push(`JWT_SECRET=${randomBytes(32).toString('base64url')}`)
|
|
|
|
if (external && !('RAY_FULLSTACK_SERVICES' in saved))
|
|
additions.push('RAY_FULLSTACK_SERVICES=external')
|
|
|
|
if (additions.length) {
|
|
if (process.platform !== 'win32') chmodSync(envFile, 0o600)
|
|
|
|
appendFileSync(envFile, `\n${additions.join('\n')}\n`)
|
|
console.log('Updated apps/server/.env.local for this version.')
|
|
}
|
|
}
|
|
|
|
const env = configuration()
|
|
|
|
if (!external && env.RAY_FULLSTACK_SERVICES === 'external')
|
|
throw new Error(
|
|
'This workspace uses external services. Run pnpm fullstack:setup --external or configure Compose in a separate checkout.',
|
|
)
|
|
|
|
if (action === 'up') {
|
|
const port = portFrom(env, 'APP_PORT', '8080')
|
|
|
|
await run(
|
|
'docker',
|
|
[
|
|
...compose(env),
|
|
'--profile',
|
|
'app',
|
|
'up',
|
|
'--build',
|
|
'-d',
|
|
'--wait',
|
|
'--wait-timeout',
|
|
'180',
|
|
],
|
|
{ ...env, APP_PORT: port },
|
|
)
|
|
console.log(
|
|
`Fullstack services ready at http://127.0.0.1:${port}/ray-template/.`,
|
|
)
|
|
} else {
|
|
if (external && (!env.DATABASE_URL || !env.REDIS_URL))
|
|
throw new Error('External setup requires DATABASE_URL and REDIS_URL.')
|
|
|
|
if (!external)
|
|
await run(
|
|
'docker',
|
|
[...compose(env), 'up', '-d', '--wait', 'postgres', 'redis'],
|
|
env,
|
|
)
|
|
|
|
await run(pnpm, ['server:db:migrate'], env)
|
|
await run(pnpm, ['server:db:seed'], env)
|
|
console.log(
|
|
'Fullstack setup complete. Run pnpm dev:full; use the administrator account from apps/server/.env.local.',
|
|
)
|
|
}
|
|
} else if (action === 'stop') {
|
|
const env = configuration()
|
|
|
|
if (env.RAY_FULLSTACK_SERVICES === 'external')
|
|
throw new Error(
|
|
'Stop external services through their own deployment environment.',
|
|
)
|
|
|
|
await run('docker', [...compose(env), '--profile', 'app', 'stop'], env)
|
|
} else {
|
|
await dev(configuration())
|
|
}
|
|
} catch (error) {
|
|
console.error(
|
|
error instanceof Error ? error.message : 'Fullstack command failed.',
|
|
)
|
|
process.exitCode = 1
|
|
}
|