feature: initial commit

This commit is contained in:
Andy Burke 2025-06-24 15:40:30 -07:00
commit 2c27f003c9
15 changed files with 1601 additions and 0 deletions

16
public/api/auth/README.md Normal file
View file

@ -0,0 +1,16 @@
# /api/auth
Authentication for the service.
## POST /api/auth
Log into the service.
```
{
email?: string; // either email or username must be specified
username?: string;
password_hash: string; //should be a base64-encoded SHA-256 hash of the user's client-entered pw
totp?: string; // TOTP if configured on account
}
```

192
public/api/auth/index.ts Normal file
View file

@ -0,0 +1,192 @@
import { PASSWORD_ENTRY_STORE } from '../../../models/password_entry.ts';
import { USER, USER_STORE } from '../../../models/user.ts';
import { generateSecret } from 'jsr:@stdext/crypto/utils';
import { encodeBase32 } from 'jsr:@std/encoding';
import { verify } from 'jsr:@stdext/crypto/hash';
import lurid from 'jsr:@andyburke/lurid';
import { SESSION, SESSIONS } from '../../../models/session.ts';
import { TOTP_ENTRY_STORE } from '../../../models/totp_entry.ts';
import { verifyTotp } from 'jsr:@stdext/crypto/totp';
import { encodeBase64 } from 'jsr:@std/encoding/base64';
import parse_body from '../../../utils/bodyparser.ts';
const DEFAULT_SESSION_TIME: number = 60 * 60; // 1 Hour
// POST /api/auth - Authenticate
export async function POST(req: Request, meta: Record<string, any>): Promise<Response> {
try {
const body = await parse_body(req);
const email: string = body.email?.toLowerCase().trim() ?? '';
const username: string = body.username?.toLowerCase() ?? '';
const password: string | undefined = body.password;
const password_hash: string | undefined = body.password_hash ?? (typeof password === 'string'
? encodeBase64(
await crypto.subtle.digest('SHA-256', new TextEncoder().encode(password ?? ''))
)
: undefined);
const totp: string | undefined = body.totp;
if ((!email.length && !username.length) || (email.length && username.length)) {
return Response.json({
error: {
message: 'You must specify either an email or username to log in.',
cause: 'email_or_username_required'
}
}, {
status: 400
});
}
// password has should be a base64-encoded SHA-256 hash
if (typeof password_hash !== 'string') {
return Response.json({
error: {
message: 'invalid password hash',
cause: 'invalid_password_hash'
}
}, {
status: 400
});
}
let user: USER | undefined = undefined;
if (email.length) {
user = (await USER_STORE.find({
email
})).shift();
} else if (username.length) {
user = (await USER_STORE.find({
username
})).shift();
}
if (!user) {
return Response.json({
error: {
message: 'Could not locate an account with this email or username.',
cause: 'missing_account'
}
}, {
status: 400
});
}
const password_entry = await PASSWORD_ENTRY_STORE.get(user.id);
if (!password_entry) {
return Response.json({
error: {
message: 'Missing password entry for this account, please contact support.',
cause: 'missing_password_entry'
}
}, {
status: 500
});
}
const verified = verify('bcrypt', `${password_hash}${password_entry.salt}`, password_entry.hash);
if (!verified) {
return Response.json({
error: {
message: 'Incorrect password.',
cause: 'incorrect_password'
}
}, {
status: 400
});
}
const totp_entry = await TOTP_ENTRY_STORE.get(user.id);
if (totp_entry) {
if (typeof totp !== 'string' || !totp.length) {
return Response.json({
two_factor: true,
totp: true
}, {
status: 202,
headers: {
'Set-Cookie': `checklist_observer_totp_user_id=${user.id}; Path=/; Max-Age=300`
}
});
}
const valid_totp: boolean = await verifyTotp(totp, totp_entry.secret);
if (!valid_totp) {
return Response.json({
error: {
message: 'Incorrect TOTP.',
cause: 'incorrect_totp'
}
}, {
status: 400
});
}
}
const session_result: SESSION_RESULT = await get_session({
user,
expires: body.session?.expires
});
// TODO: verify this redirect is relative?
const headers = session_result.headers;
let status = 201;
if (typeof meta?.query?.redirect === 'string') {
const url = new URL(req.url);
session_result.headers.append('location', `${url.origin}${meta.query.redirect}`);
status = 302;
}
return Response.json({
user,
session: session_result.session
}, {
status,
headers
});
} catch (error) {
return Response.json({
error: {
message: (error as Error).message ?? 'Unknown Error!',
cause: (error as Error).cause ?? 'unknown'
}
}, { status: 400 });
}
}
export type SESSION_RESULT = {
session: SESSION;
headers: Headers;
};
export type SESSION_INFO = {
user: USER;
expires: string | undefined;
};
export async function get_session(session_settings: SESSION_INFO): Promise<SESSION_RESULT> {
const now = new Date().toISOString();
const expires: string = session_settings.expires ??
new Date(new Date(now).valueOf() + DEFAULT_SESSION_TIME).toISOString();
const session: SESSION = {
id: lurid(),
user_id: session_settings.user.id,
secret: encodeBase32(generateSecret()),
timestamps: {
created: now,
expires,
ended: ''
}
};
await SESSIONS.create(session);
const headers = new Headers();
headers.append('Set-Cookie', `checklist_observer_session_id=${session.id}; Path=/; Expires=${expires}`);
return {
session,
headers
};
}

