freshyo/apps/backend/tests/seed-local.ts
2026-10-20 00:31:05 +05:30

135 lines
5.1 KiB
TypeScript

/**
* seed-local — idempotent local-D1 principals for the live API suite.
*
* Run from apps/backend (the wrangler dev server may stay running):
*
* bun run tests/seed-local.ts
*
* It creates/updates three fixed local-only principals and writes tests/.env:
*
* superadmin e2e_super (username/password)
* staff e2e_staff region 1, role 2 (name/password)
* user e2e.user@freshyo.test (identifier/password)
*
* It never deletes rows and never touches production. Re-running is safe.
*/
import bcrypt from 'bcryptjs'
import { execFileSync } from 'node:child_process'
import { existsSync, readdirSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
const PASSWORD = process.env.SEED_PASSWORD ?? 'FreshyoTest!2026'
const API_BASE_URL = process.env.API_BASE_URL ?? 'http://localhost:8787'
const STAFF_NAME = 'e2e_staff'
const SUPERADMIN_USERNAME = 'e2e_super'
const USER_EMAIL = 'e2e.user@freshyo.test'
const USER_MOBILE = '9000000001'
// Credentials-less account (users row, no user_creds): UAUTH-09 / UPASS-04.
const NOCREDS_EMAIL = 'e2e.nocreds@freshyo.test'
const NOCREDS_MOBILE = '9000000002'
const REGION_ID = 1
const ROLE_ID = 2 // "admin"
const d1Dir = resolve(process.cwd(), '.wrangler/state/v3/d1/miniflare-D1DatabaseObject')
if (!existsSync(d1Dir)) {
throw new Error(`[seed-local] D1 state not found at ${d1Dir}. Start "bun run dev" once first.`)
}
const dbFile = readdirSync(d1Dir).find((name) => name.endsWith('.sqlite') && !name.startsWith('metadata'))
if (!dbFile) throw new Error(`[seed-local] no D1 sqlite file in ${d1Dir}`)
const dbPath = resolve(d1Dir, dbFile)
const sql = (statement: string) => {
execFileSync('sqlite3', [dbPath, statement], { stdio: ['ignore', 'pipe', 'pipe'] })
}
const q = (value: string) => `'${value.replace(/'/g, "''")}'`
async function main() {
const hash = await bcrypt.hash(PASSWORD, 12)
sql(`
INSERT INTO superadmins (username, password_hash)
VALUES (${q(SUPERADMIN_USERNAME)}, ${q(hash)})
ON CONFLICT(username) DO UPDATE SET password_hash = excluded.password_hash;
UPDATE staff_users
SET password = ${q(hash)}, region_id = ${REGION_ID}, staff_role_id = ${ROLE_ID}
WHERE name = ${q(STAFF_NAME)};
INSERT INTO staff_users (name, password, staff_role_id, region_id)
SELECT ${q(STAFF_NAME)}, ${q(hash)}, ${ROLE_ID}, ${REGION_ID}
WHERE NOT EXISTS (SELECT 1 FROM staff_users WHERE name = ${q(STAFF_NAME)});
INSERT INTO users (name, email, mobile)
SELECT 'E2E User', ${q(USER_EMAIL)}, ${q(USER_MOBILE)}
WHERE NOT EXISTS (SELECT 1 FROM users WHERE email = ${q(USER_EMAIL)});
INSERT INTO user_creds (user_id, user_password)
SELECT id, ${q(hash)} FROM users WHERE email = ${q(USER_EMAIL)}
ON CONFLICT(user_id) DO UPDATE SET user_password = excluded.user_password;
-- Credentials-less account: a users row with NO user_creds row.
INSERT INTO users (name, email, mobile)
SELECT 'E2E No Creds', ${q(NOCREDS_EMAIL)}, ${q(NOCREDS_MOBILE)}
WHERE NOT EXISTS (SELECT 1 FROM users WHERE email = ${q(NOCREDS_EMAIL)});
DELETE FROM user_creds WHERE user_id = (SELECT id FROM users WHERE email = ${q(NOCREDS_EMAIL)});
`)
const env = `# Generated by tests/seed-local.ts — local-only credentials.
API_BASE_URL=${API_BASE_URL}
TEST_STAFF_NAME=${STAFF_NAME}
TEST_STAFF_PASSWORD=${PASSWORD}
TEST_USER_IDENTIFIER=${USER_EMAIL}
TEST_USER_PASSWORD=${PASSWORD}
# Credentials-less account for UAUTH-09 / UPASS-04.
TEST_NOCREDS_IDENTIFIER=${NOCREDS_EMAIL}
TEST_SUPERADMIN_USERNAME=${SUPERADMIN_USERNAME}
TEST_SUPERADMIN_PASSWORD=${PASSWORD}
# Region/bound used by most suites (seeded by migrations).
TEST_REGION_ID=${REGION_ID}
TEST_BOUND_ID=1
# Second region for isolation tests.
TEST_OTHER_REGION_ID=2
TEST_OTHER_BOUND_ID=3
# Cache polling (products/stores are eventual; slots/availability are synchronous).
CACHE_POLL_TIMEOUT_MS=180000
CACHE_POLL_INTERVAL_MS=3000
`
writeFileSync(resolve(__dirname, '.env'), env, { mode: 0o600 })
// Prove the principals resolve before the suite runs.
async function call(proc: string, input: unknown) {
const res = await fetch(`${API_BASE_URL}/api/trpc/${proc}?batch=1`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ 0: input }),
})
const body: any = await res.json()
const item = Array.isArray(body) ? body[0] : body
if (!res.ok || item?.error) {
throw new Error(`${proc}: ${res.status} ${JSON.stringify(item?.error?.json ?? item?.error ?? body)}`)
}
return item?.result?.data
}
await call('admin.staffUser.login', { name: STAFF_NAME, password: PASSWORD })
await call('user.auth.login', { identifier: USER_EMAIL, password: PASSWORD })
await call('superadmin.auth.login', { username: SUPERADMIN_USERNAME, password: PASSWORD })
console.log(`[seed-local] D1: ${dbPath}`)
console.log(`[seed-local] wrote ${resolve(__dirname, '.env')}`)
console.log('[seed-local] staff, user and superadmin logins verified')
}
main().catch((error) => {
console.error('[seed-local] failed:', error.message)
process.exit(1)
})