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
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
# Google Analytics 4 - Web analytics
# Get your measurement ID from https://analytics.google.com
# Format: G-XXXXXXXXXX
NUXT_PUBLIC_GTAG_ID=G-DN17ZDXFX7
NUXT_PUBLIC_GTAG_ID=G-XXXXXXXXXX

#
# For production (after deploying worker):
Expand Down
47 changes: 27 additions & 20 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,23 +56,30 @@ jobs:
- name: Build
run: npm run build

# NOTE: The Cloudflare Worker in worker/ is a separate sub-project with its own
# dependencies, tsconfig and tests. It is intentionally NOT part of this
# workflow yet because its test suite currently has pre-existing failures and
# type errors (see the tracking issue). Once those are resolved, add a job here:
#
# worker:
# runs-on: ubuntu-latest
# defaults:
# run:
# working-directory: worker
# steps:
# - uses: actions/checkout@v7
# - uses: actions/setup-node@v7
# with:
# node-version-file: .nvmrc
# cache: npm
# cache-dependency-path: worker/package-lock.json
# - run: npm ci
# - run: npm run type-check
# - run: npm run test
# The Cloudflare Worker in worker/ is a separate sub-project with its own
# dependencies, tsconfig and tests, so it is checked independently.
worker:
name: Worker (type-check & test)
runs-on: ubuntu-latest
defaults:
run:
working-directory: worker
steps:
- name: Checkout
uses: actions/checkout@v7

- name: Setup Node
uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: worker/package-lock.json

- name: Install dependencies
run: npm ci

- name: Type-check
run: npm run type-check

- name: Unit tests
run: npm run test
35 changes: 24 additions & 11 deletions worker/src/middleware/cors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,20 @@ import { Context, Next } from "hono";
import type { Env } from "../types";

