tina4-nodejs 3.13.158 → 3.13.160
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +2 -2
- package/package.json +1 -1
- package/packages/cli/dist/bin.js +138 -43
- package/packages/cli/src/commands/generate.ts +72 -23
- package/packages/core/dist/index.js +138 -43
- package/packages/core/src/authGate.ts +37 -24
- package/packages/core/src/middleware.ts +18 -6
- package/packages/core/src/response.ts +60 -2
- package/packages/core/src/server.ts +30 -3
- package/packages/orm/dist/index.js +138 -43
- package/packages/orm/src/migration.ts +34 -0
- package/types/core/src/authGate.d.ts +22 -7
- package/types/core/src/response.d.ts +17 -1
- package/types/orm/src/migration.d.ts +0 -24
|
@@ -9325,6 +9325,13 @@ function consumeSqlDelimiter(state) {
|
|
|
9325
9325
|
}
|
|
9326
9326
|
return true;
|
|
9327
9327
|
}
|
|
9328
|
+
function hasExecutableSql(sql) {
|
|
9329
|
+
const body = sql.replace(/\/\*[\s\S]*?\*\//g, "").replace(/--[^\n]*/g, "");
|
|
9330
|
+
return body.replace(/[;\s]/g, "") !== "";
|
|
9331
|
+
}
|
|
9332
|
+
function isUnappliedScaffold(sql) {
|
|
9333
|
+
return TINA4_EDIT_MARKER_RE.test(sql) && !hasExecutableSql(sql);
|
|
9334
|
+
}
|
|
9328
9335
|
function splitStatements(sql, delimiter2 = ";") {
|
|
9329
9336
|
const state = {
|
|
9330
9337
|
sql: normalizeQuotes(sql),
|
|
@@ -9509,6 +9516,12 @@ async function runPendingMigrations(db, dir, delimiter2) {
|
|
|
9509
9516
|
result.skipped.push(file);
|
|
9510
9517
|
continue;
|
|
9511
9518
|
}
|
|
9519
|
+
if (isUnappliedScaffold(sqlContent)) {
|
|
9520
|
+
console.warn(
|
|
9521
|
+
` Migration ${file} is still an unedited scaffold (a 'tina4:edit' placeholder with no SQL yet) \u2014 skipped and kept pending. Write the migration and remove the tina4:edit line(s), then run migrate again.`
|
|
9522
|
+
);
|
|
9523
|
+
continue;
|
|
9524
|
+
}
|
|
9512
9525
|
const statements = splitStatements(sqlContent, delimiter2);
|
|
9513
9526
|
try {
|
|
9514
9527
|
await adapterStartTransaction(db);
|
|
@@ -9653,7 +9666,7 @@ export class ${className} {
|
|
|
9653
9666
|
writeFileSync(filePath, content, "utf-8");
|
|
9654
9667
|
return filePath;
|
|
9655
9668
|
}
|
|
9656
|
-
var ALTER_ADD_RE, CREATE_TABLE_RE, MIGRATION_TABLE, SMART_QUOTES, SMART_QUOTE_RE, SET_TERM_RE, MIGRATION_LOCK_NAME, PG_ADVISORY_KEY, delay, Migration;
|
|
9669
|
+
var ALTER_ADD_RE, CREATE_TABLE_RE, MIGRATION_TABLE, SMART_QUOTES, SMART_QUOTE_RE, SET_TERM_RE, TINA4_EDIT_MARKER_RE, MIGRATION_LOCK_NAME, PG_ADVISORY_KEY, delay, Migration;
|
|
9657
9670
|
var init_migration = __esm({
|
|
9658
9671
|
"../orm/src/migration.ts"() {
|
|
9659
9672
|
"use strict";
|
|
@@ -9678,6 +9691,7 @@ var init_migration = __esm({
|
|
|
9678
9691
|
};
|
|
9679
9692
|
SMART_QUOTE_RE = new RegExp(`[${Object.keys(SMART_QUOTES).join("")}]`, "g");
|
|
9680
9693
|
SET_TERM_RE = /^SET\s+TERM\s+(\S+)$/i;
|
|
9694
|
+
TINA4_EDIT_MARKER_RE = /(?:#|\/\/|--|\/\*|\{#)\s*tina4:edit\b/i;
|
|
9681
9695
|
MIGRATION_LOCK_NAME = "tina4_migration_lock";
|
|
9682
9696
|
PG_ADVISORY_KEY = BigInt.asIntN(
|
|
9683
9697
|
64,
|
|
@@ -22177,6 +22191,41 @@ function negotiatedErrorBody(code, message, requestId) {
|
|
|
22177
22191
|
body.request_id = requestId;
|
|
22178
22192
|
return body;
|
|
22179
22193
|
}
|
|
22194
|
+
async function renderNegotiatedError(req2, res, code, message) {
|
|
22195
|
+
const { Log: Log2 } = await Promise.resolve().then(() => (init_logger(), logger_exports));
|
|
22196
|
+
const requestId = Log2.getRequestId() ?? "";
|
|
22197
|
+
const writeJson = () => {
|
|
22198
|
+
const body = negotiatedErrorBody(code, message, requestId);
|
|
22199
|
+
res.raw.statusCode = code;
|
|
22200
|
+
res.raw.setHeader("Content-Type", "application/json");
|
|
22201
|
+
res.raw.end(JSON.stringify(body));
|
|
22202
|
+
};
|
|
22203
|
+
if (wantsJson(req2)) {
|
|
22204
|
+
writeJson();
|
|
22205
|
+
return;
|
|
22206
|
+
}
|
|
22207
|
+
const data = { path: req2?.path ?? "", error_message: "", request_id: requestId, status_code: code };
|
|
22208
|
+
const template = `errors/${code}.twig`;
|
|
22209
|
+
let html = null;
|
|
22210
|
+
try {
|
|
22211
|
+
html = (await getFrond()).render(template, data);
|
|
22212
|
+
} catch {
|
|
22213
|
+
}
|
|
22214
|
+
if (!html) {
|
|
22215
|
+
try {
|
|
22216
|
+
const fw = await getFrameworkFrond();
|
|
22217
|
+
html = fw ? fw.render(template, data) : null;
|
|
22218
|
+
} catch {
|
|
22219
|
+
html = null;
|
|
22220
|
+
}
|
|
22221
|
+
}
|
|
22222
|
+
if (html) {
|
|
22223
|
+
res.raw.writeHead(code, { "Content-Type": "text/html; charset=utf-8" });
|
|
22224
|
+
res.raw.end(html);
|
|
22225
|
+
return;
|
|
22226
|
+
}
|
|
22227
|
+
writeJson();
|
|
22228
|
+
}
|
|
22180
22229
|
var HEADER_TOKEN, _frondCache, _defaultTemplatesDir, _globalFrond, _frameworkFrond, ERROR_CODE_NAMES;
|
|
22181
22230
|
var init_response = __esm({
|
|
22182
22231
|
"src/response.ts"() {
|
|
@@ -22188,6 +22237,7 @@ var init_response = __esm({
|
|
|
22188
22237
|
_globalFrond = null;
|
|
22189
22238
|
_frameworkFrond = null;
|
|
22190
22239
|
ERROR_CODE_NAMES = {
|
|
22240
|
+
401: "UNAUTHORIZED",
|
|
22191
22241
|
403: "FORBIDDEN",
|
|
22192
22242
|
404: "NOT_FOUND",
|
|
22193
22243
|
405: "METHOD_NOT_ALLOWED",
|
|
@@ -22256,7 +22306,7 @@ async function interpretHookResult(result, req2, res) {
|
|
|
22256
22306
|
}
|
|
22257
22307
|
return [req2, res, false];
|
|
22258
22308
|
}
|
|
22259
|
-
function middleware500(res, mwClass, methodName, error2) {
|
|
22309
|
+
async function middleware500(res, mwClass, methodName, error2, req2) {
|
|
22260
22310
|
const clsName = mwClass?.name ?? mwClass?.constructor?.name ?? "Middleware";
|
|
22261
22311
|
const err = error2;
|
|
22262
22312
|
const type2 = err?.name ?? error2?.constructor?.name ?? "Error";
|
|
@@ -22265,6 +22315,10 @@ function middleware500(res, mwClass, methodName, error2) {
|
|
|
22265
22315
|
Log.error(`Middleware ${clsName}.${methodName} raised ${type2}: ${message}`);
|
|
22266
22316
|
} catch {
|
|
22267
22317
|
}
|
|
22318
|
+
if (req2 && res?.raw && typeof res.raw.writeHead === "function" && !res.raw.writableEnded) {
|
|
22319
|
+
await renderNegotiatedError(req2, res, 500, "Internal Server Error");
|
|
22320
|
+
return res;
|
|
22321
|
+
}
|
|
22268
22322
|
if (typeof res.json === "function") {
|
|
22269
22323
|
res.json({ error: "Internal Server Error", status: 500 }, 500);
|
|
22270
22324
|
} else if (typeof res === "function") {
|
|
@@ -22565,7 +22619,7 @@ var init_middleware = __esm({
|
|
|
22565
22619
|
res = nextRes;
|
|
22566
22620
|
if (stop2) return [req2, res, false];
|
|
22567
22621
|
} catch (error2) {
|
|
22568
|
-
res = middleware500(res, cls, method, error2);
|
|
22622
|
+
res = await middleware500(res, cls, method, error2, req2);
|
|
22569
22623
|
return [req2, res, false];
|
|
22570
22624
|
}
|
|
22571
22625
|
if (res.raw.statusCode >= 400 || res.raw.writableEnded) {
|
|
@@ -22609,7 +22663,7 @@ var init_middleware = __esm({
|
|
|
22609
22663
|
res = nextRes;
|
|
22610
22664
|
if (stop2) return [req2, res];
|
|
22611
22665
|
} catch (error2) {
|
|
22612
|
-
res = middleware500(res, cls, method, error2);
|
|
22666
|
+
res = await middleware500(res, cls, method, error2, req2);
|
|
22613
22667
|
continue;
|
|
22614
22668
|
}
|
|
22615
22669
|
}
|
|
@@ -23613,7 +23667,7 @@ var init_ssoIdentity = __esm({
|
|
|
23613
23667
|
// src/authGate.ts
|
|
23614
23668
|
function enforceRouteAuth(req2, res, match) {
|
|
23615
23669
|
if (!(match.secure === true && match.noAuth !== true)) {
|
|
23616
|
-
return
|
|
23670
|
+
return null;
|
|
23617
23671
|
}
|
|
23618
23672
|
const authHeader = req2.headers.authorization ?? "";
|
|
23619
23673
|
const headerToken = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : "";
|
|
@@ -23643,7 +23697,7 @@ function enforceRouteAuth(req2, res, match) {
|
|
|
23643
23697
|
const identity = liveSessionIdentity(req2.session?.get?.("_tina4_sso"));
|
|
23644
23698
|
if (identity) {
|
|
23645
23699
|
req2.user = identity;
|
|
23646
|
-
return rbacForbidden(match, identity
|
|
23700
|
+
return rbacForbidden(match, identity);
|
|
23647
23701
|
}
|
|
23648
23702
|
const sessionToken = req2.session?.get?.("token");
|
|
23649
23703
|
if (sessionToken) {
|
|
@@ -23656,9 +23710,7 @@ function enforceRouteAuth(req2, res, match) {
|
|
|
23656
23710
|
}
|
|
23657
23711
|
}
|
|
23658
23712
|
if (!payload) {
|
|
23659
|
-
|
|
23660
|
-
res.raw.end(JSON.stringify({ error: "Unauthorized" }));
|
|
23661
|
-
return true;
|
|
23713
|
+
return { status: 401, message: "Unauthorized" };
|
|
23662
23714
|
}
|
|
23663
23715
|
req2.user = payload;
|
|
23664
23716
|
if (tokenSource === "body") {
|
|
@@ -23667,7 +23719,7 @@ function enforceRouteAuth(req2, res, match) {
|
|
|
23667
23719
|
res.header("FreshToken", fresh);
|
|
23668
23720
|
}
|
|
23669
23721
|
}
|
|
23670
|
-
return rbacForbidden(match, req2.user
|
|
23722
|
+
return rbacForbidden(match, req2.user);
|
|
23671
23723
|
}
|
|
23672
23724
|
function rbacClaimList(subject, key, legacy) {
|
|
23673
23725
|
const coerce = (v) => {
|
|
@@ -23684,27 +23736,23 @@ function rbacPermGranted(granted, required) {
|
|
|
23684
23736
|
(g) => g === "*" || g === required || g.endsWith(".*") && required.startsWith(g.slice(0, -1))
|
|
23685
23737
|
);
|
|
23686
23738
|
}
|
|
23687
|
-
function rbacForbidden(match, payload
|
|
23739
|
+
function rbacForbidden(match, payload) {
|
|
23688
23740
|
const requiredRoles = match.requiredRoles ?? [];
|
|
23689
23741
|
const requiredPerms = match.requiredPerms ?? [];
|
|
23690
23742
|
if (requiredRoles.length === 0 && requiredPerms.length === 0) {
|
|
23691
|
-
return
|
|
23743
|
+
return null;
|
|
23692
23744
|
}
|
|
23693
23745
|
const subject = payload && typeof payload === "object" ? payload : {};
|
|
23746
|
+
const forbidden = { status: 403, message: "Forbidden" };
|
|
23694
23747
|
const roles = rbacClaimList(subject, "roles", "role");
|
|
23695
23748
|
for (const group of requiredRoles) {
|
|
23696
|
-
if (!group.some((r) => roles.includes(r))) return
|
|
23749
|
+
if (!group.some((r) => roles.includes(r))) return forbidden;
|
|
23697
23750
|
}
|
|
23698
23751
|
const perms = rbacClaimList(subject, "permissions");
|
|
23699
23752
|
for (const group of requiredPerms) {
|
|
23700
|
-
if (!group.some((p) => rbacPermGranted(perms, p))) return
|
|
23753
|
+
if (!group.some((p) => rbacPermGranted(perms, p))) return forbidden;
|
|
23701
23754
|
}
|
|
23702
|
-
return
|
|
23703
|
-
}
|
|
23704
|
-
function writeForbidden(res) {
|
|
23705
|
-
res.raw.writeHead(403, { "Content-Type": "application/json" });
|
|
23706
|
-
res.raw.end(JSON.stringify({ error: "Forbidden" }));
|
|
23707
|
-
return true;
|
|
23755
|
+
return null;
|
|
23708
23756
|
}
|
|
23709
23757
|
var init_authGate = __esm({
|
|
23710
23758
|
"src/authGate.ts"() {
|
|
@@ -28178,6 +28226,7 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
|
|
|
28178
28226
|
}
|
|
28179
28227
|
const fields = fieldsOverride || parseFields(flags.fields || "");
|
|
28180
28228
|
const isCreate = name.startsWith("create_") || fieldsOverride !== void 0;
|
|
28229
|
+
const isView = isCreate && fieldsOverride === void 0 && table2.endsWith("_view");
|
|
28181
28230
|
const fileName = `${ts}_${name}.sql`;
|
|
28182
28231
|
const path10 = join20(dir, fileName);
|
|
28183
28232
|
setResolutionField("migration_path", `migrations/${fileName}`);
|
|
@@ -28187,7 +28236,13 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
|
|
|
28187
28236
|
}
|
|
28188
28237
|
let upSql;
|
|
28189
28238
|
let downSql;
|
|
28190
|
-
if (
|
|
28239
|
+
if (isView) {
|
|
28240
|
+
upSql = `-- tina4:edit write the CREATE VIEW statement, then remove the
|
|
28241
|
+
-- tina4:edit lines. For example:
|
|
28242
|
+
-- CREATE VIEW ${table2} AS
|
|
28243
|
+
-- SELECT id, /* columns */ FROM source_table WHERE /* ... */;`;
|
|
28244
|
+
downSql = `DROP VIEW IF EXISTS ${table2};`;
|
|
28245
|
+
} else if (isCreate) {
|
|
28191
28246
|
const colLines = [" id INTEGER PRIMARY KEY AUTOINCREMENT"];
|
|
28192
28247
|
for (const [fname, ftype] of fields) {
|
|
28193
28248
|
const info = FIELD_TYPE_MAP[ftype] || FIELD_TYPE_MAP.string;
|
|
@@ -28213,9 +28268,6 @@ DROP TABLE IF EXISTS ${table2};`;
|
|
|
28213
28268
|
|
|
28214
28269
|
-- UP
|
|
28215
28270
|
${upSql}
|
|
28216
|
-
|
|
28217
|
-
-- DOWN
|
|
28218
|
-
${downSql}
|
|
28219
28271
|
`;
|
|
28220
28272
|
writeFileSafe(path10, content);
|
|
28221
28273
|
const downPath = join20(dir, `${ts}_${name}.down.sql`);
|
|
@@ -28225,7 +28277,7 @@ ${downSql}
|
|
|
28225
28277
|
${downSql}
|
|
28226
28278
|
`;
|
|
28227
28279
|
writeFileSafe(downPath, downContent);
|
|
28228
|
-
if (emitTest && isCreate) emitMigrationTest(name, table2);
|
|
28280
|
+
if (emitTest && isCreate && !isView) emitMigrationTest(name, table2);
|
|
28229
28281
|
}
|
|
28230
28282
|
function generateMiddleware(name, _flags) {
|
|
28231
28283
|
const snake = toSnake(name);
|
|
@@ -29036,9 +29088,11 @@ function emitRouteStubTest(route) {
|
|
|
29036
29088
|
* Routing test for ${route} \u2014 no mocks, real Router + route discovery.
|
|
29037
29089
|
*
|
|
29038
29090
|
* Generated with src/routes/api/${route}/ by \`tina4nodejs generate route
|
|
29039
|
-
* ${route}\` (no --model). The handlers
|
|
29040
|
-
* implement them
|
|
29041
|
-
* register on the REAL Router, and the list handler
|
|
29091
|
+
* ${route}\` (no --model). The handlers start as AI-FILL stubs that throw until
|
|
29092
|
+
* you implement them. This tests what is live on generation: all five routes
|
|
29093
|
+
* register on the REAL Router, and the list handler is wired and callable. It
|
|
29094
|
+
* stays GREEN whether the stub still throws OR you have filled it in \u2014
|
|
29095
|
+
* implementing the handler never turns this test red.
|
|
29042
29096
|
* Run with: npx tsx tests/${route}.test.ts
|
|
29043
29097
|
*/
|
|
29044
29098
|
import { dirname, resolve } from "node:path";
|
|
@@ -29055,9 +29109,15 @@ for (const sig of ["GET /api/${route}", "POST /api/${route}", "GET /api/${route}
|
|
|
29055
29109
|
assert(\`route registered: \${sig}\`, sigs.includes(sig));
|
|
29056
29110
|
}
|
|
29057
29111
|
|
|
29058
|
-
// The
|
|
29059
|
-
|
|
29060
|
-
|
|
29112
|
+
// The list handler is WIRED: a loud AI-FILL stub (throws) on generation. This
|
|
29113
|
+
// stays green whether it still throws OR you have filled it in, so doing the
|
|
29114
|
+
// work never turns the suite red.
|
|
29115
|
+
assert("list handler is callable", typeof listHandler === "function");
|
|
29116
|
+
try {
|
|
29117
|
+
await listHandler({} as never, {} as never);
|
|
29118
|
+
} catch {
|
|
29119
|
+
// still the scaffold stub (throws until filled) \u2014 expected
|
|
29120
|
+
}`;
|
|
29061
29121
|
writeTest(route, standaloneTest(doc, body));
|
|
29062
29122
|
}
|
|
29063
29123
|
function emitMiddlewareTest(name, snake) {
|
|
@@ -29141,8 +29201,14 @@ ServiceRunner.register(service.name, service.handler, { interval: (service as {
|
|
|
29141
29201
|
assert("registers on a real ServiceRunner", ServiceRunner.list().some((s) => s.name === "${snake}"));
|
|
29142
29202
|
ServiceRunner.remove("${snake}");
|
|
29143
29203
|
|
|
29144
|
-
// The
|
|
29145
|
-
|
|
29204
|
+
// The task is WIRED: a loud AI-FILL stub (throws) on generation. This stays
|
|
29205
|
+
// green whether it still throws OR you have filled it in.
|
|
29206
|
+
assert("task is callable", typeof ${camel}Task === "function");
|
|
29207
|
+
try {
|
|
29208
|
+
await ${camel}Task({} as never);
|
|
29209
|
+
} catch {
|
|
29210
|
+
// still the scaffold stub (throws until filled) \u2014 expected
|
|
29211
|
+
}`;
|
|
29146
29212
|
writeTest(snake, standaloneTest(doc, body));
|
|
29147
29213
|
}
|
|
29148
29214
|
function emitQueueTest(topic, slug, pascal) {
|
|
@@ -29164,8 +29230,14 @@ assert("the job is really on the queue", new Queue({ topic: "${topic}" }).size()
|
|
|
29164
29230
|
assert("consumer default export is a daemon", worker.daemon === true);
|
|
29165
29231
|
assert("consumer handler is wired", typeof worker.handler === "function");
|
|
29166
29232
|
|
|
29167
|
-
// The per-job handler is
|
|
29168
|
-
|
|
29233
|
+
// The per-job handler is WIRED: a loud AI-FILL stub (throws) on generation.
|
|
29234
|
+
// This stays green whether it still throws OR you have filled it in.
|
|
29235
|
+
assert("handle is callable", typeof handle${pascal} === "function");
|
|
29236
|
+
try {
|
|
29237
|
+
await handle${pascal}({});
|
|
29238
|
+
} catch {
|
|
29239
|
+
// still the scaffold stub (throws until filled) \u2014 expected
|
|
29240
|
+
}`;
|
|
29169
29241
|
writeTest(slug, standaloneTest(doc, body));
|
|
29170
29242
|
}
|
|
29171
29243
|
function emitValidatorTest(name, snake, pascal) {
|
|
@@ -29227,9 +29299,14 @@ import { ${handler} } from "../src/routes/ws_${base}.js"; // importing register
|
|
|
29227
29299
|
const closed = await ${handler}(null as never, "close", "");
|
|
29228
29300
|
assert("close event handled cleanly", closed === undefined);
|
|
29229
29301
|
|
|
29230
|
-
// The "message" branch is
|
|
29231
|
-
|
|
29232
|
-
|
|
29302
|
+
// The "message" branch is WIRED: a loud AI-FILL stub (throws) on generation.
|
|
29303
|
+
// This stays green whether it still throws OR you have filled it in.
|
|
29304
|
+
try {
|
|
29305
|
+
await ${handler}(null as never, "message", "hi");
|
|
29306
|
+
assert("message branch is callable", true);
|
|
29307
|
+
} catch {
|
|
29308
|
+
assert("message branch is callable", true); // still the scaffold stub
|
|
29309
|
+
}`;
|
|
29233
29310
|
writeTest(`ws_${base}`, standaloneTest(doc, body));
|
|
29234
29311
|
}
|
|
29235
29312
|
function emitListenerTest(event, slug) {
|
|
@@ -29246,9 +29323,15 @@ import { Events } from "tina4-nodejs";
|
|
|
29246
29323
|
import "../src/listeners/${slug}.js"; // importing registers the listener via Events.on()`;
|
|
29247
29324
|
const body = `assert("listener registered on the real event bus", Events.listeners("${event}").length >= 1);
|
|
29248
29325
|
|
|
29249
|
-
//
|
|
29250
|
-
|
|
29251
|
-
|
|
29326
|
+
// Emitting reaches the listener. It starts as a loud AI-FILL stub (a strict emit
|
|
29327
|
+
// re-raises); once you implement it this test STILL passes, so doing the work
|
|
29328
|
+
// never turns the suite red.
|
|
29329
|
+
try {
|
|
29330
|
+
await Events.emit("${event}", { strict: true }, { id: 1 });
|
|
29331
|
+
assert("emitting reaches the listener", true);
|
|
29332
|
+
} catch {
|
|
29333
|
+
assert("emitting reaches the listener", true); // still the scaffold stub
|
|
29334
|
+
}`;
|
|
29252
29335
|
writeTest(slug, standaloneTest(doc, body));
|
|
29253
29336
|
}
|
|
29254
29337
|
function emitAuthTest() {
|
|
@@ -43679,6 +43762,12 @@ async function invokeRouteHandler(match, req2, res) {
|
|
|
43679
43762
|
if (args.length === 0) return await match.handler();
|
|
43680
43763
|
return await match.handler(...args);
|
|
43681
43764
|
}
|
|
43765
|
+
function coerceHandlerResult(res, result) {
|
|
43766
|
+
if (res.raw.writableEnded || res.raw.headersSent) return;
|
|
43767
|
+
if (result === void 0 || result === null) return;
|
|
43768
|
+
if (result === res) return;
|
|
43769
|
+
res(result);
|
|
43770
|
+
}
|
|
43682
43771
|
async function renderIfTemplateRoute(match, res, result) {
|
|
43683
43772
|
if (res.raw.writableEnded) return;
|
|
43684
43773
|
if (!match.template) return;
|
|
@@ -43690,7 +43779,11 @@ async function runMatchedRoute(ctx) {
|
|
|
43690
43779
|
const { req: req2, res, match, postMatchMiddleware } = ctx;
|
|
43691
43780
|
req2.params = match.params;
|
|
43692
43781
|
if (await runGlobalMiddlewarePass(postMatchMiddleware, req2, res)) return;
|
|
43693
|
-
|
|
43782
|
+
const authReject = enforceRouteAuth(req2, res, match);
|
|
43783
|
+
if (authReject) {
|
|
43784
|
+
await renderNegotiatedError(req2, res, authReject.status, authReject.message);
|
|
43785
|
+
return;
|
|
43786
|
+
}
|
|
43694
43787
|
const routeMiddlewareClasses = (match.middlewares ?? []).filter(isMiddlewareClass);
|
|
43695
43788
|
let handlerSkipped = false;
|
|
43696
43789
|
if (match.middlewares && match.middlewares.length > 0) {
|
|
@@ -43698,7 +43791,9 @@ async function runMatchedRoute(ctx) {
|
|
|
43698
43791
|
handlerSkipped = !proceed || res.raw.writableEnded;
|
|
43699
43792
|
}
|
|
43700
43793
|
if (!handlerSkipped) {
|
|
43701
|
-
|
|
43794
|
+
const result = await invokeRouteHandler(match, req2, res);
|
|
43795
|
+
await renderIfTemplateRoute(match, res, result);
|
|
43796
|
+
coerceHandlerResult(res, result);
|
|
43702
43797
|
}
|
|
43703
43798
|
const afterMiddleware = [...ctx.allGlobalMiddleware, ...routeMiddlewareClasses];
|
|
43704
43799
|
if (afterMiddleware.length > 0) {
|
|
@@ -30,15 +30,31 @@ export interface AuthGateRoute {
|
|
|
30
30
|
requiredPerms?: string[][];
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/**
|
|
34
|
+
* A rejection the caller must RENDER (ERR-DEC-02, #342). The gate decides the
|
|
35
|
+
* status and message but does NOT render — the template engine stays out of the
|
|
36
|
+
* auth path's import graph (the auth path imports only node: builtins; see
|
|
37
|
+
* test/authRs256OptIn.test.ts). server.ts, which already depends on Frond,
|
|
38
|
+
* renders this through the shared negotiated renderer.
|
|
39
|
+
*/
|
|
40
|
+
export interface AuthReject {
|
|
41
|
+
status: number;
|
|
42
|
+
message: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
33
45
|
/**
|
|
34
46
|
* Enforce auth for a matched route.
|
|
35
47
|
*
|
|
36
|
-
* Returns `
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
48
|
+
* Returns an `AuthReject` (status + message) when the request is REJECTED — the
|
|
49
|
+
* caller must render it and stop (not run the handler). Returns `null` when the
|
|
50
|
+
* route is public OR a valid token was presented (in which case `req.user` is
|
|
51
|
+
* populated and, for a body formToken, a `FreshToken` header is set). Auth is
|
|
52
|
+
* enforced only for a route that is `secure` and not `noAuth` (the dev
|
|
53
|
+
* dashboard registers its own routes `noAuth`).
|
|
54
|
+
*
|
|
55
|
+
* The gate deliberately does NOT render the rejection: rendering needs the
|
|
56
|
+
* template engine, and the auth path's import graph must stay node:-builtins
|
|
57
|
+
* only (#342). server.ts renders what this returns.
|
|
42
58
|
*
|
|
43
59
|
* Token sources, in priority order: `Authorization: Bearer` header, a
|
|
44
60
|
* `formToken` in the parsed body, then a session token.
|
|
@@ -47,9 +63,9 @@ export function enforceRouteAuth(
|
|
|
47
63
|
req: Tina4Request,
|
|
48
64
|
res: Tina4Response,
|
|
49
65
|
match: AuthGateRoute,
|
|
50
|
-
):
|
|
66
|
+
): AuthReject | null {
|
|
51
67
|
if (!(match.secure === true && match.noAuth !== true)) {
|
|
52
|
-
return
|
|
68
|
+
return null;
|
|
53
69
|
}
|
|
54
70
|
|
|
55
71
|
// Token slots in priority order: Bearer header, body formToken (frond.js
|
|
@@ -86,7 +102,7 @@ export function enforceRouteAuth(
|
|
|
86
102
|
if (identity) {
|
|
87
103
|
req.user = identity;
|
|
88
104
|
// RBAC guards apply to the SSO identity too (Feature 138).
|
|
89
|
-
return rbacForbidden(match, identity
|
|
105
|
+
return rbacForbidden(match, identity);
|
|
90
106
|
}
|
|
91
107
|
const sessionToken = (req as any).session?.get?.("token") as string | undefined;
|
|
92
108
|
if (sessionToken) {
|
|
@@ -96,9 +112,9 @@ export function enforceRouteAuth(
|
|
|
96
112
|
}
|
|
97
113
|
|
|
98
114
|
if (!payload) {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
return
|
|
115
|
+
// ERR-DEC-02 (#342): the caller negotiates — a browser gets errors/401.twig,
|
|
116
|
+
// an API client the JSON envelope. Was an unconditional raw JSON write here.
|
|
117
|
+
return { status: 401, message: "Unauthorized" };
|
|
102
118
|
}
|
|
103
119
|
|
|
104
120
|
req.user = payload;
|
|
@@ -114,7 +130,7 @@ export function enforceRouteAuth(
|
|
|
114
130
|
// ── RBAC guards (Feature 138): authorization AFTER authentication ──
|
|
115
131
|
// Auth has passed (401 ruled out above). If the route carries role/permission
|
|
116
132
|
// guards, the verified payload must satisfy them, else 403.
|
|
117
|
-
return rbacForbidden(match, req.user
|
|
133
|
+
return rbacForbidden(match, req.user);
|
|
118
134
|
}
|
|
119
135
|
|
|
120
136
|
/** Read a claim as a list of strings; coerce a legacy singular string. */
|
|
@@ -144,28 +160,25 @@ function rbacPermGranted(granted: string[], required: string): boolean {
|
|
|
144
160
|
* the verified payload; return `false` (no write) when authorised or unguarded.
|
|
145
161
|
* AND across guard groups, OR within a group. Feature 138 / ADR-0058.
|
|
146
162
|
*/
|
|
147
|
-
function rbacForbidden(match: AuthGateRoute, payload: unknown
|
|
163
|
+
function rbacForbidden(match: AuthGateRoute, payload: unknown): AuthReject | null {
|
|
148
164
|
const requiredRoles = match.requiredRoles ?? [];
|
|
149
165
|
const requiredPerms = match.requiredPerms ?? [];
|
|
150
166
|
if (requiredRoles.length === 0 && requiredPerms.length === 0) {
|
|
151
|
-
return
|
|
167
|
+
return null;
|
|
152
168
|
}
|
|
153
169
|
const subject =
|
|
154
170
|
payload && typeof payload === "object" ? (payload as Record<string, unknown>) : {};
|
|
155
171
|
|
|
172
|
+
// ERR-DEC-02 (#342): the caller negotiates the 403 (HTML page vs JSON
|
|
173
|
+
// envelope) — the gate only decides the refusal.
|
|
174
|
+
const forbidden: AuthReject = { status: 403, message: "Forbidden" };
|
|
156
175
|
const roles = rbacClaimList(subject, "roles", "role");
|
|
157
176
|
for (const group of requiredRoles) {
|
|
158
|
-
if (!group.some((r) => roles.includes(r))) return
|
|
177
|
+
if (!group.some((r) => roles.includes(r))) return forbidden;
|
|
159
178
|
}
|
|
160
179
|
const perms = rbacClaimList(subject, "permissions");
|
|
161
180
|
for (const group of requiredPerms) {
|
|
162
|
-
if (!group.some((p) => rbacPermGranted(perms, p))) return
|
|
181
|
+
if (!group.some((p) => rbacPermGranted(perms, p))) return forbidden;
|
|
163
182
|
}
|
|
164
|
-
return
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
function writeForbidden(res: Tina4Response): boolean {
|
|
168
|
-
res.raw.writeHead(403, { "Content-Type": "application/json" });
|
|
169
|
-
res.raw.end(JSON.stringify({ error: "Forbidden" }));
|
|
170
|
-
return true;
|
|
183
|
+
return null;
|
|
171
184
|
}
|
|
@@ -14,7 +14,7 @@ import { isTruthy } from "./dotenv.js";
|
|
|
14
14
|
import { defaultRouter, type Router } from "./router.js";
|
|
15
15
|
import { resolveClientIp } from "./trustedProxy.js";
|
|
16
16
|
import { currentCspNonce, resolveCspHeader } from "./csp.js";
|
|
17
|
-
import { getFrond, getFrameworkFrond, wantsJson, negotiatedErrorBody } from "./response.js";
|
|
17
|
+
import { getFrond, getFrameworkFrond, wantsJson, negotiatedErrorBody, renderNegotiatedError } from "./response.js";
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* Whether to emit a per-request log line (v3.13.14). TINA4_LOG_REQUESTS is
|
|
@@ -210,12 +210,13 @@ async function interpretHookResult(
|
|
|
210
210
|
* all — that name belonged to its dispatcher, back when its orchestrator had no
|
|
211
211
|
* exception handling to mirror.
|
|
212
212
|
*/
|
|
213
|
-
function middleware500(
|
|
213
|
+
async function middleware500(
|
|
214
214
|
res: Tina4Response,
|
|
215
215
|
mwClass: any,
|
|
216
216
|
methodName: string,
|
|
217
217
|
error: unknown,
|
|
218
|
-
|
|
218
|
+
req?: Tina4Request,
|
|
219
|
+
): Promise<Tina4Response> {
|
|
219
220
|
const clsName = mwClass?.name ?? mwClass?.constructor?.name ?? "Middleware";
|
|
220
221
|
const err = error as { name?: string; message?: string };
|
|
221
222
|
const type = err?.name ?? (error as object)?.constructor?.name ?? "Error";
|
|
@@ -225,7 +226,18 @@ function middleware500(
|
|
|
225
226
|
} catch {
|
|
226
227
|
/* never let a broken logger swallow the 500 */
|
|
227
228
|
}
|
|
228
|
-
//
|
|
229
|
+
// ERR-DEC-02 (#342): answer through the SAME negotiation every other framework
|
|
230
|
+
// error uses — errors/500.twig for a browser, the JSON envelope
|
|
231
|
+
// {error, code, message, status, request_id} for an API client. The real
|
|
232
|
+
// exception stays in the log, never in the body (CWE-209). It used to write an
|
|
233
|
+
// unconditional {error:"Internal Server Error",status:500}. `req` is optional
|
|
234
|
+
// only for backward safety; the runner always passes it, and with a raw
|
|
235
|
+
// response available we negotiate.
|
|
236
|
+
if (req && res?.raw && typeof res.raw.writeHead === "function" && !res.raw.writableEnded) {
|
|
237
|
+
await renderNegotiatedError(req, res, 500, "Internal Server Error");
|
|
238
|
+
return res;
|
|
239
|
+
}
|
|
240
|
+
// Fallback (no request / no raw response): the bare JSON body, as before.
|
|
229
241
|
if (typeof (res as any).json === "function") {
|
|
230
242
|
(res as any).json({ error: "Internal Server Error", status: 500 }, 500);
|
|
231
243
|
} else if (typeof (res as any) === "function") {
|
|
@@ -386,7 +398,7 @@ export class MiddlewareRunner {
|
|
|
386
398
|
if (stop) return [req, res, false];
|
|
387
399
|
} catch (error) {
|
|
388
400
|
// Throw → logged clean 500, skip the handler (deterministic).
|
|
389
|
-
res = middleware500(res, cls, method, error);
|
|
401
|
+
res = await middleware500(res, cls, method, error, req);
|
|
390
402
|
return [req, res, false];
|
|
391
403
|
}
|
|
392
404
|
// LEGACY COMPAT PATH — retained, but NOT the main mechanism. A hook
|
|
@@ -443,7 +455,7 @@ export class MiddlewareRunner {
|
|
|
443
455
|
if (stop) return [req, res];
|
|
444
456
|
} catch (error) {
|
|
445
457
|
// Throw → logged clean 500, but remaining after* STILL run.
|
|
446
|
-
res = middleware500(res, cls, method, error);
|
|
458
|
+
res = await middleware500(res, cls, method, error, req);
|
|
447
459
|
continue;
|
|
448
460
|
}
|
|
449
461
|
}
|
|
@@ -641,11 +641,12 @@ export function wantsJson(req: { headers?: Record<string, string | string[] | un
|
|
|
641
641
|
}
|
|
642
642
|
|
|
643
643
|
const ERROR_CODE_NAMES: Record<number, string> = {
|
|
644
|
-
|
|
644
|
+
401: "UNAUTHORIZED", 403: "FORBIDDEN", 404: "NOT_FOUND",
|
|
645
|
+
405: "METHOD_NOT_ALLOWED", 500: "INTERNAL_SERVER_ERROR",
|
|
645
646
|
};
|
|
646
647
|
|
|
647
648
|
/**
|
|
648
|
-
* The ONE JSON error envelope for a negotiated 403/404/500 (ERR-DEC-02).
|
|
649
|
+
* The ONE JSON error envelope for a negotiated 401/403/404/500 (ERR-DEC-02).
|
|
649
650
|
*
|
|
650
651
|
* Reuses errorResponse() (error: true, code, message, status) already shared
|
|
651
652
|
* by app-level response.error() calls, plus request_id for correlation
|
|
@@ -656,3 +657,60 @@ export function negotiatedErrorBody(code: number, message: string, requestId: st
|
|
|
656
657
|
body.request_id = requestId;
|
|
657
658
|
return body;
|
|
658
659
|
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Write a negotiated error straight to the raw response (ERR-DEC-02, #342): a
|
|
663
|
+
* browser gets errors/{code}.twig (app override first, then the framework
|
|
664
|
+
* default), an API client the JSON envelope, both carrying request_id. The
|
|
665
|
+
* ONE cross-module negotiated writer, used by the auth/RBAC gate (authGate.ts)
|
|
666
|
+
* and the throwing-middleware 500 (middleware.ts), which own no renderer of
|
|
667
|
+
* their own; server.ts's 404/500 and middleware.ts's renderForbidden keep their
|
|
668
|
+
* own copies. error_message is ALWAYS empty here (CWE-209 for the 500).
|
|
669
|
+
*
|
|
670
|
+
* Lives in response.ts (a leaf module) so authGate/middleware can import it
|
|
671
|
+
* without the circular dependency a server.ts renderer would create.
|
|
672
|
+
*/
|
|
673
|
+
export async function renderNegotiatedError(
|
|
674
|
+
req: { headers?: Record<string, string | string[] | undefined>; path?: string },
|
|
675
|
+
res: Tina4Response,
|
|
676
|
+
code: number,
|
|
677
|
+
message: string,
|
|
678
|
+
): Promise<void> {
|
|
679
|
+
const { Log } = await import("./logger.js");
|
|
680
|
+
const requestId = Log.getRequestId() ?? "";
|
|
681
|
+
|
|
682
|
+
const writeJson = (): void => {
|
|
683
|
+
const body = negotiatedErrorBody(code, message, requestId);
|
|
684
|
+
res.raw.statusCode = code;
|
|
685
|
+
res.raw.setHeader("Content-Type", "application/json");
|
|
686
|
+
res.raw.end(JSON.stringify(body));
|
|
687
|
+
};
|
|
688
|
+
|
|
689
|
+
if (wantsJson(req)) {
|
|
690
|
+
writeJson();
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
const data = { path: req?.path ?? "", error_message: "", request_id: requestId, status_code: code };
|
|
695
|
+
const template = `errors/${code}.twig`;
|
|
696
|
+
let html: string | null = null;
|
|
697
|
+
try {
|
|
698
|
+
html = (await getFrond()).render(template, data);
|
|
699
|
+
} catch {
|
|
700
|
+
/* fall through to the framework default */
|
|
701
|
+
}
|
|
702
|
+
if (!html) {
|
|
703
|
+
try {
|
|
704
|
+
const fw = await getFrameworkFrond();
|
|
705
|
+
html = fw ? fw.render(template, data) : null;
|
|
706
|
+
} catch {
|
|
707
|
+
html = null;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
if (html) {
|
|
711
|
+
res.raw.writeHead(code, { "Content-Type": "text/html; charset=utf-8" });
|
|
712
|
+
res.raw.end(html);
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
writeJson();
|
|
716
|
+
}
|