@dim24/servin 0.0.0-stage → 0.2.1

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,108 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { serve, wire, guard, serveStatic, redirect } from '../index.js';
7
+
8
+ test('Static routing, Redirect, dan Custom Error Pages (404, 401, 403)', async () => {
9
+ const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'servin-extra-'));
10
+ await fs.mkdir(path.join(tmpDir, 'assets'), { recursive: true });
11
+ await fs.writeFile(path.join(tmpDir, 'index.html'), '<h1>Home Static</h1>', 'utf8');
12
+ await fs.writeFile(path.join(tmpDir, '.env'), 'SECRET=123', 'utf8');
13
+ await fs.writeFile(path.join(tmpDir, 'assets', 'app.js'), 'console.log("ok");', 'utf8');
14
+ const forbiddenPage = path.join(tmpDir, '403.html');
15
+ await fs.writeFile(forbiddenPage, '<h1>403 Dilarang Masuk</h1>', 'utf8');
16
+
17
+ const requireAdmin = () => {
18
+ if (!wire.session.user) wire.abort(401, 'Belum login');
19
+ if (wire.session.role !== 'admin') wire.abort(403, 'Bukan admin');
20
+ };
21
+
22
+ const instance = await serve({
23
+ port: 0,
24
+ silent: true,
25
+ session: { secret: 'secret-testing-key-32-characters!!' },
26
+ static: {
27
+ '/': tmpDir
28
+ },
29
+ errors: {
30
+ 404({ path: reqPath }) {
31
+ return wire.html`<h1>404 Custom: ${reqPath}</h1>`;
32
+ },
33
+ 401({ message }) {
34
+ return { customUnauthorized: true, reason: message };
35
+ },
36
+ 403: wire.file(forbiddenPage)
37
+ },
38
+ api: {
39
+ assets: serveStatic(path.join(tmpDir, 'assets'), { cacheControl: 'max-age=3600' }),
40
+ 'old-url': redirect('/new-url', 301),
41
+ 'new-url': {
42
+ get: () => ({ arrived: true })
43
+ },
44
+ login: {
45
+ async post({ role }) {
46
+ wire.session.user = 'andi';
47
+ wire.session.role = role;
48
+ wire.redirect('/admin');
49
+ }
50
+ },
51
+ admin: guard(requireAdmin, {
52
+ get: () => ({ secretPanel: true })
53
+ })
54
+ }
55
+ });
56
+
57
+ const base = instance.url;
58
+
59
+ try {
60
+ // 1. Static folder & index.html
61
+ const rootRes = await fetch(`${base}/`);
62
+ assert.equal(rootRes.status, 200);
63
+ assert.equal(await rootRes.text(), '<h1>Home Static</h1>');
64
+
65
+ const jsRes = await fetch(`${base}/assets/app.js`);
66
+ assert.equal(jsRes.status, 200);
67
+ assert.equal(jsRes.headers.get('cache-control'), 'max-age=3600');
68
+ assert.equal(await jsRes.text(), 'console.log("ok");');
69
+
70
+ // 2. Dotfile (.env) otomatis diblokir -> masuk ke custom 404
71
+ const envRes = await fetch(`${base}/.env`);
72
+ assert.equal(envRes.status, 404);
73
+ assert.equal(await envRes.text(), '<h1>404 Custom: /.env</h1>');
74
+
75
+ // 3. Redirect deklaratif 301
76
+ const redirRes = await fetch(`${base}/old-url`, { redirect: 'manual' });
77
+ assert.equal(redirRes.status, 301);
78
+ assert.equal(redirRes.headers.get('location'), '/new-url');
79
+
80
+ // 4. Custom 401 Unauthorized
81
+ const unauthRes = await fetch(`${base}/admin`);
82
+ assert.equal(unauthRes.status, 401);
83
+ assert.deepEqual(await unauthRes.json(), {
84
+ customUnauthorized: true,
85
+ reason: 'Belum login'
86
+ });
87
+
88
+ // 5. wire.redirect() menyimpan cookie session, lalu akses admin sebagai member -> Custom 403 HTML file
89
+ const loginRes = await fetch(`${base}/login`, {
90
+ method: 'POST',
91
+ headers: { 'Content-Type': 'application/json' },
92
+ body: JSON.stringify({ role: 'member' }),
93
+ redirect: 'manual'
94
+ });
95
+ assert.equal(loginRes.status, 302);
96
+ assert.equal(loginRes.headers.get('location'), '/admin');
97
+ const cookie = loginRes.headers.get('set-cookie').split(';')[0];
98
+
99
+ const forbiddenRes = await fetch(`${base}/admin`, {
100
+ headers: { Cookie: cookie }
101
+ });
102
+ assert.equal(forbiddenRes.status, 403);
103
+ assert.equal(await forbiddenRes.text(), '<h1>403 Dilarang Masuk</h1>');
104
+ } finally {
105
+ await instance.close();
106
+ await fs.rm(tmpDir, { recursive: true, force: true });
107
+ }
108
+ });
package/src/session.js ADDED
@@ -0,0 +1,311 @@
1
+ import crypto from 'node:crypto';
2
+ import { parseDuration } from './utils.js';
3
+
4
+ export class MemorySessionStore {
5
+ constructor() {
6
+ this.records = new Map();
7
+ this.userIndex = new Map();
8
+ }
9
+
10
+ async get(sid) {
11
+ const entry = this.records.get(sid);
12
+ if (!entry) return null;
13
+ if (entry.expiresAt && entry.expiresAt <= Date.now()) {
14
+ await this.delete(sid);
15
+ return null;
16
+ }
17
+ return entry;
18
+ }
19
+
20
+ async set(sid, record) {
21
+ const existing = this.records.get(sid);
22
+ if (existing?.userId && existing.userId !== record.userId) {
23
+ this.userIndex.get(existing.userId)?.delete(sid);
24
+ }
25
+ this.records.set(sid, record);
26
+ if (record.userId !== undefined && record.userId !== null) {
27
+ if (!this.userIndex.has(record.userId)) {
28
+ this.userIndex.set(record.userId, new Set());
29
+ }
30
+ this.userIndex.get(record.userId).add(sid);
31
+ }
32
+ }
33
+
34
+ async delete(sid) {
35
+ const existing = this.records.get(sid);
36
+ if (existing?.userId !== undefined && existing?.userId !== null) {
37
+ this.userIndex.get(existing.userId)?.delete(sid);
38
+ }
39
+ this.records.delete(sid);
40
+ }
41
+
42
+ async listByUser(userId) {
43
+ const sids = this.userIndex.get(userId);
44
+ if (!sids) return [];
45
+ const list = [];
46
+ for (const sid of [...sids]) {
47
+ const rec = await this.get(sid);
48
+ if (rec) {
49
+ list.push({
50
+ id: sid.slice(0, 8),
51
+ createdAt: rec.createdAt,
52
+ updatedAt: rec.updatedAt,
53
+ device: rec.data?.device || 'Unknown'
54
+ });
55
+ }
56
+ }
57
+ return list;
58
+ }
59
+
60
+ async revokeOthers(userId, currentSid) {
61
+ const sids = this.userIndex.get(userId);
62
+ if (!sids) return [];
63
+ const revoked = [];
64
+ for (const sid of [...sids]) {
65
+ if (sid !== currentSid) {
66
+ await this.delete(sid);
67
+ revoked.push(sid);
68
+ }
69
+ }
70
+ return revoked;
71
+ }
72
+ }
73
+
74
+ export class SessionManager {
75
+ constructor(config = {}, broker = null) {
76
+ if (!config.secret) {
77
+ throw new Error('session.secret is required when session is enabled');
78
+ }
79
+ this.key = crypto.createHash('sha256').update(String(config.secret)).digest();
80
+ this.cookieName = config.cookieName || 'servin_sid';
81
+ this.ttlMs = parseDuration(config.ttl || '7d', 7 * 86_400_000);
82
+ this.rolling = config.rolling ?? true;
83
+ this.secure = config.secure ?? false;
84
+ this.sameSite = config.sameSite || 'Lax';
85
+ this.store = config.store || new MemorySessionStore();
86
+ this.broker = broker;
87
+ }
88
+
89
+ sealSid(sid) {
90
+ const iv = crypto.randomBytes(12);
91
+ const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
92
+ const enc = Buffer.concat([cipher.update(sid, 'utf8'), cipher.final()]);
93
+ const tag = cipher.getAuthTag();
94
+ return Buffer.concat([iv, tag, enc]).toString('base64url');
95
+ }
96
+
97
+ openSid(token) {
98
+ try {
99
+ const raw = Buffer.from(token, 'base64url');
100
+ if (raw.length < 29) return null;
101
+ const iv = raw.subarray(0, 12);
102
+ const tag = raw.subarray(12, 28);
103
+ const enc = raw.subarray(28);
104
+ const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, iv);
105
+ decipher.setAuthTag(tag);
106
+ return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8');
107
+ } catch {
108
+ return null;
109
+ }
110
+ }
111
+
112
+ parseCookieSid(cookieHeader) {
113
+ if (!cookieHeader) return null;
114
+ const parts = cookieHeader.split(';');
115
+ for (const part of parts) {
116
+ const eq = part.indexOf('=');
117
+ if (eq === -1) continue;
118
+ const k = part.slice(0, eq).trim();
119
+ if (k === this.cookieName) {
120
+ return this.openSid(part.slice(eq + 1).trim());
121
+ }
122
+ }
123
+ return null;
124
+ }
125
+
126
+ buildSetCookie(token, maxAgeSec) {
127
+ const attrs = [
128
+ `${this.cookieName}=${token}`,
129
+ 'Path=/',
130
+ 'HttpOnly',
131
+ `SameSite=${this.sameSite}`,
132
+ `Max-Age=${maxAgeSec}`
133
+ ];
134
+ if (this.secure) attrs.push('Secure');
135
+ return attrs.join('; ');
136
+ }
137
+
138
+ async listByUser(userId) {
139
+ return this.store.listByUser(userId);
140
+ }
141
+
142
+ async revokeOthers(userId, currentSid) {
143
+ const revokedSids = await this.store.revokeOthers(userId, currentSid);
144
+ for (const sid of revokedSids) {
145
+ this.broker?.kickSession(sid);
146
+ }
147
+ return revokedSids.length;
148
+ }
149
+
150
+ createHandle(ctx) {
151
+ const manager = this;
152
+ let loaded = false;
153
+ let dirty = false;
154
+ let destroyed = false;
155
+ let sid = null;
156
+ let data = {};
157
+ let userId = null;
158
+ let createdAt = Date.now();
159
+ let pendingAsync = null;
160
+
161
+ const ensureLoadedSync = () => {
162
+ if (loaded) return;
163
+ loaded = true;
164
+ const cookieHdr = ctx.req?.headers?.get('cookie');
165
+ const parsedSid = manager.parseCookieSid(cookieHdr);
166
+ if (parsedSid) {
167
+ sid = parsedSid;
168
+ if (manager.store instanceof MemorySessionStore) {
169
+ const entry = manager.store.records.get(sid);
170
+ if (entry && (!entry.expiresAt || entry.expiresAt > Date.now())) {
171
+ data = { ...entry.data };
172
+ userId = entry.userId ?? null;
173
+ createdAt = entry.createdAt;
174
+ if (manager.rolling) dirty = true;
175
+ } else {
176
+ sid = null;
177
+ }
178
+ }
179
+ }
180
+ };
181
+
182
+ const assertMutable = () => {
183
+ if (ctx.headersSent) {
184
+ throw new Error('Cannot mutate wire.session after response headers have been sent');
185
+ }
186
+ };
187
+
188
+ const apiMethods = {
189
+ async rotate() {
190
+ assertMutable();
191
+ ensureLoadedSync();
192
+ if (sid) {
193
+ await manager.store.delete(sid);
194
+ manager.broker?.kickSession(sid);
195
+ }
196
+ sid = crypto.randomUUID();
197
+ createdAt = Date.now();
198
+ dirty = true;
199
+ destroyed = false;
200
+ },
201
+ bind(uid) {
202
+ assertMutable();
203
+ ensureLoadedSync();
204
+ if (!sid) sid = crypto.randomUUID();
205
+ userId = uid;
206
+ dirty = true;
207
+ }
208
+ };
209
+
210
+ const proxy = new Proxy({}, {
211
+ get(_, prop) {
212
+ if (prop in apiMethods) return apiMethods[prop];
213
+ if (prop === 'id') {
214
+ ensureLoadedSync();
215
+ return sid;
216
+ }
217
+ ensureLoadedSync();
218
+ return data[prop];
219
+ },
220
+ set(_, prop, value) {
221
+ assertMutable();
222
+ ensureLoadedSync();
223
+ if (!sid) sid = crypto.randomUUID();
224
+ data[prop] = value;
225
+ dirty = true;
226
+ destroyed = false;
227
+ return true;
228
+ },
229
+ deleteProperty(_, prop) {
230
+ assertMutable();
231
+ ensureLoadedSync();
232
+ delete data[prop];
233
+ dirty = true;
234
+ return true;
235
+ },
236
+ ownKeys() {
237
+ ensureLoadedSync();
238
+ return Reflect.ownKeys(data);
239
+ },
240
+ getOwnPropertyDescriptor(_, prop) {
241
+ ensureLoadedSync();
242
+ return Object.getOwnPropertyDescriptor(data, prop);
243
+ }
244
+ });
245
+
246
+ return {
247
+ proxy,
248
+ get sid() {
249
+ ensureLoadedSync();
250
+ return sid;
251
+ },
252
+ destroy() {
253
+ assertMutable();
254
+ ensureLoadedSync();
255
+ destroyed = true;
256
+ dirty = true;
257
+ data = {};
258
+ userId = null;
259
+ if (sid) {
260
+ const oldSid = sid;
261
+ sid = null;
262
+ pendingAsync = manager.store.delete(oldSid);
263
+ manager.broker?.kickSession(oldSid);
264
+ }
265
+ },
266
+ replace(newObj) {
267
+ assertMutable();
268
+ ensureLoadedSync();
269
+ if (!sid) sid = crypto.randomUUID();
270
+ data = { ...newObj };
271
+ dirty = true;
272
+ destroyed = false;
273
+ },
274
+ async preload() {
275
+ if (loaded) return;
276
+ loaded = true;
277
+ const cookieHdr = ctx.req?.headers?.get('cookie');
278
+ const parsedSid = manager.parseCookieSid(cookieHdr);
279
+ if (parsedSid) {
280
+ const entry = await manager.store.get(parsedSid);
281
+ if (entry) {
282
+ sid = parsedSid;
283
+ data = { ...entry.data };
284
+ userId = entry.userId ?? null;
285
+ createdAt = entry.createdAt;
286
+ if (manager.rolling) dirty = true;
287
+ }
288
+ }
289
+ },
290
+ async commit(headers) {
291
+ if (pendingAsync) await pendingAsync;
292
+ if (!dirty) return;
293
+ if (destroyed) {
294
+ headers.append('Set-Cookie', manager.buildSetCookie('', 0));
295
+ return;
296
+ }
297
+ if (!sid) sid = crypto.randomUUID();
298
+ const now = Date.now();
299
+ await manager.store.set(sid, {
300
+ userId,
301
+ data,
302
+ createdAt,
303
+ updatedAt: now,
304
+ expiresAt: now + manager.ttlMs
305
+ });
306
+ const sealed = manager.sealSid(sid);
307
+ headers.append('Set-Cookie', manager.buildSetCookie(sealed, Math.floor(manager.ttlMs / 1000)));
308
+ }
309
+ };
310
+ }
311
+ }