freshyo/apps/backend/scripts/remove-notif-creds.ts
2026-10-20 00:31:05 +05:30

170 lines
5.9 KiB
TypeScript

#!/usr/bin/env bun
/**
* remove-notif-creds — delete every `notif_creds` row except one user's.
*
* After `pull_db` imports the production dump into local D1, every user's push
* credentials come along. This keeps only the account you actually test with.
*
* Run from apps/backend:
*
* bun run remove-notif-creds
* bun run remove-notif-creds -- --keep-mobile 9676651496 --dry-run
*
* This script is LOCAL-ONLY by design: it must never delete credentials from the
* remote/production D1. The goal is to stop the local dev backend from pushing
* test notifications to real users' devices.
*
* Flags:
* --keep-mobile <n> mobile whose notif_creds are kept (default 9676651496)
* --dry-run report what would be deleted, change nothing
* --show-sql print the SQL and exit
* --allow-missing-keep if the keep-user does not exist, delete ALL rows
* --help show this help
*
* Env overrides:
* D1_CONFIG wrangler config file (default: wrangler.dev.toml — local state)
* D1_DB_NAME D1 database name (default: freshyo-dev)
*/
import { existsSync } from 'node:fs'
import { resolve } from 'node:path'
const DEFAULT_KEEP_MOBILE = '9676651496'
const USAGE = `remove-notif-creds — keep one user's notif_creds, delete the rest (LOCAL D1 ONLY)
Usage:
bun run remove-notif-creds [--keep-mobile <mobile>] [--dry-run] [--show-sql] [--allow-missing-keep]
Options:
--keep-mobile <n> mobile whose notif_creds are kept (default ${DEFAULT_KEEP_MOBILE})
--dry-run report what would be deleted, change nothing
--show-sql print the SQL instead of running it
--allow-missing-keep delete ALL notif_creds when the keep-user is missing
--help show this help
This script never targets the remote database. It only edits the local D1 state
so the local backend stops pushing test notifications to real devices.
`
const argv = process.argv.slice(2)
const flag = (n: string) => argv.includes(`--${n}`)
const opt = (n: string): string | undefined => {
const eq = argv.find((a) => a.startsWith(`--${n}=`))
if (eq) return eq.slice(n.length + 3)
const i = argv.indexOf(`--${n}`)
if (i !== -1 && argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) return argv[i + 1]
return undefined
}
function die(msg: string): never {
console.error(`\n error: ${msg}\n`)
console.error(USAGE)
process.exit(1)
}
if (flag('help') || flag('h')) {
console.log(USAGE)
process.exit(0)
}
const keepMobile = (opt('keep-mobile') ?? DEFAULT_KEEP_MOBILE).trim()
const dryRun = flag('dry-run')
const showSql = flag('show-sql')
const allowMissingKeep = flag('allow-missing-keep')
if (flag('remote')) {
die('this script is local-only: it refuses to modify the remote/production D1')
}
if (!keepMobile) die('--keep-mobile must not be empty')
const BACKEND_DIR = resolve(import.meta.dir, '..')
const config = process.env.D1_CONFIG ?? 'wrangler.dev.toml'
const dbName = process.env.D1_DB_NAME ?? 'freshyo-dev'
const WRANGLER = resolve(BACKEND_DIR, 'node_modules/.bin/wrangler')
function run(args: string[]): { out: string; err: string; code: number } {
const p = Bun.spawnSync([existsSync(WRANGLER) ? WRANGLER : 'wrangler', ...args], {
cwd: BACKEND_DIR,
stdout: 'pipe',
stderr: 'pipe',
})
return { out: p.stdout.toString(), err: p.stderr.toString(), code: p.exitCode }
}
function parseJson(out: string): any[] | null {
const s = out.indexOf('[')
const e = out.lastIndexOf(']')
if (s === -1 || e === -1) return null
try {
return JSON.parse(out.slice(s, e + 1))
} catch {
return null
}
}
const q = (s: string) => `'${s.replace(/'/g, "''")}'`
const targetArgs = ['d1', 'execute', dbName, '--config', resolve(BACKEND_DIR, config), '--local']
const query = (sql: string) => {
const res = run([...targetArgs, '--json', '--command', sql])
if (res.code !== 0) die(`query failed:\n${res.err || res.out}`)
return parseJson(res.out)?.[0]?.results ?? []
}
const main = async () => {
// 1) Resolve the account to keep. Refusing to proceed without it avoids a
// typo silently wiping every credential.
const keepRows = query(
`SELECT id, name, mobile FROM users WHERE mobile = ${q(keepMobile)} ORDER BY id LIMIT 1;`
)
const keep = keepRows[0] as { id: number; name: string | null; mobile: string | null } | undefined
if (!keep && !allowMissingKeep) {
die(
`no user found with mobile ${keepMobile}. Refusing to delete every notif_creds row. ` +
`Pass --allow-missing-keep to delete all, or --keep-mobile <mobile> to pick another account.`
)
}
const before = Number(query('SELECT COUNT(*) AS n FROM notif_creds;')[0]?.n ?? 0)
const keepCount = keep
? Number(query(`SELECT COUNT(*) AS n FROM notif_creds WHERE user_id = ${keep.id};`)[0]?.n ?? 0)
: 0
const sql = keep
? `DELETE FROM notif_creds WHERE user_id <> ${keep.id};`
: 'DELETE FROM notif_creds;'
if (showSql) {
console.log(`-- target: ${dbName} (local) via ${config}`)
if (keep) console.log(`-- keep: #${keep.id} ${keep.name ?? ''} (${keep.mobile ?? keepMobile})`)
console.log(sql)
return
}
if (dryRun) {
console.log(
`\n dry-run: would delete ${before - keepCount} of ${before} notif_creds row(s)` +
(keep
? `, keeping ${keepCount} for #${keep.id} ${keep.name ?? ''} (${keep.mobile ?? keepMobile})`
: ', keeping none') +
`\n target: ${dbName} (local)\n`
)
return
}
// 2) Delete.
const write = run([...targetArgs, '--command', sql])
if (write.code !== 0) die(`delete failed:\n${write.err || write.out}`)
// 3) Report.
const after = Number(query('SELECT COUNT(*) AS n FROM notif_creds;')[0]?.n ?? 0)
console.log(
`\n Removed ${before - after} notif_creds row(s)` +
(keep ? `; kept ${after} for #${keep.id} ${keep.name ?? ''} (${keep.mobile ?? keepMobile})` : '') +
`\n target: ${dbName} (local)\n`
)
}
await main()