## 那道「单向门」其实一直开着
`PASSWORD_HASH_UPGRADE` 是并行试跑第一天撞出来的补丁:新后端把 Django 的
pbkdf2 升级成 argon2 之后,旧后端验不了,登录过新站的学生回滚就登不上
(phase5 切换手册里记着这件事)。当时的修法是给**登录时的自动升级**加个开关,
默认关闭。
但写密码的地方有五个,开关只管住了一个:
POST /users 注册
PUT /admin/users/:id 管理员改密码
POST /admin/users 批量导入用户
POST /admin/users/:id/reset-password 重置密码 ← 老师天天在用
登录成功后的自动升级 ← 只有这一处受开关管
后面四处无条件 `Bun.password.hash(argon2id)`。也就是说开关关得好好的,
**老师给学生点一次「重置密码」,那个账号就回不去旧站了** —— 而「老师帮学生
查/改密码」正是这套系统的日常功能,`raw_password` 那一列存在的理由就是它。
所以那半年里「默认关闭 = 回滚安全」是个假象。
## 改法
五处统一走 `auth/password.ts` 的 `hashPassword()`,开关两个方向都变成真的:
- `true`:五处全写 argon2id,登录时把存量 pbkdf2 顺手升级掉。
- `false`:五处全写 Django 格式的 `pbkdf2_sha256$1200000$<22位salt>$<base64>`,
登录时也不动存量哈希 —— 两边都验得了。
新加的 `hashDjangoPbkdf2` 逐项对齐 Django 6 的 `PBKDF2PasswordHasher`:
1200000 迭代、22 位 salt、`RANDOM_STRING_CHARS` 字符集、sha256/32 字节。
**默认值定成 `true`** —— 旧站今天下线了,没有回滚路径要照顾。要把旧站拉回来
就先设 `PASSWORD_HASH_UPGRADE=false`,切换手册三处说明都改了。
⚠️ `verifyPassword` 的 pbkdf2 分支**永远不能删**,代码和注释里都写了:生产库
1710 个账号全是 Django 写的 pbkdf2(迭代次数 120000~1200000,跨了好几个
Django 版本),它们只会在各自下次登录时才升级成 argon2。
## 顺带:dev seed 只有学生号
`seed:dev` 只建 `student`(普通用户),本机想测后台得手工往库里塞 email 和
user_profile —— 而缺 user_profile 的表现极其隐蔽:`/api/me` 返回
profile-not-found → 前端 getMyProfile 抛异常 → localStorage 的 authed 存不进去
→ **所有 /admin 路由被守卫静默弹回首页**,不报错。我在这上面卡了很久。
现在 seed 同时建学生和超管(`devadmin` / `devadmin123`),profile 和 email 一起
建好,并且写密码也走 hashPassword。另外加了一道防呆:DATABASE_URL 不是本机时
直接拒绝执行 —— 这个脚本会重置密码并把明文写进 raw_password,其中一个还是超管,
对着生产库跑一次就是把超管密码改掉。要绕过设 `OJ2_SEED_FORCE=true`。
## 验证
全程拿**旧后端那个真的 Django venv** 对打,不是照着文档推:
- 事实核对:Bun 写的 `$argon2id$…` 在 Django 里 `identify_hasher` 抛
`Unknown password hashing algorithm ''`;换成 Django 格式 `argon2$argon2id$…`
能识别,但 `verify()` 抛 `Couldn't load 'Argon2PasswordHasher' algorithm
library: No module named 'argon2'`(旧后端确实没装 argon2-cffi)。
原注释说的「格式对了也验不了」结论对,机制略有出入。
- 双向互验:OJ2 写的哈希 Django `check_password` 通过、错密码不通过;
Django `make_password` 写的哈希 OJ2 `verifyPassword` 也认。
- 默认(argon2):拿 Django 现造一个 120000 迭代的老哈希塞进库,登录 200 →
哈希变成 argon2 → 再登一次仍 200。
- 退路(`=false`):同一个老哈希登录 200 且**哈希不变**;走后台「重置密码」
之后落库是 `pbkdf2_sha256$1200000$…`,**旧站的 Django 验这个新密码通过**。
- 一次 1200000 迭代约 107ms(写密码时的开销;验旧哈希的开销本来就在)。
- tsc(apps/api) 0 error、check:routes 168 条无遮蔽、vue-tsc 0 error、build 通过。
测试用户(pwtest1 / legacyuser)已删干净,本机库用新 seed 复位。
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
118 lines
3.9 KiB
TypeScript
118 lines
3.9 KiB
TypeScript
import { eq, sql } from "drizzle-orm"
|
||
|
||
import { hashPassword } from "../auth/password"
|
||
import { db, schema } from "../db"
|
||
|
||
/**
|
||
* 本机开发用的账号。**只能对本地库跑** —— 它会重置账号密码并把明文写进
|
||
* raw_password,其中一个还是超管。对着生产库跑一次就是把超管密码改掉,
|
||
* 所以这里按 DATABASE_URL 的主机名拦一道,需要绕过时显式设 OJ2_SEED_FORCE=true。
|
||
*/
|
||
const url = process.env.DATABASE_URL ?? "postgres://onlinejudge:onlinejudge@localhost:5433/onlinejudge"
|
||
const host = (() => {
|
||
try {
|
||
return new URL(url).hostname
|
||
} catch {
|
||
return ""
|
||
}
|
||
})()
|
||
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", ""])
|
||
if (!LOCAL_HOSTS.has(host) && process.env.OJ2_SEED_FORCE !== "true") {
|
||
console.error(
|
||
`[seed:dev] DATABASE_URL 指向 ${host},不是本机。这个脚本会重置账号密码` +
|
||
`(含一个超管)并写明文 raw_password,拒绝执行。\n` +
|
||
` 确实要对这个库跑,设 OJ2_SEED_FORCE=true。`,
|
||
)
|
||
process.exit(1)
|
||
}
|
||
|
||
const now = new Date().toISOString()
|
||
|
||
// 阶段 1 是带着显式 id 导入的,PostgreSQL 的序列没跟着走,先对齐
|
||
await db.execute(
|
||
sql`select setval(pg_get_serial_sequence('"user"', 'id'), coalesce(max(${schema.user.id}), 1), true) from ${schema.user}`,
|
||
)
|
||
|
||
interface SeedAccount {
|
||
username: string
|
||
password: string
|
||
adminType: "Regular User" | "Super Admin"
|
||
problemPermission: "None" | "All"
|
||
realName: string
|
||
}
|
||
|
||
/**
|
||
* 建号或就地更新。**user_profile 那一行不能省** —— 缺了它 `/api/me` 返回
|
||
* profile-not-found,前端的 getMyProfile 抛异常、localStorage 的 authed 存不
|
||
* 进去,于是所有 /admin 路由被守卫弹回首页,而且不报错。本机的 devadmin 原来
|
||
* 就缺 profile 和 email,后台页面一律进不去,排查了很久才找到这里。
|
||
*/
|
||
async function seed(account: SeedAccount) {
|
||
// 走 hashPassword 而不是直接 argon2:本机也跟着 PASSWORD_HASH_UPGRADE 走,
|
||
// 默认写 Django 格式的 pbkdf2,和线上一个行为
|
||
const passwordHash = await hashPassword(account.password)
|
||
const email = `${account.username}@example.test`
|
||
const [user] = await db
|
||
.insert(schema.user)
|
||
.values({
|
||
username: account.username,
|
||
password: passwordHash,
|
||
rawPassword: account.password,
|
||
email,
|
||
createTime: now,
|
||
adminType: account.adminType,
|
||
problemPermission: account.problemPermission,
|
||
openApi: false,
|
||
isDisabled: false,
|
||
sessionKeys: [],
|
||
})
|
||
.onConflictDoUpdate({
|
||
target: schema.user.username,
|
||
set: {
|
||
password: passwordHash,
|
||
rawPassword: account.password,
|
||
email,
|
||
adminType: account.adminType,
|
||
problemPermission: account.problemPermission,
|
||
isDisabled: false,
|
||
},
|
||
})
|
||
.returning({ id: schema.user.id, username: schema.user.username })
|
||
|
||
if (!user) throw new Error(`Failed to seed ${account.username}`)
|
||
|
||
const [profile] = await db
|
||
.select({ id: schema.userProfile.id })
|
||
.from(schema.userProfile)
|
||
.where(eq(schema.userProfile.userId, user.id))
|
||
.limit(1)
|
||
|
||
if (!profile) {
|
||
await db.insert(schema.userProfile).values({
|
||
userId: user.id,
|
||
acmProblemsStatus: { problems: {}, contest_problems: {} },
|
||
avatar: "/public/avatar/default.png",
|
||
realName: account.realName,
|
||
})
|
||
}
|
||
|
||
console.log(` ${account.adminType.padEnd(13)} ${user.username} / ${account.password}`)
|
||
}
|
||
|
||
console.log("Seeded development logins:")
|
||
await seed({
|
||
username: process.env.OJ2_DEV_USERNAME ?? "student",
|
||
password: process.env.OJ2_DEV_PASSWORD ?? "student123",
|
||
adminType: "Regular User",
|
||
problemPermission: "None",
|
||
realName: "开发用学生",
|
||
})
|
||
await seed({
|
||
username: process.env.OJ2_DEV_ADMIN_USERNAME ?? "devadmin",
|
||
password: process.env.OJ2_DEV_ADMIN_PASSWORD ?? "devadmin123",
|
||
adminType: "Super Admin",
|
||
problemPermission: "All",
|
||
realName: "开发用超管",
|
||
})
|
||
process.exit(0)
|