- V11 client_logs table with per-user storage and retention/pruning - POST/GET/DELETE /logs with batch validation, rate limit and admin access - redact bearer tokens, Authorization headers and query/JSON secrets twice - add X-Request-Id to responses and include it in the server log pattern - report client error entries immediately in the server log - scripts/logs.sh for source-side retrieval and clearing - chart knobs CLIENT_LOG_RETENTION_DAYS and CLIENT_LOG_MAX_ROWS_PER_USER
165 lines
5.7 KiB
Kotlin
165 lines
5.7 KiB
Kotlin
package win.taptap.musicmanager.api
|
|
|
|
import io.ktor.http.HttpStatusCode
|
|
import io.ktor.server.response.respond
|
|
import io.ktor.server.routing.Route
|
|
import io.ktor.server.routing.delete
|
|
import io.ktor.server.routing.get
|
|
import io.ktor.server.routing.post
|
|
import io.ktor.server.routing.route
|
|
import java.security.MessageDigest
|
|
import win.taptap.musicmanager.config.UsersConfig
|
|
import win.taptap.musicmanager.db.ApiTokenRepository
|
|
import win.taptap.musicmanager.discovery.DiscoveryService
|
|
import win.taptap.musicmanager.discovery.MusicCatalogs
|
|
import win.taptap.musicmanager.discovery.TopUpService
|
|
import win.taptap.musicmanager.media.MediaGcService
|
|
import win.taptap.musicmanager.media.MediaStore
|
|
import win.taptap.musicmanager.radio.RadioService
|
|
import win.taptap.musicmanager.scanner.CoverArtService
|
|
import win.taptap.musicmanager.scanner.ScanStatus
|
|
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
|
|
|
/**
|
|
* Routing for the native API.
|
|
*
|
|
* Every handler resolves the bearer token explicitly. Media URLs may also carry
|
|
* `?token=` because HTML audio and `<img>` tags cannot set headers.
|
|
*/
|
|
fun Route.apiRoutes(
|
|
users: UsersConfig,
|
|
coverArtService: CoverArtService,
|
|
transcoder: FfmpegTranscoder,
|
|
radioService: RadioService,
|
|
discoveryService: DiscoveryService,
|
|
topUpService: TopUpService,
|
|
catalogs: MusicCatalogs,
|
|
mediaStore: MediaStore,
|
|
gc: MediaGcService,
|
|
defaultSource: String,
|
|
deezerQuality: Int,
|
|
loudnessEnabled: Boolean,
|
|
loudnessTargetLufs: Double,
|
|
clientLogRetentionDays: Int,
|
|
startScan: () -> Boolean,
|
|
scanStatus: () -> ScanStatus,
|
|
) {
|
|
route("/api/v1") {
|
|
post("/auth/login") {
|
|
val request = call.receiveJson<LoginRequest>()
|
|
val user = users.byName(request.username.trim())
|
|
?: throw ApiException(
|
|
HttpStatusCode.Unauthorized,
|
|
"invalid_credentials",
|
|
"Wrong username or password",
|
|
)
|
|
if (!constantTimeEquals(request.password, user.password)) {
|
|
throw ApiException(
|
|
HttpStatusCode.Unauthorized,
|
|
"invalid_credentials",
|
|
"Wrong username or password",
|
|
)
|
|
}
|
|
|
|
val issued = ApiTokenRepository.create(
|
|
userName = user.name,
|
|
deviceName = request.deviceName.ifBlank { "Unknown device" },
|
|
platform = request.platform.ifBlank { "unknown" },
|
|
)
|
|
call.respond(
|
|
HttpStatusCode.OK,
|
|
LoginResponse(
|
|
token = issued.raw,
|
|
expiresAt = issued.record.expiresAt,
|
|
user = user.toDto(),
|
|
),
|
|
)
|
|
}
|
|
|
|
get("/me") {
|
|
val user = call.requireApiUser(users)
|
|
call.respond(user.toDto())
|
|
}
|
|
|
|
/** Source and audio settings the client cannot infer from a song. */
|
|
get("/info") {
|
|
call.requireApiUser(users)
|
|
call.respond(
|
|
ServerInfoDto(
|
|
defaultSource = defaultSource,
|
|
deezerQuality = deezerQuality,
|
|
loudnessEnabled = loudnessEnabled,
|
|
loudnessTargetLufs = loudnessTargetLufs,
|
|
clientLogRetentionDays = clientLogRetentionDays,
|
|
),
|
|
)
|
|
}
|
|
|
|
post("/auth/logout") {
|
|
call.requireApiUser(users)
|
|
ApiTokenRepository.revokeRaw(call.bearerToken().orEmpty())
|
|
call.respond(HttpStatusCode.NoContent)
|
|
}
|
|
|
|
get("/auth/devices") {
|
|
val user = call.requireApiUser(users)
|
|
val current = call.apiToken()
|
|
val devices = ApiTokenRepository.list(user.name).map { record ->
|
|
DeviceDto(
|
|
id = record.id,
|
|
deviceName = record.deviceName,
|
|
platform = record.platform,
|
|
createdAt = record.createdAt,
|
|
lastUsedAt = record.lastUsedAt,
|
|
expiresAt = record.expiresAt,
|
|
current = record.id == current?.id,
|
|
)
|
|
}
|
|
call.respond(devices)
|
|
}
|
|
|
|
delete("/auth/devices/{id}") {
|
|
val user = call.requireApiUser(users)
|
|
val id = call.parameters["id"] ?: badRequest("Device id is required")
|
|
if (!ApiTokenRepository.revoke(id, user.name)) notFound("Device")
|
|
call.respond(HttpStatusCode.NoContent)
|
|
}
|
|
|
|
get("/scan") {
|
|
call.requireApiUser(users)
|
|
val status = scanStatus()
|
|
call.respond(ScanStatusDto(status.scanning, status.count, status.error))
|
|
}
|
|
|
|
post("/scan") {
|
|
val user = call.requireApiUser(users)
|
|
if (!user.admin) forbidden("Only admins can start a scan")
|
|
val started = startScan()
|
|
call.respond(
|
|
HttpStatusCode.Accepted,
|
|
ScanStatusDto(scanning = started, count = scanStatus().count),
|
|
)
|
|
}
|
|
|
|
songRoutes(users, catalogs, mediaStore, coverArtService, transcoder, defaultSource)
|
|
moodRoutes(
|
|
users = users,
|
|
radioService = radioService,
|
|
discoveryService = discoveryService,
|
|
topUpService = topUpService,
|
|
catalogs = catalogs,
|
|
mediaStore = mediaStore,
|
|
gc = gc,
|
|
defaultSource = defaultSource,
|
|
)
|
|
sessionRoutes(users, radioService, gc)
|
|
logRoutes(users)
|
|
}
|
|
}
|
|
|
|
private fun constantTimeEquals(candidate: String, expected: String): Boolean =
|
|
MessageDigest.isEqual(
|
|
candidate.toByteArray(Charsets.UTF_8),
|
|
expected.toByteArray(Charsets.UTF_8),
|
|
)
|