4 Commits
Author SHA1 Message Date
Worph 331ebb65c4 CI: push to ipcr-push-85-17-246-67.ip.nsl.sh (the box's cert no longer covers nip.io) [skip ci] 2026-11-04 14:31:33 +00:00
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
14 changed files with 622 additions and 232 deletions
+6 -3
View File
@@ -2,10 +2,10 @@
# 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
# push ipcr-push-85-17-246-67.ip.nsl.sh/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
# The push goes to ipcr-push-85-17-246-67.ip.nsl.sh, 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
@@ -34,7 +34,7 @@ on:
default: 'latest'
env:
REGISTRY: ipcr-push-85-17-246-67.nip.io
REGISTRY: ipcr-push-85-17-246-67.ip.nsl.sh
IPCR_PULL: ipcr-watch.nsl.sh/ipns/metadec.eth
IMAGE_NAME: metadec.eth/${{ github.event.repository.name }}
@@ -81,6 +81,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}}
+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;
@@ -1321,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) {
@@ -1378,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('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('PATCH /meta/:hash merges metadata', async function() {
const response = await app.inject({
method: 'PATCH',
url: '/meta/testhash001',
payload: {
patchedField: 'patchedValue',
anotherField: '123'
}
});
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);
});
});
@@ -119,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
@@ -171,6 +181,10 @@ export const config: EnvConfig = {
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)
@@ -27,6 +27,7 @@ import type {
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';
/**
@@ -376,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
*/
@@ -445,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,
@@ -471,6 +500,8 @@ export class ContainerManager extends EventEmitter {
// 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,
+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
*/
@@ -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)`);
}
}