@dim24/servin 0.0.0-stage → 0.0.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.
- package/LICENSE +21 -0
- package/README.md +1655 -3
- package/example/index.js +43 -0
- package/example/router.js +11 -0
- package/index.js +3 -0
- package/package.json +38 -4
- package/src/server.js +793 -0
- package/src/servin.test.js +292 -0
- package/src/session.js +311 -0
- package/src/tree.js +504 -0
- package/src/utils.js +436 -0
- package/src/websocket.js +311 -0
- package/src/wire.js +254 -0
- package/test.js +45 -0
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import fs from 'node:fs/promises';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
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
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
reactTo(items.post, () => {
|
|
67
|
+
reactionTriggeredCount++;
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const instance = await serve({
|
|
71
|
+
port: 0,
|
|
72
|
+
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>`
|
|
79
|
+
},
|
|
80
|
+
// 2. File streaming
|
|
81
|
+
staticPage: {
|
|
82
|
+
get: () => wire.file(sampleHtmlPath)
|
|
83
|
+
},
|
|
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
|
+
}
|
|
92
|
+
},
|
|
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
|
+
}
|
|
110
|
+
}
|
|
111
|
+
},
|
|
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
|
+
}
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
const base = instance.url;
|
|
140
|
+
|
|
141
|
+
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>');
|
|
152
|
+
});
|
|
153
|
+
|
|
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);
|
|
280
|
+
});
|
|
281
|
+
|
|
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([])'));
|
|
287
|
+
});
|
|
288
|
+
} finally {
|
|
289
|
+
await instance.close();
|
|
290
|
+
await fs.rm(tmpDir, { recursive: true, force: true });
|
|
291
|
+
}
|
|
292
|
+
});
|
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
|
+
}
|