Skip to content
Source
Sign inSign up
samwillis/neonbricks
Open History to see the last commit

auth.ts

88 lines2.9 KB

1import { createHash, randomBytes, randomUUID } from "node:crypto";
2import type { PoolClient } from "pg";
3import { pool } from "./db";
4export class DomainError extends Error {
5 constructor(
6 public code: string,
7 public status = 409,
8 ) {
9 super(code);
10 }
12export type Identity = {
13 session: string;
14 guest: string;
15 name: string;
16 color: string;
17};
18export const hash = (text: string) =>
19 createHash("sha256").update(text).digest("hex");
20export async function newSession(name: string, color: string) {
21 const guest = randomUUID(),
22 session = randomUUID(),
23 token = randomBytes(32).toString("base64url");
24 const c = await pool.connect();
25 try {
26 await c.query("BEGIN");
27 await c.query("INSERT INTO guests(id,name,color) VALUES($1,$2,$3)", [
28 guest,
29 name,
30 color,
31 ]);
32 const { rows } = await c.query(
33 "INSERT INTO guest_sessions(id,guest,hash,expires_at,absolute_expiry) VALUES($1,$2,$3,clock_timestamp()+interval '30 minutes',clock_timestamp()+interval '24 hours') RETURNING expires_at",
34 [session, guest, hash(token)],
35 );
36 await c.query("COMMIT");
37 return { token, guest, name, color, expiresAt: rows[0].expires_at };
38 } catch (e) {
39 await c.query("ROLLBACK");
40 throw e;
41 } finally {
42 c.release();
43 }
45export async function authenticate(
46 authorization: string | undefined,
47): Promise<Identity> {
48 if (!authorization?.startsWith("Bearer "))
49 throw new DomainError("Sign in to join the workshop", 401);
50 const { rows } = await pool.query(
51 "SELECT s.id AS session,s.guest,g.name,g.color FROM guest_sessions s JOIN guests g ON g.id=s.guest WHERE s.hash=$1 AND s.revoked=0 AND s.expires_at>clock_timestamp() AND s.absolute_expiry>clock_timestamp()",
52 [hash(authorization.slice(7))],
53 );
54 if (!rows[0])
55 throw new DomainError(
56 "Your guest session expired. Rejoin the workshop.",
57 401,
58 );
59 return rows[0];
61export async function lockAccess(
62 c: PoolClient,
63 a: Identity,
64 world: string,
65 editor = true,
66) {
67 const { rows } = await c.query(
68 `SELECT w.*,s.revoked,s.expires_at>clock_timestamp() AND s.absolute_expiry>clock_timestamp() AS valid,
69 w.expires_at IS NULL OR w.expires_at>clock_timestamp() AS unexpired,m.role,m.active
70 FROM guest_sessions s JOIN worlds w ON w.id=$1 JOIN world_memberships m ON m.world=w.id AND m.guest=s.guest
71 WHERE s.id=$2 AND s.guest=$3 FOR SHARE OF s,w,m`,
72 [world, a.session, a.guest],
73 );
74 const w = rows[0];
75 if (!w) throw new DomainError("Workshop access denied", 403);
76 if (!w.valid || w.revoked) throw new DomainError("Session expired", 401);
77 if (editor && (w.status !== "open" || !w.unexpired))
78 throw new DomainError("This workshop is closed or expired", 410);
79 if (!w.active || (editor && w.role !== "editor"))
80 throw new DomainError("Workshop access denied", 403);
81 return w as {
82 id: string;
83 generation: number;
84 status: string;
85 catalogue: string;
86 owner: string;
87 };