Compare commits
5
Commits
main
..
5e5a14030a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e5a14030a | ||
|
|
2c5aa01a9a | ||
|
|
1261a9b482 | ||
|
|
e42386a5ee | ||
|
|
d512863aa7 |
@@ -0,0 +1,16 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
data
|
||||||
|
docker-data
|
||||||
|
backups
|
||||||
|
.env
|
||||||
|
.env.docker
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
*.db
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
*.tsbuildinfo
|
||||||
|
test
|
||||||
|
coverage
|
||||||
|
.cursor-sqlite-audit.cjs
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Copy to .env.docker on the server (never commit real secrets).
|
||||||
|
#
|
||||||
|
# Required in production:
|
||||||
|
JWT_SECRET=replace-with-a-long-random-secret
|
||||||
|
#
|
||||||
|
# Frontend origin (your deployed Vue app URL):
|
||||||
|
CORS_ORIGIN=https://your-frontend-domain.example
|
||||||
+3
-2
@@ -6,8 +6,9 @@ NODE_ENV=development
|
|||||||
# CORS (Vue dev server)
|
# CORS (Vue dev server)
|
||||||
CORS_ORIGIN=http://localhost:5173
|
CORS_ORIGIN=http://localhost:5173
|
||||||
|
|
||||||
# SQLite — production database
|
# SQLite — path inside container or on host (DB_PATH or DATABASE_PATH)
|
||||||
# DB_PATH=E:/absolute/path/to/backend-nest/data/app.db
|
# DB_PATH=/app/data/app.db
|
||||||
|
# DATABASE_PATH=/app/data/app.db
|
||||||
|
|
||||||
# JWT — must match legacy Fastify when migrating existing tokens
|
# JWT — must match legacy Fastify when migrating existing tokens
|
||||||
JWT_SECRET=gold-land-dev-secret-change-in-production
|
JWT_SECRET=gold-land-dev-secret-change-in-production
|
||||||
|
|||||||
@@ -2,4 +2,13 @@ node_modules/
|
|||||||
dist/
|
dist/
|
||||||
data/
|
data/
|
||||||
.env
|
.env
|
||||||
|
.env.docker
|
||||||
*.db
|
*.db
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
*.tsbuildinfo
|
||||||
|
backups/
|
||||||
|
docker-data/
|
||||||
|
data/*.db
|
||||||
|
data/*.db-wal
|
||||||
|
data/*.db-shm
|
||||||
|
|||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
FROM node:22.12.0-bookworm-slim AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends python3 make g++ \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY nest-cli.json tsconfig.json tsconfig.build.json ./
|
||||||
|
COPY src ./src
|
||||||
|
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM node:22.12.0-bookworm-slim AS production
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV NODE_ENV=production \
|
||||||
|
PORT=3000 \
|
||||||
|
HOST=0.0.0.0 \
|
||||||
|
DB_PATH=/app/data/app.db
|
||||||
|
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends python3 make g++ \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
|
||||||
|
RUN npm ci --omit=dev \
|
||||||
|
&& npm rebuild better-sqlite3 \
|
||||||
|
&& apt-get purge -y python3 make g++ \
|
||||||
|
&& apt-get autoremove -y \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY --from=builder /app/dist ./dist
|
||||||
|
|
||||||
|
RUN mkdir -p /app/data \
|
||||||
|
&& chown -R node:node /app
|
||||||
|
|
||||||
|
USER node
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||||
|
CMD node -e "fetch('http://127.0.0.1:3000/health').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
|
||||||
|
|
||||||
|
CMD ["node", "dist/main.js"]
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
services:
|
||||||
|
backend:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
image: child-gold-land-backend:latest
|
||||||
|
container_name: child-gold-land-backend
|
||||||
|
ports:
|
||||||
|
- "${PORT:-3000}:3000"
|
||||||
|
env_file:
|
||||||
|
- .env.docker
|
||||||
|
environment:
|
||||||
|
NODE_ENV: production
|
||||||
|
PORT: 3000
|
||||||
|
HOST: 0.0.0.0
|
||||||
|
DB_PATH: /app/data/app.db
|
||||||
|
volumes:
|
||||||
|
# Persistent SQLite storage (WAL/SHM live here too).
|
||||||
|
# On server, replace with e.g. /var/lib/child-gold-land/data:/app/data
|
||||||
|
- sqlite_data:/app/data
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
[
|
||||||
|
"CMD",
|
||||||
|
"node",
|
||||||
|
"-e",
|
||||||
|
"fetch('http://127.0.0.1:3000/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))",
|
||||||
|
]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 20s
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
sqlite_data:
|
||||||
|
name: child-gold-land-sqlite
|
||||||
@@ -99,14 +99,25 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
seedDemoAccount(): void {
|
seedDemoAccount(): void {
|
||||||
|
const demoPasswordHash = bcrypt.hashSync('123456', 10)
|
||||||
const demo = this.findAccountByUsername('demo')
|
const demo = this.findAccountByUsername('demo')
|
||||||
if (demo) return
|
|
||||||
|
if (demo) {
|
||||||
|
// Dev DB may retain a stale hash after recovery/migration — keep demo login predictable.
|
||||||
|
if (process.env.NODE_ENV !== 'production') {
|
||||||
|
this.database
|
||||||
|
.getDb()
|
||||||
|
.prepare('UPDATE auth_accounts SET password_hash = ? WHERE username = ?')
|
||||||
|
.run(demoPasswordHash, 'demo')
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
this.users.ensureUser('demo')
|
this.users.ensureUser('demo')
|
||||||
const account: AuthAccount = {
|
const account: AuthAccount = {
|
||||||
id: randomUUID(),
|
id: randomUUID(),
|
||||||
username: 'demo',
|
username: 'demo',
|
||||||
passwordHash: bcrypt.hashSync('123456', 10),
|
passwordHash: demoPasswordHash,
|
||||||
userId: 'demo',
|
userId: 'demo',
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,11 @@ export class EnvironmentVariables {
|
|||||||
@IsString()
|
@IsString()
|
||||||
DB_PATH?: string
|
DB_PATH?: string
|
||||||
|
|
||||||
|
/** Alias for DB_PATH (e.g. Docker Compose). DB_PATH takes precedence when both are set. */
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
DATABASE_PATH?: string
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
JWT_SECRET?: string
|
JWT_SECRET?: string
|
||||||
@@ -43,7 +48,7 @@ export function validateEnv(config: Record<string, unknown>): EnvironmentVariabl
|
|||||||
PORT: Number(config.PORT ?? 3001),
|
PORT: Number(config.PORT ?? 3001),
|
||||||
HOST: (config.HOST as string | undefined) ?? '0.0.0.0',
|
HOST: (config.HOST as string | undefined) ?? '0.0.0.0',
|
||||||
CORS_ORIGIN: (config.CORS_ORIGIN as string | undefined) ?? 'http://localhost:5173',
|
CORS_ORIGIN: (config.CORS_ORIGIN as string | undefined) ?? 'http://localhost:5173',
|
||||||
DB_PATH: config.DB_PATH as string | undefined,
|
DB_PATH: (config.DB_PATH ?? config.DATABASE_PATH) as string | undefined,
|
||||||
JWT_SECRET: jwtSecret ?? 'gold-land-dev-secret-change-in-production',
|
JWT_SECRET: jwtSecret ?? 'gold-land-dev-secret-change-in-production',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,10 @@ export class DatabaseService implements OnModuleInit, OnModuleDestroy {
|
|||||||
private readonly dbPath: string
|
private readonly dbPath: string
|
||||||
|
|
||||||
constructor(@Optional() @Inject(ConfigService) private readonly config?: ConfigService) {
|
constructor(@Optional() @Inject(ConfigService) private readonly config?: ConfigService) {
|
||||||
const configured = this.config?.get<string>('DB_PATH') ?? process.env.DB_PATH
|
const configured =
|
||||||
|
this.config?.get<string>('DB_PATH') ??
|
||||||
|
process.env.DB_PATH ??
|
||||||
|
process.env.DATABASE_PATH
|
||||||
this.dbPath = configured ?? join(process.cwd(), 'data', 'app.db')
|
this.dbPath = configured ?? join(process.cwd(), 'data', 'app.db')
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -20,7 +23,10 @@ export class DatabaseService implements OnModuleInit, OnModuleDestroy {
|
|||||||
mkdirSync(dirname(this.dbPath), { recursive: true })
|
mkdirSync(dirname(this.dbPath), { recursive: true })
|
||||||
this.db = new Database(this.dbPath)
|
this.db = new Database(this.dbPath)
|
||||||
this.db.pragma('journal_mode = WAL')
|
this.db.pragma('journal_mode = WAL')
|
||||||
runSchemaMigrations(this.db)
|
const applied = runSchemaMigrations(this.db)
|
||||||
|
if (applied.length > 0) {
|
||||||
|
this.logger.log(`Applied migrations: ${applied.join(', ')}`)
|
||||||
|
}
|
||||||
this.logger.log(`SQLite ready at ${this.dbPath}`)
|
this.logger.log(`SQLite ready at ${this.dbPath}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import type Database from 'better-sqlite3'
|
||||||
|
import { SQL_MIGRATIONS } from './migrations'
|
||||||
|
|
||||||
|
const MIGRATIONS_TABLE = 'schema_migrations'
|
||||||
|
|
||||||
|
function ensureMigrationsTable(db: Database.Database): void {
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
applied_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isMigrationApplied(db: Database.Database, id: string): boolean {
|
||||||
|
const row = db
|
||||||
|
.prepare(`SELECT id FROM ${MIGRATIONS_TABLE} WHERE id = ?`)
|
||||||
|
.get(id) as { id: string } | undefined
|
||||||
|
return row !== undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function recordMigrationApplied(db: Database.Database, id: string): void {
|
||||||
|
db.prepare(`INSERT INTO ${MIGRATIONS_TABLE} (id, applied_at) VALUES (?, ?)`).run(
|
||||||
|
id,
|
||||||
|
new Date().toISOString(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Run pending versioned migrations inside a transaction per migration. */
|
||||||
|
export function runPendingMigrations(db: Database.Database): string[] {
|
||||||
|
ensureMigrationsTable(db)
|
||||||
|
|
||||||
|
const applied: string[] = []
|
||||||
|
|
||||||
|
for (const migration of SQL_MIGRATIONS) {
|
||||||
|
if (isMigrationApplied(db, migration.id)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const apply = db.transaction(() => {
|
||||||
|
db.exec(migration.up)
|
||||||
|
recordMigrationApplied(db, migration.id)
|
||||||
|
})
|
||||||
|
|
||||||
|
apply()
|
||||||
|
applied.push(migration.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
return applied
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listAppliedMigrationIds(db: Database.Database): string[] {
|
||||||
|
ensureMigrationsTable(db)
|
||||||
|
const rows = db
|
||||||
|
.prepare(`SELECT id FROM ${MIGRATIONS_TABLE} ORDER BY id`)
|
||||||
|
.all() as Array<{ id: string }>
|
||||||
|
return rows.map((row) => row.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listPendingMigrationIds(db: Database.Database): string[] {
|
||||||
|
ensureMigrationsTable(db)
|
||||||
|
const applied = new Set(listAppliedMigrationIds(db))
|
||||||
|
return SQL_MIGRATIONS.filter((migration) => !applied.has(migration.id)).map(
|
||||||
|
(migration) => migration.id,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,55 +1,17 @@
|
|||||||
import type Database from 'better-sqlite3'
|
import type Database from 'better-sqlite3'
|
||||||
|
import {
|
||||||
|
listAppliedMigrationIds,
|
||||||
|
listPendingMigrationIds,
|
||||||
|
runPendingMigrations,
|
||||||
|
} from './migration-runner'
|
||||||
|
|
||||||
/** Idempotent schema setup — mirrors backend/db.ts + backend/migrations.ts (no destructive ops). */
|
/** Apply all pending versioned SQL migrations (safe to call on every startup). */
|
||||||
export function runSchemaMigrations(db: Database.Database): void {
|
export function runSchemaMigrations(db: Database.Database): string[] {
|
||||||
db.exec(`
|
return runPendingMigrations(db)
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
state_json TEXT NOT NULL,
|
|
||||||
updated_at TEXT NOT NULL
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS user_level_progress (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
user_id TEXT NOT NULL,
|
|
||||||
level_id INTEGER NOT NULL,
|
|
||||||
best_score INTEGER NOT NULL DEFAULT 0,
|
|
||||||
stars INTEGER NOT NULL DEFAULT 0,
|
|
||||||
attempts_count INTEGER NOT NULL DEFAULT 0,
|
|
||||||
started_at TEXT,
|
|
||||||
completed_at TEXT,
|
|
||||||
updated_at TEXT NOT NULL,
|
|
||||||
UNIQUE(user_id, level_id)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS reward_ledger (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
user_id TEXT NOT NULL,
|
|
||||||
source_type TEXT NOT NULL,
|
|
||||||
source_id TEXT NOT NULL,
|
|
||||||
reward_key TEXT NOT NULL,
|
|
||||||
xp_delta INTEGER NOT NULL DEFAULT 0,
|
|
||||||
coins_delta INTEGER NOT NULL DEFAULT 0,
|
|
||||||
metadata_json TEXT,
|
|
||||||
created_at TEXT NOT NULL,
|
|
||||||
UNIQUE(user_id, reward_key)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_user_level_progress_user
|
|
||||||
ON user_level_progress(user_id);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_reward_ledger_user
|
|
||||||
ON reward_ledger(user_id);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS auth_accounts (
|
|
||||||
id TEXT PRIMARY KEY,
|
|
||||||
username TEXT NOT NULL UNIQUE,
|
|
||||||
password_hash TEXT NOT NULL,
|
|
||||||
user_id TEXT NOT NULL,
|
|
||||||
created_at TEXT NOT NULL
|
|
||||||
);
|
|
||||||
`)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export { listAppliedMigrationIds, listPendingMigrationIds }
|
||||||
|
|
||||||
export const EXPECTED_TABLES = [
|
export const EXPECTED_TABLES = [
|
||||||
'users',
|
'users',
|
||||||
'user_level_progress',
|
'user_level_progress',
|
||||||
@@ -61,5 +23,7 @@ export function listUserTables(db: Database.Database): string[] {
|
|||||||
const rows = db
|
const rows = db
|
||||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")
|
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")
|
||||||
.all() as Array<{ name: string }>
|
.all() as Array<{ name: string }>
|
||||||
return rows.map((row) => row.name)
|
return rows
|
||||||
|
.map((row) => row.name)
|
||||||
|
.filter((name) => name !== 'schema_migrations')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
/** Initial application schema — idempotent (CREATE IF NOT EXISTS). */
|
||||||
|
export const migrationId = '001_initial_schema'
|
||||||
|
|
||||||
|
export const up = `
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
state_json TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS user_level_progress (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
user_id TEXT NOT NULL,
|
||||||
|
level_id INTEGER NOT NULL,
|
||||||
|
best_score INTEGER NOT NULL DEFAULT 0,
|
||||||
|
stars INTEGER NOT NULL DEFAULT 0,
|
||||||
|
attempts_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
started_at TEXT,
|
||||||
|
completed_at TEXT,
|
||||||
|
updated_at TEXT NOT NULL,
|
||||||
|
UNIQUE(user_id, level_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS reward_ledger (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
user_id TEXT NOT NULL,
|
||||||
|
source_type TEXT NOT NULL,
|
||||||
|
source_id TEXT NOT NULL,
|
||||||
|
reward_key TEXT NOT NULL,
|
||||||
|
xp_delta INTEGER NOT NULL DEFAULT 0,
|
||||||
|
coins_delta INTEGER NOT NULL DEFAULT 0,
|
||||||
|
metadata_json TEXT,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
UNIQUE(user_id, reward_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_level_progress_user
|
||||||
|
ON user_level_progress(user_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_reward_ledger_user
|
||||||
|
ON reward_ledger(user_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS auth_accounts (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL UNIQUE,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
user_id TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
`
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { migrationId as id001, up as up001 } from './001-initial-schema'
|
||||||
|
|
||||||
|
export interface SqlMigration {
|
||||||
|
id: string
|
||||||
|
up: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ordered list — append new files and import them here. */
|
||||||
|
export const SQL_MIGRATIONS: SqlMigration[] = [
|
||||||
|
{ id: id001, up: up001 },
|
||||||
|
]
|
||||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user