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: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
DATABASE_URL=postgresql://t31_dev:change-me@127.0.0.1:5432/t31_project2
API_HOST=127.0.0.1
API_PORT=3001
# Enable only for the documented local Apache proxy on the VM.
AUTH_TRUST_PROXY=false
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ jobs:
apps/api/dist
apps/api/migrations
apps/api/package.json
apps/validation/dist
apps/validation/package.json
apps/web/dist
apps/web/package.json
package.json
Expand Down
3 changes: 2 additions & 1 deletion Dockerfile.dev
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ WORKDIR /app
COPY package.json package-lock.json ./
COPY apps/api/package.json ./apps/api/package.json
COPY apps/web/package.json ./apps/web/package.json
COPY apps/validation/package.json ./apps/validation/package.json

RUN npm ci

Expand All @@ -21,4 +22,4 @@ EXPOSE 3001
# Vite normally binds to 127.0.0.1 in this project.
# We override it here with 0.0.0.0 so it is reachable
# from outside the Docker container.
CMD ["sh", "-c", "npm run db:migrate && exec ./node_modules/.bin/concurrently -k \"npm run dev:api\" \"npm run dev --workspace @t31/web -- --host 0.0.0.0\""]
CMD ["sh", "-c", "npm run build --workspace @t31/validation && npm run db:migrate && exec ./node_modules/.bin/concurrently -k \"npm run dev:api\" \"npm run dev --workspace @t31/web -- --host 0.0.0.0\""]
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ Security trade-off: localStorage is readable by JavaScript on the same origin. A

### Protected routes

Se [auth-forbedringer](docs/auth-improvements.md) for delt Zod-validering,
feilkoder, genererte klientoperasjoner og rate limiting bak Apache.

`/cookbook` and `/recipes/new` require a validated session. On refresh, the router waits for session restoration before rendering protected content or redirecting to login. A temporary API/network error shows a retry action and preserves the token. Successful login or registration returns to the requested protected URL, including its query and hash. Explore and recipe details remain public. This is client-side routing; future protected API operations must enforce authentication and ownership on the server.