View file

@ -0,0 +1,149 @@
import { PASSWORD_ENTRY, PASSWORD_ENTRY_STORE } from '../../../../models/password_entry.ts';
import { SESSIONS } from '../../../../models/session.ts';
import { USER, USER_STORE } from '../../../../models/user.ts';
import { USER_PERMISSIONS, USER_PERMISSIONS_STORE } from '../../../../models/user_permissions.ts';
import parse_body from '../../../../utils/bodyparser.ts';
export const PERMISSIONS: Record<string, (req: Request, meta: Record<string, any>) => Promise<boolean>> = {};
// GET /api/users/:id - Get single user
PERMISSIONS.GET = (_req: Request, meta: Record<string, any>): Promise<boolean> => {
const user_is_self = !!meta.user && !!meta.params && meta.user.id === meta.params.id;
const can_read_self = meta.user_permissions?.permissions.includes('self.read');
const can_read_others = meta.user_permissions?.permissions?.includes('users.read');
return can_read_others || (can_read_self && user_is_self);
};
export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> {
const user_id: string = meta.params?.id?.toLowerCase().trim() ?? '';
const user: USER | null = user_id.length === 49 ? await USER_STORE.get(user_id) : null; // lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
if (!user) {
return Response.json({
error: {
message: `Could not locate a user with id: "${user_id}"`,
cause: 'unknown_user'
}
}, {
status: 404
});
}
const user_is_self = meta.user?.id === user.id;
const has_permission_to_read = (user_is_self && meta.user_permissions?.permissions?.includes('self.read')) ||
(meta.user_permissions?.permissions?.includes('users.read'));
if (!has_permission_to_read) {
return Response.json({
error: {
message: 'Permission denied.',
cause: 'permission_denied'
}
}, {
status: 400
});
}
return Response.json(user, {
status: 200
});
}
// PUT /api/users/:id - Update user
PERMISSIONS.PUT = (_req: Request, meta: Record<string, any>): Promise<boolean> => {
const user_is_self = !!meta.user && !!meta.params && meta.user.id === meta.params.id;
const can_write_self = meta.user_permissions?.permissions.includes('self.write');
const can_write_others = meta.user_permissions?.permissions?.includes('users.write');
return can_write_others || (can_write_self && user_is_self);
};
export async function PUT(req: Request, meta: { params: Record<string, any> }): Promise<Response> {
const now = new Date().toISOString();
const id: string = meta.params.id ?? '';
const existing = await USER_STORE.get(id);
if (!existing) {
return Response.json({
error: {
message: 'User not found',
cause: 'unknown_user'
}
}, {
status: 404
});
}
try {
const body = await parse_body(req);
const updated = {
...existing,
username: body.username || existing.username,
timestamps: {
created: existing.timestamps.created,
updated: now
}
};
await USER_STORE.update(updated);
return Response.json(updated, {
status: 200
});
} catch (err) {
return Response.json({
error: {
message: (err as Error)?.message ?? 'Unknown error due to invalid user data.',
cause: (err as Error)?.cause ?? 'invalid_user_data'
}
}, {
status: 400
});
}
}
// DELETE /api/users/:id - Delete user
PERMISSIONS.DELETE = (_req: Request, meta: Record<string, any>): Promise<boolean> => {
const user_is_self = !!meta.user && !!meta.params && meta.user.id === meta.params.id;
const can_write_self = meta.user_permissions?.permissions.includes('self.write');
const can_write_others = meta.user_permissions?.permissions?.includes('users.write');
return can_write_others || (can_write_self && user_is_self);
};
export async function DELETE(_req: Request, meta: { params: Record<string, any> }): Promise<Response> {
const user_id: string = meta.params.id ?? '';
const user: USER | null = await USER_STORE.get(user_id);
if (!user) {
return Response.json({
error: {
message: 'Error deleting user.',
cause: 'unknown_user'
}
}, {
status: 404
});
}
const password_entry: PASSWORD_ENTRY | null = await PASSWORD_ENTRY_STORE.get(user_id);
if (password_entry) {
await PASSWORD_ENTRY_STORE.delete(password_entry);
}
const user_permissions: USER_PERMISSIONS | null = await USER_PERMISSIONS_STORE.get(user_id);
if (user_permissions) {
await USER_PERMISSIONS_STORE.delete(user_permissions);
}
const sessions = await SESSIONS.find({
user_id
});
for (const session of sessions) {
await SESSIONS.delete(session);
}
await USER_STORE.delete(user);
return Response.json({
deleted: true
}, {
status: 200
});
}

