Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions apps/api/scripts/dev-token.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@
# Prints a JWT for one of the seeded local users, signed with the local compose secret.
# Only works against the local stack (docker compose), never a real Supabase project.
#
# apps/api/scripts/dev-token.sh admin # Ada Admin, tech team
# apps/api/scripts/dev-token.sh super # Sam Super, president, superuser
# apps/api/scripts/dev-token.sh techexec # admin, tech team (also: admin)
# apps/api/scripts/dev-token.sh pres # admin, president
# apps/api/scripts/dev-token.sh superuser # admin, president, superuser (also: super)
# apps/api/scripts/dev-token.sh user # Una User, not an exec
#
# curl -H "Authorization: Bearer $(apps/api/scripts/dev-token.sh admin)" localhost:8080/api/me
set -euo pipefail

case "${1:-admin}" in
admin) sub=00000000-0000-4000-8000-000000000001 ;;
super) sub=00000000-0000-4000-8000-000000000002 ;;
user) sub=00000000-0000-4000-8000-000000000003 ;;
*) echo "usage: $0 admin|super|user" >&2; exit 1 ;;
case "${1:-techexec}" in
techexec|admin) sub=00000000-0000-4000-8000-000000000001 ;;
superuser|super) sub=00000000-0000-4000-8000-000000000002 ;;
user) sub=00000000-0000-4000-8000-000000000003 ;;
pres) sub=00000000-0000-4000-8000-000000000004 ;;
*) echo "usage: $0 techexec|pres|superuser|user" >&2; exit 1 ;;
esac

secret="local-dev-jwt-secret-not-for-production-0123456789"
Expand All @@ -24,7 +26,7 @@ b64url() { openssl base64 -A | tr '+/' '-_' | tr -d '='; }

header=$(printf '{"alg":"HS256","typ":"JWT"}' | b64url)
payload=$(printf '{"sub":"%s","iss":"%s","aud":"authenticated","role":"authenticated","email":"%s@example.test","iat":%d,"exp":%d}' \
"$sub" "$issuer" "$1" "$now" "$((now + 3600))" | b64url)
"$sub" "$issuer" "${1:-techexec}" "$now" "$((now + 3600))" | b64url)
signature=$(printf '%s.%s' "$header" "$payload" | openssl dgst -sha256 -hmac "$secret" -binary | b64url)

printf '%s.%s.%s\n' "$header" "$payload" "$signature"
5 changes: 5 additions & 0 deletions apps/web/src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { supabase } from "./supabase";
import { devToken } from "./devLogin";

