7 Commits
Author SHA1 Message Date
Worph e1fd108f3a virtual path and NFO title fall back to parsedTitle, filename-parser's guess since the claims model
Build and Push Docker Image / build (push) Successful in 2m7s
2026-10-25 19:25:07 +00:00
Worph b0edfb5f97 per-plugin signing keys and a POST /api/claims relay; own writes signed; no filePath claims, no record delete when a file disappears
Build and Push Docker Image / build (push) Successful in 1m58s
2026-10-25 17:36:18 +00:00
Manielle c03c7a6bdb CI accepts four-part tags (v1.2.3.1) for fixes
Build and Push Docker Image / build (push) Successful in 1m58s
2026-10-25 14:22:00 +01:00
Worph 89ffd3b7d4 gitea workflow: push to IPCR's direct host (Cloudflare 100 MB cap)
Build and Push Docker Image / build (push) Successful in 2m26s
2026-10-13 10:02:17 +00:00
Worph c81dcaf0b5 gitea workflow: publish to IPCR (metadec.eth) instead of ghcr
Build and Push Docker Image / build (push) Failing after 2m6s
2026-10-12 18:30:31 +00:00
Worph dc564baf87 remove refreshes the plugin pipeline; spawned plugins advertise their container name (HOSTNAME)
Build and Push Docker Image / build (push) Failing after 13s
2026-10-04 18:14:33 +00:00
Worph fa4826ee2e beacon v2 Scan card on the Plugins page + external plugins by URL (persisted in cache/state, no Docker needed), discover/external API, spawned plugins advertise bound to this meta-sort, accept {status:ok} configure replies
Build and Push Docker Image / build (push) Failing after 14s
2026-10-04 17:19:27 +00:00
26 changed files with 1645 additions and 252 deletions
+100
View File
@@ -0,0 +1,100 @@
# Gitea twin of .github/workflows/docker-publish.yml. Gitea runs only .gitea/workflows/ once this
# folder exists, and GitHub never reads it.
#
# Publishes to IPCR on watch.nsl.sh instead of ghcr.io:
# push ipcr-push-85-17-246-67.nip.io/metadec.eth/<repo>:<tag> docker login as metadec.eth with the
# IPCR_PUSH_TOKEN secret (the metadec.eth namespace token from the IPCR dashboard)
# pull ipcr-watch.nsl.sh/ipns/metadec.eth/metadec.eth/<repo>:<tag> anonymous
# The push goes to ipcr-push-85-17-246-67.nip.io, the box's own address, not ipcr-push-watch.nsl.sh: Cloudflare fronts
# *.watch.nsl.sh and refuses any request over 100 MB (413), which a large image layer is.
# That host's certificate is signed by the box's private Mesh Router CA, given to buildkit from
# the IPCR_CA_PEM repo variable. docker login would make the job's Docker daemon check the
# certificate without that CA, so the login is written straight into ~/.docker/config.json.
# The runner's job image (node:22-bookworm) has no docker CLI, so the static one is
# installed first; buildx installs itself. No `type=gha` cache: the runner has none.
name: Build and Push Docker Image
on:
push:
branches:
- main
tags:
- 'v*'
workflow_dispatch:
inputs:
tag:
description: 'Tag for the image (optional, defaults to sha)'
required: false
type: string
meta_core_version:
description: 'meta-core version to use (default: latest)'
required: false
type: string
default: 'latest'
env:
REGISTRY: ipcr-push-85-17-246-67.nip.io
IPCR_PULL: ipcr-watch.nsl.sh/ipns/metadec.eth
IMAGE_NAME: metadec.eth/${{ github.event.repository.name }}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: recursive # For plugins
- name: Install Docker CLI
run: curl -fsSL https://download.docker.com/linux/static/stable/x86_64/docker-28.5.1.tgz | tar -xz -C /usr/local/bin --strip-components=1 docker/docker
- name: Trust the Mesh Router CA
run: printf '%s\n' "$IPCR_CA_PEM" > /tmp/ipcr-ca.pem
env:
IPCR_CA_PEM: ${{ vars.IPCR_CA_PEM }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
version: latest
buildkitd-config-inline: |
[registry."${{ env.REGISTRY }}"]
ca = ["/tmp/ipcr-ca.pem"]
- name: Log in to IPCR
env:
IPCR_PUSH_TOKEN: ${{ secrets.IPCR_PUSH_TOKEN }}
run: |
mkdir -p ~/.docker
printf '{"auths":{"%s":{"auth":"%s"}}}\n' "$REGISTRY" "$(printf 'metadec.eth:%s' "$IPCR_PUSH_TOKEN" | base64 -w0)" > ~/.docker/config.json
- name: Extract metadata (tags, labels)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=semver,pattern={{version}}
# A fix to release 1.2.3 is tagged v1.2.3.1: four numbers are not semver, so
# the pattern above makes no tag for it; this one does (image tag 1.2.3.1).
type=match,pattern=v(\d+\.\d+\.\d+\.\d+),group=1
type=semver,pattern={{major}}.{{minor}}
type=sha,prefix=
type=raw,value=latest,enable={{is_default_branch}}
type=raw,value=${{ inputs.tag }},enable=${{ inputs.tag != '' }}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
META_CORE_IMAGE=${{ env.IPCR_PULL }}/metadec.eth/meta-core:${{ inputs.meta_core_version || 'latest' }}
+3
View File
@@ -52,6 +52,9 @@ jobs:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=semver,pattern={{version}}
# A fix to release 1.2.3 is tagged v1.2.3.1: four numbers are not semver, so
# the pattern above makes no tag for it; this one does (image tag 1.2.3.1).
type=match,pattern=v(\d+\.\d+\.\d+\.\d+),group=1
type=semver,pattern={{major}}.{{minor}}
type=sha,prefix=
type=raw,value=latest,enable={{is_default_branch}}
+13
View File
@@ -44,6 +44,19 @@ http {
try_files $uri $uri/ /index.html;
}
# Signed claims relay (plugins -> meta-sort -> meta-core). Exact match so
# a large claim batch is not cut at nginx's 1 MB default (the API takes
# up to 16 MB); reads of /api/meta/{cid}/claims use the /api/ block.
location = /api/claims {
client_max_body_size 16m;
proxy_pass http://api;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# API routes
location /api/ {
proxy_pass http://api;
+6 -1
View File
@@ -1,5 +1,10 @@
{
"spec": ["dist/api/api.test.js", "dist/kv/*.test.js"],
"spec": [
"dist/api/api.test.js",
"dist/kv/*.test.js",
"dist/container-plugins/*.test.js",
"dist/discovery/*.test.js"
],
"timeout": 30000,
"exit": true
}
@@ -1027,7 +1027,9 @@ export class UnifiedAPIServer {
instanceCount: p.instances,
healthyCount: p.healthyInstances,
enabled: p.enabled,
image: p.image
image: p.image,
kind: p.kind,
url: p.url
})),
queue: queueStatus || null
};
@@ -1040,6 +1042,67 @@ export class UnifiedAPIServer {
}
});
// Beacon v2 Scan card: enrichment plugins advertising on the network
// (metamesh.enrich/<id>), classified against what this meta-sort runs.
this.app.post('/api/plugins/discover', async (_request, reply) => {
const leaderClient = this.kvManager?.getLeaderClient();
const empty = {
cap: 'metamesh.enrich/*', disabled: true,
summary: { nodes: 0, capable: 0, configured: 0, boundElsewhere: 0, addable: 0 },
candidates: [],
};
if (!leaderClient) return reply.send(empty);
const status = this.containerManager?.getStatus();
const configured: Array<[string, string]> = (status?.plugins ?? [])
.filter((p) => p.url)
.map((p) => [p.pluginId, p.url as string]);
const report = await leaderClient.scan('metamesh.enrich/*', configured, 1500);
// Same plugin id already loaded under another URL (e.g. our own spawned
// container of it): adding it would clash, so it counts as configured.
const loaded = new Set((status?.plugins ?? []).map((p) => p.pluginId));
for (const c of report.candidates) {
if (c.state !== 'addable') continue;
const id = c.caps.map((cap) => cap.match(/^metamesh\.enrich\/([^@]+)/)?.[1]).find((x) => x && loaded.has(x));
if (id) {
c.state = 'configured';
c.configuredAs = id;
report.summary.addable--;
report.summary.configured++;
}
}
return reply.send(report);
});
// External plugin (one meta-sort did not spawn) — the Scan card's Add.
this.app.post<{ Body: { url?: string; name?: string } }>('/api/plugins/external', async (request, reply) => {
if (!this.containerManager) {
return reply.status(503).send({ error: 'Container manager not initialized' });
}
const url = request.body?.url;
if (!url) return reply.status(400).send({ error: 'url is required' });
try {
const entry = await this.containerManager.addExternalPlugin(url, request.body?.name);
// Bring it into the processing pipeline (same as /api/plugins/rescan).
await this.getPluginManager?.()?.loadContainerPlugins();
return { success: true, plugin: entry };
} catch (error: any) {
return reply.status(400).send({ error: error.message });
}
});
this.app.delete<{ Params: { pluginId: string } }>('/api/plugins/external/:pluginId', async (request, reply) => {
if (!this.containerManager) {
return reply.status(503).send({ error: 'Container manager not initialized' });
}
try {
await this.containerManager.removeExternalPlugin(request.params.pluginId);
await this.getPluginManager?.()?.loadContainerPlugins();
return { success: true };
} catch (error: any) {
return reply.status(400).send({ error: error.message });
}
});
// Get container plugin manifest
this.app.get<{
Params: { pluginId: string }
@@ -1184,6 +1247,9 @@ export class UnifiedAPIServer {
try {
await this.containerManager.removePlugin(pluginId);
// Drop it from the processing pipeline too (else it lingers in
// /api/plugins until the next rescan or restart).
await this.getPluginManager?.()?.loadContainerPlugins();
return {
success: true,
message: `Plugin '${pluginId}' removed successfully`
@@ -1255,9 +1321,8 @@ export class UnifiedAPIServer {
}
/**
* Setup meta-core compatible API routes
* These routes allow container plugins to write metadata directly to Redis
* Matches the meta-core Go sidecar API for compatibility
* Setup meta-core compatible API routes for container plugins: merged reads
* (`GET /meta/...`) and the signed-claims relay (`POST /api/claims`).
*/
private setupMetaCoreRoutes(): void {
if (!this.kvClient) {
@@ -1312,125 +1377,43 @@ export class UnifiedAPIServer {
}
});
// PUT /meta/{hash}/{key} - Set single property
this.app.put<{
Params: { hash: string; '*': string };
Body: { value: string }
}>('/meta/:hash/*', async (request, reply) => {
const { hash } = request.params;
const key = request.params['*'];
const { value } = request.body || {};
if (!key) {
return reply.status(400).send({ error: 'Missing key' });
// Writes: plugins post signed MMUR2 claims; meta-sort relays them to
// meta-core untouched (never re-signs — the plugin is the signer). See
// docs/implementation/metacore-claims-model.md §15.
this.app.post<{ Body: unknown }>('/api/claims', { bodyLimit: 16 * 1024 * 1024 }, async (request, reply) => {
if (!this.kvClient!.relayClaims) {
return reply.status(503).send({ error: 'meta-core API not configured' });
}
if (value === undefined) {
return reply.status(400).send({ error: 'Missing value in body' });
}
try {
// Get existing metadata and merge
const existing = await this.kvClient!.getMetadataFlat(hash) || {};
existing[key] = String(value);
await this.kvClient!.setMetadataFlat(hash, existing);
return { status: 'ok' };
const { status, body } = await this.kvClient!.relayClaims(request.body);
return reply.status(status).send(body);
} catch (error: any) {
return reply.status(500).send({
error: 'Failed to set property',
details: error.message
});
return reply.status(502).send({ error: 'Failed to relay claims to meta-core', details: error.message });
}
});
// DELETE /meta/{hash}/{key} - Delete single property
this.app.delete<{
Params: { hash: string; '*': string }
}>('/meta/:hash/*', async (request, reply) => {
const { hash } = request.params;
const key = request.params['*'];
if (!key) {
return reply.status(400).send({ error: 'Missing key' });
// Claims read relay: plugins read their own csv-set vote before appending.
this.app.get<{ Params: { cid: string } }>('/api/meta/:cid/claims', async (request, reply) => {
if (!this.kvClient!.fetchClaims) {
return reply.status(503).send({ error: 'meta-core API not configured' });
}
const q = request.url.indexOf('?');
try {
const existing = await this.kvClient!.getMetadataFlat(hash);
if (!existing) {
return { status: 'ok' }; // Nothing to delete
}
delete existing[key];
await this.kvClient!.setMetadataFlat(hash, existing);
return { status: 'ok' };
const { status, body } = await this.kvClient!.fetchClaims(request.params.cid, q >= 0 ? request.url.slice(q) : '');
return reply.status(status).send(body);
} catch (error: any) {
return reply.status(500).send({
error: 'Failed to delete property',
details: error.message
});
return reply.status(502).send({ error: 'Failed to read claims from meta-core', details: error.message });
}
});
// PATCH /meta/{hash} - Merge metadata (partial update)
this.app.patch<{
Params: { hash: string };
Body: Record<string, string>
}>('/meta/:hash', async (request, reply) => {
const { hash } = request.params;
const newMetadata = request.body;
if (!newMetadata || typeof newMetadata !== 'object') {
return reply.status(400).send({ error: 'Body must be an object with key-value pairs' });
}
try {
// Get existing metadata and merge
const existing = await this.kvClient!.getMetadataFlat(hash) || {};
const merged = { ...existing, ...newMetadata };
await this.kvClient!.setMetadataFlat(hash, merged);
return { status: 'ok' };
} catch (error: any) {
return reply.status(500).send({
error: 'Failed to merge metadata',
details: error.message
});
}
});
// POST /meta/{hash}/_add/{key} - Add value to a set field (comma-separated)
this.app.post<{
Params: { hash: string; key: string };
Body: { value: string }
}>('/meta/:hash/_add/:key', async (request, reply) => {
const { hash, key } = request.params;
const { value } = request.body || {};
if (!value) {
return reply.status(400).send({ error: 'Missing value in body' });
}
try {
const existing = await this.kvClient!.getMetadataFlat(hash) || {};
const currentValue = existing[key] || '';
// Parse existing as comma-separated set
const values = new Set(currentValue ? currentValue.split(',').map(v => v.trim()) : []);
values.add(String(value));
existing[key] = Array.from(values).join(',');
await this.kvClient!.setMetadataFlat(hash, existing);
return { status: 'ok' };
} catch (error: any) {
return reply.status(500).send({
error: 'Failed to add to set',
details: error.message
});
}
});
// The unsigned write verbs are gone (meta-core v2.0.0 refuses unsigned
// writes); answer like meta-core does so an old plugin build fails loudly.
const gone = async (_request: unknown, reply: any) =>
reply.status(410).send({ error: 'gone', use: 'POST /api/claims' });
this.app.put('/meta/:hash/*', gone);
this.app.delete('/meta/:hash/*', gone);
this.app.patch('/meta/:hash', gone);
this.app.post('/meta/:hash/_add/:key', gone);
// Health check for meta-core compatibility
this.app.get('/meta-health', async () => {
+41 -58
View File
@@ -138,6 +138,23 @@ class MockKVClient implements IKVClient {
this.data.get(hashId)!.set(property, value);
}
/** Bodies relayed to meta-core's POST /api/claims, in order. */
relayed: unknown[] = [];
/** `cid + search` of every claims read relayed to meta-core. */
claimReads: string[] = [];
async fetchClaims(cid: string, search: string): Promise<{ status: number; body: unknown }> {
this.claimReads.push(cid + search);
return { status: 200, body: { claims: [] } };
}
async relayClaims(body: unknown): Promise<{ status: number; body: unknown }> {
this.relayed.push(body);
const claims = Array.isArray(body) ? body : [];
return { status: 200, body: claims.map(() => ({ status: 'accepted' })) };
}
async deleteMetadataFlat(hashId: string): Promise<number> {
const entry = this.data.get(hashId);
const count = entry?.size ?? 0;
@@ -663,72 +680,38 @@ describe('UnifiedAPIServer', function() {
expect(body).to.have.property('value', 'movie');
});
it('PUT /meta/:hash/:key sets property value', async function() {
const response = await app.inject({
method: 'PUT',
url: '/meta/testhash001/metaCustomField',
payload: { value: 'metaCustomValue' }
});
expect(response.statusCode).to.equal(200);
// Verify the update
const verify = await app.inject({
method: 'GET',
url: '/meta/testhash001/metaCustomField'
});
const body = JSON.parse(verify.payload);
expect(body).to.have.property('value', 'metaCustomValue');
});
it('PATCH /meta/:hash merges metadata', async function() {
const response = await app.inject({
method: 'PATCH',
url: '/meta/testhash001',
payload: {
patchedField: 'patchedValue',
anotherField: '123'
it('unsigned write verbs answer 410 with a pointer to POST /api/claims', async function() {
const attempts = [
{ method: 'PUT' as const, url: '/meta/testhash001/metaCustomField', payload: { value: 'x' } },
{ method: 'PATCH' as const, url: '/meta/testhash001', payload: { patchedField: 'x' } },
{ method: 'DELETE' as const, url: '/meta/testhash001/fileName' },
{ method: 'POST' as const, url: '/meta/testhash001/_add/genres', payload: { value: 'Drama' } },
];
for (const a of attempts) {
const response = await app.inject(a);
expect(response.statusCode, `${a.method} ${a.url}`).to.equal(410);
expect(JSON.parse(response.payload)).to.deep.equal({ error: 'gone', use: 'POST /api/claims' });
}
// Nothing was written behind the 410s.
const verify = await app.inject({ method: 'GET', url: '/meta/testhash001/fileName' });
expect(JSON.parse(verify.payload)).to.have.property('value', 'Test Movie.mp4');
});
it('GET /api/meta/:cid/claims relays the read to meta-core with its query', async function() {
const response = await app.inject({ method: 'GET', url: '/api/meta/bafycid/claims?key=genres' });
expect(response.statusCode).to.equal(200);
const body = JSON.parse(response.payload);
expect(body).to.have.property('status', 'ok');
// Verify the merge
const verify = await app.inject({
method: 'GET',
url: '/meta/testhash001'
});
const verifyBody = JSON.parse(verify.payload);
expect(verifyBody.metadata).to.have.property('patchedField', 'patchedValue');
expect(verifyBody.metadata).to.have.property('fileName', 'Test Movie.mp4'); // Original preserved
expect(JSON.parse(response.payload)).to.deep.equal({ claims: [] });
expect(mockKV.claimReads.at(-1)).to.equal('bafycid?key=genres');
});
it('DELETE /meta/:hash/:key removes property', async function() {
// First set a property
await app.inject({
method: 'PUT',
url: '/meta/testhash001/toDeleteMeta',
payload: { value: 'deleteMe' }
});
// Verify property was set
const beforeDelete = await app.inject({
method: 'GET',
url: '/meta/testhash001/toDeleteMeta'
});
expect(beforeDelete.statusCode).to.equal(200);
// Then delete it
const response = await app.inject({
method: 'DELETE',
url: '/meta/testhash001/toDeleteMeta'
});
it('POST /api/claims relays the signed batch to meta-core untouched', async function() {
const batch = [{ cid: 'bafy', uid: 'zQ3s', key: 'title', value: 'A', ts: 1, sig: 'c2ln' }];
const response = await app.inject({ method: 'POST', url: '/api/claims', payload: batch });
expect(response.statusCode).to.equal(200);
const body = JSON.parse(response.payload);
expect(body).to.have.property('status', 'ok');
expect(JSON.parse(response.payload)).to.deep.equal([{ status: 'accepted' }]);
expect(mockKV.relayed.at(-1)).to.deep.equal(batch);
});
});
@@ -89,6 +89,13 @@ interface EnvConfig {
/** Path to container plugins config file (default: '/app/plugins.yml') */
CONTAINER_PLUGINS_CONFIG: string;
/**
* External plugins added by URL from the Plugins page's beacon Scan card
* (default: '<CACHE_FOLDER_PATH>/state/external-plugins.json'). Kept apart
* from plugins.yml, which the store app mounts read-only.
*/
EXTERNAL_PLUGINS_PATH: string;
/** Docker socket path (default: '/var/run/docker.sock') */
DOCKER_SOCKET_PATH: string;
@@ -112,6 +119,16 @@ interface EnvConfig {
*/
PLUGIN_CACHE_HOST_PATH?: string;
/**
* Where meta-sort keeps one signing key per container plugin
* (`<dir>/<pluginId>.key`, 0600), injected as `METAMESH_SIGNING_KEY`.
* Default: `<dirname(METAMESH_SIGNING_KEY_FILE)>/plugins` — next to
* meta-sort's own key, so one backed-up `keys/` dir holds every identity
* (store/dev bind it at /keys). Falls back to
* `<CACHE_FOLDER_PATH>/state/keys/plugins` when no key file is configured.
*/
METASORT_PLUGIN_KEYS_DIR: string;
// NOTE: Plugin output files are written via WebDAV (WEBDAV_URL/plugin/<pluginId>/)
// No PLUGIN_OUTPUT_HOST_PATH needed - plugins use HTTP PUT to write files
@@ -156,12 +173,18 @@ export const config: EnvConfig = {
// Container Plugins Configuration
CONTAINER_PLUGINS_CONFIG: process.env.CONTAINER_PLUGINS_CONFIG || '/app/plugins.yml',
EXTERNAL_PLUGINS_PATH: process.env.EXTERNAL_PLUGINS_PATH
|| `${process.env.CACHE_FOLDER_PATH || '/data/cache'}/state/external-plugins.json`,
DOCKER_SOCKET_PATH: process.env.DOCKER_SOCKET_PATH || '/var/run/docker.sock',
CONTAINER_CALLBACK_URL: process.env.CONTAINER_CALLBACK_URL || 'http://meta-sort:8180',
CONTAINER_META_CORE_URL: process.env.CONTAINER_META_CORE_URL || 'http://meta-sort',
CONTAINER_NETWORK: process.env.CONTAINER_NETWORK || 'meta-network',
PLUGIN_STACK_NAME: process.env.PLUGIN_STACK_NAME,
PLUGIN_CACHE_HOST_PATH: process.env.PLUGIN_CACHE_HOST_PATH,
METASORT_PLUGIN_KEYS_DIR: process.env.METASORT_PLUGIN_KEYS_DIR
|| (process.env.METAMESH_SIGNING_KEY_FILE
? `${process.env.METAMESH_SIGNING_KEY_FILE.replace(/\/[^/]*$/, '') || '/'}/plugins`
: `${process.env.CACHE_FOLDER_PATH || '/data/cache'}/state/keys/plugins`),
// Event Subscriber Configuration
META_CORE_URL: process.env.META_CORE_URL,
@@ -27,7 +27,8 @@ export function renamingRule(metamesh: Local, filepath?: string): string | null
}
// The display name — never the `titles/*` name set, which has no preferred member (METADATA_KEYS.md §3).
const title = metamesh.title || metamesh.originalTitle;
// `parsedTitle` is filename-parser's guess (claims model, D12): last resort.
const title = metamesh.title || metamesh.originalTitle || (metamesh as { parsedTitle?: string }).parsedTitle;
if (!title) {
if (metamesh.fileType !== "torrent") {
//don't warn for torrent files because they don't always have a title (eg representing a folder of files)
@@ -25,6 +25,10 @@ import type {
PluginConfigureResponse,
} from './types.js';
import { config } from '../config/EnvConfig.js';
import { existsSync } from 'fs';
import { hostname } from 'os';
import { randomBytes } from 'crypto';
import { ExternalPluginStore, type ExternalPluginEntry } from './ExternalPluginStore.js';
/**
* Service info structure from meta-core service discovery
@@ -96,6 +100,11 @@ export class ContainerManager extends EventEmitter {
private stackName?: string;
private callbackUrl: string;
private metaCoreUrl: string;
/** External plugins (added by URL); see ExternalPluginStore. */
private externalStore: ExternalPluginStore;
private externalEntries: ExternalPluginEntry[] = [];
/** False when Docker is unreachable: only external plugins run then. */
private dockerAvailable = false;
constructor(
private configPath: string = config.CONTAINER_PLUGINS_CONFIG,
@@ -116,6 +125,12 @@ export class ContainerManager extends EventEmitter {
// Configure stack name for Docker Desktop grouping
this.stackName = config.PLUGIN_STACK_NAME;
this.externalStore = new ExternalPluginStore(config.EXTERNAL_PLUGINS_PATH);
}
/** Swap the external-plugin store (tests). */
setExternalStore(store: ExternalPluginStore): void {
this.externalStore = store;
}
/**
@@ -183,22 +198,41 @@ export class ContainerManager extends EventEmitter {
console.warn(' Plugins will not have access to files.');
}
// Initialize Docker client
// Docker is needed only for the plugins we spawn. Without it (no
// socket, permission denied) external plugins still run.
try {
await this.dockerClient.initialize();
// Ensure network exists
await this.dockerClient.ensureNetwork(this.network);
this.dockerAvailable = true;
} catch (error) {
console.warn('[ContainerManager] Docker unavailable — only external plugins will run:', error);
}
// Load configuration
// Load configuration. A missing or broken plugins.yml means "no
// spawned plugins", not "no plugin manager": external plugins can
// still be added from the UI.
if (existsSync(this.configPath)) {
try {
this.pluginsConfig = await loadConfig(this.configPath);
} catch (error) {
console.error(`[ContainerManager] Ignoring ${this.configPath}:`, error);
}
} else {
console.log(`[ContainerManager] No ${this.configPath}; no spawned plugins`);
}
if (!this.pluginsConfig) {
this.pluginsConfig = { version: '1.0', plugins: {} };
}
// Get enabled plugins
const enabledPlugins = getEnabledPlugins(this.pluginsConfig);
const enabledPlugins = this.dockerAvailable ? getEnabledPlugins(this.pluginsConfig) : [];
console.log(`[ContainerManager] Found ${enabledPlugins.length} enabled plugins`);
if (this.dockerAvailable) {
// Clean up any stale containers from previous runs
await this.cleanupStaleContainers();
}
// Spawn containers for each enabled plugin
for (const { id, config: pluginConfig } of enabledPlugins) {
@@ -213,6 +247,21 @@ export class ContainerManager extends EventEmitter {
}
}
// External plugins (added by URL). One unreachable at boot is
// registered anyway and picked up by the health loop when it appears.
this.externalEntries = await this.externalStore.load();
for (const entry of this.externalEntries.filter((e) => e.enabled)) {
if (this.instances.has(entry.pluginId)) {
console.warn(
`[ContainerManager] External plugin '${entry.pluginId}' (${entry.url}) skipped: ` +
'a spawned plugin already has that id'
);
continue;
}
this.attachExternal(entry);
}
console.log(`[ContainerManager] ${this.externalEntries.length} external plugin(s) configured`);
this.initialized = true;
this.emit('manager:initialized', { pluginCount: enabledPlugins.length });
@@ -328,6 +377,32 @@ export class ContainerManager extends EventEmitter {
}
}
/**
* The plugin's signing key (64 hex chars), minted on first spawn and kept
* at `<METASORT_PLUGIN_KEYS_DIR>/<pluginId>.key` (0600). Containers are
* recreated on every spawn and store installs give them no volume, so the
* key lives with meta-sort and is injected as `METAMESH_SIGNING_KEY`: one
* stable uid per plugin id (docs/implementation/metacore-claims-model.md
* §15). Losing the file means a new uid and orphaned votes — back it up.
*/
private async pluginSigningKey(pluginId: string): Promise<string> {
const dir = config.METASORT_PLUGIN_KEYS_DIR;
const file = join(dir, `${pluginId.replace(/[^A-Za-z0-9._-]/g, '_')}.key`);
if (!existsSync(file)) {
await fs.mkdir(dir, { recursive: true, mode: 0o700 });
await fs.writeFile(file, randomBytes(32).toString('hex') + '\n', { mode: 0o600, flag: 'wx' })
.catch((error: NodeJS.ErrnoException) => {
if (error.code !== 'EEXIST') throw error; // another instance minted it first
});
console.log(`[ContainerManager] Minted signing key for plugin '${pluginId}' at ${file}`);
}
const key = (await fs.readFile(file, 'utf8')).trim();
if (!/^[0-9a-fA-F]{64}$/.test(key)) {
throw new Error(`[ContainerManager] signing key ${file} is not 64 hex characters`);
}
return key;
}
/**
* Spawn a single container instance
*/
@@ -397,6 +472,8 @@ export class ContainerManager extends EventEmitter {
console.warn(`[ContainerManager] WARNING: WebDAV not configured. Plugin '${pluginId}' won't have access to files. Ensure meta-core is running and accessible.`);
}
const signingKey = await this.pluginSigningKey(pluginId);
// Create container
const containerId = await this.dockerClient.createContainer({
image: pluginConfig.image,
@@ -415,6 +492,16 @@ export class ContainerManager extends EventEmitter {
CALLBACK_URL: this.callbackUrl,
WEBDAV_URL: this.webdavUrl || '',
FILES_PATH: '/files', // Virtual path - files accessed via WebDAV
// Beacon v2: advertise the URL we reach it on (so a Scan shows it
// as configured), and only to this meta-sort (another one's
// Scan shows it as bound elsewhere, never addable).
BEACON_ADVERTISE_URL: `http://${containerName}:8080`,
BEACON_BINDS: hostname(),
// Docker's own HOSTNAME is the container id; advertise a name
// an operator can read in the Scan card.
HOSTNAME: containerName,
// The plugin signs its claims as itself (one uid per plugin id).
METAMESH_SIGNING_KEY: signingKey,
},
// Docker Desktop grouping
stackName: this.stackName,
@@ -427,6 +514,7 @@ export class ContainerManager extends EventEmitter {
// Create instance record
const instance: ContainerPluginInstance = {
pluginId,
kind: 'container',
containerId,
containerName,
baseUrl: `http://${containerName}:8080`,
@@ -445,6 +533,12 @@ export class ContainerManager extends EventEmitter {
* Stop a container instance
*/
private async stopInstance(instance: ContainerPluginInstance): Promise<void> {
if (instance.kind === 'external') {
// Not ours to stop: just stop using it.
instance.status = 'stopped';
this.emit('plugin:stopped', { pluginId: instance.pluginId, instanceIndex: instance.instanceIndex });
return;
}
console.log(`[ContainerManager] Stopping ${instance.containerName}...`);
try {
@@ -490,6 +584,11 @@ export class ContainerManager extends EventEmitter {
if (healthy) {
instance.status = 'healthy';
instance.lastHealthCheck = Date.now();
// An external plugin unreachable at boot has no manifest
// yet; the scheduler needs one.
if (!instance.manifest) {
instance.manifest = await this.fetchManifest(instance).catch(() => undefined);
}
if (previousStatus !== 'healthy') {
this.emit('plugin:healthy', { pluginId, instance });
@@ -609,9 +708,12 @@ export class ContainerManager extends EventEmitter {
throw new Error(`Failed to configure plugin: ${response.status}`);
}
// Two contracts in the wild: `{ success: true }` and the TS plugins'
// `{ status: 'ok' }`. Before both were accepted every configure of a
// TS plugin "failed" (silently, behind a try/warn).
const data = (await response.json()) as PluginConfigureResponse;
if (!data.success) {
throw new Error(`Plugin configuration failed: ${data.error}`);
if (!data.success && data.status !== 'ok') {
throw new Error(`Plugin configuration failed: ${data.error ?? JSON.stringify(data)}`);
}
}
@@ -678,11 +780,14 @@ export class ContainerManager extends EventEmitter {
for (const [pluginId, instances] of this.instances) {
const pluginConfig = this.pluginsConfig?.plugins[pluginId];
const healthyCount = instances.filter((i) => i.status === 'healthy').length;
const external = instances[0]?.kind === 'external';
plugins.push({
pluginId,
enabled: pluginConfig?.enabled !== false,
image: pluginConfig?.image || 'unknown',
image: external ? instances[0].baseUrl : pluginConfig?.image || 'unknown',
kind: external ? 'external' : 'container',
url: instances[0]?.baseUrl,
instances: instances.length,
healthyInstances: healthyCount,
manifest: instances[0]?.manifest,
@@ -717,6 +822,16 @@ export class ContainerManager extends EventEmitter {
const instances = this.instances.get(pluginId);
const pluginConfig = this.pluginsConfig?.plugins[pluginId];
if (instances?.[0]?.kind === 'external') {
// Nothing to respawn: re-probe it and refresh its manifest.
for (const instance of instances) {
const healthy = await this.checkHealth(instance);
instance.status = healthy ? 'healthy' : 'unhealthy';
if (healthy) instance.manifest = await this.fetchManifest(instance).catch(() => instance.manifest);
}
return;
}
if (!instances || !pluginConfig) {
throw new Error(`Plugin '${pluginId}' not found`);
}
@@ -779,6 +894,93 @@ export class ContainerManager extends EventEmitter {
}
}
/** The external plugins, as persisted. */
getExternalPlugins(): ExternalPluginEntry[] {
return [...this.externalEntries];
}
/**
* Register an external plugin (one meta-sort did not spawn) by URL — what
* the beacon Scan card's Add does. Its manifest id becomes its plugin id,
* so it must be reachable now and its id must not clash with a loaded one.
*/
async addExternalPlugin(rawUrl: string, name?: string): Promise<ExternalPluginEntry> {
const url = rawUrl.trim().replace(/\/+$/, '');
if (!/^https?:\/\//.test(url)) {
throw new Error('url must start with http:// or https://');
}
for (const list of this.instances.values()) {
const holder = list.find((i) => i.baseUrl.replace(/\/+$/, '') === url);
if (holder) throw new Error(`${url} is already registered as '${holder.pluginId}'`);
}
const probe: ContainerPluginInstance = {
pluginId: '?', kind: 'external', containerId: '', containerName: url, baseUrl: url,
instanceIndex: 0, status: 'starting', tasksProcessed: 0, tasksFailed: 0,
};
let manifest: ContainerPluginManifest;
try {
manifest = await this.fetchManifest(probe);
} catch (error) {
throw new Error(`could not read ${url}/manifest: ${error instanceof Error ? error.message : error}`);
}
const pluginId = manifest?.id;
if (!pluginId || !/^[a-z][a-z0-9-]*$/.test(pluginId)) {
throw new Error(`${url}/manifest has no usable plugin id`);
}
if (this.instances.has(pluginId)) {
throw new Error(`a plugin with id '${pluginId}' is already loaded`);
}
const entry: ExternalPluginEntry = {
pluginId, url, enabled: true, name: name?.trim() || undefined, addedAt: new Date().toISOString(),
};
this.externalEntries = [...this.externalEntries.filter((e) => e.pluginId !== pluginId), entry];
await this.externalStore.save(this.externalEntries);
this.attachExternal(entry, manifest);
console.log(`[ContainerManager] External plugin '${pluginId}' added (${url})`);
return entry;
}
/** Forget an external plugin. Throws if `pluginId` is not one. */
async removeExternalPlugin(pluginId: string): Promise<void> {
const known = this.externalEntries.some((e) => e.pluginId === pluginId);
const instances = this.instances.get(pluginId);
if (!known && !(instances?.[0]?.kind === 'external')) {
throw new Error(`'${pluginId}' is not an external plugin`);
}
if (instances?.[0]?.kind === 'external') {
const interval = this.healthCheckIntervals.get(pluginId);
if (interval) {
clearInterval(interval);
this.healthCheckIntervals.delete(pluginId);
}
for (const instance of instances) await this.stopInstance(instance);
this.instances.delete(pluginId);
this.roundRobinCounters.delete(pluginId);
}
this.externalEntries = this.externalEntries.filter((e) => e.pluginId !== pluginId);
await this.externalStore.save(this.externalEntries);
console.log(`[ContainerManager] External plugin '${pluginId}' removed`);
}
/** One instance pointing at `entry.url`, kept alive by the health loop. */
private attachExternal(entry: ExternalPluginEntry, manifest?: ContainerPluginManifest): void {
const instance: ContainerPluginInstance = {
pluginId: entry.pluginId,
kind: 'external',
containerId: '',
// The scheduler reports completions by this name; the URL is unique.
containerName: entry.url,
baseUrl: entry.url,
instanceIndex: 0,
status: 'starting',
manifest,
tasksProcessed: 0,
tasksFailed: 0,
};
this.instances.set(entry.pluginId, [instance]);
this.startHealthCheck(entry.pluginId);
}
/**
* Add a new plugin dynamically
*/
@@ -838,6 +1040,11 @@ export class ContainerManager extends EventEmitter {
console.log(`[ContainerManager] Removing plugin '${pluginId}'...`);
const instances = this.instances.get(pluginId);
// An external plugin is forgotten (and un-persisted), never stopped.
if (instances?.[0]?.kind === 'external' || this.externalEntries.some((e) => e.pluginId === pluginId)) {
await this.removeExternalPlugin(pluginId);
return;
}
if (instances) {
// Stop health check
@@ -0,0 +1,52 @@
/**
* External plugins — enrichment plugins meta-sort did NOT spawn, reached by
* URL (typically a MetaPlugin* store app found with the Plugins page's beacon
* Scan card). Persisted as JSON next to the cache, because the store app
* mounts plugins.yml read-only.
*/
import { promises as fs } from 'fs';
import { dirname } from 'path';
export interface ExternalPluginEntry {
/** The plugin's manifest id — its identity in the pipeline. */
pluginId: string;
/** Base URL of the plugin's HTTP contract (/manifest, /health, /process). */
url: string;
enabled: boolean;
/** Name it was added under (the advertising instance), display only. */
name?: string;
addedAt?: string;
}
export class ExternalPluginStore {
constructor(private readonly path: string) {}
/** The persisted list; empty when the file is missing or unreadable. */
async load(): Promise<ExternalPluginEntry[]> {
let raw: string;
try {
raw = await fs.readFile(this.path, 'utf-8');
} catch {
return [];
}
try {
const parsed = JSON.parse(raw);
const list = Array.isArray(parsed?.plugins) ? parsed.plugins : [];
return list.filter(
(e: Partial<ExternalPluginEntry>) => typeof e?.pluginId === 'string' && typeof e?.url === 'string'
).map((e: ExternalPluginEntry) => ({ ...e, enabled: e.enabled !== false }));
} catch (error) {
console.error(`[ExternalPluginStore] ${this.path} is not valid JSON; ignoring it:`, error);
return [];
}
}
/** Atomic write: a crash mid-save leaves the previous file intact. */
async save(entries: ExternalPluginEntry[]): Promise<void> {
await fs.mkdir(dirname(this.path), { recursive: true });
const tmp = `${this.path}.tmp`;
await fs.writeFile(tmp, JSON.stringify({ plugins: entries }, null, 2), 'utf-8');
await fs.rename(tmp, this.path);
}
}
@@ -0,0 +1,74 @@
import { strict as assert } from 'assert';
import { createServer, type Server } from 'http';
import { mkdtempSync, readFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { ContainerManager } from './ContainerManager.js';
import { ExternalPluginStore } from './ExternalPluginStore.js';
/**
* External plugins are the meta-sort side of the beacon Scan card's Add: a
* plugin meta-sort did not spawn, reached by URL, identified by its manifest
* id, persisted outside the read-only plugins.yml.
*/
describe('external plugins', () => {
let server: Server;
let url: string;
before(async () => {
server = createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
if (req.url === '/manifest') {
res.end(JSON.stringify({ id: 'language', name: 'Language', version: '1.0.2', defaultQueue: 'fast' }));
} else if (req.url === '/health') {
res.end(JSON.stringify({ status: 'healthy', ready: true, version: '1.0.2' }));
} else {
res.statusCode = 404;
res.end('{}');
}
});
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const addr = server.address();
url = `http://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : 0}`;
});
after(() => server.close());
function manager(path: string): ContainerManager {
const m = new ContainerManager('/nonexistent/plugins.yml', 'none', '/files', 'http://cb', 'http://core');
m.setExternalStore(new ExternalPluginStore(path));
return m;
}
it('adds by URL under the manifest id, persists, and refuses duplicates', async () => {
const path = join(mkdtempSync(join(tmpdir(), 'ext-')), 'state', 'external-plugins.json');
const m = manager(path);
const entry = await m.addExternalPlugin(`${url}/`, 'metapluginlanguage-plugin');
assert.equal(entry.pluginId, 'language');
assert.equal(entry.url, url, 'trailing slash normalised');
const saved = JSON.parse(readFileSync(path, 'utf-8'));
assert.equal(saved.plugins[0].pluginId, 'language');
await assert.rejects(m.addExternalPlugin(url), /already registered/);
const status = m.getStatus().plugins.find((p) => p.pluginId === 'language');
assert.equal(status?.kind, 'external');
assert.equal(status?.url, url);
await m.removeExternalPlugin('language');
assert.equal(m.getStatus().plugins.length, 0);
assert.deepEqual(JSON.parse(readFileSync(path, 'utf-8')).plugins, []);
await assert.rejects(m.removeExternalPlugin('language'), /not an external plugin/);
});
it('rejects a URL whose manifest cannot be read', async () => {
const m = manager(join(mkdtempSync(join(tmpdir(), 'ext-')), 'x.json'));
await assert.rejects(m.addExternalPlugin('http://127.0.0.1:9/'), /could not read/);
await assert.rejects(m.addExternalPlugin('ftp://x'), /http/);
});
it('a missing or corrupt store reads as empty', async () => {
const dir = mkdtempSync(join(tmpdir(), 'ext-'));
assert.deepEqual(await new ExternalPluginStore(join(dir, 'missing.json')).load(), []);
});
});
@@ -164,7 +164,12 @@ export type ContainerInstanceStatus = 'starting' | 'healthy' | 'unhealthy' | 'st
export interface ContainerPluginInstance {
/** Plugin ID */
pluginId: string;
/** Docker container ID */
/**
* `container` = spawned by meta-sort from plugins.yml; `external` = added by
* URL (beacon Scan card), not ours to start or stop. Absent = container.
*/
kind?: 'container' | 'external';
/** Docker container ID ('' for an external plugin) */
containerId: string;
/** Container name (e.g., 'meta-plugin-ffmpeg-0') */
containerName: string;
@@ -211,7 +216,9 @@ export interface PluginConfigureRequest {
* Configure response from POST /configure
*/
export interface PluginConfigureResponse {
success: boolean;
/** Older contract. The TS plugins answer `{ status: 'ok' }` instead. */
success?: boolean;
status?: string;
error?: string;
}
@@ -315,7 +322,11 @@ export interface ContainerManagerStatus {
plugins: Array<{
pluginId: string;
enabled: boolean;
/** Docker image, or the plugin URL for an external plugin. */
image: string;
kind: 'container' | 'external';
/** Base URL of the first instance. */
url?: string;
instances: number;
healthyInstances: number;
manifest?: ContainerPluginManifest;
@@ -0,0 +1,30 @@
import { strict as assert } from 'assert';
import { capMatches, classifyScan, suggestedName, type MeshNeighbor } from './meshdisco.js';
/** Mirrors meta-feeder-sdk `beacon::scan` tests: same rules, same JSON. */
describe('beacon v2 scan classification', () => {
const node = (instance: string, cap: string, http?: string, binds?: string): MeshNeighbor => ({
name: 'plugin', instance, caps: [cap], addr: '10.0.0.1', lastSeen: 0,
resources: [{ id: 'x', caps: [cap], ...(http ? { endpoints: { http } } : {}), ...(binds ? { binds } : {}) }],
});
it('classifies configured, addable and bound-elsewhere', () => {
const r = classifyScan('metamesh.enrich/*', 'metasort-app', [
node('meta-plugin-language-0', 'metamesh.enrich/language', 'http://meta-plugin-language-0:8080/', 'metasort-app'),
node('metapluginffmpeg-plugin', 'metamesh.enrich/ffmpeg', 'http://metapluginffmpeg-plugin:8080'),
node('other-sort-plugin', 'metamesh.enrich/tmdb', 'http://x:8080', 'other-metasort'),
node('no-endpoint', 'metamesh.enrich/tmdb'),
node('a-service', 'metamesh.service/meta-core', 'http://core'),
], [['language', 'http://meta-plugin-language-0:8080']]);
assert.deepEqual(r.summary, { nodes: 5, capable: 3, configured: 1, boundElsewhere: 1, addable: 1 });
assert.equal(r.candidates[0].instance, 'metapluginffmpeg-plugin');
assert.equal(r.candidates[1].configuredAs, 'language');
assert.equal(r.candidates[2].state, 'bound-elsewhere');
});
it('caps and names', () => {
assert.ok(capMatches('metamesh.enrich/*', 'metamesh.enrich/language@1'));
assert.ok(!capMatches('metamesh.enrich/*', 'metamesh.enrichx/a'));
assert.equal(suggestedName('MetaPlugin Language'), 'metaplugin-language');
});
});
@@ -102,6 +102,85 @@ export interface MeshNodeConfig {
payload?: () => { status?: string; resources: BeaconResource[] };
}
/** How a discovered resource relates to this consumer (Scan card). */
export type ScanState = 'configured' | 'addable' | 'bound-elsewhere';
export interface ScanCandidate {
instance: string;
name: string;
version?: string;
resourceId: string;
caps: string[];
/** endpoints.http — what the consumer would register. */
url: string;
binds?: string;
state: ScanState;
/** The list entry that already holds this URL (state `configured`). */
configuredAs?: string;
/** A list-safe name to register it under. */
suggestedName: string;
}
/** Same JSON as meta-feeder-sdk `beacon::ScanReport`. */
export interface ScanReport {
cap: string;
self: string;
durationMs: number;
summary: { nodes: number; capable: number; configured: number; boundElsewhere: number; addable: number };
candidates: ScanCandidate[];
}
/** Lower-case, `[a-z0-9._-]` only — accepted by every consumer's name rules. */
export function suggestedName(instance: string): string {
const s = instance.trim().toLowerCase().replace(/[^a-z0-9._-]/g, '-');
return s || 'plugin';
}
const normUrl = (u: string) => u.trim().replace(/\/+$/, '');
/**
* Classify every resource matching `pattern` against the consumer's
* `(name, url)` list. Mirrors meta-feeder-sdk `beacon::classify`.
*/
export function classifyScan(
pattern: string,
self: string,
neighbors: MeshNeighbor[],
configured: Array<[string, string]>,
): ScanReport {
const summary = { nodes: neighbors.length, capable: 0, configured: 0, boundElsewhere: 0, addable: 0 };
const candidates: ScanCandidate[] = [];
for (const n of neighbors) {
for (const r of n.resources) {
if (!resourceMatches(r, pattern)) continue;
const http = resourceEndpoint(r, 'http');
if (!http) continue; // nothing a consumer could register
const url = normUrl(http);
summary.capable++;
const hit = configured.find(([, u]) => normUrl(u) === url);
let state: ScanState;
if (hit) { state = 'configured'; summary.configured++; }
else if (r.binds && r.binds !== self) { state = 'bound-elsewhere'; summary.boundElsewhere++; }
else { state = 'addable'; summary.addable++; }
candidates.push({
instance: n.instance,
name: n.name,
...(n.version ? { version: n.version } : {}),
resourceId: r.id,
caps: r.caps ?? [],
url,
...(r.binds ? { binds: r.binds } : {}),
state,
...(hit ? { configuredAs: hit[0] } : {}),
suggestedName: suggestedName(n.instance),
});
}
}
const rank: Record<ScanState, number> = { addable: 0, configured: 1, 'bound-elsewhere': 2 };
candidates.sort((a, b) => rank[a.state] - rank[b.state] || a.instance.localeCompare(b.instance));
return { cap: pattern, self, durationMs: 0, summary, candidates };
}
/**
* Does capability `cap` satisfy `pattern`? `*` matches everything; an `@N` on
* the pattern must equal the cap's contract (none ignores it); `x/*` matches
@@ -333,6 +412,19 @@ export class MeshNode {
return [...best.values()].sort((a, b) => a.name.localeCompare(b.name));
}
/**
* The Scan card: probe everyone, wait `waitMs` for the replies, then
* classify what matches `pattern` against `configured` ([name, url]).
*/
async scan(pattern: string, configured: Array<[string, string]>, waitMs = 1500): Promise<ScanReport> {
const started = Date.now();
this.probe();
await new Promise((r) => setTimeout(r, waitMs));
const report = classifyScan(pattern, this.cfg.instance, this.getNeighbors(), configured);
report.durationMs = Date.now() - started;
return report;
}
/** This node as a row, so a UI can render itself without waiting. */
self(): MeshNeighbor {
const { status, resources } = this.payload();
@@ -557,6 +649,11 @@ export class MetaCoreLocator {
return this.node.self();
}
/** The Scan card — see {@link MeshNode.scan}. */
scan(pattern: string, configured: Array<[string, string]>, waitMs = 1500): Promise<ScanReport> {
return this.node.scan(pattern, configured, waitMs);
}
probe(want: string[] = []): void {
this.node.probe(want);
}
+5 -5
View File
@@ -1,7 +1,6 @@
import {config} from "./config/EnvConfig.js";
import os from 'os';
import {existsSync} from 'fs';
import {WatchedFileProcessor} from "./logic/WatchedFileProcessor.js";
import {UnifiedAPIServer} from "./api/UnifiedAPIServer.js";
import {StreamingPipeline} from "./logic/pipeline/StreamingPipeline.js";
@@ -168,8 +167,11 @@ process.on('SIGINT', async () => {
const pluginManager = await initializePluginManager();
console.log('[Startup] Plugin manager initialized');
// Initialize container plugins if config file exists
if (existsSync(config.CONTAINER_PLUGINS_CONFIG)) {
// Container plugins: the ones spawned from plugins.yml AND the external
// ones added by URL (beacon Scan card). Always initialised — with no
// plugins.yml and no Docker it still serves the external ones, and the
// Plugins page can add the first one.
{
console.log('[Startup] Initializing container plugins...');
try {
// Get webdavUrlInternal from meta-core via LeaderClient (for container-to-container access)
@@ -215,8 +217,6 @@ process.on('SIGINT', async () => {
console.error('[Startup] Failed to initialize container plugins:', error);
console.log('[Startup] Continuing without container plugins...');
}
} else {
console.log(`[Startup] Container plugins config not found at ${config.CONTAINER_PLUGINS_CONFIG}, skipping`);
}
// Initialize hash index cache (loads existing hashes from disk)
+15 -1
View File
@@ -102,10 +102,24 @@ export interface IKVClient {
setMetadataProperty(hashId: string, property: string, value: string): Promise<void>;
/**
* Delete all metadata for a file
* Delete all metadata for a file. A no-op against meta-core v2.0.0+
* (claims model: records outlive files).
*/
deleteMetadataFlat(hashId: string): Promise<number>;
/**
* Forward an already-signed claim batch to meta-core's `POST /api/claims`
* untouched (the relay plugins write through). Optional: only the
* meta-core-backed client implements it.
*/
relayClaims?(body: unknown): Promise<{ status: number; body: unknown }>;
/**
* Forward `GET /api/meta/{cid}/claims` (+ query string) to meta-core
* verbatim. Optional, like relayClaims.
*/
fetchClaims?(cid: string, search: string): Promise<{ status: number; body: unknown }>;
/**
* Get all unique hash IDs (files) stored in KV
*/
@@ -23,7 +23,7 @@
* api-mediated-access lockdown; everything routes over HTTP.
*/
import { MetaCoreLocator, type MeshNeighbor } from '../discovery/meshdisco.js';
import { MetaCoreLocator, type MeshNeighbor, type ScanReport } from '../discovery/meshdisco.js';
import type { LeaderLockInfo } from './IKVClient.js';
export interface LeaderClientConfig {
@@ -273,6 +273,11 @@ export class LeaderClient {
return this.locator.self();
}
/** Beacon v2 Scan card: probe, wait, classify `pattern` against `configured`. */
scan(pattern: string, configured: Array<[string, string]>, waitMs = 1500): Promise<ScanReport> {
return this.locator.scan(pattern, configured, waitMs);
}
close(): void {
this.onChangeCallbacks = [];
void this.locator.stop();
@@ -1,23 +1,29 @@
/**
* MetaCoreApiWriter — HTTP writer for metadata, replacing direct Redis writes.
* MetaCoreApiWriter — meta-sort's HTTP client for meta-core.
*
* meta-core owns the Redis schema (UUID-rooted, reverse-indexed by CID). Any
* service writing directly to Redis risks drifting the schema; the lockdown
* plan (docs/api-mediated-access.md in meta-core) routes every write through
* meta-core's HTTP /meta/{hash} family.
* Since meta-core v2.0.0 (claims model) every metadata write is a vote signed
* by meta-sort's own key (`METAMESH_SIGNING_KEY_FILE`) and posted to
* `POST /api/claims` (docs/implementation/metacore-claims-model.md). Signing
* lives in `meta-core-client.ts`, mirrored from the plugins.
*
* This writer covers the three operations meta-sort actually performs in
* production:
* - setMetadataFlat → PATCH /meta/{hash} (merge semantics)
* - setMetadataProperty → PUT /meta/{hash}/{key}
* - deleteMetadataFlat → DELETE /meta/{hash}
* - setMetadataFlat → one signed claim per field (one batch)
* - setMetadataProperty → one signed claim
* - deleteMetadataFlat → no-op: records describe content and outlive the
* file (§13 G3); there is no record delete any more
* - relayClaims → pass-through of plugins' signed claims (relay,
* never re-signed)
*
* Reads and stream consumption stay on Redis in PR B; PR C migrates those.
* `filePath` and `mtimeNano` are meta-core's file-watcher facts (`local_file`,
* unsigned and box-local) — meta-sort never claims them.
*/
import {
buildRecordFields,
buildFilePrefix,
} from './MetadataUtils.js';
import { MetaCoreClient } from './meta-core-client.js';
/** Watcher facts meta-core keeps in `local_file`; never written as claims. */
const LOCAL_FILE_FIELDS = ['filePath', 'mtimeNano'];
/** One file-backed root as listed by meta-core's GET /api/files/tuples. */
export interface FileTuple {
@@ -48,18 +54,19 @@ export interface MetaCoreApiWriterConfig {
export class MetaCoreApiWriter {
private apiUrl: string;
private timeoutMs: number;
private claims: MetaCoreClient;
constructor(config: MetaCoreApiWriterConfig) {
// Trim trailing slash so we can join paths predictably.
this.apiUrl = config.apiUrl.replace(/\/+$/, '');
this.timeoutMs = config.timeoutMs ?? 30000;
this.claims = new MetaCoreClient(this.apiUrl);
}
/**
* PATCH /meta/{hash}.
*
* meta-core's PATCH calls MergeMetadataFlat — merge semantics, matches
* what setMetadataFlat used to do via Redis pipeline of SETs.
* One signed claim per field, posted as a single batch. `hashId` is the
* content cid (meta-sort keys records by midhash256), which is what a claim
* names. Throws when meta-core refuses the batch.
*/
async setMetadataFlat(
hashId: string,
@@ -68,47 +75,63 @@ export class MetaCoreApiWriter {
): Promise<void> {
// `buildRecordFields` is the single write-shape boundary, shared with the
// direct-Redis path in RedisClient. It emits the `cids/<cid>` key-set and
// never a per-algorithm `cid_*` field — which meta-core would now reject
// with a 400 anyway.
const flat = buildRecordFields(metadata, excludeFields);
// never a per-algorithm `cid_*` field.
const flat = buildRecordFields(metadata, [...excludeFields, ...LOCAL_FILE_FIELDS]);
if (Object.keys(flat).length === 0) return;
await this.fetchJson('PATCH', `/meta/${encodeURIComponent(hashId)}`, flat);
const ok = await this.claims.mergeMetadata(hashId, flat);
if (!ok) throw new Error(`[MetaCoreApiWriter] claims for ${hashId} were not accepted`);
}
/**
* PUT /meta/{hash}/{key}.
*
* meta-core accepts either JSON {"value":"..."} or plain text; we use
* the JSON form to avoid ambiguity with values that happen to look like
* JSON themselves.
*/
/** One signed claim. Throws when meta-core refuses it. */
async setMetadataProperty(hashId: string, property: string, value: string): Promise<void> {
await this.fetchJson(
'PUT',
`/meta/${encodeURIComponent(hashId)}/${this.encodePropertyPath(property)}`,
{ value }
);
if (LOCAL_FILE_FIELDS.includes(property)) return;
const ok = await this.claims.setProperty(hashId, property, value);
if (!ok) throw new Error(`[MetaCoreApiWriter] claim ${hashId}/${property} was not accepted`);
}
/**
* DELETE /meta/{hash}.
*
* Removes every property and unregisters the hashId from file:__index__.
* No-op since the claims model: a record describes content, and votes about
* content stay true when one copy of the file disappears. meta-core's
* watcher drops the file's `local_file` row on its own (§13 G3).
*/
async deleteMetadataFlat(hashId: string): Promise<number> {
const body = await this.fetchJson(
'DELETE',
`/meta/${encodeURIComponent(hashId)}`,
null
);
// meta-core's response is {success, hashId, deleted: N}.
if (body && typeof body === 'object' && typeof (body as any).deleted === 'number') {
return (body as any).deleted;
}
async deleteMetadataFlat(_hashId: string): Promise<number> {
return 0;
}
/**
* Forward `GET /api/meta/{cid}/claims[?query]` to meta-core verbatim (plugins
* read their own csv-set vote through it before appending).
*/
async fetchClaims(cid: string, search: string): Promise<{ status: number; body: unknown }> {
const response = await fetch(`${this.apiUrl}/api/meta/${encodeURIComponent(cid)}/claims${search}`, {
method: 'GET',
signal: AbortSignal.timeout(this.timeoutMs),
headers: { Accept: 'application/json' },
});
const text = await response.text();
let parsed: unknown = text;
try { parsed = text ? JSON.parse(text) : null; } catch { /* keep raw text */ }
return { status: response.status, body: parsed };
}
/**
* Forward an already-signed claim batch to meta-core untouched (the relay
* plugins write through). Returns meta-core's status and body verbatim.
*/
async relayClaims(body: unknown): Promise<{ status: number; body: unknown }> {
const response = await fetch(`${this.apiUrl}/api/claims`, {
method: 'POST',
signal: AbortSignal.timeout(this.timeoutMs),
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(body),
});
const text = await response.text();
let parsed: unknown = text;
try { parsed = text ? JSON.parse(text) : null; } catch { /* keep raw text */ }
return { status: response.status, body: parsed };
}
/**
* GET /meta/{hash}. Returns the flat metadata map (or null if absent).
*/
@@ -453,6 +453,22 @@ export class RedisKVClient implements IKVClient {
await this.redis.sadd(this.buildKey('file:__index__'), hashId);
}
/** Pass `GET /api/meta/{cid}/claims` through to meta-core (plugin relay). */
async fetchClaims(cid: string, search: string): Promise<{ status: number; body: unknown }> {
if (!this.writer) {
return { status: 503, body: { error: 'meta-core API not configured' } };
}
return this.writer.fetchClaims(cid, search);
}
/** Pass a signed claim batch through to meta-core (plugin relay). */
async relayClaims(body: unknown): Promise<{ status: number; body: unknown }> {
if (!this.writer) {
return { status: 503, body: { error: 'meta-core API not configured' } };
}
return this.writer.relayClaims(body);
}
async deleteMetadataFlat(hashId: string): Promise<number> {
if (this.writer) {
return this.writer.deleteMetadataFlat(hashId);
@@ -0,0 +1,380 @@
/**
* meta-core client: signed claim writes (MMUR2) + plain reads.
*
* MIRRORED byte-for-byte across every `metamesh-plugin-*` TypeScript plugin and
* meta-sort-core (`src/kv/meta-core-client.ts`) — guarded by
* `scripts/check-mirrors.sh`. Edit one copy, then copy it everywhere.
*
* Every write is a vote signed by THIS container's key
* (docs/implementation/metacore-claims-model.md §3, §9):
*
* bytes_to_sign = "MMUR2\n" || canonical CBOR [cid, uid, key, value, ts]
* sig = ECDSA-secp256k1(SHA-256(bytes)), compact r||s, low-S
*
* and is posted to `POST {baseUrl}/api/claims` — meta-core directly, or
* meta-sort's pass-through relay when the plugin runs under meta-sort. The
* encoding is pinned by meta-core's `internal/claim/testdata/claim-vectors.json`
* (vendored as `test/claim-vectors.json`).
*
* Key: `METAMESH_SIGNING_KEY` (64 hex chars) or `METAMESH_SIGNING_KEY_FILE`
* (read; generated and written 0600 if missing). With neither, writes are
* refused (logged, return false) — no silent throwaway identities.
*
* Fails gracefully if meta-core is unavailable: logs and returns, never throws.
*/
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
// ---------------------------------------------------------------- encoding --
const DOMAIN = Buffer.from('MMUR2\n', 'utf8');
const B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
const N = BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141');
const HALF_N = N >> 1n;
/** A claim value: text (public), bytes (private envelope) or null (retraction). */
export type ClaimValue = string | Uint8Array | null;
export interface SignedClaim {
cid: string;
uid: string;
key: string;
value: ClaimValue;
ts: number;
sig: Uint8Array;
}
function head(major: number, n: number | bigint): Buffer {
const m = major << 5;
const v = BigInt(n);
if (v < 24n) return Buffer.from([m | Number(v)]);
if (v <= 0xffn) return Buffer.from([m | 24, Number(v)]);
if (v <= 0xffffn) {
const b = Buffer.alloc(3);
b[0] = m | 25;
b.writeUInt16BE(Number(v), 1);
return b;
}
if (v <= 0xffffffffn) {
const b = Buffer.alloc(5);
b[0] = m | 26;
b.writeUInt32BE(Number(v), 1);
return b;
}
const b = Buffer.alloc(9);
b[0] = m | 27;
b.writeBigUInt64BE(v, 1);
return b;
}
function text(s: string): Buffer {
const raw = Buffer.from(s, 'utf8');
return Buffer.concat([head(3, raw.length), raw]);
}
/** The exact bytes an MMUR2 signature covers. */
export function signedBytes(cid: string, uid: string, key: string, value: ClaimValue, ts: number): Buffer {
let v: Buffer;
if (value === null) v = Buffer.from([0xf6]);
else if (typeof value === 'string') v = text(value);
else v = Buffer.concat([head(2, value.length), Buffer.from(value)]);
return Buffer.concat([DOMAIN, head(4, 5), text(cid), text(uid), text(key), v, head(0, ts)]);
}
function base58Encode(bytes: Uint8Array): string {
let n = BigInt('0x' + (Buffer.from(bytes).toString('hex') || '0'));
let out = '';
while (n > 0n) {
out = B58[Number(n % 58n)] + out;
n /= 58n;
}
for (const b of bytes) {
if (b !== 0) break;
out = '1' + out;
}
return out;
}
function base58Decode(s: string): Buffer {
let n = 0n;
for (const ch of s) {
const i = B58.indexOf(ch);
if (i < 0) throw new Error(`invalid base58 character ${ch}`);
n = n * 58n + BigInt(i);
}
let hex = n === 0n ? '' : n.toString(16);
if (hex.length % 2) hex = '0' + hex;
let zeros = 0;
while (zeros < s.length && s[zeros] === '1') zeros++;
return Buffer.concat([Buffer.alloc(zeros), Buffer.from(hex, 'hex')]);
}
function b64url(b: Buffer): string {
return b.toString('base64url');
}
function publicKeyFromCompressed(compressed: Buffer): crypto.KeyObject {
const full = crypto.ECDH.convertKey(compressed, 'secp256k1', undefined, undefined, 'uncompressed') as Buffer;
return crypto.createPublicKey({
key: { kty: 'EC', crv: 'secp256k1', x: b64url(full.subarray(1, 33)), y: b64url(full.subarray(33, 65)) },
format: 'jwk',
});
}
/** Rewrite a compact signature to its low-S form (MMUR2 refuses high-S). */
function lowS(sig: Buffer): Buffer {
const s = BigInt('0x' + sig.subarray(32).toString('hex'));
if (s <= HALF_N) return sig;
const fixed = Buffer.from((N - s).toString(16).padStart(64, '0'), 'hex');
return Buffer.concat([sig.subarray(0, 32), fixed]);
}
/** True when the claim's signature is a valid low-S signature by its uid. */
export function verifyClaim(c: SignedClaim): boolean {
try {
const sig = Buffer.from(c.sig);
if (sig.length !== 64) return false;
if (BigInt('0x' + sig.subarray(32).toString('hex')) > HALF_N) return false;
if (!c.uid.startsWith('z')) return false;
const pub = base58Decode(c.uid.slice(1));
if (pub.length !== 33) return false;
return crypto.verify(
'sha256',
signedBytes(c.cid, c.uid, c.key, c.value, c.ts),
{ key: publicKeyFromCompressed(pub), dsaEncoding: 'ieee-p1363' },
sig,
);
} catch {
return false;
}
}
// ----------------------------------------------------------------- signer --
export class ClaimSigner {
readonly uid: string;
private readonly key: crypto.KeyObject;
private lastTs = 0;
constructor(privateKeyHex: string) {
const hex = privateKeyHex.trim().replace(/^0x/i, '');
if (!/^[0-9a-fA-F]{64}$/.test(hex)) throw new Error('signing key must be 64 hex characters');
const d = Buffer.from(hex, 'hex');
const ecdh = crypto.createECDH('secp256k1');
ecdh.setPrivateKey(d);
const full = ecdh.getPublicKey(null, 'uncompressed');
this.uid = 'z' + base58Encode(ecdh.getPublicKey(null, 'compressed'));
this.key = crypto.createPrivateKey({
key: {
kty: 'EC', crv: 'secp256k1', d: b64url(d),
x: b64url(full.subarray(1, 33)), y: b64url(full.subarray(33, 65)),
},
format: 'jwk',
});
}
/** Milliseconds, strictly increasing within this process (ts is the version). */
nextTs(): number {
this.lastTs = Math.max(Date.now(), this.lastTs + 1);
return this.lastTs;
}
sign(cid: string, key: string, value: ClaimValue, ts: number = this.nextTs()): SignedClaim {
const raw = crypto.sign('sha256', signedBytes(cid, this.uid, key, value, ts), {
key: this.key,
dsaEncoding: 'ieee-p1363',
});
return { cid, uid: this.uid, key, value, ts, sig: lowS(raw) };
}
}
let cachedSigner: ClaimSigner | null | undefined;
/**
* The process signer from the environment, or null when no key is configured.
* Read lazily on first write; `resetSignerForTests()` forgets it.
*/
export function loadSigner(): ClaimSigner | null {
if (cachedSigner !== undefined) return cachedSigner;
const inline = process.env.METAMESH_SIGNING_KEY;
const file = process.env.METAMESH_SIGNING_KEY_FILE;
try {
if (inline) {
cachedSigner = new ClaimSigner(inline);
} else if (file) {
if (!fs.existsSync(file)) {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, crypto.randomBytes(32).toString('hex') + '\n', { mode: 0o600 });
}
cachedSigner = new ClaimSigner(fs.readFileSync(file, 'utf8'));
} else {
cachedSigner = null;
}
} catch (error) {
console.warn(`[MetaCoreClient] Signing key unusable: ${error instanceof Error ? error.message : String(error)}`);
cachedSigner = null;
}
if (cachedSigner) console.log(`[MetaCoreClient] Signing claims as ${cachedSigner.uid}`);
else console.warn('[MetaCoreClient] No METAMESH_SIGNING_KEY / METAMESH_SIGNING_KEY_FILE — metadata writes are refused');
return cachedSigner;
}
export function resetSignerForTests(): void {
cachedSigner = undefined;
}
/** The §3.4 JSON form. */
export function claimToJSON(c: SignedClaim): Record<string, unknown> {
let value: unknown = null;
if (typeof c.value === 'string') value = c.value;
else if (c.value) value = { b64: Buffer.from(c.value).toString('base64') };
return { cid: c.cid, uid: c.uid, key: c.key, value, ts: c.ts, sig: Buffer.from(c.sig).toString('base64') };
}
// ----------------------------------------------------------------- client --
export class MetaCoreClient {
constructor(private baseUrl: string) {}
private async safeFetch(url: string, options: RequestInit): Promise<Response | null> {
try {
return await fetch(url, { ...options, signal: AbortSignal.timeout(10000) });
} catch (error) {
console.warn(`[MetaCoreClient] Warning: meta-core unavailable at ${this.baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
return null;
}
}
/**
* Sign and post claims about `cid`. True when every claim was accepted (or
* was already stored: `unchanged` / `stale` are not failures).
*/
async writeClaims(cid: string, values: Array<[string, ClaimValue]>): Promise<boolean> {
if (values.length === 0) return true;
const signer = loadSigner();
if (!signer) return false;
const claims = values.map(([key, value]) => claimToJSON(signer.sign(cid, key, value)));
const response = await this.safeFetch(`${this.baseUrl}/api/claims`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(claims),
});
if (!response) return false;
if (!response.ok) {
console.warn(`[MetaCoreClient] Claims for ${cid} rejected: ${response.status}`);
return false;
}
const statuses = await response.json().catch(() => null) as Array<{ status?: string; reason?: string }> | null;
const bad = (statuses ?? []).filter((s) => s.status === 'bad_signature' || s.status === 'bad_request');
if (bad.length > 0) {
console.warn(`[MetaCoreClient] ${bad.length} claim(s) for ${cid} refused: ${bad[0].status} ${bad[0].reason ?? ''}`);
return false;
}
return true;
}
/** One text claim. */
async setProperty(hashId: string, key: string, value: string): Promise<boolean> {
return this.writeClaims(hashId, [[key, String(value)]]);
}
/** One text claim per entry, in a single batch. */
async mergeMetadata(hashId: string, metadata: Record<string, string>): Promise<boolean> {
return this.writeClaims(hashId, Object.entries(metadata).map(([k, v]) => [k, String(v)]));
}
/**
* Retract this signer's own vote for `key`. Other signers' votes for the
* same key are untouched (there are no negative votes).
*/
async deleteProperty(hashId: string, key: string): Promise<boolean> {
return this.writeClaims(hashId, [[key, null]]);
}
/**
* Append a member to a legacy csv-set field (`genres`, `studio`, `tags`,
* `announceList`, …) — the comma-joined shape readers still parse (the
* METADATA_KEYS §14.12 key-set migration is out of scope for phase 1).
*
* Under claims a signer owns only its OWN vote, so this reads this
* signer's current claim for (cid, key) from
* `GET /api/meta/{cid}/claims?key=<key>` (other signers' claims are
* ignored), adds the member if absent and signs the new full value as one
* text claim. Members are kept raw (no escaping), same as the old
* meta-sort `_add` proxy. A member already present writes nothing.
*/
async addToSet(hashId: string, key: string, value: string): Promise<boolean> {
const member = String(value);
if (!member) return true;
const signer = loadSigner();
if (!signer) return false;
const current = await this.ownClaimValue(hashId, key, signer.uid);
if (current === undefined) return false; // could not read: never clobber our own set
const members = current ? current.split(',').map((v) => v.trim()).filter(Boolean) : [];
if (members.includes(member)) return true;
return this.writeClaims(hashId, [[key, [...members, member].join(',')]]);
}
/**
* This signer's newest text claim for (cid, key): the value, `null` when it
* has none, `undefined` when the claims could not be read.
*/
private async ownClaimValue(cid: string, key: string, uid: string): Promise<string | null | undefined> {
const url = `${this.baseUrl}/api/meta/${encodeURIComponent(cid)}/claims?key=${encodeURIComponent(key)}`;
const response = await this.safeFetch(url, { method: 'GET' });
if (!response) return undefined;
if (response.status === 404) return null;
if (!response.ok) {
console.warn(`[MetaCoreClient] Failed to read claims for ${cid}/${key}: ${response.status}`);
return undefined;
}
const body = await response.json().catch(() => null) as unknown;
const list = (Array.isArray(body) ? body : (body as { claims?: unknown })?.claims) as
Array<{ uid?: string; key?: string; value?: unknown; ts?: number }> | undefined;
let best: { value: string; ts: number } | null = null;
for (const c of Array.isArray(list) ? list : []) {
if (c.uid !== uid || c.key !== key || typeof c.value !== 'string') continue;
const ts = Number(c.ts) || 0;
if (!best || ts > best.ts) best = { value: c.value, ts };
}
return best ? best.value : null;
}
async getProperty(hashId: string, key: string): Promise<string | null> {
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { method: 'GET' });
if (!response || !response.ok) return null;
const data = await response.json() as { value?: unknown };
return data.value === undefined || data.value === null ? null : String(data.value);
}
/**
* Whole merged record, in whatever form the endpoint serves (meta-sort's
* /meta is nested, meta-core's is flat) — callers flatten. `null` when the
* call itself failed, `{}` when the record does not exist.
*/
async getMetadata(hashId: string): Promise<Record<string, unknown> | null> {
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}`, { method: 'GET' });
if (!response) return null;
if (response.status === 404) return {};
if (!response.ok) return null;
const data = await response.json() as { metadata?: Record<string, unknown> };
return data.metadata ?? {};
}
/**
* Compute the CID of a file under FILES_PATH via meta-core's `POST /file/cid`.
* @param filePath - path relative to FILES_PATH (e.g. "poster/Movie (2024)_poster.jpg")
*/
async computeFileCID(filePath: string): Promise<string | null> {
const response = await this.safeFetch(`${this.baseUrl}/file/cid`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: filePath }),
});
if (!response || !response.ok) return null;
const data = await response.json().catch(() => null) as { cid?: string } | null;
return data?.cid ?? null;
}
}
@@ -87,7 +87,8 @@ export class JellyfinFormatHandler implements IMetadataFormatHandler {
// Title: the display name. `titles/*` is an unordered name set with no
// preferred member, so it is never the NFO title (METADATA_KEYS.md §3).
const title = metadata.title || metadata.originalTitle;
// `parsedTitle` is filename-parser's guess (claims model, D12): last resort.
const title = metadata.title || metadata.originalTitle || (metadata as { parsedTitle?: string }).parsedTitle;
if (title) jellyfinFields.title = title;
// IDs
@@ -631,20 +631,11 @@ export class FileProcessorPiscina implements FileAnalyzerInterface{
const metadata = this.database.get(filePath);
this.database.delete(filePath);
// Delete from KV if configured (using nested key architecture)
if (this.kvClient && metadata) {
try {
const hashId = metadata.hashId;
// Delete all properties for this file using nested key architecture
if (hashId) {
const deletedCount = await this.kvClient.deleteMetadataFlat(hashId);
console.log(`Metadata deleted from KV: /file/${hashId} (${deletedCount} keys)`);
}
} catch (metaError) {
// Log error but don't fail the entire process
console.error(`Failed to delete metadata from KV:`, metaError);
}
// Nothing to delete in meta-core: since the claims model a record
// describes content and its votes outlive this copy of the file.
// meta-core's own watcher drops the file's `local_file` row.
if (metadata?.hashId) {
console.log(`File removed: ${filePath} (/file/${metadata.hashId} kept — records outlive files)`);
}
}
@@ -220,6 +220,17 @@ export class PluginManager extends EventEmitter {
return;
}
// Forget container-backed plugins that are gone (an external plugin
// removed from the Plugins page); they have no local dir.
const present = new Set(status.plugins.map((p) => p.pluginId));
for (const [id, loaded] of this.loadedPlugins) {
if (loaded.pluginDir === '' && !present.has(id)) {
this.loadedPlugins.delete(id);
this.manifests.delete(id);
this.activePluginIds.delete(id);
}
}
// Load state for plugin active status
const state = await this.loadState();
@@ -0,0 +1,60 @@
import { useEffect, useRef } from 'react';
import '../meta-beacon-scan.js';
/**
* The Plugins page's beacon v2 Scan card: enrichment plugins advertising on
* the network (`metamesh.enrich/<id>`, typically MetaPlugin* store apps), with
* an Add per new one. A thin wrapper around the framework-free
* <meta-beacon-scan> element shared with meta-share and meta-gateway; the
* --mm-scan-* tokens map this dashboard's palette onto it.
*
* Add registers the plugin as an EXTERNAL plugin (POST /api/plugins/external):
* meta-sort calls it by URL and never starts or stops it.
*/
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace JSX {
interface IntrinsicElements {
'meta-beacon-scan': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> & {
'scan-endpoint'?: string;
'add-endpoint'?: string;
'add-extra'?: string;
label?: string;
};
}
}
}
const TOKENS = {
display: 'block',
'--mm-scan-fg': 'var(--text-primary)',
'--mm-scan-bg': 'var(--bg-secondary)',
'--mm-scan-border': 'var(--border-color)',
'--mm-scan-accent': 'var(--accent-primary)',
'--mm-scan-err': 'var(--accent-secondary)',
} as React.CSSProperties;
function BeaconScanCard({ onAdded }: { onAdded: () => void }) {
const ref = useRef<HTMLElement>(null);
useEffect(() => {
const el = ref.current;
if (!el) return;
const handler = () => onAdded();
el.addEventListener('beacon-added', handler);
return () => el.removeEventListener('beacon-added', handler);
}, [onAdded]);
return (
<meta-beacon-scan
ref={ref}
style={TOKENS}
scan-endpoint="/api/plugins/discover"
add-endpoint="/api/plugins/external"
label="enrichment plugins"
/>
);
}
export default BeaconScanCard;
@@ -0,0 +1,277 @@
/**
* <meta-beacon-scan> — "what plugins are on the network?", as a card.
*
* The Scan button POSTs to the host's own discover endpoint, which probes the
* beacon v2 group (239.255.99.1:9099), waits for the replies, and classifies
* every resource matching the host's capability (transport plugins for
* meta-share, feeders for meta-gateway, enrichment plugins for meta-sort):
*
* 10 nodes on the network · 3 transport plugins · 3 already configured
*
* Each `addable` row gets an Add button that POSTs {name, url} to the host's
* existing add endpoint. Response shape: meta-feeder-sdk `beacon::ScanReport`
* (docs/project-architecture/beacon-v2.md).
*
* ⚠ MIRRORED FILE. Byte-identical copies live in meta-share, meta-gateway and
* meta-sort-ui; see `scripts/check-mirrors.sh`. Edit one → edit all.
*
* Shadow DOM for the same reason as <meta-service-menu>: the three hosts use
* incompatible token vocabularies. Style it from the host with
* --mm-scan-fg, --mm-scan-bg, --mm-scan-border, --mm-scan-accent,
* --mm-scan-ok, --mm-scan-err
*
* Attributes:
* scan-endpoint POST → ScanReport (required)
* add-endpoint POST {name, url, ...add-extra} (required)
* add-extra JSON object merged into the add body (optional)
* label what the host calls a capable resource, plural
* (default "plugins")
*
* Events (bubbling, composed):
* beacon-added detail = { candidate, response }, after a successful Add
*/
const STATE_TEXT = {
addable: "new",
configured: "configured",
"bound-elsewhere": "bound elsewhere",
};
const TEMPLATE = `
<style>
:host {
--_fg: var(--mm-scan-fg, #e8eaed);
--_bg: var(--mm-scan-bg, transparent);
--_border: var(--mm-scan-border, rgba(255, 255, 255, 0.14));
--_accent: var(--mm-scan-accent, #4ecdc4);
--_ok: var(--mm-scan-ok, #3fb950);
--_err: var(--mm-scan-err, #f85149);
display: block;
color: var(--_fg);
font-family: inherit;
font-size: 14px;
line-height: 1.4;
}
.card {
background: var(--_bg);
border: 1px solid var(--_border);
border-radius: 10px;
padding: 0.9rem 1rem;
}
.head { display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap; }
.title { font-weight: 600; }
.hint { opacity: 0.7; font-size: 0.85em; }
.spacer { flex: 1; }
button {
font: inherit;
font-size: 0.85em;
cursor: pointer;
color: var(--_fg);
background: transparent;
border: 1px solid var(--_border);
border-radius: 6px;
padding: 0.3rem 0.8rem;
}
button:hover:not(:disabled) { border-color: var(--_accent); color: var(--_accent); }
button:disabled { opacity: 0.5; cursor: progress; }
button.add { border-color: var(--_accent); color: var(--_accent); }
.summary { margin-top: 0.6rem; font-size: 0.9em; }
.summary b { color: var(--_accent); }
.error { margin-top: 0.6rem; color: var(--_err); font-size: 0.85em; }
ul { list-style: none; margin: 0.6rem 0 0; padding: 0; }
li {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 0.2rem 0.75rem;
align-items: center;
padding: 0.5rem 0;
border-top: 1px solid var(--_border);
}
.who { display: flex; gap: 0.5rem; align-items: baseline; flex-wrap: wrap; min-width: 0; }
.name { font-weight: 600; }
.muted { opacity: 0.65; font-size: 0.85em; }
code { font-size: 0.8em; opacity: 0.8; overflow-wrap: anywhere; }
.chips { display: inline-flex; gap: 0.3rem; flex-wrap: wrap; }
.chip {
font-size: 0.72em;
padding: 0 0.4rem;
border-radius: 3px;
border: 1px solid var(--_border);
opacity: 0.85;
}
.state { font-size: 0.75em; padding: 0.05rem 0.45rem; border-radius: 999px; border: 1px solid currentColor; }
.state.addable { color: var(--_accent); }
.state.configured { color: var(--_ok); }
.state.bound-elsewhere { opacity: 0.6; }
.row-actions { display: flex; gap: 0.5rem; align-items: center; grid-row: span 2; }
.row-err { color: var(--_err); font-size: 0.8em; }
</style>
<div class="card">
<div class="head">
<span class="title">Beacon discovery</span>
<span class="hint">plugins advertising themselves on this network</span>
<span class="spacer"></span>
<button class="scan" type="button">Scan</button>
</div>
<div class="summary" hidden></div>
<div class="error" hidden></div>
<ul></ul>
</div>
`;
function h(tag, cls, text) {
const n = document.createElement(tag);
if (cls) n.className = cls;
if (text != null) n.textContent = text;
return n;
}
async function readError(res) {
const body = await res.text().catch(() => "");
try {
const j = JSON.parse(body);
return j.error || j.message || body || `HTTP ${res.status}`;
} catch {
return body || `HTTP ${res.status}`;
}
}
class MetaBeaconScan extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = TEMPLATE;
this._scanBtn = this.shadowRoot.querySelector("button.scan");
this._summary = this.shadowRoot.querySelector(".summary");
this._error = this.shadowRoot.querySelector(".error");
this._list = this.shadowRoot.querySelector("ul");
this._busy = false;
}
connectedCallback() {
if (this._wired) return;
this._wired = true;
this._scanBtn.addEventListener("click", () => this.scan());
}
get label() {
return this.getAttribute("label") || "plugins";
}
async scan() {
const endpoint = this.getAttribute("scan-endpoint");
if (!endpoint || this._busy) return;
this._busy = true;
this._scanBtn.disabled = true;
this._scanBtn.textContent = "Scanning…";
this._error.hidden = true;
try {
const res = await fetch(endpoint, { method: "POST", headers: { Accept: "application/json" } });
if (!res.ok) throw new Error(await readError(res));
this._render(await res.json());
} catch (e) {
// Keep the last result visible; just say what went wrong.
this._error.textContent = `Scan failed: ${e.message}`;
this._error.hidden = false;
} finally {
this._busy = false;
this._scanBtn.disabled = false;
this._scanBtn.textContent = "Scan again";
}
}
_render(report) {
const s = report.summary || {};
this._summary.replaceChildren();
const part = (n, text) => {
const span = h("span");
span.append(h("b", null, String(n ?? 0)), ` ${text}`);
return span;
};
const parts = [
part(s.nodes, s.nodes === 1 ? "node on the network" : "nodes on the network"),
part(s.capable, this.label),
part(s.configured, "already configured"),
part(s.addable, "new"),
];
if (s.boundElsewhere) parts.push(part(s.boundElsewhere, "bound to another consumer"));
parts.forEach((p, i) => {
if (i) this._summary.append(" · ");
this._summary.append(p);
});
this._summary.hidden = false;
this._list.replaceChildren(...(report.candidates || []).map((c) => this._row(c)));
}
_row(c) {
const li = h("li");
const who = h("div", "who");
who.append(h("span", "name", c.instance));
if (c.name && c.name !== c.instance) who.append(h("span", "muted", c.name));
if (c.version) who.append(h("span", "muted", `v${c.version}`));
const chips = h("span", "chips");
for (const cap of c.caps || []) chips.append(h("span", "chip", cap));
who.append(chips);
const actions = h("div", "row-actions");
const state = h("span", `state ${c.state}`, STATE_TEXT[c.state] || c.state);
if (c.state === "configured" && c.configuredAs) state.title = `listed as "${c.configuredAs}"`;
if (c.state === "bound-elsewhere" && c.binds) state.title = `belongs to ${c.binds}`;
actions.append(state);
if (c.state === "addable") {
const add = h("button", "add", "Add");
add.type = "button";
add.addEventListener("click", () => this._add(c, add, li));
actions.append(add);
}
const where = h("div");
where.append(h("code", null, c.url));
li.append(who, actions, where);
return li;
}
async _add(candidate, btn, li) {
const endpoint = this.getAttribute("add-endpoint");
if (!endpoint) return;
let extra = {};
try {
extra = JSON.parse(this.getAttribute("add-extra") || "{}");
} catch {
/* a malformed attribute must not block the add */
}
btn.disabled = true;
btn.textContent = "Adding…";
li.querySelector(".row-err")?.remove();
try {
const res = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ ...extra, name: candidate.suggestedName, url: candidate.url }),
});
if (!res.ok) throw new Error(await readError(res));
const text = await res.text();
let response = null;
try {
response = text ? JSON.parse(text) : null;
} catch {
response = text;
}
this.dispatchEvent(
new CustomEvent("beacon-added", { bubbles: true, composed: true, detail: { candidate, response } }),
);
btn.textContent = "Added";
} catch (e) {
btn.disabled = false;
btn.textContent = "Add";
li.append(h("div", "row-err", e.message));
}
}
}
if (!customElements.get("meta-beacon-scan")) {
customElements.define("meta-beacon-scan", MetaBeaconScan);
}
export default MetaBeaconScan;
@@ -5,6 +5,7 @@ import {
PluginTimingsResponse
} from '../types';
import { formatMs, formatNumber } from '../utils/format';
import BeaconScanCard from '../components/BeaconScanCard';
interface AddPluginForm {
pluginId: string;
@@ -33,6 +34,8 @@ function Plugins() {
cpus: '0.5',
});
const [restartAllStatus, setRestartAllStatus] = useState<string | null>(null);
// Plugins meta-sort reaches by URL but did not spawn (added from the Scan card).
const [externalUrls, setExternalUrls] = useState<Record<string, string>>({});
const fetchPlugins = useCallback(async () => {
try {
@@ -41,6 +44,14 @@ function Plugins() {
const data = await res.json();
setPluginsData(data);
setError(null);
fetch('/api/plugins/containers')
.then((r) => (r.ok ? r.json() : null))
.then((c: { plugins?: Array<{ id: string; kind?: string; url?: string }> } | null) => {
const map: Record<string, string> = {};
for (const p of c?.plugins ?? []) if (p.kind === 'external' && p.url) map[p.id] = p.url;
setExternalUrls(map);
})
.catch(() => {});
} else if (res.status === 503) {
setError('Plugin manager not yet initialized. Process a file to initialize plugins.');
}
@@ -370,6 +381,9 @@ function Plugins() {
<div className="plugin-info">
<span className="plugin-name">{plugin.name}</span>
<span className="plugin-version">v{plugin.version}</span>
{externalUrls[plugin.id] && (
<span className="plugin-external" title={`external: ${externalUrls[plugin.id]}`}>external</span>
)}
</div>
<label className="toggle" onClick={(e) => e.stopPropagation()}>
<input
@@ -677,6 +691,17 @@ function Plugins() {
</div>
)}
{/* Beacon v2: plugins advertising on the network, with Scan + Add */}
<div className="card beacon-scan-card">
<h2>Discover plugins</h2>
<p className="card-description">
Enrichment plugins installed as their own apps announce themselves on the network.
Scan to list them; Add registers one as an external plugin (meta-sort calls it by URL
and never starts or stops it). Remove it from the list like any other plugin.
</p>
<BeaconScanCard onAdded={fetchPlugins} />
</div>
{/* Queue Assignment Section */}
{pluginsData && pluginsData.activeCount > 0 && (
<div className="card queue-assignment-card">
@@ -920,6 +945,14 @@ function Plugins() {
overflow-y: auto;
}
.plugin-external {
margin-left: 0.5rem;
font-size: 0.7rem;
padding: 0 0.4rem;
border-radius: 3px;
border: 1px dashed var(--accent-primary);
color: var(--accent-primary);
}
.plugin-item {
background: var(--bg-tertiary);
border-radius: 8px;