mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 18:04:18 +00:00
fix(server): plan 3b close-out — case folding on both sides for identifier lookups (non-ASCII login regression); coverage ratchet restored; repository scaffold and instanceof ratchet on TrekRepository; D-shape tests load-bearing
This commit is contained in:
@@ -77,16 +77,26 @@ export function columnIncrementedBy(platform: Platform, ref: string, amount: num
|
||||
|
||||
/**
|
||||
* A case-insensitive column reference, for use as a filter's object key:
|
||||
* `{ [lower(platform, 'email')]: value.toLowerCase() }` produces
|
||||
* `WHERE LOWER(email) = ?`. This is the parity-preserving equivalent of the
|
||||
* legacy `LOWER(col) = LOWER(?)` sites (`AuthService`/`OidcService`/
|
||||
* `UserProfileService`'s username/email CI lookups): the caller lowercases
|
||||
* the bound value itself (every one of this migration's call sites already
|
||||
* does, via `String.prototype.toLowerCase`), so the comparison is between
|
||||
* two already-lowercased values either way — SQLite's `LOWER()` is ASCII-only
|
||||
* exactly like `toLowerCase()` is for the identifier characters these
|
||||
* columns hold (usernames/emails), so the two spellings agree on every
|
||||
* input this codebase stores.
|
||||
* `{ [lower(platform, 'email')]: <value-side> }` produces
|
||||
* `WHERE LOWER(email) = <value-side>`.
|
||||
*
|
||||
* **SQLite's `LOWER()` is ASCII-only; JavaScript's `String.prototype
|
||||
* .toLowerCase()` is full-Unicode.** They do NOT agree on every input this
|
||||
* codebase stores — a locally-registered e-mail can carry any non-whitespace
|
||||
* character (`EMAIL_REGEX`), including non-ASCII letters (program rule 18;
|
||||
* Plan 3b Task 7 review, H1: `JOSÉ@x.com` proved a live login lockout). Two
|
||||
* value-side shapes are legitimate, and they are NOT interchangeable:
|
||||
*
|
||||
* - `LOWER(col) = LOWER(?)` — pair with `lowerParam()` below, binding the
|
||||
* RAW value. Both sides are folded by the SAME engine (SQLite's), so they
|
||||
* agree on every input. This is the shape for every legacy
|
||||
* `LOWER(col) = LOWER(?)` statement (AU9, AU12, UP5, UP6, O12).
|
||||
* - `LOWER(col) = ?` — pair with a value the CALLER has already lowered in
|
||||
* JS (`value.toLowerCase()`) as a plain string, matching a legacy
|
||||
* `LOWER(col) = ?` statement exactly (only O4 today —
|
||||
* `OidcService.findOrCreateUser` JS-lowers the email once upfront and the
|
||||
* legacy statement it replaced never re-lowered it in SQL). Do not use
|
||||
* this shape for a value the caller has not already lowered.
|
||||
*
|
||||
* Typed `RawQueryFragment & symbol` (not the bare `RawQueryFragment` the
|
||||
* other helpers in this file return): TypeScript only accepts a
|
||||
@@ -100,3 +110,20 @@ export function lower(platform: Platform, ref: string): RawQueryFragment & symbo
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* The value-side twin of `lower()`: `LOWER(?)` bound with the RAW,
|
||||
* untransformed value, for the right-hand side of a `lower(platform, col)`
|
||||
* filter key. Together they render `LOWER(<column>) = LOWER(?)`,
|
||||
* byte-for-byte a legacy `LOWER(col) = LOWER(?)` statement, because SQLite
|
||||
* folds BOTH sides with the same (ASCII-only) engine — proven directly
|
||||
* against `better-sqlite3`: `SELECT LOWER(?)` on `'JOSÉ@x.com'` yields
|
||||
* `'josÉ@x.com'` (only the ASCII letters fold; the `É` is untouched), the
|
||||
* same transform SQLite would apply to a stored column. Do NOT pre-lower
|
||||
* the value in JS before calling this (program rule 18) — that reintroduces
|
||||
* the mixed-engine bug this helper exists to close.
|
||||
*/
|
||||
export function lowerParam(platform: Platform, value: string): RawQueryFragment {
|
||||
if (platform instanceof SqlitePlatform) return raw('LOWER(?)', [value]);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
|
||||
@@ -135,6 +135,15 @@ export class OauthClientsRepository extends TrekRepository<OauthClients> {
|
||||
);
|
||||
return rows.map((row) => ({
|
||||
id: row.id as string,
|
||||
// `row.user?.id`'s `?? null` fallback is unreachable THROUGH THIS
|
||||
// METHOD specifically: the query already filters `{ user: userId }`
|
||||
// on a concrete, non-null `userId`, so every returned row's `user`
|
||||
// relation is populated by construction — `findPublicById` below is
|
||||
// the id-scoped sibling that genuinely reads an anonymous (NULL
|
||||
// `user_id`) client and exercises this same shape's null branch.
|
||||
// Kept for type-shape symmetry with that sibling, not dead by
|
||||
// mistake (the `countNonGuest`/`COALESCE(is_guest, 0)` precedent
|
||||
// above is the same kind of defensive-but-unreachable fallback).
|
||||
user_id: row.user?.id ?? null,
|
||||
name: row.name,
|
||||
client_id: row.client_id,
|
||||
|
||||
@@ -93,6 +93,15 @@ export class OauthConsentsRepository extends TrekRepository<OauthConsents> {
|
||||
* Promise<Entity>`); shadowing it would either fail to compile or silently
|
||||
* hide the base method, the same collision `Users.repository.ts::insertUser`
|
||||
* avoided with `create`.
|
||||
*
|
||||
* One more divergence from the legacy statement (Task 7 review, B-I1),
|
||||
* unobservable and strictly better: the legacy `INSERT OR REPLACE`
|
||||
* deletes-then-inserts, so a re-consent always assigned a NEW surrogate
|
||||
* `id`; `em.upsert` with `onConflictAction: 'merge'` keeps the existing
|
||||
* one. `oauth_consents` has only `id`/`client_id`/`user_id`/`scopes`/
|
||||
* `updated_at` and nothing reads `id`, so this is unobservable — and it
|
||||
* avoids the FK churn a delete+insert would otherwise cause if anything
|
||||
* ever did reference this row's surrogate key.
|
||||
*/
|
||||
async upsertGrant(clientId: string, userId: number, scopes: string): Promise<void> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Users } from '../entities/Users.entity';
|
||||
import { toRow, type AssertRowKeys } from './_shared/rows';
|
||||
import { columnIncrementedBy, currentTimestamp, lower } from '../dialect/sql-functions';
|
||||
import { columnIncrementedBy, currentTimestamp, lower, lowerParam } from '../dialect/sql-functions';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
/**
|
||||
@@ -278,12 +278,21 @@ export class UsersRepository extends TrekRepository<Users> {
|
||||
/**
|
||||
* `SELECT id FROM users WHERE (LOWER(email) = LOWER(?) OR LOWER(username) = LOWER(?))
|
||||
* AND COALESCE(is_guest, 0) = 0`
|
||||
*
|
||||
* Both operands of each comparison are folded by SQLite's own `LOWER()`
|
||||
* (`lowerParam` binds the RAW value) — never a JS-lowered bind. SQLite's
|
||||
* `LOWER()` is ASCII-only; `String.prototype.toLowerCase()` is
|
||||
* full-Unicode, and mixing them locks out any non-ASCII cased identifier
|
||||
* (program rule 18; Plan 3b Task 7 review, H1).
|
||||
*/
|
||||
async findIdByEmailOrUsernameCI(email: string, username: string): Promise<number | null> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const row = await this.findOne(
|
||||
{
|
||||
$or: [{ [lower(platform, 'email')]: email.toLowerCase() }, { [lower(platform, 'username')]: username.toLowerCase() }],
|
||||
$or: [
|
||||
{ [lower(platform, 'email')]: lowerParam(platform, email) },
|
||||
{ [lower(platform, 'username')]: lowerParam(platform, username) },
|
||||
],
|
||||
is_guest: 0,
|
||||
},
|
||||
{ fields: ['id'] },
|
||||
@@ -342,10 +351,39 @@ export class UsersRepository extends TrekRepository<Users> {
|
||||
// AU12 / O4 — email lookup (login + OIDC email-fallback)
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/** `SELECT * FROM users WHERE LOWER(email) = LOWER(?) AND COALESCE(is_guest, 0) = 0` */
|
||||
/**
|
||||
* `SELECT * FROM users WHERE LOWER(email) = LOWER(?) AND COALESCE(is_guest, 0) = 0`
|
||||
* — AU9's sibling for AU12 (`AuthService.loginUser`, `auth.service.ts`).
|
||||
*
|
||||
* Both sides folded by SQLite's own `LOWER()` (`lowerParam` binds the
|
||||
* RAW, untransformed email) — the legacy statement lowered BOTH operands
|
||||
* in SQL, so a JS-lowered bind here would disagree with the column on
|
||||
* every non-ASCII cased character (program rule 18; Plan 3b Task 7
|
||||
* review, H1: a `JOSÉ@x.com` account could register but never log back
|
||||
* in). Distinct from `findByEmailLoweredBind` below, which mirrors O4's
|
||||
* different legacy statement — do not collapse the two back into one
|
||||
* method (D4).
|
||||
*/
|
||||
async findByEmailCI(email: string): Promise<UserRow | null> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const user = await this.findOne({ [lower(platform, 'email')]: email.toLowerCase(), is_guest: 0 });
|
||||
const user = await this.findOne({ [lower(platform, 'email')]: lowerParam(platform, email), is_guest: 0 });
|
||||
return user ? (toRow(user) as UserRow) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT * FROM users WHERE LOWER(email) = ? AND COALESCE(is_guest, 0) = 0`
|
||||
* — O4 (`OidcService.findOrCreateUser`, `oidc.service.ts:655`), whose only
|
||||
* caller JS-lowers the email itself (`oidc.service.ts:620`,
|
||||
* `userInfo.email.trim().toLowerCase()`) before calling this method,
|
||||
* exactly mirroring the legacy statement's `LOWER(email) = ?` (SQL
|
||||
* `LOWER()` on the column, a bind the CALLER already lowered — not a
|
||||
* second SQL `LOWER()` on the value side). Do not point a caller that has
|
||||
* NOT already lowered its value at this method — use `findByEmailCI`
|
||||
* above instead.
|
||||
*/
|
||||
async findByEmailLoweredBind(alreadyLoweredEmail: string): Promise<UserRow | null> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const user = await this.findOne({ [lower(platform, 'email')]: alreadyLoweredEmail, is_guest: 0 });
|
||||
return user ? (toRow(user) as UserRow) : null;
|
||||
}
|
||||
|
||||
@@ -595,7 +633,16 @@ export class UsersRepository extends TrekRepository<Users> {
|
||||
// PK15 — re-auth before passkey deletion
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/** `SELECT password_hash FROM users WHERE id = ?` */
|
||||
/**
|
||||
* `SELECT password_hash FROM users WHERE id = ?`
|
||||
*
|
||||
* The `?? null` fallback's own "row present but `password_hash` itself
|
||||
* null" branch is unreachable: `password_hash TEXT NOT NULL` in the
|
||||
* baseline schema (never relaxed by a later migration) — the same
|
||||
* defensive-but-unreachable shape as `countNonGuest`'s `COALESCE(is_guest,
|
||||
* 0)` above. The `?.`/`??` combination still earns its keep for the
|
||||
* "row missing" case (`?.` alone would leave `undefined`, not `null`).
|
||||
*/
|
||||
async getPasswordHash(id: number): Promise<string | null> {
|
||||
const row = await this.findOne({ id }, { fields: ['password_hash'] });
|
||||
return row?.password_hash ?? null;
|
||||
@@ -665,11 +712,14 @@ export class UsersRepository extends TrekRepository<Users> {
|
||||
* `SELECT id FROM users WHERE LOWER(username) = LOWER(?) AND id != ?
|
||||
* AND COALESCE(is_guest, 0) = 0` (UP5, `updateSettings`'s own-username
|
||||
* collision check).
|
||||
*
|
||||
* Both sides folded by SQLite's own `LOWER()` (`lowerParam` binds the RAW
|
||||
* value) — program rule 18.
|
||||
*/
|
||||
async findIdByUsernameCI(username: string, excludeId: number): Promise<number | null> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const row = await this.findOne(
|
||||
{ [lower(platform, 'username')]: username.toLowerCase(), id: { $ne: excludeId }, is_guest: 0 },
|
||||
{ [lower(platform, 'username')]: lowerParam(platform, username), id: { $ne: excludeId }, is_guest: 0 },
|
||||
{ fields: ['id'] },
|
||||
);
|
||||
return row?.id ?? null;
|
||||
@@ -681,11 +731,17 @@ export class UsersRepository extends TrekRepository<Users> {
|
||||
* a genuinely different WHERE than UP5's, so a separate method per D4
|
||||
* rather than an optional parameter that would silently change UP5's
|
||||
* shape.
|
||||
*
|
||||
* Both sides folded by SQLite's own `LOWER()` (`lowerParam` binds the RAW
|
||||
* value) — program rule 18. The only caller sanitises the username to
|
||||
* `[a-zA-Z0-9_.-]` before calling (`oidc.service.ts`), so this cannot
|
||||
* diverge in practice today; fixed anyway so the guarantee lives in the
|
||||
* method, not the caller.
|
||||
*/
|
||||
async findIdByUsernameCIAny(username: string): Promise<number | null> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const row = await this.findOne(
|
||||
{ [lower(platform, 'username')]: username.toLowerCase() },
|
||||
{ [lower(platform, 'username')]: lowerParam(platform, username) },
|
||||
{ fields: ['id'] },
|
||||
);
|
||||
return row?.id ?? null;
|
||||
@@ -771,11 +827,16 @@ export class UsersRepository extends TrekRepository<Users> {
|
||||
// UP6 — email collision check
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/** `SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id != ? AND COALESCE(is_guest, 0) = 0` */
|
||||
/**
|
||||
* `SELECT id FROM users WHERE LOWER(email) = LOWER(?) AND id != ? AND COALESCE(is_guest, 0) = 0`
|
||||
*
|
||||
* Both sides folded by SQLite's own `LOWER()` (`lowerParam` binds the RAW
|
||||
* value) — program rule 18.
|
||||
*/
|
||||
async findIdByEmailCI(email: string, excludeId: number): Promise<number | null> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const row = await this.findOne(
|
||||
{ [lower(platform, 'email')]: email.toLowerCase(), id: { $ne: excludeId }, is_guest: 0 },
|
||||
{ [lower(platform, 'email')]: lowerParam(platform, email), id: { $ne: excludeId }, is_guest: 0 },
|
||||
{ fields: ['id'] },
|
||||
);
|
||||
return row?.id ?? null;
|
||||
@@ -870,11 +931,15 @@ export class UsersRepository extends TrekRepository<Users> {
|
||||
* `DELETE FROM users WHERE id = ?` — `UserCleanupService.deleteUserCompletely`'s
|
||||
* final statement, the root of its 13-table transaction
|
||||
* (**security-sensitive**: account erasure). Named `deleteById`, not
|
||||
* `remove`/`delete`: `EntityRepository#remove` is a real (persist-marking,
|
||||
* needs-a-`flush()`) method on the base class — shadowing it would change
|
||||
* its signature and behaviour; `deleteById` matches the naming this
|
||||
* program already uses for a native, immediate delete
|
||||
* (`McpTokensRepository.deleteById`).
|
||||
* `remove`/`delete`: `remove` is `EntityManager`'s (persist-marking,
|
||||
* needs-a-`flush()`), not `EntityRepository`'s — MikroORM 7.2.1's
|
||||
* `EntityRepository` has no `remove` method at all (Task 7 review, L1;
|
||||
* verified against the installed `.d.ts`, not assumed — that is why
|
||||
* `OauthClientsRepository.remove`/`TagsRepository.remove`/
|
||||
* `CategoriesRepository.remove` compile as their own, unrelated methods).
|
||||
* `deleteById` is chosen for naming consistency with this program's other
|
||||
* native, immediate deletes (`McpTokensRepository.deleteById`), not to
|
||||
* avoid a compiler conflict that does not exist.
|
||||
*/
|
||||
async deleteById(id: number): Promise<void> {
|
||||
await this.nativeDelete({ id });
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { EntityRepository, FilterQuery, FilterValue, OrderDefinition } from '@mikro-orm/core';
|
||||
import type { FilterQuery, FilterValue, OrderDefinition } from '@mikro-orm/core';
|
||||
import type { TrekRepository } from './trek-repository';
|
||||
|
||||
/**
|
||||
* Shared lookup shapes for entities scoped to a user.
|
||||
@@ -20,6 +21,16 @@ import type { EntityRepository, FilterQuery, FilterValue, OrderDefinition } from
|
||||
* missing helper"). If a future entity needs that shape, recover it from
|
||||
* git history rather than reintroducing it speculatively.
|
||||
*
|
||||
* Typed `repo: TrekRepository<T>` (Task 7 review, A-L3/B-L4 — was the core
|
||||
* `EntityRepository<T>` until this task, the last two places in the
|
||||
* repository tree still restating `disableIdentityMap: true` per call
|
||||
* because the type couldn't see `TrekRepository`'s own validation and read
|
||||
* default): at runtime the argument was always a `TrekRepository` (every
|
||||
* concrete repository extends it), so the guard always fired — this closed
|
||||
* a typing gap, not a safety gap. The two per-call `disableIdentityMap:
|
||||
* true` literals below are gone now that the base class's `find`/`findOne`
|
||||
* overrides supply the same default.
|
||||
*
|
||||
* These helpers return live MikroORM entities, not rows — unlike every other
|
||||
* repository method in this codebase (D4: "repositories return rows, never a
|
||||
* live entity"). They are an internal building block for `TagsRepository`,
|
||||
@@ -37,8 +48,9 @@ import type { EntityRepository, FilterQuery, FilterValue, OrderDefinition } from
|
||||
* listForOwner<Tags, 'user', 'name'>(tags, 'user', userId, 'name');
|
||||
* findOwnedByUser<Tags, 'user'>(tags, id, 'user', userId);
|
||||
*
|
||||
* Both helpers pass `disableIdentityMap: true` (Plan 3b Task 1 fix round,
|
||||
* supersedes Plan 3a's I1 "`refresh: true` on every PK-only `findOne`" — see
|
||||
* Both helpers get `disableIdentityMap: true` from `TrekRepository`'s own
|
||||
* `find`/`findOne` default now (Plan 3b Task 1 fix round, supersedes Plan
|
||||
* 3a's I1 "`refresh: true` on every PK-only `findOne`" — see
|
||||
* `Users.repository.ts`'s class-level docstring and
|
||||
* `.superpowers/sdd/2026-09-22-orm-phase3b/task-1-review.md` B1): both are
|
||||
* "rows out" reads whose entity is converted via `toRow` and discarded, never
|
||||
@@ -63,14 +75,13 @@ import type { EntityRepository, FilterQuery, FilterValue, OrderDefinition } from
|
||||
* `SELECT * FROM <table> WHERE <ownerField> = ? ORDER BY <orderField> ASC`.
|
||||
*/
|
||||
export async function listForOwner<T extends { id: unknown }, K extends keyof T, OF extends keyof T>(
|
||||
repo: EntityRepository<T>,
|
||||
repo: TrekRepository<T>,
|
||||
ownerField: K,
|
||||
ownerId: FilterValue<T[K]>,
|
||||
orderField: OF,
|
||||
): Promise<T[]> {
|
||||
return repo.find({ [ownerField]: ownerId } as FilterQuery<T>, {
|
||||
orderBy: { [orderField]: 'asc' } as OrderDefinition<T>,
|
||||
disableIdentityMap: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -83,10 +94,10 @@ export async function listForOwner<T extends { id: unknown }, K extends keyof T,
|
||||
* `assign`+`flush`.
|
||||
*/
|
||||
export async function findOwnedByUser<T extends { id: unknown }, K extends keyof T>(
|
||||
repo: EntityRepository<T>,
|
||||
repo: TrekRepository<T>,
|
||||
id: T['id'],
|
||||
ownerField: K,
|
||||
ownerId: FilterValue<T[K]>,
|
||||
): Promise<T | null> {
|
||||
return repo.findOne({ id, [ownerField]: ownerId } as FilterQuery<T>, { disableIdentityMap: true });
|
||||
return repo.findOne({ id, [ownerField]: ownerId } as FilterQuery<T>);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import {
|
||||
EntityRepository,
|
||||
type CountByOptions,
|
||||
type CountOptions,
|
||||
type Cursor,
|
||||
type DeleteOptions,
|
||||
type Dictionary,
|
||||
type EntityData,
|
||||
type EntityKey,
|
||||
type FilterQuery,
|
||||
type FindAllOptions,
|
||||
type FindByCursorOptions,
|
||||
type FindOneOptions,
|
||||
type FindOneOrFailOptions,
|
||||
type FindOptions,
|
||||
type GetKyselyOptions,
|
||||
type Loaded,
|
||||
@@ -14,7 +20,9 @@ import {
|
||||
type QueryBuilder,
|
||||
type RequiredEntityData,
|
||||
type SqlEntityManager,
|
||||
type StreamOptions,
|
||||
type UpdateOptions,
|
||||
type UpsertManyOptions,
|
||||
type UpsertOptions,
|
||||
type WithUsingOptions,
|
||||
} from '@mikro-orm/sql';
|
||||
@@ -157,6 +165,76 @@ export abstract class TrekRepository<Entity extends object> extends EntityReposi
|
||||
return super.count(where, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Task 7 review, M4: `TrekRepository` left seven DB-reaching base-class
|
||||
* methods unoverridden (none used anywhere in this program today —
|
||||
* `grep -rnE "\.(countBy|findAndCount|findByCursor|findOneOrFail|
|
||||
* insertMany|upsertMany|stream)\(" src/db/repositories/` was 0 hits — but
|
||||
* the FIRST one used would silently lose both guarantees: no
|
||||
* `validateRequestContext()`, and — for the read-shaped ones — no
|
||||
* `disableIdentityMap: true` default). Same shape as `findOne`/`find`/
|
||||
* `findAll` above: `Using` dropped for the same override-compatibility
|
||||
* reason documented on `findOne`.
|
||||
*/
|
||||
override async findOneOrFail<Hint extends string = never, Fields extends string = never, Excludes extends string = never>(
|
||||
where: FilterQuery<Entity>,
|
||||
options?: FindOneOrFailOptions<Entity, Hint, Fields, Excludes>,
|
||||
): Promise<Loaded<Entity, Hint, Fields, Excludes>> {
|
||||
this.validateRequestContext();
|
||||
const disableIdentityMap = options?.disableIdentityMap ?? true;
|
||||
return super.findOneOrFail(where, { ...options, disableIdentityMap });
|
||||
}
|
||||
|
||||
override async findAndCount<Hint extends string = never, Fields extends string = never, Excludes extends string = never>(
|
||||
where: FilterQuery<Entity>,
|
||||
options?: FindOptions<Entity, Hint, Fields, Excludes>,
|
||||
): Promise<[Loaded<Entity, Hint, Fields, Excludes>[], number]> {
|
||||
this.validateRequestContext();
|
||||
const disableIdentityMap = options?.disableIdentityMap ?? true;
|
||||
return super.findAndCount(where, { ...options, disableIdentityMap });
|
||||
}
|
||||
|
||||
override async findByCursor<
|
||||
Hint extends string = never,
|
||||
Fields extends string = never,
|
||||
Excludes extends string = never,
|
||||
IncludeCount extends boolean = true,
|
||||
Using extends string = never,
|
||||
>(
|
||||
options: WithUsingOptions<FindByCursorOptions<Entity, Hint, Fields, Excludes, IncludeCount>, Entity, Using>,
|
||||
): Promise<Cursor<Entity, Hint, Fields, Excludes, IncludeCount>> {
|
||||
this.validateRequestContext();
|
||||
const disableIdentityMap = options?.disableIdentityMap ?? true;
|
||||
return super.findByCursor({ ...options, disableIdentityMap });
|
||||
}
|
||||
|
||||
/** Grouping counts don't hydrate an entity — no identity map to isolate — so this only needs the fail-closed guard, matching `count` above. */
|
||||
override async countBy(groupBy: EntityKey<Entity> | readonly EntityKey<Entity>[], options?: CountByOptions<Entity>): Promise<Dictionary<number>> {
|
||||
this.validateRequestContext();
|
||||
return super.countBy(groupBy, options);
|
||||
}
|
||||
|
||||
override stream<Hint extends string = never, Fields extends string = never, Excludes extends string = never, Using extends string = never>(
|
||||
options?: WithUsingOptions<StreamOptions<Entity, Hint, Fields, Excludes>, Entity, Using>,
|
||||
): AsyncIterableIterator<Loaded<Entity, Hint, Fields, Excludes>> {
|
||||
this.validateRequestContext();
|
||||
const disableIdentityMap = options?.disableIdentityMap ?? true;
|
||||
return super.stream({ ...options, disableIdentityMap });
|
||||
}
|
||||
|
||||
override async insertMany(data: Entity[] | RequiredEntityData<Entity>[], options?: NativeInsertUpdateOptions<Entity>): Promise<Primary<Entity>[]> {
|
||||
this.validateRequestContext();
|
||||
return super.insertMany(data, options);
|
||||
}
|
||||
|
||||
override async upsertMany<Fields extends string = never>(
|
||||
entitiesOrData?: EntityData<Entity>[] | Entity[],
|
||||
options?: UpsertManyOptions<Entity, Fields>,
|
||||
): Promise<Entity[]> {
|
||||
this.validateRequestContext();
|
||||
return super.upsertMany(entitiesOrData, options);
|
||||
}
|
||||
|
||||
override async nativeUpdate(where: FilterQuery<Entity>, data: EntityData<Entity>, options?: UpdateOptions<Entity>): Promise<number> {
|
||||
this.validateRequestContext();
|
||||
return super.nativeUpdate(where, data, options);
|
||||
|
||||
@@ -62,6 +62,25 @@
|
||||
* not "parity with the legacy". Check which kind of seam a route's legacy
|
||||
* handler was (`git show <base>:<file>` on the actual statement, not the
|
||||
* route) before writing that test.
|
||||
*
|
||||
* **A THIRD shape narrows nothing at all: a PRE-COERCED `Number()` seam**
|
||||
* (Task 7 review, M2/A-M2). The two `Number()`-seam routes above still hand
|
||||
* `toRowId` the RAW STRING — the legacy code's own `Number(id)` conversion
|
||||
* moved to a repository-facing call site, so `toRowId` sees what the legacy
|
||||
* `Number()` used to see and narrows exactly as described. But on some
|
||||
* routes the legacy's `Number(id)` conversion itself survives UPSTREAM of
|
||||
* `toRowId`, and `toRowId` receives an already-coerced `number`, not the
|
||||
* original string — `oauth-api.controller.ts::revokeSession`'s `DELETE
|
||||
* /api/oauth/sessions/:id` is that shape on both the legacy and the
|
||||
* converted tree: `Number(id)` runs first, `toRowId(Number(id))` only
|
||||
* checks `Number.isSafeInteger`, and the legacy statement never matched a
|
||||
* non-safe-integer either — so `'0x10'`, `'1e1'`, `'16.0'` and `' 16'` all
|
||||
* reach the SAME row on both trees (verified live, Task 7 review security
|
||||
* report). There is no narrowing to name here, and no regression test
|
||||
* should claim one for this shape — record it as "the pre-coerced
|
||||
* `Number()` seam: full parity" and move on, the same way `passkey.service
|
||||
* .ts::adminResetPasskeys` (`:502-507`) already documents its own copy of
|
||||
* this exact shape.
|
||||
*/
|
||||
export function toRowId(value: unknown): number | null {
|
||||
if (typeof value === 'number') {
|
||||
|
||||
@@ -548,6 +548,12 @@ export class OauthService {
|
||||
sessionId: number,
|
||||
ip?: string | null,
|
||||
): Promise<{ error?: string; status?: number; success?: boolean }> {
|
||||
// `sessionId` is already a `number` here — `oauth-api.controller.ts`'s
|
||||
// `DELETE /api/oauth/sessions/:id` calls `Number(id)` before this method
|
||||
// (byte-identical to the legacy route), so `toRowId` only guards against
|
||||
// `NaN`/a non-safe-integer, never narrows a string shape (Task 7 review,
|
||||
// B-I2/A-M2's "pre-coerced Number() seam" — see `row-id.ts`'s own
|
||||
// docstring). This is full parity, not the accepted-narrowing shape.
|
||||
const id = toRowId(sessionId);
|
||||
if (id === null) return { error: 'Session not found', status: 404 };
|
||||
|
||||
|
||||
@@ -652,7 +652,10 @@ export class OidcService implements OnModuleDestroy {
|
||||
let user = await this.usersRepo.findByOidcIdentity(sub, config.issuer);
|
||||
if (!user) {
|
||||
// Never link/log-in to a guest (#1362) via its synthetic email.
|
||||
user = await this.usersRepo.findByEmailCI(email);
|
||||
// `email` is already JS-lowered above (O4 shape) — findByEmailLoweredBind
|
||||
// mirrors the legacy `LOWER(email) = ?` statement exactly; do not use
|
||||
// findByEmailCI here, it is AU12's `LOWER(email) = LOWER(?)` shape.
|
||||
user = await this.usersRepo.findByEmailLoweredBind(email);
|
||||
}
|
||||
|
||||
if (user) {
|
||||
|
||||
@@ -189,7 +189,16 @@ export class TrekWsAdapter extends WsAdapter {
|
||||
// The request rides along: the handshake reads the ws token off its query
|
||||
// string, so dropping it here would leave handleConnection with nothing
|
||||
// to authenticate.
|
||||
withRequestContext(this.orm, () => callback(socket, request));
|
||||
//
|
||||
// `handleConnection` is async and this listener is not — a rejection
|
||||
// inside it (or inside `withRequestContext` itself) would otherwise be
|
||||
// an unhandled rejection (T1-F7b; `applyPlatformUploads`'s `.catch(next)`
|
||||
// in `platform.routes.ts` is the sibling pattern for the pre-init HTTP
|
||||
// path). Logged through the adapter's own error path, not thrown —
|
||||
// there is no request/response here to propagate a failure to.
|
||||
Promise.resolve(withRequestContext(this.orm, () => callback(socket, request))).catch((err: unknown) =>
|
||||
logError(`ws connection handler error: ${err instanceof Error ? err.message : String(err)}`),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -209,7 +218,12 @@ export class TrekWsAdapter extends WsAdapter {
|
||||
if (!this.orm) {
|
||||
throw new Error('TrekWsAdapter: no MikroORM available to build a request context for this disconnect');
|
||||
}
|
||||
withRequestContext(this.orm, () => callback(...args));
|
||||
// Same T1-F7b shape as bindClientConnect above — handleDisconnect is
|
||||
// async and this listener is not, so an unhandled rejection here would
|
||||
// otherwise be silent.
|
||||
Promise.resolve(withRequestContext(this.orm, () => callback(...args))).catch((err: unknown) =>
|
||||
logError(`ws disconnect handler error: ${err instanceof Error ? err.message : String(err)}`),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user