feature: signup and login work

This commit is contained in:
Andy Burke 2025-06-25 20:51:29 -07:00
parent a4a750b35c
commit 3d42591ee5
18 changed files with 956 additions and 65 deletions

View file

@ -9,15 +9,15 @@ import { TOTP_ENTRIES } 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';
import { SESSION_ID_TOKEN, SESSION_SECRET_TOKEN } from '../../../utils/prechecks.ts';
const DEFAULT_SESSION_TIME: number = 60 * 60; // 1 Hour
const DEFAULT_SESSION_TIME: number = 60 * 60 * 1_000; // 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'
@ -27,11 +27,11 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
: undefined);
const totp: string | undefined = body.totp;
if ((!email.length && !username.length) || (email.length && username.length)) {
if (!username.length) {
return Response.json({
error: {
message: 'You must specify either an email or username to log in.',
cause: 'email_or_username_required'
message: 'You must specify a username to log in.',
cause: 'username_required'
}
}, {
status: 400
@ -51,20 +51,14 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
}
let user: USER | undefined = undefined;
if (email.length) {
user = (await USERS.find({
email
})).shift();
} else if (username.length) {
user = (await USERS.find({
username
})).shift();
}
user = (await USERS.find({
username
})).shift();
if (!user) {
return Response.json({
error: {
message: 'Could not locate an account with this email or username.',
message: `Could not locate an account with username: ${username}`,
cause: 'missing_account'
}
}, {
@ -105,7 +99,7 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
}, {
status: 202,
headers: {
'Set-Cookie': `checklist_observer_totp_user_id=${user.id}; Path=/; Max-Age=300`
'Set-Cookie': `totp_user_id=${user.id}; Path=/; Max-Age=300`
}
});
}
@ -123,7 +117,7 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
}
}
const session_result: SESSION_RESULT = await get_session({
const session_result: SESSION_RESULT = await create_new_session({
user,
expires: body.session?.expires
});
@ -164,7 +158,7 @@ export type SESSION_INFO = {
expires: string | undefined;
};
export async function get_session(session_settings: SESSION_INFO): Promise<SESSION_RESULT> {
export async function create_new_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();
@ -183,7 +177,13 @@ export async function get_session(session_settings: SESSION_INFO): Promise<SESSI
await SESSIONS.create(session);
const headers = new Headers();
headers.append('Set-Cookie', `checklist_observer_session_id=${session.id}; Path=/; Expires=${expires}`);
headers.append('Set-Cookie', `${SESSION_ID_TOKEN}=${session.id}; Path=/; Expires=${expires}`);
headers.append(`x-${SESSION_ID_TOKEN}`, session.id);
// TODO: this wasn't really intended to be persisted in a cookie, but we are using it to
// generate the TOTP for the call to /api/users/me
headers.append('Set-Cookie', `${SESSION_SECRET_TOKEN}=${session.secret}; Path=/; Expires=${expires}`);
return {
session,

View file

@ -1,19 +1,24 @@
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../utils/prechecks.ts';
import { PASSWORD_ENTRIES, PASSWORD_ENTRY } from '../../../../models/password_entry.ts';
import { SESSIONS } from '../../../../models/session.ts';
import { USER, USERS } from '../../../../models/user.ts';
import { PERMISSIONS_STORE, USER_PERMISSIONS } from '../../../../models/user_permissions.ts';
import parse_body from '../../../../utils/bodyparser.ts';
import { CANNED_RESPONSES } from '../../../../utils/canned_responses.ts';
export const PERMISSIONS: Record<string, (req: Request, meta: Record<string, any>) => Promise<boolean>> = {};
export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/users/:id - Get single user
PERMISSIONS.GET = (_req: Request, meta: Record<string, any>): Promise<boolean> => {
PRECHECKS.GET = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
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);
};
const has_permission = can_read_others || (can_read_self && user_is_self);
if (!has_permission) {
return CANNED_RESPONSES.permission_denied();
}
}];
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 USERS.get(user_id) : null; // lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
@ -29,34 +34,22 @@ export async function GET(_req: Request, meta: Record<string, any>): Promise<Res
});
}
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> => {
PRECHECKS.PUT = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
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);
};
const has_permission = can_write_others || (can_write_self && user_is_self);
if (!has_permission) {
return CANNED_RESPONSES.permission_denied();
}
}];
export async function PUT(req: Request, meta: { params: Record<string, any> }): Promise<Response> {
const now = new Date().toISOString();
const id: string = meta.params.id ?? '';
@ -101,13 +94,16 @@ export async function PUT(req: Request, meta: { params: Record<string, any> }):
}
// DELETE /api/users/:id - Delete user
PERMISSIONS.DELETE = (_req: Request, meta: Record<string, any>): Promise<boolean> => {
PRECHECKS.DELETE = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
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);
};
const has_permission = can_write_others || (can_write_self && user_is_self);
if (!has_permission) {
return CANNED_RESPONSES.permission_denied();
}
}];
export async function DELETE(_req: Request, meta: { params: Record<string, any> }): Promise<Response> {
const user_id: string = meta.params.id ?? '';

View file

@ -6,28 +6,27 @@ 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';
import { create_new_session, SESSION_RESULT } from '../auth/index.ts';
import { PRECHECKS } from './me/index.ts';
import { get_session, get_user, require_user } from '../../../utils/prechecks.ts';
import { CANNED_RESPONSES } from '../../../utils/canned_responses.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'
'self.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> => {
PRECHECKS.GET = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const can_read_others = meta.user_permissions?.permissions?.includes('users.read');
return can_read_others;
};
if (!can_read_others) {
return CANNED_RESPONSES.permission_denied();
}
}];
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();
@ -132,7 +131,7 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
await PERMISSIONS_STORE.create(user_permissions);
const session_result: SESSION_RESULT = await get_session({
const session_result: SESSION_RESULT = await create_new_session({
user,
expires: undefined
});

View file

@ -0,0 +1,7 @@
# /api/users/me
Get the current user.
## GET /api/users/me
Return the currently logged in user or an error.

View file

@ -0,0 +1,25 @@
import { CANNED_RESPONSES } from '../../../../utils/canned_responses.ts';
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../utils/prechecks.ts';
export const PERMISSIONS: Record<string, (req: Request, meta: Record<string, any>) => Promise<boolean>> = {};
export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/users/me - Get the current user
PRECHECKS.GET = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const can_read_self = meta.user_permissions?.permissions.includes('self.read');
const has_permission = can_read_self;
console.dir({
meta,
can_read_self,
has_permission
});
if (!has_permission) {
return CANNED_RESPONSES.permission_denied();
}
}];
export function GET(_req: Request, meta: Record<string, any>): Response {
return Response.json(meta.user, {
status: 200
});
}

