feat: Sprint 1 slice 1 — API signup + web signup/chat shell
Mirror to GitHub / mirror (push) Canceled after 0s
Mirror to GitHub / mirror (push) Canceled after 0s
- api: Fastify POST /auth/signup (validation, scrypt hash, in-memory store) - web: React+Vite SignUp form and chat shell with dev proxy - 35 tests green (api 5, web 2, e2e 28)
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { buildApp } from '../src/app.ts';
|
||||
|
||||
describe('POST /auth/signup', () => {
|
||||
it('creates a user and returns a session token', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/signup',
|
||||
payload: { email: 'a@example.com', password: 'password123' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = res.json();
|
||||
expect(body.user.email).toBe('a@example.com');
|
||||
expect(body.user.id).toBeTruthy();
|
||||
expect(body.sessionToken).toBeTruthy();
|
||||
});
|
||||
|
||||
it('rejects an invalid email with 400', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/signup',
|
||||
payload: { email: 'not-an-email', password: 'password123' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects a short password with 400', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/signup',
|
||||
payload: { email: 'a@example.com', password: 'short' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects a duplicate email with 409', async () => {
|
||||
const app = await buildApp();
|
||||
const payload = { email: 'a@example.com', password: 'password123' };
|
||||
await app.inject({ method: 'POST', url: '/auth/signup', payload });
|
||||
const res = await app.inject({ method: 'POST', url: '/auth/signup', payload });
|
||||
|
||||
expect(res.statusCode).toBe(409);
|
||||
});
|
||||
|
||||
it('does not return the password hash', async () => {
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/signup',
|
||||
payload: { email: 'a@example.com', password: 'password123' },
|
||||
});
|
||||
|
||||
expect(res.json().user.passwordHash).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+14
-1
@@ -2,5 +2,18 @@
|
||||
"name": "@wursor/api",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {}
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"start": "tsx src/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"fastify": "^5.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.0",
|
||||
"tsx": "^4.20.3",
|
||||
"typescript": "^5.9.2",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import Fastify from 'fastify';
|
||||
import { authRoutes } from './routes/auth.ts';
|
||||
import { InMemoryUserStore } from './services/user-store.ts';
|
||||
|
||||
export async function buildApp() {
|
||||
const app = Fastify();
|
||||
const store = new InMemoryUserStore();
|
||||
await authRoutes(app, store);
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { buildApp } from './app.ts';
|
||||
|
||||
const port = Number(process.env.PORT ?? 3000);
|
||||
const app = await buildApp();
|
||||
|
||||
await app.listen({ port, host: '0.0.0.0' });
|
||||
@@ -0,0 +1,24 @@
|
||||
import { randomBytes, randomUUID, scryptSync, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
export function hashPassword(password: string): string {
|
||||
const salt = randomBytes(16).toString('hex');
|
||||
const hash = scryptSync(password, salt, 32).toString('hex');
|
||||
return `${salt}:${hash}`;
|
||||
}
|
||||
|
||||
export function verifyPassword(password: string, stored: string): boolean {
|
||||
const [salt, hash] = stored.split(':');
|
||||
if (salt === undefined || hash === undefined) {
|
||||
return false;
|
||||
}
|
||||
const candidate = scryptSync(password, salt, 32);
|
||||
return timingSafeEqual(candidate, Buffer.from(hash, 'hex'));
|
||||
}
|
||||
|
||||
export function newToken(): string {
|
||||
return randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
export function newId(): string {
|
||||
return randomUUID();
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { hashPassword, newId, newToken } from '../lib/crypto.ts';
|
||||
import type { UserStore } from '../services/user-store.ts';
|
||||
|
||||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
type SignupBody = {
|
||||
email?: string;
|
||||
password?: string;
|
||||
};
|
||||
|
||||
export async function authRoutes(app: FastifyInstance, store: UserStore): Promise<void> {
|
||||
app.post('/auth/signup', async (request, reply) => {
|
||||
const { email: rawEmail, password } = request.body as SignupBody;
|
||||
const email = rawEmail?.trim().toLowerCase();
|
||||
|
||||
if (email === undefined || email === '' || !EMAIL_RE.test(email)) {
|
||||
return reply.status(400).send({ error: 'invalid_email' });
|
||||
}
|
||||
if (password === undefined || password.length < 8) {
|
||||
return reply.status(400).send({ error: 'weak_password' });
|
||||
}
|
||||
if (store.findByEmail(email) !== undefined) {
|
||||
return reply.status(409).send({ error: 'email_exists' });
|
||||
}
|
||||
|
||||
const user = store.create({ id: newId(), email, passwordHash: hashPassword(password) });
|
||||
return reply.status(201).send({ user: { id: user.id, email: user.email }, sessionToken: newToken() });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export type User = {
|
||||
id: string;
|
||||
email: string;
|
||||
passwordHash: string;
|
||||
};
|
||||
|
||||
export interface UserStore {
|
||||
findByEmail(email: string): User | undefined;
|
||||
create(user: User): User;
|
||||
}
|
||||
|
||||
export class InMemoryUserStore implements UserStore {
|
||||
private byEmail = new Map<string, User>();
|
||||
|
||||
findByEmail(email: string): User | undefined {
|
||||
return this.byEmail.get(email);
|
||||
}
|
||||
|
||||
create(user: User): User {
|
||||
this.byEmail.set(user.email, user);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
Generated
+1358
-12
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { SignUp } from '../src/components/SignUp.tsx';
|
||||
|
||||
describe('SignUp', () => {
|
||||
it('submits the email and password', async () => {
|
||||
const onSignUp = vi.fn().mockResolvedValue(undefined);
|
||||
render(<SignUp onSignUp={onSignUp} />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Email'), 'a@example.com');
|
||||
await userEvent.type(screen.getByLabelText('Password'), 'password123');
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Sign up' }));
|
||||
|
||||
expect(onSignUp).toHaveBeenCalledWith('a@example.com', 'password123');
|
||||
});
|
||||
|
||||
it('shows an error when signup fails', async () => {
|
||||
const onSignUp = vi.fn().mockRejectedValue(new Error('email_exists'));
|
||||
render(<SignUp onSignUp={onSignUp} />);
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Email'), 'a@example.com');
|
||||
await userEvent.type(screen.getByLabelText('Password'), 'password123');
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Sign up' }));
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('email_exists');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Wursor</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
+22
-1
@@ -2,5 +2,26 @@
|
||||
"name": "@wursor/web",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {}
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/jest-dom": "^7.0.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@testing-library/user-event": "^14.6.4",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.4",
|
||||
"@vitejs/plugin-react": "^6.0.5",
|
||||
"jsdom": "^30.0.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^8.2.1",
|
||||
"vitest": "^3.2.7"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useState } from 'react';
|
||||
import { SignUp } from './components/SignUp.tsx';
|
||||
|
||||
async function signUp(email: string, password: string): Promise<void> {
|
||||
const res = await fetch('/auth/signup', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => null)) as { error?: string } | null;
|
||||
throw new Error(body?.error ?? 'Sign up failed');
|
||||
}
|
||||
}
|
||||
|
||||
export function App() {
|
||||
const [signedUp, setSignedUp] = useState(false);
|
||||
|
||||
if (signedUp) {
|
||||
return (
|
||||
<div className="wursor-welcome">
|
||||
<p>Describe what you want.</p>
|
||||
<input className="wursor-chat-input" placeholder="Describe what you want…" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SignUp
|
||||
onSignUp={async (email, password) => {
|
||||
await signUp(email, password);
|
||||
setSignedUp(true);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
|
||||
type SignUpProps = {
|
||||
onSignUp: (email: string, password: string) => Promise<void>;
|
||||
};
|
||||
|
||||
export function SignUp({ onSignUp }: SignUpProps) {
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
setError(null);
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await onSignUp(email, password);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Something went wrong');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="wursor-signup" onSubmit={submit}>
|
||||
<input name="email" type="email" aria-label="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
<input
|
||||
name="password"
|
||||
type="password"
|
||||
aria-label="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
{error ? <p role="alert">{error}</p> : null}
|
||||
<button type="submit" disabled={submitting}>
|
||||
Sign up
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { App } from './App.tsx';
|
||||
import './styles/global.css';
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,8 @@
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
import { afterEach } from 'vitest';
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import react from '@vitejs/plugin-react';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
proxy: {
|
||||
'/auth': 'http://localhost:3000',
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
setupFiles: ['./src/test-setup.ts'],
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user