Repository navigation
Expand file tree
/
Copy pathplugin-manager.test.ts
More file actions
885 lines (883 loc) · 30 KB
/
Copy pathplugin-manager.test.ts
File metadata and controls
885 lines (883 loc) · 30 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
import { afterEach, expect, it, vi } from "vitest";
import { mkdtemp, rm, writeFile, readFile, mkdir } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, dirname } from "node:path";
import { createServer } from "node:http";
import { zipSync, strToU8 } from "fflate";
import { openTestDatabase, testTableColumns } from "./database.js";
import { PluginManager } from "@server/plugins/manager.js";
import { PluginStore } from "@server/plugins/store.js";
import { digest, unpack, archiveFileIndex } from "@server/plugins/archive.js";
import { createApp } from "@server/app/create-app.js";
import { createUser } from "@core/modules/identity/passwords.js";
import type { DB } from "@db/index.js";
import { storageRuntime } from "@server/adapters/storage.js";
import { createHostFileStore } from "@server/services/host-file-store.js";
import { configuredFileStore } from "@server/services/file-store-config.js";
import { bindPluginStorage } from "@server/services/plugin-storage.js";
import {
checkOperation,
pluginServices,
} from "@core/shared/plugin-services.js";
import { systemErrorReason } from "@core/shared/errors.js";
const dirs: string[] = [],
dbs: DB[] = [];
afterEach(async () => {
await Promise.all(dbs.splice(0).map((db) => db.destroy()));
await Promise.all(
dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })),
);
});
async function directory() {
const dir = await mkdtemp(join(tmpdir(), "doca-plugin-manager-"));
dirs.push(dir);
return dir;
}
async function database() {
const db = await openTestDatabase({ driver: "sqlite", path: ":memory:" });
dbs.push(db);
return db;
}
function bundle(
version = "1.0.0",
dataVersion = "1",
id = "example.demo",
dependencies: any[] = [],
uninstall = "async uninstall() {}",
sdkRange = "^0.2.0",
) {
const manifest = {
schemaVersion: 1,
id,
version,
displayName: "Demo",
sdkRange,
dependencies,
};
return zipSync(
{
"package.json": strToU8(
JSON.stringify({
name: `@example/${id}`,
version,
type: "module",
doca: {
dataVersion,
storage: "host",
manifest: "./manifest.json",
server: "./server.js",
web: { directory: "./web", entry: "./index.js" },
},
}).replace(`@example/${id}`, id),
),
"manifest.json": strToU8(JSON.stringify(manifest)),
"server.js": strToU8(
`export default () => ({ manifest: ${JSON.stringify(manifest)}${uninstall ? `, ${uninstall}` : ""} });`,
),
"web/index.js": strToU8(
`export default () => ({manifest: { pluginId: '${id}', version: '${version}', targets:['web']}});`,
),
"web/chunk.js": strToU8("export const value = 42;"),
},
{ mtime: new Date("2020-01-01T00:00:00Z") },
);
}
async function dropPlugin(root: string, bytes: Uint8Array) {
const files = unpack(bytes);
const manifest = JSON.parse(Buffer.from(files["manifest.json"]!).toString());
for (const [name, data] of Object.entries(files)) {
const file = join(root, manifest.id, name);
await mkdir(dirname(file), { recursive: true });
await writeFile(file, data);
}
}
it("starts core and management with old SDK plugins isolated, then upgrades one without deleting data", async () => {
const db = await database(),
root = await directory();
const old = "example.old",
other = "example.other",
consumer = "example.consumer";
for (const id of [old, other])
await dropPlugin(
root,
bundle(
"1.0.0",
"1",
id,
[],
"async uninstall() { throw Error('old code must not run') }",
"^0.1.9",
),
);
await dropPlugin(
root,
bundle("1.0.0", "1", consumer, [{ id: old, range: "^1.0.0" }]),
);
await dropPlugin(root, bundle("1.0.0", "1", "example.healthy"));
const manager = new PluginManager(root, [], db);
expect((await manager.prepare()).map((p) => p.manifest.id)).toEqual([
"example.healthy",
]);
await manager.confirm();
const storage = await bindPluginStorage(db, manager.archiveStore, old, "1");
await storage.database.defineSchema({
version: 1,
tables: {
retained: {
columns: {
id: { type: "text", nullable: false },
value: { type: "text", nullable: false },
},
primaryKey: ["id"],
unique: [],
},
},
});
await storage.database.insert("retained", [
{ id: "original", value: "keep me" },
]);
const saved = await db.selectFrom("plugin_registry").selectAll().execute();
const namespace = await db
.selectFrom("plugin_storage_namespaces")
.selectAll()
.where("plugin_id", "=", old)
.execute();
const origin = "http://127.0.0.1:39130",
headers = { host: "127.0.0.1:39130", origin };
const app = await createApp(db, { origin, pluginDirectory: root });
try {
expect((await app.inject({ url: "/health", headers })).statusCode).toBe(
200,
);
const bootstrap = (
await app.inject({ url: "/api/v1/bootstrap", headers })
).json();
expect(bootstrap.plugins.map((p: any) => p.id)).toContain(
"example.healthy",
);
expect(bootstrap.plugins.map((p: any) => p.id)).not.toContain(old);
expect(bootstrap.plugins.map((p: any) => p.id)).not.toContain(consumer);
expect(
(
await app.inject({
url: `/api/v1/plugin-assets/${old}/1.0.0/index.js`,
headers,
})
).statusCode,
).toBe(404);
expect(
(await app.inject({ url: "/api/v1/admin/plugins", headers })).statusCode,
).toBe(401);
await createUser(
db,
{
login: "isolated-admin",
displayName: "Isolated admin",
password: "isolated-password-2026",
},
{ bootstrap: true },
);
const login = await app.inject({
method: "POST",
url: "/api/v1/auth/login",
headers,
payload: { login: "isolated-admin", password: "isolated-password-2026" },
});
expect(login.statusCode, login.body).toBe(200);
const cookie = String(login.headers["set-cookie"]).split(";")[0]!;
const guarded = await app.inject({
method: "POST",
url: "/api/v1/resources",
headers: { ...headers, cookie },
payload: {
kind: "document",
format: "markdown",
title: "Must remain blocked",
},
});
expect(guarded.statusCode, guarded.body).toBe(503);
expect(guarded.body).toContain("plugin_policies_unavailable");
const missingSource = await app.inject({
method: "POST",
url: "/api/v1/content/list",
headers: { ...headers, cookie },
payload: {
sourceId: `${old}.content`,
purpose: "analysis",
config: {},
cursor: null,
limit: 10,
},
});
expect(missingSource.statusCode, missingSource.body).toBe(404);
const inventory = (
await app.inject({
url: "/api/v1/admin/plugins",
headers: { ...headers, cookie },
})
).json();
expect([...pluginServices(db).unavailablePlugins].sort()).toEqual(
[consumer, old, other].sort(),
);
const blocked = await checkOperation(
db,
"any-principal",
"resources.create",
).catch((error) => error);
expect(blocked.status).toBe(503);
expect(systemErrorReason(blocked)?.code).toBe(
"plugin_policies_unavailable",
);
expect(pluginServices(db).permissions.has(`${old}.resource`)).toBe(false);
expect(inventory.restartRequired).toBe(false);
expect(inventory.plugins.find((p: any) => p.id === old)).toMatchObject({
enabled: true,
runningVersion: null,
pending: false,
startupIssue: { code: "sdk_incompatible", sdkRange: "^0.1.9" },
});
expect(
await db.selectFrom("plugin_registry").selectAll().execute(),
).toEqual(saved);
} finally {
await app.close();
}
expect(pluginServices(db).unavailablePlugins.size).toBe(0);
await expect(
manager.install(
bundle("1.1.0", "1", old, [], "async uninstall() {}", "^0.1.9"),
"local",
),
).rejects.toThrow(/SDK/);
await expect(manager.change(old, "remove")).rejects.toThrow(/SDK/);
expect(await db.selectFrom("plugin_registry").selectAll().execute()).toEqual(
saved,
);
await manager.install(bundle("1.1.0", "1", old), "local");
expect(
(await manager.inventory()).plugins.find((p) => p.id === old),
).toMatchObject({ version: "1.1.0", pending: true, runningVersion: null, canCancel: false });
await expect(manager.change(old, "cancel")).rejects.toThrow(/SDK/);
const restart = new PluginManager(await directory(), [], db);
expect((await restart.prepare()).map((p) => p.manifest.id).sort()).toEqual(
[consumer, "example.healthy", old].sort(),
);
await restart.confirm();
expect(
(await restart.inventory()).plugins.find((p) => p.id === old),
).toMatchObject({
runningVersion: "1.1.0",
pending: false,
startupIssue: null,
});
expect(
(await restart.inventory()).plugins.find((p) => p.id === other)
?.startupIssue?.code,
).toBe("sdk_incompatible");
expect(
await db
.selectFrom("plugin_storage_namespaces")
.selectAll()
.where("plugin_id", "=", old)
.execute(),
).toEqual(namespace);
const restored = await bindPluginStorage(db, restart.archiveStore, old, "1");
expect(await restored.database.select("retained")).toEqual([
{ id: "original", value: "keep me" },
]);
// An explicit disable takes effect after restart and lifts the conservative write guard.
await restart.change(other, "disable");
const recovered = await createApp(db, {
origin,
pluginDirectory: await directory(),
});
try {
expect(pluginServices(db).unavailablePlugins.size).toBe(0);
await expect(
checkOperation(db, "any-principal", "resources.create"),
).resolves.toBeUndefined();
} finally {
await recovered.close();
}
});
it("installs and restores S3 plugin archives with frozen deployment credentials through the real SDK", async () => {
const objects = new Map<string, Buffer>();
const requests: {
method: string;
path: string;
authorization: string;
sessionToken: string;
ifNoneMatch?: string;
}[] = [];
const server = createServer(async (request, response) => {
const path = request.url!.split("?")[0]!;
requests.push({
method: request.method!,
path,
authorization: request.headers.authorization ?? "",
sessionToken: String(request.headers["x-amz-security-token"] ?? ""),
ifNoneMatch: request.headers["if-none-match"],
});
if (request.method === "PUT") {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(Buffer.from(chunk));
if (objects.has(path)) response.statusCode = 412;
else objects.set(path, Buffer.concat(chunks));
response.end();
} else if (request.method === "GET" && objects.has(path)) {
const bytes = objects.get(path)!;
response.setHeader("Content-Length", bytes.length);
response.end(bytes);
} else {
response.statusCode = 404;
response.end();
}
});
try {
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (!address || typeof address === "string")
throw new Error("Missing test endpoint port");
const runtime = storageRuntime({
DOCA_FILE_STORE_ID: "cloud",
DOCA_FILE_STORES_JSON: JSON.stringify({
version: 1,
stores: {
cloud: {
provider: "s3",
bucket: "doca-test",
region: "us-east-1",
endpoint: `http://127.0.0.1:${address.port}`,
forcePathStyle: true,
credentials: {
accessKeyId: "isolated-test-access",
secretAccessKey: "isolated-test-secret",
sessionToken: "isolated-test-session",
},
},
},
}),
});
const config = configuredFileStore(runtime.configuration, "cloud");
if (config.provider !== "s3") throw new Error("Expected S3 fixture");
const credentials = { ...config.credentials };
expect(Object.isFrozen(config.credentials)).toBe(true);
const files = createHostFileStore(runtime);
const db = await database();
const first = new PluginManager(
await directory(),
[],
db,
undefined,
files,
);
const bytes = bundle();
const hash = digest(bytes);
const key = `host/plugin-releases/${hash}.zip`;
expect((await first.install(bytes, "local")).restartRequired).toBe(true);
expect(objects.get(`/doca-test/${key}`)).toEqual(Buffer.from(bytes));
expect(
await db
.selectFrom("plugin_archives")
.selectAll()
.executeTakeFirstOrThrow(),
).toMatchObject({ store_id: "cloud", object_key: key, sha256: hash });
expect(
await files.putImmutable(key, bytes, "application/zip"),
).toMatchObject({
existed: true,
sha256: hash,
});
const restarted = new PluginManager(
await directory(),
[],
db,
undefined,
files,
);
expect((await restarted.prepare())[0]!.manifest.id).toBe("example.demo");
await restarted.confirm();
expect((await restarted.inventory()).plugins[0]!.runningVersion).toBe(
"1.0.0",
);
expect(requests.map((request) => request.method)).toEqual([
"PUT",
"GET",
"PUT",
"GET",
"GET",
]);
for (const request of requests) {
expect(request.path).toBe(`/doca-test/${key}`);
expect(request.authorization).toContain(
"Credential=isolated-test-access/",
);
expect(request.sessionToken).toBe("isolated-test-session");
if (request.method === "PUT") expect(request.ifNoneMatch).toBe("*");
}
expect(objects.size).toBe(1);
expect(config.credentials).toEqual(credentials);
} finally {
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
server.closeAllConnections();
});
}
});
it.each(["local", "npm", "store"] as const)(
"rejects undeclared storage through %s installation without saving the plugin or running its factory",
async (source) => {
const db = await database();
const manager = new PluginManager(await directory(), [], db);
await manager.prepare();
await manager.confirm();
const before = await db.selectFrom("plugin_registry").selectAll().execute();
const files = unpack(bundle());
const pkg = JSON.parse(new TextDecoder().decode(files["package.json"]!));
delete pkg.doca.storage;
files["package.json"] = strToU8(JSON.stringify(pkg));
files["server.js"] = strToU8("throw new Error('plugin code must not run')");
await expect(manager.install(zipSync(files), source)).rejects.toThrow(
'doca.storage must be "host"',
);
expect(
await db.selectFrom("plugin_registry").selectAll().execute(),
).toEqual(before);
expect(
await db.selectFrom("plugin_archives").selectAll().execute(),
).toEqual([]);
},
);
it("rejects an old shared archive on startup without importing code or modifying persisted registry/data", async () => {
const db = await database();
const first = new PluginManager(await directory(), [], db);
await first.prepare();
await first.confirm();
await first.install(bundle(), "local");
const row = await db
.selectFrom("plugin_registry")
.selectAll()
.executeTakeFirstOrThrow();
const state = JSON.parse(row.state);
const archive = await db
.selectFrom("plugin_archives")
.selectAll()
.executeTakeFirstOrThrow();
const files = unpack(
await first.archiveStore.read(
archive.store_id,
archive.object_key,
archive.size,
archive.sha256,
),
);
const pkg = JSON.parse(new TextDecoder().decode(files["package.json"]!));
delete pkg.doca.storage;
files["package.json"] = strToU8(JSON.stringify(pkg));
files["server.js"] = strToU8("throw new Error('old plugin must not run')");
const oldBytes = zipSync(files);
const oldHash = digest(oldBytes);
state.desired["example.demo"].sha256 = oldHash;
const stored = await first.archiveStore.putImmutable(
`host/plugin-releases/${oldHash}.zip`,
oldBytes,
"application/zip",
);
await db.transaction().execute(async (tx) => {
await tx
.updateTable("plugin_archives")
.set({
sha256: oldHash,
store_id: stored.storeId,
object_key: stored.key,
size: stored.size,
file_index: archiveFileIndex(oldBytes),
})
.where("sha256", "=", archive.sha256)
.execute();
await tx
.updateTable("plugin_registry")
.set({ state: JSON.stringify(state) })
.where("id", "=", row.id)
.execute();
});
const before = await db.selectFrom("plugin_registry").selectAll().execute();
const archives = await db.selectFrom("plugin_archives").selectAll().execute();
const directoryPath = await directory();
const dataPath = join(directoryPath, ".old-business-data");
await writeFile(dataPath, "preserved");
const restarted = new PluginManager(directoryPath, [], db);
await expect(restarted.prepare()).rejects.toThrow(
'doca.storage must be "host"',
);
expect(await db.selectFrom("plugin_registry").selectAll().execute()).toEqual(
before,
);
expect(await db.selectFrom("plugin_archives").selectAll().execute()).toEqual(
archives,
);
expect(await readFile(dataPath, "utf8")).toBe("preserved");
});
it("synchronizes uploads to a second empty instance and repairs partial/corrupt caches before loading", async () => {
const db = await database(),
a = await directory(),
b = await directory();
const first = new PluginManager(a, [], db);
await first.prepare();
await first.confirm();
const bytes = bundle();
expect((await first.install(bytes, "local")).restartRequired).toBe(true);
const second = new PluginManager(b, [], db);
const plugins = await second.prepare();
await second.confirm();
expect(plugins[0]!.manifest.id).toBe("example.demo");
expect((await second.inventory()).plugins[0]!.runningVersion).toBe("1.0.0");
expect((await first.inventory()).plugins[0]!.runningVersion).toBeNull();
const root = plugins[0]!.root;
await writeFile(join(root, "web/chunk.js"), "corrupt");
await rm(join(root, "server.js"));
const restarted = new PluginManager(b, [], db);
await restarted.prepare();
await restarted.confirm();
expect(await readFile(join(root, "web/chunk.js"), "utf8")).toBe(
"export const value = 42;",
);
expect(await readFile(join(root, "server.js"), "utf8")).toContain(
"export default",
);
await db.updateTable("plugin_archives").set({ size: 1 }).execute();
await expect(
new PluginManager(await directory(), [], db).prepare(),
).rejects.toThrow();
});
it("uses a complete verified cache without fetching its shared archive again", async () => {
const db = await database(),
dir = await directory();
const first = new PluginManager(dir, [], db);
await first.install(bundle(), "local");
await first.prepare();
const restarted = new PluginManager(dir, [], db);
vi.spyOn(restarted.archiveStore, "read").mockRejectedValue(
new Error("archive backend is unavailable"),
);
expect(await restarted.prepare()).toHaveLength(1);
await writeFile(
join(dir, ".releases", digest(bundle()), "web/chunk.js"),
"corrupt",
);
await expect(
new PluginManager(dir, [], db, undefined, restarted.archiveStore).prepare(),
).rejects.toThrow("backend is unavailable");
});
it("upgrades without touching running code and clears the structure number on uninstall", async () => {
const db = await database(),
dir = await directory();
const installer = new PluginManager(dir, [], db);
await installer.install(bundle(), "local");
const running = new PluginManager(dir, [], db);
const [old] = await running.prepare();
await running.confirm();
await running.install(bundle("1.1.0"), "local");
expect((await running.inventory()).plugins[0]).toMatchObject({
version: "1.1.0",
runningVersion: "1.0.0",
pending: true,
canCancel: true,
});
expect(await readFile(old!.server, "utf8")).toContain('"version":"1.0.0"');
await expect(running.install(bundle("1.2.0", "2"), "local")).rejects.toThrow(
"Incompatible data structure for example.demo: package 1.2.0 declares 2, but the installed structure is 1.",
);
await expect(running.install(bundle("1.0.0"), "local")).rejects.toThrow();
const newInstance = new PluginManager(await directory(), [], db);
await newInstance.prepare();
await newInstance.confirm();
expect(
(await newInstance.assetPlugin("example.demo", "1.0.0"))!.manifest.version,
).toBe("1.0.0");
await newInstance.change("example.demo", "remove");
const emptyInstance = new PluginManager(await directory(), [], db);
expect(await emptyInstance.prepare()).toEqual([]);
await emptyInstance.confirm();
expect((await emptyInstance.inventory()).plugins).toEqual([]);
expect(
JSON.parse(
(
await db
.selectFrom("plugin_registry")
.select("state")
.executeTakeFirstOrThrow()
).state,
).dataVersions,
).toEqual({});
expect(
(await emptyInstance.install(bundle("2.0.0", "2"), "local")).plugins[0],
).toMatchObject({
version: "2.0.0",
dataVersion: "2",
});
expect(
await db.selectFrom("plugin_archives").selectAll().execute(),
).toHaveLength(3);
});
it("requires old instances to restart after reinstalling the same release and cannot cancel cleared storage", async () => {
const db = await database();
const installer = new PluginManager(await directory(), [], db);
await installer.install(bundle(), "local");
await expect(installer.change("example.demo", "cancel")).rejects.toThrow(
"cannot be cancelled",
);
const old = new PluginManager(await directory(), [], db);
await old.prepare();
await old.confirm();
await old.change("example.demo", "disable");
await old.change("example.demo", "cancel");
expect((await old.inventory()).restartRequired).toBe(false);
await installer.change("example.demo", "remove");
await expect(old.change("example.demo", "cancel")).rejects.toThrow(
"cannot be cancelled",
);
await installer.install(bundle(), "local");
const before = await db.selectFrom("plugin_registry").selectAll().execute();
expect((await old.inventory()).plugins[0]).toMatchObject({
version: "1.0.0",
runningVersion: "1.0.0",
pending: true,
canCancel: false,
});
expect((await old.inventory()).restartRequired).toBe(true);
await expect(old.change("example.demo", "cancel")).rejects.toThrow(
"installation changed",
);
expect(await db.selectFrom("plugin_registry").selectAll().execute()).toEqual(
before,
);
const restarted = new PluginManager(await directory(), [], db);
await restarted.prepare();
await restarted.confirm();
expect((await restarted.inventory()).restartRequired).toBe(false);
await restarted.change("example.demo", "disable");
await restarted.change("example.demo", "cancel");
expect((await restarted.inventory()).restartRequired).toBe(false);
await restarted.change("example.demo", "disable");
const disabled = new PluginManager(await directory(), [], db);
await disabled.prepare();
await disabled.confirm();
await disabled.change("example.demo", "enable");
expect((await disabled.inventory()).plugins[0]).toMatchObject({
runningVersion: null,
pending: true,
canCancel: true,
});
await disabled.change("example.demo", "cancel");
expect((await disabled.inventory()).restartRequired).toBe(false);
});
it("keeps the install when the plugin uninstall method fails", async () => {
const db = await database();
const manager = new PluginManager(await directory(), [], db);
await manager.install(
bundle(
"1.0.0",
"1",
"example.demo",
[],
"async uninstall() { throw new Error('database busy') }",
),
"local",
);
await manager.prepare();
await manager.confirm();
await expect(manager.change("example.demo", "remove")).rejects.toThrow(
"database busy",
);
const state = JSON.parse(
(
await db
.selectFrom("plugin_registry")
.select("state")
.executeTakeFirstOrThrow()
).state,
);
expect(state.desired["example.demo"].dataVersion).toBe("1");
expect(state.dataVersions["example.demo"]).toBe("1");
});
it("defers runtime imports until startup and rejects a missing uninstall then", async () => {
const db = await database(),
directoryPath = await directory();
const manager = new PluginManager(directoryPath, [], db);
await manager.install(bundle("1.0.0", "1", "example.demo", [], ""), "local");
const installed = await new PluginManager(
await directory(),
[],
db,
).prepare();
const { importInstalledPlugins } =
await import("@server/plugins/installation.js");
await expect(importInstalledPlugins(installed)).rejects.toThrow(
"must implement uninstall",
);
});
it("validates enabled dependency graphs and refuses concurrent lost updates", async () => {
const db = await database();
const a = new PluginManager(await directory(), [], db),
b = new PluginManager(await directory(), [], db);
await a.install(bundle(), "local");
await a.install(
bundle("1.0.0", "1", "example.consumer", [
{ id: "example.demo", range: "^1.0.0" },
]),
"local",
);
await expect(a.change("example.demo", "disable")).rejects.toThrow();
await expect(a.change("example.demo", "remove")).rejects.toThrow();
let arrivals = 0;
let release!: () => void;
const barrier = new Promise<void>((resolve) => {
release = resolve;
});
for (const manager of [a, b]) {
const save = (manager as any).save.bind(manager);
vi.spyOn(manager as any, "save").mockImplementation(
async (...args: unknown[]) => {
if (++arrivals === 2) release();
await barrier;
return save(...args);
},
);
}
const results = await Promise.allSettled([
a.change("example.consumer", "disable"),
b.change("example.consumer", "remove"),
]);
expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1);
expect(results.filter((r) => r.status === "rejected")).toHaveLength(1);
});
it("rejects archive traversal without publishing", async () => {
const db = await database(),
manager = new PluginManager(await directory(), [], db);
const bad = zipSync({
"../escape": strToU8("bad"),
"package.json": strToU8("{}"),
});
await expect(manager.install(bad, "local")).rejects.toThrow("path");
expect((await manager.inventory()).plugins).toEqual([]);
});
it("publishes an offline folder once and synchronizes it from the shared registry", async () => {
const db = await database(),
dir = await directory();
for (const [name, content] of Object.entries(unpack(bundle()))) {
const file = join(dir, "example.demo", name);
await mkdir(join(file, ".."), { recursive: true });
await writeFile(file, content);
}
const first = new PluginManager(dir, [], db);
expect(await first.prepare()).toHaveLength(1);
await first.confirm();
const second = new PluginManager(await directory(), [], db);
expect(await second.prepare()).toHaveLength(1);
await first.change("example.demo", "remove");
expect(await new PluginManager(dir, [], db).prepare()).toHaveLength(0);
});
it("protects management endpoints and removes notes from new deployments", async () => {
const db = await database();
const app = await createApp(db, {
origin: "http://127.0.0.1:39130",
pluginDirectory: await directory(),
});
try {
const headers = {
host: "127.0.0.1:39130",
origin: "http://127.0.0.1:39130",
};
expect(
(await app.inject({ url: "/api/v1/admin/plugins", headers })).statusCode,
).toBe(401);
expect(
(await app.inject({ url: "/api/v1/admin/plugins/operations", headers }))
.statusCode,
).toBe(401);
await createUser(
db,
{
login: "plugin-admin",
displayName: "Admin",
password: "plugin-admin-password",
},
{ bootstrap: true },
);
const login = await app.inject({
method: "POST",
url: "/api/v1/auth/login",
headers,
payload: { login: "plugin-admin", password: "plugin-admin-password" },
});
const cookie = String(login.headers["set-cookie"]).split(";")[0]!;
const upload = await app.inject({
method: "POST",
url: "/api/v1/admin/plugins/upload",
headers: { ...headers, cookie, "content-type": "application/zip" },
payload: Buffer.from(bundle()),
});
expect(upload.statusCode, upload.body).toBe(200);
expect(upload.json().restartRequired).toBe(true);
const history = await app.inject({
url: "/api/v1/admin/plugins/operations",
headers: { ...headers, cookie },
});
expect(history.statusCode).toBe(200);
expect(history.json().items).toEqual([
expect.objectContaining({
stage: "staged",
pluginId: "example.demo",
version: "1.0.0",
error: null,
active: false,
}),
expect.objectContaining({
stage: "requested",
pluginId: "example.demo",
version: "1.0.0",
error: null,
active: false,
}),
]);
const failed = await app.inject({
method: "POST",
url: "/api/v1/admin/plugins/upload",
headers: { ...headers, cookie, "content-type": "application/zip" },
payload: Buffer.from("invalid archive"),
});
expect(failed.statusCode).toBe(400);
const afterFailure = await app.inject({
url: "/api/v1/admin/plugins/operations",
headers: { ...headers, cookie },
});
expect(afterFailure.json().items[0]).toMatchObject({
stage: "failed",
pluginId: null,
version: null,
error: expect.any(String),
active: false,
});
expect(afterFailure.json().items[0].error.length).toBeGreaterThan(0);
expect(
(
await app.inject({
url: "/api/v1/quick-notes",
headers: { ...headers, cookie },
})
).statusCode,
).toBe(404);
const tables = await testTableColumns(db);
expect(
tables.some(
(t) => t.name === "quick_notes" || t.name === "quick_note_compilations",
),
).toBe(false);
} finally {
await app.close();
}
});