Assignees
@@ -553,7 +555,7 @@ export function TaskDialog({
)}
)}
- {!canFullyEdit && (
+ {!canEditAssignees && (
Assignees
@@ -573,7 +575,7 @@ export function TaskDialog({
className="input mt-1"
value={pointOfContactUid}
onChange={(e) => setPointOfContactUid(e.target.value)}
- disabled={!canFullyEdit}
+ disabled={!canEditTask}
>
{visibleUsers.map((user) => (
@@ -629,7 +631,7 @@ export function TaskDialog({
className="mt-0.5"
checked={prerequisiteTaskIds.includes(candidate.id)}
onChange={() => togglePrerequisite(candidate.id)}
- disabled={!canFullyEdit}
+ disabled={!canEditTask}
/>
{candidate.title}
@@ -655,12 +657,12 @@ export function TaskDialog({
The first link is shown on the task card. Put the most useful CAD or reference link first.
{links.map((link, index) => (
))}
- {canFullyEdit && }
+ {canEditTask && }
diff --git a/src/lib/auth-api.ts b/src/lib/auth-api.ts
new file mode 100644
index 0000000..02fff5f
--- /dev/null
+++ b/src/lib/auth-api.ts
@@ -0,0 +1,49 @@
+import { auth } from "@/lib/firebase";
+
+const baseUrl = () => process.env.NEXT_PUBLIC_OPS_API_URL?.replace(/\/$/, "");
+
+async function request
(path: string, init?: RequestInit, authenticated = false): Promise {
+ const url = baseUrl();
+ if (!url) throw new Error("The Ops authentication service is unavailable.");
+ const token = authenticated ? await auth.currentUser?.getIdToken() : null;
+ if (authenticated && !token) throw new Error("Sign in before approving another device.");
+ const response = await fetch(`${url}${path}`, {
+ ...init,
+ cache: "no-store",
+ headers: {
+ "Content-Type": "application/json",
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
+ ...init?.headers,
+ },
+ });
+ const body = await response.json().catch(() => null) as (T & { error?: string }) | null;
+ if (!response.ok) throw new Error(body?.error ?? "The authentication request failed.");
+ return body as T;
+}
+
+export interface DeviceLinkStart {
+ id: string;
+ pollToken: string;
+ approvalUrl: string;
+ expiresAt: number;
+}
+
+export function requestPasswordReset(email: string) {
+ return request<{ sent: true }>("/auth/password-reset", { method: "POST", body: JSON.stringify({ email }) });
+}
+
+export function beginDeviceLink() {
+ return request("/auth/device-link", { method: "POST" });
+}
+
+export function pollDeviceLink(id: string, token: string) {
+ const query = new URLSearchParams({ id, token });
+ return request<{ status: "pending" } | { status: "approved"; customToken: string }>(`/auth/device-link?${query}`);
+}
+
+export function respondToDeviceLink(id: string, token: string, approve: boolean) {
+ return request<{ status: "approved" | "denied" }>("/auth/device-link", {
+ method: approve ? "PATCH" : "DELETE",
+ body: JSON.stringify({ id, token }),
+ }, true);
+}
diff --git a/workers/api/src/auth.ts b/workers/api/src/auth.ts
new file mode 100644
index 0000000..fc976c1
--- /dev/null
+++ b/workers/api/src/auth.ts
@@ -0,0 +1,177 @@
+///
+
+import { createFirebaseCustomToken, verifyFirebaseToken } from "./firebase-auth";
+
+export interface AuthEnv {
+ DB: D1Database;
+ FIREBASE_PROJECT_ID: string;
+ FIREBASE_WEB_API_KEY?: string;
+ FIREBASE_SERVICE_ACCOUNT_EMAIL?: string;
+ FIREBASE_SERVICE_ACCOUNT_PRIVATE_KEY?: string;
+}
+
+const linkLifetimeMs = 5 * 60 * 1000;
+const idPattern = /^[0-9a-f-]{36}$/i;
+const tokenPattern = /^[A-Za-z0-9_-]{40,100}$/;
+
+export function isAuthRoute(path: string) {
+ return path === "/auth/password-reset" || path === "/auth/device-link";
+}
+
+export async function handleAuth(request: Request, env: AuthEnv, cors: Headers) {
+ try {
+ const path = new URL(request.url).pathname;
+ if (path === "/auth/password-reset") return passwordReset(request, env, cors);
+ return deviceLink(request, env, cors);
+ } catch (error) {
+ console.error("Auth request failed", error);
+ const message = error instanceof Error ? error.message : "Authentication request failed";
+ const status = message === "Unauthorized" ? 401 : message === "Forbidden" ? 403 : message.includes("not configured") ? 503 : message.startsWith("Invalid") ? 400 : message.includes("expired") || message.includes("used") || message.includes("denied") || message.includes("already answered") ? 410 : 500;
+ return json({ error: status === 500 ? "Authentication request failed" : message }, status, cors);
+ }
+}
+
+async function passwordReset(request: Request, env: AuthEnv, cors: Headers) {
+ if (request.method !== "POST") return methodNotAllowed(cors, "POST, OPTIONS");
+ const clientIp = request.headers.get("CF-Connecting-IP") ?? "unknown";
+ const limit = await consumeRateLimit(env.DB, `password-reset:${clientIp}`, 5 * 60_000, 3);
+ if (!limit.allowed) {
+ const headers = new Headers(cors);
+ headers.set("Retry-After", String(Math.ceil(limit.retryAfterMs / 1000)));
+ return json({ error: "Too many reset requests. Wait a few minutes and try again." }, 429, headers);
+ }
+ const body = await request.json<{ email?: unknown }>().catch(() => ({} as { email?: unknown }));
+ const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
+ if (!email || email.length > 320 || !email.includes("@")) return json({ error: "Enter a valid email address." }, 400, cors);
+ if (!env.FIREBASE_WEB_API_KEY) throw new Error("Firebase password reset is not configured");
+ const response = await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=${encodeURIComponent(env.FIREBASE_WEB_API_KEY)}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ requestType: "PASSWORD_RESET", email }),
+ });
+ if (!response.ok) {
+ const providerError = await response.text();
+ console.error("Firebase password reset failed", response.status, providerError);
+ // Preserve account privacy while still telling the UI that delivery did not start.
+ if (!providerError.includes("EMAIL_NOT_FOUND")) throw new Error("Firebase password reset failed");
+ }
+ return json({ sent: true }, 200, cors);
+}
+
+async function deviceLink(request: Request, env: AuthEnv, cors: Headers) {
+ if (request.method === "POST") {
+ if (!env.FIREBASE_SERVICE_ACCOUNT_EMAIL || !env.FIREBASE_SERVICE_ACCOUNT_PRIVATE_KEY) throw new Error("QR sign-in is not configured yet");
+ const clientIp = request.headers.get("CF-Connecting-IP") ?? "unknown";
+ const limit = await consumeRateLimit(env.DB, `device-link:${clientIp}`, 60_000, 10);
+ if (!limit.allowed) return json({ error: "Too many sign-in requests. Try again shortly." }, 429, cors);
+ const origin = request.headers.get("Origin");
+ if (!origin) throw new Error("Invalid sign-in origin");
+ const id = crypto.randomUUID();
+ const approvalToken = randomToken();
+ const pollToken = randomToken();
+ const now = Date.now();
+ await env.DB.batch([
+ env.DB.prepare("DELETE FROM device_sign_in_requests WHERE expires_at < ? OR consumed_at IS NOT NULL").bind(now - 24 * 60 * 60 * 1000),
+ env.DB.prepare(`INSERT INTO device_sign_in_requests
+ (id, approval_token_hash, poll_token_hash, expires_at, created_at)
+ VALUES (?, ?, ?, ?, ?)`).bind(id, await hashToken(approvalToken), await hashToken(pollToken), now + linkLifetimeMs, now),
+ ]);
+ const approvalUrl = new URL("/device-link", origin);
+ approvalUrl.searchParams.set("id", id);
+ approvalUrl.searchParams.set("token", approvalToken);
+ return json({ id, pollToken, approvalUrl: approvalUrl.toString(), expiresAt: now + linkLifetimeMs }, 201, cors);
+ }
+
+ if (request.method === "GET") {
+ const url = new URL(request.url);
+ const id = url.searchParams.get("id") ?? "";
+ const token = url.searchParams.get("token") ?? "";
+ validateLinkCredentials(id, token);
+ const now = Date.now();
+ const row = await env.DB.prepare(`SELECT approved_uid AS approvedUid, expires_at AS expiresAt,
+ denied_at AS deniedAt, consumed_at AS consumedAt FROM device_sign_in_requests
+ WHERE id = ? AND poll_token_hash = ?`).bind(id, await hashToken(token)).first<{
+ approvedUid: string | null; expiresAt: number; deniedAt: number | null; consumedAt: number | null;
+ }>();
+ if (!row) throw new Error("Invalid device sign-in request");
+ if (row.expiresAt <= now) throw new Error("This QR code has expired");
+ if (row.deniedAt) throw new Error("Sign-in was denied");
+ if (row.consumedAt) throw new Error("This QR code has already been used");
+ if (!row.approvedUid) return json({ status: "pending" }, 200, cors);
+ if (!env.FIREBASE_SERVICE_ACCOUNT_EMAIL || !env.FIREBASE_SERVICE_ACCOUNT_PRIVATE_KEY) throw new Error("QR sign-in is not configured");
+ const profile = await env.DB.prepare("SELECT uid FROM users WHERE uid = ?").bind(row.approvedUid).first();
+ if (!profile) throw new Error("Forbidden");
+ const customToken = await createFirebaseCustomToken(row.approvedUid, env.FIREBASE_SERVICE_ACCOUNT_EMAIL, env.FIREBASE_SERVICE_ACCOUNT_PRIVATE_KEY);
+ const claimed = await env.DB.prepare("UPDATE device_sign_in_requests SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL").bind(now, id).run();
+ if (claimed.meta.changes !== 1) throw new Error("This QR code has already been used");
+ return json({ status: "approved", customToken }, 200, cors);
+ }
+
+ if (request.method === "PATCH" || request.method === "DELETE") {
+ const uid = await verifyFirebaseToken(bearerToken(request), env.FIREBASE_PROJECT_ID);
+ const profile = await env.DB.prepare("SELECT uid FROM users WHERE uid = ?").bind(uid).first();
+ if (!profile) throw new Error("Forbidden");
+ const body = await request.json<{ id?: unknown; token?: unknown }>().catch(() => ({} as { id?: unknown; token?: unknown }));
+ const id = typeof body.id === "string" ? body.id : "";
+ const token = typeof body.token === "string" ? body.token : "";
+ validateLinkCredentials(id, token);
+ const now = Date.now();
+ const result = request.method === "PATCH"
+ ? await env.DB.prepare(`UPDATE device_sign_in_requests SET approved_uid = ?, approved_at = ?
+ WHERE id = ? AND approval_token_hash = ? AND approved_uid IS NULL AND denied_at IS NULL
+ AND consumed_at IS NULL AND expires_at > ?`).bind(uid, now, id, await hashToken(token), now).run()
+ : await env.DB.prepare(`UPDATE device_sign_in_requests SET denied_at = ?
+ WHERE id = ? AND approval_token_hash = ? AND approved_uid IS NULL AND denied_at IS NULL
+ AND consumed_at IS NULL AND expires_at > ?`).bind(now, id, await hashToken(token), now).run();
+ if (result.meta.changes !== 1) throw new Error("This QR code is invalid, expired, or already answered");
+ return json({ status: request.method === "PATCH" ? "approved" : "denied" }, 200, cors);
+ }
+
+ return methodNotAllowed(cors, "GET, POST, PATCH, DELETE, OPTIONS");
+}
+
+async function consumeRateLimit(db: D1Database, key: string, windowMs: number, maximum: number) {
+ const now = Date.now();
+ const row = await db.prepare("SELECT window_started_at AS windowStartedAt, attempts FROM auth_rate_limits WHERE key = ?").bind(key).first<{ windowStartedAt: number; attempts: number }>();
+ if (!row || now - row.windowStartedAt >= windowMs) {
+ await db.prepare(`INSERT INTO auth_rate_limits (key, window_started_at, attempts) VALUES (?, ?, 1)
+ ON CONFLICT(key) DO UPDATE SET window_started_at = excluded.window_started_at, attempts = 1`).bind(key, now).run();
+ return { allowed: true, retryAfterMs: 0 };
+ }
+ if (row.attempts >= maximum) return { allowed: false, retryAfterMs: Math.max(1000, windowMs - (now - row.windowStartedAt)) };
+ await db.prepare("UPDATE auth_rate_limits SET attempts = attempts + 1 WHERE key = ?").bind(key).run();
+ return { allowed: true, retryAfterMs: 0 };
+}
+
+function randomToken() {
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
+ return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
+}
+
+async function hashToken(token: string) {
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
+}
+
+function validateLinkCredentials(id: string, token: string) {
+ if (!idPattern.test(id) || !tokenPattern.test(token)) throw new Error("Invalid device sign-in request");
+}
+
+function bearerToken(request: Request) {
+ const authorization = request.headers.get("Authorization");
+ if (!authorization?.startsWith("Bearer ")) throw new Error("Unauthorized");
+ return authorization.slice("Bearer ".length);
+}
+
+function json(body: unknown, status: number, headers: Headers) {
+ const next = new Headers(headers);
+ next.set("Content-Type", "application/json; charset=utf-8");
+ next.set("Cache-Control", "no-store");
+ return new Response(JSON.stringify(body), { status, headers: next });
+}
+
+function methodNotAllowed(headers: Headers, allow: string) {
+ const next = new Headers(headers);
+ next.set("Allow", allow);
+ return new Response("Method not allowed", { status: 405, headers: next });
+}
diff --git a/workers/api/src/core.ts b/workers/api/src/core.ts
index 881d469..06be525 100644
--- a/workers/api/src/core.ts
+++ b/workers/api/src/core.ts
@@ -102,19 +102,19 @@ function allowedTaskPatch(task: Task, changes: Record, actor: U
const keys = Object.keys(changes);
const only = (allowed: string[]) => keys.every((key) => allowed.includes(key));
if (only(["status", "order", "updatedAt", "history"])) return true;
- const contentKeys = new Set(["title", "description"]);
+ const contentKeys = new Set(["title", "description", "priority", "dueDate", "pointOfContactUid", "blockedReason", "blockedDetails", "prerequisiteTaskIds", "links"]);
const certificationKeys = new Set(["requiredCertificationIds", "requireAllCertifications"]);
- if (only(["title", "description", "requiredCertificationIds", "requireAllCertifications", "updatedAt"])) {
+ if (only([...contentKeys, ...certificationKeys, "updatedAt"])) {
const changesContent = keys.some((key) => contentKeys.has(key));
const changesCertifications = keys.some((key) => certificationKeys.has(key));
- return (!changesContent || canEditTaskContent(task, actor)) && (!changesCertifications || actor.role === "student");
+ return (!changesContent || canEditTaskContent(task, actor)) && (!changesCertifications || canEditTaskContent(task, actor));
}
if (only(["comments", "updatedAt"])) {
const next = Array.isArray(changes.comments) ? changes.comments as Array> : [];
const added = next.at(-1);
return next.length === task.comments.length + 1 && JSON.stringify(next.slice(0, -1)) === JSON.stringify(task.comments) && added?.authorUid === actor.uid && typeof added.body === "string" && added.body.length > 0 && added.body.length <= 2000;
}
- if (only(["attachments", "updatedAt"]) && task.assigneeUids.includes(actor.uid)) {
+ if (only(["attachments", "updatedAt"]) && canEditTaskContent(task, actor)) {
const next = Array.isArray(changes.attachments) ? changes.attachments as Array> : [];
const beforeIds = new Set(task.attachments.map((item) => item.id)); const afterIds = new Set(next.map((item) => item.id));
const delta = [...new Set([...beforeIds, ...afterIds])].filter((id) => beforeIds.has(id) !== afterIds.has(id));
@@ -124,6 +124,7 @@ function allowedTaskPatch(task: Task, changes: Record, actor: U
const next = Array.isArray(changes.assigneeUids) ? changes.assigneeUids.filter((value): value is string => typeof value === "string") : [];
const before = new Set(task.assigneeUids); const after = new Set(next);
const changed = [...new Set([...before, ...after])].filter((uid) => before.has(uid) !== after.has(uid));
+ if (canEditTaskContent(task, actor)) return true;
if (changed.length !== 1 || changed[0] !== actor.uid) return false;
if (!before.has(actor.uid) && after.has(actor.uid)) {
const required = Array.isArray(task.requiredCertificationIds) ? task.requiredCertificationIds.filter((id): id is string => typeof id === "string") : [];
diff --git a/workers/api/src/firebase-auth.ts b/workers/api/src/firebase-auth.ts
new file mode 100644
index 0000000..4c3c219
--- /dev/null
+++ b/workers/api/src/firebase-auth.ts
@@ -0,0 +1,28 @@
+import { createRemoteJWKSet, importPKCS8, jwtVerify, SignJWT } from "jose";
+
+const firebaseKeys = createRemoteJWKSet(
+ new URL("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com"),
+);
+
+export async function verifyFirebaseToken(token: string, projectId: string) {
+ const { payload } = await jwtVerify(token, firebaseKeys, {
+ algorithms: ["RS256"],
+ audience: projectId,
+ issuer: `https://securetoken.google.com/${projectId}`,
+ });
+ if (!payload.sub) throw new Error("Unauthorized");
+ return payload.sub;
+}
+
+export async function createFirebaseCustomToken(uid: string, serviceAccountEmail: string, privateKeyPem: string) {
+ const now = Math.floor(Date.now() / 1000);
+ const privateKey = await importPKCS8(privateKeyPem.replaceAll("\\n", "\n"), "RS256");
+ return new SignJWT({ uid })
+ .setProtectedHeader({ alg: "RS256", typ: "JWT" })
+ .setIssuer(serviceAccountEmail)
+ .setSubject(serviceAccountEmail)
+ .setAudience("https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit")
+ .setIssuedAt(now)
+ .setExpirationTime(now + 60 * 60)
+ .sign(privateKey);
+}
diff --git a/workers/api/src/index.ts b/workers/api/src/index.ts
index f4a6dff..3c1eaaa 100644
--- a/workers/api/src/index.ts
+++ b/workers/api/src/index.ts
@@ -1,11 +1,12 @@
///
-import { createRemoteJWKSet, jwtVerify } from "jose";
import { handleOperations, isOperationsRoute } from "./operations";
import { handleCore, isCoreRoute } from "./core";
import { handleNotifications, isNotificationRoute, sendDailyEmailDigests } from "./notifications";
+import { handleAuth, isAuthRoute, type AuthEnv } from "./auth";
+import { verifyFirebaseToken } from "./firebase-auth";
-interface Env {
+interface Env extends AuthEnv {
ATTACHMENTS: R2Bucket;
DB: D1Database;
FIREBASE_PROJECT_ID: string;
@@ -17,10 +18,6 @@ interface Env {
RESEND_API_KEY?: string;
RESEND_FROM?: string;
}
-
-const firebaseKeys = createRemoteJWKSet(
- new URL("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com"),
-);
const attachmentRoute = /^\/attachments\/([^/]+)\/([^/]+)\/([^/]+)$/;
const certificationRoute = /^\/certifications(?:\/([^/]+))?$/;
const maxAttachmentSize = 20 * 1024 * 1024;
@@ -42,6 +39,10 @@ export default {
return json({ ok: true }, 200, cors);
}
+ if (isAuthRoute(url.pathname)) {
+ return handleAuth(request, env, cors);
+ }
+
if (isCoreRoute(url.pathname)) {
try {
const token = bearerToken(request);
@@ -218,16 +219,6 @@ function certificationUpsert(db: D1Database, certification: CertificationRow) {
.bind(certification.id, certification.name, certification.description, certification.subteam, new Date().toISOString());
}
-async function verifyFirebaseToken(token: string, projectId: string) {
- const { payload } = await jwtVerify(token, firebaseKeys, {
- algorithms: ["RS256"],
- audience: projectId,
- issuer: `https://securetoken.google.com/${projectId}`,
- });
- if (!payload.sub) throw new Error("Unauthorized");
- return payload.sub;
-}
-
async function requireCoach(uid: string, env: Env) {
const profile = await fetchD1Profile(env.DB, uid);
if (profile?.role !== "coach") throw new Error("Forbidden");
diff --git a/workers/api/src/notifications.ts b/workers/api/src/notifications.ts
index 53a6a8d..7967dce 100644
--- a/workers/api/src/notifications.ts
+++ b/workers/api/src/notifications.ts
@@ -1,6 +1,6 @@
///
-import webpush from "web-push";
+import { sendNotification, setVapidDetails } from "web-push";
export interface NotificationEnv {
DB: D1Database;
@@ -123,13 +123,13 @@ export async function notifyUsers(env: NotificationEnv, recipientUids: string[],
VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`).bind(crypto.randomUUID(), uid, notification.type, notification.title, notification.body, notification.taskId ?? null, createdAt)));
if (!env.VAPID_PUBLIC_KEY || !env.VAPID_PRIVATE_KEY || !env.VAPID_SUBJECT) return;
- webpush.setVapidDetails(env.VAPID_SUBJECT, env.VAPID_PUBLIC_KEY, env.VAPID_PRIVATE_KEY);
+ setVapidDetails(env.VAPID_SUBJECT, env.VAPID_PUBLIC_KEY, env.VAPID_PRIVATE_KEY);
const placeholders = uniqueUids.map(() => "?").join(",");
const subscriptions = await env.DB.prepare(`SELECT endpoint, uid, p256dh, auth FROM push_subscriptions
WHERE uid IN (${placeholders}) AND uid IN (SELECT uid FROM notification_preferences WHERE push_enabled = 1)`).bind(...uniqueUids).all<{ endpoint: string; uid: string; p256dh: string; auth: string }>();
await Promise.all(subscriptions.results.map(async (subscription) => {
try {
- await webpush.sendNotification({ endpoint: subscription.endpoint, keys: { p256dh: subscription.p256dh, auth: subscription.auth } }, JSON.stringify(notification));
+ await sendNotification({ endpoint: subscription.endpoint, keys: { p256dh: subscription.p256dh, auth: subscription.auth } }, JSON.stringify(notification));
} catch (error) {
const statusCode = typeof error === "object" && error && "statusCode" in error ? Number(error.statusCode) : 0;
if (statusCode === 404 || statusCode === 410) await env.DB.prepare("DELETE FROM push_subscriptions WHERE endpoint = ?").bind(subscription.endpoint).run();