Compare commits

...
23 Commits
Author SHA1 Message Date
chris add7c430b3 Alter INTERNAL_PG_USER from secret to var
CI/CD Pipeline / test (push) Successful in 28s
CI/CD Pipeline / deploy-internal (push) Successful in 9s
2026-09-30 11:08:28 -04:00
chris 5e48caf791 Change secrets to vars
CI/CD Pipeline / test (push) Successful in 30s
CI/CD Pipeline / deploy-internal (push) Failing after 10s
2026-09-30 10:46:13 -04:00
chris ec5924fda9 Add auth router and service to api index
CI/CD Pipeline / test (push) Successful in 29s
CI/CD Pipeline / deploy-internal (push) Successful in 10s
2026-09-30 09:44:48 -04:00
chris 3d7be239d6 Add auth.middleware and Pool to category router 2026-09-30 09:44:23 -04:00
chris f27d87531c Add auth role to api 2026-09-30 09:43:54 -04:00
chris 9a476d9b86 Add import and use of Pool from pg 2026-09-30 09:41:28 -04:00
chris c7ee1ec01e Update findAllDescendants function signature 2026-09-30 09:40:22 -04:00
chris 1e57851111 Add userid number to findAllDescendants call 2026-09-30 09:39:36 -04:00
chris e08667927d Add sessions, users tables to schema 2026-09-30 09:36:42 -04:00
chris b87441260f Disable sslmode on internal deployment task
CI/CD Pipeline / deploy-internal (push) Failing after 9s
CI/CD Pipeline / test (push) Successful in 30s
2026-09-25 13:49:31 -04:00
chris df30510ff2 Retry host secret with exposed port
CI/CD Pipeline / test (push) Successful in 30s
CI/CD Pipeline / deploy-internal (push) Failing after 9s
2026-09-25 13:46:53 -04:00
chris 17d179618b Revert to previous and fix error in URL
CI/CD Pipeline / test (push) Failing after 28s
CI/CD Pipeline / deploy-internal (push) Skipped
2026-09-25 13:34:00 -04:00
chris 62c0f4e445 Remove network, ignored; use 127.0.0.1
CI/CD Pipeline / test (push) Failing after 27s
CI/CD Pipeline / deploy-internal (push) Skipped
2026-09-25 13:27:52 -04:00
chris de4fc9bf9e Add container network for visibility
CI/CD Pipeline / test (push) Failing after 29s
CI/CD Pipeline / deploy-internal (push) Skipped
2026-09-25 13:24:15 -04:00
chris befdacb50b Alter host to point to worflow service
CI/CD Pipeline / test (push) Failing after 29s
CI/CD Pipeline / deploy-internal (push) Skipped
2026-09-25 13:15:17 -04:00
chris cb1cf425f1 Add missing $ for variable expansion
CI/CD Pipeline / test (push) Failing after 27s
CI/CD Pipeline / deploy-internal (push) Skipped
2026-09-25 13:10:38 -04:00
chris 19268ae00f Alter target host
CI/CD Pipeline / test (push) Failing after 29s
CI/CD Pipeline / deploy-internal (push) Skipped
2026-09-25 13:07:52 -04:00
chris 868b91e440 Fix pg password variable name
CI/CD Pipeline / test (push) Failing after 28s
CI/CD Pipeline / deploy-internal (push) Skipped
2026-09-25 13:05:46 -04:00
chris 6755bf05fa Add variables for test database
CI/CD Pipeline / test (push) Failing after 5m1s
CI/CD Pipeline / deploy-internal (push) Skipped
2026-09-25 12:59:07 -04:00
chris 2e217a23d7 Add manual trigger option for testing without commit
CI/CD Pipeline / test (push) Failing after 27s
CI/CD Pipeline / deploy-internal (push) Skipped
2026-09-25 12:37:21 -04:00
chris 28d1805470 Update CI/CD with new secrets
CI/CD Pipeline / test (push) Failing after 42s
CI/CD Pipeline / deploy-internal (push) Skipped
2026-09-25 10:47:08 -04:00
chris 3c0106e97e Refresh modules and add auth dependencies 2026-08-29 13:40:51 -04:00
chris 1457029985 First complied tailwind file 2026-08-29 13:38:06 -04:00
18 changed files with 1095 additions and 17 deletions

