@dim24/servin 0.0.1 → 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.
@@ -1,290 +1,106 @@
1
1
  import test from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
- import crypto from 'node:crypto';
4
3
  import fs from 'node:fs/promises';
5
4
  import os from 'node:os';
6
5
  import path from 'node:path';
7
- import { serve, wire, guard, reactTo } from '../index.js';
8
-
9
- test('Suite lengkap seluruh kapabilitas servin', async (t) => {
10
- const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'servin-test-'));
11
- const sampleHtmlPath = path.join(tmpDir, 'page.html');
12
- await fs.writeFile(sampleHtmlPath, '<h1>Static HTML File</h1>', 'utf8');
13
-
14
- let dbFetchCount = 0;
15
- let coalFetchCount = 0;
16
- let reactionTriggeredCount = 0;
17
- const itemsDb = new Map([
18
- ['1', { id: '1', title: 'Belajar Servin', status: 'draft', secretToken: 'hidden_xyz' }]
19
- ]);
20
-
21
- const requireAuth = () => {
22
- if (!wire.session.userId) wire.abort(401, 'Unauthorized');
23
- };
24
-
25
- const items = {
26
- // GET /items & POST /items
27
- cache: '5m',
28
- get() {
29
- dbFetchCount++;
30
- return [...itemsDb.values()];
31
- },
32
- expect: { title: 'string', status: ['draft', 'published'] },
33
- async post(payload) {
34
- const id = String(itemsDb.size + 1);
35
- const record = { id, ...payload, secretToken: 'secret_999' };
36
- itemsDb.set(id, record);
37
- wire.undo(() => itemsDb.delete(id));
38
- wire.status(201);
39
- return record;
40
- },
41
-
42
- // /items/:id -> GET, PATCH, DELETE
43
- $id: {
44
- cache: '5m',
45
- get(id) {
46
- dbFetchCount++;
47
- const item = itemsDb.get(id);
48
- if (!item) wire.abort(404, 'Item not found');
49
- return item;
50
- },
51
- patch(id, payload) {
52
- const item = itemsDb.get(id);
53
- if (!item) wire.abort(404, 'Item not found');
54
- Object.assign(item, payload);
55
- return item;
56
- },
57
- delete(id) {
58
- if (!itemsDb.has(id)) wire.abort(404, 'Item not found');
59
- itemsDb.delete(id);
60
- wire.status(204);
61
- return null;
62
- }
63
- }
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');
64
20
  };
65
21
 
