fix: harden the Homarr provider

This commit is contained in:
ajnart committed 2026-08-12 12:33:04 +02:00
1 parent 0774b02878
commit bffa3e723c
43 files changed
+515 -999

No files matched your search

+7 -2
View File
@@ -29,6 +29,7 @@ import {
import type { createTRPCContext } from "../trpc";
import { fetchOpenRouterGenerationTelemetryAsync } from "../assistant-generation-telemetry";
import { env } from "../env";
import { orderMessagesByParent } from "../assistant-message-order";
import { verifyAssistantGenerationAccessToken } from "../assistant-generation-access";
import { createTRPCRouter, isDemoMode, permissionRequiredProcedure, protectedProcedure } from "../trpc";
@@ -129,6 +130,9 @@ const normalizeDiscoveryPath = (value: string | null) => {
return path;
};
const getHomarrProviderBaseUrl = () =>
`${(env.WORKSHOP_API_URL ?? env.HOMARR_WEBSITE_URL).replace(/\/+$/u, "")}/api/ai/v1`;
const getConfigurationAsync = async (db: Database) => {
return await db.query.assistantConfigurations.findFirst({
where: eq(assistantConfigurations.id, configurationId),
@@ -547,8 +551,9 @@ export const assistantRouter = createTRPCRouter({
}),
)
.mutation(async ({ ctx, input }) => {
const baseUrl = normalizeBaseUrl(input.baseUrl);
const modelDiscoveryPath = normalizeDiscoveryPath(input.modelDiscoveryPath);
const baseUrl = input.provider === "homarr" ? getHomarrProviderBaseUrl() : normalizeBaseUrl(input.baseUrl);
const modelDiscoveryPath =
input.provider === "homarr" ? "/models" : normalizeDiscoveryPath(input.modelDiscoveryPath);
const existing = await getConfigurationAsync(ctx.db);
const destinationChanged =
existing !== undefined && (existing.provider !== input.provider || existing.baseUrl !== baseUrl);
@@ -128,8 +128,8 @@ describe("assistantRouter.updateConnection", () => {
await caller.updateConnection({
provider: "homarr",
baseUrl: "https://homarr.dev/api/ai/v1",
modelDiscoveryPath: "/models",
baseUrl: "https://attacker.example/v1",
modelDiscoveryPath: "/attacker-models",
apiKey: "must-not-be-stored",
customHeaders: { "X-Secret": "must-not-be-stored" },
clearApiKey: false,
@@ -139,6 +139,8 @@ describe("assistantRouter.updateConnection", () => {
const [configuration] = await db.select().from(assistantConfigurations);
expect(configuration).toMatchObject({
provider: "homarr",
baseUrl: "https://homarr.dev/api/ai/v1",
modelDiscoveryPath: "/models",
encryptedApiKey: null,
encryptedHeaders: null,
enabled: false,
@@ -203,7 +205,7 @@ describe("assistantRouter.updateConfiguration", () => {
baseUrl: "https://homarr.dev/api/ai/v1",
encryptedApiKey: null,
encryptedHeaders: null,
modelId: "homarr/deepseek-v4-flash-latest",
modelId: "homarr/model",
})
.where(eq(assistantConfigurations.id, "default"));
const caller = assistantRouter.createCaller({ db, deviceType: undefined, session: adminSession });
@@ -213,8 +215,8 @@ describe("assistantRouter.updateConfiguration", () => {
Response.json({
data: [
{
id: "homarr/deepseek-v4-flash-latest",
name: "DeepSeek V4 Flash Latest",
id: "homarr/model",
name: "Homarr model",
supported_parameters: ["tools"],
architecture: { output_modalities: ["text"] },
},
@@ -226,7 +228,7 @@ describe("assistantRouter.updateConfiguration", () => {
try {
await caller.updateConfiguration({
enabled: true,
modelId: "homarr/deepseek-v4-flash-latest",
modelId: "homarr/model",
webSearchEnabled: true,
});
} finally {
@@ -23,7 +23,7 @@ export const resolveAiEvaluationProviderConfig = (environment: Record<string, st
const baseUrl = (configuredBaseUrl || DEFAULT_AI_PROVIDER_BASE_URL).replace(/\/+$/u, "");
const homarrProvider = baseUrl.endsWith("/api/ai/v1");
const openRouterProvider = baseUrl === DEFAULT_AI_PROVIDER_BASE_URL;
const providerDefaultModel = homarrProvider ? "homarr/deepseek-v4-flash-latest" : DEFAULT_GENERATOR_MODEL;
const providerDefaultModel = homarrProvider ? "homarr/model" : DEFAULT_GENERATOR_MODEL;
return {
apiKey: environment.AI_PROVIDER_API_KEY ?? (openRouterProvider ? environment.OPENROUTER_API_KEY : undefined),
baseUrl,
@@ -194,8 +194,8 @@ describe("AI authoring evaluation", () => {
).toEqual({
apiKey: "workshop-token",
baseUrl: "https://homarr.dev/api/ai/v1",
generatorModel: "homarr/deepseek-v4-flash-latest",
judgeModel: "homarr/deepseek-v4-flash-latest",
generatorModel: "homarr/model",
judgeModel: "homarr/model",
});
expect(
resolveAiEvaluationProviderConfig({
@@ -221,8 +221,8 @@ describe("AI authoring evaluation", () => {
).toEqual({
apiKey: "workshop-token",
baseUrl: "https://homarr.dev/api/ai/v1",
generatorModel: "homarr/deepseek-v4-flash-latest",
judgeModel: "homarr/deepseek-v4-flash-latest",
generatorModel: "homarr/model",
judgeModel: "homarr/model",
});
});
+1
View File
@@ -46,6 +46,7 @@ interface AssistantProviderPreset {
export const assistantProviderPresets = {
homarr: {
// Browser and server code replace this public fallback with WORKSHOP_API_URL at runtime.
baseUrl: "https://homarr.dev/api/ai/v1",
modelDiscoveryPath: "/models",
requiresApiKey: false,
+1 -1
View File
@@ -6212,7 +6212,7 @@
"options": {
"homarr": {
"label": "Homarr",
"description": "Community-funded DeepSeek V4 Flash access through Homarr. Each user signs in with the Community Workshop and receives a daily allowance."
"description": "Community-funded access to the model selected by the Homarr team. Each user signs in with the Community Workshop and receives a daily allowance."
},
"openrouter": {
"label": "OpenRouter",
+5 -35
View File
@@ -13,7 +13,6 @@ import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import type {
WorkshopComment,
WorkshopAssistantActivity,
WorkshopAssistantUsage,
WorkshopReport,
WorkshopReportSummary,
@@ -30,7 +29,6 @@ import {
WORKSHOP_REQUEST_TIMEOUT_MS,
WORKSHOP_SCHEMA_BY_TYPE,
workshopCommentSchema,
workshopAssistantActivitySchema,
workshopAssistantUsageSchema,
workshopReportSchema,
workshopReportSummarySchema,
@@ -144,19 +142,6 @@ export interface WorkshopCommentRecord extends WorkshopBaseRecord {
expand?: { author?: WorkshopUserRecord };
}
export interface WorkshopAssistantActivityRecord extends WorkshopBaseRecord {
status: "processing" | "completed" | "failed";
model: string;
requestUnits: number;
inputTokens: number;
outputTokens: number;
totalTokens: number;
durationMs: number;
cost: number;
created: string;
updated: string;
}
export interface TypedWorkshopPocketBase extends PocketBase {
collection(idOrName: "users"): RecordService<WorkshopUserRecord>;
collection(idOrName: "submissions"): RecordService<WorkshopSubmissionRecord>;
@@ -165,7 +150,6 @@ export interface TypedWorkshopPocketBase extends PocketBase {
collection(idOrName: "reports"): RecordService<WorkshopReportRecord>;
collection(idOrName: "workshop_report_summaries"): RecordService<WorkshopReportSummaryRecord>;
collection(idOrName: "comments"): RecordService<WorkshopCommentRecord>;
collection(idOrName: "assistant_activity"): RecordService<WorkshopAssistantActivityRecord>;
collection(idOrName: string): RecordService;
}
@@ -289,6 +273,7 @@ export class WorkshopBackend {
}
public get currentUser(): WorkshopUser | null {
if (!this.pocketBase.authStore.isValid) return null;
const record = this.pocketBase.authStore.record;
if (!record) return null;
const parsed = workshopUserSchema.safeParse({
@@ -308,7 +293,10 @@ export class WorkshopBackend {
}
public async refreshAuth() {
if (!this.pocketBase.authStore.isValid) return null;
if (!this.pocketBase.authStore.isValid) {
this.pocketBase.authStore.clear();
return null;
}
try {
await this.pocketBase.collection("users").authRefresh();
return this.currentUser;
@@ -352,24 +340,6 @@ export class WorkshopBackend {
}
}
public async listAssistantActivity(limit = 10, signal?: AbortSignal): Promise<WorkshopAssistantActivity[]> {
try {
const result = await this.pocketBase
.collection("assistant_activity")
.getList(1, Math.min(Math.max(limit, 1), 50), {
sort: "-created",
signal: requestSignal(signal),
requestKey: null,
});
return result.items.flatMap((item) => {
const parsed = workshopAssistantActivitySchema.safeParse(item);
return parsed.success ? [parsed.data] : [];
});
} catch (error) {
throw workshopError(error, "Failed to load live Homarr provider activity");
}
}
public async list(options: WorkshopListOptions = {}): Promise<WorkshopPage<WorkshopSubmissionSummary>> {
try {
const page = options.page ?? 1;
+2 -30
View File
@@ -88,7 +88,7 @@ describe("WorkshopBackend", () => {
test("lets PocketBase own the complete GitHub popup flow", async () => {
mocks.authWithOAuth2.mockResolvedValue({
token: "token",
token: validWorkshopToken,
record: {
id: "user-id",
name: "octocat",
@@ -137,6 +137,7 @@ describe("WorkshopBackend", () => {
id: "author-id",
name: "octocat",
} as never);
expect(client.currentUser).toBeNull();
expect(client.authToken).toBeNull();
client.pocketBase.authStore.save(validWorkshopToken, { id: 42 } as never);
@@ -144,35 +145,6 @@ describe("WorkshopBackend", () => {
expect(client.authToken).toBeNull();
});
test("loads only valid anonymous provider activity records", async () => {
mocks.getList.mockResolvedValue({
items: [
{
id: "activity-id",
status: "completed",
model: "homarr/deepseek-v4-flash-latest",
requestUnits: 2,
inputTokens: 12,
outputTokens: 7,
totalTokens: 19,
durationMs: 250,
cost: 0.0001,
created: "2026-08-11 10:00:00.000Z",
updated: "2026-08-11 10:00:00.250Z",
},
{ id: "invalid" },
],
});
const client = new WorkshopBackend("https://workshop.example.com");
await expect(client.listAssistantActivity()).resolves.toHaveLength(1);
expect(mocks.getList).toHaveBeenCalledWith(
1,
10,
expect.objectContaining({ sort: "-created", requestKey: null, signal: expect.any(AbortSignal) }),
);
});
test("sends the exported schema while leaving initial revision ownership to PocketBase", async () => {
const client = new WorkshopBackend("https://workshop.example.com");
client.pocketBase.authStore.save(validWorkshopToken, { id: "author-id" } as never);
-15
View File
@@ -110,21 +110,6 @@ export const workshopAssistantUsageSchema = z.object({
});
export type WorkshopAssistantUsage = z.infer<typeof workshopAssistantUsageSchema>;
export const workshopAssistantActivitySchema = z.object({
id: z.string(),
status: z.enum(["processing", "completed", "failed"]),
model: z.string(),
requestUnits: z.number().int().positive(),
inputTokens: z.number().int().nonnegative().default(0),
outputTokens: z.number().int().nonnegative().default(0),
totalTokens: z.number().int().nonnegative().default(0),
durationMs: z.number().int().nonnegative().default(0),
cost: z.number().nonnegative().default(0),
created: z.string(),
updated: z.string(),
});
export type WorkshopAssistantActivity = z.infer<typeof workshopAssistantActivitySchema>;
const normalizeWorkshopSubmissionRecord = (value: unknown) => {
if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
const record = value as Record<string, unknown>;