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
185 lines (163 loc) · 5.32 KB
/
Copy pathroute.ts
File metadata and controls
185 lines (163 loc) · 5.32 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// src/app/api/clients/route.ts
//
// Functions: GET, POST
import { NextResponse } from "next/server"
import {
authenticate,
decodeKey,
parseJsonBody,
validateIntRange,
validateMaxLength,
validatePort,
} from "@/lib/api-helpers"
import { encrypt } from "@/lib/crypto"
import { sanitizeHost } from "@/lib/data-transforms"
import { db } from "@/lib/db"
import { downloadClients } from "@/lib/db/schema"
import { VALID_CLIENT_TYPES } from "@/lib/download-clients"
import { errMsg } from "@/lib/error-utils"
import {
CLIENT_POLL_INTERVAL_DEFAULT,
CLIENT_POLL_INTERVAL_MAX,
CLIENT_POLL_INTERVAL_MIN,
CREDENTIAL_MAX,
CROSS_SEED_TAG_MAX,
CROSS_SEED_TAGS_MAX,
HOST_MAX,
} from "@/lib/limits"
import { log } from "@/lib/logger"
import { fetchDownloadClients, serializeDownloadClientResponse } from "@/lib/server-data"
import { PROXY_HOST_PATTERN } from "@/lib/tunnel"
export async function GET() {
const auth = await authenticate()
if (auth instanceof NextResponse) return auth
const clients = await fetchDownloadClients()
return NextResponse.json(clients.map(serializeDownloadClientResponse))
}
export async function POST(request: Request) {
const auth = await authenticate()
if (auth instanceof NextResponse) return auth
const body = await parseJsonBody(request)
if (body instanceof NextResponse) return body
const {
name,
host,
username,
password,
type,
port,
useSsl,
pollIntervalSeconds,
isDefault,
crossSeedTags,
} = body as {
name?: string
host?: string
username?: string
password?: string
type?: string
port?: number
useSsl?: boolean
pollIntervalSeconds?: number
isDefault?: boolean
crossSeedTags?: string[]
}
if (!name || !host || !username || !password) {
return NextResponse.json(
{ error: "name, host, username, and password are required" },
{ status: 400 }
)
}
if (
typeof name !== "string" ||
typeof host !== "string" ||
typeof username !== "string" ||
typeof password !== "string"
) {
return NextResponse.json({ error: "Invalid field types" }, { status: 400 })
}
const nameErr = validateMaxLength(name, CREDENTIAL_MAX, "Name")
if (nameErr) return nameErr
const hostErr = validateMaxLength(host, HOST_MAX, "Host")
if (hostErr) return hostErr
const usernameErr = validateMaxLength(username, CREDENTIAL_MAX, "Username")
if (usernameErr) return usernameErr
const passwordErr = validateMaxLength(password, CREDENTIAL_MAX, "Password")
if (passwordErr) return passwordErr
const sanitizedHost = sanitizeHost(host)
if (!PROXY_HOST_PATTERN.test(sanitizedHost)) {
return NextResponse.json({ error: "Invalid host format" }, { status: 400 })
}
const resolvedType = typeof type === "string" ? type : "qbittorrent"
if (!(VALID_CLIENT_TYPES as readonly string[]).includes(resolvedType)) {
return NextResponse.json({ error: "Invalid client type" }, { status: 400 })
}
const resolvedPort = typeof port === "number" ? port : 8080
const portErr = validatePort(resolvedPort)
if (portErr) return portErr
if (typeof pollIntervalSeconds === "number") {
const pollErr = validateIntRange(
pollIntervalSeconds,
CLIENT_POLL_INTERVAL_MIN,
CLIENT_POLL_INTERVAL_MAX,
"pollIntervalSeconds",
`Poll interval must be between ${CLIENT_POLL_INTERVAL_MIN} and ${CLIENT_POLL_INTERVAL_MAX} seconds`
)
if (pollErr) return pollErr
}
const key = decodeKey(auth)
const encryptedUsername = encrypt(username, key)
const encryptedPassword = encrypt(password, key)
const resolvedIsDefault = typeof isDefault === "boolean" ? isDefault : false
const resolvedTags = Array.isArray(crossSeedTags) ? crossSeedTags : []
if (resolvedTags.length > CROSS_SEED_TAGS_MAX) {
return NextResponse.json(
{ error: "Cannot specify more than 50 cross-seed tags" },
{ status: 400 }
)
}
if (
resolvedTags.length > 0 &&
!resolvedTags.every(
(t: unknown) => typeof t === "string" && t.length > 0 && t.length <= CROSS_SEED_TAG_MAX
)
) {
return NextResponse.json(
{ error: "Each cross-seed tag must be a non-empty string of 100 characters or fewer" },
{ status: 400 }
)
}
try {
const [client] = await db.transaction(async (tx) => {
if (resolvedIsDefault) {
await tx.update(downloadClients).set({ isDefault: false })
}
return tx
.insert(downloadClients)
.values({
name: name.trim(),
host: sanitizedHost,
type: resolvedType,
port: resolvedPort,
useSsl: typeof useSsl === "boolean" ? useSsl : false,
encryptedUsername,
encryptedPassword,
pollIntervalSeconds:
typeof pollIntervalSeconds === "number"
? pollIntervalSeconds
: CLIENT_POLL_INTERVAL_DEFAULT,
isDefault: resolvedIsDefault,
crossSeedTags: resolvedTags,
})
.returning()
})
log.info({ route: "POST /api/clients", clientId: client.id }, "download client created")
return NextResponse.json({ id: client.id, name: client.name }, { status: 201 })
} catch (err) {
log.error(
{ route: "POST /api/clients", error: errMsg(err) },
"Failed to create download client"
)
return NextResponse.json({ error: "Failed to create download client" }, { status: 500 })
}
}