jskelet 0.2.5 → 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.
Files changed (106) hide show
  1. package/AGENTS.md +132 -132
  2. package/CHANGELOG.md +403 -383
  3. package/LICENSE +21 -21
  4. package/bin/jskelet.mjs +103 -103
  5. package/docs/01-baslangic.md +285 -285
  6. package/docs/02-mimari.md +293 -287
  7. package/docs/03-routing.md +486 -480
  8. package/docs/04-render-ve-sablonlar.md +490 -490
  9. package/docs/05-islands.md +482 -482
  10. package/docs/06-cache.md +1231 -1209
  11. package/docs/07-yapilandirma.md +44 -21
  12. package/docs/08-build.md +366 -366
  13. package/docs/09-dev-araclari.md +335 -335
  14. package/docs/10-dagitim.md +329 -329
  15. package/docs/11-tasima.md +1 -0
  16. package/docs/12-panel-ve-oturum.md +384 -384
  17. package/docs/README.md +105 -105
  18. package/docs/en/01-getting-started.md +292 -292
  19. package/docs/en/02-architecture.md +311 -305
  20. package/docs/en/03-routing.md +503 -497
  21. package/docs/en/04-rendering.md +504 -504
  22. package/docs/en/05-islands.md +492 -492
  23. package/docs/en/06-caching.md +1197 -1198
  24. package/docs/en/07-configuration.md +1009 -986
  25. package/docs/en/08-build.md +383 -383
  26. package/docs/en/09-dev-tools.md +342 -342
  27. package/docs/en/10-deployment.md +332 -332
  28. package/docs/en/11-migration.md +360 -359
  29. package/docs/en/12-dashboards-and-sessions.md +392 -392
  30. package/docs/en/README.md +112 -112
  31. package/package.json +102 -102
  32. package/src/build/ensure-build.mjs +15 -15
  33. package/src/build/paths.mjs +143 -143
  34. package/src/build/resolve-peer.mjs +36 -36
  35. package/src/build/tasks/client.mjs +268 -268
  36. package/src/build/tasks/css.mjs +124 -124
  37. package/src/build/tasks/fonts.mjs +146 -146
  38. package/src/build/tasks/icons.mjs +224 -224
  39. package/src/build/tasks/images.mjs +244 -244
  40. package/src/build/tasks/precompress.mjs +78 -78
  41. package/src/client/{cache-panel → admin}/i18n.js +756 -670
  42. package/src/client/{cache-panel → admin}/login.html +74 -74
  43. package/src/client/{cache-panel → admin}/panel.css +804 -756
  44. package/src/client/admin/panel.html +486 -0
  45. package/src/client/{cache-panel → admin}/panel.js +1242 -915
  46. package/src/client/devtools/report.html +185 -185
  47. package/src/client/devtools/report.js +725 -725
  48. package/src/client/dom.js +95 -95
  49. package/src/client/form.js +192 -192
  50. package/src/client/index.js +35 -35
  51. package/src/client/registry.js +297 -297
  52. package/src/client/safe-image.js +91 -91
  53. package/src/client/store.js +36 -36
  54. package/src/client/swap.js +188 -188
  55. package/src/config/defaults.js +16 -7
  56. package/src/config/index.js +38 -22
  57. package/src/config/pattern.js +107 -107
  58. package/src/http/control-flow.js +71 -71
  59. package/src/http/cookies.js +257 -257
  60. package/src/http/request-cache.js +46 -46
  61. package/src/http/request-context.js +162 -162
  62. package/src/index.js +83 -83
  63. package/src/init.mjs +221 -221
  64. package/src/log.mjs +58 -0
  65. package/src/runtime/alias-hooks.mjs +119 -119
  66. package/src/runtime/register.mjs +4 -4
  67. package/src/server/admin/actions.js +229 -0
  68. package/src/server/admin/auth.js +125 -0
  69. package/src/server/admin/event-log.js +151 -0
  70. package/src/server/admin/gate.js +209 -0
  71. package/src/server/admin/inventory.js +188 -0
  72. package/src/server/admin/mount.js +56 -0
  73. package/src/server/admin/router.js +216 -0
  74. package/src/server/admin/snapshot.js +126 -0
  75. package/src/server/assets.js +147 -147
  76. package/src/server/cache-deps.js +42 -42
  77. package/src/server/cloudflare.js +607 -607
  78. package/src/server/create-app.js +295 -291
  79. package/src/server/data-cache.js +462 -462
  80. package/src/server/dev/report.js +369 -369
  81. package/src/server/dev/socket.js +170 -170
  82. package/src/server/dev/version-check.mjs +139 -139
  83. package/src/server/html-cache.js +817 -817
  84. package/src/server/metadata.js +102 -102
  85. package/src/server/middleware/compression.js +205 -205
  86. package/src/server/middleware/csrf.js +134 -134
  87. package/src/server/middleware/dev-gate.js +62 -62
  88. package/src/server/middleware/headers.js +37 -37
  89. package/src/server/middleware/redirects.js +32 -32
  90. package/src/server/middleware/static-precompressed.js +100 -100
  91. package/src/server/middleware/trailing-slash.js +53 -0
  92. package/src/server/middleware/upstream-proxy.js +141 -141
  93. package/src/server/prewarm.js +601 -601
  94. package/src/server/redis.js +569 -569
  95. package/src/server/router.js +128 -128
  96. package/src/server/status-page.js +164 -164
  97. package/src/server/upstream-limiter.js +376 -376
  98. package/src/server/upstream-tracking.js +166 -166
  99. package/src/start.mjs +7 -7
  100. package/src/templates/layout.ejs +44 -44
  101. package/src/version.mjs +31 -31
  102. package/src/views/components/loader.js +85 -85
  103. package/src/views/helpers/html.js +102 -102
  104. package/src/views/helpers/tags.js +245 -245
  105. package/src/client/cache-panel/panel.html +0 -308
  106. package/src/server/cache-panel.js +0 -759
