jskelet 0.2.4 → 0.3.0

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.
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Admin paneli mutasyonları. Cevap metin değil `{ ok, code, params }` —
3
+ * i18n client'ta.
4
+ */
5
+ import {
6
+ clearHtmlCache,
7
+ dropHtmlCacheKey,
8
+ getHtmlCacheSize,
9
+ invalidateHtmlCache,
10
+ } from "../html-cache.js";
11
+ import {
12
+ clearDataCache,
13
+ dropDataCacheKey,
14
+ } from "../data-cache.js";
15
+ import {
16
+ getRedisStatus,
17
+ inspectRedis,
18
+ redisDropMatching,
19
+ } from "../redis.js";
20
+ import {
21
+ clearCloudflareCacheReserve,
22
+ purgeCloudflare,
23
+ setCloudflareFeature,
24
+ setCloudflareSetting,
25
+ toCloudflareUrls,
26
+ } from "../cloudflare.js";
27
+ import { prewarm, prewarmProgress } from "../prewarm.js";
28
+
29
+ /**
30
+ * @param {Record<string, any>} body
31
+ * @param {import('express').Request} req
32
+ * @returns {Promise<{ ok: boolean, code?: string,
33
+ * params?: Record<string, string | number>,
34
+ * parts?: ({ code: string, params?: Record<string, string | number> } | null)[] }>}
35
+ */
36
+ export async function runAction(body, req) {
37
+ const type = String(body?.type ?? "");
38
+
39
+ switch (type) {
40
+ case "html:clear": {
41
+ const size = getHtmlCacheSize();
42
+ clearHtmlCache();
43
+ return { ok: true, code: "html.cleared", params: { count: size } };
44
+ }
45
+
46
+ case "data:clear": {
47
+ const prefix = typeof body.prefix === "string" && body.prefix ? body.prefix : undefined;
48
+ const removed = clearDataCache(prefix);
49
+ return prefix
50
+ ? { ok: true, code: "data.clearedPrefix", params: { count: removed, prefix } }
51
+ : { ok: true, code: "data.cleared", params: { count: removed } };
52
+ }
53
+
54
+ case "html:invalidate": {
55
+ const target = String(body.target ?? "");
56
+ if (!target.startsWith("/")) {
57
+ return { ok: false, code: "target.invalid" };
58
+ }
59
+
60
+ const hard = body.hard === true;
61
+ const count = invalidateHtmlCache(target, { hard });
62
+ return {
63
+ ok: true,
64
+ code: hard ? "html.dropped" : "html.marked",
65
+ params: { count, target },
66
+ };
67
+ }
68
+
69
+ case "html:drop": {
70
+ const key = String(body.key ?? "");
71
+ if (!key) return { ok: false, code: "key.missing" };
72
+ const existed = dropHtmlCacheKey(key);
73
+ return { ok: true, code: existed ? "entry.dropped" : "entry.absent", params: { key } };
74
+ }
75
+
76
+ case "data:drop": {
77
+ const key = String(body.key ?? "");
78
+ if (!key) return { ok: false, code: "key.missing" };
79
+ const existed = dropDataCacheKey(key);
80
+ return { ok: true, code: existed ? "entry.dropped" : "entry.absent", params: { key } };
81
+ }
82
+
83
+ case "redis:inspect": {
84
+ const result = await inspectRedis();
85
+ if (!result.ok) return { ok: false, code: "redis.unreachable" };
86
+
87
+ return {
88
+ ok: true,
89
+ parts: [
90
+ { code: "redis.htmlKeys", params: { count: result.html } },
91
+ { code: "redis.dataKeys", params: { count: result.data } },
92
+ result.totalKeys !== null
93
+ ? { code: "redis.dbKeys", params: { count: result.totalKeys } }
94
+ : null,
95
+ result.usedMemory ? { code: "redis.memory", params: { value: result.usedMemory } } : null,
96
+ ].filter(Boolean),
97
+ };
98
+ }
99
+
100
+ case "redis:drop": {
101
+ const kind = body.kind === "data" ? "data" : "html";
102
+ const status = getRedisStatus();
103
+ if (!status.connected) {
104
+ return { ok: false, code: "redis.notConnected" };
105
+ }
106
+
107
+ const dropped = await redisDropMatching(kind);
108
+ return {
109
+ ok: true,
110
+ code: kind === "data" ? "redis.droppedData" : "redis.droppedHtml",
111
+ params: { count: dropped },
112
+ };
113
+ }
114
+
115
+ case "cf:purge-everything": {
116
+ const result = await purgeCloudflare({ everything: true });
117
+ return result.ok
118
+ ? { ok: true, code: "cf.purgedEverything" }
119
+ : cloudflareFailure(result.error);
120
+ }
121
+
122
+ case "cf:purge-urls": {
123
+ const paths = Array.isArray(body.paths) ? body.paths.map(String) : [];
124
+ if (!paths.length) return { ok: false, code: "cf.noPaths" };
125
+
126
+ const urls = toCloudflareUrls(paths, originOf(req));
127
+ if (!urls.length) return { ok: false, code: "cf.noHostname" };
128
+
129
+ const result = await purgeCloudflare({ files: urls });
130
+ return result.ok
131
+ ? {
132
+ ok: true,
133
+ code: "cf.purgedUrls",
134
+ params: { count: result.purged, batches: result.batches },
135
+ }
136
+ : cloudflareFailure(result.error);
137
+ }
138
+
139
+ case "cf:purge-keys": {
140
+ /** @type {"prefixes" | "hosts" | "tags"} */
141
+ const kind =
142
+ body.kind === "hosts" ? "hosts" : body.kind === "tags" ? "tags" : "prefixes";
143
+
144
+ const values = String(body.values ?? "")
145
+ .split(/[\s,]+/)
146
+ .filter(Boolean);
147
+
148
+ if (!values.length) return { ok: false, code: "cf.nothingToPurge" };
149
+
150
+ const result = await purgeCloudflare({ [kind]: values });
151
+ return result.ok
152
+ ? { ok: true, code: "cf.purgedKeys", params: { count: result.purged, kind } }
153
+ : cloudflareFailure(result.error);
154
+ }
155
+
156
+ case "cf:setting": {
157
+ const result = await setCloudflareSetting(body.id, body.value);
158
+ return result.ok
159
+ ? {
160
+ ok: true,
161
+ code: "cf.settingChanged",
162
+ params: { id: String(body.id), value: String(result.value) },
163
+ }
164
+ : cloudflareFailure(result.error);
165
+ }
166
+
167
+ case "cf:feature": {
168
+ const value = body.value === "on" ? "on" : "off";
169
+ const result = await setCloudflareFeature(body.feature, value);
170
+ return result.ok
171
+ ? {
172
+ ok: true,
173
+ code: "cf.featureChanged",
174
+ params: { feature: String(body.feature), value },
175
+ }
176
+ : cloudflareFailure(result.error);
177
+ }
178
+
179
+ case "cf:clear-reserve": {
180
+ const result = await clearCloudflareCacheReserve();
181
+ return result.ok
182
+ ? { ok: true, code: "cf.reserveClearing" }
183
+ : cloudflareFailure(result.error);
184
+ }
185
+
186
+ case "prewarm": {
187
+ if (prewarmProgress.active) {
188
+ return { ok: false, code: "prewarm.busy" };
189
+ }
190
+
191
+ const requested = Array.isArray(body.paths) ? body.paths : [];
192
+ const paths = requested.filter(
193
+ (/** @type {unknown} */ value) =>
194
+ typeof value === "string" && value.startsWith("/"),
195
+ );
196
+
197
+ prewarm({
198
+ origin: `${req.protocol}://${req.get("host")}`,
199
+ paths: paths.length ? paths : undefined,
200
+ }).catch((error) => {
201
+ console.error("[admin] prewarm failed", error);
202
+ });
203
+
204
+ return paths.length
205
+ ? { ok: true, code: "prewarm.paths", params: { count: paths.length } }
206
+ : { ok: true, code: "prewarm.all" };
207
+ }
208
+
209
+ default:
210
+ return { ok: false, code: "action.unknown", params: { type } };
211
+ }
212
+ }
213
+
214
+ /**
215
+ * @param {string | undefined} error
216
+ * @returns {{ ok: false, code: string, params: { error: string } }}
217
+ */
218
+ function cloudflareFailure(error) {
219
+ return { ok: false, code: "cf.failed", params: { error: error ?? "unknown error" } };
220
+ }
221
+
222
+ /**
223
+ * @param {import('express').Request} req
224
+ * @returns {string | undefined}
225
+ */
226
+ function originOf(req) {
227
+ const host = req.get("host");
228
+ return host ? `${req.protocol}://${host}` : undefined;
229
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Admin paneli oturum ve şifre yönetimi.
3
+ *
4
+ * Şifre süreç ömrü kadar; kalıcı sır yok. Cookie parse framework'ün
5
+ * `parseCookies()` yolunu kullanmaz — o yol isteği "kişiselleştirilmiş"
6
+ * işaretler.
7
+ */
8
+ import crypto from "node:crypto";
9
+ import process from "node:process";
10
+ import { safeEqual } from "../../http/cookies.js";
11
+
12
+ export const COOKIE_NAME = "jskelet_admin_sid";
13
+
14
+ /**
15
+ * Aksiyon isteklerinde beklenen başlık. Tarayıcı bu başlığı çapraz site bir
16
+ * formla gönderemez (preflight gerekir), yani panelin kendi CSRF freni.
17
+ */
18
+ export const ACTION_HEADER = "x-jskelet-admin";
19
+
20
+ /** 32 haneli, süreç ömrü kadar geçerli şifre. */
21
+ export const PASSWORD = crypto.randomBytes(16).toString("hex");
22
+
23
+ /** @type {Map<string, number>} token → son kullanma zamanı. */
24
+ const sessions = new Map();
25
+
26
+ /**
27
+ * @param {import('express').Request} req
28
+ * @param {string} name
29
+ * @returns {string | null}
30
+ */
31
+ export function readCookie(req, name) {
32
+ const header = req.headers.cookie;
33
+ if (!header) return null;
34
+
35
+ for (const part of header.split(";")) {
36
+ const eq = part.indexOf("=");
37
+ if (eq === -1) continue;
38
+ if (part.slice(0, eq).trim() !== name) continue;
39
+ return decodeURIComponent(part.slice(eq + 1).trim());
40
+ }
41
+
42
+ return null;
43
+ }
44
+
45
+ /**
46
+ * Süresi geçmiş oturumları eler.
47
+ */
48
+ export function pruneSessions() {
49
+ const now = Date.now();
50
+ for (const [token, expiresAt] of sessions) {
51
+ if (now >= expiresAt) sessions.delete(token);
52
+ }
53
+ }
54
+
55
+ /**
56
+ * @param {import('express').Request} req
57
+ * @returns {boolean}
58
+ */
59
+ export function authenticated(req) {
60
+ const token = readCookie(req, COOKIE_NAME);
61
+ if (!token) return false;
62
+
63
+ const expiresAt = sessions.get(token);
64
+ if (expiresAt === undefined) return false;
65
+
66
+ if (Date.now() >= expiresAt) {
67
+ sessions.delete(token);
68
+ return false;
69
+ }
70
+
71
+ return true;
72
+ }
73
+
74
+ /**
75
+ * @param {string} password
76
+ * @returns {boolean}
77
+ */
78
+ export function passwordMatches(password) {
79
+ return Boolean(password) && safeEqual(password, PASSWORD);
80
+ }
81
+
82
+ /**
83
+ * @param {number} sessionHours
84
+ * @returns {{ token: string, maxAge: number }}
85
+ */
86
+ export function createSession(sessionHours) {
87
+ pruneSessions();
88
+ const token = crypto.randomBytes(32).toString("base64url");
89
+ const maxAge = Math.round(sessionHours * 3600);
90
+ sessions.set(token, Date.now() + maxAge * 1000);
91
+ return { token, maxAge };
92
+ }
93
+
94
+ /**
95
+ * @param {import('express').Request} req
96
+ */
97
+ export function destroySession(req) {
98
+ const token = readCookie(req, COOKIE_NAME);
99
+ if (token) sessions.delete(token);
100
+ }
101
+
102
+ /**
103
+ * @param {string} basePath
104
+ * @param {string} token
105
+ * @param {number} maxAge
106
+ * @returns {string}
107
+ */
108
+ export function sessionCookie(basePath, token, maxAge) {
109
+ return [
110
+ `${COOKIE_NAME}=${token}`,
111
+ `Path=${basePath}`,
112
+ `Max-Age=${maxAge}`,
113
+ "HttpOnly",
114
+ "SameSite=Strict",
115
+ ...(process.env.NODE_ENV === "development" ? [] : ["Secure"]),
116
+ ].join("; ");
117
+ }
118
+
119
+ /**
120
+ * @param {string} basePath
121
+ * @returns {string}
122
+ */
123
+ export function clearSessionCookie(basePath) {
124
+ return `${COOKIE_NAME}=; Path=${basePath}; Max-Age=0`;
125
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Admin paneli için süreç içi olay kuyruğu.
3
+ *
4
+ * Kaynaklar: HTTP `finish` middleware'i ve `log.mjs` aboneliği. Gövde yok —
5
+ * yalnızca meta. Admin kapalıyken bu modül yüklenmez.
6
+ */
7
+ import * as log from "../../log.mjs";
8
+ import { getConfig } from "../../config/index.js";
9
+
10
+ /** @typedef {{ kind: string, id: number, at: number, [key: string]: unknown }} LogEntry */
11
+
12
+ /** @type {LogEntry[]} */
13
+ const ring = [];
14
+
15
+ /** @type {Set<(entry: LogEntry) => void>} */
16
+ const live = new Set();
17
+
18
+ let nextId = 1;
19
+ /** @type {(() => void) | null} */
20
+ let unsubscribeLog = null;
21
+ /** @type {string} */
22
+ let basePath = "/_jskelet/admin";
23
+ /** @type {string} */
24
+ let prewarmUa = "jskelet-prewarm";
25
+ let maxSize = 500;
26
+
27
+ /**
28
+ * @param {{ basePath: string, logSize: number, prewarmUserAgent?: string }} options
29
+ */
30
+ export function configureEventLog(options) {
31
+ basePath = options.basePath;
32
+ maxSize = options.logSize;
33
+ if (options.prewarmUserAgent) prewarmUa = options.prewarmUserAgent;
34
+
35
+ if (!unsubscribeLog) {
36
+ unsubscribeLog = log.subscribe((raw) => {
37
+ // HTTP finish middleware zaten kendi kaydını yazıyor; log.http
38
+ // çift kayıt üretmesin.
39
+ if (raw.kind === "http") return;
40
+ push({
41
+ kind: typeof raw.kind === "string" ? raw.kind : "event",
42
+ scope: raw.scope ?? null,
43
+ message: raw.message ?? "",
44
+ note: raw.note ?? null,
45
+ ms: raw.ms ?? null,
46
+ });
47
+ });
48
+ }
49
+ }
50
+
51
+ /**
52
+ * @param {Omit<LogEntry, "id" | "at"> & { kind: string }} partial
53
+ * @returns {LogEntry}
54
+ */
55
+ export function push(partial) {
56
+ /** @type {LogEntry} */
57
+ const entry = {
58
+ ...partial,
59
+ id: nextId++,
60
+ at: Date.now(),
61
+ };
62
+
63
+ ring.push(entry);
64
+ while (ring.length > maxSize) ring.shift();
65
+
66
+ for (const listener of live) {
67
+ try {
68
+ listener(entry);
69
+ } catch {
70
+ // SSE dinleyicisi paneli düşürmesin.
71
+ }
72
+ }
73
+
74
+ return entry;
75
+ }
76
+
77
+ /**
78
+ * @param {number} [afterId]
79
+ * @param {number} [limit]
80
+ * @returns {LogEntry[]}
81
+ */
82
+ export function list(afterId = 0, limit = 200) {
83
+ const capped = Math.min(Math.max(1, limit), maxSize);
84
+ const filtered = afterId > 0 ? ring.filter((entry) => entry.id > afterId) : ring;
85
+ return filtered.slice(-capped);
86
+ }
87
+
88
+ /**
89
+ * @param {(entry: LogEntry) => void} listener
90
+ * @returns {() => void}
91
+ */
92
+ export function subscribeLive(listener) {
93
+ live.add(listener);
94
+ return () => live.delete(listener);
95
+ }
96
+
97
+ /**
98
+ * HTTP yanıt bitiminde ring'e yazar. Admin yolları ve prewarm UA atlanır.
99
+ *
100
+ * @returns {import('express').RequestHandler}
101
+ */
102
+ export function requestLogMiddleware() {
103
+ const brand = getConfig().brand;
104
+
105
+ /** @type {import('express').RequestHandler} */
106
+ return (req, res, next) => {
107
+ const pathname = req.path || "";
108
+ if (pathname === basePath || pathname.startsWith(`${basePath}/`)) {
109
+ return next();
110
+ }
111
+
112
+ if (req.headers["user-agent"] === (brand.prewarmUserAgent || prewarmUa)) {
113
+ return next();
114
+ }
115
+
116
+ const started = process.hrtime.bigint();
117
+
118
+ res.on("finish", () => {
119
+ const routePath = matchedRoute(req);
120
+ push({
121
+ kind: "http",
122
+ method: req.method,
123
+ url: req.originalUrl,
124
+ path: req.path,
125
+ route: routePath,
126
+ status: res.statusCode,
127
+ ms: Number(process.hrtime.bigint() - started) / 1e6,
128
+ cache: /** @type {string | null} */ (
129
+ res.getHeader(brand.cacheHeader) ?? null
130
+ ),
131
+ });
132
+ });
133
+
134
+ next();
135
+ };
136
+ }
137
+
138
+ /**
139
+ * Express'in eşleştirdiği route deseni (mount + path). Yoksa null.
140
+ *
141
+ * @param {import('express').Request} req
142
+ * @returns {string | null}
143
+ */
144
+ function matchedRoute(req) {
145
+ const layer = /** @type {any} */ (req).route;
146
+ if (!layer || typeof layer.path !== "string") return null;
147
+
148
+ const base = /** @type {any} */ (req).baseUrl || "";
149
+ const pattern = layer.path === "/" ? base || "/" : `${base}${layer.path}`;
150
+ return pattern || null;
151
+ }
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Admin paneli erişim kapısı: IP allowlist, bot UA engeli, ban sayacı.
3
+ *
4
+ * Yasaklı / reddedilen her cevap 404: 401/403 panelin varlığını doğrular.
5
+ */
6
+ import net from "node:net";
7
+
8
+ /** Bilinen crawler / bot imzaları (küçük harf). */
9
+ const BOT_MARKERS = [
10
+ "googlebot",
11
+ "bingbot",
12
+ "slurp",
13
+ "duckduckbot",
14
+ "baiduspider",
15
+ "yandexbot",
16
+ "sogou",
17
+ "exabot",
18
+ "facebot",
19
+ "facebookexternalhit",
20
+ "ia_archiver",
21
+ "applebot",
22
+ "semrushbot",
23
+ "ahrefsbot",
24
+ "mj12bot",
25
+ "dotbot",
26
+ "petalbot",
27
+ "bytespider",
28
+ "gptbot",
29
+ "claudebot",
30
+ "ccbot",
31
+ "amazonbot",
32
+ "twitterbot",
33
+ "linkedinbot",
34
+ "embedly",
35
+ "quora link preview",
36
+ "showyoubot",
37
+ "outbrain",
38
+ "pinterest",
39
+ "redditbot",
40
+ "whatsapp",
41
+ "telegrambot",
42
+ "discordbot",
43
+ "crawler",
44
+ "spider",
45
+ "bot/",
46
+ "bot;",
47
+ ];
48
+
49
+ /** @type {Map<string, { fails: number, bannedUntil: number }>} */
50
+ const offenders = new Map();
51
+
52
+ /**
53
+ * @param {import('express').Request} req
54
+ * @returns {string}
55
+ */
56
+ export function clientKey(req) {
57
+ // `trust proxy` ayarı `req.ip`e yansıyor; ters proxy arkasında doğru IP,
58
+ // doğrudan internete açık bir sunucuda soket adresi kullanılır.
59
+ return req.ip ?? req.socket.remoteAddress ?? "unknown";
60
+ }
61
+
62
+ /**
63
+ * @param {string} ua
64
+ * @returns {boolean}
65
+ */
66
+ export function looksLikeBot(ua) {
67
+ if (!ua) return true;
68
+ const lower = ua.toLowerCase();
69
+ return BOT_MARKERS.some((marker) => lower.includes(marker));
70
+ }
71
+
72
+ /**
73
+ * Exact IP veya CIDR (`10.0.0.0/8`). IPv6 için yalnızca exact eşleşme.
74
+ *
75
+ * @param {string} ip
76
+ * @param {string[]} allowIps
77
+ * @returns {boolean}
78
+ */
79
+ export function ipAllowed(ip, allowIps) {
80
+ if (!allowIps.length) return true;
81
+
82
+ const normalized = normalizeIp(ip);
83
+ if (!normalized) return false;
84
+
85
+ for (const entry of allowIps) {
86
+ if (entry.includes("/")) {
87
+ if (matchCidr(normalized, entry)) return true;
88
+ continue;
89
+ }
90
+ if (normalizeIp(entry) === normalized) return true;
91
+ }
92
+
93
+ return false;
94
+ }
95
+
96
+ /**
97
+ * @param {string} ip
98
+ * @returns {string | null}
99
+ */
100
+ function normalizeIp(ip) {
101
+ if (!ip) return null;
102
+ // Express IPv4-mapped IPv6: `:ffff:127.0.0.1`
103
+ const mapped = ip.startsWith("::ffff:") ? ip.slice(7) : ip;
104
+ return mapped;
105
+ }
106
+
107
+ /**
108
+ * @param {string} ip
109
+ * @param {string} cidr
110
+ * @returns {boolean}
111
+ */
112
+ function matchCidr(ip, cidr) {
113
+ const [network, bitsRaw] = cidr.split("/");
114
+ const bits = Number(bitsRaw);
115
+ if (!Number.isFinite(bits) || bits < 0 || bits > 32) return false;
116
+ if (net.isIPv4(ip) && net.isIPv4(network)) {
117
+ const ipNum = ipv4ToInt(ip);
118
+ const netNum = ipv4ToInt(network);
119
+ if (ipNum === null || netNum === null) return false;
120
+ const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
121
+ return (ipNum & mask) === (netNum & mask);
122
+ }
123
+ return false;
124
+ }
125
+
126
+ /**
127
+ * @param {string} ip
128
+ * @returns {number | null}
129
+ */
130
+ function ipv4ToInt(ip) {
131
+ const parts = ip.split(".").map(Number);
132
+ if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n) || n < 0 || n > 255)) {
133
+ return null;
134
+ }
135
+ return ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
136
+ }
137
+
138
+ /**
139
+ * @param {import('express').Request} req
140
+ * @returns {boolean}
141
+ */
142
+ export function banned(req) {
143
+ const record = offenders.get(clientKey(req));
144
+ if (!record) return false;
145
+
146
+ if (record.bannedUntil && Date.now() >= record.bannedUntil) {
147
+ offenders.delete(clientKey(req));
148
+ return false;
149
+ }
150
+
151
+ return record.bannedUntil > 0;
152
+ }
153
+
154
+ /**
155
+ * @param {import('express').Request} req
156
+ * @param {string} reason
157
+ * @param {{ banAttempts: number, banHours: number }} settings
158
+ */
159
+ export function noteFailure(req, reason, settings) {
160
+ const key = clientKey(req);
161
+ const record = offenders.get(key) ?? { fails: 0, bannedUntil: 0 };
162
+ record.fails += 1;
163
+
164
+ if (record.fails >= settings.banAttempts) {
165
+ record.bannedUntil = Date.now() + settings.banHours * 3600_000;
166
+ console.warn(
167
+ `[admin] ${key} banned for ${settings.banHours}h after ` +
168
+ `${record.fails} failed attempts (${reason})`,
169
+ );
170
+ }
171
+
172
+ offenders.set(key, record);
173
+ }
174
+
175
+ /**
176
+ * @param {import('express').Request} req
177
+ */
178
+ export function clearOffender(req) {
179
+ offenders.delete(clientKey(req));
180
+ }
181
+
182
+ /**
183
+ * Kapı middleware'i: ban → IP → bot. Hepsi 404.
184
+ *
185
+ * @param {() => typeof import('../../config/defaults.js').DEFAULT_ADMIN} getSettings
186
+ * @returns {import('express').RequestHandler}
187
+ */
188
+ export function gateMiddleware(getSettings) {
189
+ return (req, res, next) => {
190
+ if (banned(req)) {
191
+ res.status(404).type("text/plain").send("Not Found");
192
+ return;
193
+ }
194
+
195
+ const settings = getSettings();
196
+
197
+ if (!ipAllowed(clientKey(req), settings.allowIps)) {
198
+ res.status(404).type("text/plain").send("Not Found");
199
+ return;
200
+ }
201
+
202
+ if (settings.blockBots && looksLikeBot(String(req.headers["user-agent"] ?? ""))) {
203
+ res.status(404).type("text/plain").send("Not Found");
204
+ return;
205
+ }
206
+
207
+ next();
208
+ };
209
+ }