Encryption keys

This commit is contained in:
2026-10-29 17:29:25 -03:00
parent 5c5490a36a
commit bf00317e95
11 changed files with 609 additions and 3 deletions
+49
View File
@@ -0,0 +1,49 @@
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 });
},
});
+32
View File
@@ -0,0 +1,32 @@
import { z } from "@zod/zod";
import { define } from "@/utils.ts";
import { db, type User } from "@/src/db.ts";
import type { GetKeyResponse } from "@/src/keys.ts";
const GetKeyBody = z.object({
code: z.string().min(1),
});
export const handler = define.handlers({
async POST(ctx) {
const body = GetKeyBody.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 { key_check, passphrase_backup } = user as Partial<User>;
return Response.json(
{
user_id: user.id,
key_check: key_check ?? null,
passphrase_backup: passphrase_backup ?? null,
} satisfies GetKeyResponse,
);
},
});