forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
123 lines (114 loc) · 4.09 KB
/
Copy pathroute.ts
File metadata and controls
123 lines (114 loc) · 4.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// src/app/api/auth/setup/route.ts
import { NextResponse } from "next/server"
import { parseJsonBody, validateIntRange } from "@/lib/api-helpers"
import { hashPassword } from "@/lib/auth"
import { generateSalt } from "@/lib/crypto"
import { db } from "@/lib/db"
import { appSettings } from "@/lib/db/schema"
import { errMsg } from "@/lib/error-utils"
import {
PASSWORD_MAX,
PASSWORD_MIN,
SNAPSHOT_RETENTION_MAX,
SNAPSHOT_RETENTION_MIN,
USERNAME_MAX,
USERNAME_MIN,
} from "@/lib/limits"
import { log } from "@/lib/logger"
export async function POST(request: Request) {
const body = await parseJsonBody(request)
if (body instanceof NextResponse) return body
const { password, username, snapshotRetentionDays } = body as {
password?: string
username?: string
snapshotRetentionDays?: number
}
if (
!password ||
typeof password !== "string" ||
password.length < PASSWORD_MIN ||
password.length > PASSWORD_MAX
) {
return NextResponse.json(
{ error: `Password must be between ${PASSWORD_MIN} and ${PASSWORD_MAX} characters` },
{ status: 400 }
)
}
if (typeof username !== "string" || !username.trim()) {
return NextResponse.json({ error: "Username is required" }, { status: 400 })
}
const validatedUsername = username.trim()
if (validatedUsername.length < USERNAME_MIN || validatedUsername.length > USERNAME_MAX) {
return NextResponse.json(
{ error: `Username must be between ${USERNAME_MIN} and ${USERNAME_MAX} characters` },
{ status: 400 }
)
}
if (!/^[\w\-. ]+$/.test(validatedUsername)) {
return NextResponse.json(
{
error: "Username may only contain letters, numbers, underscores, hyphens, dots, and spaces",
},
{ status: 400 }
)
}
// Validate optional retention setting
let validatedRetention: number | undefined
if (snapshotRetentionDays !== undefined) {
if (typeof snapshotRetentionDays !== "number") {
return NextResponse.json(
{
error: `snapshotRetentionDays must be an integer between ${SNAPSHOT_RETENTION_MIN} and ${SNAPSHOT_RETENTION_MAX}`,
},
{ status: 400 }
)
}
const retentionErr = validateIntRange(
snapshotRetentionDays,
SNAPSHOT_RETENTION_MIN,
SNAPSHOT_RETENTION_MAX,
"snapshotRetentionDays",
`snapshotRetentionDays must be an integer between ${SNAPSHOT_RETENTION_MIN} and ${SNAPSHOT_RETENTION_MAX}`
)
if (retentionErr) return retentionErr
validatedRetention = snapshotRetentionDays
}
// Fast pre-flight: skip expensive hashing if already configured
const preCheck = await db.select({ id: appSettings.id }).from(appSettings).limit(1)
if (preCheck.length > 0) {
log.warn({ route: "POST /api/auth/setup" }, "setup rejected — already configured")
return NextResponse.json({ error: "Already configured" }, { status: 400 })
}
const passwordHash = await hashPassword(password)
const encryptionSalt = generateSalt()
// Atomic check-and-insert with serializable isolation: prevents TOCTOU race
let inserted: boolean
try {
inserted = await db.transaction(
async (tx) => {
const existing = await tx.select({ id: appSettings.id }).from(appSettings).limit(1)
if (existing.length > 0) return false
await tx.insert(appSettings).values({
passwordHash,
encryptionSalt,
username: validatedUsername,
...(validatedRetention !== undefined && { snapshotRetentionDays: validatedRetention }),
})
return true
},
{ isolationLevel: "serializable" }
)
} catch (err) {
log.error({ route: "POST /api/auth/setup", error: errMsg(err) }, "Setup transaction failed")
return NextResponse.json(
{ error: "Setup failed due to a database error. Please try again." },
{ status: 500 }
)
}
if (!inserted) {
log.warn({ route: "POST /api/auth/setup" }, "setup rejected: race condition")
return NextResponse.json({ error: "Already configured" }, { status: 400 })
}
log.info({ route: "POST /api/auth/setup" }, "initial setup completed")
return NextResponse.json({ success: true })
}