Skip to content
Draft
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
355f21b
Passwords also refuse a distinctive word of an institute's name, not …
omerFixesBugs Nov 16, 2026
7016eff
Sprint 1 P1-J plan (docs/plans/sprint-1-p1j-password-hash.md): the ap…
omerFixesBugs Nov 16, 2026
25da8a3
Sprint 1 P2 plan (docs/plans/sprint-1-p2-files.md): institute profile…
omerFixesBugs Nov 16, 2026
995e61e
Test users get phone numbers no other test user of the same database …
omerFixesBugs Nov 16, 2026
356c448
The app login can no longer read users.password_hash (P1-J): SELECT o…
omerFixesBugs Nov 16, 2026
3ca69eb
Every Prisma client leaves users.password_hash out of its reads (P1-J…
omerFixesBugs Nov 16, 2026
30e85f6
Files and the institute profile in the database (P2 task 1): stored_f…
omerFixesBugs Nov 16, 2026
687a83b
CORS_ORIGINS is normalised in env.ts as browsers send Origin (lower-c…
omerFixesBugs Nov 16, 2026
ff8981c
Shared file caps, types and the institute profile schema (P2 task 2):…
omerFixesBugs Nov 16, 2026
917d5eb
The start-up login check also refuses a login with REPLICATION (a rep…
omerFixesBugs Nov 16, 2026
bc6644b
Password login without the hash (P1-J): the API hashes the typed pass…
omerFixesBugs Nov 16, 2026
b0e6315
GET /me/password reads hasPassword from auth_my_password_is_set() (P1…
omerFixesBugs Nov 16, 2026
47fb357
Docs for P1-J: database.md (password_hash not readable by the app, a …
omerFixesBugs Nov 16, 2026
20b29e9
Redis is pinned to one exact version, redis:7.4.11-alpine (the versio…
omerFixesBugs Nov 16, 2026
81bfc26
Docs for the follow-ups: decisions-pending gets the section "Small fo…
omerFixesBugs Nov 16, 2026
9cc9d54
Image processing for uploads (P2 task 3): sharp 0.35.5 (already in th…
omerFixesBugs Nov 16, 2026
b0e010b
FileStore and the per-institute cap (P2 task 4): PostgresFileStore is…
omerFixesBugs Nov 16, 2026
caec9f7
Photo and profile routes (P2 task 5): GET/PUT/DELETE /students/:id/ph…
omerFixesBugs Nov 16, 2026
57cf79f
Web (P2 task 6): Settings → Institute profile (names, EIIN, contact, …
omerFixesBugs Nov 16, 2026
4e4cbb2
Docs for P2 (task 7): docs/files.md, database.md (the three tables an…
omerFixesBugs Nov 16, 2026
724ffb0
The photo dialog's preview URL is made when a file is chosen, not in …
omerFixesBugs Nov 16, 2026
110857d
files.spec: the profile fields by id ("নাম (বাংলা)" is also part of t…
omerFixesBugs Nov 16, 2026
8c3a4f9
After the review (P1-J7): a dedicated login for the password login. j…
omerFixesBugs Nov 16, 2026
72b714b
The password login looks the hash up on its own database login (Login…
omerFixesBugs Nov 16, 2026
06f3236
Docs after the P1-J review: what an injection in an ordinary request …
omerFixesBugs Nov 16, 2026
82f6600
Test phones never wrap and their lock survives races (review of PR #1…
omerFixesBugs Nov 16, 2026
27403c3
The institute-name rule compares passwords and names like the phone r…
omerFixesBugs Nov 16, 2026
7aa31c5
An origin setting with a login, a path, a query or a fragment is no o…
omerFixesBugs Nov 16, 2026
fd6430e
Docs after the review of PR #17: P1-I's title line says it is built h…
omerFixesBugs Nov 16, 2026
9dbee45
P1-J migration after the second review: it first checks that jantrik_…
omerFixesBugs Nov 16, 2026
a980a60
The password login's database login must reach the same database, por…
omerFixesBugs Nov 16, 2026
ff673b8
Docs after the second P1-J review: the server upgrade creates the rol…
omerFixesBugs Nov 16, 2026
13deed2
A file reference is tied to its kind (review R6): UNIQUE (tenant_id, …
omerFixesBugs Nov 16, 2026
cb86722
Uploads hold no database connection while they arrive (review R1): th…
omerFixesBugs Nov 16, 2026
459bcf7
Web after the review: a chosen image is shrunk in the browser to 1600…
omerFixesBugs Nov 16, 2026
944e840
Docs after the review: auth.md (the request pipeline and @OwnTransact…
omerFixesBugs Nov 16, 2026
282c8b6
Review round 2, API: uploads in flight bounded before multer (16 per …
omerFixesBugs Nov 16, 2026
cfd4506
Review round 2, web: the browser asks for the EXIF orientation explic…
omerFixesBugs Nov 16, 2026
73eb83b
Docs for review round 2: auth.md (the upload routes' re-checks, Uploa…
omerFixesBugs Nov 16, 2026
e622e52
The interceptor opens its transaction through an unchecked entry (aro…
omerFixesBugs Nov 16, 2026
3d2c5d5
Review round 3: no upload slot leaks when the client left before Uplo…
omerFixesBugs Nov 16, 2026
de19108
The two new origin tests' development settings also name DATABASE_LOG…
omerFixesBugs Nov 16, 2026
aa0105b
Merge P1-J (#16) into the small follow-ups (#17): the ready resolutio…
omerFixesBugs Nov 16, 2026
b1efceb
Merge remote-tracking branch 'origin/feature/sprint-1-p1j-password-ha…
omerFixesBugs Nov 16, 2026
b5d3697
Merge remote-tracking branch 'origin/feature/sprint-1-p2-files' into …
omerFixesBugs Nov 16, 2026
c857102
Merge remote-tracking branch 'origin/feature/small-followups-after-p1…
omerFixesBugs Nov 16, 2026
9309fa8
Work in progress: a staff guide draft and draft legal texts (terms of…
omerFixesBugs Nov 19, 2026
ed5d56c
Docs only: a plain staff guide draft (signing in, setup, students, gu…
omerFixesBugs Nov 19, 2026
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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ jobs:
--health-timeout 5s
--health-retries 10
redis:
image: redis:7-alpine
image: redis:7.4.11-alpine
ports:
- 6379:6379
options: >-
Expand Down Expand Up @@ -159,7 +159,7 @@ jobs:
--health-timeout 5s
--health-retries 10
redis:
image: redis:7-alpine
image: redis:7.4.11-alpine
ports:
- 6379:6379
options: >-
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/auth/login-prisma.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const SAFE: LoginPrivileges = {
login: 'jantrik_login_app',
superuser: false,
bypassRls: false,
replication: false,
createRole: false,
canBecome: [],
};

Expand All @@ -15,6 +17,8 @@ const privilegeRow = (p: LoginPrivileges) => ({
login: p.login,
superuser: p.superuser,
bypass_rls: p.bypassRls,
replication: p.replication,
create_role: p.createRole,
can_become: p.canBecome,
});

Expand Down
16 changes: 13 additions & 3 deletions apps/api/src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,22 @@ export const envSchema = z
.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
API_PORT: z.coerce.number().int().positive().default(4000),
/** Comma-separated allowlist of browser origins (credentials are allowed). */
/**
* Comma-separated allowlist of browser origins (credentials are allowed). Normalised as
* browsers send `Origin` (lower-case host, no trailing slash, no default port), so the CORS
* check (an exact match) allows what the production check passed. An entry that is not exactly
* an origin (not a URL, or with a login, a path, a query or a fragment) stays as written: it
* matches no browser's Origin, and production refuses it.
*/
CORS_ORIGINS: z
.string()
.default('http://localhost:3000')
.transform((v) =>
v
.split(',')
.map((o) => o.trim())
.filter(Boolean),
.filter(Boolean)
.map((o) => normaliseOrigin(o) ?? o),
),
/**
* The platform web app's origins (comma-separated): the only browser origins /platform/*
Expand All @@ -52,7 +59,10 @@ export const envSchema = z
.filter(Boolean)) {
const origin = normaliseOrigin(entry);
if (origin === null) {
ctx.addIssue({ code: 'custom', message: `PLATFORM_ORIGINS: "${entry}" is not a URL` });
ctx.addIssue({
code: 'custom',
message: `PLATFORM_ORIGINS: "${entry}" is not an origin (scheme, host and port only)`,
});
return z.NEVER;
}
origins.push(origin);
Expand Down
93 changes: 93 additions & 0 deletions apps/api/src/config/production-env.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { envSchema, validateEnv } from './env.js';
import { isAllowedOrigin } from './dev-lan.js';
import { validateIngestEnv } from './ingest-env.js';
import {
API_ONLY_SECRETS,
DATABASE_ADMIN_SECRETS,
normaliseOrigin,
trustsAnyClient,
unsafeOrigin,
} from './production-env.js';
Expand Down Expand Up @@ -171,6 +173,97 @@ describe('production env: the API and the worker', () => {
expect(apiError({ ...api, PLATFORM_ORIGINS: 'https://PLATFORM.jantrik.com.bd/' })).toBe('');
});

it('pins Redis to one exact version in the production compose, the development compose and CI', () => {
const images = [
'deploy/docker-compose.prod.yml',
'docker-compose.yml',
'.github/workflows/ci.yml',
].flatMap((file) =>
[
...readFileSync(path.resolve(import.meta.dirname, '../../../..', file), 'utf8').matchAll(
/image:\s*(redis:\S+)/g,
),
].map((m) => ({ file, image: m[1]! })),
);
// The production compose and the development one once each, CI's two jobs.
expect(images).toHaveLength(4);
for (const { file, image } of images) {
expect(image, file).toMatch(/^redis:\d+\.\d+\.\d+-alpine$/);
}
expect(new Set(images.map((i) => i.image)).size).toBe(1);
});

it('treats an entry with a login, a path, a query or a fragment as no origin at all', () => {
const dev = {
DATABASE_URL: 'postgresql://jantrik_app:x@localhost:5432/jantrik',
DATABASE_PLATFORM_URL: 'postgresql://jantrik_platform_app:x@localhost:5432/jantrik',
// Required once PR #16 (P1-J) is merged; ignored by the schema before that.
DATABASE_LOGIN_URL: 'postgresql://jantrik_login_app:x@localhost:5432/jantrik',
DATABASE_INGEST_URL: 'postgresql://jantrik_ingest_app:x@localhost:5432/jantrik',
JWT_ACCESS_SECRET: 'x'.repeat(40),
OTP_PEPPER: 'y'.repeat(40),
};
for (const entry of [
// A URL's origin would drop the part before @: this is https://evil.example.
'https://app.jantrik.com.bd@evil.example',
'https://user:pw@app.jantrik.com.bd',
'https://app.jantrik.com.bd/app',
'https://app.jantrik.com.bd/?x=1',
'https://app.jantrik.com.bd/#top',
]) {
expect(normaliseOrigin(entry), entry).toBeNull();
// Production refuses it in either list.
expect(
apiError({ ...api, CORS_ORIGINS: `${entry},https://platform.jantrik.com.bd` }),
).toMatch(/CORS_ORIGINS must hold https origins only; ".*" is not an origin/);
expect(apiError({ ...api, PLATFORM_ORIGINS: entry })).toMatch(
/PLATFORM_ORIGINS: ".*" is not an origin/,
);
// Development keeps a CORS entry as written: it matches no browser's Origin.
const parsed = envSchema.parse({ ...dev, CORS_ORIGINS: entry });
expect(parsed.CORS_ORIGINS).toEqual([entry]);
expect(isAllowedOrigin('https://evil.example', parsed)).toBe(false);
expect(isAllowedOrigin('https://app.jantrik.com.bd', parsed)).toBe(false);
}
expect(normaliseOrigin('HTTPS://App.Jantrik.com.bd:443/')).toBe('https://app.jantrik.com.bd');
});

it('normalises CORS_ORIGINS too, so the CORS middleware allows what the start-up check passed', () => {
const dev = {
DATABASE_URL: 'postgresql://jantrik_app:x@localhost:5432/jantrik',
DATABASE_PLATFORM_URL: 'postgresql://jantrik_platform_app:x@localhost:5432/jantrik',
// Required once PR #16 (P1-J) is merged; ignored by the schema before that.
DATABASE_LOGIN_URL: 'postgresql://jantrik_login_app:x@localhost:5432/jantrik',
DATABASE_INGEST_URL: 'postgresql://jantrik_ingest_app:x@localhost:5432/jantrik',
JWT_ACCESS_SECRET: 'x'.repeat(40),
OTP_PEPPER: 'y'.repeat(40),
};
const parsed = envSchema.parse({
...dev,
CORS_ORIGINS:
'HTTPS://App.Jantrik.com.bd/ , http://localhost:3000/,https://a.example.com:443',
});
expect(parsed.CORS_ORIGINS).toEqual([
'https://app.jantrik.com.bd',
'http://localhost:3000',
'https://a.example.com',
]);
// The browser sends the normalised form; the middleware's check is an exact match.
expect(isAllowedOrigin('https://app.jantrik.com.bd', parsed)).toBe(true);
// An entry that is not an origin stays as written (production refuses it, see above).
expect(envSchema.parse({ ...dev, CORS_ORIGINS: '*,app.jantrik.com.bd' }).CORS_ORIGINS).toEqual([
'*',
'app.jantrik.com.bd',
]);
// Production: an upper-case, slash-ended entry passes the check and is allowed by the middleware.
const prod = {
...api,
CORS_ORIGINS: 'https://APP.jantrik.com.bd/,https://platform.jantrik.com.bd',
};
expect(apiError(prod)).toBe('');
expect(envSchema.parse(prod).CORS_ORIGINS).toContain('https://app.jantrik.com.bd');
});

it('refuses secrets shorter than 32 characters', () => {
for (const key of ['JWT_ACCESS_SECRET', 'OTP_PEPPER', 'PLATFORM_TOTP_KEY']) {
expect(apiError({ ...api, [key]: 'k'.repeat(31) })).toMatch(new RegExp(key));
Expand Down
13 changes: 9 additions & 4 deletions apps/api/src/config/production-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,19 @@ const LOCAL_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\]|0\.0\.0\.0|\[::\])$/i;

/**
* A browser origin as browsers send it in `Origin` (scheme, lower-case host, port when not the
* default; no path or trailing slash), or null when `value` is not a URL with an origin.
* default; no trailing slash), or null when `value` is not exactly an origin. A login, a path, a
* query or a fragment makes it no origin: `URL.origin` would silently drop them, and
* `https://app.example@evil.example` would become `https://evil.example`.
*/
export function normaliseOrigin(value: string): string | null {
let url: URL;
try {
const origin = new URL(value).origin;
return origin === 'null' ? null : origin;
url = new URL(value);
} catch {
return null;
}
if (url.username || url.password || url.pathname !== '/' || url.search || url.hash) return null;
return url.origin === 'null' ? null : url.origin;
}

/** Why a browser origin may not be allowed in production, or null when it may. */
Expand All @@ -46,6 +50,7 @@ export function unsafeOrigin(origin: string): string | null {
} catch {
return 'not a URL';
}
if (normaliseOrigin(origin) === null) return 'not an origin (scheme, host and port only)';
if (url.protocol !== 'https:') return 'not https';
if (LOCAL_HOST.test(url.hostname) || url.hostname.endsWith('.localhost')) {
return 'a local address';
Expand Down Expand Up @@ -239,7 +244,7 @@ export function apiProductionProblems(env: ApiProductionEnv): EnvProblem[] {
"PLATFORM_ORIGINS must list the platform's web origin (https://platform.<domain>)",
);
}
const cors = new Set(env.CORS_ORIGINS.map((o) => normaliseOrigin(o) ?? o));
const cors = new Set(env.CORS_ORIGINS); // normalised by env.ts, as PLATFORM_ORIGINS
for (const origin of env.PLATFORM_ORIGINS) {
const why = unsafeOrigin(origin);
if (why) {
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/ingest/ingest-prisma.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ const SAFE: LoginPrivileges = {
login: 'jantrik_ingest_app',
superuser: false,
bypassRls: false,
replication: false,
createRole: false,
canBecome: [],
};

Expand Down Expand Up @@ -60,6 +62,8 @@ function serviceWith(privileges: LoginPrivileges, ...answers: (Check | Error | t
login: privileges.login,
superuser: privileges.superuser,
bypass_rls: privileges.bypassRls,
replication: privileges.replication,
create_role: privileges.createRole,
can_become: privileges.canBecome,
},
]),
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/platform/platform-prisma.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const SAFE: LoginPrivileges = {
login: 'jantrik_platform_app',
superuser: false,
bypassRls: false,
replication: false,
createRole: false,
canBecome: [],
};

Expand All @@ -13,6 +15,8 @@ const privilegeRow = (p: LoginPrivileges) => ({
login: p.login,
superuser: p.superuser,
bypass_rls: p.bypassRls,
replication: p.replication,
create_role: p.createRole,
can_become: p.canBecome,
});

Expand Down
13 changes: 13 additions & 0 deletions apps/api/src/prisma/prisma.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ const SAFE: LoginPrivileges = {
login: 'jantrik_app',
superuser: false,
bypassRls: false,
replication: false,
createRole: false,
canBecome: [],
};

Expand All @@ -31,6 +33,8 @@ function service(...answers: (LoginPrivileges | Error)[]) {
login: a.login,
superuser: a.superuser,
bypass_rls: a.bypassRls,
replication: a.replication,
create_role: a.createRole,
can_become: a.canBecome,
},
]),
Expand Down Expand Up @@ -63,6 +67,15 @@ describe('PrismaService startup check', () => {
);
});

it('refuses a login with REPLICATION or CREATEROLE', async () => {
await expect(service({ ...SAFE, replication: true }).s.onModuleInit()).rejects.toThrow(
/DATABASE_URL.*has REPLICATION/,
);
await expect(service({ ...SAFE, createRole: true }).s.onModuleInit()).rejects.toThrow(
/DATABASE_URL.*has CREATEROLE/,
);
});

it('refuses a login that can become a BYPASSRLS role', async () => {
await expect(
service({ ...SAFE, canBecome: ['admin_bypass'] }).s.onModuleInit(),
Expand Down
3 changes: 3 additions & 0 deletions apps/api/test/password-set.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,9 @@ describe('staff set their own password', () => {
).body.accessToken as string;
expect(await rejected(token, 'my KODOM tola school!')).toEqual(['HAS_INSTITUTE_NAME']);
expect(await rejected(token, 'বকুলকোচিংসেন্টার২০২৬')).toEqual(['HAS_INSTITUTE_NAME']);
// A distinctive word of either name is enough (P1-I); generic words alone are not.
expect(await rejected(token, 'kodom@2026 rain')).toEqual(['HAS_INSTITUTE_NAME']);
expect(await rejected(token, 'বকুল২০২৬১২৩৪৫')).toEqual(['HAS_INSTITUTE_NAME']);
await passTime(phone, userId);
const code = await codeFor(token, phone);
await setPassword(token, code, GOOD).expect(204);
Expand Down
9 changes: 8 additions & 1 deletion apps/api/test/support/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { SMS_PROVIDER, type MemorySmsProvider } from '../../src/sms/sms.provider
import { TenantAccessService } from '../../src/tenancy/tenant-access.service.js';
import { Clock } from '../../src/common/clock.js';
import { TestController } from './test.controller.js';
import { phoneSource } from './test-phones.js';

export interface Harness {
app: INestApplication;
Expand Down Expand Up @@ -76,8 +77,14 @@ export async function createHarness(opts: { clock?: Clock } = {}): Promise<Harne
};
}

let phones: (() => string) | undefined;
/**
* A valid Bangladeshi mobile number (E.164) that no other test user of this database has, in this
* run or an earlier one (`test-phones.ts`; the db package's tests draw from +88014, these from
* +88013).
*/
export const randomPhone = (): string =>
`+88018${String(Math.floor(Math.random() * 1e8)).padStart(8, '0')}`;
(phones ??= phoneSource('+88013', process.env['DATABASE_URL']!))();
/**
* A distinct client IP per call (sent as X-Forwarded-For) so per-IP limits don't collide. Fully
* random: test files run in parallel workers and share Redis, so a per-worker counter repeats.
Expand Down
Loading