Files
OmniRoute/scripts/dev/http-method-guard.cjs
小妍儿 ✨ cb55651736 feat(api): import caller-supplied gateway API keys atomically (#18010)
## Summary

Add `POST /api/keys/import` so a management client can provision the same caller-supplied gateway key on multiple instances without invoking whole-database restore.

- Required `key`/`name`, optional UUID `id`; inherits every create-policy field and refinement through `createKeySchema.safeExtend`.
- Same management authentication as key creation, including `admin` access-token scope and the open-mode management-key credential requirement.
- One synchronous SQLite IMMEDIATE transaction checks identity and inserts the complete policy. Existing explicit id + same value is a read-only retry (200); conflicting id/value is 409 without another id or secret in the response; new import is 201.
- Existing crypto helpers supply encrypted-at-rest storage when configured, hash and prefix. Responses whitelist masked key + stored policy. Environment/self-loop credential collisions are rejected. New imports trigger best-effort asynchronous cloud sync.
- No rekey, settings/provider/combo/session import, or changes to `import-json` authorization. Existing creation remains server-generated.

Closes #18005

## Target branch and design

Thanks @xiaoyaner0201.
2026-11-08 18:33:03 -03:00

107 lines
3.2 KiB
JavaScript

"use strict";
const http = require("node:http");
const HIGH_RISK_METHOD_RULES = [
[/^\/api\/auth\/login\/?$/, ["POST"]],
[/^\/api\/auth\/logout\/?$/, ["POST"]],
[/^\/api\/keys\/?$/, ["GET", "POST"]],
// Must precede the generic /api/keys/{id} rule: "import" is a static segment, not a key id.
[/^\/api\/keys\/import\/?$/, ["POST"]],
[/^\/api\/keys\/[^/]+\/?$/, ["GET", "PATCH", "DELETE"]],
[/^\/api\/keys\/[^/]+\/devices\/?$/, ["GET"]],
];
let installed = false;
function getPathname(req) {
const rawUrl = typeof req?.url === "string" && req.url ? req.url : "/";
try {
return new URL(rawUrl, "http://localhost").pathname;
} catch {
return rawUrl.split("?")[0] || "/";
}
}
function getAllowedMethods(pathname) {
for (const [pattern, methods] of HIGH_RISK_METHOD_RULES) {
if (pattern.test(pathname)) return methods;
}
return null;
}
function getAllowHeader(pathname) {
const methods = getAllowedMethods(pathname);
return methods ? methods.join(", ") : null;
}
// Methods undici/fetch cannot represent: Next's middleware adapter throws
// `TypeError: 'TRACE' HTTP method is unsupported.` while building the Request,
// which surfaces as an unhandled 500 on EVERY route (caught by the dast-smoke
// Schemathesis negative tests). Reject them up-front with a clean 405.
const UNSUPPORTED_METHODS = new Set(["TRACE", "TRACK", "CONNECT"]);
function maybeHandleDisallowedMethod(req, res) {
const method = typeof req?.method === "string" ? req.method.toUpperCase() : "";
const pathname = getPathname(req);
if (UNSUPPORTED_METHODS.has(method)) {
res.statusCode = 405;
res.setHeader("Allow", getAllowHeader(pathname) || "GET, POST, OPTIONS");
res.setHeader("Cache-Control", "no-store");
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(
JSON.stringify({
error: {
code: "METHOD_NOT_ALLOWED",
message: `${method} is not allowed`,
},
})
);
return true;
}
const methods = getAllowedMethods(pathname);
if (!methods || method === "OPTIONS" || methods.includes(method)) return false;
res.statusCode = 405;
res.setHeader("Allow", methods.join(", "));
res.setHeader("Cache-Control", "no-store");
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(
JSON.stringify({
error: {
code: "METHOD_NOT_ALLOWED",
message: `${method || "Method"} is not allowed`,
},
})
);
return true;
}
function wrapRequestListenerWithMethodGuard(listener) {
return function methodGuardRequestHandler(req, res) {
if (maybeHandleDisallowedMethod(req, res)) return;
return listener.call(this, req, res);
};
}
function installHttpMethodGuard() {
if (installed) return;
installed = true;
const originalCreateServer = http.createServer.bind(http);
http.createServer = function createServerWithMethodGuard(...args) {
const lastFnIdx = args.map((arg) => typeof arg === "function").lastIndexOf(true);
if (lastFnIdx >= 0) {
args[lastFnIdx] = wrapRequestListenerWithMethodGuard(args[lastFnIdx]);
}
return originalCreateServer(...args);
};
}
module.exports = {
getAllowHeader,
maybeHandleDisallowedMethod,
wrapRequestListenerWithMethodGuard,
installHttpMethodGuard,
};