Skip to content
Open
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
41 changes: 29 additions & 12 deletions packages/api/src/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,45 @@
import type { MiddlewareHandler } from "hono"
import { timingSafeEqual } from "node:crypto"

/**
* Simple token-based auth middleware.
*
* Policy:
* GET, POST → public (no token required)
* GET, POST → public (no token required)
* PUT, DELETE, PATCH → require Bearer token
*
* BUG: The allow-list check uses `'post'` (lowercase) instead of `'POST'`.
* HTTP methods are always uppercase per RFC 7231, so POST is never matched
* as a public method — POST requests incorrectly require a token.
*
* Fix: change `'post'` to `'POST'` in the public methods array.
* SECURITY NOTE — do not copy this policy into a real system.
* Making GET and POST public for *every* route is a deliberate test-fixture
* choice for this e2e corpus, asserted by packages/api/test/auth.test.ts.
* It means /users can be read and written unauthenticated, exposing email
* addresses (personal information under the Privacy Act 1988). A production
* service must default-deny and opt individual routes into public access
* instead of allow-listing whole HTTP verbs [ISM-1546, APP-11].
* See docs/plans/2026-09-28-auth-middleware-security-assessment.md (SEC-004).
*/
export const authMiddleware: MiddlewareHandler = async (c, next) => {
// BUG: 'post' should be 'POST' — POST is never treated as public
const publicMethods = ["GET", "post"]
const PUBLIC_METHODS = ["GET", "POST"]

const BEARER_SCHEME = /^Bearer (.+)$/

function secretsMatch(presented: string, expected: string): boolean {
const a = Buffer.from(presented, "utf8")
const b = Buffer.from(expected, "utf8")
if (a.length !== b.length) return false
return timingSafeEqual(a, b)
}

if (publicMethods.includes(c.req.method)) {
export const authMiddleware: MiddlewareHandler = async (c, next) => {
if (PUBLIC_METHODS.includes(c.req.method.toUpperCase())) {
return next()
}

const token = c.req.header("Authorization")?.replace("Bearer ", "")
if (!token || token !== (process.env.API_TOKEN ?? "test-token")) {
const expected = process.env.API_TOKEN
if (!expected) {
return c.json({ error: "Unauthorized", status: 401 }, 401)
}

const presented = BEARER_SCHEME.exec(c.req.header("Authorization") ?? "")?.[1]
if (!presented || !secretsMatch(presented, expected)) {
return c.json({ error: "Unauthorized", status: 401 }, 401)
}

Expand Down
6 changes: 1 addition & 5 deletions packages/api/src/routes/users.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { Hono } from "hono"
import { db } from "../lib/db"
import { notFound } from "../lib/errors"
// BUG: missing import — `badRequest` is used below but not imported here.
// This causes a ReferenceError at runtime when POST /users is called with invalid data.
// Fix: add `badRequest` to the import from "../lib/errors"
import { notFound, badRequest } from "../lib/errors"

const router = new Hono()

Expand All @@ -20,7 +17,6 @@ router.get("/:id", (c) => {
router.post("/", async (c) => {
const body = await c.req.json().catch(() => null)
if (!body || !body.username || !body.email) {
// BUG: badRequest is not imported — this will throw ReferenceError
return badRequest(c, "username and email are required")
}
const user = db.users.create({ username: body.username, email: body.email })
Expand Down
6 changes: 1 addition & 5 deletions packages/shared/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
/**
* Shared types used by both the API and any consumers.
*
* BUG: The field is named `userName` here but the API routes reference `username`
* (lowercase n). This causes a type error in routes/users.ts and a runtime
* mismatch when serialising responses.
*/

export type User = {
id: string
userName: string // BUG: should be `username` to match API usage
username: string
email: string
createdAt: string
}
Expand Down
17 changes: 13 additions & 4 deletions packages/shared/src/utils/pagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,19 @@ import type { PaginatedResponse } from "../types"
* @param items Full array of items
* @param page 1-indexed page number
* @param size Number of items per page
*
* TODO: implement this function — it is currently a stub.
* The test in packages/shared/test/pagination.test.ts exercises the full contract.
*/
export function paginate<T>(items: T[], page: number, size: number): PaginatedResponse<T> {
throw new Error("not implemented")
const pageSize = Number.isFinite(size) && size > 0 ? Math.floor(size) : 0
const currentPage = Number.isFinite(page) && page > 0 ? Math.floor(page) : 1
const total = items.length
const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0
const start = (currentPage - 1) * pageSize

return {
data: pageSize > 0 ? items.slice(start, start + pageSize) : [],
page: currentPage,
pageSize,
total,
totalPages,
}
}
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"moduleResolution": "bundler",
"strict": true,
"skipLibCheck": true,
"types": ["bun-types"],
"paths": {
"@e2e/shared": ["./packages/shared/src/index.ts"]
}
Expand Down
Loading