javascript-solid-server 0.0.214 → 0.0.216
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/jss.js +5 -0
- package/docs/configuration.md +44 -0
- package/package.json +1 -1
- package/src/plugins.js +200 -0
- package/src/server.js +21 -0
- package/test/plugins.test.js +252 -0
package/bin/jss.js
CHANGED
|
@@ -268,6 +268,11 @@ program
|
|
|
268
268
|
mongoUrl: config.mongoUrl,
|
|
269
269
|
mongoDatabase: config.mongoDatabase,
|
|
270
270
|
mcp: config.mcp,
|
|
271
|
+
// Config-file-only keys (no CLI flags yet): omitting them here made
|
|
272
|
+
// the documented `-c config.json` route silently boot without the
|
|
273
|
+
// declared apps (#592).
|
|
274
|
+
appPaths: config.appPaths,
|
|
275
|
+
plugins: config.plugins,
|
|
271
276
|
});
|
|
272
277
|
|
|
273
278
|
await server.listen({ port: config.port, host: config.host });
|
package/docs/configuration.md
CHANGED
|
@@ -389,6 +389,50 @@ for the design discussion and
|
|
|
389
389
|
for a complete example (a multiplayer game where pod WebIDs are the player
|
|
390
390
|
accounts).
|
|
391
391
|
|
|
392
|
+
## App Plugins (plugins)
|
|
393
|
+
|
|
394
|
+
The plugin loader
|
|
395
|
+
([#206](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/206))
|
|
396
|
+
does the appPaths wiring for you: declare the apps in config and the server
|
|
397
|
+
imports, mounts, and tears them down itself.
|
|
398
|
+
|
|
399
|
+
```js
|
|
400
|
+
const fastify = createServer({
|
|
401
|
+
root: './data',
|
|
402
|
+
idp: true,
|
|
403
|
+
plugins: [
|
|
404
|
+
{ module: 'tideholm/jss-plugin/tideholm-jss.js', prefix: '/tideholm',
|
|
405
|
+
config: { bots: 8 } },
|
|
406
|
+
{ module: './my-app/plugin.js', prefix: '/myapp' },
|
|
407
|
+
],
|
|
408
|
+
});
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
Each entry:
|
|
412
|
+
|
|
413
|
+
- `module` — import specifier: a package path (resolved from JSS's module
|
|
414
|
+
graph) or a file path (`./…` or absolute, resolved from the process cwd).
|
|
415
|
+
The module exports `activate(api)`, called during startup.
|
|
416
|
+
- `prefix` — the app's mount point. Added to `appPaths` automatically, so
|
|
417
|
+
the app owns authentication below it (see the section above). Must start
|
|
418
|
+
with `/`; invalid prefixes fail startup.
|
|
419
|
+
- `config` — passed to the plugin verbatim as `api.config`.
|
|
420
|
+
- `id` — optional stable identifier (defaults to a name derived from
|
|
421
|
+
`module`); names the plugin's private data dir, so set it explicitly if
|
|
422
|
+
you load two plugins whose specifiers reduce to the same name.
|
|
423
|
+
|
|
424
|
+
`activate(api)` receives: `api.fastify` (register routes here),
|
|
425
|
+
`api.prefix`, `api.config`, `api.log`, `api.auth.getAgent(request)`
|
|
426
|
+
(identity, as above), `api.storage.pluginDir()` (a private server-side
|
|
427
|
+
directory under the data root, never served over HTTP), and
|
|
428
|
+
`api.ws.route(path, (socket, request) => {})` for WebSocket endpoints —
|
|
429
|
+
routed through the same upgrade path as the built-in realtime features, so
|
|
430
|
+
plugins never attach their own `'upgrade'` listener. Return
|
|
431
|
+
`{ deactivate }` to run teardown (state saves, timers) on server close.
|
|
432
|
+
|
|
433
|
+
A plugin that fails to import or activate fails `listen()` loudly rather
|
|
434
|
+
than booting a server silently missing an app.
|
|
435
|
+
|
|
392
436
|
## Storage Quotas
|
|
393
437
|
|
|
394
438
|
Limit storage per pod to prevent abuse and manage resources:
|
package/package.json
CHANGED
package/src/plugins.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin loader — the #206 seam, assembled from its shipped parts.
|
|
3
|
+
*
|
|
4
|
+
* createServer({
|
|
5
|
+
* plugins: [
|
|
6
|
+
* { module: 'tideholm/jss-plugin/tideholm-jss.js', prefix: '/tideholm',
|
|
7
|
+
* config: { bots: 8 } },
|
|
8
|
+
* { module: './my-app/plugin.js', prefix: '/myapp' },
|
|
9
|
+
* ],
|
|
10
|
+
* })
|
|
11
|
+
*
|
|
12
|
+
* Each entry's module is imported and its exported `activate(api)` called
|
|
13
|
+
* during server startup (before listen completes). The api wires the seams
|
|
14
|
+
* every plugin consumer so far has needed:
|
|
15
|
+
*
|
|
16
|
+
* api.fastify scoped Fastify instance to register routes on
|
|
17
|
+
* api.prefix the entry's mount prefix ('' when none)
|
|
18
|
+
* api.config the entry's config object, verbatim
|
|
19
|
+
* api.log server logger
|
|
20
|
+
* api.auth.getAgent(req) -> agent id string | null (#584)
|
|
21
|
+
* api.storage.pluginDir() -> private server-side data dir for this plugin
|
|
22
|
+
* api.ws.route(path, (socket, request) => {}) (#588)
|
|
23
|
+
*
|
|
24
|
+
* The entry's `prefix` is added to appPaths automatically (#582), so the
|
|
25
|
+
* plugin owns authentication and authorization under its mount — the same
|
|
26
|
+
* deal the bundled pseudo-plugins (idp, /db, /storage/…) already have.
|
|
27
|
+
*
|
|
28
|
+
* ws.route registers WebSocket endpoints through @fastify/websocket — the
|
|
29
|
+
* same single upgrade path the bundled realtime features (nostr relay,
|
|
30
|
+
* tunnel, notifications…) use — so plugins never attach their own 'upgrade'
|
|
31
|
+
* listener. That matters: node only auto-destroys stray upgrade attempts
|
|
32
|
+
* while the server has NO 'upgrade' listener, so a plugin attaching one
|
|
33
|
+
* would become responsible for every unclaimed socket on the host (#588).
|
|
34
|
+
* The handler receives the raw ws socket; a plugin with its own
|
|
35
|
+
* WebSocketServer({ noServer: true }) can feed it straight in:
|
|
36
|
+
* api.ws.route('/myapp/ws', (socket, req) => wss.emit('connection', socket, req));
|
|
37
|
+
*
|
|
38
|
+
* activate() may return { deactivate() {} }; deactivate runs on server
|
|
39
|
+
* close (world saves, timer teardown). A plugin that fails to load fails
|
|
40
|
+
* the boot loudly — the operator wrote the config, and a server silently
|
|
41
|
+
* missing an app is worse than one that refuses to start.
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
import fs from 'fs';
|
|
45
|
+
import path from 'path';
|
|
46
|
+
import { pathToFileURL } from 'url';
|
|
47
|
+
import websocket from '@fastify/websocket';
|
|
48
|
+
import { getAgent } from '../auth.js';
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* api.log speaks both dialects: pino-style (info/warn/error/debug, what
|
|
52
|
+
* fastify.log is) and console-style (log/error, what plain node apps
|
|
53
|
+
* expect) — plugins shouldn't need to know which logger the host runs.
|
|
54
|
+
*/
|
|
55
|
+
export function makePluginLog(base) {
|
|
56
|
+
const call = (level) => (...args) => {
|
|
57
|
+
const fn = base?.[level] ?? base?.info ?? base?.log;
|
|
58
|
+
if (typeof fn === 'function') fn.call(base, ...args);
|
|
59
|
+
};
|
|
60
|
+
return { log: call('info'), info: call('info'), warn: call('warn'), error: call('error'), debug: call('debug') };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Same normalization appPaths applies: no trailing slash, must be '/x…'. */
|
|
64
|
+
export function normalizePrefix(p) {
|
|
65
|
+
if (typeof p !== 'string') return '';
|
|
66
|
+
const trimmed = p.trim().replace(/\/+$/, '');
|
|
67
|
+
return trimmed.startsWith('/') && trimmed.length > 1 ? trimmed : '';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Directory-safe plugin id: entry.id, or derived from the module spec.
|
|
72
|
+
* Bare package specifiers keep their full path ('@scope/pkg/plugin.js' ->
|
|
73
|
+
* 'scope-pkg-plugin') so same-named files in different packages don't
|
|
74
|
+
* collide; file paths use the basename, because a machine-specific
|
|
75
|
+
* directory prefix must not name the plugin's data dir (the id — and with
|
|
76
|
+
* it pluginDir — would change whenever the deployment moves). The loader
|
|
77
|
+
* additionally rejects duplicate ids, so any residual collision fails the
|
|
78
|
+
* boot instead of silently sharing storage.
|
|
79
|
+
*/
|
|
80
|
+
export function pluginId(spec) {
|
|
81
|
+
const module = String(spec.module);
|
|
82
|
+
const raw = typeof spec.id === 'string' && spec.id
|
|
83
|
+
? spec.id
|
|
84
|
+
: (module.startsWith('.') || path.isAbsolute(module)
|
|
85
|
+
? path.basename(module)
|
|
86
|
+
: module
|
|
87
|
+
).replace(/\.[cm]?js$/, '');
|
|
88
|
+
const id = raw.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
|
|
89
|
+
if (!id) throw new Error(`plugins: cannot derive an id from ${JSON.stringify(spec.module)}; set entry.id`);
|
|
90
|
+
return id;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Load and activate every plugin entry. Called from createServer inside a
|
|
95
|
+
* fastify.register scope, so `fastify` here is that scope; routes and hooks
|
|
96
|
+
* plugins add land on the running server.
|
|
97
|
+
*
|
|
98
|
+
* @param {object} fastify scoped instance the plugins register on
|
|
99
|
+
* @param {Array} entries options.plugins, verbatim
|
|
100
|
+
* @param {object} ctx { appPaths, root, log }
|
|
101
|
+
*/
|
|
102
|
+
export async function loadPlugins(fastify, entries, ctx) {
|
|
103
|
+
const log = makePluginLog(ctx.log);
|
|
104
|
+
const seenIds = new Set();
|
|
105
|
+
for (const entry of entries) {
|
|
106
|
+
const spec = typeof entry === 'string' ? { module: entry } : entry;
|
|
107
|
+
if (!spec || typeof spec.module !== 'string' || !spec.module) {
|
|
108
|
+
throw new Error('plugins: each entry needs a module (import specifier or path)');
|
|
109
|
+
}
|
|
110
|
+
const id = pluginId(spec);
|
|
111
|
+
if (seenIds.has(id)) {
|
|
112
|
+
throw new Error(`plugins: duplicate id '${id}' — set entry.id to keep the plugins' data dirs apart`);
|
|
113
|
+
}
|
|
114
|
+
seenIds.add(id);
|
|
115
|
+
|
|
116
|
+
// Paths resolve from the operator's cwd; bare specifiers stay package
|
|
117
|
+
// imports resolved from JSS's own module graph.
|
|
118
|
+
const href = spec.module.startsWith('.') || path.isAbsolute(spec.module)
|
|
119
|
+
? pathToFileURL(path.resolve(spec.module)).href
|
|
120
|
+
: spec.module;
|
|
121
|
+
let mod;
|
|
122
|
+
try {
|
|
123
|
+
mod = await import(href);
|
|
124
|
+
} catch (err) {
|
|
125
|
+
throw new Error(`plugin ${id}: cannot import ${spec.module}: ${err.message}`);
|
|
126
|
+
}
|
|
127
|
+
const activate = mod.activate ?? mod.default;
|
|
128
|
+
if (typeof activate !== 'function') {
|
|
129
|
+
throw new Error(`plugin ${id}: module exports no activate(api) function`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Any provided prefix must validate — a falsy one ('', 0) silently
|
|
133
|
+
// skipping the appPaths exemption would mount the app behind WAC.
|
|
134
|
+
// Omit the property entirely for a plugin with no mount prefix.
|
|
135
|
+
const prefix = normalizePrefix(spec.prefix);
|
|
136
|
+
if (spec.prefix !== undefined && !prefix) {
|
|
137
|
+
throw new Error(`plugin ${id}: invalid prefix ${JSON.stringify(spec.prefix)} (must start with '/'; omit for none)`);
|
|
138
|
+
}
|
|
139
|
+
if (prefix) ctx.appPaths.push(prefix); // WAC exemption under the mount (#582)
|
|
140
|
+
|
|
141
|
+
const api = {
|
|
142
|
+
fastify,
|
|
143
|
+
prefix,
|
|
144
|
+
config: spec.config ?? {},
|
|
145
|
+
log,
|
|
146
|
+
auth: { getAgent },
|
|
147
|
+
storage: {
|
|
148
|
+
// Under the data root's dot-guard (like .idp): never served over LDP.
|
|
149
|
+
pluginDir() {
|
|
150
|
+
const dir = path.join(ctx.root, '.plugins', id);
|
|
151
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
152
|
+
return dir;
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
ws: {
|
|
156
|
+
async route(wsPath, handler) {
|
|
157
|
+
if (typeof wsPath !== 'string' || !wsPath.startsWith('/')) {
|
|
158
|
+
throw new Error(`plugin ${id}: ws.route path must start with '/'`);
|
|
159
|
+
}
|
|
160
|
+
if (!fastify.websocketServer) {
|
|
161
|
+
await fastify.register(websocket);
|
|
162
|
+
}
|
|
163
|
+
fastify.get(wsPath, { websocket: true }, (connection, request) => {
|
|
164
|
+
// @fastify/websocket v8 hands a SocketStream; the ws socket is
|
|
165
|
+
// .socket. Later majors hand the socket directly — accept both.
|
|
166
|
+
const socket = connection.socket ?? connection;
|
|
167
|
+
// A plugin bug here must not become an unhandled rejection that
|
|
168
|
+
// takes the host down: log it and close the one affected socket.
|
|
169
|
+
try {
|
|
170
|
+
Promise.resolve(handler(socket, request)).catch((err) => {
|
|
171
|
+
log.error(`plugin ${id}: ws handler failed: ${err.message}`);
|
|
172
|
+
socket.terminate?.();
|
|
173
|
+
});
|
|
174
|
+
} catch (err) {
|
|
175
|
+
log.error(`plugin ${id}: ws handler failed: ${err.message}`);
|
|
176
|
+
socket.terminate?.();
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
let result;
|
|
184
|
+
try {
|
|
185
|
+
result = await activate(api);
|
|
186
|
+
} catch (err) {
|
|
187
|
+
throw new Error(`plugin ${id}: activate() failed: ${err.message}`);
|
|
188
|
+
}
|
|
189
|
+
if (result && typeof result.deactivate === 'function') {
|
|
190
|
+
fastify.addHook('onClose', async () => {
|
|
191
|
+
try {
|
|
192
|
+
await result.deactivate();
|
|
193
|
+
} catch (err) {
|
|
194
|
+
log.warn(`plugin ${id}: deactivate() failed: ${err.message}`);
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
log.info(`plugin ${id} active${prefix ? ` at ${prefix}` : ''}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
package/src/server.js
CHANGED
|
@@ -60,6 +60,9 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
|
60
60
|
* @param {string} options.apNostrPubkey - Nostr pubkey for identity linking
|
|
61
61
|
* @param {boolean} options.webidTls - Enable WebID-TLS client certificate auth (default false)
|
|
62
62
|
* @param {boolean} options.pay - Enable HTTP 402 paid /pay/* routes (default false)
|
|
63
|
+
* @param {Array} options.plugins - App plugins to load (#206): [{ module, prefix, config, id }].
|
|
64
|
+
* Each module's activate(api) runs at startup; prefix is WAC-exempted via appPaths.
|
|
65
|
+
* See src/plugins.js for the api surface.
|
|
63
66
|
* @param {number} options.payCost - Cost per request in satoshis (default 1)
|
|
64
67
|
* @param {string} options.payMempoolUrl - Mempool API base URL (default testnet4)
|
|
65
68
|
* @param {string} options.payAddress - Pod's MRC20 address for receiving token transfers
|
|
@@ -117,6 +120,10 @@ export function createServer(options = {}) {
|
|
|
117
120
|
.map((p) => p.trim().replace(/\/+$/, '')) // '/myapp/' matches like '/myapp'
|
|
118
121
|
.filter((p) => p.startsWith('/') && p.length > 1)
|
|
119
122
|
: [];
|
|
123
|
+
// App plugins (#206): loaded at startup, each entry's prefix joins
|
|
124
|
+
// appPaths. The WAC hook reads the array per request, so pushes made
|
|
125
|
+
// during plugin activation are honored.
|
|
126
|
+
const pluginEntries = Array.isArray(options.plugins) ? options.plugins : [];
|
|
120
127
|
// ActivityPub federation is OFF by default
|
|
121
128
|
const activitypubEnabled = options.activitypub ?? false;
|
|
122
129
|
const apUsername = options.apUsername ?? 'me';
|
|
@@ -411,6 +418,20 @@ export function createServer(options = {}) {
|
|
|
411
418
|
});
|
|
412
419
|
}
|
|
413
420
|
|
|
421
|
+
// Load app plugins (#206). Deferred into a register scope so the dynamic
|
|
422
|
+
// imports and async activation run during fastify's startup; a failing
|
|
423
|
+
// plugin fails listen() rather than leaving a half-configured server.
|
|
424
|
+
if (pluginEntries.length) {
|
|
425
|
+
fastify.register(async (instance) => {
|
|
426
|
+
const { loadPlugins } = await import('./plugins.js');
|
|
427
|
+
await loadPlugins(instance, pluginEntries, {
|
|
428
|
+
appPaths,
|
|
429
|
+
root: options.root || process.env.DATA_ROOT || './data',
|
|
430
|
+
log: fastify.log,
|
|
431
|
+
});
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
|
|
414
435
|
// Register Nostr relay if enabled
|
|
415
436
|
if (nostrEnabled) {
|
|
416
437
|
fastify.register(async (instance) => {
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin loader (#206) — createServer({ plugins }) end to end.
|
|
3
|
+
*
|
|
4
|
+
* A fixture plugin (written to disk per test run, in the #206 activate(api)
|
|
5
|
+
* shape both real consumers — Tideholm and bridge — already export) is
|
|
6
|
+
* loaded from config and verified against the whole api surface: HTTP
|
|
7
|
+
* routes under a WAC-exempt prefix (#582), auth.getAgent (#584), a
|
|
8
|
+
* WebSocket endpoint through ws.route (#588), private storage under the
|
|
9
|
+
* data root's dot-guard, config pass-through, and deactivate on close.
|
|
10
|
+
* Failure paths (missing module, no activate export, bad prefix) must fail
|
|
11
|
+
* listen() loudly rather than boot a server silently missing an app.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { describe, it, before, after, afterEach } from 'node:test';
|
|
15
|
+
import assert from 'node:assert';
|
|
16
|
+
import path from 'path';
|
|
17
|
+
import { WebSocket } from 'ws';
|
|
18
|
+
import fs from 'fs-extra';
|
|
19
|
+
import { createServer } from '../src/server.js';
|
|
20
|
+
import { pluginId } from '../src/plugins.js';
|
|
21
|
+
|
|
22
|
+
const TEST_DATA_DIR = './test-data-plugins';
|
|
23
|
+
const FIXTURE_DIR = './test-fixtures-plugins';
|
|
24
|
+
|
|
25
|
+
let server;
|
|
26
|
+
let baseUrl;
|
|
27
|
+
let originalDataRoot;
|
|
28
|
+
|
|
29
|
+
// The fixture records activation evidence into this file so tests can
|
|
30
|
+
// assert on what the plugin saw (config, prefix, storage dir, deactivate).
|
|
31
|
+
const EVIDENCE = path.resolve(FIXTURE_DIR, 'evidence.json');
|
|
32
|
+
|
|
33
|
+
const FIXTURE_PLUGIN = `
|
|
34
|
+
import fs from 'fs';
|
|
35
|
+
|
|
36
|
+
export async function activate(api) {
|
|
37
|
+
const dir = api.storage.pluginDir();
|
|
38
|
+
const evidence = {
|
|
39
|
+
prefix: api.prefix,
|
|
40
|
+
config: api.config,
|
|
41
|
+
pluginDir: dir,
|
|
42
|
+
hasGetAgent: typeof api.auth.getAgent === 'function',
|
|
43
|
+
deactivated: false,
|
|
44
|
+
};
|
|
45
|
+
const record = () =>
|
|
46
|
+
fs.writeFileSync(${JSON.stringify(EVIDENCE)}, JSON.stringify(evidence));
|
|
47
|
+
record();
|
|
48
|
+
|
|
49
|
+
api.fastify.all(api.prefix + '/echo', async (request, reply) => {
|
|
50
|
+
const agent = await api.auth.getAgent(request);
|
|
51
|
+
reply.code(200).send({ app: true, method: request.method, agent });
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
await api.ws.route(api.prefix + '/ws', (socket) => {
|
|
55
|
+
socket.on('message', (data) => socket.send('pong:' + String(data)));
|
|
56
|
+
});
|
|
57
|
+
await api.ws.route(api.prefix + '/ws-throw', () => {
|
|
58
|
+
throw new Error('plugin bug');
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
return {
|
|
62
|
+
deactivate() {
|
|
63
|
+
evidence.deactivated = true;
|
|
64
|
+
record();
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
`;
|
|
69
|
+
|
|
70
|
+
async function startWith(plugins) {
|
|
71
|
+
await fs.emptyDir(TEST_DATA_DIR);
|
|
72
|
+
server = createServer({
|
|
73
|
+
logger: false,
|
|
74
|
+
forceCloseConnections: true,
|
|
75
|
+
root: TEST_DATA_DIR,
|
|
76
|
+
plugins,
|
|
77
|
+
});
|
|
78
|
+
await server.listen({ port: 0, host: '127.0.0.1' });
|
|
79
|
+
const address = server.server.address();
|
|
80
|
+
baseUrl = `http://127.0.0.1:${address.port}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function evidence() {
|
|
84
|
+
return JSON.parse(fs.readFileSync(EVIDENCE, 'utf8'));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
describe('plugin loader (#206)', () => {
|
|
88
|
+
before(async () => {
|
|
89
|
+
originalDataRoot = process.env.DATA_ROOT;
|
|
90
|
+
await fs.emptyDir(FIXTURE_DIR);
|
|
91
|
+
await fs.writeFile(path.join(FIXTURE_DIR, 'fixture-plugin.js'), FIXTURE_PLUGIN);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
afterEach(async () => {
|
|
95
|
+
if (server) {
|
|
96
|
+
await server.close();
|
|
97
|
+
server = null;
|
|
98
|
+
}
|
|
99
|
+
await fs.remove(TEST_DATA_DIR);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
after(async () => {
|
|
103
|
+
await fs.remove(FIXTURE_DIR);
|
|
104
|
+
if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
|
|
105
|
+
else process.env.DATA_ROOT = originalDataRoot;
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('loads a plugin from config and serves its routes under a WAC-exempt prefix', async () => {
|
|
109
|
+
await startWith([
|
|
110
|
+
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game', config: { bots: 3 } },
|
|
111
|
+
]);
|
|
112
|
+
// Unauthenticated POST reaches the app: the prefix joined appPaths.
|
|
113
|
+
const res = await fetch(`${baseUrl}/game/echo`, { method: 'POST' });
|
|
114
|
+
assert.strictEqual(res.status, 200);
|
|
115
|
+
const body = await res.json();
|
|
116
|
+
assert.strictEqual(body.app, true);
|
|
117
|
+
assert.strictEqual(body.method, 'POST');
|
|
118
|
+
assert.strictEqual(body.agent, null); // getAgent callable, anon -> null
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('passes prefix and config through to activate()', async () => {
|
|
122
|
+
await startWith([
|
|
123
|
+
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game/', config: { bots: 3 } },
|
|
124
|
+
]);
|
|
125
|
+
const seen = evidence();
|
|
126
|
+
assert.strictEqual(seen.prefix, '/game'); // trailing slash normalized
|
|
127
|
+
assert.deepStrictEqual(seen.config, { bots: 3 });
|
|
128
|
+
assert.strictEqual(seen.hasGetAgent, true);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it('ws.route serves a WebSocket endpoint under the prefix', async () => {
|
|
132
|
+
await startWith([
|
|
133
|
+
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game' },
|
|
134
|
+
]);
|
|
135
|
+
const ws = new WebSocket(`${baseUrl.replace('http', 'ws')}/game/ws`);
|
|
136
|
+
await new Promise((resolve, reject) => {
|
|
137
|
+
ws.on('open', resolve);
|
|
138
|
+
ws.on('error', reject);
|
|
139
|
+
});
|
|
140
|
+
const reply = await new Promise((resolve, reject) => {
|
|
141
|
+
ws.on('message', (data) => resolve(String(data)));
|
|
142
|
+
ws.on('error', reject);
|
|
143
|
+
ws.send('hello');
|
|
144
|
+
});
|
|
145
|
+
assert.strictEqual(reply, 'pong:hello');
|
|
146
|
+
ws.close();
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('pluginDir is created under the data root and shielded from LDP', async () => {
|
|
150
|
+
await startWith([
|
|
151
|
+
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game' },
|
|
152
|
+
]);
|
|
153
|
+
const seen = evidence();
|
|
154
|
+
assert.ok(seen.pluginDir.includes(path.join('.plugins', 'fixture-plugin')));
|
|
155
|
+
assert.ok(fs.existsSync(seen.pluginDir));
|
|
156
|
+
// Write a secret; the dot-guard must keep it unreachable over HTTP.
|
|
157
|
+
await fs.writeFile(path.join(seen.pluginDir, 'secret.txt'), 'hush');
|
|
158
|
+
const res = await fetch(`${baseUrl}/.plugins/fixture-plugin/secret.txt`);
|
|
159
|
+
assert.notStrictEqual(res.status, 200);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('deactivate() runs on server close', async () => {
|
|
163
|
+
await startWith([
|
|
164
|
+
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game' },
|
|
165
|
+
]);
|
|
166
|
+
assert.strictEqual(evidence().deactivated, false);
|
|
167
|
+
await server.close();
|
|
168
|
+
server = null;
|
|
169
|
+
assert.strictEqual(evidence().deactivated, true);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('sibling LDP paths keep full WAC enforcement', async () => {
|
|
173
|
+
await startWith([
|
|
174
|
+
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game' },
|
|
175
|
+
]);
|
|
176
|
+
const res = await fetch(`${baseUrl}/somepod/private/thing`, { method: 'PUT', body: 'x' });
|
|
177
|
+
assert.ok([401, 403].includes(res.status), `expected WAC rejection, got ${res.status}`);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it('a plugin that cannot be imported fails listen() loudly', async () => {
|
|
181
|
+
await fs.emptyDir(TEST_DATA_DIR);
|
|
182
|
+
server = createServer({
|
|
183
|
+
logger: false,
|
|
184
|
+
forceCloseConnections: true,
|
|
185
|
+
root: TEST_DATA_DIR,
|
|
186
|
+
plugins: [{ module: `${FIXTURE_DIR}/no-such-plugin.js`, prefix: '/x' }],
|
|
187
|
+
});
|
|
188
|
+
await assert.rejects(
|
|
189
|
+
server.listen({ port: 0, host: '127.0.0.1' }),
|
|
190
|
+
/cannot import/,
|
|
191
|
+
);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it('a throwing ws handler closes that socket but not the server', async () => {
|
|
195
|
+
await startWith([
|
|
196
|
+
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game' },
|
|
197
|
+
]);
|
|
198
|
+
const ws = new WebSocket(`${baseUrl.replace('http', 'ws')}/game/ws-throw`);
|
|
199
|
+
await new Promise((resolve) => {
|
|
200
|
+
ws.on('close', resolve);
|
|
201
|
+
ws.on('error', resolve);
|
|
202
|
+
});
|
|
203
|
+
// The host survives its plugin's bug.
|
|
204
|
+
const res = await fetch(`${baseUrl}/game/echo`);
|
|
205
|
+
assert.strictEqual(res.status, 200);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it('derives collision-resistant ids and rejects duplicates', async () => {
|
|
209
|
+
// Bare specifiers keep their full path; file paths use the basename.
|
|
210
|
+
assert.strictEqual(pluginId({ module: '@scope1/pkg/plugin.js' }), 'scope1-pkg-plugin');
|
|
211
|
+
assert.strictEqual(pluginId({ module: '@scope2/pkg/plugin.js' }), 'scope2-pkg-plugin');
|
|
212
|
+
assert.strictEqual(pluginId({ module: '/some/machine/path/foo.js' }), 'foo');
|
|
213
|
+
assert.strictEqual(pluginId({ module: './x.js', id: 'Custom Id!' }), 'custom-id');
|
|
214
|
+
|
|
215
|
+
// Two entries reducing to the same id fail the boot, not share a dir.
|
|
216
|
+
await fs.emptyDir(TEST_DATA_DIR);
|
|
217
|
+
server = createServer({
|
|
218
|
+
logger: false,
|
|
219
|
+
forceCloseConnections: true,
|
|
220
|
+
root: TEST_DATA_DIR,
|
|
221
|
+
plugins: [
|
|
222
|
+
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/a' },
|
|
223
|
+
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/b' },
|
|
224
|
+
],
|
|
225
|
+
});
|
|
226
|
+
await assert.rejects(
|
|
227
|
+
server.listen({ port: 0, host: '127.0.0.1' }),
|
|
228
|
+
/duplicate id/,
|
|
229
|
+
);
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
it('an invalid prefix fails listen() loudly', async () => {
|
|
233
|
+
// Any provided prefix must validate — including falsy ones, which would
|
|
234
|
+
// otherwise mount the app without its WAC exemption.
|
|
235
|
+
for (const prefix of ['game', '', '/', 0, null]) {
|
|
236
|
+
await fs.emptyDir(TEST_DATA_DIR);
|
|
237
|
+
server = createServer({
|
|
238
|
+
logger: false,
|
|
239
|
+
forceCloseConnections: true,
|
|
240
|
+
root: TEST_DATA_DIR,
|
|
241
|
+
plugins: [{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix }],
|
|
242
|
+
});
|
|
243
|
+
await assert.rejects(
|
|
244
|
+
server.listen({ port: 0, host: '127.0.0.1' }),
|
|
245
|
+
/invalid prefix/,
|
|
246
|
+
`prefix ${JSON.stringify(prefix)} should be rejected`,
|
|
247
|
+
);
|
|
248
|
+
await server.close();
|
|
249
|
+
server = null;
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
});
|