/**
* Client for the DEVS API (apps/api). All data goes through it; Supabase is only used to log in.
Expand Down Expand Up @@ -29,6 +30,10 @@ type RequestOptions = {
};

async function authHeader(): Promise<Record<string, string>> {
if (import.meta.env.DEV) {
const local = devToken();
if (local) return { Authorization: `Bearer ${local}` };
}
const { data } = await supabase.auth.getSession();
const token = data.session?.access_token;
return token ? { Authorization: `Bearer ${token}` } : {};
Expand Down
19 changes: 12 additions & 7 deletions apps/web/src/lib/auth.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import { supabase } from "./supabase";
import { fetchMe } from "./api";
import { devSignOut, devToken } from "./devLogin";

/** True if someone is logged in and the API says they're an exec. Logs out anyone else. */
export async function checkAdminAuthorization(): Promise<boolean> {
try {
const {
data: { session },
error: sessionError,
} = await supabase.auth.getSession();
const devSession = import.meta.env.DEV && devToken() !== null;
if (!devSession) {
const {
data: { session },
error: sessionError,
} = await supabase.auth.getSession();

if (sessionError || !session) {
return false;
if (sessionError || !session) {
return false;
}
}

const me = await fetchMe();
if (me.role !== "admin") {
await supabase.auth.signOut();
await handleLogout();
return false;
}

Expand All @@ -28,6 +32,7 @@ export async function checkAdminAuthorization(): Promise<boolean> {

export async function handleLogout(): Promise<void> {
try {
if (import.meta.env.DEV) devSignOut();
await supabase.auth.signOut();
} catch (err) {
console.error("Logout failed:", err);
Expand Down
81 changes: 81 additions & 0 deletions apps/web/src/lib/devLogin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* Logins for the seeded local accounts (db/seed/dev_seed.sql), for `pnpm dev` only.
*
* No Supabase Auth runs locally, so this signs a login token with the local compose secret,
* which only the local Docker API trusts. Every caller checks `import.meta.env.DEV` first, so
* none of this is in a production build.
*/
const LOCAL_SECRET = "local-dev-jwt-secret-not-for-production-0123456789";
const LOCAL_ISSUER = "http://localhost:54321/auth/v1";
const PASSWORD = "development";
const STORAGE_KEY = "devToken";

const ACCOUNTS: Record<string, string> = {
"techexec@example.test": "00000000-0000-4000-8000-000000000001",
"superuser@example.test": "00000000-0000-4000-8000-000000000002",
"pres@example.test": "00000000-0000-4000-8000-000000000004",
};

const encoder = new TextEncoder();

function base64url(bytes: Uint8Array): string {
return btoa(String.fromCharCode(...bytes))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
}

async function signToken(sub: string, email: string): Promise<string> {
const now = Math.floor(Date.now() / 1000);
const header = base64url(encoder.encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));
const payload = base64url(
encoder.encode(
JSON.stringify({
sub,
email,
iss: LOCAL_ISSUER,
aud: "authenticated",
role: "authenticated",
iat: now,
exp: now + 8 * 60 * 60,
}),
),
);
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(LOCAL_SECRET),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
);
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(`${header}.${payload}`));
return `${header}.${payload}.${base64url(new Uint8Array(signature))}`;
}

/** Logs in as a seeded account. False if the email isn't one of them or the password is wrong. */
export async function devSignIn(email: string, password: string): Promise<boolean> {
const normalised = email.trim().toLowerCase();
const sub = ACCOUNTS[normalised];
if (!sub || password !== PASSWORD) return false;
localStorage.setItem(STORAGE_KEY, await signToken(sub, normalised));
return true;
}

/** The current dev login token, or null if there's none or it has expired. */
export function devToken(): string | null {
const token = localStorage.getItem(STORAGE_KEY);
if (!token) return null;
try {
const payload = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
const { exp } = JSON.parse(atob(payload)) as { exp: number };
if (exp * 1000 > Date.now()) return token;
} catch {
// Not a token we wrote: drop it.
}
localStorage.removeItem(STORAGE_KEY);
return null;
}

export function devSignOut(): void {
localStorage.removeItem(STORAGE_KEY);
}
20 changes: 13 additions & 7 deletions apps/web/src/lib/login.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { supabase } from "./supabase";
import { fetchMe } from "./api";
import { devSignIn } from "./devLogin";
import { handleLogout } from "./auth";

type LoginParams = {
email: string;
Expand All @@ -20,19 +22,23 @@ export async function handleLoginSubmit(
setLoading(true);

try {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
// Under pnpm dev, the seeded local accounts log in without Supabase (see devLogin.ts).
const devAccount = import.meta.env.DEV && (await devSignIn(email, password));
if (!devAccount) {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});

if (error || !data.user) {
throw new Error("Invalid email or password");
if (error || !data.user) {
throw new Error("Invalid email or password");
}
}

// Exec access is decided by the API from the database, not by anything the browser can set.
const me = await fetchMe();
if (me.role !== "admin") {
await supabase.auth.signOut();
await handleLogout();
throw new Error("You do not have access");
}

Expand Down
17 changes: 10 additions & 7 deletions db/seed/dev_seed.sql
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
-- Fake data for local Docker and the API's tests. Never run against a real project:
-- every person here is made up, and the ids are fixed so tests can mint tokens for them.

-- Local logins (pnpm dev only, password "development"): techexec, pres and superuser @example.test.
insert into auth.users (id, email, aud, role) values
('00000000-0000-4000-8000-000000000001', 'admin@example.test', 'authenticated', 'authenticated'),
('00000000-0000-4000-8000-000000000002', 'super@example.test', 'authenticated', 'authenticated'),
('00000000-0000-4000-8000-000000000003', 'user@example.test', 'authenticated', 'authenticated')
on conflict (id) do nothing;
('00000000-0000-4000-8000-000000000001', 'techexec@example.test', 'authenticated', 'authenticated'),
('00000000-0000-4000-8000-000000000002', 'superuser@example.test', 'authenticated', 'authenticated'),
('00000000-0000-4000-8000-000000000003', 'user@example.test', 'authenticated', 'authenticated'),
('00000000-0000-4000-8000-000000000004', 'pres@example.test', 'authenticated', 'authenticated')
on conflict (id) do update set email = excluded.email;

insert into public.profiles (id, role, username, team, is_superuser) values
('00000000-0000-4000-8000-000000000001', 'admin', 'Ada Admin', 'tech', false),
('00000000-0000-4000-8000-000000000002', 'admin', 'Sam Super', 'president', true),
('00000000-0000-4000-8000-000000000003', 'user', 'Una User', null, false)
('00000000-0000-4000-8000-000000000001', 'admin', 'techexec', 'tech', false),
('00000000-0000-4000-8000-000000000002', 'admin', 'superuser', 'president', true),
('00000000-0000-4000-8000-000000000003', 'user', 'Una User', null, false),
('00000000-0000-4000-8000-000000000004', 'admin', 'pres', 'president', false)
-- on_auth_user_created has already made a plain 'user' profile for each, as on a real project.
on conflict (id) do update set
role = excluded.role, username = excluded.username, team = excluded.team, is_superuser = excluded.is_superuser;
Expand Down
Loading