deckhearth/scripts/setup-neon-db.js

174 lines
5.6 KiB
JavaScript
Raw Normal View History

#!/usr/bin/env node
/**
* Neon Database Setup Script
*
* This script sets up the database tables in your Neon database.
* Make sure you have the POSTGRES_URL environment variable set.
*/
// Load environment variables from .env.local
import dotenv from 'dotenv';
dotenv.config({ path: '.env.local' });
import { neon } from '@neondatabase/serverless';
import bcrypt from 'bcryptjs';
async function setupNeonDatabase() {
feat(seed): require ADMIN_INITIAL_PASSWORD env var; strip admin123 from README Closes P0 #3 from .convoys/ship-readiness.md. scripts/setup-neon-db.js: - Read ADMIN_INITIAL_PASSWORD env var at the top of setupNeonDatabase() before any DB connection. Fail loudly (process.exit(1)) with an actionable message if unset or empty. - Replace bcrypt.hash('admin123', 12) with bcrypt.hash(adminPassword, 12). - Delete the two console.log lines that echoed admin user + password to stdout (R3 - stdout leak into CI logs). - Keep ON CONFLICT (email) DO NOTHING unchanged. Re-running setup-db on an env with the admin row already present is a no-op for the password (R4 - silent rotation prevention). Rotation of existing weak-hash admin rows is out of scope (Decision A - queued for the rotate-default-admin follow-up convoy). README.md: - Add ADMIN_INITIAL_PASSWORD to the install-step env-example block with a CI-secret note (and add KV_REST_API_URL/KV_REST_API_TOKEN for completeness; they're optional for local dev). - Replace the "Default Admin Account" section with "First-time admin setup", documenting the env var, openssl rand suggestion, and the operator rotation note for envs that predate this change. - Zero occurrences of 'admin123' remain in README.md (the operator rotation note refers to "the prior weak default" instead of naming the literal string, so grep verification A2 holds). Decisions A1 (going-forward only), B (operational change allowed), C1 (no vitest coverage - manual smoke in PR description) per .convoys/drop-public-setup.md section Decisions. Smoke output: see PR description. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 15:57:31 -04:00
const adminPassword = process.env.ADMIN_INITIAL_PASSWORD;
if (!adminPassword || !adminPassword.trim()) {
console.error(
'❌ ADMIN_INITIAL_PASSWORD environment variable is not set.\n' +
'\n' +
' Set it in .env.local for local dev, or as a CI secret if you run setup from CI.\n' +
' Generate a strong password with: openssl rand -base64 24\n' +
' See README.md → "First-time admin setup" for the full flow.\n'
);
process.exit(1);
}
const sql = neon(process.env.POSTGRES_URL);
try {
console.log('✅ Connecting to Neon database...');
// Create tables
await sql`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
role VARCHAR(50) DEFAULT 'user',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`;
console.log('✅ Created users table');
await sql`
CREATE TABLE IF NOT EXISTS cards (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
set_name VARCHAR(255),
set_code VARCHAR(50),
card_number VARCHAR(50),
rarity VARCHAR(50),
game VARCHAR(50) NOT NULL,
mana_cost VARCHAR(50),
cmc INTEGER,
card_type VARCHAR(255),
colors JSONB,
oracle_text TEXT,
power VARCHAR(10),
toughness VARCHAR(10),
image_url TEXT,
stock_image_url TEXT,
current_price DECIMAL(10,2),
market_price DECIMAL(10,2),
scryfall_id VARCHAR(255) UNIQUE,
verified BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`;
console.log('✅ Created cards table');
await sql`
CREATE TABLE IF NOT EXISTS user_cards (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
card_id INTEGER REFERENCES cards(id) ON DELETE CASCADE,
quantity INTEGER DEFAULT 1,
condition VARCHAR(50) DEFAULT 'NM',
is_foil BOOLEAN DEFAULT false,
notes TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, card_id, is_foil)
)
`;
console.log('✅ Created user_cards table');
await sql`
CREATE TABLE IF NOT EXISTS collections (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
description TEXT,
is_public BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`;
console.log('✅ Created collections table');
await sql`
CREATE TABLE IF NOT EXISTS collection_cards (
id SERIAL PRIMARY KEY,
collection_id INTEGER REFERENCES collections(id) ON DELETE CASCADE,
card_id INTEGER REFERENCES cards(id) ON DELETE CASCADE,
quantity INTEGER DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(collection_id, card_id)
)
`;
console.log('✅ Created collection_cards table');
await sql`
CREATE TABLE IF NOT EXISTS decks (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
description TEXT,
game VARCHAR(50),
is_public BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`;
console.log('✅ Created decks table');
await sql`
CREATE TABLE IF NOT EXISTS deck_cards (
id SERIAL PRIMARY KEY,
deck_id INTEGER REFERENCES decks(id) ON DELETE CASCADE,
card_id INTEGER REFERENCES cards(id) ON DELETE CASCADE,
quantity INTEGER DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(deck_id, card_id)
)
`;
console.log('✅ Created deck_cards table');
// Create admin user
feat(seed): require ADMIN_INITIAL_PASSWORD env var; strip admin123 from README Closes P0 #3 from .convoys/ship-readiness.md. scripts/setup-neon-db.js: - Read ADMIN_INITIAL_PASSWORD env var at the top of setupNeonDatabase() before any DB connection. Fail loudly (process.exit(1)) with an actionable message if unset or empty. - Replace bcrypt.hash('admin123', 12) with bcrypt.hash(adminPassword, 12). - Delete the two console.log lines that echoed admin user + password to stdout (R3 - stdout leak into CI logs). - Keep ON CONFLICT (email) DO NOTHING unchanged. Re-running setup-db on an env with the admin row already present is a no-op for the password (R4 - silent rotation prevention). Rotation of existing weak-hash admin rows is out of scope (Decision A - queued for the rotate-default-admin follow-up convoy). README.md: - Add ADMIN_INITIAL_PASSWORD to the install-step env-example block with a CI-secret note (and add KV_REST_API_URL/KV_REST_API_TOKEN for completeness; they're optional for local dev). - Replace the "Default Admin Account" section with "First-time admin setup", documenting the env var, openssl rand suggestion, and the operator rotation note for envs that predate this change. - Zero occurrences of 'admin123' remain in README.md (the operator rotation note refers to "the prior weak default" instead of naming the literal string, so grep verification A2 holds). Decisions A1 (going-forward only), B (operational change allowed), C1 (no vitest coverage - manual smoke in PR description) per .convoys/drop-public-setup.md section Decisions. Smoke output: see PR description. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 15:57:31 -04:00
const hashedPassword = await bcrypt.hash(adminPassword, 12);
await sql`
INSERT INTO users (email, password, role)
feat(brand): infrastructure + email migration for Deck Hearth (B2 of 2) Closes the pick-a-name convoy. Applies D1-D5 + Risk 4 PRESERVE per operator gate-1 ratification. Infrastructure renames: - lib/rate-limit.js: 5 Redis key prefixes tcgvault:* → deckhearth:* (D5). One-time per-15-min / per-1-hour counter reset accepted; no user impact because counter windows are short anyway. Existing rate-limit state in Upstash will accumulate at the new prefix on first request. - package.json: name field tcg-vault → deck-hearth (D2) - package-lock.json: regenerated for the name change; STOP-on-churn protocol confirmed only the two name lines changed (no dep churn) - All three test users (admin/alice/bob) renamed to @deckhearth.com (D4) - One-off migration script scripts/migrations/2026-05-24-rename-admin- email.js (NEW): ESM, idempotent, UNIQUE-collision-safe. Per the no-go-zones rule for new migrations. Operator MUST run post-deploy. - README.md + TESTING_GUIDE.md operator-caveat blockquotes flagged - pages/login.js demo-credential pre-fill updated PRESERVED per Risk 4: - test/lib/permission-middleware.test.js literal admin@tcgvault.com with 7-line architect-authored "why" comment block. This is the documented pre-fix-auth-bypass bug shape; the regression-lock literal stays as historical truth. Verification: - npm run lint: 128 problems (baseline preserved) - npm run test:run: 21/21 pass (preserved literal keeps green) - Grep across full repo: 0 hits for TCG Vault / tcgvault / tcg-vault except the explicit preserve in the test file + .convoys/ historical - lib/rate-limit.js: 5 deckhearth: prefixes, 0 tcgvault: prefixes - node --check on the new migration script: exit 0 - git diff package-lock.json: only the 2 "name": lines changed (no churn) Operator post-merge action: - Run `node scripts/migrations/2026-05-24-rename-admin-email.js` against the production Neon DB. Order matters: migration FIRST, then any subsequent `npm run setup-db` invocation. Migration script will refuse to run if collision detected (means setup-db already ran post-rename). Architect brief: .convoys/pick-a-name/brief-2-infrastructure-and-email-migration.md Architect commit: 50ce9ab Operator gate-1: D1-D5 + Risk 4 PRESERVE ratified. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 02:58:48 -04:00
VALUES (${'admin@deckhearth.com'}, ${hashedPassword}, ${'admin'})
ON CONFLICT (email) DO NOTHING
`;
console.log('✅ Created admin user');
console.log('🎉 Neon database setup completed successfully!');
console.log('');
console.log('📋 Database Details:');
console.log(' Database: Neon PostgreSQL');
feat(brand): infrastructure + email migration for Deck Hearth (B2 of 2) Closes the pick-a-name convoy. Applies D1-D5 + Risk 4 PRESERVE per operator gate-1 ratification. Infrastructure renames: - lib/rate-limit.js: 5 Redis key prefixes tcgvault:* → deckhearth:* (D5). One-time per-15-min / per-1-hour counter reset accepted; no user impact because counter windows are short anyway. Existing rate-limit state in Upstash will accumulate at the new prefix on first request. - package.json: name field tcg-vault → deck-hearth (D2) - package-lock.json: regenerated for the name change; STOP-on-churn protocol confirmed only the two name lines changed (no dep churn) - All three test users (admin/alice/bob) renamed to @deckhearth.com (D4) - One-off migration script scripts/migrations/2026-05-24-rename-admin- email.js (NEW): ESM, idempotent, UNIQUE-collision-safe. Per the no-go-zones rule for new migrations. Operator MUST run post-deploy. - README.md + TESTING_GUIDE.md operator-caveat blockquotes flagged - pages/login.js demo-credential pre-fill updated PRESERVED per Risk 4: - test/lib/permission-middleware.test.js literal admin@tcgvault.com with 7-line architect-authored "why" comment block. This is the documented pre-fix-auth-bypass bug shape; the regression-lock literal stays as historical truth. Verification: - npm run lint: 128 problems (baseline preserved) - npm run test:run: 21/21 pass (preserved literal keeps green) - Grep across full repo: 0 hits for TCG Vault / tcgvault / tcg-vault except the explicit preserve in the test file + .convoys/ historical - lib/rate-limit.js: 5 deckhearth: prefixes, 0 tcgvault: prefixes - node --check on the new migration script: exit 0 - git diff package-lock.json: only the 2 "name": lines changed (no churn) Operator post-merge action: - Run `node scripts/migrations/2026-05-24-rename-admin-email.js` against the production Neon DB. Order matters: migration FIRST, then any subsequent `npm run setup-db` invocation. Migration script will refuse to run if collision detected (means setup-db already ran post-rename). Architect brief: .convoys/pick-a-name/brief-2-infrastructure-and-email-migration.md Architect commit: 50ce9ab Operator gate-1: D1-D5 + Risk 4 PRESERVE ratified. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 02:58:48 -04:00
console.log(' Admin user ready (email: admin@deckhearth.com)');
console.log('');
console.log('🔧 Next Steps:');
console.log(' 1. Test the API endpoints');
console.log(' 2. Start building the frontend');
} catch (error) {
console.error('❌ Database setup failed:', error.message);
console.log('');
console.log('🔧 Troubleshooting:');
console.log(' 1. Make sure POSTGRES_URL is set in .env.local');
console.log(' 2. Check your Neon database connection');
console.log(' 3. Ensure the database URL is correct');
process.exit(1);
}
}
setupNeonDatabase();