User codes
This commit is contained in:
@@ -1,3 +1,7 @@
|
||||
Do not style anything for now
|
||||
|
||||
Do not add libraries without asking first or giving me the option to choose a different library
|
||||
|
||||
## Commands
|
||||
|
||||
- `deno task dev`: dev server (Vite)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
This will be an end to end encrypted file service
|
||||
|
||||
The flow for a new user will go as follows:
|
||||
|
||||
- Basically empty page with a text input, they will type in a code and the server will verify that code
|
||||
- If the code is not verified, give an error
|
||||
- If the code verifies, they will be taken to a second screen where they will choose between generating a new
|
||||
cryptographic key or importing one from another session
|
||||
- Choosing one of the 2 will take the user to the main hub of the service where they will be able to see their files,
|
||||
upload new ones and such
|
||||
|
||||
There will be no database file, just a json file at DATABASE_PATH that will store the few users we have and such
|
||||
|
||||
Users will be an dictionary in the database file with a "users" key, the users dictionary will be a
|
||||
`Record<string, User>` where the key to that is a `monotonicUlid()`
|
||||
@@ -20,6 +20,8 @@
|
||||
],
|
||||
"imports": {
|
||||
"@/": "./",
|
||||
"@std/ulid": "jsr:@std/ulid@^1.0.0",
|
||||
"@zod/zod": "jsr:@zod/zod@^4.6.7",
|
||||
"fresh": "jsr:@fresh/core@^2.3.3",
|
||||
"preact": "npm:preact@^10.29.1",
|
||||
"@preact/signals": "npm:@preact/signals@^2.9.0",
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"jsr:@deno/loader@0.4": "0.4.0",
|
||||
"jsr:@deno/loader@~0.3.10": "0.3.14",
|
||||
"jsr:@fresh/build-id@1": "1.0.1",
|
||||
"jsr:@fresh/core@*": "2.3.3",
|
||||
"jsr:@fresh/core@2": "2.3.3",
|
||||
"jsr:@fresh/core@^2.3.3": "2.3.3",
|
||||
"jsr:@fresh/plugin-vite@^1.1.2": "1.1.2",
|
||||
@@ -27,7 +28,9 @@
|
||||
"jsr:@std/path@^1.1.2": "1.1.6",
|
||||
"jsr:@std/path@^1.1.5": "1.1.6",
|
||||
"jsr:@std/semver@^1.0.6": "1.0.8",
|
||||
"jsr:@std/ulid@1": "1.0.0",
|
||||
"jsr:@std/uuid@^1.0.9": "1.1.1",
|
||||
"jsr:@zod/zod@^4.6.7": "4.6.7",
|
||||
"npm:@babel/core@^7.28.0": "7.29.7",
|
||||
"npm:@babel/preset-react@^7.27.1": "7.29.7_@babel+core@7.29.7",
|
||||
"npm:@opentelemetry/api@^1.9.0": "1.9.1",
|
||||
@@ -36,6 +39,7 @@
|
||||
"npm:@prefresh/vite@^2.4.8": "2.4.12_preact@10.29.8_vite@7.3.6_preact-render-to-string@6.7.0",
|
||||
"npm:@remix-run/node-fetch-server@0.12": "0.12.0",
|
||||
"npm:@tailwindcss/vite@^4.1.12": "4.3.3_vite@7.3.6",
|
||||
"npm:@types/babel__core@^7.20.5": "7.20.5",
|
||||
"npm:esbuild-wasm@~0.25.11": "0.25.12",
|
||||
"npm:esbuild@0.25.7": "0.25.7",
|
||||
"npm:esbuild@~0.25.5": "0.25.12",
|
||||
@@ -107,6 +111,7 @@
|
||||
"npm:@babel/preset-react",
|
||||
"npm:@prefresh/vite",
|
||||
"npm:@remix-run/node-fetch-server",
|
||||
"npm:@types/babel__core",
|
||||
"npm:rollup",
|
||||
"npm:vite@^7.1.4"
|
||||
]
|
||||
@@ -165,11 +170,17 @@
|
||||
"@std/semver@1.0.8": {
|
||||
"integrity": "dc830e8b8b6a380c895d53fbfd1258dc253704ca57bbe1629ac65fd7830179b7"
|
||||
},
|
||||
"@std/ulid@1.0.0": {
|
||||
"integrity": "d41c3d27a907714413649fee864b7cde8d42ee68437d22b79d5de4f81d808780"
|
||||
},
|
||||
"@std/uuid@1.1.1": {
|
||||
"integrity": "7b49060282d90f72fec64952f8c7a2914cbe6fdba3eca665f8cedc90830154a7",
|
||||
"dependencies": [
|
||||
"jsr:@std/bytes"
|
||||
]
|
||||
},
|
||||
"@zod/zod@4.6.7": {
|
||||
"integrity": "6706868ce1e1907362e1bf008e298e482723345f0ba4125c43e5b9fd7960b186"
|
||||
}
|
||||
},
|
||||
"npm": {
|
||||
@@ -1480,6 +1491,8 @@
|
||||
"dependencies": [
|
||||
"jsr:@fresh/core@^2.3.3",
|
||||
"jsr:@fresh/plugin-vite@^1.1.2",
|
||||
"jsr:@std/ulid@1",
|
||||
"jsr:@zod/zod@^4.6.7",
|
||||
"npm:@preact/signals@^2.9.0",
|
||||
"npm:@tailwindcss/vite@^4.1.12",
|
||||
"npm:preact@^10.29.1",
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import Form from "@/islands/Form.tsx";
|
||||
import { Signal } from "@preact/signals";
|
||||
|
||||
interface AskCodeProps {
|
||||
page: Signal<string>;
|
||||
}
|
||||
|
||||
export default function AskCode({ page }: AskCodeProps) {
|
||||
const on_success = (data: { code: string }) => {
|
||||
localStorage.setItem("code", data.code);
|
||||
page.value = "keys";
|
||||
};
|
||||
|
||||
return (
|
||||
<Form action="/api/verify_code" on_success={on_success}>
|
||||
<input type="text" name="code" />
|
||||
<button type="submit">Enter</button>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { ComponentChildren } from "preact";
|
||||
import { useSignal } from "@preact/signals";
|
||||
|
||||
interface FormProps<T> {
|
||||
action: string;
|
||||
on_success: (data: T) => void;
|
||||
on_error?: (message: string) => void;
|
||||
class?: string;
|
||||
method?: string;
|
||||
children: ComponentChildren;
|
||||
}
|
||||
|
||||
// Posts the form's named fields as a JSON object of strings
|
||||
export default function Form<T = unknown>(props: FormProps<T>) {
|
||||
const submitting = useSignal(false);
|
||||
const error = useSignal("");
|
||||
|
||||
async function submit(event: SubmitEvent) {
|
||||
event.preventDefault();
|
||||
if (submitting.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
const form = event.currentTarget as HTMLFormElement;
|
||||
const body = Object.fromEntries(new FormData(form));
|
||||
|
||||
submitting.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const method = props.method ?? "POST";
|
||||
const response = await fetch(
|
||||
props.action,
|
||||
method.toUpperCase() === "GET" ? { method } : {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
);
|
||||
const data = response.status === 204 ? undefined : await response.json().catch(() => undefined);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data?.error ?? `Request failed with status ${response.status}`);
|
||||
}
|
||||
props.on_success(data as T);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
if (props.on_error) props.on_error(message);
|
||||
else error.value = message;
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form class={props.class} onSubmit={submit}>
|
||||
<fieldset disabled={submitting.value}>{props.children}</fieldset>
|
||||
{error.value && <p role="alert">{error.value}</p>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useSignal } from "@preact/signals";
|
||||
|
||||
import AskCode from "./AskCode.tsx";
|
||||
|
||||
export default function MainIsland() {
|
||||
const page = useSignal("askcode");
|
||||
|
||||
if (page.value === "askcode") {
|
||||
return <AskCode page={page} />;
|
||||
} else if (page.value === "keys") {
|
||||
return localStorage.getItem("code");
|
||||
} else {
|
||||
return "Error";
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,16 @@
|
||||
import { App, staticFiles } from "fresh";
|
||||
import { App, csp, csrf, staticFiles } from "fresh";
|
||||
import { define, type State } from "./utils.ts";
|
||||
|
||||
export const app = new App<State>();
|
||||
|
||||
// Vite's dev client injects CSS through <style> tags without a nonce
|
||||
app.use(csrf(), csp({ useNonce: !import.meta.env.DEV }));
|
||||
|
||||
app.use(staticFiles());
|
||||
|
||||
// Pass a shared value from a middleware
|
||||
app.use(async (ctx) => {
|
||||
ctx.state.shared = "hello";
|
||||
return await ctx.next();
|
||||
});
|
||||
|
||||
// this is the same as the /api/:name route defined via a file. feel free to delete this!
|
||||
app.get("/api2/:name", (ctx) => {
|
||||
const name = ctx.params.name;
|
||||
return new Response(
|
||||
`Hello, ${name.charAt(0).toUpperCase() + name.slice(1)}!`,
|
||||
);
|
||||
});
|
||||
|
||||
// this can also be defined via a file. feel free to delete this!
|
||||
const exampleLoggerMiddleware = define.middleware((ctx) => {
|
||||
app.use(define.middleware((ctx) => {
|
||||
console.log(`${ctx.req.method} ${ctx.req.url}`);
|
||||
return ctx.next();
|
||||
});
|
||||
app.use(exampleLoggerMiddleware);
|
||||
}));
|
||||
|
||||
// Include file-system based routes here
|
||||
app.fsRoutes();
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { define } from "@/utils.ts";
|
||||
import { get_all_users, new_user } from "@/src/db.ts";
|
||||
import { generate_code } from "@/src/crypto.ts";
|
||||
|
||||
export const handler = define.handlers({
|
||||
async POST(ctx) {
|
||||
const data = await ctx.req.json();
|
||||
// TODO: zod schema
|
||||
|
||||
const code = data.code;
|
||||
const users = await get_all_users();
|
||||
if (users.length >= 1) {
|
||||
const maybe_user = users.find((user) => user.code === code);
|
||||
|
||||
if (maybe_user) {
|
||||
return Response.json({ code });
|
||||
}
|
||||
|
||||
return Response.json({ error: "Invalid code" }, { status: 401 });
|
||||
}
|
||||
|
||||
// create admin
|
||||
const admin_code = generate_code();
|
||||
await new_user({ name: "admin", code: admin_code, admin: true });
|
||||
|
||||
return Response.json({ code: admin_code });
|
||||
},
|
||||
});
|
||||
+7
-2
@@ -1,5 +1,10 @@
|
||||
import { define } from "@/utils.ts";
|
||||
import MainIsland from "@/islands/MainIsland.tsx";
|
||||
|
||||
export default define.page(function (ctx) {
|
||||
return <div></div>;
|
||||
export default define.page(function () {
|
||||
return (
|
||||
<div>
|
||||
<MainIsland />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
||||
|
||||
export function generate_code(length = 16) {
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(length));
|
||||
return Array.from(bytes, (byte) => ALPHABET[byte % 32]).join("");
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { monotonicUlid } from "@std/ulid";
|
||||
|
||||
import { DATABASE_PATH } from "@/src/server_constants.ts";
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
admin: boolean;
|
||||
}
|
||||
|
||||
interface Database {
|
||||
users: Record<string, User>;
|
||||
}
|
||||
|
||||
let write_queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
function get_database_path() {
|
||||
if (!DATABASE_PATH) {
|
||||
throw new Error("DATABASE_PATH is not set");
|
||||
}
|
||||
return DATABASE_PATH;
|
||||
}
|
||||
|
||||
async function read_database(): Promise<Database> {
|
||||
try {
|
||||
return JSON.parse(await Deno.readTextFile(get_database_path()));
|
||||
} catch (error) {
|
||||
if (error instanceof Deno.errors.NotFound) return { users: {} };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Writes to a temp file first so a crash mid-write can't corrupt the database
|
||||
async function write_database(database: Database) {
|
||||
const path = get_database_path();
|
||||
await Deno.writeTextFile(`${path}.tmp`, JSON.stringify(database, null, "\t"));
|
||||
await Deno.rename(`${path}.tmp`, path);
|
||||
}
|
||||
|
||||
// Runs read-modify-write operations one at a time so concurrent calls don't overwrite each other
|
||||
function with_write_lock<T>(fn: () => Promise<T>): Promise<T> {
|
||||
const result = write_queue.then(fn);
|
||||
write_queue = result.catch(() => {});
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function get_user(id: string): Promise<User | undefined> {
|
||||
const database = await read_database();
|
||||
return database.users[id];
|
||||
}
|
||||
|
||||
export function new_user(user: Omit<User, "id">): Promise<User> {
|
||||
return with_write_lock(async () => {
|
||||
const database = await read_database();
|
||||
const created: User = { ...user, id: monotonicUlid() };
|
||||
database.users[created.id] = created;
|
||||
await write_database(database);
|
||||
return created;
|
||||
});
|
||||
}
|
||||
|
||||
export async function get_all_users(): Promise<User[]> {
|
||||
const database = await read_database();
|
||||
return Object.values(database.users);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export const DATABASE_PATH = Deno.env.get("DATABASE_PATH");
|
||||
@@ -1,9 +1,7 @@
|
||||
import { createDefine } from "fresh";
|
||||
|
||||
// This specifies the type of "ctx.state" which is used to share
|
||||
// data among middlewares, layouts and routes.
|
||||
// deno-lint-ignore no-empty-interface
|
||||
export interface State {
|
||||
shared: string;
|
||||
}
|
||||
|
||||
export const define = createDefine<State>();
|
||||
|
||||
Reference in New Issue
Block a user