/**
* CORS configuration headers - Very permissive for development
* CORS configuration headers
*
* Only the configured frontend origin (or the request origin when it matches)
* is ever reflected, so browsers on other sites cannot make cross-origin
* requests. Credentials are intentionally not enabled: the API authenticates
* via an `Authorization: Bearer` header rather than cookies.
*/
export const getCorsHeaders = (origin: string) => {
export const getCorsHeaders = (origin: string | undefined, allowedOrigin: string) => {
const allowOrigin = origin === allowedOrigin ? origin : allowedOrigin;

return {
"Access-Control-Allow-Origin": origin || "*",
"Access-Control-Allow-Origin": allowOrigin,
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With, Accept, Origin",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Max-Age": "86400",
};
};
Expand All @@ -24,23 +30,30 @@ export const getCorsHeaders = (origin: string) => {
* and handles preflight requests
*/
export const corsMiddleware = async (c: Context<{ Bindings: Env }>, next: Next) => {
const origin = c.req.header("Origin") || "*";
const allowedOrigin = c.env.FRONTEND_URL;
const origin = c.req.header("Origin");

// Handle preflight requests
if (c.req.method === "OPTIONS") {
const headers = getCorsHeaders(origin);
return new Response(null, {
status: 204,
headers,
headers: getCorsHeaders(origin, allowedOrigin),
});
}

// Continue to next middleware/handler
await next();

// Add CORS headers to response
const headers = getCorsHeaders(origin);
Object.entries(headers).forEach(([key, value]) => {
c.res.headers.set(key, value);
// Rebuild the response with CORS headers rather than mutating c.res.headers,
// because some responses (e.g. redirects) expose immutable headers.
const headers = new Headers(c.res.headers);
Object.entries(getCorsHeaders(origin, allowedOrigin)).forEach(([key, value]) => {
headers.set(key, value);
});

c.res = new Response(c.res.body, {
status: c.res.status,
statusText: c.res.statusText,
headers,
});
};
100 changes: 21 additions & 79 deletions worker/src/services/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
*/

import type { User, Progress, QuizScore, Bookmark, BookmarkWithParams, Env } from '../types'
import { ErrorCode } from '../types'
import {
createDatabaseError,
createValidationError,
createNotFoundError,
} from '../utils/errors'

/**
* Generate a unique ID using crypto
Expand Down Expand Up @@ -55,11 +59,7 @@ export async function createUser(
updated_at: now,
}
} catch (error) {
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to create user',
details: error,
}
throw createDatabaseError('Failed to create user', error)
}
}

Expand All @@ -79,11 +79,7 @@ export async function getUserByGoogleId(db: D1Database, googleId: string): Promi
return result
} catch (error) {
console.error(error)
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to get user by Google ID',
details: error,
}
throw createDatabaseError('Failed to get user by Google ID', error)
}
}

Expand All @@ -102,11 +98,7 @@ export async function getUserById(db: D1Database, userId: string): Promise<User

return result
} catch (error) {
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to get user by ID',
details: error,
}
throw createDatabaseError('Failed to get user by ID', error)
}
}

Expand Down Expand Up @@ -157,22 +149,15 @@ export async function updateUser(

const user = await getUserById(db, userId)
if (!user) {
throw {
code: ErrorCode.NOT_FOUND,
message: 'User not found after update',
}
throw createNotFoundError('User not found after update')
}

return user
} catch (error) {
if ((error as any).code) {
throw error
}
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to update user',
details: error,
}
throw createDatabaseError('Failed to update user', error)
}
}

Expand Down Expand Up @@ -219,11 +204,7 @@ export async function saveProgress(
completed_at: completedAt,
}
} catch (error) {
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to save progress',
details: error,
}
throw createDatabaseError('Failed to save progress', error)
}
}

Expand All @@ -246,11 +227,7 @@ export async function getProgressByUserId(db: D1Database, userId: string): Promi
completed: Boolean(p.completed),
}))
} catch (error) {
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to get progress',
details: error,
}
throw createDatabaseError('Failed to get progress', error)
}
}

Expand Down Expand Up @@ -297,11 +274,7 @@ export async function saveQuizScore(
completed_at: completedAt,
}
} catch (error) {
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to save quiz score',
details: error,
}
throw createDatabaseError('Failed to save quiz score', error)
}
}

Expand All @@ -320,11 +293,7 @@ export async function getQuizScoresByUserId(db: D1Database, userId: string): Pro

return result.results || []
} catch (error) {
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to get quiz scores',
details: error,
}
throw createDatabaseError('Failed to get quiz scores', error)
}
}

Expand Down Expand Up @@ -363,11 +332,7 @@ export async function saveBookmark(
// Validate JSON size is under 10KB
const jsonSize = new TextEncoder().encode(parametersJson).length
if (jsonSize > 10240) {
throw {
code: ErrorCode.VALIDATION_ERROR,
message: 'Parameters exceed 10KB limit',
details: { size: jsonSize, limit: 10240 }
}
throw createValidationError('Parameters exceed 10KB limit', { size: jsonSize, limit: 10240 })
}

console.log("Initiating insert")
Expand Down Expand Up @@ -408,11 +373,7 @@ export async function saveBookmark(
if ((error as any).code) {
throw error
}
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to save bookmark',
details: error,
}
throw createDatabaseError('Failed to save bookmark', error)
}
}

Expand Down Expand Up @@ -452,11 +413,7 @@ export async function updateBookmark(
// Validate JSON size is under 10KB
const jsonSize = new TextEncoder().encode(parametersJson).length
if (jsonSize > 10240) {
throw {
code: ErrorCode.VALIDATION_ERROR,
message: 'Parameters exceed 10KB limit',
details: { size: jsonSize, limit: 10240 }
}
throw createValidationError('Parameters exceed 10KB limit', { size: jsonSize, limit: 10240 })
}

fields.push('parameters = ?')
Expand All @@ -483,22 +440,15 @@ export async function updateBookmark(
.first<Bookmark>()

if (!result) {
throw {
code: ErrorCode.NOT_FOUND,
message: 'Bookmark not found',
}
throw createNotFoundError('Bookmark not found')
}

return result
} catch (error) {
if ((error as any).code) {
throw error
}
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to update bookmark',
details: error,
}
throw createDatabaseError('Failed to update bookmark', error)
}
}

Expand Down Expand Up @@ -537,11 +487,7 @@ export async function getBookmarksByUserId(db: D1Database, userId: string): Prom

return bookmarks
} catch (error) {
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to get bookmarks',
details: error,
}
throw createDatabaseError('Failed to get bookmarks', error)
}
}

Expand All @@ -566,10 +512,6 @@ export async function deleteBookmark(

return (result.meta?.changes || 0) > 0
} catch (error) {
throw {
code: ErrorCode.DATABASE_ERROR,
message: 'Failed to delete bookmark',
details: error,
}
throw createDatabaseError('Failed to delete bookmark', error)
}
}
37 changes: 15 additions & 22 deletions worker/src/utils/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,40 +102,33 @@ export function isValidEmail(email: string): boolean {
/**
* Validates module ID format
* Module IDs should follow the pattern: domain/module-name
* Examples: regression/linear-regression, clustering/k-means
* Examples: linear-regression, attention-mechanisms, regression/linear-regression
* Requirements: 7.4
*/
export function isValidModuleId(moduleId: string): boolean {
if (typeof moduleId !== 'string' || !moduleId) {
return false
}

// Module ID pattern: domain/module-name (kebab-case)
const moduleIdRegex = /^[a-z]+(?:-[a-z0-9]+)*$/

if (!moduleIdRegex.test(moduleId)) {
return false
}


// Length constraints
if (moduleId.length > 100) {
return false
}

// Ensure no consecutive hyphens or slashes
if (moduleId.includes('--') || moduleId.includes('//')) {

// A module ID is one or two kebab-case segments separated by "/".
//
// The app identifies modules by their bare ID (e.g. "linear-regression",
// "attention-mechanisms" β€” see `loadQuiz('decision-trees', ...)` and each
// module's config.json "id"), so a single segment is the common case. The
// nested "domain/module" form is also accepted.
const segmentRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
const segments = moduleId.split('/')

if (segments.length > 2) {
return false
}

// Ensure doesn't start or end with hyphen
const parts = moduleId.split('/')
for (const part of parts) {
if (part.startsWith('-') || part.endsWith('-')) {
return false
}
}

return true

return segments.every((segment) => segmentRegex.test(segment))
}

/**
Expand Down
Loading
Loading