From a926990e4a3f5facaeb25a8b7b953b12bec6e56f Mon Sep 17 00:00:00 2001 From: Maurice Date: Sat, 10 Oct 2026 11:50:35 +0200 Subject: [PATCH] fix(db): timestamp columns are written and stored in one canonical spelling A DbTimestamp brand, produced only by dbNow(), types the expiry writes of OAuth tokens and password reset links, and collection edits stamp updated_at the same way. parseDbTimestamp() reads the stored text as UTC and replaces the oauth-local parser; utcSuffix lives once beside it. A data migration rewrites the ISO values those writers left behind, and the OAuth session lists keep answering the expiries in ISO. Two outputs change on purpose. collections.updated_at used to come back in two spellings: a collection never edited answered the column default (2026-01-02 03:04:05), an edited one the ISO text its writer stored (2026-01-02T03:04:05.678Z). It now answers the canonical text in every case, in the PUT and cover responses and, once the migration has run, in every read; the shared schema types it as a plain string and the client does not read it. The ISO expiries of the OAuth session lists are rebuilt from the stored second-precision text, so they end in .000Z instead of carrying the milliseconds of the write. --- server/docs/nest-migration-history.md | 2 +- ...42700_timestamps_stored_in_one_spelling.ts | 37 ++++++++ .../db/repositories/Collections.repository.ts | 10 ++- .../db/repositories/OauthTokens.repository.ts | 9 +- .../PasswordResetTokens.repository.ts | 3 +- server/src/db/types/db-timestamp.type.ts | 35 +++++++- server/src/db/types/index.ts | 3 +- server/src/nest/admin/admin.helpers.ts | 5 -- server/src/nest/admin/admin.service.ts | 2 +- server/src/nest/auth/auth.helpers.ts | 6 +- server/src/nest/auth/auth.service.ts | 8 +- .../nest/oauth/oauth-token-retention.job.ts | 3 +- server/src/nest/oauth/oauth.helpers.ts | 8 -- server/src/nest/oauth/oauth.service.ts | 42 ++++++--- server/tests/unit/db/legacy-baseline.test.ts | 1 + .../OauthTokens.repository.test.ts | 11 +-- .../PasswordResetTokens.repository.test.ts | 5 +- .../db/timestamp-spelling-migration.test.ts | 90 +++++++++++++++++++ .../unit/db/types/db-timestamp.type.test.ts | 44 ++++++++- server/tests/unit/nest/auth.helpers.test.ts | 29 ------ server/tests/unit/nest/auth.service.test.ts | 12 +++ .../unit/nest/collections.service.test.ts | 15 ++++ .../nest/oauth-token-retention.job.test.ts | 2 +- server/tests/unit/nest/oauth.service.test.ts | 50 ++++++++++- 24 files changed, 346 insertions(+), 86 deletions(-) create mode 100644 server/src/db/migrations/Migration20200101042700_timestamps_stored_in_one_spelling.ts create mode 100644 server/tests/unit/db/timestamp-spelling-migration.test.ts diff --git a/server/docs/nest-migration-history.md b/server/docs/nest-migration-history.md index 3a2d27114..8ecb54863 100644 --- a/server/docs/nest-migration-history.md +++ b/server/docs/nest-migration-history.md @@ -907,7 +907,7 @@ services: the `auth.bridge` (`resolveAuthToggles`), `notifications.bridge` imports all became injections, while `PERMISSION_ACTIONS` stayed a plain const import and the `mcp/sessionManager` deep import kept its anti-cycle comment. The pure + module-scoped half moved to `admin.helpers.ts` — `compareVersions`, -`utcSuffix`, `BCRYPT_COST`, the import-time `isDocker` probe (a documented +`utcSuffix` (since moved to `db/types`, shared with `auth.helpers`), `BCRYPT_COST`, the import-time `isDocker` probe (a documented parity exception, auth.helpers precedent) and the 5-minute version cache, which stays module-scoped so the bridge instance and the container singleton share it. Ahead of the fold the 11 packing-template functions relocated to diff --git a/server/src/db/migrations/Migration20200101042700_timestamps_stored_in_one_spelling.ts b/server/src/db/migrations/Migration20200101042700_timestamps_stored_in_one_spelling.ts new file mode 100644 index 000000000..80e4a6d13 --- /dev/null +++ b/server/src/db/migrations/Migration20200101042700_timestamps_stored_in_one_spelling.ts @@ -0,0 +1,37 @@ +import { Migration } from '@mikro-orm/migrations'; + +/** + * Timestamps the app wrote in JavaScript's ISO spelling are stored in the + * spelling of every other DATETIME column. + * + * Every DATETIME column holds `YYYY-MM-DD HH:MM:SS` in UTC, the text SQLite's + * `CURRENT_TIMESTAMP` writes. Four columns were also written with + * `toISOString()` (`2026-01-02T03:04:05.678Z`): a collection's `updated_at` + * after an edit or a new cover, a password reset link's expiry, and the two + * expiries of an OAuth token. The two spellings do not compare as text, so a + * SQL `refresh_token_expires_at > CURRENT_TIMESTAMP` kept a token listed as + * live until the end of the day it expired. The writers now use the canonical + * spelling, and this turns the rows they left behind into it: the date, a + * space, the time to the second. + * + * Only values in the full ISO shape with a trailing `Z` are touched, so the + * statement can run again without changing anything. + */ +export class Migration20200101042700_timestamps_stored_in_one_spelling extends Migration { + override name = 'Migration20200101042700_timestamps_stored_in_one_spelling'; + + override async up(): Promise { + const columns: Array<[table: string, column: string]> = [ + ['collections', 'updated_at'], + ['password_reset_tokens', 'expires_at'], + ['oauth_tokens', 'access_token_expires_at'], + ['oauth_tokens', 'refresh_token_expires_at'], + ]; + for (const [table, column] of columns) { + await this.execute( + `UPDATE ${table} SET ${column} = replace(substr(${column}, 1, 19), 'T', ' ') ` + + `WHERE ${column} LIKE '____-__-__T__:__:__%Z'`, + ); + } + } +} diff --git a/server/src/db/repositories/Collections.repository.ts b/server/src/db/repositories/Collections.repository.ts index 07f294159..2384b7ab8 100644 --- a/server/src/db/repositories/Collections.repository.ts +++ b/server/src/db/repositories/Collections.repository.ts @@ -1,6 +1,7 @@ import type { Collections } from '../entities/Collections.entity'; import { TrekRepository } from './_shared/trek-repository'; import type { DB } from '../kysely/db'; +import { dbNow } from '../types'; /** `collections` — every scalar column, `getCollectionRow`'s (CL14) `SELECT *` shape. */ export interface CollectionRow { @@ -198,7 +199,8 @@ export class CollectionsRepository extends TrekRepository { * built (the service resolves `body.field !== undefined` itself, same * shape as every other repository's `presenceSet`-fed write) — an empty * `write` short-circuits before the `UPDATE`, matching the legacy - * `if (updates.length > 0)` guard. + * `if (updates.length > 0)` guard. `updated_at` is stamped with {@link dbNow}, + * the same text `CURRENT_TIMESTAMP` writes (it used to be `toISOString()`). */ async updateFields( id: number, @@ -213,7 +215,7 @@ export class CollectionsRepository extends TrekRepository { }>, ): Promise { if (Object.keys(write).length === 0) return; - await this.readDb().updateTable('collections').set({ ...write, updated_at: new Date().toISOString() }).where('id', '=', id).execute(); + await this.readDb().updateTable('collections').set({ ...write, updated_at: dbNow() }).where('id', '=', id).execute(); } /** CL31 (`setCollectionCover`) — `SELECT cover_image FROM collections WHERE id=?`. */ @@ -222,9 +224,9 @@ export class CollectionsRepository extends TrekRepository { return row?.cover_image; } - /** CL32 (`setCollectionCover`) — `UPDATE collections SET cover_image=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`. */ + /** CL32 (`setCollectionCover`) — `UPDATE collections SET cover_image=?, updated_at= WHERE id=?`. */ async setCoverImage(id: number, coverUrl: string | null): Promise { - await this.readDb().updateTable('collections').set({ cover_image: coverUrl, updated_at: new Date().toISOString() }).where('id', '=', id).execute(); + await this.readDb().updateTable('collections').set({ cover_image: coverUrl, updated_at: dbNow() }).where('id', '=', id).execute(); } /** CL35 (`deleteCollection`) — `DELETE FROM collections WHERE id=?` (CASCADE drops members + places + tags). */ diff --git a/server/src/db/repositories/OauthTokens.repository.ts b/server/src/db/repositories/OauthTokens.repository.ts index 5a1086124..77103f93d 100644 --- a/server/src/db/repositories/OauthTokens.repository.ts +++ b/server/src/db/repositories/OauthTokens.repository.ts @@ -3,6 +3,7 @@ import { type AssertRowKeys } from './_shared/rows'; import { columnRef, currentTimestamp } from '../dialect/sql-functions'; import { TrekRepository } from './_shared/trek-repository'; import type { DB } from '../kysely/db'; +import type { DbTimestamp } from '../types'; /** * The Kysely-side table shape `em.getKysely()` needs for `collectChainIds`'s @@ -24,8 +25,8 @@ export interface NewOauthTokenRow { refresh_token_hash: string; scopes: string; audience: string | null; - access_token_expires_at: string; - refresh_token_expires_at: string; + access_token_expires_at: DbTimestamp; + refresh_token_expires_at: DbTimestamp; parent_token_id: number | null; } @@ -356,12 +357,12 @@ export class OauthTokensRepository extends TrekRepository { * @txIndependent a retention sweep: every pass leaves a consistent table, and the * next sweep picks up what a failed one left. */ - async deleteExpiredBefore(cutoffIso: string, maxPasses = 50): Promise { + async deleteExpiredBefore(cutoff: DbTimestamp, maxPasses = 50): Promise { let total = 0; for (let pass = 0; pass < maxPasses; pass++) { const result = await this.kysely() .deleteFrom('oauth_tokens') - .where('refresh_token_expires_at', '<', cutoffIso) + .where('refresh_token_expires_at', '<', cutoff) .where('id', 'not in', (eb) => eb.selectFrom('oauth_tokens as child').select('child.parent_token_id').where('child.parent_token_id', 'is not', null), ) diff --git a/server/src/db/repositories/PasswordResetTokens.repository.ts b/server/src/db/repositories/PasswordResetTokens.repository.ts index bc4323d2e..ed2cf5076 100644 --- a/server/src/db/repositories/PasswordResetTokens.repository.ts +++ b/server/src/db/repositories/PasswordResetTokens.repository.ts @@ -1,6 +1,7 @@ import type { PasswordResetTokens } from '../entities/PasswordResetTokens.entity'; import type { AssertRowKeys } from './_shared/rows'; import { currentTimestamp } from '../dialect/sql-functions'; +import type { DbTimestamp } from '../types'; import { TrekRepository } from './_shared/trek-repository'; /** A `password_reset_tokens` row as the API emits it. */ @@ -20,7 +21,7 @@ const _passwordResetTokenRowKeys: AssertRowKeys { const [base, pre] = v.split('-pre.'); diff --git a/server/src/nest/admin/admin.service.ts b/server/src/nest/admin/admin.service.ts index ef1012a20..2ae3f316a 100644 --- a/server/src/nest/admin/admin.service.ts +++ b/server/src/nest/admin/admin.service.ts @@ -62,11 +62,11 @@ import { compareVersions, isDocker, readVersionCache, - utcSuffix, writeVersionCache, type VersionInfo, } from './admin.helpers'; import { MANAGED_FORBIDDEN_ERROR } from '../common/managed'; +import { utcSuffix } from '../../db/types'; import { SessionsService } from '../sessions/sessions.service'; /** Outbound GitHub calls: hard timeout and response-size cap (server/CLAUDE.md). */ diff --git a/server/src/nest/auth/auth.helpers.ts b/server/src/nest/auth/auth.helpers.ts index 40422ea6c..f40df04b2 100644 --- a/server/src/nest/auth/auth.helpers.ts +++ b/server/src/nest/auth/auth.helpers.ts @@ -1,6 +1,7 @@ import bcrypt from 'bcryptjs'; import crypto from 'crypto'; import { User } from '../../types'; +import { utcSuffix } from '../../db/types'; import { decrypt_api_key } from '../common/crypto/apiKeyCrypto'; /** @@ -48,11 +49,6 @@ export const ADMIN_SETTINGS_KEYS = [ // Helpers (exported for route-level use where needed) // --------------------------------------------------------------------------- -export function utcSuffix(ts: string | null | undefined): string | null { - if (!ts) return null; - return ts.endsWith('Z') ? ts : ts.replace(' ', 'T') + 'Z'; -} - export function stripUserForClient(user: User): Record { const { password_hash: _p, diff --git a/server/src/nest/auth/auth.service.ts b/server/src/nest/auth/auth.service.ts index 41d8481ca..716a7e3b3 100644 --- a/server/src/nest/auth/auth.service.ts +++ b/server/src/nest/auth/auth.service.ts @@ -8,7 +8,7 @@ import QRCode from 'qrcode'; import { randomBytes, createHash } from 'crypto'; import type { Request, Response } from 'express'; import { WEB_PUSH_CHANNEL_ID } from '@trek/shared'; -import { readEnv } from '../../app-config'; +import { getAppUrl, readEnv } from '../../app-config'; import { JWT_SECRET } from '../../config'; import { UnitOfWork } from '../database/unit-of-work'; import { PermissionsService } from '../permissions/permissions.service'; @@ -55,7 +55,7 @@ import { WebauthnConfigService } from './webauthn-config.service'; import { setAuthCookie, clearAuthCookie } from '../common/cookie'; import { MailerService } from '../notifications/mailer/mailer.service'; import { AllowedFileTypesService } from '../files/allowed-file-types.service'; -import { getAppUrl } from '../../app-config'; +import { dbNow, parseDbTimestamp } from '../../db/types'; import { ADMIN_SETTINGS_KEYS, BCRYPT_COST, @@ -1006,7 +1006,7 @@ export class AuthService { const raw = randomBytes(PASSWORD_RESET_TOKEN_BYTES).toString('base64url'); const token_hash = hashResetToken(raw); - const expires_at = new Date(Date.now() + PASSWORD_RESET_TTL_MS).toISOString(); + const expires_at = dbNow(new Date(Date.now() + PASSWORD_RESET_TTL_MS)); // Invalidate any prior unconsumed tokens for this user and issue the new one // together, so there is always exactly one live reset link in flight. await this.uow.transactional(async () => { @@ -1042,7 +1042,7 @@ export class AuthService { if (!row) return { error: 'Invalid or expired reset link', status: 400 }; if (row.consumed_at) return { error: 'This reset link has already been used', status: 400 }; - if (new Date(row.expires_at).getTime() < Date.now()) { + if ((parseDbTimestamp(row.expires_at)?.getTime() ?? Number.NaN) < Date.now()) { return { error: 'Reset link has expired. Please request a new one.', status: 400 }; } diff --git a/server/src/nest/oauth/oauth-token-retention.job.ts b/server/src/nest/oauth/oauth-token-retention.job.ts index 255a5847d..3d3de7856 100644 --- a/server/src/nest/oauth/oauth-token-retention.job.ts +++ b/server/src/nest/oauth/oauth-token-retention.job.ts @@ -3,6 +3,7 @@ import { InjectRepository } from '@mikro-orm/nestjs'; import { OauthTokens } from '../../db/entities/OauthTokens.entity'; import type { OauthTokensRepository } from '../../db/repositories/OauthTokens.repository'; import { logError, logInfo } from '../audit/audit-log.logger'; +import { dbNow } from '../../db/types'; import { CronRegistrarService } from '../scheduling/cron-registrar.service'; /** How long a token is kept after its refresh token expired. */ @@ -30,7 +31,7 @@ export class OauthTokenRetentionJob implements OnApplicationBootstrap { async tick(now: Date = new Date()): Promise { try { - const cutoff = new Date(now.getTime() - OAUTH_TOKEN_RETENTION_DAYS * 24 * 60 * 60 * 1000).toISOString(); + const cutoff = dbNow(new Date(now.getTime() - OAUTH_TOKEN_RETENTION_DAYS * 24 * 60 * 60 * 1000)); const removed = await this.tokens.deleteExpiredBefore(cutoff); if (removed > 0) logInfo(`OAuth token retention: removed ${removed} expired token(s)`); } catch (err: unknown) { diff --git a/server/src/nest/oauth/oauth.helpers.ts b/server/src/nest/oauth/oauth.helpers.ts index c613a3c23..f6446ee7b 100644 --- a/server/src/nest/oauth/oauth.helpers.ts +++ b/server/src/nest/oauth/oauth.helpers.ts @@ -24,14 +24,6 @@ export const REFRESH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days rolling */ export const REFRESH_ROTATION_GRACE_MS = 30 * 1000; -/** SQLite writes CURRENT_TIMESTAMP as UTC without a zone; JS would read it as local. */ -export function parseSqliteUtc(ts: string | null | undefined): Date | null { - if (!ts) return null; - const iso = ts.endsWith('Z') ? ts : ts.replace(' ', 'T') + 'Z'; - const d = new Date(iso); - return Number.isNaN(d.getTime()) ? null : d; -} - // PKCE format (RFC 7636) export const CODE_CHALLENGE_RE = /^[A-Za-z0-9_-]{43}$/; export const CODE_VERIFIER_RE = /^[A-Za-z0-9\-._~]{43,128}$/; diff --git a/server/src/nest/oauth/oauth.service.ts b/server/src/nest/oauth/oauth.service.ts index a5e06af14..4a4097775 100644 --- a/server/src/nest/oauth/oauth.service.ts +++ b/server/src/nest/oauth/oauth.service.ts @@ -32,14 +32,36 @@ import { generateAccessToken, generateRefreshToken, hashToken, - parseSqliteUtc, redirectUriMatches, timingSafeEqualHex, } from './oauth.helpers'; +import { dbNow, parseDbTimestamp } from '../../db/types'; import { AUTH_CODE_TTL_MS, PendingCodeStore, pendingCodesSlot, type PendingCode } from './oauth.pending-codes'; export type { PendingCode } from './oauth.pending-codes'; +/** + * A stored expiry lies in the past. A value that does not parse counts as not + * expired, as the `new Date(value) < new Date()` this replaces did. + */ +function hasExpired(stored: string): boolean { + const at = parseDbTimestamp(stored); + return at !== null && at.getTime() < Date.now(); +} + +/** + * The session lists have always answered the two expiries in the ISO spelling + * the issuer used to store (`toISOString()`); the columns now hold the canonical + * text, so the lists turn it back. Seconds precision: the milliseconds are `.000`. + */ +function expiriesAsIso(row: { access_token_expires_at: string; refresh_token_expires_at: string }) { + const iso = (stored: string) => parseDbTimestamp(stored)?.toISOString() ?? stored; + return { + access_token_expires_at: iso(row.access_token_expires_at), + refresh_token_expires_at: iso(row.refresh_token_expires_at), + }; +} + export interface OAuthTokenInfo { user: User; scopes: string[]; @@ -307,8 +329,8 @@ export class OauthService { refresh_token_hash: refreshHash, scopes: JSON.stringify(scopes), audience, - access_token_expires_at: accessExpiry.toISOString(), - refresh_token_expires_at: refreshExpiry.toISOString(), + access_token_expires_at: dbNow(accessExpiry), + refresh_token_expires_at: dbNow(refreshExpiry), parent_token_id: parentTokenId, }); @@ -353,8 +375,8 @@ export class OauthService { refresh_token_hash: placeholderHash, scopes: JSON.stringify(scopes), audience, - access_token_expires_at: accessExpiry.toISOString(), - refresh_token_expires_at: now.toISOString(), + access_token_expires_at: dbNow(accessExpiry), + refresh_token_expires_at: dbNow(now), parent_token_id: null, }); @@ -389,7 +411,7 @@ export class OauthService { if (!row) return null; if (row.revoked_at) return null; - if (new Date(row.access_token_expires_at) < new Date()) return null; + if (hasExpired(row.access_token_expires_at)) return null; return { user: { id: row.user_id, username: row.username, email: row.email, role: row.role as 'admin' | 'user' }, @@ -432,7 +454,7 @@ export class OauthService { * has every child revoked with it, so neither can slip through here. */ private async isConcurrentRotation(row: OauthTokenRefreshRow): Promise { - const revokedAt = parseSqliteUtc(row.revoked_at); + const revokedAt = parseDbTimestamp(row.revoked_at); if (!revokedAt) return false; if (Date.now() - revokedAt.getTime() > REFRESH_ROTATION_GRACE_MS) return false; const successor = await this.tokens.findSuccessorAlive(row.id); @@ -494,7 +516,7 @@ export class OauthService { return { error: 'invalid_grant', status: 400 }; } - if (new Date(row.refresh_token_expires_at) < new Date()) return { error: 'invalid_grant', status: 400 }; + if (hasExpired(row.refresh_token_expires_at)) return { error: 'invalid_grant', status: 400 }; // Revoke old pair immediately (rotation) and issue new pair linked to old row. // Do NOT revoke active MCP sessions here: a legitimate refresh isn't a security @@ -543,7 +565,7 @@ export class OauthService { async listOAuthSessions(userId: number): Promise[]> { const rows = await this.tokens.listActiveByUser(userId); - return rows.map(r => ({ ...r, scopes: JSON.parse(r.scopes) })); + return rows.map(r => ({ ...r, ...expiriesAsIso(r), scopes: JSON.parse(r.scopes) })); } async revokeSession( @@ -712,7 +734,7 @@ export class OauthService { } catch { scopes = null; } - return { ...r, scopes }; + return { ...r, ...expiriesAsIso(r), scopes }; }); } diff --git a/server/tests/unit/db/legacy-baseline.test.ts b/server/tests/unit/db/legacy-baseline.test.ts index 72c1ca92e..c48adf81b 100644 --- a/server/tests/unit/db/legacy-baseline.test.ts +++ b/server/tests/unit/db/legacy-baseline.test.ts @@ -38,6 +38,7 @@ const UNNUMBERED = [ 'Migration20200101042400_one_account_per_email_whatever_its_case', 'Migration20200101042500_a_cron_tick_runs_in_one_process', 'Migration20200101042600_a_session_row_per_sign_in', + 'Migration20200101042700_timestamps_stored_in_one_spelling', ]; // The last step the positional runner ever had; planLegacyBaseline refuses a // schema_version past it. diff --git a/server/tests/unit/db/repositories/OauthTokens.repository.test.ts b/server/tests/unit/db/repositories/OauthTokens.repository.test.ts index 9deb4e9e7..134b4aae2 100644 --- a/server/tests/unit/db/repositories/OauthTokens.repository.test.ts +++ b/server/tests/unit/db/repositories/OauthTokens.repository.test.ts @@ -10,6 +10,7 @@ import { deleteRows, findRow, findRows, insertRow, updateRows } from '../../../h import type { OauthTokensRepository } from '../../../../src/db/repositories/OauthTokens.repository'; import { UnitOfWork } from '../../../../src/nest/database/unit-of-work'; import { withRequestContext } from '../../../../src/nest/database/request-context'; +import { dbNow } from '../../../../src/db/types'; const testDb = createSnapshotTestDb(); let t: TestOrm; @@ -83,8 +84,8 @@ describe('OauthTokensRepository', () => { it('OAUTHTOKREPO-001: writes exactly the given columns', async () => { const { user } = createUser(testDb); await seedClient(user.id, 'proto-1'); - const accessExpiry = new Date(Date.now() + 3600_000).toISOString(); - const refreshExpiry = new Date(Date.now() + 30 * 24 * 3600_000).toISOString(); + const accessExpiry = dbNow(new Date(Date.now() + 3600_000)); + const refreshExpiry = dbNow(new Date(Date.now() + 30 * 24 * 3600_000)); await tokens.insertToken({ client_id: 'proto-1', user_id: user.id, @@ -115,7 +116,7 @@ describe('OauthTokensRepository', () => { const parentId = await seedToken({ clientId: 'proto-2', userId: user.id }); await tokens.insertToken({ client_id: 'proto-2', user_id: user.id, access_token_hash: 'a2', refresh_token_hash: 'r2', scopes: '[]', audience: null, - access_token_expires_at: new Date().toISOString(), refresh_token_expires_at: new Date().toISOString(), parent_token_id: parentId, + access_token_expires_at: dbNow(), refresh_token_expires_at: dbNow(), parent_token_id: parentId, }); const row = await findRow(t, OauthTokens, { access_token_hash: 'a2' }); expect(row?.parent_token_id).toBe(parentId); @@ -557,8 +558,8 @@ describe('OauthTokensRepository', () => { }); describe('deleteExpiredBefore (retention)', () => { - const longAgo = '2026-01-01T00:00:00.000Z'; - const cutoff = '2026-06-01T00:00:00.000Z'; + const longAgo = '2026-01-01 00:00:00'; + const cutoff = dbNow(new Date('2026-06-01T00:00:00.000Z')); const ids = async () => (await findRows(t, OauthTokens, {}, { id: 'asc' })).map((r) => r.id); it('OAUTHTOKREPO-040: deletes a whole expired chain, parents after their children', async () => { diff --git a/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts b/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts index 2c5d4675b..fc807f514 100644 --- a/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts +++ b/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts @@ -1,5 +1,6 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; import { createHash } from 'crypto'; +import { dbNow } from '../../../../src/db/types'; import { createSnapshotTestDb } from '../../../helpers/db-mock'; import { resetTestDb } from '../../../helpers/test-db'; import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; @@ -52,7 +53,7 @@ describe('PasswordResetTokensRepository', () => { it('PWDRESETREPO-001: writes the exact column set, hash-only (the raw token never appears)', async () => { const { user } = createUser(testDb); const tokenHash = hash('raw-token-value'); - const expiresAt = new Date(Date.now() + 60 * 60 * 1000).toISOString(); + const expiresAt = dbNow(new Date(Date.now() + 60 * 60 * 1000)); await tokens.insertToken({ user_id: user.id, token_hash: tokenHash, expires_at: expiresAt, created_ip: '1.2.3.4' }); @@ -63,7 +64,7 @@ describe('PasswordResetTokensRepository', () => { it('PWDRESETREPO-002: writes a NULL created_ip', async () => { const { user } = createUser(testDb); const tokenHash = hash('no-ip-token'); - await tokens.insertToken({ user_id: user.id, token_hash: tokenHash, expires_at: new Date().toISOString(), created_ip: null }); + await tokens.insertToken({ user_id: user.id, token_hash: tokenHash, expires_at: dbNow(), created_ip: null }); const row = await findRow(t, PasswordResetTokens, { token_hash: tokenHash }); expect(row?.created_ip).toBeNull(); diff --git a/server/tests/unit/db/timestamp-spelling-migration.test.ts b/server/tests/unit/db/timestamp-spelling-migration.test.ts new file mode 100644 index 000000000..3e212e094 --- /dev/null +++ b/server/tests/unit/db/timestamp-spelling-migration.test.ts @@ -0,0 +1,90 @@ +/** + * `Migration20200101042700_timestamps_stored_in_one_spelling`: the four + * DATETIME columns the app also wrote with `toISOString()` end up in the + * canonical `YYYY-MM-DD HH:MM:SS` text; canonical values, NULLs and anything + * not in the full ISO shape stay as they are, and a second run changes nothing. + */ +import { describe, expect, it } from 'vitest'; +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery, runMigrationDirect } from '../../helpers/migration-step'; +import { Migration20200101042700_timestamps_stored_in_one_spelling } from '../../../src/db/migrations/Migration20200101042700_timestamps_stored_in_one_spelling'; +import type { MikroORM } from '@mikro-orm/sqlite'; + +const TARGET = 'Migration20200101042700_timestamps_stored_in_one_spelling'; + +async function ormBeforeTarget(): Promise { + const orm = await createMigrationOrm(); + const names = await pendingNames(orm); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); + await migrateTo(orm, names[idx - 1]); + return orm; +} + +async function seed(orm: MikroORM): Promise { + await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')"); + await rawExec(orm, "INSERT INTO collections (id, owner_id, name, updated_at) VALUES (1, 1, 'iso', '2026-03-04T05:06:07.890Z')"); + await rawExec(orm, "INSERT INTO collections (id, owner_id, name, updated_at) VALUES (2, 1, 'canonical', '2026-03-04 05:06:07')"); + await rawExec(orm, "INSERT INTO collections (id, owner_id, name, updated_at) VALUES (3, 1, 'null', NULL)"); + await rawExec(orm, "INSERT INTO collections (id, owner_id, name, updated_at) VALUES (4, 1, 'offset', '2026-03-04T05:06:07+02:00')"); + await rawExec(orm, "INSERT INTO collections (id, owner_id, name, updated_at) VALUES (5, 1, 'no-millis', '2026-03-04T05:06:07Z')"); + await rawExec( + orm, + "INSERT INTO password_reset_tokens (id, user_id, token_hash, expires_at) VALUES (1, 1, 'h1', '2026-05-06T07:08:09.123Z'), (2, 1, 'h2', '2026-05-06 07:08:09')", + ); + await rawExec(orm, "INSERT INTO oauth_clients (id, name, client_id, client_secret_hash) VALUES ('c', 'Client', 'cid', 'x')"); + await rawExec( + orm, + `INSERT INTO oauth_tokens (id, client_id, user_id, access_token_hash, refresh_token_hash, access_token_expires_at, refresh_token_expires_at) + VALUES (1, 'cid', 1, 'a1', 'r1', '2026-07-08T09:10:11.000Z', '2026-08-08T09:10:11.999Z'), + (2, 'cid', 1, 'a2', 'r2', '2026-07-08 09:10:11', '2026-08-08 09:10:11')`, + ); +} + +const read = async (orm: MikroORM) => ({ + collections: await rawQuery(orm, 'SELECT id, updated_at FROM collections ORDER BY id'), + resets: await rawQuery(orm, 'SELECT id, expires_at FROM password_reset_tokens ORDER BY id'), + tokens: await rawQuery(orm, 'SELECT id, access_token_expires_at, refresh_token_expires_at FROM oauth_tokens ORDER BY id'), +}); + +const EXPECTED = { + collections: [ + { id: 1, updated_at: '2026-03-04 05:06:07' }, + { id: 2, updated_at: '2026-03-04 05:06:07' }, + { id: 3, updated_at: null }, + { id: 4, updated_at: '2026-03-04T05:06:07+02:00' }, + { id: 5, updated_at: '2026-03-04 05:06:07' }, + ], + resets: [ + { id: 1, expires_at: '2026-05-06 07:08:09' }, + { id: 2, expires_at: '2026-05-06 07:08:09' }, + ], + tokens: [ + { id: 1, access_token_expires_at: '2026-07-08 09:10:11', refresh_token_expires_at: '2026-08-08 09:10:11' }, + { id: 2, access_token_expires_at: '2026-07-08 09:10:11', refresh_token_expires_at: '2026-08-08 09:10:11' }, + ], +}; + +describe('timestamp spelling migration', () => { + it('TSSPELLMIG-001: ISO values become the canonical text, everything else stays', async () => { + const orm = await ormBeforeTarget(); + try { + await seed(orm); + await migrateTo(orm, TARGET); + expect(await read(orm)).toEqual(EXPECTED); + } finally { + await orm.close(true); + } + }, 30000); + + it('TSSPELLMIG-002: running it again changes nothing', async () => { + const orm = await ormBeforeTarget(); + try { + await seed(orm); + await migrateTo(orm, TARGET); + await runMigrationDirect(orm, Migration20200101042700_timestamps_stored_in_one_spelling); + expect(await read(orm)).toEqual(EXPECTED); + } finally { + await orm.close(true); + } + }, 30000); +}); diff --git a/server/tests/unit/db/types/db-timestamp.type.test.ts b/server/tests/unit/db/types/db-timestamp.type.test.ts index 237f85697..28971fc93 100644 --- a/server/tests/unit/db/types/db-timestamp.type.test.ts +++ b/server/tests/unit/db/types/db-timestamp.type.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { DB_TIMESTAMP_RE, DbTimestampType, dbNow } from '../../../../src/db/types'; +import { DB_TIMESTAMP_RE, DbTimestampType, dbNow, parseDbTimestamp, utcSuffix } from '../../../../src/db/types'; // The value converters take no platform: the wire format is the same text on // every dialect (see db-timestamp.type.ts). const type = new DbTimestampType(); @@ -46,3 +46,45 @@ describe('DbTimestampType', () => { expect(type.runtimeType).toBe('string'); }); }); + +describe('parseDbTimestamp', () => { + it('TS-101: reads the canonical text as UTC, whatever the process time zone', () => { + expect(parseDbTimestamp('2026-09-21 13:05:09')?.toISOString()).toBe('2026-09-21T13:05:09.000Z'); + }); + + it('TS-102: still reads an ISO value an older writer left behind', () => { + expect(parseDbTimestamp('2026-09-21T13:05:09.123Z')?.toISOString()).toBe('2026-09-21T13:05:09.123Z'); + }); + + it('TS-103: empty and unparseable values are null', () => { + expect(parseDbTimestamp(null)).toBeNull(); + expect(parseDbTimestamp(undefined)).toBeNull(); + expect(parseDbTimestamp('')).toBeNull(); + expect(parseDbTimestamp('not a date')).toBeNull(); + }); + + it('TS-104: round-trips dbNow to the second', () => { + const at = new Date(Date.UTC(2026, 0, 2, 3, 4, 5, 999)); + expect(parseDbTimestamp(dbNow(at))?.getTime()).toBe(Date.UTC(2026, 0, 2, 3, 4, 5)); + }); +}); + +describe('utcSuffix', () => { + it('TS-111: returns null for null, undefined and the empty string', () => { + expect(utcSuffix(null)).toBeNull(); + expect(utcSuffix(undefined)).toBeNull(); + expect(utcSuffix('')).toBeNull(); + }); + + it('TS-112: returns a timestamp already ending with Z unchanged', () => { + expect(utcSuffix('2024-01-01T12:00:00Z')).toBe('2024-01-01T12:00:00Z'); + }); + + it('TS-113: replaces the space with T and appends Z for the canonical text', () => { + expect(utcSuffix('2024-01-01 12:00:00')).toBe('2024-01-01T12:00:00Z'); + }); + + it('TS-114: appends Z when T is present but Z is missing', () => { + expect(utcSuffix('2024-06-15T08:30:00')).toBe('2024-06-15T08:30:00Z'); + }); +}); diff --git a/server/tests/unit/nest/auth.helpers.test.ts b/server/tests/unit/nest/auth.helpers.test.ts index 3ca74b2e2..6c02dc6df 100644 --- a/server/tests/unit/nest/auth.helpers.test.ts +++ b/server/tests/unit/nest/auth.helpers.test.ts @@ -17,7 +17,6 @@ vi.mock('../../../src/nest/common/crypto/apiKeyCrypto', () => ({ })); import { - utcSuffix, stripUserForClient, maskKey, normalizeBackupCode, @@ -28,34 +27,6 @@ import { import { avatarUrl } from '../../../src/nest/common/avatarUrl'; import type { User } from '../../../src/types'; -// ── utcSuffix ──────────────────────────────────────────────────────────────── - -describe('utcSuffix', () => { - it('returns null for null', () => { - expect(utcSuffix(null)).toBeNull(); - }); - - it('returns null for undefined', () => { - expect(utcSuffix(undefined)).toBeNull(); - }); - - it('returns null for empty string', () => { - expect(utcSuffix('')).toBeNull(); - }); - - it('returns timestamp unchanged when already ending with Z', () => { - expect(utcSuffix('2024-01-01T12:00:00Z')).toBe('2024-01-01T12:00:00Z'); - }); - - it('replaces space with T and appends Z for SQLite-style datetime', () => { - expect(utcSuffix('2024-01-01 12:00:00')).toBe('2024-01-01T12:00:00Z'); - }); - - it('appends Z when T is present but Z is missing', () => { - expect(utcSuffix('2024-06-15T08:30:00')).toBe('2024-06-15T08:30:00Z'); - }); -}); - // ── stripUserForClient ─────────────────────────────────────────────────────── function makeUser(overrides: Partial = {}): User { diff --git a/server/tests/unit/nest/auth.service.test.ts b/server/tests/unit/nest/auth.service.test.ts index 090d4f327..17784c884 100644 --- a/server/tests/unit/nest/auth.service.test.ts +++ b/server/tests/unit/nest/auth.service.test.ts @@ -1105,6 +1105,18 @@ describe('resetPassword', () => { .toEqual({ error: 'Reset link has expired. Please request a new one.', status: 400 }); }); + it('AUTH-DB-083b: the reset link stores its expiry in the canonical UTC text and expires on it, not on local time', async () => { + const { user } = createUser(testDb); + const issued = await svc.requestPasswordReset(user.email, null); + const row = await findRow(orm, PasswordResetTokens, { user: user.id }); + expect(row!.expires_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/); + + const aMinuteAgo = new Date(Date.now() - 60_000).toISOString().slice(0, 19).replace('T', ' '); + await updateRows(orm, PasswordResetTokens, { user: user.id }, { expires_at: aMinuteAgo }); + expect(await svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' })) + .toEqual({ error: 'Reset link has expired. Please request a new one.', status: 400 }); + }); + it('AUTH-DB-084: an MFA-enabled account demands a code, then consumes a backup code', async () => { const { user } = createUser(testDb); const secret = authenticator.generateSecret(); diff --git a/server/tests/unit/nest/collections.service.test.ts b/server/tests/unit/nest/collections.service.test.ts index cb7cd240e..a5b6aa478 100644 --- a/server/tests/unit/nest/collections.service.test.ts +++ b/server/tests/unit/nest/collections.service.test.ts @@ -209,6 +209,21 @@ describe('collections CRUD + visibility', () => { try { await svc.getCollection(b.id, col.id); } catch (e) { expect((e as { status: number }).status).toBe(404); } }); + it('COLLECTIONS-SVC-003b: an edit and a new cover stamp updated_at in the canonical timestamp text', async () => { + const a = createUser(testDb).user; + const col = await svc.createCollection(a.id, { name: 'Stamped' }); + await updateRows(await orm(), Collections, { id: col.id }, { updated_at: '2000-01-01 00:00:00' }); + + const updated = await svc.updateCollection(a.id, col.id, { name: 'Renamed' }); + expect(updated.updated_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/); + expect(updated.updated_at).not.toBe('2000-01-01 00:00:00'); + + await updateRows(await orm(), Collections, { id: col.id }, { updated_at: '2000-01-01 00:00:00' }); + const covered = await svc.setCollectionCover(a.id, col.id, '/uploads/covers/x.jpg'); + expect(covered.updated_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/); + expect(covered.updated_at).not.toBe('2000-01-01 00:00:00'); + }); + it('COLLECTIONS-SVC-003: updateCollection renames; reorder only touches visible rows', async () => { const a = createUser(testDb).user; const col = await svc.createCollection(a.id, { name: 'Old' }); diff --git a/server/tests/unit/nest/oauth-token-retention.job.test.ts b/server/tests/unit/nest/oauth-token-retention.job.test.ts index 81f9006b2..6218a7fca 100644 --- a/server/tests/unit/nest/oauth-token-retention.job.test.ts +++ b/server/tests/unit/nest/oauth-token-retention.job.test.ts @@ -28,7 +28,7 @@ describe('OauthTokenRetentionJob', () => { const del = vi.fn().mockResolvedValue(4); await make(del).job.tick(new Date('2026-10-07T00:00:00.000Z')); expect(OAUTH_TOKEN_RETENTION_DAYS).toBe(30); - expect(del).toHaveBeenCalledWith('2026-09-07T00:00:00.000Z'); + expect(del).toHaveBeenCalledWith('2026-09-07 00:00:00'); expect(logMock.logInfo).toHaveBeenCalledWith('OAuth token retention: removed 4 expired token(s)'); }); diff --git a/server/tests/unit/nest/oauth.service.test.ts b/server/tests/unit/nest/oauth.service.test.ts index 17732baae..e73032532 100644 --- a/server/tests/unit/nest/oauth.service.test.ts +++ b/server/tests/unit/nest/oauth.service.test.ts @@ -64,7 +64,7 @@ import { sweepPendingCodes, } from '../../../src/nest/oauth/oauth.pending-codes'; import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; -import { insertRow, updateRows } from '../../helpers/factories/rows'; +import { findRow, insertRow, updateRows } from '../../helpers/factories/rows'; import { dbNow } from '../../../src/db/types'; import { AuditLog } from '../../../src/db/entities/AuditLog.entity'; import type { AuditLogRepository } from '../../../src/db/repositories/AuditLog.repository'; @@ -599,6 +599,34 @@ describe('listOAuthSessions + revokeSession', () => { expect(sessions[0].client_id).toBe(clientId); }); + it('stores both expiries in the canonical text and lists them in the ISO spelling the API has always answered', async () => { + const { user } = createUser(testDb); + const created = await makeClient(user.id); + const clientId = created.client!.client_id as string; + + await issueTokens(clientId, user.id, ['trips:read']); + const row = await findRow(t, OauthTokens, { user: user.id }); + expect(row!.access_token_expires_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/); + expect(row!.refresh_token_expires_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/); + + const [session] = await listOAuthSessions(user.id); + expect(session.access_token_expires_at).toBe(`${row!.access_token_expires_at.replace(' ', 'T')}.000Z`); + expect(session.refresh_token_expires_at).toBe(`${row!.refresh_token_expires_at.replace(' ', 'T')}.000Z`); + const [adminRow] = (await svc.listAllOAuthSessions()) as Array>; + expect(adminRow.access_token_expires_at).toBe(session.access_token_expires_at); + }); + + it('a legacy ISO expiry still lists as stored', async () => { + const { user } = createUser(testDb); + const created = await makeClient(user.id); + const clientId = created.client!.client_id as string; + await issueTokens(clientId, user.id, ['trips:read']); + await updateRows(t, OauthTokens, { user: user.id }, { access_token_expires_at: '2999-01-02T03:04:05.678Z', refresh_token_expires_at: '2999-01-02T03:04:05.678Z' }); + + const [session] = await listOAuthSessions(user.id); + expect(session.access_token_expires_at).toBe('2999-01-02T03:04:05.678Z'); + }); + it('revoked session is not listed', async () => { const { user } = createUser(testDb); const created = await makeClient(user.id); @@ -1238,6 +1266,26 @@ describe('branches the legacy suite could not reach', () => { expect(await getUserByAccessToken(tokens.access_token)).toBeNull(); }); + it('rejects an access token whose canonical expiry passed earlier today (UTC, not local time)', async () => { + const { user } = createUser(testDb); + const created = await makeClient(user.id); + const clientId = (created.client as { client_id: string }).client_id; + const tokens = await issueTokens(clientId, user.id, ['trips:read']); + await updateRows(t, OauthTokens, {}, { access_token_expires_at: dbNow(new Date(Date.now() - 60_000)) }); + + expect(await getUserByAccessToken(tokens.access_token)).toBeNull(); + }); + + it('refreshTokens rejects a refresh token whose canonical expiry passed', async () => { + const { user } = createUser(testDb); + const created = await makeClient(user.id); + const client = created.client as { client_id: string; client_secret: string }; + const tokens = await issueTokens(client.client_id, user.id, ['trips:read']); + await updateRows(t, OauthTokens, {}, { refresh_token_expires_at: dbNow(new Date(Date.now() - 60_000)) }); + + expect(await refreshTokens(tokens.refresh_token, client.client_id, client.client_secret)).toEqual({ error: 'invalid_grant', status: 400 }); + }); + it('refreshTokens rejects an unknown client before touching the token', async () => { expect(await refreshTokens('trekrf_whatever', 'no-such-client', 'secret')).toEqual({ error: 'invalid_client', status: 401 }); });