Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+230
View File
@@ -0,0 +1,230 @@
"use strict";
// GET /api/account used to answer createdAt: null for every account, forever:
// the handler emitted `createdAt: user.created_at || null`, but the lookup
// layer (findUserByEmail / findUserById) never fetched users.created_at in
// its SELECTs and mapUserRow never mapped the column, so the property was
// undefined on every mapped user and the `|| null` collapsed it permanently.
// Account age therefore never reached the dashboard. The fix is layered, and
// this file pins every layer by reading the sources as text, like the other
// audit tests:
//
// * mysql-schema.sql — users.created_at is a database-defaulted
// TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP column: the database, not
// application code, is the source of truth for when an account was born;
// * lookups — both primary SELECTs end with ..., username,
// username_changed_at, created_at FROM users, while the legacy-schema
// fallback stays deliberately narrow (SELECT id, email, password, secret,
// admin, suspended, suspended_at, suspended_by, agent_access FROM users),
// proving the retry never starts fetching created_at it cannot get;
// * fallback routing — the ER_BAD_FIELD_ERROR predicate now also matches
// 'created_at', so a pre-created_at schema degrades into the reduced
// retry instead of `throw err` out of the login path;
// * mapping — mapUserRow normalizes the column through
// normalizeUserCreatedAt (Date -> ISO-8601 UTC string, missing/garbage ->
// null), defined immediately above it, so /api/account sees one
// deterministic shape no matter what the driver materialized;
// * handler — GET /api/account keeps emitting
// createdAt: user.created_at || null from the mapped user;
// * leak guard — buildRenderSafeUser stays free of created_at/createdAt:
// the render-safe projection handed to EJS templates must not start
// carrying account metadata;
// * single-writer — no INSERT INTO users may list the created_at column:
// DEFAULT CURRENT_TIMESTAMP remains the only birth certificate, so no
// insert can forge an account age.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const SCHEMA_SQL = path.join(ROOT, "mysql-schema.sql");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const schemaSource = fs.readFileSync(SCHEMA_SQL, "utf8");
function extractRoute(source, routeMarker, nextRouteMarker) {
const start = source.indexOf(routeMarker);
assert.ok(start >= 0, `route marker not found: ${routeMarker}`);
const end = source.indexOf(nextRouteMarker, start);
assert.ok(end > start, `next route marker not found after route: ${nextRouteMarker}`);
return source.slice(start, end);
}
// The users CREATE TABLE block runs to the next table definition in the
// schema file, so the created_at assertion cannot be satisfied by a column
// on some other table.
const USERS_TABLE_START = "CREATE TABLE IF NOT EXISTS users (";
const USERS_TABLE_END = "CREATE TABLE IF NOT EXISTS nodes (";
const FIND_BY_EMAIL_START = "async function findUserByEmail(email) {";
const FIND_BY_ID_START = "async function findUserById(id) {";
const GET_ID_BY_EMAIL_START = "async function getUserIdByEmail(email) {";
const MAP_ROW_START = "function mapUserRow(row) {";
const MAP_ROW_END = "function hasTwoFactorEnabled(user) {";
const RENDER_SAFE_START = "function buildRenderSafeUser(user) {";
const ACCOUNT_ROUTE_START = 'app.get("/api/account"';
const ACCOUNT_ROUTE_END = 'app.post("/api/account/username"';
const usersTableBlock = extractRoute(schemaSource, USERS_TABLE_START, USERS_TABLE_END);
const findByEmailBlock = extractRoute(indexSource, FIND_BY_EMAIL_START, FIND_BY_ID_START);
const findByIdBlock = extractRoute(indexSource, FIND_BY_ID_START, GET_ID_BY_EMAIL_START);
const mapUserRowBlock = extractRoute(indexSource, MAP_ROW_START, MAP_ROW_END);
const renderSafeBlock = extractRoute(indexSource, RENDER_SAFE_START, FIND_BY_ID_START);
const accountRouteBlock = extractRoute(indexSource, ACCOUNT_ROUTE_START, ACCOUNT_ROUTE_END);
// Both lookups must show the same repaired shape, so the per-block assertions
// run over this list with the function name in the failure messages.
const lookupBlocks = [
["findUserByEmail", findByEmailBlock],
["findUserById", findByIdBlock],
];
// The repaired primary SELECT tail, and the deliberately narrow legacy retry:
// the fallback proves a pre-created_at schema still logs in (it must exist),
// and must never start listing created_at itself. session_epoch may trail
// created_at (added later for cluster-wide session rebinding) — the contract
// is that created_at is selected, not that it is the last column.
const PRIMARY_SELECT_TAIL = /username, username_changed_at, created_at(, session_epoch)? FROM users/;
const LEGACY_FALLBACK_SELECT = /SELECT id, email, password, secret, admin, suspended, suspended_at, suspended_by, agent_access FROM users/;
// The catch predicate routes a missing-column error into the reduced retry.
const LEGACY_FALLBACK_PREDICATE = /err\.code === 'ER_BAD_FIELD_ERROR' && \(err\.message\?\.includes\('avatar_url'\) \|\| err\.message\?\.includes\('totp_last_counter'\) \|\| err\.message\?\.includes\('username'\) \|\| err\.message\?\.includes\('created_at'\)( \|\| err\.message\?\.includes\('session_epoch'\))?\)/;
// The helper is extracted from index.js so the behavioral test below runs the
// REAL shipped function, not a copy that can drift from it.
const HELPER_START = "function normalizeUserCreatedAt(";
const helperStart = indexSource.indexOf(HELPER_START);
assert.ok(helperStart >= 0, `helper marker not found: ${HELPER_START}`);
// The helper is a straight-line function with no nested braces, so its closing
// brace is the first "\n}\n" after the start.
const helperClosing = indexSource.indexOf("\n}\n", helperStart);
assert.ok(helperClosing > helperStart, "normalizeUserCreatedAt closing brace not found");
const helperSource = indexSource.slice(helperStart, helperClosing + 2);
assert.ok(helperSource.endsWith("}"), "normalizeUserCreatedAt extraction must end at its closing brace");
test("users.created_at is a database-defaulted TIMESTAMP column", () => {
assert.match(
usersTableBlock,
/created_at\s+TIMESTAMP\s+NOT\s+NULL\s+DEFAULT\s+CURRENT_TIMESTAMP/,
"the users CREATE TABLE block must declare created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP: the database, not application code, is the source of truth for account age"
);
});
test("both user lookups select created_at", () => {
for (const [name, block] of lookupBlocks) {
assert.match(
block,
PRIMARY_SELECT_TAIL,
`${name}'s primary SELECT must end with ..., username, username_changed_at, created_at FROM users, or user.created_at stays undefined and /api/account keeps answering createdAt: null`
);
assert.match(
block,
LEGACY_FALLBACK_SELECT,
`${name} must keep the deliberately narrow legacy fallback SELECT (SELECT id, email, ..., agent_access FROM users) so a pre-created_at schema still serves logins instead of hard-failing`
);
}
});
test("legacy fallback degrades on missing created_at instead of throwing", () => {
for (const [name, block] of lookupBlocks) {
assert.match(
block,
LEGACY_FALLBACK_PREDICATE,
`${name}'s ER_BAD_FIELD_ERROR predicate must also match 'created_at' so a pre-created_at schema routes into the reduced retry instead of \`throw err\` out of the login path`
);
}
});
test("mapUserRow normalizes created_at through normalizeUserCreatedAt", () => {
const mapRowStart = indexSource.indexOf(MAP_ROW_START);
assert.ok(mapRowStart >= 0, `marker not found: ${MAP_ROW_START}`);
assert.ok(
helperStart >= 0 && helperStart < mapRowStart,
"normalizeUserCreatedAt must be defined BEFORE mapUserRow so the mapping runs at module load without hitting a TDZ reference"
);
assert.match(
mapUserRowBlock,
/created_at:\s*normalizeUserCreatedAt\(row\.created_at\)/,
"mapUserRow's returned object must end with created_at: normalizeUserCreatedAt(row.created_at), or the lookup layer fetches a value the mapped user never carries"
);
});
test("normalizeUserCreatedAt behavior: Date->ISO, missing->null, garbage->null", () => {
// Build the REAL helper extracted from index.js above; if the shipped
// implementation ever drifts from the contract, this fails against it.
const normalizeUserCreatedAt = new Function("return " + helperSource)();
// mysql2 materializes TIMESTAMP columns as JS Date objects (db.js sets no
// dateStrings option): the mapped value must be the deterministic ISO-8601
// UTC string.
assert.strictEqual(
normalizeUserCreatedAt(new Date(0)),
"1970-01-01T00:00:00.000Z",
"a Date value must normalize to its ISO-8601 UTC string"
);
// Legacy-schema rows omit the column entirely, so every "no value" shape
// must collapse to null (the JSON emission then writes createdAt: null).
assert.strictEqual(normalizeUserCreatedAt(null), null, "null must normalize to null");
assert.strictEqual(normalizeUserCreatedAt(undefined), null, "undefined must normalize to null");
assert.strictEqual(normalizeUserCreatedAt(""), null, "an empty string must normalize to null");
// An ISO string passes through unchanged: no double-parsing drift.
assert.strictEqual(
normalizeUserCreatedAt("2026-09-26T00:00:00.000Z"),
"2026-09-26T00:00:00.000Z",
"an ISO-8601 string must pass through unchanged"
);
assert.strictEqual(
normalizeUserCreatedAt("not-a-date"),
null,
"an unparseable string must normalize to null instead of becoming Invalid Date"
);
// Epoch milliseconds (2025-09-26T06:40:00Z, verified with
// `new Date(1758868800000).toISOString()`; toISOString is timezone-
// independent so the expectation holds on every machine).
assert.strictEqual(
normalizeUserCreatedAt(1758868800000),
"2025-09-26T06:40:00.000Z",
"epoch milliseconds must normalize through new Date(...) to the ISO-8601 UTC string"
);
});
test("GET /api/account keeps emitting createdAt from the mapped user", () => {
assert.match(
accountRouteBlock,
/createdAt:\s*user\.created_at\s*\|\|\s*null/,
'GET /api/account must keep emitting createdAt: user.created_at || null from the mapped user'
);
});
test("buildRenderSafeUser does not forward created_at into templates", () => {
// Leak guard: the render-safe projection is what EJS templates receive, and
// account metadata (account age) must not ride into the HTML source behind
// a future template edit.
assert.doesNotMatch(
renderSafeBlock,
/created_at|createdAt/,
"buildRenderSafeUser must not forward created_at/createdAt: the render-safe projection stays free of account metadata"
);
});
test("user INSERTs keep relying on the database default", () => {
// Single-writer guard for account age: both known INSERTs list explicit
// columns, and none may start setting created_at manually —
// DEFAULT CURRENT_TIMESTAMP is the source of truth for when an account
// was born, so no insert can forge it.
assert.doesNotMatch(
indexSource,
/INSERT INTO users\s*\([^)]*\bcreated_at\b/,
"no INSERT INTO users may list the created_at column: DEFAULT CURRENT_TIMESTAMP is the only source of account age"
);
});