No files matched your search

+8 -7
View File
@@ -1,6 +1,7 @@
name: CI/CD Pipeline
on:
workflow_dispatch:
push:
branches: [ main ]
@@ -13,14 +14,14 @@ jobs:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: test_user
POSTGRES_PASSWORD: test_password
POSTGRES_DB: test_db
POSTGRES_USER: ${{ secrets.TEST_PG_USER }}
POSTGRES_PASSWORD: ${{ secrets.TEST_PG_USER_PASSWORD }}
POSTGRES_DB: ${{ secrets.TEST_PG_DATABASE }}
ports:
- 5433:5432
- ${{ secrets.TEST_PG_PORT }}:5432
# Ensure Postgres is completely booted before running tests
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-timeout 5s
--health-retries 5
@@ -47,7 +48,7 @@ jobs:
working-directory: ./api
run: npx dbmate up
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
# 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
npx dbmate up
env:
DATABASE_URL: ${{ secrets.INTERNAL_PROD_DB_URL }}
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)
# - 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
View File
@@ -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: -
--
@@ -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);
--
-- 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: -
--
@@ -96,6 +147,30 @@ ALTER TABLE ONLY public.schema_migrations
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: -
--
@@ -103,6 +178,21 @@ ALTER TABLE ONLY public.schema_migrations
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
--
@@ -115,4 +205,5 @@ CREATE INDEX idx_categories_path_gist ON public.categories USING gist (path);
--
INSERT INTO public.schema_migrations (version) VALUES
('20260824235922');
('20260824235922'),
('20260829174406');
+59
View File
@@ -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);
});
});
+53
View File
@@ -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' });
}
};
}
+88
View File
@@ -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);
});
});
});
+92
View File
@@ -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;
}
+39
View File
@@ -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
});
});
});
+33
View File
@@ -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');
}
}
+1 -1
View File
@@ -32,7 +32,7 @@ describe('CategoryRepository - Live Database Integration Tests', () => {
});
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)
assert.equal(results.length, 3);
+3 -2
View File
@@ -14,14 +14,15 @@ export class CategoryRepository {
* Finds all descendants of a given path (including the path itself).
* Uses the ltree operator <@ (is-descendant-of).
*/
async findAllDescendants(parentPath: string): Promise<CategoryNode[]> {
async findAllDescendants(parentPath: string, userId: number): Promise<CategoryNode[]> {
const query = `
SELECT id, name, path
FROM categories
WHERE path <@ $1::ltree
AND user_id = $2 --
ORDER BY path ASC;
`;
const result = await this.db.query(query, [parentPath]);
const result = await this.db.query(query, [parentPath, userId]);
return result.rows;
}
+7 -2
View File
@@ -1,5 +1,6 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { Pool } from 'pg';
import { createCategoryRouter } from './category.router.ts';
import { CategoryRepository } from './category.repository.ts';
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
}
const pool = new Pool({
connectionString: process.env.DATABASE_URL || process.env.INTERNAL_PROD_DB_URL
});
describe('Category Router Endpoints', () => {
it('GET /tree{/:path} - should return 200 and structural JSON array data on valid requests', async () => {
const mockRepo = createMockRepository('success');
const router = createCategoryRouter(mockRepo);
const router = createCategoryRouter(mockRepo, pool);
const mockReq = { params: { path: 'Top' } } as unknown as Request;
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 () => {
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 { mockRes, data } = createMockResponse();
+8 -3
View File
@@ -1,18 +1,23 @@
import { Router, Request, Response } from 'express';
import { CategoryRepository } from './category.repository.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
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 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 {
const rawPath = req.params.path;
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
if (!LTREE_REGEX.test(parentPath)) {
res.status(400).json({
@@ -22,7 +27,7 @@ export function createCategoryRouter(repository: CategoryRepository): Router {
return; // Break execution early
}
const flatRows = await repository.findAllDescendants(parentPath);
const flatRows = await repository.findAllDescendants(parentPath, userId);
const nestedTree = flatRows.length > 0 ? buildCategoryTree(flatRows) : [];
res.json({ success: true, data: nestedTree });
+5
View File
@@ -4,6 +4,9 @@ import { CategoryRepository } from './category.repository.ts';
import { createCategoryRouter } from './category.router.ts';
import { join } from 'node:path';
import process from 'node:process';
import { createAuthRouter } from './auth.router.ts';
import { AuthService } from './auth.service.ts';
try {
process.loadEnvFile(join(import.meta.dirname, '../.env'));
@@ -13,6 +16,7 @@ try {
const app = express();
const port = process.env.API_PORT || 8300;
const authService = new AuthService();
// Initialize your database pool
const pool = new Pool({
@@ -20,6 +24,7 @@ const pool = new Pool({
});
app.use(express.json());
app.use('/api/auth', createAuthRouter(pool, authService));
// Inject the database pool into the repository layer
const categoryRepository = new CategoryRepository(pool);
+1
View File
@@ -3918,6 +3918,7 @@
},
"devDependencies": {
"@tailwindcss/cli": "^4.3.3",
"@types/node": "^26.4.0",
"tailwindcss": "^4.3.3"
}
}
+3 -1
View File
@@ -13,7 +13,9 @@
"test:web": "npm run test --workspace=web"
},
"allowScripts": {
"esbuild@0.28.2": true
"esbuild@0.28.2": true,
"argon2@0.45.1": true,
"@parcel/watcher@2.5.1": true
},
"devDependencies": {
"concurrently": "^10.0.5"
+1
View File
@@ -13,6 +13,7 @@
},
"devDependencies": {
"@tailwindcss/cli": "^4.3.3",
"@types/node": "^26.4.0",
"tailwindcss": "^4.3.3"
}
}
+581
View File
@@ -0,0 +1,581 @@
/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */
@layer properties;
@layer theme, base, components, utilities;
@layer theme {
:root, :host {
--font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue",
"Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
"Segoe UI Symbol", "Noto Color Emoji";
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",
"Courier New", monospace;
--color-blue-600: oklch(54.6% 0.245 262.881);
--color-slate-50: oklch(98.4% 0.003 247.858);
--color-slate-100: oklch(96.8% 0.007 247.896);
--color-slate-200: oklch(92.9% 0.013 255.508);
--color-slate-300: oklch(86.9% 0.022 252.894);
--color-slate-400: oklch(70.4% 0.04 256.788);
--color-slate-500: oklch(55.4% 0.046 257.417);
--color-slate-700: oklch(37.2% 0.044 257.287);
--color-slate-800: oklch(27.9% 0.041 260.031);
--color-slate-900: oklch(20.8% 0.042 265.755);
--color-white: #fff;
--spacing: 0.25rem;
--container-4xl: 56rem;
--text-xs: 0.75rem;
--text-xs--line-height: calc(1 / 0.75);
--text-sm: 0.875rem;
--text-sm--line-height: calc(1.25 / 0.875);
--text-3xl: 1.875rem;
--text-3xl--line-height: calc(2.25 / 1.875);
--text-4xl: 2.25rem;
--text-4xl--line-height: calc(2.5 / 2.25);
--font-weight-medium: 500;
--font-weight-semibold: 600;
--font-weight-bold: 700;
--tracking-tight: -0.025em;
--radius-md: 0.375rem;
--radius-xl: 0.75rem;
--default-transition-duration: 150ms;
--default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
--default-font-family: var(--font-sans);
--default-mono-font-family: var(--font-mono);
}
}
@layer base {
*, ::after, ::before, ::backdrop, ::file-selector-button {
box-sizing: border-box;
margin: 0;
padding: 0;
border: 0 solid;
}
html, :host {
line-height: 1.5;
-webkit-text-size-adjust: 100%;
tab-size: 4;
font-family: var(--default-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");
font-feature-settings: var(--default-font-feature-settings, normal);
font-variation-settings: var(--default-font-variation-settings, normal);
-webkit-tap-highlight-color: transparent;
}
hr {
height: 0;
color: inherit;
border-top-width: 1px;
}
abbr:where([title]) {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
}
h1, h2, h3, h4, h5, h6 {
font-size: inherit;
font-weight: inherit;
}
a {
color: inherit;
-webkit-text-decoration: inherit;
text-decoration: inherit;
}
b, strong {
font-weight: bolder;
}
code, kbd, samp, pre {
font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);
font-feature-settings: var(--default-mono-font-feature-settings, normal);
font-variation-settings: var(--default-mono-font-variation-settings, normal);
font-size: 1em;
}
small {
font-size: 80%;
}
sub, sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
table {
text-indent: 0;
border-color: inherit;
border-collapse: collapse;
}
:-moz-focusring:where(:not(iframe)) {
outline: auto;
}
progress {
vertical-align: baseline;
}
summary {
display: list-item;
}
ol, ul, menu {
list-style: none;
}
img, svg, video, canvas, audio, iframe, embed, object {
display: block;
vertical-align: middle;
}
img, video {
max-width: 100%;
height: auto;
}
button, input, select, optgroup, textarea, ::file-selector-button {
font: inherit;
font-feature-settings: inherit;
font-variation-settings: inherit;
letter-spacing: inherit;
color: inherit;
border-radius: 0;
background-color: transparent;
opacity: 1;
}
:where(select:is([multiple], [size])) optgroup {
font-weight: bolder;
}
:where(select:is([multiple], [size])) optgroup option {
padding-inline-start: 20px;
}
::file-selector-button {
margin-inline-end: 4px;
}
::placeholder {
opacity: 1;
}
@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {
::placeholder {
color: currentcolor;
@supports (color: color-mix(in lab, red, red)) {
color: color-mix(in oklab, currentcolor 50%, transparent);
}
}
}
textarea {
resize: vertical;
}
::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-date-and-time-value {
min-height: 1lh;
text-align: inherit;
}
::-webkit-datetime-edit {
display: inline-flex;
}
::-webkit-datetime-edit-fields-wrapper {
padding: 0;
}
::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {
padding-block: 0;
}
::-webkit-calendar-picker-indicator {
line-height: 1;
}
:-moz-ui-invalid {
box-shadow: none;
}
button, input:where([type="button"], [type="reset"], [type="submit"]), ::file-selector-button {
appearance: button;
}
::-webkit-inner-spin-button, ::-webkit-outer-spin-button {
height: auto;
}
[hidden]:where(:not([hidden="until-found"])) {
display: none !important;
}
}
@layer utilities {
.relative {
position: relative;
}
.static {
position: static;
}
.mx-auto {
margin-inline: auto;
}
.my-1 {
margin-block: var(--spacing);
}
.mt-2 {
margin-top: calc(var(--spacing) * 2);
}
.mb-8 {
margin-bottom: calc(var(--spacing) * 8);
}
.ml-2 {
margin-left: calc(var(--spacing) * 2);
}
.flow-root {
display: flow-root;
}
.inline-block {
display: inline-block;
}
.inline-flex {
display: inline-flex;
}
.table\! {
display: table !important;
}
.h-full {
height: 100%;
}
.w-4 {
width: calc(var(--spacing) * 4);
}
.max-w-4xl {
max-width: var(--container-4xl);
}
.translate-y-\[-1px\] {
--tw-translate-y: -1px;
translate: var(--tw-translate-x) var(--tw-translate-y);
}
.transform {
transform: var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,);
}
.cursor-pointer {
cursor: pointer;
}
.items-center {
align-items: center;
}
.gap-2 {
gap: calc(var(--spacing) * 2);
}
:where(.space-y-2 > :not(:last-child)) {
--tw-space-y-reverse: 0;
margin-block-start: calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));
margin-block-end: calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)));
}
.rounded {
border-radius: 0.25rem;
}
.rounded-md {
border-radius: var(--radius-md);
}
.rounded-xl {
border-radius: var(--radius-xl);
}
.border {
border-style: var(--tw-border-style);
border-width: 1px;
}
.border-b {
border-bottom-style: var(--tw-border-style);
border-bottom-width: 1px;
}
.border-l {
border-left-style: var(--tw-border-style);
border-left-width: 1px;
}
.border-dashed {
--tw-border-style: dashed;
border-style: dashed;
}
.border-slate-200 {
border-color: var(--color-slate-200);
}
.border-slate-200\/60 {
border-color: color-mix(in srgb, oklch(92.9% 0.013 255.508) 60%, transparent);
@supports (color: color-mix(in lab, red, red)) {
border-color: color-mix(in oklab, var(--color-slate-200) 60%, transparent);
}
}
.bg-slate-50 {
background-color: var(--color-slate-50);
}
.bg-slate-100 {
background-color: var(--color-slate-100);
}
.bg-white {
background-color: var(--color-white);
}
.p-6 {
padding: calc(var(--spacing) * 6);
}
.px-1\.5 {
padding-inline: calc(var(--spacing) * 1.5);
}
.px-2 {
padding-inline: calc(var(--spacing) * 2);
}
.py-0\.5 {
padding-block: calc(var(--spacing) * 0.5);
}
.py-1 {
padding-block: var(--spacing);
}
.py-4 {
padding-block: calc(var(--spacing) * 4);
}
.pb-6 {
padding-bottom: calc(var(--spacing) * 6);
}
.pl-6 {
padding-left: calc(var(--spacing) * 6);
}
.text-center {
text-align: center;
}
.font-mono {
font-family: var(--font-mono);
}
.text-3xl {
font-size: var(--text-3xl);
line-height: var(--tw-leading, var(--text-3xl--line-height));
}
.text-sm {
font-size: var(--text-sm);
line-height: var(--tw-leading, var(--text-sm--line-height));
}
.text-xs {
font-size: var(--text-xs);
line-height: var(--tw-leading, var(--text-xs--line-height));
}
.text-\[10px\] {
font-size: 10px;
}
.font-bold {
--tw-font-weight: var(--font-weight-bold);
font-weight: var(--font-weight-bold);
}
.font-medium {
--tw-font-weight: var(--font-weight-medium);
font-weight: var(--font-weight-medium);
}
.font-semibold {
--tw-font-weight: var(--font-weight-semibold);
font-weight: var(--font-weight-semibold);
}
.tracking-tight {
--tw-tracking: var(--tracking-tight);
letter-spacing: var(--tracking-tight);
}
.text-slate-300 {
color: var(--color-slate-300);
}
.text-slate-400 {
color: var(--color-slate-400);
}
.text-slate-500 {
color: var(--color-slate-500);
}
.text-slate-700 {
color: var(--color-slate-700);
}
.text-slate-800 {
color: var(--color-slate-800);
}
.text-slate-900 {
color: var(--color-slate-900);
}
.antialiased {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.shadow-sm {
--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));
box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
}
.transition-all {
transition-property: all;
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
transition-duration: var(--tw-duration, var(--default-transition-duration));
}
.transition-transform {
transition-property: transform, translate, scale, rotate;
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
transition-duration: var(--tw-duration, var(--default-transition-duration));
}
.duration-200 {
--tw-duration: 200ms;
transition-duration: 200ms;
}
.select-none {
-webkit-user-select: none;
user-select: none;
}
@media (hover: hover) {
.hover\:bg-slate-50:hover {
background-color: var(--color-slate-50);
}
.hover\:text-blue-600:hover {
color: var(--color-blue-600);
}
}
@media (width >= 40rem) {
.sm\:text-4xl {
font-size: var(--text-4xl);
line-height: var(--tw-leading, var(--text-4xl--line-height));
}
}
@media (width >= 48rem) {
.md\:p-8 {
padding: calc(var(--spacing) * 8);
}
.md\:p-12 {
padding: calc(var(--spacing) * 12);
}
}
}
@property --tw-translate-x {
syntax: "*";
inherits: false;
initial-value: 0;
}
@property --tw-translate-y {
syntax: "*";
inherits: false;
initial-value: 0;
}
@property --tw-translate-z {
syntax: "*";
inherits: false;
initial-value: 0;
}
@property --tw-rotate-x {
syntax: "*";
inherits: false;
}
@property --tw-rotate-y {
syntax: "*";
inherits: false;
}
@property --tw-rotate-z {
syntax: "*";
inherits: false;
}
@property --tw-skew-x {
syntax: "*";
inherits: false;
}
@property --tw-skew-y {
syntax: "*";
inherits: false;
}
@property --tw-space-y-reverse {
syntax: "*";
inherits: false;
initial-value: 0;
}
@property --tw-border-style {
syntax: "*";
inherits: false;
initial-value: solid;
}
@property --tw-font-weight {
syntax: "*";
inherits: false;
}
@property --tw-tracking {
syntax: "*";
inherits: false;
}
@property --tw-shadow {
syntax: "*";
inherits: false;
initial-value: 0 0 #0000;
}
@property --tw-shadow-color {
syntax: "*";
inherits: false;
}
@property --tw-shadow-alpha {
syntax: "<percentage>";
inherits: false;
initial-value: 100%;
}
@property --tw-inset-shadow {
syntax: "*";
inherits: false;
initial-value: 0 0 #0000;
}
@property --tw-inset-shadow-color {
syntax: "*";
inherits: false;
}
@property --tw-inset-shadow-alpha {
syntax: "<percentage>";
inherits: false;
initial-value: 100%;
}
@property --tw-ring-color {
syntax: "*";
inherits: false;
}
@property --tw-ring-shadow {
syntax: "*";
inherits: false;
initial-value: 0 0 #0000;
}
@property --tw-inset-ring-color {
syntax: "*";
inherits: false;
}
@property --tw-inset-ring-shadow {
syntax: "*";
inherits: false;
initial-value: 0 0 #0000;
}
@property --tw-ring-inset {
syntax: "*";
inherits: false;
}
@property --tw-ring-offset-width {
syntax: "<length>";
inherits: false;
initial-value: 0px;
}
@property --tw-ring-offset-color {
syntax: "*";
inherits: false;
initial-value: #fff;
}
@property --tw-ring-offset-shadow {
syntax: "*";
inherits: false;
initial-value: 0 0 #0000;
}
@property --tw-duration {
syntax: "*";
inherits: false;
}
@layer properties {
@supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))) {
*, ::before, ::after, ::backdrop {
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-translate-z: 0;
--tw-rotate-x: initial;
--tw-rotate-y: initial;
--tw-rotate-z: initial;
--tw-skew-x: initial;
--tw-skew-y: initial;
--tw-space-y-reverse: 0;
--tw-border-style: solid;
--tw-font-weight: initial;
--tw-tracking: initial;
--tw-shadow: 0 0 #0000;
--tw-shadow-color: initial;
--tw-shadow-alpha: 100%;
--tw-inset-shadow: 0 0 #0000;
--tw-inset-shadow-color: initial;
--tw-inset-shadow-alpha: 100%;
--tw-ring-color: initial;
--tw-ring-shadow: 0 0 #0000;
--tw-inset-ring-color: initial;
--tw-inset-ring-shadow: 0 0 #0000;
--tw-ring-inset: initial;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-offset-shadow: 0 0 #0000;
--tw-duration: initial;
}
}
}