merge: remove the bug-report integration for v1.23

# Conflicts:
#	messages/de.json
#	messages/en.json
#	messages/es.json
#	messages/fr.json
#	messages/it.json
#	messages/pl.json
#	src/app/admin/[section]/renderer.tsx
This commit is contained in:
Marc-André Bombeck committed 2026-06-27 20:47:24 +02:00
commit b271a39fe4
68 files changed
+115 -3344

No files matched your search

-13
View File
@@ -8,7 +8,6 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { __resetAllCachesForTests, cached, caches } from "../server-cache";
import {
invalidateAppSettings,
invalidateUserDashboardWidgets,
invalidateUserDashboardSnapshot,
invalidateUserInsights,
@@ -95,8 +94,6 @@ async function primeAllCaches(): Promise<void> {
dashboardSnapshotCacheKey(USER_B),
async () => ({ snap: 2 }),
);
await cached(caches.bugreportStatus, "singleton", async () => ({ s: 1 }));
}
describe("invalidateUserMeasurements", () => {
@@ -347,13 +344,3 @@ describe("invalidateUserProfile", () => {
expect(caches.medications.get(USER_A)).not.toBeNull();
});
});
describe("invalidateAppSettings", () => {
it("evicts the entire bug-report status cache (singleton row)", async () => {
await primeAllCaches();
invalidateAppSettings();
expect(caches.bugreportStatus.get("singleton")).toBeNull();
// Per-user caches untouched.
expect(caches.analytics.get(`${USER_A}|default`)).not.toBeNull();
});
});
-1
View File
@@ -616,7 +616,6 @@ describe("global cache registry", () => {
expect(caches.medications).toBeDefined();
expect(caches.achievements).toBeDefined();
expect(caches.dashboardWidgets).toBeDefined();
expect(caches.bugreportStatus).toBeDefined();
expect(caches.workouts).toBeDefined();
expect(caches.medicationsIntake).toBeDefined();
expect(caches.moodAnalytics).toBeDefined();
-13
View File
@@ -288,16 +288,3 @@ export function invalidateAllCaches(): void {
cache.deleteByPrefix("");
}
}
/**
* Global eviction of the bug-report-status cache.
*
* The cache is keyed on the singleton `"singleton"` slot because the
* underlying data is a row in `AppSettings`. Any admin write to the
* GitHub-token / bug-report-enabled fields invalidates the entire
* cache; the per-user `isAdmin` flag is layered on at request time, so
* the cache itself only stores role-agnostic shape.
*/
export function invalidateAppSettings(): void {
caches.bugreportStatus.deleteByPrefix("");
}
+1 -6
View File
@@ -428,7 +428,7 @@ export class ServerCache<T> {
*
* The blueprint's full eight-cache roster is provisioned so future
* rounds can wire the remaining routes (`/api/medications`,
* `/api/dashboard/widgets`, `/api/bugreport/status`, `/api/workouts`,
* `/api/dashboard/widgets`, `/api/workouts`,
* `/api/mood/analytics`) without churning the helper module.
*/
export const caches = {
@@ -511,11 +511,6 @@ export const caches = {
maxEntries: 500,
ttlMs: 300_000,
}),
bugreportStatus: new ServerCache<unknown>({
name: "bugreportStatus",
maxEntries: 10,
ttlMs: 600_000,
}),
workouts: new ServerCache<unknown>({
name: "workouts",
maxEntries: 1000,
-1
View File
@@ -90,7 +90,6 @@ export const ENCRYPTED_COLUMNS: readonly EncryptedColumn[] = [
field: "webPushVapidPrivateKeyEncrypted",
kind: "string",
},
{ model: "AppSettings", field: "githubIssueTokenEncrypted", kind: "string" },
// ───── Custom labels (mood + cycle) ─────
{ model: "MoodTag", field: "labelEncrypted", kind: "string" },
-10
View File
@@ -156,16 +156,6 @@ async function ensureAppSettingsSchema() {
ALTER TABLE "app_settings"
ADD COLUMN IF NOT EXISTS "glitchtip_environment" TEXT;
`);
await prisma.$executeRawUnsafe(`
ALTER TABLE "app_settings"
ADD COLUMN IF NOT EXISTS "github_issue_token_encrypted" TEXT;
`);
await prisma.$executeRawUnsafe(`
ALTER TABLE "app_settings"
ADD COLUMN IF NOT EXISTS "github_issue_repo" TEXT;
`);
}
async function ensureMedicationSchema() {
-174
View File
@@ -1,174 +0,0 @@
/**
* GitHub publisher for feedback items.
*
* Centralises the GitHub Issues API interaction so /api/bugreport (legacy
* direct-submit) and /api/admin/feedback/[id]/github (admin-promotes-feedback)
* share one implementation. Reads the configured token + repo from AppSettings
* (encrypted) with env-var fallback.
*/
import { prisma } from "@/lib/db";
import { decrypt } from "@/lib/crypto";
import { getEvent } from "@/lib/logging/context";
import { safeFetch } from "@/lib/safe-fetch";
export interface FeedbackInput {
category: string;
subject: string;
description: string;
username: string;
metadata?: unknown;
}
export interface PublishResult {
issueNumber: number;
issueUrl: string;
}
export class GithubPublishError extends Error {
constructor(
message: string,
public status: number,
) {
super(message);
this.name = "GithubPublishError";
}
}
/**
* Resolves the configured GitHub token + repo from AppSettings (or env).
* Returns null if no configuration is present (caller should treat as 503).
*/
async function getGithubConfig(): Promise<{
token: string;
repo: string;
} | null> {
const appSettings = await prisma.appSettings.findUnique({
where: { id: "singleton" },
select: {
githubIssueTokenEncrypted: true,
githubIssueRepo: true,
},
});
let configuredToken: string | null = null;
if (appSettings?.githubIssueTokenEncrypted) {
try {
configuredToken = decrypt(appSettings.githubIssueTokenEncrypted);
} catch {
getEvent()?.addWarning("Failed to decrypt GitHub issue token");
}
}
const token = configuredToken || process.env.GITHUB_ISSUE_TOKEN || "";
const repo =
appSettings?.githubIssueRepo || process.env.GITHUB_ISSUE_REPO || "";
if (!token || !repo) return null;
return { token, repo };
}
/**
* Sanitise a free-text field for GitHub markdown (strip control chars,
* neutralise fenced code blocks, hard-cap length).
*/
function sanitize(text: string, max = 5000): string {
return text.replace(/```/g, "\\`\\`\\`").slice(0, max);
}
/**
* Escape a string for safe inclusion in a `RegExp(..)` constructor — the
* standard "don't let an attacker turn input into regex metacharacters"
* helper. Used to redact secrets from logged error bodies.
*/
function escapeRegex(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Publishes a feedback item as a GitHub Issue. Returns issue number + URL.
* Throws GithubPublishError on API failure.
*/
export async function publishFeedbackToGithub(
input: FeedbackInput,
): Promise<PublishResult> {
const config = await getGithubConfig();
if (!config) {
throw new GithubPublishError(
"GitHub publishing is not configured (missing token or repository)",
503,
);
}
const now = new Date();
const dateStr = now.toISOString().replace("T", " ").slice(0, 16) + " UTC";
const safeUsername = input.username.replace(/[`*_~<>\[\]|]/g, "");
const safeSubject = sanitize(input.subject, 200);
const safeDescription = sanitize(input.description);
const categoryLabelMap: Record<string, string> = {
BUG: "bug",
FEATURE_REQUEST: "enhancement",
QUESTION: "question",
OTHER: "feedback",
};
const categoryLabel = categoryLabelMap[input.category] ?? "feedback";
let body = `**Reported by:** ${safeUsername}\n`;
body += `**Category:** ${input.category}\n`;
body += `**Date:** ${dateStr}\n\n`;
body += `## Description\n\n${safeDescription}\n`;
if (input.metadata && typeof input.metadata === "object") {
const meta = input.metadata as Record<string, unknown>;
const lines: string[] = [];
for (const [key, value] of Object.entries(meta)) {
if (value == null) continue;
const v = String(value).slice(0, 200);
lines.push(`- **${key}:** ${v.replace(/[`<>]/g, "")}`);
}
if (lines.length > 0) {
body += `\n## Context\n\n${lines.join("\n")}\n`;
}
}
body += `\n\n---\n*Created via HealthLog feedback*`;
const title = `[${categoryLabel}] ${safeSubject || `Feedback – ${dateStr}`}`;
const res = await safeFetch(
`https://api.github.com/repos/${config.repo}/issues`,
{
method: "POST",
headers: {
Authorization: `Bearer ${config.token}`,
"Content-Type": "application/json",
Accept: "application/vnd.github.v3+json",
},
body: JSON.stringify({
title,
body,
labels: [categoryLabel, "user-reported"],
}),
},
);
if (!res.ok) {
const errBody = await res.text();
// Strip the GitHub PAT before logging — GitHub error responses can echo
// request headers in some failure modes, and Wide Events flow to Loki
// unredacted. Keep the response shape useful for debugging without
// leaking the credential.
const sanitisedErr = errBody
.replace(new RegExp(escapeRegex(config.token), "g"), "[REDACTED]")
.slice(0, 500);
getEvent()?.addWarning("GitHub issue creation failed: " + sanitisedErr);
throw new GithubPublishError(
`Failed to create GitHub issue (HTTP ${res.status})`,
res.status === 401 || res.status === 403 ? res.status : 502,
);
}
const issue = (await res.json()) as { number: number; html_url: string };
return { issueNumber: issue.number, issueUrl: issue.html_url };
}
@@ -25,7 +25,6 @@ const FULL_METRICS: AchievementMetrics = {
passkeyLoginCount: 1000,
passwordLoginCount: 1000,
loginDayStreak: 1000,
bugReportCount: 1000,
moodEntryCount: 1000,
moodDayStreak: 1000,
moodImprovementHit: 1000,
@@ -91,8 +90,8 @@ describe("gamification achievements", () => {
).toBe(3);
});
it("ships the expanded definition list (65 total — v1.4.18 + v1.16.1 care routine)", () => {
expect(ACHIEVEMENT_DEFINITIONS).toHaveLength(65);
it("ships the expanded definition list (63 total — v1.4.18 + v1.16.1 care routine)", () => {
expect(ACHIEVEMENT_DEFINITIONS).toHaveLength(63);
});
it("includes mood and hidden categories in the render order", () => {
@@ -103,8 +102,8 @@ describe("gamification achievements", () => {
it("evaluates unlocked achievements and points when all metrics maxed", () => {
const result = evaluateAchievementsWithCompletionDates(FULL_METRICS, {});
expect(result.summary.unlockedCount).toBe(65);
expect(result.summary.totalCount).toBe(65);
expect(result.summary.unlockedCount).toBe(63);
expect(result.summary.totalCount).toBe(63);
expect(result.summary.nextAchievement).toBeNull();
expect(result.summary.earnedPoints).toBe(result.summary.totalPoints);
});
@@ -598,7 +598,6 @@ export async function buildAchievementsResult(
in: [
"auth.login.passkey",
"auth.login.password",
"bugreport.submit",
// v1.4.18 — hidden Easter-egg triggers
"doctor-report.generate",
"doctor-report.pdf.generate",
@@ -700,9 +699,6 @@ export async function buildAchievementsResult(
const passwordLoginDates = auditEvents
.filter((event) => event.action === "auth.login.password")
.map((event) => event.createdAt);
const bugReportDates = auditEvents
.filter((event) => event.action === "bugreport.submit")
.map((event) => event.createdAt);
const loginDaySeries = getEventDaySeries([
...passkeyLoginDates,
...passwordLoginDates,
@@ -800,7 +796,6 @@ export async function buildAchievementsResult(
passkeyLoginCount: passkeyLoginDates.length,
passwordLoginCount: passwordLoginDates.length,
loginDayStreak: calculateLongestStreak(freeze(loginDaySeries.dayKeys)),
bugReportCount: bugReportDates.length,
...expansionValues,
// v1.16.1 — care-routine metrics.
missFreeDayStreak: calculateLongestStreak(freeze(missFreeSeries.dayKeys)),
@@ -848,15 +843,6 @@ export async function buildAchievementsResult(
continue;
}
if (definition.metric === "bugReportCount") {
const completedAt = findCountCompletionDate(
bugReportDates,
definition.target,
);
if (completedAt) completionDates[definition.id] = completedAt;
continue;
}
if (definition.metric === "overIntakeCount") {
const completedAt = findCountCompletionDate(
intakeIssueMetrics.overIntakeDates,
+2 -27
View File
@@ -15,7 +15,6 @@ export type AchievementMetricKey =
| "passkeyLoginCount"
| "passwordLoginCount"
| "loginDayStreak"
| "bugReportCount"
// v1.4.18 expansion ─ mood
| "moodEntryCount"
| "moodDayStreak"
@@ -84,7 +83,7 @@ export interface AchievementDefinition {
* v1.18.0 — module ownership for an achievement metric. Returns the
* `ModuleKey` whose enable/disable state governs the badge, or `null`
* when the badge belongs to a core domain (vitals, medications) or to
* an account-wide capability (security, login, bug reports) that has no
* an account-wide capability (security, login) that has no
* toggleable module behind it.
*
* The string literals here intentionally mirror `MODULE_KEYS` in
@@ -148,7 +147,6 @@ function categoryForMetric(metric: AchievementMetricKey): AchievementCategory {
case "passwordLoginCount":
return "security";
case "loginDayStreak":
case "bugReportCount":
case "consistentMonthCount":
case "entryDayStreak":
case "weekendStreakCount":
@@ -192,7 +190,6 @@ export interface AchievementMetrics {
passkeyLoginCount: number;
passwordLoginCount: number;
loginDayStreak: number;
bugReportCount: number;
moodEntryCount: number;
moodDayStreak: number;
moodImprovementHit: number;
@@ -386,16 +383,6 @@ export const ACHIEVEMENT_DEFINITIONS: AchievementDefinition[] = [
tDescription: "achievements.badges.passwordLogin1.description",
format: "count",
}),
define({
id: "bugreport-1",
metric: "bugReportCount",
target: 1,
points: 30,
icon: "Bug",
tTitle: "achievements.badges.bugReport1.title",
tDescription: "achievements.badges.bugReport1.description",
format: "count",
}),
define({
id: "login-streak-7",
metric: "loginDayStreak",
@@ -668,17 +655,6 @@ export const ACHIEVEMENT_DEFINITIONS: AchievementDefinition[] = [
format: "count",
isHidden: true,
}),
define({
id: "hidden-bug-buddy",
metric: "bugReportCount",
target: 5,
points: 60,
icon: "Bug",
tTitle: "achievements.badges.hiddenBugBuddy.title",
tDescription: "achievements.badges.hiddenBugBuddy.description",
format: "count",
isHidden: true,
}),
// ─── v1.16.1 ─ care routine (6) ─────────────────────────
// Quiet, clinically meaningful milestones: therapy adherence without
// a single auto-missed dose, sustained measurement consistency, a
@@ -932,7 +908,7 @@ export function evaluateAchievementsWithCompletionDates(
* 2. Hidden Easter-eggs always stay (the "?" placeholder is the
* whole point).
* 3. Achievements without a metric-data precondition (security,
* bugreport, login-streaks) stay because the precondition is
* login-streaks) stay because the precondition is
* "the user has an account", which is implicit.
*/
export function applyDiscoveryFilter(
@@ -977,7 +953,6 @@ function isEarnable(
case "passkeyLoginCount":
case "passwordLoginCount":
case "loginDayStreak":
case "bugReportCount":
case "consistentMonthCount":
case "entryDayStreak":
case "weekendStreakCount":
-2
View File
@@ -41,6 +41,4 @@ export const settingsKeys = {
shareLinks: () => ["share-links"] as const,
featureFlags: () => ["feature-flags"] as const,
bugreportStatus: () => ["bugreport", "status"] as const,
};
-14
View File
@@ -62,20 +62,6 @@ export const adminSettingsSchema = z
)
.optional(),
glitchtipEnvironment: z.string().optional(),
bugReportRepo: z
.string()
.refine(
(v) => {
const trimmed = v.trim();
if (!trimmed) return true;
return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(trimmed);
},
{ message: "GitHub repository must be in owner/repo format" },
)
.optional(),
bugReportToken: z.string().optional(),
clearBugReportToken: z.boolean().optional(),
bugReportEnabled: z.boolean().optional(),
reminderLateMinutes: z.number().int().min(15).max(480).optional(),
reminderMissedMinutes: z.number().int().min(30).max(720).optional(),
moodLogGlobal: z.boolean().optional(),
-44
View File
@@ -1,44 +0,0 @@
import { z } from "zod/v4";
export const feedbackCategoryEnum = z.enum([
"BUG",
"FEATURE_REQUEST",
"QUESTION",
"OTHER",
]);
export const feedbackStatusEnum = z.enum([
"OPEN",
"ACKNOWLEDGED",
"RESOLVED",
"ARCHIVED",
]);
// Strictly PNG / JPEG / WEBP / GIF data URLs. SVG intentionally excluded —
// it can carry inline JS that would execute when the admin inbox renders the
// preview.
const SCREENSHOT_DATA_URL =
/^data:image\/(png|jpeg|webp|gif);base64,[A-Za-z0-9+/=]+$/;
export const createFeedbackSchema = z.object({
category: feedbackCategoryEnum.default("BUG"),
subject: z.string().min(3).max(200),
description: z.string().min(10).max(5000),
screenshot: z
.string()
.max(7_000_000, "Screenshot too large (max 5 MB)")
.regex(
SCREENSHOT_DATA_URL,
"Screenshot must be a base64-encoded PNG/JPEG/WEBP/GIF data URL",
)
.optional(),
metadata: z.record(z.string(), z.unknown()).optional(),
});
export const updateFeedbackSchema = z.object({
status: feedbackStatusEnum.optional(),
adminNote: z.string().max(5000).nullable().optional(),
});
export type CreateFeedbackPayload = z.infer<typeof createFeedbackSchema>;
export type UpdateFeedbackPayload = z.infer<typeof updateFeedbackSchema>;