## Database
Expand Down
4 changes: 3 additions & 1 deletion apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
"start": "node --env-file-if-exists=../../.env dist/server.js"
},
"dependencies": {
"@t31/validation": "*",
"argon2": "0.45.1",
"drizzle-orm": "0.45.2",
"graphql": "16.12.0",
"graphql-yoga": "5.16.2",
"pg": "8.16.3"
"pg": "8.16.3",
"zod": "4.6.7"
},
"devDependencies": {
"@types/pg": "8.15.6",
Expand Down
54 changes: 35 additions & 19 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,39 @@ import { readFileSync } from 'node:fs';
import { createSchema, createYoga } from 'graphql-yoga';

import type { Resolvers } from './generated.js';
import { authResolvers } from './features/auth/authResolvers.js';
import type { IncomingMessage } from 'node:http';
import {
createAuthResolvers,
type AuthContext,
} from './features/auth/authResolvers.js';
import { authClientKey } from './features/auth/authRateLimit.js';
import { authService, type AuthService } from './features/auth/authService.js';

export const app = createYoga({
schema: createSchema({
typeDefs: readFileSync(
new URL('./schema.graphql', import.meta.url),
'utf8',
),
resolvers: {
Query: {
health: () => 'ok',
...authResolvers.Query,
},
Mutation: {
...authResolvers.Mutation,
},
} satisfies Resolvers,
}),
graphqlEndpoint: '/graphql',
});
export function createApp(
service: AuthService = authService,
trustProxy = process.env.AUTH_TRUST_PROXY === 'true',
) {
const authResolvers = createAuthResolvers(service);
return createYoga<{ req?: IncomingMessage }, AuthContext>({
context: ({ request, req }) => ({
authClient: authClientKey(request, req?.socket.remoteAddress, trustProxy),
}),
schema: createSchema({
typeDefs: readFileSync(
new URL('./schema.graphql', import.meta.url),
'utf8',
),
resolvers: {
Query: {
health: () => 'ok',
...authResolvers.Query,
},
Mutation: {
...authResolvers.Mutation,
},
} satisfies Resolvers<AuthContext>,
}),
graphqlEndpoint: '/graphql',
});
}
export const app = createApp();
119 changes: 119 additions & 0 deletions apps/api/src/features/auth/authApp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// @vitest-environment node
import { describe, expect, it, vi } from 'vitest';
import { print } from 'graphql';
import { createApp } from '../../app.js';
import { createAuthService } from './authService.js';
import type { AuthRepository } from './authRepository.js';
import {
LoginDocument,
CurrentUserDocument,
SignOutDocument,
RegisterDocument,
} from '../../../../../contracts/generated.js';

const token = '11111111-1111-4111-8111-111111111111';
const user = {
id: '22222222-2222-4222-8222-222222222222',
name: 'Hasan',
email: 'hasan@example.com',
};
function setup() {
let active = false;
const repository: AuthRepository = {
findUserByEmail: vi.fn(async () => ({ ...user, passwordHash: 'hash' })),
createUser: vi.fn(async () => user),
createUserWithSession: vi.fn(async () => ({ user, sessionToken: token })),
createSession: vi.fn(async () => {
active = true;
return token;
}),
findUserBySession: vi.fn(async () => (active ? user : null)),
deleteSession: vi.fn(async () => {
active = false;
}),
};
const service = createAuthService(repository, {
hash: async () => 'hash',
verify: async (_hash, password) => password === 'x',
});
const app = createApp(service, false);
async function request(
document: Parameters<typeof print>[0],
variables: Record<string, unknown>,
) {
const response = await app.fetch('http://localhost/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: print(document), variables }),
});
return (await response.json()) as {
data: {
login?: { sessionToken: string };
currentUser?: typeof user | null;
signOut?: boolean;
};
errors?: { extensions: { code: string } }[];
};
}
return { repository, request };
}
describe('GraphQL authentication contract', () => {
it('logs in with a short existing password, restores session and invalidates it on logout', async () => {
const { request } = setup();
const login = await request(LoginDocument, {
email: user.email,
password: 'x',
});
expect(login.errors).toBeUndefined();
expect(login.data.login?.sessionToken).toBe(token);
expect(
(await request(CurrentUserDocument, { sessionToken: token })).data
.currentUser,
).toEqual(user);
expect(
(await request(SignOutDocument, { sessionToken: token })).data.signOut,
).toBe(true);
expect(
(await request(CurrentUserDocument, { sessionToken: token })).data
.currentUser,
).toBeNull();
});
it('does not query the repository for malformed session IDs', async () => {
const { request, repository } = setup();
expect(
(await request(CurrentUserDocument, { sessionToken: 'broken' })).data
.currentUser,
).toBeNull();
expect(
(await request(SignOutDocument, { sessionToken: 'broken' })).data.signOut,
).toBe(false);
expect(repository.findUserBySession).not.toHaveBeenCalled();
expect(repository.deleteSession).not.toHaveBeenCalled();
});
it('returns structured codes for invalid input, credentials, duplicate email and rate limits', async () => {
const { request } = setup();
expect(
(await request(LoginDocument, { email: 'a@', password: 'x' })).errors?.[0]
?.extensions.code,
).toBe('INVALID_INPUT');
expect(
(await request(LoginDocument, { email: user.email, password: 'wrong' }))
.errors?.[0]?.extensions.code,
).toBe('INVALID_CREDENTIALS');
expect(
(
await request(RegisterDocument, {
name: 'Hasan',
email: user.email,
password: 'secret',
})
).errors?.[0]?.extensions.code,
).toBe('EMAIL_TAKEN');
for (let i = 0; i < 8; i++)
await request(LoginDocument, { email: user.email, password: 'wrong' });
expect(
(await request(LoginDocument, { email: user.email, password: 'wrong' }))
.errors?.[0]?.extensions.code,
).toBe('RATE_LIMITED');
});
});
41 changes: 41 additions & 0 deletions apps/api/src/features/auth/authRateLimit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// @vitest-environment node
import { describe, expect, it } from 'vitest';
import { authClientKey, createAuthRateLimiter } from './authRateLimit.js';

