Skip to content
Draft
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: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ Built with **Next.js, TypeScript, Node.js, Apollo Server, GraphQL, and PostgreSQ

## Learn the project

Start with the [build-from-zero lesson](docs/technical-manual.md#10-build-it-from-zero-a-teaching-sequence), then [build the React/CSS interface](docs/technical-manual.md#11-build-the-interface-from-layout-to-interaction) and [trace FR-1041 from click to SQL](docs/technical-manual.md#12-follow-fr-1041-from-a-click-to-sql-and-back). The manual includes exercises with executable solutions and explains the demo's limits.

- [Technical manual](docs/technical-manual.md): setup, architecture, contracts, failure labs, extension exercises, and interview answers.
- [Product story](docs/product-story.md): the hypothetical workflow, intended value, limitations, and a 60–90 second demo script.

Expand Down
381 changes: 380 additions & 1 deletion docs/technical-manual.md

Large diffs are not rendered by default.

7 changes: 2 additions & 5 deletions src/app/api/graphql/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { getDatabase } from '@/lib/database';
import { createApi } from '@/lib/graphql';
import { RoutingService } from '@/lib/routing';
import { hasAllowedOrigin } from '@/lib/request-origin';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
Expand All @@ -12,11 +13,7 @@ const started = api.start();
export async function POST(request: NextRequest) {
if (!request.headers.get('content-type')?.startsWith('application/json'))
return NextResponse.json({ error: 'Use application/json.' }, { status: 415 });
const origin = request.headers.get('origin');
// NextURL normalizes loopback IPs to localhost. Preserve the browser's Host
// when comparing origins so legitimate 127.0.0.1 requests remain same-origin.
const expectedOrigin = `${request.nextUrl.protocol}//${request.headers.get('host')}`;
if (origin && origin !== expectedOrigin)
if (!hasAllowedOrigin(request))
return NextResponse.json({ error: 'Cross-origin requests are not allowed.' }, { status: 403 });
const body = await request.text();
if (body.length > 16000)
Expand Down
5 changes: 5 additions & 0 deletions src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -1179,3 +1179,8 @@ form .button {
animation: none;
}
}

.warehouse-region {
font-size: 13px;
color: var(--muted);
}
7 changes: 2 additions & 5 deletions src/components/dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ export default function Dashboard() {
Grant’s workspace<small>Fulfillment operations</small>
</div>
</div>
<div className="nav-label">WORKSPACE</div>

<nav aria-label="Main navigation">
{(
[
Expand Down Expand Up @@ -211,7 +211,6 @@ export default function Dashboard() {
<div className="content">
<div className="page-heading">
<div>
<div className="eyebrow">FULFILLMENT CONTROL</div>
<h1>
{
{
Expand Down Expand Up @@ -412,7 +411,6 @@ export default function Dashboard() {
{selected ? (
<>
<div className="detail-heading">
<span className="eyebrow">ROUTING INSPECTOR</span>
<div>
<h2>{selected.id}</h2>
<span className={`badge ${selected.status.toLowerCase()}`}>
Expand Down Expand Up @@ -607,7 +605,7 @@ export default function Dashboard() {
<section className="panel" key={warehouse.id}>
<div className="panel-heading">
<div>
<div className="eyebrow">{warehouse.region}</div>
<div className="warehouse-region">{warehouse.region}</div>
<h2>
{warehouse.name}, {warehouse.state}
</h2>
Expand Down Expand Up @@ -703,7 +701,6 @@ export default function Dashboard() {
{tab === 'guide' && (
<div className="guide-grid">
<section className="panel guide">
<div className="eyebrow">YOUR FIVE-MINUTE WALKTHROUGH</div>
<h2>Follow an order from stock to allocation.</h2>
<p>
This demo reconstructs a warehouse routing workflow with fictional data. Every
Expand Down
14 changes: 14 additions & 0 deletions src/lib/request-origin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { NextRequest } from 'next/server';

/** Compare the browser's exact origin, not an allowlist of loopback aliases. */
export function hasAllowedOrigin(request: Pick<NextRequest, 'headers' | 'nextUrl'>): boolean {
const origin = request.headers.get('origin');
// Non-browser clients such as curl may omit Origin, as before.
if (origin === null) return true;
const host = request.headers.get('host');
if (!host) return false;
// NextURL canonicalizes 127.0.0.1 and [::1] to localhost. Use the actual
// request Host, including its port, so each spelling works only with itself.
// Do not use X-Forwarded-Host to expand trust without a proxy trust policy.
return origin === `${request.nextUrl.protocol}//${host}`;
}
4 changes: 3 additions & 1 deletion src/lib/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,10 @@ export class RoutingService {
)
).map((r) => r.data),
inventory: await inventoryFor(tx, sessionId),
// Qualify the numeric column: the output `id` is text for GraphQL and
// ORDER BY id would sort that alias lexically (9 before 10 or 100).
events: await tx.query<AuditEvent>(
'SELECT id::text,id::text AS "eventId",order_id AS "orderId",action,detail,created_at::text AS "createdAt" FROM audit_events WHERE session_id=$1 ORDER BY id DESC LIMIT 100',
'SELECT id::text,id::text AS "eventId",order_id AS "orderId",action,detail,created_at::text AS "createdAt" FROM audit_events WHERE session_id=$1 ORDER BY audit_events.id DESC LIMIT 100',
[sessionId],
),
storageMode: this.db.mode,
Expand Down
35 changes: 35 additions & 0 deletions tests/audit-history.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import type { Database } from '../src/lib/database';
import { RoutingService } from '../src/lib/routing';

// Shared contract: exercise the actual dashboard SQL on both database adapters.
export async function assertRecentAuditHistory(db: Database) {
const session = randomUUID();
const otherSession = randomUUID();
const service = new RoutingService(db);
try {
await service.initialize(session);
const inserted = await db.query<{ id: string; detail: string }>(
`INSERT INTO audit_events(session_id, action, detail, created_at)
SELECT $1, 'HISTORY_TEST', 'Event ' || n, '2026-01-01T00:00:00Z'::timestamptz
FROM generate_series(1, 125) AS n
RETURNING id::text, detail`,
[session],
);
// A later event from another workspace must not leak into this history.
await service.initialize(otherSession);
const expected = inserted.sort((a, b) => (BigInt(a.id) > BigInt(b.id) ? -1 : 1)).slice(0, 100);
assert.ok(expected.every((event) => BigInt(event.id) > 9n));
const actual = (await service.dashboard(session)).events;
assert.equal(actual.length, 100);
assert.deepEqual(
actual.map(({ id, detail }) => ({ id, detail })),
expected,
'history must contain the newest 100 numeric IDs in descending order',
);
assert.ok(actual.every((event) => event.action === 'HISTORY_TEST'));
} finally {
await db.query('DELETE FROM demo_sessions WHERE id=$1 OR id=$2', [session, otherSession]);
}
}
13 changes: 13 additions & 0 deletions tests/audit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { test } from 'node:test';
import { createDatabase, migrate } from '../src/lib/database';
import { assertRecentAuditHistory } from './audit-history';

test('audit history returns the newest 100 events across numeric ID boundaries', async () => {
const db = await createDatabase();
try {
await migrate(db);
await assertRecentAuditHistory(db);
} finally {
await db.close();
}
});
62 changes: 53 additions & 9 deletions tests/e2e/dashboard.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,61 @@ test('stock shortage, quote failure, audit trail and last-unit race', async ({ p
await expect(page.getByRole('heading', { name: 'Decision trail' })).toBeVisible();
});

test('HTTP origin checks allow the current host and reject a foreign origin', async ({
test('HTTP origin checks allow each local host and reject mismatched origins', async ({
request,
baseURL,
}) => {
const data = { query: '{ products { sku } }' };
const allowed = await request.post('/api/graphql', { headers: { origin: baseURL! }, data });
expect(allowed.status()).toBe(200);
expect((await allowed.json()).data.products).toHaveLength(5);
const rejected = await request.post('/api/graphql', {
headers: { origin: 'https://unrelated.example' },
data,
});
expect(rejected.status()).toBe(403);
for (const hostname of ['localhost', '127.0.0.1']) {
const url = new URL(baseURL!);
url.hostname = hostname;
const allowed = await request.post(`${url.origin}/api/graphql`, {
headers: { origin: url.origin },
data,
});
expect(allowed.status()).toBe(200);
expect((await allowed.json()).data.products).toHaveLength(5);
}
const mismatchedPort = new URL(baseURL!);
mismatchedPort.port = String(Number(mismatchedPort.port) + 1);
for (const origin of [
'https://unrelated.example',
baseURL!.replace('127.0.0.1', 'localhost'),
mismatchedPort.origin,
baseURL!.replace('http:', 'https:'),
'null',
'',
]) {
const rejected = await request.post('/api/graphql', {
headers: { origin, 'x-forwarded-host': origin.replace(/^https?:\/\//, '') },
data,
});
expect(rejected.status(), origin).toBe(403);
expect(await rejected.json()).toEqual({ error: 'Cross-origin requests are not allowed.' });
expect(rejected.headers()['set-cookie']).toBeUndefined();
}
});

test('activity renders numeric event order after more than nine events', async ({ page }) => {
await page.goto('/');
await expect(page.getByText('RNO recommended', { exact: true })).toBeVisible();
const ids: string[] = [];
for (let index = 0; index < 12; index++) {
const response = await page.request.post('/api/graphql', {
data: {
query: `mutation { createOrder(input: { customer: "History fixture", destinationId: NYC,
items: [{ sku: "PH-100", quantity: 1 }] }) { id } }`,
},
});
const result = await response.json();
expect(result.errors).toBeUndefined();
ids.push(result.data.createOrder.id);
}
await page.getByRole('button', { name: 'Activity log', exact: true }).click();
await page.getByRole('button', { name: 'Refresh', exact: true }).click();
const articles = page.locator('.timeline article');
await expect(articles).toHaveCount(13);
await expect(articles.first().getByRole('button')).toHaveText(ids[11]);
await expect(page.locator('.timeline article button')).toHaveText([...ids].reverse());
await expect(articles.last()).toContainText('DEMO READY');
});
12 changes: 12 additions & 0 deletions tests/postgres.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { createDatabase, migrate } from '../src/lib/database';
import { RoutingService } from '../src/lib/routing';
import { assertRecentAuditHistory } from './audit-history';

test('PostgreSQL audit history returns the newest 100 numeric IDs', async () => {
assert.ok(process.env.DATABASE_URL, 'Set DATABASE_URL to a disposable PostgreSQL database.');
const db = await createDatabase(process.env.DATABASE_URL);
try {
await migrate(db);
await assertRecentAuditHistory(db);
} finally {
await db.close();
}
});

test('separate PostgreSQL pools compete for one unit', async () => {
assert.ok(process.env.DATABASE_URL, 'Set DATABASE_URL to a disposable PostgreSQL database.');
Expand Down
50 changes: 50 additions & 0 deletions tests/request-origin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { NextRequest } from 'next/server';
import { hasAllowedOrigin } from '../src/lib/request-origin';

test('same-origin localhost, IPv4 and IPv6 loopback survive NextURL normalization', () => {
for (const host of ['localhost:3000', '127.0.0.1:3000', '[::1]:3000']) {
const origin = `http://${host}`;
const request = new NextRequest(`${origin}/api/graphql`, { headers: { host, origin } });
assert.equal(request.nextUrl.hostname, 'localhost');
assert.equal(hasAllowedOrigin(request), true, origin);
}
});

test('origin checks retain exact host, port and scheme boundaries', () => {
for (const origin of [
'https://unrelated.example',
'http://localhost:3000',
'http://127.0.0.1:3001',
'https://127.0.0.1:3000',
'http://127.0.0.1.evil.example:3000',
'http://127.0.0.1:3000@evil.example',
'null',
'',
]) {
const request = new NextRequest('http://127.0.0.1:3000/api/graphql', {
headers: { host: '127.0.0.1:3000', origin, 'x-forwarded-host': origin.slice(7) },
});
assert.equal(hasAllowedOrigin(request), false, origin);
}
});

test('explicit origins require Host; absent Origin remains usable by CLI clients', () => {
const url = 'http://localhost:3000/api/graphql';
assert.equal(
hasAllowedOrigin(new NextRequest(url, { headers: { origin: 'http://localhost:3000' } })),
false,
);
assert.equal(
hasAllowedOrigin(new NextRequest(url, { headers: { host: 'localhost:3000' } })),
true,
);
});

test('HTTPS same-origin requests remain allowed without a loopback exception', () => {
const request = new NextRequest('https://dispatch.example/api/graphql', {
headers: { host: 'dispatch.example', origin: 'https://dispatch.example' },
});
assert.equal(hasAllowedOrigin(request), true);
});
59 changes: 59 additions & 0 deletions tests/walkthrough.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createDatabase, migrate } from '../src/lib/database';
import { RoutingService } from '../src/lib/routing';

test('FR-1041 walkthrough prices, multi-item reservation, retries and release match the guide', async () => {
const db = await createDatabase();
const service = new RoutingService(db);
const session = 'walkthrough-only';
try {
await migrate(db);
await service.initialize(session);
const before = await service.dashboard(session);
const preview = await service.preview(session, 'FR-1041');
assert.deepEqual(
preview.candidates.map(({ warehouseId, costCents, transitDays, distanceMiles }) => ({
warehouseId,
costCents,
transitDays,
distanceMiles,
})),
[
{ warehouseId: 'BUF', costCents: 1812, transitDays: 1, distanceMiles: 292 },
{ warehouseId: 'RNO', costCents: 3326, transitDays: 4, distanceMiles: 2394 },
],
);
assert.equal(preview.savingsCents, 1514);
assert.deepEqual((await service.dashboard(session)).inventory, before.inventory);
await service.route(session, 'FR-1041');
await service.route(session, 'FR-1041');
const allocated = await service.dashboard(session);
for (const row of allocated.inventory) {
const expected = row.warehouseId === 'BUF' ? ({ 'PH-100': 4, 'HS-200': 2 }[row.sku] ?? 0) : 0;
assert.equal(row.reserved, expected);
assert.equal(row.available, row.onHand - expected);
assert.equal(
row.onHand,
before.inventory.find(
(original) => original.warehouseId === row.warehouseId && original.sku === row.sku,
)!.onHand,
);
}
assert.equal(allocated.orders.find((o) => o.id === 'FR-1041')!.warehouseId, 'BUF');
await service.cancel(session, 'FR-1041');
await service.cancel(session, 'FR-1041');
const after = await service.dashboard(session);
assert.deepEqual(after.inventory, before.inventory);
const order = after.orders.find((o) => o.id === 'FR-1041')!;
assert.equal(order.status, 'CANCELLED');
assert.equal(order.warehouseId, null);
assert.equal(order.decision!.selectedWarehouseId, 'BUF');
assert.deepEqual(
after.events.filter((e) => e.orderId === 'FR-1041').map((e) => e.action),
['CANCELLED', 'ALLOCATED'],
);
} finally {
await db.close();
}
});
Loading