Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions apps/web/app/api/account/api-keys/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/session";
import { createApiKey, listApiKeys, revokeApiKey } from "@/lib/entitlements";
import { readApiKeyRequest } from "@/lib/api-key-request";

export const runtime = "nodejs";

Expand All @@ -20,8 +21,11 @@ export async function POST(req: Request) {
{ status: 402 },
);
}
const body = await req.json().catch(() => ({}));
const created = await createApiKey(user.id, String(body.label || "API key"));
const body = await readApiKeyRequest(req);
if (!body.ok) {
return NextResponse.json({ ok: false, error: "Invalid request." }, { status: 400 });
}
const created = await createApiKey(user.id, body.label);
return NextResponse.json({ ok: true, apiKey: created.plaintext, prefix: created.prefix });
}

Expand Down
28 changes: 28 additions & 0 deletions apps/web/lib/api-key-request.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { readApiKeyRequest } from "./api-key-request";

function request(body: string): Request {
return new Request("https://aiornot.vote/api/account/api-keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body,
});
}

describe("readApiKeyRequest", () => {
it("rejects malformed JSON instead of creating a default key", async () => {
await expect(readApiKeyRequest(request('{"label":'))).resolves.toEqual({ ok: false });
});

it("rejects JSON values that are not objects", async () => {
await expect(readApiKeyRequest(request("null"))).resolves.toEqual({ ok: false });
await expect(readApiKeyRequest(request("[]"))).resolves.toEqual({ ok: false });
});

it("uses the default label only for a valid JSON object", async () => {
await expect(readApiKeyRequest(request("{}"))).resolves.toEqual({
ok: true,
label: "API key",
});
});
});
19 changes: 19 additions & 0 deletions apps/web/lib/api-key-request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export type ApiKeyRequest =
| { ok: true; label: string }
| { ok: false };

export async function readApiKeyRequest(req: Request): Promise<ApiKeyRequest> {
let body: unknown;
try {
body = await req.json();
} catch {
return { ok: false };
}

if (!body || typeof body !== "object" || Array.isArray(body)) {
return { ok: false };
}

const label = (body as Record<string, unknown>).label;
return { ok: true, label: String(label || "API key") };
}
Loading