View file

@ -468,6 +468,54 @@
top: 8px;
}
</style>
<script>
/* https://github.com/turistu/totp-in-javascript/blob/main/totp.js */
async function otp_totp(key, secs = 30, digits = 6) {
return otp_hotp(otp_unbase32(key), otp_pack64bu(Date.now() / 1000 / secs), digits);
}
async function otp_hotp(key, counter, digits) {
let y = self.crypto.subtle;
if (!y) throw Error("no self.crypto.subtle object available");
let k = await y.importKey("raw", key, { name: "HMAC", hash: "SHA-1" }, false, [
"sign",
]);
return otp_hotp_truncate(await y.sign("HMAC", k, counter), digits);
}
function otp_hotp_truncate(buf, digits) {
let a = new Uint8Array(buf),
i = a[19] & 0xf;
return otp_fmt(
10,
digits,
(((a[i] & 0x7f) << 24) | (a[i + 1] << 16) | (a[i + 2] << 8) | a[i + 3]) %
10 ** digits,
);
}
function otp_fmt(base, width, num) {
return num.toString(base).padStart(width, "0");
}
function otp_unbase32(s) {
let t = (s.toLowerCase().match(/\S/g) || [])
.map((c) => {
let i = "abcdefghijklmnopqrstuvwxyz234567".indexOf(c);
if (i < 0) throw Error(`bad char '${c}' in key`);
return otp_fmt(2, 5, i);
})
.join("");
if (t.length < 8) throw Error("key too short");
return new Uint8Array(t.match(/.{8}/g).map((d) => parseInt(d, 2)));
}
function otp_pack64bu(v) {
let b = new ArrayBuffer(8),
d = new DataView(b);
d.setUint32(0, v / 2 ** 32);
d.setUint32(4, v);
return b;
}
</script>
</head>
<body>
<div id="signup-login-wall">
@ -578,6 +626,13 @@
action="/api/auth"
onreply="(user)=>{ document.body.dataset.user = user; }"
>
<script>
const form = document.currentScript.closest("form");
form.on_response = (response) => {
// TODO: we should hold the session secret only in memory, not the cookie?
document.body.dataset.user = response.user;
};
</script>
<div>
<input
id="login-username"
@ -763,6 +818,50 @@
</body>
<script>
document.addEventListener("DOMContentLoaded", () => {
/* check if we are logged in */
(async () => {
try {
const session_id = (document.cookie.match(
/^(?:.*;)?\s*session_id\s*=\s*([^;]+)(?:.*)?$/,
) || [, null])[1];
// TODO: this wasn't really intended to be persisted in a cookie
const session_secret = (document.cookie.match(
/^(?:.*;)?\s*session_secret\s*=\s*([^;]+)(?:.*)?$/,
) || [, null])[1];
if (session_id && session_secret) {
const session_response = await fetch("/api/users/me", {
method: "GET",
headers: {
Accept: "application/json",
"x-session_id": session_id,
"x-totp": await otp_totp(session_secret),
},
});
if (!session_response.ok) {
const error_body = await session_response.json();
const error = error_body?.error;
console.dir({
error_body,
error,
});
return;
}
const user = await session_response.json();
document.body.dataset.user = user;
}
} catch (error) {
console.dir({
error,
});
}
})();
/* make all forms semi-smart */
const forms = document.querySelectorAll("form");
for (const form of forms) {
const script = form.querySelector("script");