mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
style: format server and shared with prettier
A mechanical prettier --write over server/src, server/tests, server/scripts and shared/src with the workspaces' .prettierrc; nothing but layout and import order changes, and every file keeps the same set of imports. shared is formatted throughout and its format baseline is empty. The server baseline keeps the 35 files that Prettier would grow past their lint:size limit (they need a split first, which is not a formatting change), and the generated entity files stay as their generator writes them.
This commit is contained in:
@@ -16,12 +16,47 @@
|
||||
* production declaration order (runtime provider first, registry scan later) and
|
||||
* asserts the plugin still comes up clean.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import { Addons } from '../../../src/db/entities/Addons.entity';
|
||||
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
import { PhotoProviderFields } from '../../../src/db/entities/PhotoProviderFields.entity';
|
||||
import { PhotoProviders } from '../../../src/db/entities/PhotoProviders.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginEntityMetadata } from '../../../src/db/entities/PluginEntityMetadata.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginMetaMigrations } from '../../../src/db/entities/PluginMetaMigrations.entity';
|
||||
import { PluginOauthState } from '../../../src/db/entities/PluginOauthState.entity';
|
||||
import { PluginOauthTokens } from '../../../src/db/entities/PluginOauthTokens.entity';
|
||||
import { PluginScheduledTasks } from '../../../src/db/entities/PluginScheduledTasks.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginUserErasureQueue } from '../../../src/db/entities/PluginUserErasureQueue.entity';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { Settings } from '../../../src/db/entities/Settings.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import { PluginRpcRegistry } from '../../../src/nest-rpc/rpc-kit/registry';
|
||||
import type { PluginRpcRegistryService } from '../../../src/nest-rpc/rpc-kit/registry.service';
|
||||
import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { AuditService } from '../../../src/nest/audit/audit.service';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import { PluginRpcHostFactory } from '../../../src/nest/plugins/host/plugin-rpc-host.factory';
|
||||
import { DbRpc } from '../../../src/nest/plugins/host/rpc/db.rpc';
|
||||
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
import { findRow, insertRow } from '../../helpers/factories/rows';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import type { TestingModule } from '@nestjs/testing';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import type { TestingModule } from '@nestjs/testing';
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb } = await import('../../helpers/db-mock');
|
||||
@@ -29,41 +64,6 @@ vi.mock('../../../src/db/database', async () => {
|
||||
return { db, canAccessTrip: () => undefined };
|
||||
});
|
||||
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import { AuditService } from '../../../src/nest/audit/audit.service';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { Addons } from '../../../src/db/entities/Addons.entity';
|
||||
import { PhotoProviders } from '../../../src/db/entities/PhotoProviders.entity';
|
||||
import { PhotoProviderFields } from '../../../src/db/entities/PhotoProviderFields.entity';
|
||||
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
|
||||
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
import { PluginRpcHostFactory } from '../../../src/nest/plugins/host/plugin-rpc-host.factory';
|
||||
import { PluginRpcRegistry } from '../../../src/nest-rpc/rpc-kit/registry';
|
||||
import type { PluginRpcRegistryService } from '../../../src/nest-rpc/rpc-kit/registry.service';
|
||||
import { DbRpc } from '../../../src/nest/plugins/host/rpc/db.rpc';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginScheduledTasks } from '../../../src/db/entities/PluginScheduledTasks.entity';
|
||||
import { PluginUserErasureQueue } from '../../../src/db/entities/PluginUserErasureQueue.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginEntityMetadata } from '../../../src/db/entities/PluginEntityMetadata.entity';
|
||||
import { PluginOauthTokens } from '../../../src/db/entities/PluginOauthTokens.entity';
|
||||
import { PluginOauthState } from '../../../src/db/entities/PluginOauthState.entity';
|
||||
import { PluginMetaMigrations } from '../../../src/db/entities/PluginMetaMigrations.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import { Settings } from '../../../src/db/entities/Settings.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
import { findRow, insertRow } from '../../helpers/factories/rows';
|
||||
|
||||
let codeRoot: string;
|
||||
let dataRoot: string;
|
||||
let mod: TestingModule;
|
||||
@@ -97,8 +97,14 @@ beforeAll(async () => {
|
||||
// db:own. Seeded 'inactive' (not the 'active' a real shutdown leaves) so the
|
||||
// poll below only terminates on a status the THIS-boot supervisor wrote.
|
||||
await insertRow(seedOrm, Plugins, {
|
||||
id: 'migrator', name: 'migrator', status: 'inactive', enabled: 1, permissions: '["db:own"]',
|
||||
granted_permissions: '["db:own"]', config: '{}', trek_range: '>=3.0.0',
|
||||
id: 'migrator',
|
||||
name: 'migrator',
|
||||
status: 'inactive',
|
||||
enabled: 1,
|
||||
permissions: '["db:own"]',
|
||||
granted_permissions: '["db:own"]',
|
||||
config: '{}',
|
||||
trek_range: '>=3.0.0',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -114,15 +120,21 @@ afterAll(async () => {
|
||||
});
|
||||
|
||||
describe('plugin boot vs registry scan ordering', () => {
|
||||
it('BOOT-REG-001 a plugin enabled before a restart activates cleanly even though the registry scan runs in a LATER provider\'s onModuleInit', async () => {
|
||||
it("BOOT-REG-001 a plugin enabled before a restart activates cleanly even though the registry scan runs in a LATER provider's onModuleInit", async () => {
|
||||
// Empty at construction — exactly what PluginRpcRegistryService is before its
|
||||
// own onModuleInit scan has run.
|
||||
const registry = new PluginRpcRegistry();
|
||||
t = await createTestOrm(testDb);
|
||||
// Plan 3j Task 3: `PluginRpcHostFactory`'s `audit` callback now takes
|
||||
// `PluginCapabilityAuditRepository`, not `DatabaseService`.
|
||||
const hostFactory = new PluginRpcHostFactory(t.repo(PluginCapabilityAudit), registry as unknown as PluginRpcRegistryService);
|
||||
const userSettings = new PluginUserSettingsService((t as TestOrm).repo(PluginSettingsFields), (t as TestOrm).repo(PluginUserConfig));
|
||||
const hostFactory = new PluginRpcHostFactory(
|
||||
t.repo(PluginCapabilityAudit),
|
||||
registry as unknown as PluginRpcRegistryService,
|
||||
);
|
||||
const userSettings = new PluginUserSettingsService(
|
||||
(t as TestOrm).repo(PluginSettingsFields),
|
||||
(t as TestOrm).repo(PluginUserConfig),
|
||||
);
|
||||
const auditLogRepo = t.repo(AuditLog);
|
||||
const usersRepo = t.repo(Users);
|
||||
const addonsService = await createTestAddonsService(testDb);
|
||||
@@ -211,8 +223,15 @@ describe('plugin boot vs registry scan ordering', () => {
|
||||
fs.writeFileSync(path.join(dir, 'index.js'), `module.exports = { async onLoad(ctx) {} };`);
|
||||
await insertRow(seedOrm, Addons, { id: 'needsaddon_addon', name: 'needsaddon_addon', enabled: true });
|
||||
await insertRow(seedOrm, Plugins, {
|
||||
id: 'addongated', name: 'addongated', status: 'inactive', enabled: 1, permissions: '[]', granted_permissions: '[]',
|
||||
config: '{}', trek_range: '>=3.0.0', dependencies: JSON.stringify({ requiredAddons: ['needsaddon_addon'] }),
|
||||
id: 'addongated',
|
||||
name: 'addongated',
|
||||
status: 'inactive',
|
||||
enabled: 1,
|
||||
permissions: '[]',
|
||||
granted_permissions: '[]',
|
||||
config: '{}',
|
||||
trek_range: '>=3.0.0',
|
||||
dependencies: JSON.stringify({ requiredAddons: ['needsaddon_addon'] }),
|
||||
});
|
||||
|
||||
// Self-contained ORM/collaborators — independent of test 1's `t`, which is
|
||||
@@ -233,7 +252,10 @@ describe('plugin boot vs registry scan ordering', () => {
|
||||
// Registry already scanned — this test is about the addon check, not the
|
||||
// registry-ordering bug BOOT-REG-001 pins.
|
||||
registry2.register(new DbRpc(userSettings2));
|
||||
const hostFactory2 = new PluginRpcHostFactory(t2.repo(PluginCapabilityAudit), registry2 as unknown as PluginRpcRegistryService);
|
||||
const hostFactory2 = new PluginRpcHostFactory(
|
||||
t2.repo(PluginCapabilityAudit),
|
||||
registry2 as unknown as PluginRpcRegistryService,
|
||||
);
|
||||
// Built directly on t2 (not createTestAddonsService's sharedTestOrm) so
|
||||
// its repositories share t2's allowGlobalContext: false ORM.
|
||||
const addonsService2 = new AddonsService(
|
||||
|
||||
@@ -5,10 +5,8 @@
|
||||
* built artifact, native binaries, don't-clobber-a-real-plugin, reload only a link),
|
||||
* and a full link -> activate -> reload loop through a real isolated child.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
// Plan 3j Task 3: `discoverPlugins` (called from `runtime.link`) is repository-backed
|
||||
// now (DI1–DI8) — a native `em.insert()` writes every `Opt`-defaulted entity column
|
||||
// (`sort_order`, `installed_at`, `crash_count`, `update_hold`, …), not only the ones
|
||||
@@ -18,13 +16,15 @@ import path from 'node:path';
|
||||
// (`createSnapshotTestDb` + `createTestOrm`) replaces the old hand-rolled table set,
|
||||
// same fix `registry.test.ts` needed.
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
|
||||
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import { makePlugin } from '../../helpers/factories/plugins';
|
||||
import { findRow } from '../../helpers/factories/rows';
|
||||
import { createPluginRuntime } from '../../helpers/plugin-host';
|
||||
import { sharedTestOrm } from '../../helpers/test-uow';
|
||||
import { findRow } from '../../helpers/factories/rows';
|
||||
import { makePlugin } from '../../helpers/factories/plugins';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
const dbConn = testDb;
|
||||
@@ -37,12 +37,25 @@ let runtime: PluginRuntimeService;
|
||||
const ROUTE = (v: string) =>
|
||||
`module.exports = { routes: [{ method: 'GET', path: '/v', auth: false, async handler() { return { status: 200, body: JSON.stringify({ v: ${v} }) }; } }] };`;
|
||||
|
||||
function writeSource(id: string, opts: { index?: string; native?: boolean; noBuild?: boolean; trek?: string } = {}): string {
|
||||
function writeSource(
|
||||
id: string,
|
||||
opts: { index?: string; native?: boolean; noBuild?: boolean; trek?: string } = {},
|
||||
): string {
|
||||
const dir = path.join(srcRoot, id);
|
||||
fs.mkdirSync(path.join(dir, 'server'), { recursive: true });
|
||||
// dev-link requires a `trek` range like any other install front door; `opts.trek`
|
||||
// overrides it to exercise the gate.
|
||||
fs.writeFileSync(path.join(dir, 'trek-plugin.json'), JSON.stringify({ id, name: id, version: '1.0.0', type: 'integration', permissions: [], trek: opts.trek ?? '>=3.0.0' }));
|
||||
fs.writeFileSync(
|
||||
path.join(dir, 'trek-plugin.json'),
|
||||
JSON.stringify({
|
||||
id,
|
||||
name: id,
|
||||
version: '1.0.0',
|
||||
type: 'integration',
|
||||
permissions: [],
|
||||
trek: opts.trek ?? '>=3.0.0',
|
||||
}),
|
||||
);
|
||||
if (!opts.noBuild) fs.writeFileSync(path.join(dir, 'server', 'index.js'), opts.index ?? 'module.exports = {};');
|
||||
if (opts.native) fs.writeFileSync(path.join(dir, 'server', 'addon.node'), '\0');
|
||||
return dir;
|
||||
@@ -103,10 +116,12 @@ describe('PluginRuntimeService dev-link', () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
try {
|
||||
await expect(runtime.link(writeSource('oldplug-bypass', { trek: '>=2.0.0 <3.0.0' }))).resolves.toMatchObject({
|
||||
id: 'oldplug-bypass', trekRangeBypassed: { trekRange: '>=2.0.0 <3.0.0', hostVersion: '3.3.0' },
|
||||
id: 'oldplug-bypass',
|
||||
trekRangeBypassed: { trekRange: '>=2.0.0 <3.0.0', hostVersion: '3.3.0' },
|
||||
});
|
||||
await expect(runtime.link(writeSource('rangeless-bypass', { trek: '' }))).resolves.toMatchObject({
|
||||
id: 'rangeless-bypass', trekRangeBypassed: { trekRange: null, hostVersion: '3.3.0' },
|
||||
id: 'rangeless-bypass',
|
||||
trekRangeBypassed: { trekRange: null, hostVersion: '3.3.0' },
|
||||
});
|
||||
// A dir that fits is a plain link — no marker to alarm anyone with.
|
||||
await expect(runtime.link(writeSource('fits-bypass'))).resolves.toMatchObject({ trekRangeBypassed: null });
|
||||
@@ -134,7 +149,11 @@ describe('PluginRuntimeService dev-link', () => {
|
||||
|
||||
it('refuses to clobber a real (non-linked) installed plugin of the same id', async () => {
|
||||
await makePlugin(await sharedTestOrm(dbConn), 'installed', {
|
||||
name: 'X', type: 'integration', version: '1.0.0', status: 'inactive', source_repo: 'local:upload',
|
||||
name: 'X',
|
||||
type: 'integration',
|
||||
version: '1.0.0',
|
||||
status: 'inactive',
|
||||
source_repo: 'local:upload',
|
||||
});
|
||||
await expect(runtime.link(writeSource('installed'))).rejects.toThrow(/already installed/);
|
||||
});
|
||||
|
||||
@@ -13,40 +13,40 @@
|
||||
* so every one of the 14 repositories this task injects reads/writes real columns,
|
||||
* not a hand-slimmed fixture table.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginEntityMetadata } from '../../../src/db/entities/PluginEntityMetadata.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginMetaMigrations } from '../../../src/db/entities/PluginMetaMigrations.entity';
|
||||
import { PluginOauthState } from '../../../src/db/entities/PluginOauthState.entity';
|
||||
import { PluginOauthTokens } from '../../../src/db/entities/PluginOauthTokens.entity';
|
||||
import { PluginScheduledTasks } from '../../../src/db/entities/PluginScheduledTasks.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginUserErasureQueue } from '../../../src/db/entities/PluginUserErasureQueue.entity';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { Settings } from '../../../src/db/entities/Settings.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
|
||||
import { AuditService } from '../../../src/nest/audit/audit.service';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import { PluginRuntimeService, PluginDependencyError } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
import { PluginsService } from '../../../src/nest/plugins/plugins.service';
|
||||
import { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { countRows, findRow, insertRow, updateRows } from '../../helpers/factories/rows';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { SchedulerRegistry } from '@nestjs/schedule';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { SchedulerRegistry } from '@nestjs/schedule';
|
||||
|
||||
import { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';
|
||||
import { PluginRuntimeService, PluginDependencyError } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import { PluginsService } from '../../../src/nest/plugins/plugins.service';
|
||||
import { AuditService } from '../../../src/nest/audit/audit.service';
|
||||
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { countRows, findRow, insertRow, updateRows } from '../../helpers/factories/rows';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginScheduledTasks } from '../../../src/db/entities/PluginScheduledTasks.entity';
|
||||
import { PluginUserErasureQueue } from '../../../src/db/entities/PluginUserErasureQueue.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginEntityMetadata } from '../../../src/db/entities/PluginEntityMetadata.entity';
|
||||
import { PluginOauthTokens } from '../../../src/db/entities/PluginOauthTokens.entity';
|
||||
import { PluginOauthState } from '../../../src/db/entities/PluginOauthState.entity';
|
||||
import { PluginMetaMigrations } from '../../../src/db/entities/PluginMetaMigrations.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import { Settings } from '../../../src/db/entities/Settings.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
@@ -78,14 +78,31 @@ async function buildRuntime(registrar?: CronRegistrarService): Promise<PluginRun
|
||||
const userSettings = new PluginUserSettingsService(t.repo(PluginSettingsFields), t.repo(PluginUserConfig));
|
||||
const uow = new UnitOfWork(t.em);
|
||||
return new PluginRuntimeService(
|
||||
audit, addons, userSettings,
|
||||
t.repo(Plugins), t.repo(PluginErrorLog), t.repo(PluginScheduledTasks), t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts), t.repo(PluginSettingsFields), t.repo(PluginActions), t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata), t.repo(PluginOauthTokens), t.repo(PluginOauthState), t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit), t.repo(Settings), t.repo(NotificationChannelPreferences),
|
||||
audit,
|
||||
addons,
|
||||
userSettings,
|
||||
t.repo(Plugins),
|
||||
t.repo(PluginErrorLog),
|
||||
t.repo(PluginScheduledTasks),
|
||||
t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts),
|
||||
t.repo(PluginSettingsFields),
|
||||
t.repo(PluginActions),
|
||||
t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata),
|
||||
t.repo(PluginOauthTokens),
|
||||
t.repo(PluginOauthState),
|
||||
t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit),
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
// Plan 4 Task 4: `uow` is no longer `@Optional()` — ordered ahead of
|
||||
// `registry?`/`hostFactory?`, matching the real constructor's own order.
|
||||
uow, undefined, undefined, t.orm, registrar,
|
||||
uow,
|
||||
undefined,
|
||||
undefined,
|
||||
t.orm,
|
||||
registrar,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -93,12 +110,28 @@ function buildPluginsService(): PluginsService {
|
||||
return new PluginsService(
|
||||
// A real AddonsService is not needed by any method this file calls.
|
||||
{ isAddonEnabled: async () => true } as never,
|
||||
t.repo(Plugins), t.repo(PluginEgressHosts), t.repo(PluginSettingsFields), t.repo(PluginActions),
|
||||
t.repo(PluginUserConfig), t.repo(PluginErrorLog), t.repo(PluginCapabilityAudit),
|
||||
t.repo(Plugins),
|
||||
t.repo(PluginEgressHosts),
|
||||
t.repo(PluginSettingsFields),
|
||||
t.repo(PluginActions),
|
||||
t.repo(PluginUserConfig),
|
||||
t.repo(PluginErrorLog),
|
||||
t.repo(PluginCapabilityAudit),
|
||||
);
|
||||
}
|
||||
|
||||
async function seedPlugin(id: string, overrides: Partial<{ enabled: number; granted_permissions: string; permissions: string; trek_range: string; api_version: number; version: string; author_pubkey: string }> = {}): Promise<void> {
|
||||
async function seedPlugin(
|
||||
id: string,
|
||||
overrides: Partial<{
|
||||
enabled: number;
|
||||
granted_permissions: string;
|
||||
permissions: string;
|
||||
trek_range: string;
|
||||
api_version: number;
|
||||
version: string;
|
||||
author_pubkey: string;
|
||||
}> = {},
|
||||
): Promise<void> {
|
||||
await insertRow(t, Plugins, {
|
||||
id,
|
||||
name: id,
|
||||
@@ -124,7 +157,9 @@ async function pluginRow(id: string) {
|
||||
|
||||
describe('Plan 3j Task 2 — R-install-gates named accept+refuse pairs (PR17/PR26/PR28)', () => {
|
||||
let rt: PluginRuntimeService;
|
||||
beforeAll(async () => { rt = await buildRuntime(); });
|
||||
beforeAll(async () => {
|
||||
rt = await buildRuntime();
|
||||
});
|
||||
|
||||
describe('PR17 — version-range + permission-grant gate (assertActivatable)', () => {
|
||||
it('INSTALL-GATE-PR17-ACCEPT: a plugin whose declared range admits this host, with no permission widening, passes the gate (activate resolves, never PluginDependencyError)', async () => {
|
||||
@@ -149,7 +184,7 @@ describe('Plan 3j Task 2 — R-install-gates named accept+refuse pairs (PR17/PR2
|
||||
});
|
||||
});
|
||||
|
||||
describe('PR26 — update()\'s pre-update snapshot feeding the permission-widening diff', () => {
|
||||
describe("PR26 — update()'s pre-update snapshot feeding the permission-widening diff", () => {
|
||||
const fakeRegistry = (perms: string[]) =>
|
||||
({
|
||||
resolveVersion: vi.fn(async () => ({ version: '2.0.0' })),
|
||||
@@ -165,11 +200,25 @@ describe('Plan 3j Task 2 — R-install-gates named accept+refuse pairs (PR17/PR2
|
||||
const addons = await createTestAddonsService(testDb);
|
||||
const userSettings = new PluginUserSettingsService(t.repo(PluginSettingsFields), t.repo(PluginUserConfig));
|
||||
const rtU = new PluginRuntimeService(
|
||||
audit, addons, userSettings,
|
||||
t.repo(Plugins), t.repo(PluginErrorLog), t.repo(PluginScheduledTasks), t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts), t.repo(PluginSettingsFields), t.repo(PluginActions), t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata), t.repo(PluginOauthTokens), t.repo(PluginOauthState), t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit), t.repo(Settings), t.repo(NotificationChannelPreferences), new UnitOfWork(t.em),
|
||||
audit,
|
||||
addons,
|
||||
userSettings,
|
||||
t.repo(Plugins),
|
||||
t.repo(PluginErrorLog),
|
||||
t.repo(PluginScheduledTasks),
|
||||
t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts),
|
||||
t.repo(PluginSettingsFields),
|
||||
t.repo(PluginActions),
|
||||
t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata),
|
||||
t.repo(PluginOauthTokens),
|
||||
t.repo(PluginOauthState),
|
||||
t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit),
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
new UnitOfWork(t.em),
|
||||
fakeRegistry(['db:own']),
|
||||
);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -187,11 +236,25 @@ describe('Plan 3j Task 2 — R-install-gates named accept+refuse pairs (PR17/PR2
|
||||
const addons = await createTestAddonsService(testDb);
|
||||
const userSettings = new PluginUserSettingsService(t.repo(PluginSettingsFields), t.repo(PluginUserConfig));
|
||||
const rtU = new PluginRuntimeService(
|
||||
audit, addons, userSettings,
|
||||
t.repo(Plugins), t.repo(PluginErrorLog), t.repo(PluginScheduledTasks), t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts), t.repo(PluginSettingsFields), t.repo(PluginActions), t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata), t.repo(PluginOauthTokens), t.repo(PluginOauthState), t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit), t.repo(Settings), t.repo(NotificationChannelPreferences), new UnitOfWork(t.em),
|
||||
audit,
|
||||
addons,
|
||||
userSettings,
|
||||
t.repo(Plugins),
|
||||
t.repo(PluginErrorLog),
|
||||
t.repo(PluginScheduledTasks),
|
||||
t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts),
|
||||
t.repo(PluginSettingsFields),
|
||||
t.repo(PluginActions),
|
||||
t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata),
|
||||
t.repo(PluginOauthTokens),
|
||||
t.repo(PluginOauthState),
|
||||
t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit),
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
new UnitOfWork(t.em),
|
||||
fakeRegistry(['db:own', 'db:read:trips']),
|
||||
);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -205,7 +268,7 @@ describe('Plan 3j Task 2 — R-install-gates named accept+refuse pairs (PR17/PR2
|
||||
});
|
||||
});
|
||||
|
||||
describe('PR28 — retrust()\'s signing-key TOFU comparison', () => {
|
||||
describe("PR28 — retrust()'s signing-key TOFU comparison", () => {
|
||||
const registryFor = (id: string) =>
|
||||
({
|
||||
assertRetrustable: vi.fn(async (_id: string, key: string) => ({ authorPublicKey: key })),
|
||||
@@ -222,11 +285,25 @@ describe('Plan 3j Task 2 — R-install-gates named accept+refuse pairs (PR17/PR2
|
||||
const userSettings = new PluginUserSettingsService(t.repo(PluginSettingsFields), t.repo(PluginUserConfig));
|
||||
const registry = registryFor('pr28-accept');
|
||||
const rtR = new PluginRuntimeService(
|
||||
audit, addons, userSettings,
|
||||
t.repo(Plugins), t.repo(PluginErrorLog), t.repo(PluginScheduledTasks), t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts), t.repo(PluginSettingsFields), t.repo(PluginActions), t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata), t.repo(PluginOauthTokens), t.repo(PluginOauthState), t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit), t.repo(Settings), t.repo(NotificationChannelPreferences), new UnitOfWork(t.em),
|
||||
audit,
|
||||
addons,
|
||||
userSettings,
|
||||
t.repo(Plugins),
|
||||
t.repo(PluginErrorLog),
|
||||
t.repo(PluginScheduledTasks),
|
||||
t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts),
|
||||
t.repo(PluginSettingsFields),
|
||||
t.repo(PluginActions),
|
||||
t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata),
|
||||
t.repo(PluginOauthTokens),
|
||||
t.repo(PluginOauthState),
|
||||
t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit),
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
new UnitOfWork(t.em),
|
||||
registry,
|
||||
);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -247,11 +324,25 @@ describe('Plan 3j Task 2 — R-install-gates named accept+refuse pairs (PR17/PR2
|
||||
const registry = registryFor('pr28-refuse');
|
||||
vi.mocked(registry.assertRetrustable).mockRejectedValue(new Error('nothing to re-trust'));
|
||||
const rtR = new PluginRuntimeService(
|
||||
audit, addons, userSettings,
|
||||
t.repo(Plugins), t.repo(PluginErrorLog), t.repo(PluginScheduledTasks), t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts), t.repo(PluginSettingsFields), t.repo(PluginActions), t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata), t.repo(PluginOauthTokens), t.repo(PluginOauthState), t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit), t.repo(Settings), t.repo(NotificationChannelPreferences), new UnitOfWork(t.em),
|
||||
audit,
|
||||
addons,
|
||||
userSettings,
|
||||
t.repo(Plugins),
|
||||
t.repo(PluginErrorLog),
|
||||
t.repo(PluginScheduledTasks),
|
||||
t.repo(PluginUserErasureQueue),
|
||||
t.repo(PluginEgressHosts),
|
||||
t.repo(PluginSettingsFields),
|
||||
t.repo(PluginActions),
|
||||
t.repo(PluginUserConfig),
|
||||
t.repo(PluginEntityMetadata),
|
||||
t.repo(PluginOauthTokens),
|
||||
t.repo(PluginOauthState),
|
||||
t.repo(PluginMetaMigrations),
|
||||
t.repo(PluginCapabilityAudit),
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
new UnitOfWork(t.em),
|
||||
registry,
|
||||
);
|
||||
await expect(rtR.retrust('pr28-refuse', '2.0.0', 'NEWKEY', { userId: 1 })).rejects.toThrow(/nothing to re-trust/);
|
||||
@@ -270,14 +361,22 @@ describe('R-uninstall: the cascade is one transaction', () => {
|
||||
await insertRow(t, PluginSettingsFields, { plugin_id: id, field_key: 'k', scope: 'instance' });
|
||||
await insertRow(t, PluginScheduledTasks, { plugin_id: id, name: 'poll', due_at: 0 });
|
||||
await insertRow(t, PluginErrorLog, { plugin_id: id, level: 'error', message: 'x' });
|
||||
await insertRow(t, PluginEntityMetadata, { plugin_id: id, entity_type: 'place', entity_id: 1, key: 'k', value: 'v' });
|
||||
await insertRow(t, PluginEntityMetadata, {
|
||||
plugin_id: id,
|
||||
entity_type: 'place',
|
||||
entity_id: 1,
|
||||
key: 'k',
|
||||
value: 'v',
|
||||
});
|
||||
|
||||
// Simulate a crash INSIDE the cascade, between plugin_scheduled_tasks (deletes
|
||||
// cleanly, unconditional, no try/catch) and plugin_error_log (the next
|
||||
// unconditional delete, inside the deleteData branch).
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const errorLogRepo = (rt as any).pluginErrorLog;
|
||||
const spy = vi.spyOn(errorLogRepo, 'deleteAllForPlugin').mockRejectedValueOnce(new Error('simulated mid-cascade crash'));
|
||||
const spy = vi
|
||||
.spyOn(errorLogRepo, 'deleteAllForPlugin')
|
||||
.mockRejectedValueOnce(new Error('simulated mid-cascade crash'));
|
||||
|
||||
const dataDir = path.join(dataRoot, id);
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
@@ -285,20 +384,20 @@ describe('R-uninstall: the cascade is one transaction', () => {
|
||||
await expect(rt.uninstall(id, true)).rejects.toThrow(/simulated mid-cascade crash/);
|
||||
spy.mockRestore();
|
||||
|
||||
// Everything before the simulated crash point was rolled back with it: a half
|
||||
// uninstall used to leave settings, tasks and metadata for a later plugin that
|
||||
// reuses the id to inherit.
|
||||
expect(await countRows(t, PluginSettingsFields, { plugin_id: id })).toBe(1);
|
||||
expect(await countRows(t, PluginScheduledTasks, { plugin_id: id })).toBe(1);
|
||||
expect(await countRows(t, PluginErrorLog, { plugin_id: id })).toBe(1);
|
||||
expect(await countRows(t, PluginEntityMetadata, { plugin_id: id })).toBe(1);
|
||||
expect(await countRows(t, Plugins, { id })).toBe(1);
|
||||
// The data directory goes only after the rows commit.
|
||||
expect(fs.existsSync(dataDir)).toBe(true);
|
||||
// Everything before the simulated crash point was rolled back with it: a half
|
||||
// uninstall used to leave settings, tasks and metadata for a later plugin that
|
||||
// reuses the id to inherit.
|
||||
expect(await countRows(t, PluginSettingsFields, { plugin_id: id })).toBe(1);
|
||||
expect(await countRows(t, PluginScheduledTasks, { plugin_id: id })).toBe(1);
|
||||
expect(await countRows(t, PluginErrorLog, { plugin_id: id })).toBe(1);
|
||||
expect(await countRows(t, PluginEntityMetadata, { plugin_id: id })).toBe(1);
|
||||
expect(await countRows(t, Plugins, { id })).toBe(1);
|
||||
// The data directory goes only after the rows commit.
|
||||
expect(fs.existsSync(dataDir)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Plan 3j Task 2 — R-uninstall\'s ONE named transaction: PR22/PR23 egress-host replace', () => {
|
||||
describe("Plan 3j Task 2 — R-uninstall's ONE named transaction: PR22/PR23 egress-host replace", () => {
|
||||
it('EGRESS-TX-ROLLBACK-001: a simulated failure mid-write leaves the OLD egress-host set intact, not partially cleared', async () => {
|
||||
const rt = await buildRuntime();
|
||||
const id = 'egress-tx';
|
||||
@@ -318,12 +417,16 @@ describe('Plan 3j Task 2 — R-uninstall\'s ONE named transaction: PR22/PR23 egr
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const egressRepo = (rt as any).pluginEgressHosts;
|
||||
const originalUpsert = egressRepo.upsert.bind(egressRepo);
|
||||
const spy = vi.spyOn(egressRepo, 'upsert').mockImplementation(async (data: { plugin_id: string; host: string }, ...rest: unknown[]) => {
|
||||
if (data.host === 'boom') throw new Error('simulated mid-write failure');
|
||||
return originalUpsert(data, ...rest);
|
||||
});
|
||||
const spy = vi
|
||||
.spyOn(egressRepo, 'upsert')
|
||||
.mockImplementation(async (data: { plugin_id: string; host: string }, ...rest: unknown[]) => {
|
||||
if (data.host === 'boom') throw new Error('simulated mid-write failure');
|
||||
return originalUpsert(data, ...rest);
|
||||
});
|
||||
|
||||
await expect(rt.setOperatorEgressHosts(id, ['new-a.example.com', 'boom'])).rejects.toThrow(/simulated mid-write failure/);
|
||||
await expect(rt.setOperatorEgressHosts(id, ['new-a.example.com', 'boom'])).rejects.toThrow(
|
||||
/simulated mid-write failure/,
|
||||
);
|
||||
spy.mockRestore();
|
||||
|
||||
// The OLD set survives untouched — the transaction rolled the DELETE AND the
|
||||
@@ -334,7 +437,7 @@ describe('Plan 3j Task 2 — R-uninstall\'s ONE named transaction: PR22/PR23 egr
|
||||
});
|
||||
|
||||
describe('Plan 3j Task 2 — PS7/PS9/PS11: the triple-duplicate SELECT collapses onto ONE PluginUserConfigRepository.findConfig call', () => {
|
||||
it('PS-USERCONFIG-PARITY-001: getUserConfig, setUserConfig\'s pre-write check and getUserConfigDecrypted all read the SAME stored row identically', async () => {
|
||||
it("PS-USERCONFIG-PARITY-001: getUserConfig, setUserConfig's pre-write check and getUserConfigDecrypted all read the SAME stored row identically", async () => {
|
||||
const svc = buildPluginsService();
|
||||
const id = 'ps-parity';
|
||||
await seedPlugin(id);
|
||||
@@ -366,7 +469,9 @@ describe('Plan 3j Task 2 — two racing ticks (scheduler claim/re-arm + erasure
|
||||
rt = await buildRuntime(registrar);
|
||||
await rt.onApplicationBootstrap();
|
||||
});
|
||||
afterAll(async () => { await rt.onModuleDestroy(); });
|
||||
afterAll(async () => {
|
||||
await rt.onModuleDestroy();
|
||||
});
|
||||
|
||||
it('RACE-SCHED-001: two concurrent fireDueScheduled passes deliver a due one-shot task exactly once', async () => {
|
||||
const pluginId = 'race-sched';
|
||||
@@ -405,7 +510,12 @@ describe('Plan 3j Task 2 — two racing ticks (scheduler claim/re-arm + erasure
|
||||
const pluginId = 'race-sched-recur';
|
||||
await seedPlugin(pluginId, { enabled: 1 });
|
||||
const everyMs = 60_000;
|
||||
await insertRow(t, PluginScheduledTasks, { plugin_id: pluginId, name: 'recurring', due_at: Date.now() - 1000, every_ms: everyMs });
|
||||
await insertRow(t, PluginScheduledTasks, {
|
||||
plugin_id: pluginId,
|
||||
name: 'recurring',
|
||||
due_at: Date.now() - 1000,
|
||||
every_ms: everyMs,
|
||||
});
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const supervisor = (rt as any).supervisor;
|
||||
@@ -436,7 +546,7 @@ describe('Plan 3j Task 2 — two racing ticks (scheduler claim/re-arm + erasure
|
||||
}
|
||||
});
|
||||
|
||||
it('RACE-ERASURE-001: two concurrent drains coalesce onto the SAME in-flight pass (drainUserErasures\' own promise-sharing) — one ACK, one drop', async () => {
|
||||
it("RACE-ERASURE-001: two concurrent drains coalesce onto the SAME in-flight pass (drainUserErasures' own promise-sharing) — one ACK, one drop", async () => {
|
||||
const pluginId = 'race-erasure';
|
||||
await seedPlugin(pluginId, { enabled: 1 });
|
||||
await insertRow(t, PluginUserErasureQueue, { plugin_id: pluginId, user_id: 99 });
|
||||
|
||||
@@ -3,10 +3,15 @@
|
||||
* HTTP route works through the host→child invoke path, using its own isolated
|
||||
* db. Proves the full activate → route → deactivate loop.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, afterEach, beforeEach, vi } from 'vitest';
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
import { DependencyCycleError } from '../../../src/nest/plugins/dependencies';
|
||||
import { PluginRuntimeService, PluginDependencyError } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import { createPluginRuntime } from '../../helpers/plugin-host';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, it, expect, beforeAll, afterAll, afterEach, beforeEach, vi } from 'vitest';
|
||||
|
||||
const { testDb } = vi.hoisted(() => {
|
||||
const Database = require('better-sqlite3');
|
||||
@@ -43,11 +48,6 @@ const { testDb } = vi.hoisted(() => {
|
||||
return { testDb: db };
|
||||
});
|
||||
vi.mock('../../../src/db/database', () => ({ db: testDb, canAccessTrip: () => undefined }));
|
||||
import { db as dbConn } from '../../../src/db/database';
|
||||
|
||||
import { PluginRuntimeService, PluginDependencyError } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import { createPluginRuntime } from '../../helpers/plugin-host';
|
||||
import { DependencyCycleError } from '../../../src/nest/plugins/dependencies';
|
||||
|
||||
let codeRoot: string;
|
||||
let dataRoot: string;
|
||||
@@ -77,7 +77,9 @@ beforeAll(async () => {
|
||||
};`,
|
||||
);
|
||||
|
||||
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('counter','active','[\"db:own\"]','{}')").run();
|
||||
testDb
|
||||
.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('counter','active','[\"db:own\"]','{}')")
|
||||
.run();
|
||||
runtime = await createPluginRuntime(dbConn);
|
||||
});
|
||||
|
||||
@@ -121,12 +123,17 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
});
|
||||
|
||||
it('invoke on a plugin that is not running rejects', async () => {
|
||||
await expect(runtime.invoke('never-activated', 'invoke.route', { routeId: 0, req: {} })).rejects.toThrow(/not active/);
|
||||
await expect(runtime.invoke('never-activated', 'invoke.route', { routeId: 0, req: {} })).rejects.toThrow(
|
||||
/not active/,
|
||||
);
|
||||
});
|
||||
|
||||
it('a route that throws surfaces as a rejected invoke', async () => {
|
||||
await expect(
|
||||
runtime.invoke('counter', 'invoke.route', { routeId: 1, req: { method: 'GET', path: '/boom', query: {}, body: null, user: null } }),
|
||||
runtime.invoke('counter', 'invoke.route', {
|
||||
routeId: 1,
|
||||
req: { method: 'GET', path: '/boom', query: {}, body: null, user: null },
|
||||
}),
|
||||
).rejects.toThrow(/route fail/);
|
||||
});
|
||||
|
||||
@@ -136,11 +143,19 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
|
||||
it('re-consent gate: activating a consented plugin with WIDER permissions is refused without consent', async () => {
|
||||
// consented to db:own; a version now declaring db:read:users too must not auto-grant
|
||||
testDb.prepare("INSERT INTO plugins (id, status, permissions, granted_permissions, config) VALUES ('widener','inactive','[\"db:own\",\"db:read:users\"]','[\"db:own\"]','{}')").run();
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, permissions, granted_permissions, config) VALUES ('widener','inactive','[\"db:own\",\"db:read:users\"]','[\"db:own\"]','{}')",
|
||||
)
|
||||
.run();
|
||||
await expect(runtime.activate('widener')).rejects.toThrow(/re-consent|new permissions/);
|
||||
// the key case: a plugin consented to ZERO perms ('[]') is still "consented" —
|
||||
// a later widening to db:own is blocked, not silently granted.
|
||||
testDb.prepare("INSERT INTO plugins (id, status, permissions, granted_permissions, config) VALUES ('zeroperm','inactive','[\"db:own\"]','[]','{}')").run();
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, permissions, granted_permissions, config) VALUES ('zeroperm','inactive','[\"db:own\"]','[]','{}')",
|
||||
)
|
||||
.run();
|
||||
await expect(runtime.activate('zeroperm')).rejects.toThrow(/re-consent|new permissions/);
|
||||
// (a NEVER-consented plugin — granted '' — consenting to its declared set on
|
||||
// first activate is covered by the 'counter' happy-path test above.)
|
||||
@@ -162,7 +177,10 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
it('deactivate stops the plugin and clears the enabled intent', async () => {
|
||||
await runtime.deactivate('counter');
|
||||
expect(runtime.isActive('counter')).toBe(false);
|
||||
const row = testDb.prepare("SELECT status, enabled FROM plugins WHERE id = 'counter'").get() as { status: string; enabled: number };
|
||||
const row = testDb.prepare("SELECT status, enabled FROM plugins WHERE id = 'counter'").get() as {
|
||||
status: string;
|
||||
enabled: number;
|
||||
};
|
||||
expect(row.status).toBe('inactive');
|
||||
expect(row.enabled).toBe(0);
|
||||
});
|
||||
@@ -177,17 +195,23 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
it('tolerates malformed granted_permissions / config JSON on activate', async () => {
|
||||
fs.mkdirSync(path.join(codeRoot, 'messy', 'server'), { recursive: true });
|
||||
fs.writeFileSync(path.join(codeRoot, 'messy', 'server', 'index.js'), 'module.exports = { async onLoad() {} };');
|
||||
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('messy','inactive','not-json','not-json')").run();
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, permissions, config) VALUES ('messy','inactive','not-json','not-json')",
|
||||
)
|
||||
.run();
|
||||
const rt = await createPluginRuntime(dbConn);
|
||||
await rt.activate('messy'); // must not throw despite the garbage JSON
|
||||
expect(rt.isActive('messy')).toBe(true);
|
||||
await rt.deactivate('messy');
|
||||
});
|
||||
|
||||
it('erases and exports a user\'s own-db data through the GDPR hooks', async () => {
|
||||
it("erases and exports a user's own-db data through the GDPR hooks", async () => {
|
||||
const gdir = path.join(codeRoot, 'gdpr', 'server');
|
||||
fs.mkdirSync(gdir, { recursive: true });
|
||||
fs.writeFileSync(path.join(gdir, 'index.js'), `module.exports = {
|
||||
fs.writeFileSync(
|
||||
path.join(gdir, 'index.js'),
|
||||
`module.exports = {
|
||||
async onLoad(ctx) { await ctx.db.migrate('001', 'CREATE TABLE prefs (user_id INTEGER, v TEXT)'); },
|
||||
routes: [{ method: 'POST', path: '/seed', auth: true, async handler(req, ctx) {
|
||||
await ctx.db.exec('INSERT INTO prefs (user_id, v) VALUES (?, ?)', req.user.id, 'x');
|
||||
@@ -195,11 +219,19 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
}}],
|
||||
async exportUserData({ userId }, ctx) { return await ctx.db.query('SELECT v FROM prefs WHERE user_id = ?', userId); },
|
||||
async deleteUserData({ userId }, ctx) { await ctx.db.exec('DELETE FROM prefs WHERE user_id = ?', userId); },
|
||||
};`);
|
||||
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('gdpr','active','[\"db:own\",\"hook:user-data\"]','{}')").run();
|
||||
};`,
|
||||
);
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, permissions, config) VALUES ('gdpr','active','[\"db:own\",\"hook:user-data\"]','{}')",
|
||||
)
|
||||
.run();
|
||||
await runtime.activate('gdpr');
|
||||
// seed a row for user 5
|
||||
await runtime.invoke('gdpr', 'invoke.route', { routeId: 0, req: { method: 'POST', path: '/seed', query: {}, body: null, user: { id: 5, username: 'a', isAdmin: false } } });
|
||||
await runtime.invoke('gdpr', 'invoke.route', {
|
||||
routeId: 0,
|
||||
req: { method: 'POST', path: '/seed', query: {}, body: null, user: { id: 5, username: 'a', isAdmin: false } },
|
||||
});
|
||||
|
||||
// export sees the user's data, aggregated under the plugin id
|
||||
expect(await runtime.exportUserData(5)).toEqual([{ pluginId: 'gdpr', data: [{ v: 'x' }] }]);
|
||||
@@ -209,7 +241,9 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
await (runtime as any).enqueueUserErasure(5);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (runtime as any).drainUserErasures();
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='gdpr'").get()).toMatchObject({ c: 0 });
|
||||
expect(
|
||||
testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='gdpr'").get(),
|
||||
).toMatchObject({ c: 0 });
|
||||
// the export is now empty (rows gone), proving the handler ran end-to-end
|
||||
expect(await runtime.exportUserData(5)).toEqual([{ pluginId: 'gdpr', data: [] }]);
|
||||
|
||||
@@ -230,32 +264,56 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (runtime as any).drainUserErasures();
|
||||
expect((testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='reaptest'").get() as { c: number }).c).toBe(1);
|
||||
expect(
|
||||
(
|
||||
testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='reaptest'").get() as {
|
||||
c: number;
|
||||
}
|
||||
).c,
|
||||
).toBe(1);
|
||||
|
||||
// now the data is truly gone (deleteData=true / manual removal) → the row is reaped
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (runtime as any).drainUserErasures();
|
||||
expect((testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='reaptest'").get() as { c: number }).c).toBe(0);
|
||||
expect(
|
||||
(
|
||||
testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='reaptest'").get() as {
|
||||
c: number;
|
||||
}
|
||||
).c,
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
it('leaves an erasure queued for a plugin that is offline, to run when it is back', async () => {
|
||||
// granted the hook but NOT active → enqueue keeps the row, drain leaves it
|
||||
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('offliner','inactive','[\"db:own\",\"hook:user-data\"]','{}')").run();
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, permissions, config) VALUES ('offliner','inactive','[\"db:own\",\"hook:user-data\"]','{}')",
|
||||
)
|
||||
.run();
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (runtime as any).enqueueUserErasure(9);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await (runtime as any).drainUserErasures();
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='offliner' AND user_id=9").get()).toMatchObject({ c: 1 });
|
||||
expect(
|
||||
testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='offliner' AND user_id=9").get(),
|
||||
).toMatchObject({ c: 1 });
|
||||
// a plugin WITHOUT the grant is never enqueued in the first place
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='counter' AND user_id=9").get()).toMatchObject({ c: 0 });
|
||||
expect(
|
||||
testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='counter' AND user_id=9").get(),
|
||||
).toMatchObject({ c: 0 });
|
||||
});
|
||||
|
||||
it('onApplicationBootstrap boots every ENABLED plugin — even one left in error state', async () => {
|
||||
fs.mkdirSync(path.join(codeRoot, 'booter', 'server'), { recursive: true });
|
||||
fs.writeFileSync(path.join(codeRoot, 'booter', 'server', 'index.js'), 'module.exports = { async onLoad() {} };');
|
||||
// status='error' from a previous crash, but enabled=1 → must still boot
|
||||
testDb.prepare("INSERT INTO plugins (id, status, enabled, granted_permissions, config) VALUES ('booter','error',1,'[]','{}')").run();
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, enabled, granted_permissions, config) VALUES ('booter','error',1,'[]','{}')",
|
||||
)
|
||||
.run();
|
||||
|
||||
const rt = await createPluginRuntime(dbConn);
|
||||
await rt.onApplicationBootstrap(); // fire-and-forget spawn
|
||||
@@ -267,7 +325,11 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
it('onApplicationBootstrap does NOT boot a disabled plugin', async () => {
|
||||
fs.mkdirSync(path.join(codeRoot, 'sleeper', 'server'), { recursive: true });
|
||||
fs.writeFileSync(path.join(codeRoot, 'sleeper', 'server', 'index.js'), 'module.exports = { async onLoad() {} };');
|
||||
testDb.prepare("INSERT INTO plugins (id, status, enabled, granted_permissions, config) VALUES ('sleeper','inactive',0,'[]','{}')").run();
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, enabled, granted_permissions, config) VALUES ('sleeper','inactive',0,'[]','{}')",
|
||||
)
|
||||
.run();
|
||||
|
||||
const rt = await createPluginRuntime(dbConn);
|
||||
await rt.onApplicationBootstrap();
|
||||
@@ -276,7 +338,11 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
});
|
||||
|
||||
it('outboundHostsOf extracts declared http:outbound hosts', async () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, status, granted_permissions, config) VALUES ('net','inactive','[\"db:own\",\"http:outbound:api.x.com\",\"http:outbound:*.y.com\"]','{}')").run();
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, granted_permissions, config) VALUES ('net','inactive','[\"db:own\",\"http:outbound:api.x.com\",\"http:outbound:*.y.com\"]','{}')",
|
||||
)
|
||||
.run();
|
||||
const rt = await createPluginRuntime(dbConn);
|
||||
expect(await rt.outboundHostsOf('net')).toEqual(['api.x.com', '*.y.com']);
|
||||
expect(await rt.outboundHostsOf('missing')).toEqual([]);
|
||||
@@ -286,16 +352,34 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
fs.mkdirSync(path.join(codeRoot, 'gone', 'server'), { recursive: true });
|
||||
fs.writeFileSync(path.join(codeRoot, 'gone', 'server', 'index.js'), 'module.exports={}');
|
||||
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('gone','inactive','[]','{}')").run();
|
||||
testDb.prepare("INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES ('gone','k','instance',0)").run();
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES ('gone','k','instance',0)",
|
||||
)
|
||||
.run();
|
||||
testDb.prepare("INSERT INTO settings (user_id, key, value) VALUES (1, 'plugin:gone:units', 'metric')").run();
|
||||
// Per-user secrets + OAuth tokens live in their OWN tables, not under settings —
|
||||
// a "delete all data" that leaves these behind leaks encrypted keys/tokens that a
|
||||
// same-id reinstall silently re-adopts (audit finding).
|
||||
testDb.prepare("INSERT INTO plugin_user_config (plugin_id, user_id, field_key, value) VALUES ('gone', 1, 'apiKey', 'enc:secret')").run();
|
||||
testDb.prepare("INSERT INTO plugin_oauth_tokens (plugin_id, user_id, access_token, refresh_token) VALUES ('gone', 1, 'at', 'rt')").run();
|
||||
testDb.prepare("INSERT INTO plugin_oauth_state (state, plugin_id, user_id, verifier) VALUES ('s1', 'gone', 1, 'v')").run();
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugin_user_config (plugin_id, user_id, field_key, value) VALUES ('gone', 1, 'apiKey', 'enc:secret')",
|
||||
)
|
||||
.run();
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugin_oauth_tokens (plugin_id, user_id, access_token, refresh_token) VALUES ('gone', 1, 'at', 'rt')",
|
||||
)
|
||||
.run();
|
||||
testDb
|
||||
.prepare("INSERT INTO plugin_oauth_state (state, plugin_id, user_id, verifier) VALUES ('s1', 'gone', 1, 'v')")
|
||||
.run();
|
||||
testDb.prepare("INSERT INTO plugin_meta_migrations (plugin_id, migration_id) VALUES ('gone', '001')").run();
|
||||
testDb.prepare("INSERT INTO plugin_capability_audit (plugin_id, method, code, ts, hash) VALUES ('gone', 'trips.getById', 'OK', 't', 'h')").run();
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugin_capability_audit (plugin_id, method, code, ts, hash) VALUES ('gone', 'trips.getById', 'OK', 't', 'h')",
|
||||
)
|
||||
.run();
|
||||
testDb.prepare("INSERT INTO plugin_scheduled_tasks (plugin_id, name, due_at) VALUES ('gone', 'poll', 0)").run();
|
||||
testDb.prepare("INSERT INTO plugin_user_erasure_queue (plugin_id, user_id) VALUES ('gone', 7)").run();
|
||||
|
||||
@@ -303,10 +387,22 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
|
||||
expect(fs.existsSync(path.join(codeRoot, 'gone'))).toBe(false);
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugins WHERE id='gone'").get()).toMatchObject({ c: 0 });
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_settings_fields WHERE plugin_id='gone'").get()).toMatchObject({ c: 0 });
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM settings WHERE key LIKE 'plugin:gone:%'").get()).toMatchObject({ c: 0 });
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_settings_fields WHERE plugin_id='gone'").get()).toMatchObject({
|
||||
c: 0,
|
||||
});
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM settings WHERE key LIKE 'plugin:gone:%'").get()).toMatchObject({
|
||||
c: 0,
|
||||
});
|
||||
// the secret-bearing tables + the erasure queue must be purged too (data is gone)
|
||||
for (const t of ['plugin_user_config', 'plugin_oauth_tokens', 'plugin_oauth_state', 'plugin_meta_migrations', 'plugin_capability_audit', 'plugin_scheduled_tasks', 'plugin_user_erasure_queue']) {
|
||||
for (const t of [
|
||||
'plugin_user_config',
|
||||
'plugin_oauth_tokens',
|
||||
'plugin_oauth_state',
|
||||
'plugin_meta_migrations',
|
||||
'plugin_capability_audit',
|
||||
'plugin_scheduled_tasks',
|
||||
'plugin_user_erasure_queue',
|
||||
]) {
|
||||
expect(testDb.prepare(`SELECT COUNT(*) c FROM ${t} WHERE plugin_id='gone'`).get()).toMatchObject({ c: 0 });
|
||||
}
|
||||
});
|
||||
@@ -314,7 +410,9 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
it('uninstall WITHOUT deleteData keeps pending GDPR erasures (the data survives, so must the obligation)', async () => {
|
||||
fs.mkdirSync(path.join(codeRoot, 'keepdata', 'server'), { recursive: true });
|
||||
fs.writeFileSync(path.join(codeRoot, 'keepdata', 'server', 'index.js'), 'module.exports={}');
|
||||
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('keepdata','inactive','[]','{}')").run();
|
||||
testDb
|
||||
.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('keepdata','inactive','[]','{}')")
|
||||
.run();
|
||||
// a deleted user's erasure is still pending for this plugin
|
||||
testDb.prepare("INSERT INTO plugin_user_erasure_queue (plugin_id, user_id) VALUES ('keepdata', 42)").run();
|
||||
|
||||
@@ -324,14 +422,22 @@ describe('PluginRuntimeService (M2 end-to-end)', () => {
|
||||
// same id will drain it and finally honour the deletion, instead of silently keeping
|
||||
// the user's data forever.
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugins WHERE id='keepdata'").get()).toMatchObject({ c: 0 });
|
||||
expect(testDb.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='keepdata' AND user_id=42").get()).toMatchObject({ c: 1 });
|
||||
expect(
|
||||
testDb
|
||||
.prepare("SELECT COUNT(*) c FROM plugin_user_erasure_queue WHERE plugin_id='keepdata' AND user_id=42")
|
||||
.get(),
|
||||
).toMatchObject({ c: 1 });
|
||||
});
|
||||
|
||||
it('the egress guard blocks a fetch to an undeclared host', async () => {
|
||||
fs.mkdirSync(path.join(codeRoot, 'nettry', 'server'), { recursive: true });
|
||||
fs.writeFileSync(path.join(codeRoot, 'nettry', 'server', 'index.js'),
|
||||
"module.exports = { async onLoad() { await fetch('https://blocked.example/x'); } };");
|
||||
testDb.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('nettry','inactive','[]','{}')").run();
|
||||
fs.writeFileSync(
|
||||
path.join(codeRoot, 'nettry', 'server', 'index.js'),
|
||||
"module.exports = { async onLoad() { await fetch('https://blocked.example/x'); } };",
|
||||
);
|
||||
testDb
|
||||
.prepare("INSERT INTO plugins (id, status, permissions, config) VALUES ('nettry','inactive','[]','{}')")
|
||||
.run();
|
||||
// no http:outbound granted -> egress guard blocks all outbound -> onLoad throws
|
||||
await expect((await createPluginRuntime(dbConn)).activate('nettry')).rejects.toThrow(/egress/);
|
||||
await (await createPluginRuntime(dbConn)).deactivate('nettry').catch(() => {});
|
||||
@@ -348,19 +454,28 @@ describe('PluginRuntimeService.update (re-consent gate)', () => {
|
||||
const fakeRegistry = (impl: () => void, latest = '2.0.0') =>
|
||||
({
|
||||
resolveVersion: vi.fn(async () => ({ version: latest })),
|
||||
install: vi.fn(async () => { impl(); return { id: 'x', version: latest }; }),
|
||||
install: vi.fn(async () => {
|
||||
impl();
|
||||
return { id: 'x', version: latest };
|
||||
}),
|
||||
}) as unknown as import('../../../src/nest/plugins/registry/registry.service').PluginRegistryService;
|
||||
|
||||
const seed = (id: string, enabled: number, permissions: string[], granted: string[]) => {
|
||||
fs.mkdirSync(path.join(codeRoot, id, 'server'), { recursive: true });
|
||||
fs.writeFileSync(path.join(codeRoot, id, 'server', 'index.js'), 'module.exports = { async onLoad() {} };');
|
||||
testDb.prepare('INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config) VALUES (?,?,?,?,?,?)')
|
||||
testDb
|
||||
.prepare(
|
||||
'INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config) VALUES (?,?,?,?,?,?)',
|
||||
)
|
||||
.run(id, enabled ? 'active' : 'inactive', enabled, JSON.stringify(permissions), JSON.stringify(granted), '{}');
|
||||
};
|
||||
|
||||
it('restarts transparently when the new version requests no new permissions', async () => {
|
||||
seed('upd-same', 1, ['db:own'], ['db:own']);
|
||||
const rt = await createPluginRuntime(dbConn, fakeRegistry(() => {})); // declared perms unchanged
|
||||
const rt = await createPluginRuntime(
|
||||
dbConn,
|
||||
fakeRegistry(() => {}),
|
||||
); // declared perms unchanged
|
||||
await rt.activate('upd-same');
|
||||
const res = await rt.update('upd-same');
|
||||
expect(res).toMatchObject({ activated: true, newPermissions: [], newEgress: [] });
|
||||
@@ -370,9 +485,11 @@ describe('PluginRuntimeService.update (re-consent gate)', () => {
|
||||
|
||||
it('leaves the plugin inactive and reports the delta when new rights are requested', async () => {
|
||||
seed('upd-wider', 1, ['db:own'], ['db:own']);
|
||||
const rt = await createPluginRuntime(dbConn,
|
||||
const rt = await createPluginRuntime(
|
||||
dbConn,
|
||||
fakeRegistry(() => {
|
||||
testDb.prepare("UPDATE plugins SET permissions = ? WHERE id = 'upd-wider'")
|
||||
testDb
|
||||
.prepare("UPDATE plugins SET permissions = ? WHERE id = 'upd-wider'")
|
||||
.run(JSON.stringify(['db:own', 'db:read:trips', 'http:outbound:api.new.com']));
|
||||
}),
|
||||
);
|
||||
@@ -387,17 +504,31 @@ describe('PluginRuntimeService.update (re-consent gate)', () => {
|
||||
|
||||
it('a disabled plugin stays disabled even with no new permissions', async () => {
|
||||
seed('upd-off', 0, ['db:own'], ['db:own']);
|
||||
const res = await (await createPluginRuntime(dbConn, fakeRegistry(() => {}))).update('upd-off');
|
||||
const res = await (
|
||||
await createPluginRuntime(
|
||||
dbConn,
|
||||
fakeRegistry(() => {}),
|
||||
)
|
||||
).update('upd-off');
|
||||
expect(res).toMatchObject({ activated: false, newPermissions: [], newEgress: [] });
|
||||
});
|
||||
|
||||
it('throws for an unknown plugin id', async () => {
|
||||
await expect((await createPluginRuntime(dbConn, fakeRegistry(() => {}))).update('ghost-upd')).rejects.toThrow(/not found/);
|
||||
await expect(
|
||||
(
|
||||
await createPluginRuntime(
|
||||
dbConn,
|
||||
fakeRegistry(() => {}),
|
||||
)
|
||||
).update('ghost-upd'),
|
||||
).rejects.toThrow(/not found/);
|
||||
});
|
||||
|
||||
it('throws if no registry service is wired', async () => {
|
||||
seed('upd-noreg', 0, ['db:own'], ['db:own']);
|
||||
await expect((await createPluginRuntime(dbConn)).update('upd-noreg')).rejects.toThrow(/registry service unavailable/);
|
||||
await expect((await createPluginRuntime(dbConn)).update('upd-noreg')).rejects.toThrow(
|
||||
/registry service unavailable/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -405,15 +536,22 @@ describe('PluginRuntimeService dependency gating', () => {
|
||||
const deps = (d: { requiredAddons?: string[]; pluginDependencies?: { id: string; version: string }[] }) =>
|
||||
JSON.stringify({ requiredAddons: d.requiredAddons ?? [], pluginDependencies: d.pluginDependencies ?? [] });
|
||||
const insertPlugin = (id: string, dependencies: string, enabled = 0, version = '1.0.0') =>
|
||||
testDb.prepare("INSERT INTO plugins (id, status, enabled, version, permissions, granted_permissions, config, dependencies) VALUES (?, 'inactive', ?, ?, '[]', '[]', '{}', ?)")
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, enabled, version, permissions, granted_permissions, config, dependencies) VALUES (?, 'inactive', ?, ?, '[]', '[]', '{}', ?)",
|
||||
)
|
||||
.run(id, enabled, version, dependencies);
|
||||
const cleanup = (...ids: string[]) => { for (const id of ids) testDb.prepare('DELETE FROM plugins WHERE id = ?').run(id); };
|
||||
const cleanup = (...ids: string[]) => {
|
||||
for (const id of ids) testDb.prepare('DELETE FROM plugins WHERE id = ?').run(id);
|
||||
};
|
||||
|
||||
it('blocks activation when a required addon is disabled', async () => {
|
||||
testDb.prepare("INSERT OR REPLACE INTO addons (id, enabled) VALUES ('budget', 0)").run();
|
||||
insertPlugin('needs-budget', deps({ requiredAddons: ['budget'] }));
|
||||
await expect(runtime.activate('needs-budget')).rejects.toMatchObject({ code: 'ADDON_DISABLED' });
|
||||
expect((testDb.prepare('SELECT enabled FROM plugins WHERE id = ?').get('needs-budget') as { enabled: number }).enabled).toBe(0);
|
||||
expect(
|
||||
(testDb.prepare('SELECT enabled FROM plugins WHERE id = ?').get('needs-budget') as { enabled: number }).enabled,
|
||||
).toBe(0);
|
||||
cleanup('needs-budget');
|
||||
});
|
||||
|
||||
@@ -454,8 +592,12 @@ describe('PluginRuntimeService dependency gating', () => {
|
||||
insertPlugin('unrelated-b', deps({}), 1);
|
||||
const disabled = await runtime.deactivateForDisabledAddon('budget');
|
||||
expect(disabled.sort()).toEqual(['base-b', 'dependent-b']);
|
||||
expect((testDb.prepare('SELECT enabled FROM plugins WHERE id = ?').get('base-b') as { enabled: number }).enabled).toBe(0);
|
||||
expect((testDb.prepare('SELECT enabled FROM plugins WHERE id = ?').get('unrelated-b') as { enabled: number }).enabled).toBe(1);
|
||||
expect(
|
||||
(testDb.prepare('SELECT enabled FROM plugins WHERE id = ?').get('base-b') as { enabled: number }).enabled,
|
||||
).toBe(0);
|
||||
expect(
|
||||
(testDb.prepare('SELECT enabled FROM plugins WHERE id = ?').get('unrelated-b') as { enabled: number }).enabled,
|
||||
).toBe(1);
|
||||
cleanup('base-b', 'dependent-b', 'unrelated-b');
|
||||
});
|
||||
|
||||
@@ -467,9 +609,13 @@ describe('PluginRuntimeService dependency gating', () => {
|
||||
const disabled = await runtime.deactivateWithDependents('lib-x');
|
||||
expect(disabled).toEqual(['top-x', 'mid-x', 'lib-x']); // deepest dependent first, root last
|
||||
for (const id of ['lib-x', 'mid-x', 'top-x']) {
|
||||
expect((testDb.prepare('SELECT enabled FROM plugins WHERE id = ?').get(id) as { enabled: number }).enabled).toBe(0);
|
||||
expect((testDb.prepare('SELECT enabled FROM plugins WHERE id = ?').get(id) as { enabled: number }).enabled).toBe(
|
||||
0,
|
||||
);
|
||||
}
|
||||
expect((testDb.prepare('SELECT enabled FROM plugins WHERE id = ?').get('other-x') as { enabled: number }).enabled).toBe(1);
|
||||
expect(
|
||||
(testDb.prepare('SELECT enabled FROM plugins WHERE id = ?').get('other-x') as { enabled: number }).enabled,
|
||||
).toBe(1);
|
||||
cleanup('lib-x', 'mid-x', 'top-x', 'other-x');
|
||||
});
|
||||
});
|
||||
@@ -496,9 +642,15 @@ describe('PluginRuntimeService inter-plugin (exports + events)', () => {
|
||||
} }],
|
||||
};`,
|
||||
);
|
||||
testDb.prepare("INSERT INTO plugins (id, status, version, permissions, config, capabilities, dependencies) VALUES ('lib','inactive','1.5.0','[]','{}',?,'{}')")
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, version, permissions, config, capabilities, dependencies) VALUES ('lib','inactive','1.5.0','[]','{}',?,'{}')",
|
||||
)
|
||||
.run(JSON.stringify({ provides: ['greet'], emits: ['ping'] }));
|
||||
testDb.prepare("INSERT INTO plugins (id, status, version, permissions, config, capabilities, dependencies) VALUES ('consumer','inactive','1.0.0','[]','{}','{}',?)")
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, version, permissions, config, capabilities, dependencies) VALUES ('consumer','inactive','1.0.0','[]','{}','{}',?)",
|
||||
)
|
||||
.run(JSON.stringify({ requiredAddons: [], pluginDependencies: [{ id: 'lib', version: '>=1.0.0 <2.0.0' }] }));
|
||||
await runtime.activate('lib');
|
||||
await runtime.activate('consumer');
|
||||
@@ -518,7 +670,9 @@ describe('PluginRuntimeService inter-plugin (exports + events)', () => {
|
||||
});
|
||||
|
||||
it('refuses a call from a non-dependent and to an undeclared export', async () => {
|
||||
await expect(runtime.callPlugin('lib', 'consumer', 'anything', {}, 7)).rejects.toThrow(/does not declare|not active|does not export/);
|
||||
await expect(runtime.callPlugin('lib', 'consumer', 'anything', {}, 7)).rejects.toThrow(
|
||||
/does not declare|not active|does not export/,
|
||||
);
|
||||
await expect(runtime.callPlugin('consumer', 'lib', 'nope', {}, 7)).rejects.toThrow(/does not export/);
|
||||
});
|
||||
|
||||
@@ -555,7 +709,9 @@ describe('PluginRuntimeService.retrust', () => {
|
||||
assertRetrustable: vi.fn(async (_id: string, key: string) => ({ authorPublicKey: key })),
|
||||
install: vi.fn(async (_id: string, opts?: { retrustKey?: string }) => {
|
||||
testDb
|
||||
.prepare("UPDATE plugins SET author_pubkey = ?, version = '2.0.0', update_block_code = NULL, update_block_version = NULL WHERE id = ?")
|
||||
.prepare(
|
||||
"UPDATE plugins SET author_pubkey = ?, version = '2.0.0', update_block_code = NULL, update_block_version = NULL WHERE id = ?",
|
||||
)
|
||||
.run(opts?.retrustKey, id);
|
||||
return { id, version: '2.0.0' };
|
||||
}),
|
||||
@@ -572,7 +728,9 @@ describe('PluginRuntimeService.retrust', () => {
|
||||
// The condition is re-derived SERVER-side before anything moves — the UI hiding the
|
||||
// button is a convenience, not the control.
|
||||
expect(registry.assertRetrustable).toHaveBeenCalledWith('rt-ok', 'NEWKEY');
|
||||
const row = testDb.prepare("SELECT author_pubkey, version, update_block_code FROM plugins WHERE id='rt-ok'").get() as {
|
||||
const row = testDb
|
||||
.prepare("SELECT author_pubkey, version, update_block_code FROM plugins WHERE id='rt-ok'")
|
||||
.get() as {
|
||||
author_pubkey: string | null;
|
||||
version: string;
|
||||
update_block_code: string | null;
|
||||
@@ -640,7 +798,9 @@ describe('PluginRuntimeService.retrust', () => {
|
||||
await rt.deactivate('rt-act');
|
||||
await rt.activate('rt-act');
|
||||
|
||||
const row = testDb.prepare("SELECT update_block_code, update_block_version FROM plugins WHERE id='rt-act'").get() as {
|
||||
const row = testDb
|
||||
.prepare("SELECT update_block_code, update_block_version FROM plugins WHERE id='rt-act'")
|
||||
.get() as {
|
||||
update_block_code: string;
|
||||
update_block_version: string;
|
||||
};
|
||||
@@ -661,12 +821,19 @@ describe('TREK host-version gating', () => {
|
||||
const seedRanged = (id: string, trekRange: string | null, enabled = 0) => {
|
||||
fs.mkdirSync(path.join(codeRoot, id, 'server'), { recursive: true });
|
||||
fs.writeFileSync(path.join(codeRoot, id, 'server', 'index.js'), 'module.exports = { async onLoad() {} };');
|
||||
testDb.prepare("INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config, trek_range) VALUES (?, ?, ?, '[]', '[]', '{}', ?)")
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config, trek_range) VALUES (?, ?, ?, '[]', '[]', '{}', ?)",
|
||||
)
|
||||
.run(id, enabled ? 'active' : 'inactive', enabled, trekRange);
|
||||
};
|
||||
const cleanup = (...ids: string[]) => { for (const id of ids) testDb.prepare('DELETE FROM plugins WHERE id = ?').run(id); };
|
||||
const cleanup = (...ids: string[]) => {
|
||||
for (const id of ids) testDb.prepare('DELETE FROM plugins WHERE id = ?').run(id);
|
||||
};
|
||||
|
||||
afterEach(() => { delete process.env.APP_VERSION; });
|
||||
afterEach(() => {
|
||||
delete process.env.APP_VERSION;
|
||||
});
|
||||
|
||||
it('refuses to activate a plugin this TREK has outgrown, and says so with a code', async () => {
|
||||
process.env.APP_VERSION = '4.0.0';
|
||||
@@ -683,7 +850,9 @@ describe('TREK host-version gating', () => {
|
||||
it('refuses a plugin that never declared a range at all', async () => {
|
||||
process.env.APP_VERSION = '3.3.0';
|
||||
seedRanged('undeclared', null);
|
||||
await expect((await createPluginRuntime(dbConn)).activate('undeclared')).rejects.toMatchObject({ code: 'TREK_VERSION_UNKNOWN' });
|
||||
await expect((await createPluginRuntime(dbConn)).activate('undeclared')).rejects.toMatchObject({
|
||||
code: 'TREK_VERSION_UNKNOWN',
|
||||
});
|
||||
cleanup('undeclared');
|
||||
});
|
||||
|
||||
@@ -717,8 +886,12 @@ describe('TREK host-version gating', () => {
|
||||
});
|
||||
|
||||
describe('with TREK_PLUGINS_IGNORE_TREK_RANGE set', () => {
|
||||
beforeEach(() => { process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1'; });
|
||||
afterEach(() => { delete process.env.TREK_PLUGINS_IGNORE_TREK_RANGE; });
|
||||
beforeEach(() => {
|
||||
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
|
||||
});
|
||||
afterEach(() => {
|
||||
delete process.env.TREK_PLUGINS_IGNORE_TREK_RANGE;
|
||||
});
|
||||
|
||||
it('activates a plugin this TREK has outgrown, warning in the log instead of refusing', async () => {
|
||||
process.env.APP_VERSION = '4.0.0';
|
||||
@@ -751,8 +924,14 @@ describe('TREK host-version gating', () => {
|
||||
process.env.APP_VERSION = '4.0.0';
|
||||
fs.mkdirSync(path.join(codeRoot, 'both-wrong', 'server'), { recursive: true });
|
||||
fs.writeFileSync(path.join(codeRoot, 'both-wrong', 'server', 'index.js'), 'module.exports = {};');
|
||||
testDb.prepare("INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config, trek_range) VALUES ('both-wrong','inactive',0,'[\"db:own\"]','[]','{}','>=3.2.0 <4.0.0')").run();
|
||||
await expect((await createPluginRuntime(dbConn)).activate('both-wrong')).rejects.toMatchObject({ code: 'TREK_VERSION_INCOMPATIBLE' });
|
||||
testDb
|
||||
.prepare(
|
||||
"INSERT INTO plugins (id, status, enabled, permissions, granted_permissions, config, trek_range) VALUES ('both-wrong','inactive',0,'[\"db:own\"]','[]','{}','>=3.2.0 <4.0.0')",
|
||||
)
|
||||
.run();
|
||||
await expect((await createPluginRuntime(dbConn)).activate('both-wrong')).rejects.toMatchObject({
|
||||
code: 'TREK_VERSION_INCOMPATIBLE',
|
||||
});
|
||||
cleanup('both-wrong');
|
||||
});
|
||||
});
|
||||
@@ -772,7 +951,9 @@ describe('plugin-API version gating', () => {
|
||||
)
|
||||
.run(id, apiVersion);
|
||||
};
|
||||
const cleanup = (...ids: string[]) => { for (const id of ids) testDb.prepare('DELETE FROM plugins WHERE id = ?').run(id); };
|
||||
const cleanup = (...ids: string[]) => {
|
||||
for (const id of ids) testDb.prepare('DELETE FROM plugins WHERE id = ?').run(id);
|
||||
};
|
||||
|
||||
it('refuses to activate a plugin whose apiVersion this TREK does not support', async () => {
|
||||
seedApi('future-api', 2);
|
||||
@@ -787,7 +968,9 @@ describe('plugin-API version gating', () => {
|
||||
process.env.TREK_PLUGINS_IGNORE_TREK_RANGE = '1';
|
||||
try {
|
||||
seedApi('future-api-bypass', 2);
|
||||
await expect((await createPluginRuntime(dbConn)).activate('future-api-bypass')).rejects.toMatchObject({ code: 'API_VERSION_INCOMPATIBLE' });
|
||||
await expect((await createPluginRuntime(dbConn)).activate('future-api-bypass')).rejects.toMatchObject({
|
||||
code: 'API_VERSION_INCOMPATIBLE',
|
||||
});
|
||||
} finally {
|
||||
delete process.env.TREK_PLUGINS_IGNORE_TREK_RANGE;
|
||||
cleanup('future-api-bypass');
|
||||
|
||||
@@ -59,12 +59,40 @@
|
||||
* plugin-runtime.service.ts's own comment at the wrap site) already ran inside a
|
||||
* request context by the time this file's shared `runtime` finished booting.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginEntityMetadata } from '../../../src/db/entities/PluginEntityMetadata.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginMetaMigrations } from '../../../src/db/entities/PluginMetaMigrations.entity';
|
||||
import { PluginOauthState } from '../../../src/db/entities/PluginOauthState.entity';
|
||||
import { PluginOauthTokens } from '../../../src/db/entities/PluginOauthTokens.entity';
|
||||
import { PluginScheduledTasks } from '../../../src/db/entities/PluginScheduledTasks.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginUserErasureQueue } from '../../../src/db/entities/PluginUserErasureQueue.entity';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { Settings } from '../../../src/db/entities/Settings.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
|
||||
import { AuditService } from '../../../src/nest/audit/audit.service';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
import { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { findRow, insertRow } from '../../helpers/factories/rows';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { RequestContext } from '@mikro-orm/core';
|
||||
import { SchedulerRegistry } from '@nestjs/schedule';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { RequestContext } from '@mikro-orm/core';
|
||||
import { SchedulerRegistry } from '@nestjs/schedule';
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
|
||||
|
||||
const h = vi.hoisted(() => ({
|
||||
jobs: [] as Array<{
|
||||
@@ -82,41 +110,19 @@ const h = vi.hoisted(() => ({
|
||||
vi.mock('cron', () => ({
|
||||
CronJob: {
|
||||
from: (opts: { cronTime: string; timeZone?: string; start?: boolean; onTick: () => unknown }) => {
|
||||
const job = { ...opts, stopped: false, stop() { this.stopped = true; } };
|
||||
const job = {
|
||||
...opts,
|
||||
stopped: false,
|
||||
stop() {
|
||||
this.stopped = true;
|
||||
},
|
||||
};
|
||||
h.jobs.push(job);
|
||||
return job;
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';
|
||||
import { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import { AuditService } from '../../../src/nest/audit/audit.service';
|
||||
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
import { createTestAddonsService } from '../../helpers/test-addons';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { findRow, insertRow } from '../../helpers/factories/rows';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import { Plugins } from '../../../src/db/entities/Plugins.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginScheduledTasks } from '../../../src/db/entities/PluginScheduledTasks.entity';
|
||||
import { PluginUserErasureQueue } from '../../../src/db/entities/PluginUserErasureQueue.entity';
|
||||
import { PluginEgressHosts } from '../../../src/db/entities/PluginEgressHosts.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginUserConfig } from '../../../src/db/entities/PluginUserConfig.entity';
|
||||
import { PluginEntityMetadata } from '../../../src/db/entities/PluginEntityMetadata.entity';
|
||||
import { PluginOauthTokens } from '../../../src/db/entities/PluginOauthTokens.entity';
|
||||
import { PluginOauthState } from '../../../src/db/entities/PluginOauthState.entity';
|
||||
import { PluginMetaMigrations } from '../../../src/db/entities/PluginMetaMigrations.entity';
|
||||
import { PluginCapabilityAudit } from '../../../src/db/entities/PluginCapabilityAudit.entity';
|
||||
import { Settings } from '../../../src/db/entities/Settings.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let runtime: PluginRuntimeService;
|
||||
@@ -188,7 +194,9 @@ beforeAll(async () => {
|
||||
// ran, proving the wrap decision without needing either read to touch the ORM
|
||||
// yet (raw SQL until Task 2/3 convert them).
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const preLoopSpy = vi.spyOn(runtime as any, 'installedDepRows').mockImplementation(async function (this: PluginRuntimeService) {
|
||||
const preLoopSpy = vi.spyOn(runtime as any, 'installedDepRows').mockImplementation(async function (
|
||||
this: PluginRuntimeService,
|
||||
) {
|
||||
preLoopContextSeen = RequestContext.currentRequestContext() !== undefined;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return (Object.getPrototypeOf(runtime) as any).installedDepRows.apply(this);
|
||||
@@ -198,9 +206,12 @@ beforeAll(async () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (prevEnabled === undefined) delete process.env.TREK_PLUGINS_ENABLED; else process.env.TREK_PLUGINS_ENABLED = prevEnabled;
|
||||
if (prevDir === undefined) delete process.env.TREK_PLUGINS_DIR; else process.env.TREK_PLUGINS_DIR = prevDir;
|
||||
if (prevDataDir === undefined) delete process.env.TREK_PLUGINS_DATA_DIR; else process.env.TREK_PLUGINS_DATA_DIR = prevDataDir;
|
||||
if (prevEnabled === undefined) delete process.env.TREK_PLUGINS_ENABLED;
|
||||
else process.env.TREK_PLUGINS_ENABLED = prevEnabled;
|
||||
if (prevDir === undefined) delete process.env.TREK_PLUGINS_DIR;
|
||||
else process.env.TREK_PLUGINS_DIR = prevDir;
|
||||
if (prevDataDir === undefined) delete process.env.TREK_PLUGINS_DATA_DIR;
|
||||
else process.env.TREK_PLUGINS_DATA_DIR = prevDataDir;
|
||||
await runtime.onModuleDestroy();
|
||||
await t.close();
|
||||
testDb.close();
|
||||
@@ -234,13 +245,19 @@ describe('PluginRuntimeService scheduler sweep — registered through CronRegist
|
||||
// reads at query time), and it is what a genuine `withRequestContext` wrap
|
||||
// controls, independent of what the wrapped body happens to read.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const fireSpy = vi.spyOn(runtime as any, 'fireDueScheduled').mockImplementation(async function (this: PluginRuntimeService, ...args: unknown[]) {
|
||||
const fireSpy = vi.spyOn(runtime as any, 'fireDueScheduled').mockImplementation(async function (
|
||||
this: PluginRuntimeService,
|
||||
...args: unknown[]
|
||||
) {
|
||||
contextSeen.fireDueScheduled = RequestContext.currentRequestContext() !== undefined;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return (Object.getPrototypeOf(runtime) as any).fireDueScheduled.apply(this, args);
|
||||
});
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const drainSpy = vi.spyOn(runtime as any, 'drainUserErasures').mockImplementation(async function (this: PluginRuntimeService, ...args: unknown[]) {
|
||||
const drainSpy = vi.spyOn(runtime as any, 'drainUserErasures').mockImplementation(async function (
|
||||
this: PluginRuntimeService,
|
||||
...args: unknown[]
|
||||
) {
|
||||
contextSeen.drainUserErasures = RequestContext.currentRequestContext() !== undefined;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return (Object.getPrototypeOf(runtime) as any).drainUserErasures.apply(this, args);
|
||||
@@ -280,7 +297,9 @@ describe('PluginRuntimeService scheduler sweep — registered through CronRegist
|
||||
// Prove the fail-closed error comes from the registrar's own wrapper, not a
|
||||
// side effect of the tick body itself ever having run.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(runtime2 as any, 'fireDueScheduled').mockImplementation(async () => { bodyRan = true; });
|
||||
vi.spyOn(runtime2 as any, 'fireDueScheduled').mockImplementation(async () => {
|
||||
bodyRan = true;
|
||||
});
|
||||
await expect(job2.onTick()).rejects.toThrow(/no MikroORM available/i);
|
||||
expect(bodyRan).toBe(false);
|
||||
} finally {
|
||||
@@ -299,8 +318,20 @@ describe('PluginRuntimeService scheduler sweep — registered through CronRegist
|
||||
// fixture needs one too, or the erasure row would be reaped before ever
|
||||
// reaching the ACK-gated delivery path this test is actually proving.
|
||||
await insertRow(t, Plugins, { id: pluginId, name: pluginId });
|
||||
await insertRow(t, PluginScheduledTasks, { plugin_id: pluginId, name: 'oneshot', due_at: oneShotSeedDueAt, payload: 'null', every_ms: null });
|
||||
await insertRow(t, PluginScheduledTasks, { plugin_id: pluginId, name: 'recurring', due_at: recurringSeedDueAt, payload: 'null', every_ms: 60_000 });
|
||||
await insertRow(t, PluginScheduledTasks, {
|
||||
plugin_id: pluginId,
|
||||
name: 'oneshot',
|
||||
due_at: oneShotSeedDueAt,
|
||||
payload: 'null',
|
||||
every_ms: null,
|
||||
});
|
||||
await insertRow(t, PluginScheduledTasks, {
|
||||
plugin_id: pluginId,
|
||||
name: 'recurring',
|
||||
due_at: recurringSeedDueAt,
|
||||
payload: 'null',
|
||||
every_ms: 60_000,
|
||||
});
|
||||
await insertRow(t, PluginUserErasureQueue, { plugin_id: pluginId, user_id: 4242 });
|
||||
|
||||
// Mark the plugin active without a real child spawn — the same technique
|
||||
@@ -321,11 +352,15 @@ describe('PluginRuntimeService scheduler sweep — registered through CronRegist
|
||||
// delivery is attempted, since a crash here must never double-fire.
|
||||
if (name === 'oneshot') {
|
||||
// test-sql-allow: read synchronously inside the delivery call, so it sees the row at that very moment.
|
||||
const row = testDb.prepare('SELECT id FROM plugin_scheduled_tasks WHERE plugin_id=? AND name=?').get(id, 'oneshot');
|
||||
const row = testDb
|
||||
.prepare('SELECT id FROM plugin_scheduled_tasks WHERE plugin_id=? AND name=?')
|
||||
.get(id, 'oneshot');
|
||||
expect(row).toBeUndefined(); // already deleted before delivery
|
||||
} else if (name === 'recurring') {
|
||||
// test-sql-allow: read synchronously inside the delivery call, so it sees the row at that very moment.
|
||||
const row = testDb.prepare('SELECT due_at FROM plugin_scheduled_tasks WHERE plugin_id=? AND name=?').get(id, 'recurring') as { due_at: number } | undefined;
|
||||
const row = testDb
|
||||
.prepare('SELECT due_at FROM plugin_scheduled_tasks WHERE plugin_id=? AND name=?')
|
||||
.get(id, 'recurring') as { due_at: number } | undefined;
|
||||
expect(row).toBeDefined();
|
||||
expect(row!.due_at).toBeGreaterThan(recurringSeedDueAt); // already re-armed before delivery
|
||||
}
|
||||
@@ -338,8 +373,12 @@ describe('PluginRuntimeService scheduler sweep — registered through CronRegist
|
||||
await settle();
|
||||
|
||||
// Same-shape delivery calls the legacy setInterval-driven sweep made.
|
||||
expect(invokeCalls.filter((c) => c.method === 'invoke.scheduled').map((c) => (c.payload as { name: string }).name).sort())
|
||||
.toEqual(['oneshot', 'recurring']);
|
||||
expect(
|
||||
invokeCalls
|
||||
.filter((c) => c.method === 'invoke.scheduled')
|
||||
.map((c) => (c.payload as { name: string }).name)
|
||||
.sort(),
|
||||
).toEqual(['oneshot', 'recurring']);
|
||||
expect(invokeCalls).toContainEqual({ method: 'invoke.deleteUserData', payload: { userId: 4242 } });
|
||||
|
||||
const oneShotRow = await findRow(t, PluginScheduledTasks, { plugin_id: pluginId, name: 'oneshot' });
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,18 +7,23 @@
|
||||
* - disable() tears the child down.
|
||||
* The child runs its own process — its crash/throw can never reach this test.
|
||||
*/
|
||||
import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';
|
||||
import { createTestPluginRegistry } from '../../../src/nest-rpc/rpc-kit/testing';
|
||||
import { PluginDataDb } from '../../../src/nest/plugins/host/plugin-data.service';
|
||||
import { PluginRpcHost, type HostDeps } from '../../../src/nest/plugins/host/rpc-host';
|
||||
import { DbRpc } from '../../../src/nest/plugins/host/rpc/db.rpc';
|
||||
import type { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
import {
|
||||
PluginSupervisor,
|
||||
type SupervisorHooks,
|
||||
type SupervisorTuning,
|
||||
} from '../../../src/nest/plugins/supervisor/plugin-supervisor';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import Database from 'better-sqlite3';
|
||||
import { PluginSupervisor, type SupervisorHooks, type SupervisorTuning } from '../../../src/nest/plugins/supervisor/plugin-supervisor';
|
||||
import { PluginRpcHost, type HostDeps } from '../../../src/nest/plugins/host/rpc-host';
|
||||
import { PluginDataDb } from '../../../src/nest/plugins/host/plugin-data.service';
|
||||
import { createTestPluginRegistry } from '../../../src/nest-rpc/rpc-kit/testing';
|
||||
import { DbRpc } from '../../../src/nest/plugins/host/rpc/db.rpc';
|
||||
import type { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';
|
||||
|
||||
/**
|
||||
* DbRpc also carries `settings.get`, which needs the per-user settings store. No
|
||||
@@ -40,16 +45,26 @@ function writePlugin(id: string, source: string): void {
|
||||
fs.writeFileSync(path.join(dir, 'index.js'), source);
|
||||
}
|
||||
|
||||
function makeSupervisor(events: Array<{ topic: string; data: unknown }>, tuning: SupervisorTuning = {}): PluginSupervisor {
|
||||
function makeSupervisor(
|
||||
events: Array<{ topic: string; data: unknown }>,
|
||||
tuning: SupervisorTuning = {},
|
||||
): PluginSupervisor {
|
||||
const createRpcHost = (id: string, granted: ReadonlySet<string>): PluginRpcHost => {
|
||||
const deps: HostDeps = {
|
||||
data: new PluginDataDb(id),
|
||||
callPlugin: async () => undefined,
|
||||
emitPluginEvent: async (event, payload) => { broadcasts.push({ id, event, payload }); },
|
||||
emitPluginEvent: async (event, payload) => {
|
||||
broadcasts.push({ id, event, payload });
|
||||
},
|
||||
};
|
||||
// Only db.* is exercised from a child here; the rest of the surface has its own
|
||||
// unit suites and would drag every domain service into this integration test.
|
||||
return new PluginRpcHost(id, granted, deps, createTestPluginRegistry([new DbRpc(stubUserSettings as PluginUserSettingsService)]));
|
||||
return new PluginRpcHost(
|
||||
id,
|
||||
granted,
|
||||
deps,
|
||||
createTestPluginRegistry([new DbRpc(stubUserSettings as PluginUserSettingsService)]),
|
||||
);
|
||||
};
|
||||
const hooks: SupervisorHooks = {
|
||||
onEvent: (_id, topic, data) => events.push({ topic, data }),
|
||||
@@ -144,7 +159,12 @@ describe('PluginSupervisor — isolated runtime', () => {
|
||||
await sup.activate('provider', new Set(['hook:place-detail-provider', 'events:subscribe']), {});
|
||||
|
||||
// host->plugin hook: the child runs getDetails(7, ctx) and returns its result
|
||||
const hookRes = await sup.invoke('provider', 'invoke.hook', { hook: 'placeDetailProvider', fn: 'getDetails', args: [7] }, { actingUserId: 5 });
|
||||
const hookRes = await sup.invoke(
|
||||
'provider',
|
||||
'invoke.hook',
|
||||
{ hook: 'placeDetailProvider', fn: 'getDetails', args: [7] },
|
||||
{ actingUserId: 5 },
|
||||
);
|
||||
expect(hookRes).toEqual([{ label: 'placeId', value: '7' }]);
|
||||
|
||||
// host->plugin event: ONLY the matching subscription runs (the 'other:thing' one throws if hit)
|
||||
|
||||
Reference in New Issue
Block a user