Spaces:
Runtime error
Runtime error
File size: 13,408 Bytes
46252cd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | import { ConfigService } from '@nestjs/config';
import { ModuleRef } from '@nestjs/core';
import { PluginLoaderService } from './plugin-loader.service';
import { PluginStorageService } from './plugin-storage.service';
import { HookManager } from '../hooks';
import {
PluginCapabilityError,
PluginContext,
PluginInstance,
PluginManifest,
PluginStatus,
PluginType,
} from './plugin.interfaces';
import { MessageService } from '../../modules/message/message.service';
import { SessionService } from '../../modules/session/session.service';
function makePlugin(
sessions?: string[],
permissions: string[] = ['messages:send', 'engine:read'],
activeSessions?: string[],
sessionScoped?: boolean,
): PluginInstance {
const manifest: PluginManifest = {
id: 'test-ext',
name: 'Test Extension',
version: '1.0.0',
type: PluginType.EXTENSION,
main: 'index.ts',
sessions,
permissions,
sessionScoped,
};
return { manifest, status: PluginStatus.INSTALLED, config: {}, instance: null, activeSessions };
}
describe('PluginLoaderService capability facade — ctx.messages', () => {
let loader: PluginLoaderService;
let messageService: { sendText: jest.Mock; reply: jest.Mock };
let sessionService: { getEngine: jest.Mock };
let moduleRef: { get: jest.Mock };
beforeEach(() => {
messageService = {
sendText: jest.fn().mockResolvedValue({ messageId: 'wamid', timestamp: 1 }),
reply: jest.fn().mockResolvedValue({ messageId: 'wamid', timestamp: 1 }),
};
sessionService = { getEngine: jest.fn().mockReturnValue({}) }; // truthy live engine
moduleRef = {
get: jest
.fn()
.mockImplementation((token: unknown) => (token === SessionService ? sessionService : messageService)),
};
const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
const pluginStorage = {
createPluginStorage: jest.fn().mockReturnValue({}),
} as unknown as PluginStorageService;
loader = new PluginLoaderService(
configService,
new HookManager(),
pluginStorage,
moduleRef as unknown as ModuleRef,
);
});
function contextFor(plugin: PluginInstance): PluginContext {
return (loader as unknown as { createPluginContext: (p: PluginInstance) => PluginContext }).createPluginContext(
plugin,
);
}
it('messages.sendText delegates to MessageService.sendText with a wrapped dto', async () => {
const ctx = contextFor(makePlugin(['*']));
await ctx.messages.sendText('sess-1', '628@c.us', 'hi');
expect(moduleRef.get).toHaveBeenCalledWith(MessageService, { strict: false });
expect(messageService.sendText).toHaveBeenCalledWith('sess-1', { chatId: '628@c.us', text: 'hi' });
});
it('messages.reply delegates to MessageService.reply', async () => {
const ctx = contextFor(makePlugin(['*']));
await ctx.messages.reply('sess-1', '628@c.us', 'quoted-id', 'pong');
expect(moduleRef.get).toHaveBeenCalledWith(MessageService, { strict: false });
expect(messageService.reply).toHaveBeenCalledWith('sess-1', {
chatId: '628@c.us',
quotedMessageId: 'quoted-id',
text: 'pong',
});
});
it('allows any session when manifest.sessions is absent (defaults to all)', async () => {
const ctx = contextFor(makePlugin()); // no sessions field
await ctx.messages.sendText('any-session', '628@c.us', 'hi');
expect(messageService.sendText).toHaveBeenCalledWith('any-session', { chatId: '628@c.us', text: 'hi' });
});
it('rejects an out-of-scope session BEFORE resolving the service', async () => {
const ctx = contextFor(makePlugin(['allowed-session']));
await expect(ctx.messages.sendText('other-session', '628@c.us', 'hi')).rejects.toBeInstanceOf(
PluginCapabilityError,
);
expect(moduleRef.get).not.toHaveBeenCalled();
expect(messageService.sendText).not.toHaveBeenCalled();
});
it('denies sendText when the plugin is DEACTIVATED for the session, even if manifest.sessions is ["*"]', async () => {
// manifest allows all sessions, but the operator activated the plugin only for sess-1 — a capability
// call to sess-2 must be denied (per-session activation is a real boundary, not just a hook filter).
const ctx = contextFor(makePlugin(['*'], ['messages:send', 'engine:read'], ['sess-1']));
await expect(ctx.messages.sendText('sess-2', '628@c.us', 'hi')).rejects.toBeInstanceOf(PluginCapabilityError);
expect(moduleRef.get).not.toHaveBeenCalled();
expect(messageService.sendText).not.toHaveBeenCalled();
});
it('allows sendText when the plugin IS activated for the session', async () => {
const ctx = contextFor(makePlugin(['*'], ['messages:send', 'engine:read'], ['sess-1']));
await ctx.messages.sendText('sess-1', '628@c.us', 'hi');
expect(messageService.sendText).toHaveBeenCalledWith('sess-1', { chatId: '628@c.us', text: 'hi' });
});
it('allows any session when activeSessions is undefined (operator never restricted it)', async () => {
const ctx = contextFor(makePlugin(['*'], ['messages:send', 'engine:read'], undefined));
await ctx.messages.sendText('whatever', '628@c.us', 'hi');
expect(messageService.sendText).toHaveBeenCalledWith('whatever', { chatId: '628@c.us', text: 'hi' });
});
it('a global (sessionScoped:false) plugin is allowed on any session regardless of activeSessions', async () => {
const ctx = contextFor(makePlugin(['*'], ['messages:send', 'engine:read'], [], false));
await ctx.messages.sendText('sess-9', '628@c.us', 'hi');
expect(messageService.sendText).toHaveBeenCalledWith('sess-9', { chatId: '628@c.us', text: 'hi' });
});
it('rejects sendText with PluginCapabilityError when the session has no active engine', async () => {
sessionService.getEngine.mockReturnValue(undefined);
const ctx = contextFor(makePlugin(['*']));
await expect(ctx.messages.sendText('dead-session', '628@c.us', 'hi')).rejects.toBeInstanceOf(PluginCapabilityError);
expect(messageService.sendText).not.toHaveBeenCalled();
});
it('denies sendText when the plugin does not declare the messages:send permission', async () => {
const ctx = contextFor(makePlugin(['*'], [])); // no permissions
await expect(ctx.messages.sendText('sess-1', '628@c.us', 'hi')).rejects.toBeInstanceOf(PluginCapabilityError);
expect(moduleRef.get).not.toHaveBeenCalled();
expect(messageService.sendText).not.toHaveBeenCalled();
});
it('denies reply when the plugin does not declare the messages:send permission', async () => {
const ctx = contextFor(makePlugin(['*'], []));
await expect(ctx.messages.reply('sess-1', '628@c.us', 'q', 'hi')).rejects.toBeInstanceOf(PluginCapabilityError);
expect(messageService.reply).not.toHaveBeenCalled();
});
});
describe('PluginLoaderService capability facade — ctx.engine', () => {
let loader: PluginLoaderService;
let moduleRef: { get: jest.Mock };
function build(getEngineReturn: unknown): { sessionService: { getEngine: jest.Mock } } {
const sessionService = { getEngine: jest.fn().mockReturnValue(getEngineReturn) };
moduleRef = { get: jest.fn().mockReturnValue(sessionService) };
const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
const pluginStorage = {
createPluginStorage: jest.fn().mockReturnValue({}),
} as unknown as PluginStorageService;
loader = new PluginLoaderService(
configService,
new HookManager(),
pluginStorage,
moduleRef as unknown as ModuleRef,
);
return { sessionService };
}
function contextFor(plugin: PluginInstance): PluginContext {
return (loader as unknown as { createPluginContext: (p: PluginInstance) => PluginContext }).createPluginContext(
plugin,
);
}
it('engine.getGroupInfo delegates to SessionService.getEngine(id).getGroupInfo', async () => {
const engine = { getGroupInfo: jest.fn().mockResolvedValue({ id: 'g@g.us' }) };
const { sessionService } = build(engine);
const ctx = contextFor(makePlugin(['*']));
await ctx.engine.getGroupInfo('sess-1', 'g@g.us');
expect(moduleRef.get).toHaveBeenCalledWith(SessionService, { strict: false });
expect(sessionService.getEngine).toHaveBeenCalledWith('sess-1');
expect(engine.getGroupInfo).toHaveBeenCalledWith('g@g.us');
});
it('throws PluginCapabilityError when the session has no active engine', async () => {
build(undefined);
const ctx = contextFor(makePlugin(['*']));
await expect(ctx.engine.getContacts('dead-session')).rejects.toBeInstanceOf(PluginCapabilityError);
});
it('rejects an out-of-scope session before resolving the engine', async () => {
const { sessionService } = build({ getChats: jest.fn() });
const ctx = contextFor(makePlugin(['allowed']));
await expect(ctx.engine.getChats('other')).rejects.toBeInstanceOf(PluginCapabilityError);
expect(sessionService.getEngine).not.toHaveBeenCalled();
});
it('denies engine.getGroupInfo when the plugin does not declare the engine:read permission', async () => {
const { sessionService } = build({ getGroupInfo: jest.fn() });
const ctx = contextFor(makePlugin(['*'], ['messages:send'])); // has messages, lacks engine:read
await expect(ctx.engine.getGroupInfo('sess-1', 'g@g.us')).rejects.toBeInstanceOf(PluginCapabilityError);
expect(sessionService.getEngine).not.toHaveBeenCalled();
});
it('denies engine reads when the plugin is deactivated for the session (activeSessions excludes it)', async () => {
const { sessionService } = build({ getGroupInfo: jest.fn() });
const ctx = contextFor(makePlugin(['*'], ['engine:read'], ['sess-1']));
await expect(ctx.engine.getGroupInfo('sess-2', 'g@g.us')).rejects.toBeInstanceOf(PluginCapabilityError);
expect(sessionService.getEngine).not.toHaveBeenCalled();
});
it('allows engine.getGroupInfo when the plugin declares engine:read', async () => {
const engine = { getGroupInfo: jest.fn().mockResolvedValue({ id: 'g@g.us' }) };
build(engine);
const ctx = contextFor(makePlugin(['*'], ['engine:read']));
await ctx.engine.getGroupInfo('sess-1', 'g@g.us');
expect(engine.getGroupInfo).toHaveBeenCalledWith('g@g.us');
});
it('engine.getChatHistory delegates to the engine and clamps the limit to 100', async () => {
const engine = { getChatHistory: jest.fn().mockResolvedValue([]) };
build(engine);
const ctx = contextFor(makePlugin(['*'], ['engine:read']));
await ctx.engine.getChatHistory('sess-1', 'c@c.us', 500, true);
expect(engine.getChatHistory).toHaveBeenCalledWith('c@c.us', 100, true); // 500 clamped to 100
});
it('engine.getChatHistory defaults the limit and clamps a non-positive value to 1', async () => {
const engine = { getChatHistory: jest.fn().mockResolvedValue([]) };
build(engine);
const ctx = contextFor(makePlugin(['*'], ['engine:read']));
await ctx.engine.getChatHistory('sess-1', 'c@c.us'); // no limit → default 50, includeMedia → false
await ctx.engine.getChatHistory('sess-1', 'c@c.us', 0);
expect(engine.getChatHistory).toHaveBeenNthCalledWith(1, 'c@c.us', 50, false);
expect(engine.getChatHistory).toHaveBeenNthCalledWith(2, 'c@c.us', 1, false);
});
it('denies engine.getChatHistory without the engine:read permission', async () => {
const { sessionService } = build({ getChatHistory: jest.fn() });
const ctx = contextFor(makePlugin(['*'], ['messages:send']));
await expect(ctx.engine.getChatHistory('sess-1', 'c@c.us')).rejects.toBeInstanceOf(PluginCapabilityError);
expect(sessionService.getEngine).not.toHaveBeenCalled();
});
});
describe('PluginLoaderService capability facade — ctx.net', () => {
function loaderWith(): PluginLoaderService {
const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
const pluginStorage = { createPluginStorage: jest.fn().mockReturnValue({}) } as unknown as PluginStorageService;
return new PluginLoaderService(configService, new HookManager(), pluginStorage, {
get: jest.fn(),
} as unknown as ModuleRef);
}
function netPlugin(permissions: string[], allow?: string[]): PluginInstance {
const manifest: PluginManifest = {
id: 'net-ext',
name: 'Net Extension',
version: '1.0.0',
type: PluginType.EXTENSION,
main: 'index.ts',
permissions,
net: allow ? { allow } : undefined,
};
return { manifest, status: PluginStatus.INSTALLED, config: {}, instance: null };
}
function contextFor(loader: PluginLoaderService, plugin: PluginInstance): PluginContext {
return (loader as unknown as { createPluginContext: (p: PluginInstance) => PluginContext }).createPluginContext(
plugin,
);
}
it('denies net.fetch when the plugin does not declare net:fetch', async () => {
const ctx = contextFor(loaderWith(), netPlugin([], ['*']));
await expect(ctx.net.fetch('https://api.example.com/x')).rejects.toBeInstanceOf(PluginCapabilityError);
});
it('denies net.fetch when the host is not in the manifest net.allow list', async () => {
const ctx = contextFor(loaderWith(), netPlugin(['net:fetch'], ['only.example.com:443']));
await expect(ctx.net.fetch('https://api.example.com/x')).rejects.toBeInstanceOf(PluginCapabilityError);
});
});
|