package eu.friedcutlet.yokan.services.logging import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.catchingNonCancellation private const val CrashReportPath = "crash/latest.txt" private const val MaxCrashReportBytes = 32 * 1024 object CrashReportStore { fun record(files: LocalFileService, throwable: Throwable) { val report = redact(throwable.stackTraceToString()).encodeToByteArray() files.writeBytes(CrashReportPath(files), report.copyOf(report.size.coerceAtMost(MaxCrashReportBytes))) } fun read(files: LocalFileService): String? = catchingNonCancellation { files.readBytes(CrashReportPath(files)).decodeToString() .takeIf { it.isNotBlank() } }.getOrNull() fun delete(files: LocalFileService) { catchingNonCancellation { files.deleteRecursively(CrashReportPath(files)) } } internal fun redact(value: String): String = value .replace(Regex("(?im)(authorization\\s*[:=]\\s*(?:bearer\\s+)?)[^\\s]+"), "$1[REDACTED]") .replace(Regex("(?i)(password|token|access_token|refresh_token)(\\s*[:=]\\s*)[^\\s,;]+"), "$1$2[REDACTED]") .replace(Regex("(?i)([?&](?:token|password|access_token|refresh_token)=)[^&\\s]+"), "$1[REDACTED]") private fun CrashReportPath(files: LocalFileService): String = "${files.cacheRoot.trimEnd('/', 92.toChar())}/$CrashReportPath" }