4 Commits
Author SHA1 Message Date
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
12 changed files with 712 additions and 227 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 }} images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: | tags: |
type=semver,pattern={{version}} 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=semver,pattern={{major}}.{{minor}}
type=sha,prefix= type=sha,prefix=
type=raw,value=latest,enable={{is_default_branch}} type=raw,value=latest,enable={{is_default_branch}}
+13
View File
@@ -44,6 +44,19 @@ http {
try_files $uri $uri/ /index.html; 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 # API routes
location /api/ { location /api/ {
proxy_pass http://api; proxy_pass http://api;
@@ -1321,9 +1321,8 @@ export class UnifiedAPIServer {
} }
/** /**
* Setup meta-core compatible API routes * Setup meta-core compatible API routes for container plugins: merged reads
* These routes allow container plugins to write metadata directly to Redis * (`GET /meta/...`) and the signed-claims relay (`POST /api/claims`).
* Matches the meta-core Go sidecar API for compatibility
*/ */
private setupMetaCoreRoutes(): void { private setupMetaCoreRoutes(): void {
if (!this.kvClient) { if (!this.kvClient) {
@@ -1378,125 +1377,43 @@ export class UnifiedAPIServer {
} }
}); });
// PUT /meta/{hash}/{key} - Set single property // Writes: plugins post signed MMUR2 claims; meta-sort relays them to
this.app.put<{ // meta-core untouched (never re-signs — the plugin is the signer). See
Params: { hash: string; '*': string }; // docs/implementation/metacore-claims-model.md §15.
Body: { value: string } this.app.post<{ Body: unknown }>('/api/claims', { bodyLimit: 16 * 1024 * 1024 }, async (request, reply) => {
}>('/meta/:hash/*', async (request, reply) => { if (!this.kvClient!.relayClaims) {
const { hash } = request.params; return reply.status(503).send({ error: 'meta-core API not configured' });
const key = request.params['*'];
const { value } = request.body || {};
if (!key) {
return reply.status(400).send({ error: 'Missing key' });
} }
if (value === undefined) {
return reply.status(400).send({ error: 'Missing value in body' });
}
try { try {
// Get existing metadata and merge const { status, body } = await this.kvClient!.relayClaims(request.body);
const existing = await this.kvClient!.getMetadataFlat(hash) || {}; return reply.status(status).send(body);
existing[key] = String(value);
await this.kvClient!.setMetadataFlat(hash, existing);
return { status: 'ok' };
} catch (error: any) { } catch (error: any) {
return reply.status(500).send({ return reply.status(502).send({ error: 'Failed to relay claims to meta-core', details: error.message });
error: 'Failed to set property',
details: error.message
});
} }
}); });
// DELETE /meta/{hash}/{key} - Delete single property // Claims read relay: plugins read their own csv-set vote before appending.
this.app.delete<{ this.app.get<{ Params: { cid: string } }>('/api/meta/:cid/claims', async (request, reply) => {
Params: { hash: string; '*': string } if (!this.kvClient!.fetchClaims) {
}>('/meta/:hash/*', async (request, reply) => { return reply.status(503).send({ error: 'meta-core API not configured' });
const { hash } = request.params;
const key = request.params['*'];
if (!key) {
return reply.status(400).send({ error: 'Missing key' });
} }
const q = request.url.indexOf('?');
try { try {
const existing = await this.kvClient!.getMetadataFlat(hash); const { status, body } = await this.kvClient!.fetchClaims(request.params.cid, q >= 0 ? request.url.slice(q) : '');
if (!existing) { return reply.status(status).send(body);
return { status: 'ok' }; // Nothing to delete
}
delete existing[key];
await this.kvClient!.setMetadataFlat(hash, existing);
return { status: 'ok' };
} catch (error: any) { } catch (error: any) {
return reply.status(500).send({ return reply.status(502).send({ error: 'Failed to read claims from meta-core', details: error.message });
error: 'Failed to delete property',
details: error.message
});
} }
}); });
// PATCH /meta/{hash} - Merge metadata (partial update) // The unsigned write verbs are gone (meta-core v2.0.0 refuses unsigned
this.app.patch<{ // writes); answer like meta-core does so an old plugin build fails loudly.
Params: { hash: string }; const gone = async (_request: unknown, reply: any) =>
Body: Record<string, string> reply.status(410).send({ error: 'gone', use: 'POST /api/claims' });
}>('/meta/:hash', async (request, reply) => { this.app.put('/meta/:hash/*', gone);
const { hash } = request.params; this.app.delete('/meta/:hash/*', gone);
const newMetadata = request.body; this.app.patch('/meta/:hash', gone);
this.app.post('/meta/:hash/_add/:key', gone);
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
});
}
});
// Health check for meta-core compatibility // Health check for meta-core compatibility
this.app.get('/meta-health', async () => { 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); 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> { async deleteMetadataFlat(hashId: string): Promise<number> {
const entry = this.data.get(hashId); const entry = this.data.get(hashId);
const count = entry?.size ?? 0; const count = entry?.size ?? 0;
@@ -663,72 +680,38 @@ describe('UnifiedAPIServer', function() {
expect(body).to.have.property('value', 'movie'); expect(body).to.have.property('value', 'movie');
}); });
it('PUT /meta/:hash/:key sets property value', async function() { it('unsigned write verbs answer 410 with a pointer to POST /api/claims', async function() {
const response = await app.inject({ const attempts = [
method: 'PUT', { method: 'PUT' as const, url: '/meta/testhash001/metaCustomField', payload: { value: 'x' } },
url: '/meta/testhash001/metaCustomField', { method: 'PATCH' as const, url: '/meta/testhash001', payload: { patchedField: 'x' } },
payload: { value: 'metaCustomValue' } { method: 'DELETE' as const, url: '/meta/testhash001/fileName' },
}); { method: 'POST' as const, url: '/meta/testhash001/_add/genres', payload: { value: 'Drama' } },
];
expect(response.statusCode).to.equal(200); for (const a of attempts) {
const response = await app.inject(a);
// Verify the update expect(response.statusCode, `${a.method} ${a.url}`).to.equal(410);
const verify = await app.inject({ expect(JSON.parse(response.payload)).to.deep.equal({ error: 'gone', use: 'POST /api/claims' });
method: 'GET', }
url: '/meta/testhash001/metaCustomField' // Nothing was written behind the 410s.
}); const verify = await app.inject({ method: 'GET', url: '/meta/testhash001/fileName' });
const body = JSON.parse(verify.payload); expect(JSON.parse(verify.payload)).to.have.property('value', 'Test Movie.mp4');
expect(body).to.have.property('value', 'metaCustomValue');
}); });
it('PATCH /meta/:hash merges metadata', async function() { it('GET /api/meta/:cid/claims relays the read to meta-core with its query', async function() {
const response = await app.inject({ const response = await app.inject({ method: 'GET', url: '/api/meta/bafycid/claims?key=genres' });
method: 'PATCH',
url: '/meta/testhash001',
payload: {
patchedField: 'patchedValue',
anotherField: '123'
}
});
expect(response.statusCode).to.equal(200); expect(response.statusCode).to.equal(200);
const body = JSON.parse(response.payload); expect(JSON.parse(response.payload)).to.deep.equal({ claims: [] });
expect(body).to.have.property('status', 'ok'); expect(mockKV.claimReads.at(-1)).to.equal('bafycid?key=genres');
// 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
}); });
it('DELETE /meta/:hash/:key removes property', async function() { it('POST /api/claims relays the signed batch to meta-core untouched', async function() {
// First set a property const batch = [{ cid: 'bafy', uid: 'zQ3s', key: 'title', value: 'A', ts: 1, sig: 'c2ln' }];
await app.inject({ const response = await app.inject({ method: 'POST', url: '/api/claims', payload: batch });
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'
});
expect(response.statusCode).to.equal(200); expect(response.statusCode).to.equal(200);
const body = JSON.parse(response.payload); expect(JSON.parse(response.payload)).to.deep.equal([{ status: 'accepted' }]);
expect(body).to.have.property('status', 'ok'); expect(mockKV.relayed.at(-1)).to.deep.equal(batch);
}); });
}); });
@@ -119,6 +119,16 @@ interface EnvConfig {
*/ */
PLUGIN_CACHE_HOST_PATH?: string; 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>/) // 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 // 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', CONTAINER_NETWORK: process.env.CONTAINER_NETWORK || 'meta-network',
PLUGIN_STACK_NAME: process.env.PLUGIN_STACK_NAME, PLUGIN_STACK_NAME: process.env.PLUGIN_STACK_NAME,
PLUGIN_CACHE_HOST_PATH: process.env.PLUGIN_CACHE_HOST_PATH, 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 // Event Subscriber Configuration
META_CORE_URL: process.env.META_CORE_URL, META_CORE_URL: process.env.META_CORE_URL,
@@ -27,6 +27,7 @@ import type {
import { config } from '../config/EnvConfig.js'; import { config } from '../config/EnvConfig.js';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import { hostname } from 'os'; import { hostname } from 'os';
import { randomBytes } from 'crypto';
import { ExternalPluginStore, type ExternalPluginEntry } from './ExternalPluginStore.js'; 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 * 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.`); 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 // Create container
const containerId = await this.dockerClient.createContainer({ const containerId = await this.dockerClient.createContainer({
image: pluginConfig.image, image: pluginConfig.image,
@@ -471,6 +500,8 @@ export class ContainerManager extends EventEmitter {
// Docker's own HOSTNAME is the container id; advertise a name // Docker's own HOSTNAME is the container id; advertise a name
// an operator can read in the Scan card. // an operator can read in the Scan card.
HOSTNAME: containerName, HOSTNAME: containerName,
// The plugin signs its claims as itself (one uid per plugin id).
METAMESH_SIGNING_KEY: signingKey,
}, },
// Docker Desktop grouping // Docker Desktop grouping
stackName: this.stackName, stackName: this.stackName,
+15 -1
View File
@@ -102,10 +102,24 @@ export interface IKVClient {
setMetadataProperty(hashId: string, property: string, value: string): Promise<void>; 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>; 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 * 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 * Since meta-core v2.0.0 (claims model) every metadata write is a vote signed
* service writing directly to Redis risks drifting the schema; the lockdown * by meta-sort's own key (`METAMESH_SIGNING_KEY_FILE`) and posted to
* plan (docs/api-mediated-access.md in meta-core) routes every write through * `POST /api/claims` (docs/implementation/metacore-claims-model.md). Signing
* meta-core's HTTP /meta/{hash} family. * lives in `meta-core-client.ts`, mirrored from the plugins.
* *
* This writer covers the three operations meta-sort actually performs in * - setMetadataFlat → one signed claim per field (one batch)
* production: * - setMetadataProperty → one signed claim
* - setMetadataFlat → PATCH /meta/{hash} (merge semantics) * - deleteMetadataFlat → no-op: records describe content and outlive the
* - setMetadataProperty → PUT /meta/{hash}/{key} * file (§13 G3); there is no record delete any more
* - deleteMetadataFlat → DELETE /meta/{hash} * - 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 { import {
buildRecordFields, buildRecordFields,
buildFilePrefix, buildFilePrefix,
} from './MetadataUtils.js'; } 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. */ /** One file-backed root as listed by meta-core's GET /api/files/tuples. */
export interface FileTuple { export interface FileTuple {
@@ -48,18 +54,19 @@ export interface MetaCoreApiWriterConfig {
export class MetaCoreApiWriter { export class MetaCoreApiWriter {
private apiUrl: string; private apiUrl: string;
private timeoutMs: number; private timeoutMs: number;
private claims: MetaCoreClient;
constructor(config: MetaCoreApiWriterConfig) { constructor(config: MetaCoreApiWriterConfig) {
// Trim trailing slash so we can join paths predictably. // Trim trailing slash so we can join paths predictably.
this.apiUrl = config.apiUrl.replace(/\/+$/, ''); this.apiUrl = config.apiUrl.replace(/\/+$/, '');
this.timeoutMs = config.timeoutMs ?? 30000; this.timeoutMs = config.timeoutMs ?? 30000;
this.claims = new MetaCoreClient(this.apiUrl);
} }
/** /**
* PATCH /meta/{hash}. * 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
* meta-core's PATCH calls MergeMetadataFlat — merge semantics, matches * names. Throws when meta-core refuses the batch.
* what setMetadataFlat used to do via Redis pipeline of SETs.
*/ */
async setMetadataFlat( async setMetadataFlat(
hashId: string, hashId: string,
@@ -68,47 +75,63 @@ export class MetaCoreApiWriter {
): Promise<void> { ): Promise<void> {
// `buildRecordFields` is the single write-shape boundary, shared with the // `buildRecordFields` is the single write-shape boundary, shared with the
// direct-Redis path in RedisClient. It emits the `cids/<cid>` key-set and // 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 // never a per-algorithm `cid_*` field.
// with a 400 anyway. const flat = buildRecordFields(metadata, [...excludeFields, ...LOCAL_FILE_FIELDS]);
const flat = buildRecordFields(metadata, excludeFields);
if (Object.keys(flat).length === 0) return; 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`);
} }
/** /** One signed claim. Throws when meta-core refuses it. */
* 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.
*/
async setMetadataProperty(hashId: string, property: string, value: string): Promise<void> { async setMetadataProperty(hashId: string, property: string, value: string): Promise<void> {
await this.fetchJson( if (LOCAL_FILE_FIELDS.includes(property)) return;
'PUT', const ok = await this.claims.setProperty(hashId, property, value);
`/meta/${encodeURIComponent(hashId)}/${this.encodePropertyPath(property)}`, if (!ok) throw new Error(`[MetaCoreApiWriter] claim ${hashId}/${property} was not accepted`);
{ value }
);
} }
/** /**
* DELETE /meta/{hash}. * 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
* Removes every property and unregisters the hashId from file:__index__. * watcher drops the file's `local_file` row on its own (§13 G3).
*/ */
async deleteMetadataFlat(hashId: string): Promise<number> { 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;
}
return 0; 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). * 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); 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> { async deleteMetadataFlat(hashId: string): Promise<number> {
if (this.writer) { if (this.writer) {
return this.writer.deleteMetadataFlat(hashId); 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;
}
}
@@ -631,20 +631,11 @@ export class FileProcessorPiscina implements FileAnalyzerInterface{
const metadata = this.database.get(filePath); const metadata = this.database.get(filePath);
this.database.delete(filePath); this.database.delete(filePath);
// Delete from KV if configured (using nested key architecture) // Nothing to delete in meta-core: since the claims model a record
if (this.kvClient && metadata) { // describes content and its votes outlive this copy of the file.
try { // meta-core's own watcher drops the file's `local_file` row.
const hashId = metadata.hashId; if (metadata?.hashId) {
console.log(`File removed: ${filePath} (/file/${metadata.hashId} kept — records outlive files)`);
// 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);
}
} }
} }