@@ -1,119 +1,119 @@
1
- /**
2
- * Node ESM resolve hook'ları. İki iş yapar:
3
- *
4
- * 1. `jsconfig.json` / `tsconfig.json` içindeki `compilerOptions.paths`
5
- * alias'larını çözer (`@/lib/x` → `<root>/lib/x`). Editör ve çalışma zamanı
6
- * aynı dosyadan beslendiği için ikisi birbirinden ayrışmaz.
7
- * 2. Uzantısız göreli import'lara uzantı ekler (`./cache` → `./cache.js`).
8
- * Node ESM bunu yapmaz; bundler'dan taşınan kodda en sık karşılaşılan
9
- * kırılma noktası bu.
10
- *
11
- * `node --import jskelet/register` ile kurulur.
12
- */
13
- import fs from "node:fs";
14
- import path from "node:path";
15
- import process from "node:process";
16
- import { fileURLToPath, pathToFileURL } from "node:url";
17
-
18
- const ROOT = process.cwd();
19
-
20
- /** Uzantısız hedefler için denenecek sıra. */
21
- const EXTENSIONS = [".js", ".mjs", ".json", "/index.js", "/index.mjs"];
22
-
23
- /**
24
- * @returns {{ prefix: string, target: string }[]}
25
- */
26
- function readAliases() {
27
- for (const name of ["jsconfig.json", "tsconfig.json"]) {
28
- const file = path.join(ROOT, name);
29
- if (!fs.existsSync(file)) continue;
30
-
31
- try {
32
- // Yorum içerebilen tsconfig'ler için kaba ama yeterli bir temizlik;
33
- // tam bir JSON5 ayrıştırıcısı bağımlılık eklemeye değmiyor.
34
- const raw = fs
35
- .readFileSync(file, "utf8")
36
- .replace(/\/\*[\s\S]*?\*\//g, "")
37
- .replace(/^\s*\/\/.*$/gm, "");
38
-
39
- const config = JSON.parse(raw);
40
- const baseUrl = path.resolve(ROOT, config.compilerOptions?.baseUrl ?? ".");
41
- const paths = config.compilerOptions?.paths ?? {};
42
-
43
- /** @type {{ prefix: string, target: string }[]} */
44
- const aliases = [];
45
-
46
- for (const [pattern, targets] of Object.entries(paths)) {
47
- const target = Array.isArray(targets) ? targets[0] : targets;
48
- if (!pattern.endsWith("/*") || typeof target !== "string") continue;
49
-
50
- aliases.push({
51
- prefix: pattern.slice(0, -1),
52
- target: path.resolve(baseUrl, target.slice(0, -1)),
53
- });
54
- }
55
-
56
- // Uzun önek önce: `@flags/` `@/`den önce denenmeli, yoksa `@/` yakalar.
57
- return aliases.sort((a, b) => b.prefix.length - a.prefix.length);
58
- } catch (error) {
59
- console.warn(`[alias] could not read ${name}, aliases disabled`, error);
60
- return [];
61
- }
62
- }
63
-
64
- return [];
65
- }
66
-
67
- const ALIASES = readAliases();
68
-
69
- /**
70
- * @param {string} filePath
71
- * @returns {boolean}
72
- */
73
- function isFile(filePath) {
74
- try {
75
- return fs.statSync(filePath).isFile();
76
- } catch {
77
- return false;
78
- }
79
- }
80
-
81
- /**
82
- * @param {string} filePath
83
- * @returns {string | null}
84
- */
85
- function resolveFile(filePath) {
86
- if (path.extname(filePath) && isFile(filePath)) return filePath;
87
-
88
- for (const suffix of EXTENSIONS) {
89
- const candidate = `${filePath}${suffix}`;
90
- if (isFile(candidate)) return candidate;
91
- }
92
-
93
- return isFile(filePath) ? filePath : null;
94
- }
95
-
96
- export async function resolve(specifier, context, nextResolve) {
97
- for (const { prefix, target } of ALIASES) {
98
- if (!specifier.startsWith(prefix)) continue;
99
-
100
- const base = path.join(target, specifier.slice(prefix.length));
101
- const resolved = resolveFile(base);
102
-
103
- return nextResolve(pathToFileURL(resolved ?? base).href, context);
104
- }
105
-
106
- if (
107
- (specifier.startsWith("./") || specifier.startsWith("../")) &&
108
- !path.extname(specifier) &&
109
- context.parentURL?.startsWith("file:")
110
- ) {
111
- const parentDir = path.dirname(fileURLToPath(context.parentURL));
112
- const base = path.resolve(parentDir, specifier);
113
- const resolved = resolveFile(base);
114
-
115
- if (resolved) return nextResolve(pathToFileURL(resolved).href, context);
116
- }
117
-
118
- return nextResolve(specifier, context);
119
- }
1
+ /**
2
+ * Node ESM resolve hook'ları. İki iş yapar:
3
+ *
4
+ * 1. `jsconfig.json` / `tsconfig.json` içindeki `compilerOptions.paths`
5
+ * alias'larını çözer (`@/lib/x` → `<root>/lib/x`). Editör ve çalışma zamanı
6
+ * aynı dosyadan beslendiği için ikisi birbirinden ayrışmaz.
7
+ * 2. Uzantısız göreli import'lara uzantı ekler (`./cache` → `./cache.js`).
8
+ * Node ESM bunu yapmaz; bundler'dan taşınan kodda en sık karşılaşılan
9
+ * kırılma noktası bu.
10
+ *
11
+ * `node --import jskelet/register` ile kurulur.
12
+ */
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import process from "node:process";
16
+ import { fileURLToPath, pathToFileURL } from "node:url";
17
+
18
+ const ROOT = process.cwd();
19
+
20
+ /** Uzantısız hedefler için denenecek sıra. */
21
+ const EXTENSIONS = [".js", ".mjs", ".json", "/index.js", "/index.mjs"];
22
+
23
+ /**
24
+ * @returns {{ prefix: string, target: string }[]}
25
+ */
26
+ function readAliases() {
27
+ for (const name of ["jsconfig.json", "tsconfig.json"]) {
28
+ const file = path.join(ROOT, name);
29
+ if (!fs.existsSync(file)) continue;
30
+
31
+ try {
32
+ // Yorum içerebilen tsconfig'ler için kaba ama yeterli bir temizlik;
33
+ // tam bir JSON5 ayrıştırıcısı bağımlılık eklemeye değmiyor.
34
+ const raw = fs
35
+ .readFileSync(file, "utf8")
36
+ .replace(/\/\*[\s\S]*?\*\//g, "")
37
+ .replace(/^\s*\/\/.*$/gm, "");
38
+
39
+ const config = JSON.parse(raw);
40
+ const baseUrl = path.resolve(ROOT, config.compilerOptions?.baseUrl ?? ".");
41
+ const paths = config.compilerOptions?.paths ?? {};
42
+
43
+ /** @type {{ prefix: string, target: string }[]} */
44
+ const aliases = [];
45
+
46
+ for (const [pattern, targets] of Object.entries(paths)) {
47
+ const target = Array.isArray(targets) ? targets[0] : targets;
48
+ if (!pattern.endsWith("/*") || typeof target !== "string") continue;
49
+
50
+ aliases.push({
51
+ prefix: pattern.slice(0, -1),
52
+ target: path.resolve(baseUrl, target.slice(0, -1)),
53
+ });
54
+ }
55
+
56
+ // Uzun önek önce: `@flags/` `@/`den önce denenmeli, yoksa `@/` yakalar.
57
+ return aliases.sort((a, b) => b.prefix.length - a.prefix.length);
58
+ } catch (error) {
59
+ console.warn(`[alias] could not read ${name}, aliases disabled`, error);
60
+ return [];
61
+ }
62
+ }
63
+
64
+ return [];
65
+ }
66
+
67
+ const ALIASES = readAliases();
68
+
69
+ /**
70
+ * @param {string} filePath
71
+ * @returns {boolean}
72
+ */
73
+ function isFile(filePath) {
74
+ try {
75
+ return fs.statSync(filePath).isFile();
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
81
+ /**
82
+ * @param {string} filePath
83
+ * @returns {string | null}
84
+ */
85
+ function resolveFile(filePath) {
86
+ if (path.extname(filePath) && isFile(filePath)) return filePath;
87
+
88
+ for (const suffix of EXTENSIONS) {
89
+ const candidate = `${filePath}${suffix}`;
90
+ if (isFile(candidate)) return candidate;
91
+ }
92
+
93
+ return isFile(filePath) ? filePath : null;
94
+ }
95
+
96
+ export async function resolve(specifier, context, nextResolve) {
97
+ for (const { prefix, target } of ALIASES) {
98
+ if (!specifier.startsWith(prefix)) continue;
99
+
100
+ const base = path.join(target, specifier.slice(prefix.length));
101
+ const resolved = resolveFile(base);
102
+
103
+ return nextResolve(pathToFileURL(resolved ?? base).href, context);
104
+ }
105
+
106
+ if (
107
+ (specifier.startsWith("./") || specifier.startsWith("../")) &&
108
+ !path.extname(specifier) &&
109
+ context.parentURL?.startsWith("file:")
110
+ ) {
111
+ const parentDir = path.dirname(fileURLToPath(context.parentURL));
112
+ const base = path.resolve(parentDir, specifier);
113
+ const resolved = resolveFile(base);
114
+
115
+ if (resolved) return nextResolve(pathToFileURL(resolved).href, context);
116
+ }
117
+
118
+ return nextResolve(specifier, context);
119
+ }
@@ -1,4 +1,4 @@
1
- /** `node --import jskelet/register` ile alias hook'unu kaydeder. */
2
- import { register } from "node:module";
3
-
4
- register("./alias-hooks.mjs", import.meta.url);
1
+ /** `node --import jskelet/register` ile alias hook'unu kaydeder. */
2
+ import { register } from "node:module";
3
+
4
+ register("./alias-hooks.mjs", import.meta.url);
@@ -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
+ }