66
- reactTo(items.post, () => {
67
- reactionTriggeredCount++;
68
- });
69
-
70
22
  const instance = await serve({
71
23
  port: 0,
72
24
  silent: true,
73
- redact: ['secret*'],
74
- session: { secret: 'test-secret-key-32-chars-minimum!!' },
75
- api: {
76
- // 1. HTML string & XSS-safe template
77
- home: {
78
- get: () => wire.html`<div>Hello, ${'<script>alert(1)</script>'}</div>`
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>`;
79
32
  },
80
- // 2. File streaming
81
- staticPage: {
82
- get: () => wire.file(sampleHtmlPath)
33
+ 401({ message }) {
34
+ return { customUnauthorized: true, reason: message };
83
35
  },
84
- // 3. Request coalescing
85
- heavy: {
86
- coalesce: true,
87
- async get() {
88
- coalFetchCount++;
89
- await new Promise((r) => setTimeout(r, 40));
90
- return { computed: true };
91
- }
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 })
92
43
  },
93
- // 4. CRUD Items
94
- items,
95
- // 5. Auth & Session
96
- auth: {
97
- login: {
98
- async post({ userId }) {
99
- await wire.session.rotate();
100
- wire.session.bind(userId);
101
- wire.session.userId = userId;
102
- return { loggedIn: true };
103
- }
104
- },
105
- logout: {
106
- post() {
107
- wire.session = null;
108
- return { loggedOut: true };
109
- }
44
+ login: {
45
+ async post({ role }) {
46
+ wire.session.user = 'andi';
47
+ wire.session.role = role;
48
+ wire.redirect('/admin');
110
49
  }
111
50
  },
112
- // 6. Protected WebSocket
113
- chat: guard(requireAuth, {
114
- $room: {
115
- async ws(room, socket) {
116
- socket.join(`room:${room}`);
117
- socket.send({ event: 'connected', room, user: wire.session.userId });
118
- for await (const msg of socket) {
119
- wire.publish(`room:${room}`, { from: wire.session.userId, text: msg.text });
120
- }
121
- }
122
- }
123
- }),
124
- // 7. Multipart upload
125
- upload: {
126
- async post() {
127
- const fields = {};
128
- const files = [];
129
- for await (const part of wire.multipart()) {
130
- if (part.isField) fields[part.name] = await part.text();
131
- if (part.isFile) files.push({ name: part.filename, content: await part.text() });
132
- }
133
- return { fields, files };
134
- }
135
- }
51
+ admin: guard(requireAdmin, {
52
+ get: () => ({ secretPanel: true })
53
+ })
136
54
  }
137
55
  });
138
56
 
139
57
  const base = instance.url;
140
58
 
141
59
  try {
142
- await t.test('1. HTML response dengan auto-escape XSS & File streaming', async () => {
143
- const resHtml = await fetch(`${base}/home`);
144
- assert.equal(resHtml.status, 200);
145
- assert.ok(resHtml.headers.get('content-type').includes('text/html'));
146
- const html = await resHtml.text();
147
- assert.equal(html, '<div>Hello, <script>alert(1)</script></div>');
148
-
149
- const resFile = await fetch(`${base}/staticPage`);
150
- assert.equal(resFile.status, 200);
151
- assert.equal(await resFile.text(), '<h1>Static HTML File</h1>');
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'
152
86
  });
153
87
 
154
- await t.test('2. Self-invalidating cache otomatis bersih saat PATCH dipanggil & redaction bekerja', async () => {
155
- dbFetchCount = 0;
156
-
157
- // Hit pertama: baca dari DB
158
- const r1 = await fetch(`${base}/items/1`);
159
- const d1 = await r1.json();
160
- assert.equal(d1.status, 'draft');
161
- assert.equal(d1.secretToken, undefined); // Terhapus otomatis oleh redact
162
- assert.equal(dbFetchCount, 1);
163
-
164
- // Hit kedua: ambil dari cache (dbFetchCount tetap 1)
165
- const r2 = await fetch(`${base}/items/1`);
166
- assert.equal((await r2.json()).status, 'draft');
167
- assert.equal(dbFetchCount, 1);
168
-
169
- // Mutasi PATCH -> otomatis menghapus cache GET /items/1
170
- const patchRes = await fetch(`${base}/items/1`, {
171
- method: 'PATCH',
172
- headers: { 'Content-Type': 'application/json' },
173
- body: JSON.stringify({ status: 'published' })
174
- });
175
- assert.equal(patchRes.status, 200);
176
-
177
- // Hit ketiga: cache sudah bersih, wajib membaca data terbaru dari DB
178
- const r3 = await fetch(`${base}/items/1`);
179
- assert.equal((await r3.json()).status, 'published');
180
- assert.equal(dbFetchCount, 2);
181
- });
182
-
183
- await t.test('3. Request coalescing menggabungkan 20 request paralel menjadi 1 eksekusi', async () => {
184
- coalFetchCount = 0;
185
- const responses = await Promise.all(
186
- Array.from({ length: 20 }, () => fetch(`${base}/heavy`).then((r) => r.json()))
187
- );
188
- assert.equal(responses.length, 20);
189
- assert.equal(coalFetchCount, 1);
190
- });
191
-
192
- await t.test('4. Validasi expect (422), X-Simulate dry-run, dan reactTo', async () => {
193
- // Validasi gagal -> 422
194
- const badRes = await fetch(`${base}/items`, {
195
- method: 'POST',
196
- headers: { 'Content-Type': 'application/json' },
197
- body: JSON.stringify({ title: 12345, status: 'invalid' })
198
- });
199
- assert.equal(badRes.status, 422);
200
-
201
- // Simulasi X-Simulate: true -> mengembalikan 201 tapi DB tidak bertambah
202
- const simRes = await fetch(`${base}/items`, {
203
- method: 'POST',
204
- headers: { 'Content-Type': 'application/json', 'X-Simulate': 'true' },
205
- body: JSON.stringify({ title: 'Simulasi Saja', status: 'draft' })
206
- });
207
- assert.equal(simRes.status, 201);
208
- assert.equal(itemsDb.size, 1);
209
- assert.equal(reactionTriggeredCount, 0);
210
-
211
- // Eksekusi nyata -> masuk DB & memicu reactTo
212
- const realRes = await fetch(`${base}/items`, {
213
- method: 'POST',
214
- headers: { 'Content-Type': 'application/json' },
215
- body: JSON.stringify({ title: 'Item Nyata', status: 'published' })
216
- });
217
- assert.equal(realRes.status, 201);
218
- assert.equal(itemsDb.size, 2);
219
- assert.equal(reactionTriggeredCount, 1);
220
- });
221
-
222
- await t.test('5. Multipart streaming multi-field dan multi-file', async () => {
223
- const form = new FormData();
224
- form.append('album', 'Liburan');
225
- form.append('note', 'Catatan penting');
226
- form.append('doc1', new Blob(['Isi file pertama'], { type: 'text/plain' }), 'satu.txt');
227
- form.append('doc2', new Blob(['Isi file kedua'], { type: 'text/plain' }), 'dua.txt');
228
-
229
- const res = await fetch(`${base}/upload`, { method: 'POST', body: form });
230
- assert.equal(res.status, 200);
231
- const body = await res.json();
232
- assert.deepEqual(body.fields, { album: 'Liburan', note: 'Catatan penting' });
233
- assert.equal(body.files.length, 2);
234
- assert.equal(body.files[0].content, 'Isi file pertama');
235
- assert.equal(body.files[1].content, 'Isi file kedua');
236
- });
237
-
238
- await t.test('6. Session Auth, WebSocket Linear Stream & Auto-Kick saat Logout', async () => {
239
- // Tanpa login -> ditolak 401 sebelum upgrade
240
- const unauthWs = await fetch(`${base}/chat/lobby`, {
241
- headers: {
242
- Upgrade: 'websocket',
243
- Connection: 'Upgrade',
244
- 'Sec-WebSocket-Key': crypto.randomBytes(16).toString('base64'),
245
- 'Sec-WebSocket-Version': '13'
246
- }
247
- });
248
- assert.equal(unauthWs.status, 401);
249
-
250
- // Login -> ambil cookie session
251
- const loginRes = await fetch(`${base}/auth/login`, {
252
- method: 'POST',
253
- headers: { 'Content-Type': 'application/json' },
254
- body: JSON.stringify({ userId: 'user-77' })
255
- });
256
- assert.equal(loginRes.status, 200);
257
- const cookie = loginRes.headers.get('set-cookie').split(';')[0];
258
-
259
- // Buka koneksi WebSocket menggunakan cookie session
260
- const wsUrl = base.replace('http://', 'ws://') + '/chat/lobby';
261
- const ws = new WebSocket(wsUrl, { headers: { Cookie: cookie } });
262
-
263
- const firstMsg = await new Promise((resolve, reject) => {
264
- ws.onmessage = (ev) => resolve(JSON.parse(ev.data));
265
- ws.onerror = reject;
266
- });
267
- assert.deepEqual(firstMsg, { event: 'connected', room: 'lobby', user: 'user-77' });
268
-
269
- // Logout lewat HTTP -> otomatis memutus koneksi WebSocket aktif dengan kode 4001
270
- const closePromise = new Promise((resolve) => {
271
- ws.onclose = (ev) => resolve(ev.code);
272
- });
273
-
274
- const logoutRes = await fetch(`${base}/auth/logout`, {
275
- method: 'POST',
276
- headers: { Cookie: cookie }
277
- });
278
- assert.equal(logoutRes.status, 200);
279
- assert.equal(await closePromise, 4001);
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'
280
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];
281
98
 
282
- await t.test('7. Virtual ESM Client (/@client.js) tersedia', async () => {
283
- const clientRes = await fetch(`${base}/@client.js`);
284
- assert.equal(clientRes.status, 200);
285
- const code = await clientRes.text();
286
- assert.ok(code.includes('export const api = createNode([])'));
99
+ const forbiddenRes = await fetch(`${base}/admin`, {
100
+ headers: { Cookie: cookie }
287
101
  });
102
+ assert.equal(forbiddenRes.status, 403);
103
+ assert.equal(await forbiddenRes.text(), '<h1>403 Dilarang Masuk</h1>');
288
104
  } finally {
289
105
  await instance.close();
290
106
  await fs.rm(tmpDir, { recursive: true, force: true });