164
public/api/users/index.ts Normal file
View file

@ -0,0 +1,164 @@
import { PASSWORD_ENTRY, PASSWORD_ENTRY_STORE } from '../../../models/password_entry.ts';
import { USER, USER_STORE } from '../../../models/user.ts';
import { USER_PERMISSIONS, USER_PERMISSIONS_STORE } from '../../../models/user_permissions.ts';
import { generateSecret } from 'jsr:@stdext/crypto/utils';
import { hash } from 'jsr:@stdext/crypto/hash';
import lurid from 'jsr:@andyburke/lurid';
import { encodeBase64 } from 'jsr:@std/encoding';
import parse_body from '../../../utils/bodyparser.ts';
import { get_session, SESSION_RESULT } from '../auth/index.ts';
// TODO: figure out a better solution for doling out permissions
const DEFAULT_USER_PERMISSIONS: string[] = [
'self.read',
'self.write',
'checklists.read',
'checklists.write',
'checklists.events.read',
'checklists.events.write'
];
export const PERMISSIONS: Record<string, (req: Request, meta: Record<string, any>) => Promise<boolean>> = {};
// GET /api/users - get users
// query parameters:
// partial_id: the partial id subset you would like to match (remember, lurids are lexigraphically sorted)
PERMISSIONS.GET = (_req: Request, meta: Record<string, any>): Promise<boolean> => {
const can_read_others = meta.user_permissions?.permissions?.includes('users.read');
return can_read_others;
};
export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> {
const query: URLSearchParams = meta.query;
const partial_id: string | undefined = query.get('partial_id')?.toLowerCase().trim();
const has_partial_id = typeof partial_id === 'string' && partial_id.length >= 2;
if (!has_partial_id) {
return Response.json({
error: {
message: 'You must specify a `partial_id` query parameter.',
cause: 'missing_query_parameter'
}
}, {
status: 400
});
}
const limit = Math.min(parseInt(query.get('limit') ?? '10'), 100);
const users = await USER_STORE.find({
id: partial_id
}, {
limit
});
return Response.json(users, {
status: 200
});
}
// POST /api/users - Create user
export async function POST(req: Request, meta: Record<string, any>): Promise<Response> {
try {
const now = new Date().toISOString();
const body = await parse_body(req);
const username: string = body.username?.trim() ?? '';
const normalized_username = username.toLowerCase();
const existing_user_with_username = (await USER_STORE.find({
normalized_username
})).shift();
if (existing_user_with_username) {
return Response.json({
error: {
cause: 'username_conflict',
message: 'Username is already in use.'
}
}, {
status: 400
});
}
const password_hash: string = body.password_hash ?? (typeof body.password === 'string'
? encodeBase64(
await crypto.subtle.digest('SHA-256', new TextEncoder().encode(body.password))
)
: '');
if (password_hash.length < 32) {
return Response.json({
error: {
cause: 'invalid password hash',
message: 'Password must be hashed with a stronger algorithm.'
}
}, {
status: 400
});
}
const user: USER = {
id: lurid(),
username,
timestamps: {
created: now,
updated: now
}
};
await USER_STORE.create(user);
const salt = generateSecret();
const hashed_password_value = hash('bcrypt', `${password_hash}${salt}`);
const password_entry: PASSWORD_ENTRY = {
user_id: user.id,
hash: hashed_password_value,
salt,
timestamps: {
created: now,
updated: now
}
};
await PASSWORD_ENTRY_STORE.create(password_entry);
const user_permissions: USER_PERMISSIONS = {
user_id: user.id,
permissions: DEFAULT_USER_PERMISSIONS,
timestamps: {
created: now,
updated: now
}
};
await USER_PERMISSIONS_STORE.create(user_permissions);
const session_result: SESSION_RESULT = await get_session({
user,
expires: undefined
});
// TODO: verify this redirect is ok?
const headers = session_result.headers;
let status = 201;
if (typeof meta?.query?.redirect === 'string') {
const url = new URL(req.url);
headers.append('location', `${url.origin}${meta.query.redirect}`);
status = 302;
}
return Response.json({
user,
session: session_result.session
}, {
status,
headers
});
} catch (error) {
return Response.json({
error: {
message: (error as Error).message ?? 'Unknown Error!',
cause: (error as Error).cause ?? 'unknown'
}
}, { status: 500 });
}
}