Files
2026-10-29 17:29:25 -03:00

50 lines
1.4 KiB
TypeScript

import { z } from "@zod/zod";
import { define } from "@/utils.ts";
import { db } from "@/src/db.ts";
const CreateKeyBody = z.object({
code: z.string().min(1),
key_check: z.string().min(1).max(200),
passphrase_backup: z.object({
wrapped_key: z.string().min(1).max(200),
salt: z.string().min(1).max(100),
iterations: z.number().int().min(100_000).max(10_000_000),
}).optional(),
});
export const handler = define.handlers({
async POST(ctx) {
const body = CreateKeyBody.safeParse(await ctx.req.json().catch(() => null));
if (!body.success) {
return Response.json({ error: "Invalid request" }, { status: 400 });
}
const user = await db.get_entry_by_index("users", "code", body.data.code);
if (!user) {
return Response.json({ error: "Invalid code" }, { status: 401 });
}
const already_exists = Response.json({ error: "This account already has an encryption key" }, { status: 409 });
const entry = await db.get_entry_full("users", user.id);
if (!entry || entry.value.key_check) {
return already_exists;
}
// Checked against the versionstamp so two tabs can't both register a key
const result = await db.kv.atomic()
.check(entry)
.set(entry.key, {
...entry.value,
key_check: body.data.key_check,
passphrase_backup: body.data.passphrase_backup,
})
.commit();
if (!result.ok) {
return already_exists;
}
return new Response(null, { status: 204 });
},
});