describe('authentication rate limit', () => {
it('limits attempts, separates clients and operations, and resets after the window', () => {
let time = 0;
const limiter = createAuthRateLimiter(() => time);
for (let i = 0; i < 10; i++) limiter.check('login', 'client-a');
expect(() => limiter.check('login', 'client-a')).toThrow(
expect.objectContaining({
extensions: expect.objectContaining({
code: 'RATE_LIMITED',
retryAfterSeconds: 60,
}),
}),
);
expect(() => limiter.check('login', 'client-b')).not.toThrow();
for (let i = 0; i < 5; i++) limiter.check('register', 'client-a');
expect(() => limiter.check('register', 'client-a')).toThrow();
time = 60_000;
expect(() => limiter.check('login', 'client-a')).not.toThrow();
});
it('ignores spoofed forwarding headers unless the direct proxy is trusted loopback', () => {
const request = new Request('http://localhost/graphql', {
headers: { 'x-forwarded-for': '198.51.100.1, 192.0.2.5' },
});
expect(authClientKey(request, '203.0.113.4', true)).toBe('203.0.113.4');
expect(authClientKey(request, '127.0.0.1', false)).toBe('127.0.0.1');
expect(authClientKey(request, '127.0.0.1', true)).toBe('192.0.2.5');
expect(
authClientKey(
new Request('http://localhost', {
headers: { 'x-forwarded-for': 'invalid' },
}),
'127.0.0.1',
true,
),
).toBe('127.0.0.1');
});
});
60 changes: 60 additions & 0 deletions apps/api/src/features/auth/authRateLimit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { GraphQLError } from 'graphql';
import { isIP } from 'node:net';

// Only trust Apache's appended client address when explicitly enabled and the
// direct connection is loopback. Client-supplied headers otherwise have no effect.
export function authClientKey(
request: Request,
remoteAddress: string | undefined,
trustProxy: boolean,
) {
const remote = remoteAddress ?? 'unknown';
const loopback = ['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(remote);
if (trustProxy && loopback) {
const forwarded = request.headers
.get('x-forwarded-for')
?.split(',')
.at(-1)
?.trim();
if (forwarded && isIP(forwarded)) return forwarded;
}
return remote;
}

export function createAuthRateLimiter(now = Date.now) {
const attempts = new Map<string, { count: number; expiresAt: number }>();
const windowMs = 60_000;
return {
check(operation: 'login' | 'register', client: string) {
const time = now();
// Bounded memory; no timers or background jobs.
for (const [key, entry] of attempts)
if (entry.expiresAt <= time) attempts.delete(key);
const key = operation + ':' + client;
const entry = attempts.get(key) ?? {
count: 0,
expiresAt: time + windowMs,
};
const limit = operation === 'login' ? 10 : 5;
if (
entry.count >= limit ||
(!attempts.has(key) && attempts.size >= 10_000)
) {
throw new GraphQLError(
'Too many attempts. Please try again in a minute.',
{
extensions: {
code: 'RATE_LIMITED',
retryAfterSeconds: Math.max(
1,
Math.ceil((entry.expiresAt - time) / 1000),
),
},
},
);
}
entry.count += 1;
attempts.set(key, entry);
},
};
}
21 changes: 19 additions & 2 deletions apps/api/src/features/auth/authRepository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function setup(failure?: Error | { code: string; constraint: string }) {
const client = { query, release } as unknown as PoolClient;
const pool = {
connect: vi.fn(async () => client),
query: vi.fn(),
query: vi.fn(async () => ({ rows: [] })),
} as unknown as Pool;
return {
repository: createAuthRepository(pool),
Expand All @@ -35,6 +35,23 @@ function setup(failure?: Error | { code: string; constraint: string }) {
}

describe('atomic registration', () => {
it('does not send malformed tokens to PostgreSQL', async () => {
const { repository, pool } = setup();
await expect(
repository.findUserBySession('not-a-uuid'),
).resolves.toBeNull();
await repository.deleteSession('not-a-uuid');
expect(pool.query).not.toHaveBeenCalled();
});
it('looks up only unexpired sessions', async () => {
const { repository, pool } = setup();
const token = '11111111-1111-4111-8111-111111111111';
await expect(repository.findUserBySession(token)).resolves.toBeNull();
expect(pool.query).toHaveBeenCalledWith(
expect.stringContaining('sessions.expires_at > now()'),
[token],
);
});
it('commits user and session on the same connection', async () => {
const { repository, query, release, pool } = setup();
const expiresAt = new Date();
Expand Down Expand Up @@ -67,7 +84,7 @@ describe('atomic registration', () => {
});
await expect(
repository.createUserWithSession('Hasan', user.email, 'hash', new Date()),
).rejects.toThrow('An account with this email already exists.');
).rejects.toMatchObject({ extensions: { code: 'EMAIL_TAKEN' } });
expect(query).toHaveBeenLastCalledWith('ROLLBACK');
expect(release).toHaveBeenCalledOnce();
});
Expand Down
Loading