-
Notifications
You must be signed in to change notification settings - Fork 866
Expand file tree
/
Copy pathplugin.test.js
More file actions
260 lines (219 loc) · 10.2 KB
/
Copy pathplugin.test.js
File metadata and controls
260 lines (219 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { jest } from '@jest/globals';
import { createPluginEvents } from '../../lib/plugins.js';
import { register } from './index.js';
describe('persistence plugin', () => {
let tmpDir, events, ctx, mockApp;
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'camofox-persist-plugin-'));
events = createPluginEvents();
mockApp = { delete: jest.fn() };
ctx = {
events,
config: { cookiesDir: path.join(tmpDir, 'cookies') },
log: jest.fn(),
auth: () => (req, res, next) => next(),
normalizeUserId: (u) => String(u),
safeError: (err) => err.message,
destroySession: jest.fn(async (userId, { reason } = {}) => {
await events.emitAsync('session:destroying', { userId: String(userId), reason });
await events.emitAsync('session:destroyed', { userId: String(userId), reason });
return true;
}),
};
});
afterEach(async () => {
if (tmpDir) await fs.rm(tmpDir, { recursive: true, force: true });
});
test('skips registration when no profileDir configured', async () => {
await register(mockApp, ctx, {});
expect(ctx.log).toHaveBeenCalledWith('warn', expect.stringContaining('no profileDir'));
});
test('restores persisted state on session:creating', async () => {
await register(mockApp, ctx, { profileDir: tmpDir });
// Simulate a prior persisted state
const { getUserPersistencePaths } = await import('../../lib/persistence.js');
const { userDir, storageStatePath } = getUserPersistencePaths(tmpDir, 'user-1');
await fs.mkdir(userDir, { recursive: true });
await fs.writeFile(storageStatePath, JSON.stringify({
cookies: [{ name: 'sid', value: 'abc', domain: '.example.com', path: '/' }],
origins: [],
}));
const contextOptions = { viewport: { width: 1280, height: 720 } };
await events.emitAsync('session:creating', { userId: 'user-1', contextOptions });
expect(contextOptions.storageState).toBe(storageStatePath);
});
test('checkpoints on session:cookies:import', async () => {
await register(mockApp, ctx, { profileDir: tmpDir });
const mockContext = {
storageState: jest.fn(async ({ path: p }) => {
await fs.writeFile(p, JSON.stringify({ cookies: [{ name: 'x', value: 'y', domain: '.test.com', path: '/' }] }));
}),
};
// Simulate session created then cookie import
await events.emitAsync('session:created', { userId: 'user-2', context: mockContext });
await events.emitAsync('session:cookies:import', { userId: 'user-2' });
expect(mockContext.storageState).toHaveBeenCalled();
// Verify file was written
const { getUserPersistencePaths } = await import('../../lib/persistence.js');
const { storageStatePath } = getUserPersistencePaths(tmpDir, 'user-2');
const saved = JSON.parse(await fs.readFile(storageStatePath, 'utf8'));
expect(saved.cookies[0].name).toBe('x');
});
test('persists the exact state supplied by session:storage:export', async () => {
await register(mockApp, ctx, { profileDir: tmpDir, indexedDB: true });
const storageState = {
cookies: [],
origins: [{
origin: 'https://example.test',
localStorage: [],
indexedDB: [{ name: 'auth', version: 1, stores: [] }],
}],
};
await events.emitAsync('session:storage:export', { userId: 'user-export', storageState });
const { getUserPersistencePaths } = await import('../../lib/persistence.js');
const { storageStatePath } = getUserPersistencePaths(tmpDir, 'user-export');
expect(JSON.parse(await fs.readFile(storageStatePath, 'utf8'))).toEqual(storageState);
});
test('checkpoints on session:destroying', async () => {
await register(mockApp, ctx, { profileDir: tmpDir });
const mockContext = {
storageState: jest.fn(async ({ path: p }) => {
await fs.writeFile(p, JSON.stringify({ cookies: [], origins: [] }));
}),
};
await events.emitAsync('session:created', { userId: 'user-3', context: mockContext });
await events.emitAsync('session:destroying', { userId: 'user-3', reason: 'test' });
expect(mockContext.storageState).toHaveBeenCalled();
});
test('DELETE storage_state destroys the live session without checkpointing and removes persisted state', async () => {
await register(mockApp, ctx, { profileDir: tmpDir });
const call = mockApp.delete.mock.calls.find(c => c[0] === '/sessions/:userId/storage_state');
expect(call).toBeTruthy();
const handler = call.at(-1);
const { getUserPersistencePaths } = await import('../../lib/persistence.js');
const { userDir, storageStatePath, metaPath } = getUserPersistencePaths(tmpDir, 'user-4');
await fs.mkdir(userDir, { recursive: true });
await fs.writeFile(storageStatePath, JSON.stringify({
cookies: [{ name: 'sid', value: 'a', domain: '.x.com', path: '/' }],
origins: [{
origin: 'https://x.com',
localStorage: [{ name: 'token', value: 'secret' }],
indexedDB: [{ name: 'auth', version: 1, stores: [] }],
}],
}));
await fs.writeFile(metaPath, JSON.stringify({ userId: 'user-4' }));
const mockContext = { storageState: jest.fn() };
await events.emitAsync('session:created', { userId: 'user-4', context: mockContext });
const res = { json: jest.fn(), status: jest.fn(function () { return this; }) };
await handler({ params: { userId: 'user-4' } }, res);
expect(ctx.destroySession).toHaveBeenCalledWith('user-4', { reason: 'storage_reset' });
expect(mockContext.storageState).not.toHaveBeenCalled();
await expect(fs.access(storageStatePath)).rejects.toMatchObject({ code: 'ENOENT' });
await expect(fs.access(metaPath)).rejects.toMatchObject({ code: 'ENOENT' });
expect(res.json).toHaveBeenCalledWith({
ok: true,
userId: 'user-4',
clearedLive: true,
removedPersisted: true,
});
});
test('DELETE storage_state waits for an in-flight checkpoint before deleting', async () => {
await register(mockApp, ctx, { profileDir: tmpDir });
const handler = mockApp.delete.mock.calls
.find(c => c[0] === '/sessions/:userId/storage_state')
.at(-1);
let finishCheckpoint;
let markCheckpointStarted;
const checkpointBlocked = new Promise(resolve => { finishCheckpoint = resolve; });
const checkpointStarted = new Promise(resolve => { markCheckpointStarted = resolve; });
const mockContext = {
storageState: jest.fn(async ({ path: targetPath }) => {
markCheckpointStarted();
await checkpointBlocked;
await fs.writeFile(targetPath, JSON.stringify({ cookies: [], origins: [] }));
}),
};
await events.emitAsync('session:created', { userId: 'user-race', context: mockContext });
const checkpoint = events.emitAsync('session:cookies:import', { userId: 'user-race' });
await checkpointStarted;
const res = { json: jest.fn(), status: jest.fn(function () { return this; }) };
const reset = handler({ params: { userId: 'user-race' } }, res);
await Promise.resolve();
expect(res.json).not.toHaveBeenCalled();
finishCheckpoint();
await Promise.all([checkpoint, reset]);
const { getUserPersistencePaths } = await import('../../lib/persistence.js');
const { storageStatePath } = getUserPersistencePaths(tmpDir, 'user-race');
await expect(fs.access(storageStatePath)).rejects.toMatchObject({ code: 'ENOENT' });
});
test('DELETE storage_state is idempotent without a live session or persisted file', async () => {
ctx.destroySession.mockResolvedValueOnce(false);
await register(mockApp, ctx, { profileDir: tmpDir });
const call = mockApp.delete.mock.calls.find(c => c[0] === '/sessions/:userId/storage_state');
const handler = call.at(-1);
const res = { json: jest.fn(), status: jest.fn(function () { return this; }) };
await handler({ params: { userId: 'nobody' } }, res);
expect(res.json).toHaveBeenCalledWith({
ok: true,
userId: 'nobody',
clearedLive: false,
removedPersisted: false,
});
});
test('env var CAMOFOX_PROFILE_DIR overrides pluginConfig', async () => {
const envDir = path.join(tmpDir, 'env-override');
const orig = process.env.CAMOFOX_PROFILE_DIR;
process.env.CAMOFOX_PROFILE_DIR = envDir;
try {
await register(mockApp, ctx, { profileDir: '/should/not/use' });
expect(ctx.log).toHaveBeenCalledWith(
'info',
'persistence plugin enabled',
expect.objectContaining({ profileDir: envDir })
);
} finally {
if (orig === undefined) delete process.env.CAMOFOX_PROFILE_DIR;
else process.env.CAMOFOX_PROFILE_DIR = orig;
}
});
test('does not persist IndexedDB by default', async () => {
await register(mockApp, ctx, { profileDir: tmpDir });
const mockContext = {
storageState: jest.fn(async ({ path: p }) => {
await fs.writeFile(p, JSON.stringify({ cookies: [], origins: [] }));
}),
};
await events.emitAsync('session:created', { userId: 'user-no-idb', context: mockContext });
await events.emitAsync('session:destroying', { userId: 'user-no-idb', reason: 'test' });
expect(ctx.log).toHaveBeenCalledWith(
'info',
'persistence plugin enabled',
expect.objectContaining({ indexedDB: false })
);
expect(mockContext.storageState).toHaveBeenCalled();
for (const [arg] of mockContext.storageState.mock.calls) {
expect(arg.indexedDB).toBeUndefined();
}
});
test('indexedDB: true opts in to IndexedDB persistence', async () => {
await register(mockApp, ctx, { profileDir: tmpDir, indexedDB: true });
const mockContext = {
storageState: jest.fn(async ({ path: p }) => {
await fs.writeFile(p, JSON.stringify({ cookies: [], origins: [] }));
}),
};
await events.emitAsync('session:created', { userId: 'user-idb', context: mockContext });
await events.emitAsync('session:destroying', { userId: 'user-idb', reason: 'test' });
expect(ctx.log).toHaveBeenCalledWith(
'info',
'persistence plugin enabled',
expect.objectContaining({ indexedDB: true })
);
expect(mockContext.storageState).toHaveBeenCalledWith(
expect.objectContaining({ indexedDB: true })
);
});
});