Compare commits
20
Commits
28d1805470
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
add7c430b3 | ||
|
|
5e48caf791 | ||
|
|
ec5924fda9 | ||
|
|
3d7be239d6 | ||
|
|
f27d87531c | ||
|
|
9a476d9b86 | ||
|
|
c7ee1ec01e | ||
|
|
1e57851111 | ||
|
|
e08667927d | ||
|
|
b87441260f | ||
|
|
df30510ff2 | ||
|
|
17d179618b | ||
|
|
62c0f4e445 | ||
|
|
de4fc9bf9e | ||
|
|
befdacb50b | ||
|
|
cb1cf425f1 | ||
|
|
19268ae00f | ||
|
|
868b91e440 | ||
|
|
6755bf05fa | ||
|
|
2e217a23d7 |
No files matched your search
@@ -1,6 +1,7 @@
|
|||||||
name: CI/CD Pipeline
|
name: CI/CD Pipeline
|
||||||
|
|
||||||
on:
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
push:
|
push:
|
||||||
branches: [ main ]
|
branches: [ main ]
|
||||||
|
|
||||||
@@ -13,14 +14,14 @@ jobs:
|
|||||||
postgres:
|
postgres:
|
||||||
image: postgres:16-alpine
|
image: postgres:16-alpine
|
||||||
env:
|
env:
|
||||||
POSTGRES_USER: test_user
|
POSTGRES_USER: ${{ secrets.TEST_PG_USER }}
|
||||||
POSTGRES_PASSWORD: test_password
|
POSTGRES_PASSWORD: ${{ secrets.TEST_PG_USER_PASSWORD }}
|
||||||
POSTGRES_DB: test_db
|
POSTGRES_DB: ${{ secrets.TEST_PG_DATABASE }}
|
||||||
ports:
|
ports:
|
||||||
- 5433:5432
|
- ${{ secrets.TEST_PG_PORT }}:5432
|
||||||
# Ensure Postgres is completely booted before running tests
|
# Ensure Postgres is completely booted before running tests
|
||||||
options: >-
|
options: >-
|
||||||
--health-cmd "pg_isready -U test_user -d test_db"
|
--health-cmd "pg_isready -U ${{ secrets.TEST_PG_USER }} -d ${{ secrets.TEST_PG_DATABASE }}"
|
||||||
--health-interval 10s
|
--health-interval 10s
|
||||||
--health-timeout 5s
|
--health-timeout 5s
|
||||||
--health-retries 5
|
--health-retries 5
|
||||||
@@ -47,7 +48,7 @@ jobs:
|
|||||||
working-directory: ./api
|
working-directory: ./api
|
||||||
run: npx dbmate up
|
run: npx dbmate up
|
||||||
env:
|
env:
|
||||||
DATABASE_URL: "postgres://test_user:test_password@saber.home.lan:5433/test_db?sslmode=disable"
|
DATABASE_URL: "postgres://${{ secrets.TEST_PG_USER }}:${{ secrets.TEST_PG_USER_PASSWORD }}@${{ secrets.TEST_PG_HOST }}:${{ secrets.TEST_PG_PORT }}/${{ secrets.TEST_PG_DATABASE }}?sslmode=disable"
|
||||||
|
|
||||||
# - name: Generate PgTyped Types
|
# - name: Generate PgTyped Types
|
||||||
# run: npm run pgtyped:compile
|
# run: npm run pgtyped:compile
|
||||||
@@ -73,7 +74,7 @@ jobs:
|
|||||||
sudo curl -fsSL -o /usr/local/bin/dbmate https://github.com && sudo chmod +x /usr/local/bin/dbmate
|
sudo curl -fsSL -o /usr/local/bin/dbmate https://github.com && sudo chmod +x /usr/local/bin/dbmate
|
||||||
npx dbmate up
|
npx dbmate up
|
||||||
env:
|
env:
|
||||||
DATABASE_URL: "postgres://${{ secrets.INTERNAL_PG_USER }}:${{ secrets.INTERNAL_PG_USER_PASSWORD }}@${{ secrets.INTERNAL_PG_HOST }}:${{ secrets.INTERNAL_PG_PORT }}/${{ secrets.INTERNAL_PG_DATABASE }}"
|
DATABASE_URL: "postgres://${{ vars.INTERNAL_PG_USER }}:${{ secrets.INTERNAL_PG_USER_PASSWORD }}@${{ vars.INTERNAL_PG_HOST }}:${{ secrets.INTERNAL_PG_PORT }}/${{ vars.INTERNAL_PG_DATABASE }}?sslmode=disable"
|
||||||
|
|
||||||
# # 2. Deploy your application code (Example: Rebuilding a local container)
|
# # 2. Deploy your application code (Example: Rebuilding a local container)
|
||||||
# - name: Deploy Container to Internal Server via SSH
|
# - name: Deploy Container to Internal Server via SSH
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
-- migrate:up
|
||||||
|
CREATE TABLE users (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
username TEXT UNIQUE NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
id VARCHAR(64) PRIMARY KEY,
|
||||||
|
user_id INT REFERENCES users(id) ON DELETE CASCADE NOT NULL,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_sessions_expires_at ON sessions(expires_at);
|
||||||
|
|
||||||
|
-- migrate:down
|
||||||
|
DROP TABLE sessions;
|
||||||
|
DROP TABLE users;
|
||||||
|
|
||||||
+92
-1
@@ -73,6 +73,50 @@ CREATE TABLE public.schema_migrations (
|
|||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Name: sessions; Type: TABLE; Schema: public; Owner: -
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE public.sessions (
|
||||||
|
id character varying(64) NOT NULL,
|
||||||
|
user_id integer NOT NULL,
|
||||||
|
expires_at timestamp with time zone NOT NULL,
|
||||||
|
created_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Name: users; Type: TABLE; Schema: public; Owner: -
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE TABLE public.users (
|
||||||
|
id integer NOT NULL,
|
||||||
|
username text NOT NULL,
|
||||||
|
password_hash text NOT NULL,
|
||||||
|
created_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Name: users_id_seq; Type: SEQUENCE; Schema: public; Owner: -
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE SEQUENCE public.users_id_seq
|
||||||
|
AS integer
|
||||||
|
START WITH 1
|
||||||
|
INCREMENT BY 1
|
||||||
|
NO MINVALUE
|
||||||
|
NO MAXVALUE
|
||||||
|
CACHE 1;
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Name: users_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
|
||||||
|
--
|
||||||
|
|
||||||
|
ALTER SEQUENCE public.users_id_seq OWNED BY public.users.id;
|
||||||
|
|
||||||
|
|
||||||
--
|
--
|
||||||
-- Name: categories id; Type: DEFAULT; Schema: public; Owner: -
|
-- Name: categories id; Type: DEFAULT; Schema: public; Owner: -
|
||||||
--
|
--
|
||||||
@@ -80,6 +124,13 @@ CREATE TABLE public.schema_migrations (
|
|||||||
ALTER TABLE ONLY public.categories ALTER COLUMN id SET DEFAULT nextval('public.categories_id_seq'::regclass);
|
ALTER TABLE ONLY public.categories ALTER COLUMN id SET DEFAULT nextval('public.categories_id_seq'::regclass);
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Name: users id; Type: DEFAULT; Schema: public; Owner: -
|
||||||
|
--
|
||||||
|
|
||||||
|
ALTER TABLE ONLY public.users ALTER COLUMN id SET DEFAULT nextval('public.users_id_seq'::regclass);
|
||||||
|
|
||||||
|
|
||||||
--
|
--
|
||||||
-- Name: categories categories_pkey; Type: CONSTRAINT; Schema: public; Owner: -
|
-- Name: categories categories_pkey; Type: CONSTRAINT; Schema: public; Owner: -
|
||||||
--
|
--
|
||||||
@@ -96,6 +147,30 @@ ALTER TABLE ONLY public.schema_migrations
|
|||||||
ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (version);
|
ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (version);
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Name: sessions sessions_pkey; Type: CONSTRAINT; Schema: public; Owner: -
|
||||||
|
--
|
||||||
|
|
||||||
|
ALTER TABLE ONLY public.sessions
|
||||||
|
ADD CONSTRAINT sessions_pkey PRIMARY KEY (id);
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Name: users users_pkey; Type: CONSTRAINT; Schema: public; Owner: -
|
||||||
|
--
|
||||||
|
|
||||||
|
ALTER TABLE ONLY public.users
|
||||||
|
ADD CONSTRAINT users_pkey PRIMARY KEY (id);
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Name: users users_username_key; Type: CONSTRAINT; Schema: public; Owner: -
|
||||||
|
--
|
||||||
|
|
||||||
|
ALTER TABLE ONLY public.users
|
||||||
|
ADD CONSTRAINT users_username_key UNIQUE (username);
|
||||||
|
|
||||||
|
|
||||||
--
|
--
|
||||||
-- Name: idx_categories_path_gist; Type: INDEX; Schema: public; Owner: -
|
-- Name: idx_categories_path_gist; Type: INDEX; Schema: public; Owner: -
|
||||||
--
|
--
|
||||||
@@ -103,6 +178,21 @@ ALTER TABLE ONLY public.schema_migrations
|
|||||||
CREATE INDEX idx_categories_path_gist ON public.categories USING gist (path);
|
CREATE INDEX idx_categories_path_gist ON public.categories USING gist (path);
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Name: idx_sessions_expires_at; Type: INDEX; Schema: public; Owner: -
|
||||||
|
--
|
||||||
|
|
||||||
|
CREATE INDEX idx_sessions_expires_at ON public.sessions USING btree (expires_at);
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Name: sessions sessions_user_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
|
||||||
|
--
|
||||||
|
|
||||||
|
ALTER TABLE ONLY public.sessions
|
||||||
|
ADD CONSTRAINT sessions_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE;
|
||||||
|
|
||||||
|
|
||||||
--
|
--
|
||||||
-- PostgreSQL database dump complete
|
-- PostgreSQL database dump complete
|
||||||
--
|
--
|
||||||
@@ -115,4 +205,5 @@ CREATE INDEX idx_categories_path_gist ON public.categories USING gist (path);
|
|||||||
--
|
--
|
||||||
|
|
||||||
INSERT INTO public.schema_migrations (version) VALUES
|
INSERT INTO public.schema_migrations (version) VALUES
|
||||||
('20260824235922');
|
('20260824235922'),
|
||||||
|
('20260829174406');
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { Pool } from 'pg';
|
||||||
|
import { createAuthMiddleware } from './auth.middleware.ts';
|
||||||
|
|
||||||
|
function createMockResponse() {
|
||||||
|
const res: Partial<Response> = {};
|
||||||
|
const data = { statusCode: 200, jsonPayload: null as any };
|
||||||
|
|
||||||
|
res.status = function (code: number) { data.statusCode = code; return this as Response; };
|
||||||
|
res.json = function (payload: any) { data.jsonPayload = payload; return this as Response; };
|
||||||
|
return { mockRes: res as Response, data };
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMockDb(sessionRow: any) {
|
||||||
|
return {
|
||||||
|
query: async (text: string, values: any[]) => {
|
||||||
|
return { rows: sessionRow ? [sessionRow] : [] };
|
||||||
|
}
|
||||||
|
} as unknown as Pool;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Auth Middleware (TDD)', () => {
|
||||||
|
it('should return 401 Unauthorized if no session cookie is attached to the request', async () => {
|
||||||
|
const mockDb = createMockDb(null);
|
||||||
|
const middleware = createAuthMiddleware(mockDb);
|
||||||
|
|
||||||
|
const mockReq = { headers: {} } as unknown as Request; // Missing header/cookie structures
|
||||||
|
const { mockRes, data } = createMockResponse();
|
||||||
|
let nextCalled = false;
|
||||||
|
|
||||||
|
await middleware(mockReq, mockRes, () => { nextCalled = true; });
|
||||||
|
|
||||||
|
assert.equal(data.statusCode, 401);
|
||||||
|
assert.equal(data.jsonPayload.success, false);
|
||||||
|
assert.equal(nextCalled, false); // Blocked early
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return 401 Unauthorized if the session token has expired', async () => {
|
||||||
|
// Return a mock session row that expired 1 hour ago
|
||||||
|
const pastDate = new Date(Date.now() - 3600000);
|
||||||
|
const mockDb = createMockDb({ user_id: 1, expires_at: pastDate });
|
||||||
|
const middleware = createAuthMiddleware(mockDb);
|
||||||
|
|
||||||
|
// Simulate an Express request passing an expired cookie string
|
||||||
|
const mockReq = {
|
||||||
|
headers: { cookie: 'session_token=expired-token-string' }
|
||||||
|
} as unknown as Request;
|
||||||
|
|
||||||
|
const { mockRes, data } = createMockResponse();
|
||||||
|
let nextCalled = false;
|
||||||
|
|
||||||
|
await middleware(mockReq, mockRes, () => { nextCalled = true; });
|
||||||
|
|
||||||
|
assert.equal(data.statusCode, 401);
|
||||||
|
assert.equal(nextCalled, false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
import { Pool } from 'pg';
|
||||||
|
|
||||||
|
// Helper utility to parse cookies manually without adding extra npm packages
|
||||||
|
function parseCookieString(cookieHeader: string | undefined, name: string): string | null {
|
||||||
|
if (!cookieHeader) return null;
|
||||||
|
const match = cookieHeader.match(new RegExp('(^| )' + name + '=([^;]+)'));
|
||||||
|
return match ? match[2] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAuthMiddleware(db: Pool) {
|
||||||
|
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const cookieHeader = req.headers.cookie;
|
||||||
|
const token = parseCookieString(cookieHeader, 'session_token');
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
res.status(401).json({ success: false, error: 'Unauthorized. Session cookie missing.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Query the database to find an active session matching the token
|
||||||
|
const query = `
|
||||||
|
SELECT user_id, expires_at
|
||||||
|
FROM sessions
|
||||||
|
WHERE id = $1;
|
||||||
|
`;
|
||||||
|
const result = await db.query(query, [token]);
|
||||||
|
|
||||||
|
if (result.rows.length === 0) {
|
||||||
|
res.status(401).json({ success: false, error: 'Unauthorized. Invalid session token.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = result.rows[0];
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
// Validate expiration constraint
|
||||||
|
if (new Date(session.expires_at) < now) {
|
||||||
|
res.status(401).json({ success: false, error: 'Unauthorized. Session expired.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inject the authenticated identity directly into the Request object for use in down-stream router handlers
|
||||||
|
(req as any).userId = session.user_id;
|
||||||
|
|
||||||
|
next(); // Execution matches, pass cleanly to route target
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Auth middleware failure:', error);
|
||||||
|
res.status(500).json({ success: false, error: 'Internal Server Error' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createAuthRouter } from './auth.router.ts';
|
||||||
|
import { AuthService } from './auth.service.ts';
|
||||||
|
import { Pool } from 'pg';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
|
||||||
|
function createMockResponse() {
|
||||||
|
const res: Partial<Response> = {};
|
||||||
|
const data = { statusCode: 200, jsonPayload: null as any, cookies: {} as any };
|
||||||
|
|
||||||
|
res.status = function (code: number) { data.statusCode = code; return this as Response; };
|
||||||
|
res.json = function (payload: any) { data.jsonPayload = payload; return this as Response; };
|
||||||
|
res.cookie = function (name: string, val: string, options: any) {
|
||||||
|
data.cookies[name] = { val, options };
|
||||||
|
return this as Response;
|
||||||
|
};
|
||||||
|
return { mockRes: res as Response, data };
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMockDb(userRows: any[], sessionRows: any[] = []) {
|
||||||
|
return {
|
||||||
|
query: async (text: string, values: any[]) => {
|
||||||
|
if (text.trim().startsWith('SELECT') && text.includes('FROM users')) {
|
||||||
|
return { rows: userRows };
|
||||||
|
}
|
||||||
|
return { rows: sessionRows };
|
||||||
|
}
|
||||||
|
} as unknown as Pool;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Auth Router (TDD)', () => {
|
||||||
|
const authService = new AuthService();
|
||||||
|
|
||||||
|
describe('POST /register', () => {
|
||||||
|
it('should block registrations missing username or password with a 400 status', async () => {
|
||||||
|
const mockDb = createMockDb([]);
|
||||||
|
const router = createAuthRouter(mockDb, authService);
|
||||||
|
|
||||||
|
const mockReq = { body: { username: '' } } as unknown as Request;
|
||||||
|
const { mockRes, data } = createMockResponse();
|
||||||
|
|
||||||
|
const handler = router.stack.find((l: any) => l.route.path === '/register').route.stack[0].handle;
|
||||||
|
await handler(mockReq, mockRes);
|
||||||
|
|
||||||
|
assert.equal(data.statusCode, 400);
|
||||||
|
assert.equal(data.jsonPayload.success, false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /login', () => {
|
||||||
|
it('should successfully issue a high-entropy cookie on valid credentials', async () => {
|
||||||
|
const password = 'secure-password';
|
||||||
|
const hash = await authService.hashPassword(password);
|
||||||
|
|
||||||
|
// Simulate database finding the registered user
|
||||||
|
const mockDb = createMockDb([{ id: 42, username: 'testuser', password_hash: hash }]);
|
||||||
|
const router = createAuthRouter(mockDb, authService);
|
||||||
|
|
||||||
|
const mockReq = { body: { username: 'testuser', password } } as unknown as Request;
|
||||||
|
const { mockRes, data } = createMockResponse();
|
||||||
|
|
||||||
|
const handler = router.stack.find((l: any) => l.route.path === '/login').route.stack[0].handle;
|
||||||
|
await handler(mockReq, mockRes);
|
||||||
|
|
||||||
|
assert.equal(data.statusCode, 200);
|
||||||
|
assert.equal(data.jsonPayload.success, true);
|
||||||
|
assert.ok(data.cookies['session_token']);
|
||||||
|
assert.equal(data.cookies['session_token'].options.httpOnly, true);
|
||||||
|
assert.equal(data.cookies['session_token'].options.sameSite, 'strict');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject invalid passwords with a 401 status code', async () => {
|
||||||
|
const hash = await authService.hashPassword('real-password');
|
||||||
|
const mockDb = createMockDb([{ id: 42, username: 'testuser', password_hash: hash }]);
|
||||||
|
const router = createAuthRouter(mockDb, authService);
|
||||||
|
|
||||||
|
const mockReq = { body: { username: 'testuser', password: 'wrong-password' } } as unknown as Request;
|
||||||
|
const { mockRes, data } = createMockResponse();
|
||||||
|
|
||||||
|
const handler = router.stack.find((l: any) => l.route.path === '/login').route.stack[0].handle;
|
||||||
|
await handler(mockReq, mockRes);
|
||||||
|
|
||||||
|
assert.equal(data.statusCode, 401);
|
||||||
|
assert.equal(data.jsonPayload.success, false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { Router, Request, Response } from 'express';
|
||||||
|
import { Pool } from 'pg';
|
||||||
|
import { AuthService } from './auth.service.ts';
|
||||||
|
|
||||||
|
export function createAuthRouter(db: Pool, authService: AuthService): Router {
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/auth/register
|
||||||
|
*/
|
||||||
|
router.post('/register', async (req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const { username, password } = req.body;
|
||||||
|
|
||||||
|
if (!username || !password || username.trim() === '' || password.length < 8) {
|
||||||
|
res.status(400).json({ success: false, error: 'Username required, and password must be at least 8 characters long.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if user already exists
|
||||||
|
const checkUser = await db.query('SELECT id FROM users WHERE username = $1;', [username]);
|
||||||
|
if (checkUser.rows.length > 0) {
|
||||||
|
res.status(409).json({ success: false, error: 'Username is already taken.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash password using Argon2id
|
||||||
|
const hash = await authService.hashPassword(password);
|
||||||
|
|
||||||
|
// Save user
|
||||||
|
await db.query('INSERT INTO users (username, password_hash) VALUES ($1, $2);', [username, hash]);
|
||||||
|
|
||||||
|
res.status(201).json({ success: true, message: 'User registered successfully!' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Registration failure:', error);
|
||||||
|
res.status(500).json({ success: false, error: 'Internal Server Error' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/auth/login
|
||||||
|
*/
|
||||||
|
router.post('/login', async (req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const { username, password } = req.body;
|
||||||
|
|
||||||
|
if (!username || !password) {
|
||||||
|
res.status(400).json({ success: false, error: 'Username and password are required.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await db.query('SELECT id, password_hash FROM users WHERE username = $1;', [username]);
|
||||||
|
if (result.rows.length === 0) {
|
||||||
|
res.status(401).json({ success: false, error: 'Invalid username or password.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = result.rows[0];
|
||||||
|
const validPassword = await authService.verifyPassword(password, user.password_hash);
|
||||||
|
|
||||||
|
if (!validPassword) {
|
||||||
|
res.status(401).json({ success: false, error: 'Invalid username or password.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate a high-entropy session token
|
||||||
|
const sessionToken = authService.generateSessionToken();
|
||||||
|
const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // Expires in 30 days
|
||||||
|
|
||||||
|
// Store the session securely in the database
|
||||||
|
await db.query(
|
||||||
|
'INSERT INTO sessions (id, user_id, expires_at) VALUES ($1, $2, $3);',
|
||||||
|
[sessionToken, user.id, expiresAt]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Issue the secure HttpOnly cookie
|
||||||
|
res.cookie('session_token', sessionToken, {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: process.env.NODE_ENV === 'production', // Requires HTTPS in production
|
||||||
|
sameSite: 'strict',
|
||||||
|
expires: expiresAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({ success: true, message: 'Logged in successfully!' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Login failure:', error);
|
||||||
|
res.status(500).json({ success: false, error: 'Internal Server Error' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return router;
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { AuthService } from './auth.service.ts';
|
||||||
|
|
||||||
|
describe('AuthService (TDD)', () => {
|
||||||
|
const authService = new AuthService();
|
||||||
|
|
||||||
|
describe('Password Hashing & Verification', () => {
|
||||||
|
it('should hash a raw password string and verify it successfully', async () => {
|
||||||
|
const password = 'my-super-secure-password';
|
||||||
|
const hash = await authService.hashPassword(password);
|
||||||
|
|
||||||
|
// Verify the hash is distinct and obfuscated
|
||||||
|
assert.notEqual(hash, password);
|
||||||
|
assert.ok(hash.startsWith('$argon2id$')); // Confirms it uses the Argon2id standard
|
||||||
|
|
||||||
|
// Verify correct verification resolves true
|
||||||
|
const isValid = await authService.verifyPassword(password, hash);
|
||||||
|
assert.equal(isValid, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject validation if the password string does not match the hash', async () => {
|
||||||
|
const hash = await authService.hashPassword('correct-password');
|
||||||
|
const isValid = await authService.verifyPassword('wrong-password', hash);
|
||||||
|
assert.equal(isValid, false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Session Token Generation', () => {
|
||||||
|
it('should generate high-entropy random session tokens', () => {
|
||||||
|
const token1 = authService.generateSessionToken();
|
||||||
|
const token2 = authService.generateSessionToken();
|
||||||
|
|
||||||
|
assert.equal(typeof token1, 'string');
|
||||||
|
assert.equal(token1.length, 64); // Uses a 32-byte hex representation
|
||||||
|
assert.notEqual(token1, token2); // Tokens must never collide
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import argon2 from 'argon2';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
|
||||||
|
export class AuthService {
|
||||||
|
/**
|
||||||
|
* Hashes a raw password using the Argon2id industry standard.
|
||||||
|
*/
|
||||||
|
async hashPassword(password: string): Promise<string> {
|
||||||
|
return argon2.hash(password, {
|
||||||
|
type: argon2.argon2id, // Strongest configuration variant against timing attacks
|
||||||
|
memoryCost: 2 ** 16, // 64MB memory utilization block
|
||||||
|
timeCost: 3, // 3 computational passes
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cryptographically verifies a password against a known hash.
|
||||||
|
*/
|
||||||
|
async verifyPassword(password: string, hash: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
return await argon2.verify(hash, password);
|
||||||
|
} catch {
|
||||||
|
return false; // Safely catches malformed hashes without crashing
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a unique, high-entropy 64-character hex session token.
|
||||||
|
*/
|
||||||
|
generateSessionToken(): string {
|
||||||
|
return crypto.randomBytes(32).toString('hex');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,7 +32,7 @@ describe('CategoryRepository - Live Database Integration Tests', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should fetch all deep descendants using the <@ ltree operator', async () => {
|
it('should fetch all deep descendants using the <@ ltree operator', async () => {
|
||||||
const results = await repository.findAllDescendants('Top.Science');
|
const results = await repository.findAllDescendants('Top.Science', 0);
|
||||||
|
|
||||||
// Should return Science, Astronomy, and Astrophysics (3 nodes)
|
// Should return Science, Astronomy, and Astrophysics (3 nodes)
|
||||||
assert.equal(results.length, 3);
|
assert.equal(results.length, 3);
|
||||||
|
|||||||
@@ -14,14 +14,15 @@ export class CategoryRepository {
|
|||||||
* Finds all descendants of a given path (including the path itself).
|
* Finds all descendants of a given path (including the path itself).
|
||||||
* Uses the ltree operator <@ (is-descendant-of).
|
* Uses the ltree operator <@ (is-descendant-of).
|
||||||
*/
|
*/
|
||||||
async findAllDescendants(parentPath: string): Promise<CategoryNode[]> {
|
async findAllDescendants(parentPath: string, userId: number): Promise<CategoryNode[]> {
|
||||||
const query = `
|
const query = `
|
||||||
SELECT id, name, path
|
SELECT id, name, path
|
||||||
FROM categories
|
FROM categories
|
||||||
WHERE path <@ $1::ltree
|
WHERE path <@ $1::ltree
|
||||||
|
AND user_id = $2 --
|
||||||
ORDER BY path ASC;
|
ORDER BY path ASC;
|
||||||
`;
|
`;
|
||||||
const result = await this.db.query(query, [parentPath]);
|
const result = await this.db.query(query, [parentPath, userId]);
|
||||||
return result.rows;
|
return result.rows;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { describe, it } from 'node:test';
|
import { describe, it } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
|
import { Pool } from 'pg';
|
||||||
import { createCategoryRouter } from './category.router.ts';
|
import { createCategoryRouter } from './category.router.ts';
|
||||||
import { CategoryRepository } from './category.repository.ts';
|
import { CategoryRepository } from './category.repository.ts';
|
||||||
import { Request, Response } from 'express';
|
import { Request, Response } from 'express';
|
||||||
@@ -45,11 +46,15 @@ function getRouteHandler(router: any): Function {
|
|||||||
return routeLayer.route.stack[0].handle; // Target the primary callback handler array element
|
return routeLayer.route.stack[0].handle; // Target the primary callback handler array element
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const pool = new Pool({
|
||||||
|
connectionString: process.env.DATABASE_URL || process.env.INTERNAL_PROD_DB_URL
|
||||||
|
});
|
||||||
|
|
||||||
describe('Category Router Endpoints', () => {
|
describe('Category Router Endpoints', () => {
|
||||||
|
|
||||||
it('GET /tree{/:path} - should return 200 and structural JSON array data on valid requests', async () => {
|
it('GET /tree{/:path} - should return 200 and structural JSON array data on valid requests', async () => {
|
||||||
const mockRepo = createMockRepository('success');
|
const mockRepo = createMockRepository('success');
|
||||||
const router = createCategoryRouter(mockRepo);
|
const router = createCategoryRouter(mockRepo, pool);
|
||||||
|
|
||||||
const mockReq = { params: { path: 'Top' } } as unknown as Request;
|
const mockReq = { params: { path: 'Top' } } as unknown as Request;
|
||||||
const { mockRes, data } = createMockResponse();
|
const { mockRes, data } = createMockResponse();
|
||||||
@@ -67,7 +72,7 @@ describe('Category Router Endpoints', () => {
|
|||||||
|
|
||||||
it('GET /tree{/:path} - should return 400 Bad Request if ltree path contains malformed formatting', async () => {
|
it('GET /tree{/:path} - should return 400 Bad Request if ltree path contains malformed formatting', async () => {
|
||||||
const mockRepo = createMockRepository('success');
|
const mockRepo = createMockRepository('success');
|
||||||
const router = createCategoryRouter(mockRepo);
|
const router = createCategoryRouter(mockRepo, pool);
|
||||||
|
|
||||||
const mockReq = { params: { path: 'Top.Bad Path!' } } as unknown as Request;
|
const mockReq = { params: { path: 'Top.Bad Path!' } } as unknown as Request;
|
||||||
const { mockRes, data } = createMockResponse();
|
const { mockRes, data } = createMockResponse();
|
||||||
|
|||||||
@@ -1,18 +1,23 @@
|
|||||||
import { Router, Request, Response } from 'express';
|
import { Router, Request, Response } from 'express';
|
||||||
import { CategoryRepository } from './category.repository.ts';
|
import { CategoryRepository } from './category.repository.ts';
|
||||||
import { buildCategoryTree } from './tree.utility.ts';
|
import { buildCategoryTree } from './tree.utility.ts';
|
||||||
|
import { createAuthMiddleware } from './auth.middleware.ts';
|
||||||
|
import { Pool } from 'pg';
|
||||||
|
|
||||||
// Clean regex pattern matching valid Postgres ltree structures
|
// Clean regex pattern matching valid Postgres ltree structures
|
||||||
const LTREE_REGEX = /^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$/;
|
const LTREE_REGEX = /^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$/;
|
||||||
|
|
||||||
export function createCategoryRouter(repository: CategoryRepository): Router {
|
export function createCategoryRouter(repository: CategoryRepository, db: Pool): Router {
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
const auth = createAuthMiddleware(db);
|
||||||
|
|
||||||
router.get('/tree{/:path}', async (req: Request, res: Response): Promise<void> => {
|
router.get('/tree{/:path}', auth, async (req: Request, res: Response): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
const rawPath = req.params.path;
|
const rawPath = req.params.path;
|
||||||
const parentPath = Array.isArray(rawPath) ? rawPath[0] : (rawPath || 'Top');
|
const parentPath = Array.isArray(rawPath) ? rawPath[0] : (rawPath || 'Top');
|
||||||
|
|
||||||
|
const userId = (req as any).userId;
|
||||||
|
|
||||||
// 1. INPUT VALIDATION: Stop malicious or broken ltree strings early
|
// 1. INPUT VALIDATION: Stop malicious or broken ltree strings early
|
||||||
if (!LTREE_REGEX.test(parentPath)) {
|
if (!LTREE_REGEX.test(parentPath)) {
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
@@ -22,7 +27,7 @@ export function createCategoryRouter(repository: CategoryRepository): Router {
|
|||||||
return; // Break execution early
|
return; // Break execution early
|
||||||
}
|
}
|
||||||
|
|
||||||
const flatRows = await repository.findAllDescendants(parentPath);
|
const flatRows = await repository.findAllDescendants(parentPath, userId);
|
||||||
const nestedTree = flatRows.length > 0 ? buildCategoryTree(flatRows) : [];
|
const nestedTree = flatRows.length > 0 ? buildCategoryTree(flatRows) : [];
|
||||||
|
|
||||||
res.json({ success: true, data: nestedTree });
|
res.json({ success: true, data: nestedTree });
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ import { CategoryRepository } from './category.repository.ts';
|
|||||||
import { createCategoryRouter } from './category.router.ts';
|
import { createCategoryRouter } from './category.router.ts';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import process from 'node:process';
|
import process from 'node:process';
|
||||||
|
import { createAuthRouter } from './auth.router.ts';
|
||||||
|
import { AuthService } from './auth.service.ts';
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
process.loadEnvFile(join(import.meta.dirname, '../.env'));
|
process.loadEnvFile(join(import.meta.dirname, '../.env'));
|
||||||
@@ -13,6 +16,7 @@ try {
|
|||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const port = process.env.API_PORT || 8300;
|
const port = process.env.API_PORT || 8300;
|
||||||
|
const authService = new AuthService();
|
||||||
|
|
||||||
// Initialize your database pool
|
// Initialize your database pool
|
||||||
const pool = new Pool({
|
const pool = new Pool({
|
||||||
@@ -20,6 +24,7 @@ const pool = new Pool({
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
app.use('/api/auth', createAuthRouter(pool, authService));
|
||||||
|
|
||||||
// Inject the database pool into the repository layer
|
// Inject the database pool into the repository layer
|
||||||
const categoryRepository = new CategoryRepository(pool);
|
const categoryRepository = new CategoryRepository(pool);
|
||||||
|
|||||||
Reference in new issue
Block a user