Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28bd19b4e7 | ||
|
|
de6f749424 | ||
|
|
b11129b67e | ||
|
|
0e37bb4b42 | ||
|
|
4da5c3778d | ||
|
|
ae1ee8c0b4 | ||
|
|
316db6ad03 | ||
|
|
c82a931a8c |
@@ -0,0 +1,85 @@
|
|||||||
|
# Gitea twin of .github/workflows/docker.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.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.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
|
||||||
|
# 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, master]
|
||||||
|
tags: ['v*']
|
||||||
|
pull_request:
|
||||||
|
branches: [main, master]
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: ipcr-push-85-17-246-67.ip.nsl.sh
|
||||||
|
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
|
||||||
|
|
||||||
|
- 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
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
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
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
tags: |
|
||||||
|
type=ref,event=branch
|
||||||
|
type=ref,event=pr
|
||||||
|
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
|
||||||
|
|
||||||
|
- name: Build and push
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
@@ -42,6 +42,9 @@ jobs:
|
|||||||
type=ref,event=branch
|
type=ref,event=branch
|
||||||
type=ref,event=pr
|
type=ref,event=pr
|
||||||
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
|
type=sha
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
/**
|
||||||
|
* Beacon v2 advertiser — makes this plugin findable by meta-sort's Plugins
|
||||||
|
* page (Scan → Add) without anyone typing its URL.
|
||||||
|
*
|
||||||
|
* Advertises one resource, cap `metamesh.enrich/<manifest id>`, on the beacon
|
||||||
|
* group (239.255.99.1:9099): unsolicited every 10 s, and unicast in reply to
|
||||||
|
* any probe whose `want` matches. Says `bye` on shutdown. It keeps no view of
|
||||||
|
* other nodes — a plugin only needs to be found. Spec:
|
||||||
|
* meta-root docs/project-architecture/beacon-v2.md.
|
||||||
|
*
|
||||||
|
* Env:
|
||||||
|
* ENABLE_UDP_DISCOVERY false/0/no/off disables
|
||||||
|
* BEACON_ADVERTISE_URL endpoints.http (default http://$HOSTNAME:$PORT)
|
||||||
|
* BEACON_BINDS the one meta-sort instance allowed to list it
|
||||||
|
* (meta-sort sets this on containers it spawns)
|
||||||
|
* BEACON_GROUP / BEACON_PORT / BEACON_INTERVAL_MS
|
||||||
|
*
|
||||||
|
* ⚠ MIRRORED FILE. Byte-identical copies live in every TypeScript
|
||||||
|
* metamesh-plugin-*; see meta-root `scripts/check-mirrors.sh`. Never fatal: a
|
||||||
|
* host that blocks multicast logs a warning and the plugin serves on.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import dgram from 'dgram';
|
||||||
|
import { hostname, networkInterfaces } from 'os';
|
||||||
|
|
||||||
|
const PROTO = 'beacon';
|
||||||
|
const VERSION = 2;
|
||||||
|
|
||||||
|
interface Resource {
|
||||||
|
id: string;
|
||||||
|
caps: string[];
|
||||||
|
endpoints: Record<string, string>;
|
||||||
|
binds?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NodeInfo {
|
||||||
|
name: string;
|
||||||
|
instance: string;
|
||||||
|
version?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function envNum(key: string): number | undefined {
|
||||||
|
const n = Number(process.env[key]);
|
||||||
|
return Number.isFinite(n) && n > 0 ? n : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function enabled(): boolean {
|
||||||
|
const v = (process.env.ENABLE_UDP_DISCOVERY ?? '').trim().toLowerCase();
|
||||||
|
return !['false', '0', 'no', 'off'].includes(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** IPv4 addresses of every up, non-internal interface. */
|
||||||
|
function interfaceAddresses(): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const list of Object.values(networkInterfaces())) {
|
||||||
|
for (const ni of list ?? []) {
|
||||||
|
const v4 = (ni as { family: string | number }).family === 'IPv4' || (ni as { family: string | number }).family === 4;
|
||||||
|
if (v4 && !ni.internal && ni.address) out.push(ni.address);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same matching rules as the spec: `*`, `x/*`, optional `@contract`. */
|
||||||
|
function capMatches(pattern: string, cap: string): boolean {
|
||||||
|
if (pattern === '*') return true;
|
||||||
|
const split = (s: string): [string, string | null] => {
|
||||||
|
const i = s.lastIndexOf('@');
|
||||||
|
return i >= 0 ? [s.slice(0, i), s.slice(i + 1)] : [s, null];
|
||||||
|
};
|
||||||
|
const [pb, pc] = split(pattern);
|
||||||
|
const [cb, cc] = split(cap);
|
||||||
|
if (pc !== null && cc !== pc) return false;
|
||||||
|
if (pb.endsWith('/*')) {
|
||||||
|
const prefix = pb.slice(0, -2);
|
||||||
|
const rest = cb.startsWith(prefix) ? cb.slice(prefix.length) : '';
|
||||||
|
return rest.startsWith('/') && rest.length > 1;
|
||||||
|
}
|
||||||
|
return pb === cb;
|
||||||
|
}
|
||||||
|
|
||||||
|
let socket: dgram.Socket | null = null;
|
||||||
|
let timer: NodeJS.Timeout | null = null;
|
||||||
|
let node: NodeInfo | null = null;
|
||||||
|
let resource: Resource | null = null;
|
||||||
|
let ifaces: string[] = [];
|
||||||
|
let group = '239.255.99.1';
|
||||||
|
let udpPort = 9099;
|
||||||
|
|
||||||
|
function send(msg: object, dest?: { address: string; port: number }): void {
|
||||||
|
const s = socket;
|
||||||
|
if (!s) return;
|
||||||
|
const body = Buffer.from(JSON.stringify(msg));
|
||||||
|
if (dest) {
|
||||||
|
s.send(body, dest.port, dest.address, () => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Once per interface: the default route alone reaches one network.
|
||||||
|
for (const addr of ifaces) {
|
||||||
|
try {
|
||||||
|
s.setMulticastInterface(addr);
|
||||||
|
s.send(body, udpPort, group, () => {});
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`[beacon] send on ${addr} failed:`, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function advertise(dest?: { address: string; port: number }): void {
|
||||||
|
if (!node || !resource) return;
|
||||||
|
send({ proto: PROTO, v: VERSION, type: 'advertise', node, resources: [resource] }, dest);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start advertising this plugin. Call once the HTTP server is listening, so a
|
||||||
|
* consumer that hears it can reach it. Idempotent.
|
||||||
|
*/
|
||||||
|
export function startBeacon(pluginId: string, version: string, httpPort: number): void {
|
||||||
|
if (socket || !enabled()) return;
|
||||||
|
group = process.env.BEACON_GROUP || group;
|
||||||
|
udpPort = envNum('BEACON_PORT') ?? udpPort;
|
||||||
|
const intervalMs = envNum('BEACON_INTERVAL_MS') ?? 10_000;
|
||||||
|
const instance = process.env.HOSTNAME || hostname();
|
||||||
|
const url = (process.env.BEACON_ADVERTISE_URL || `http://${instance}:${httpPort}`).replace(/\/+$/, '');
|
||||||
|
const binds = (process.env.BEACON_BINDS || '').trim();
|
||||||
|
|
||||||
|
node = { name: `metamesh-plugin-${pluginId}`, instance, ...(version ? { version } : {}) };
|
||||||
|
resource = {
|
||||||
|
id: pluginId,
|
||||||
|
caps: [`metamesh.enrich/${pluginId}`],
|
||||||
|
endpoints: { http: url, manifest: '/manifest' },
|
||||||
|
...(binds ? { binds } : {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
const s = dgram.createSocket({ type: 'udp4', reuseAddr: true });
|
||||||
|
socket = s;
|
||||||
|
s.on('error', (err) => console.warn('[beacon] socket error:', err.message));
|
||||||
|
s.on('message', (buf, rinfo) => {
|
||||||
|
let m: { proto?: string; v?: number; type?: string; from?: string; want?: string[] };
|
||||||
|
try {
|
||||||
|
m = JSON.parse(buf.toString('utf8'));
|
||||||
|
} catch {
|
||||||
|
return; // foreign traffic on the shared group
|
||||||
|
}
|
||||||
|
if (m?.proto !== PROTO || m.v !== VERSION || m.type !== 'probe' || m.from === instance) return;
|
||||||
|
const want = Array.isArray(m.want) ? m.want : [];
|
||||||
|
if (want.length === 0 || resource!.caps.some((c) => want.some((p) => capMatches(p, c)))) {
|
||||||
|
advertise({ address: rinfo.address, port: rinfo.port });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
s.bind(udpPort, '0.0.0.0', () => {
|
||||||
|
try {
|
||||||
|
s.setMulticastTTL(1);
|
||||||
|
} catch {
|
||||||
|
/* best effort */
|
||||||
|
}
|
||||||
|
ifaces = interfaceAddresses();
|
||||||
|
for (const addr of ifaces) {
|
||||||
|
try {
|
||||||
|
s.addMembership(group, addr);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`[beacon] join ${group} on ${addr} failed:`, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(`[beacon] advertising metamesh.enrich/${pluginId} at ${url} on ${group}:${udpPort}`);
|
||||||
|
advertise();
|
||||||
|
timer = setInterval(() => advertise(), intervalMs);
|
||||||
|
timer.unref?.();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Say `bye` so consumers drop this plugin at once. */
|
||||||
|
export async function stopBeacon(): Promise<void> {
|
||||||
|
if (!socket || !node) return;
|
||||||
|
if (timer) clearInterval(timer);
|
||||||
|
send({ proto: PROTO, v: VERSION, type: 'bye', node });
|
||||||
|
// Let the bye datagrams leave before the socket closes under them.
|
||||||
|
await new Promise((r) => setTimeout(r, 50));
|
||||||
|
const s = socket;
|
||||||
|
socket = null;
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
try {
|
||||||
|
s.close(() => resolve());
|
||||||
|
} catch {
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@
|
|||||||
import Fastify from 'fastify';
|
import Fastify from 'fastify';
|
||||||
import type { HealthResponse, ProcessRequest, ProcessResponse, CallbackPayload, ConfigureRequest, ConfigureResponse } from './types.js';
|
import type { HealthResponse, ProcessRequest, ProcessResponse, CallbackPayload, ConfigureRequest, ConfigureResponse } from './types.js';
|
||||||
import { manifest, process as processFile, configure } from './plugin.js';
|
import { manifest, process as processFile, configure } from './plugin.js';
|
||||||
|
import { startBeacon, stopBeacon } from './beacon-advertise.js';
|
||||||
|
|
||||||
const app = Fastify({ logger: true });
|
const app = Fastify({ logger: true });
|
||||||
let ready = false;
|
let ready = false;
|
||||||
@@ -69,11 +70,13 @@ app.post<{ Body: ProcessRequest }>('/process', async (request, reply) => {
|
|||||||
const port = parseInt(process.env.PORT || '8080', 10);
|
const port = parseInt(process.env.PORT || '8080', 10);
|
||||||
|
|
||||||
app.listen({ port, host: '0.0.0.0' }).then(() => {
|
app.listen({ port, host: '0.0.0.0' }).then(() => {
|
||||||
|
startBeacon(manifest.id, manifest.version, port);
|
||||||
ready = true;
|
ready = true;
|
||||||
console.log(`[${manifest.id}] Listening on port ${port}`);
|
console.log(`[${manifest.id}] Listening on port ${port}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on('SIGTERM', async () => {
|
process.on('SIGTERM', async () => {
|
||||||
|
await stopBeacon();
|
||||||
ready = false;
|
ready = false;
|
||||||
await app.close();
|
await app.close();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
|
|||||||
+342
-30
@@ -1,12 +1,240 @@
|
|||||||
/**
|
/**
|
||||||
* meta-core API client for writing metadata.
|
* meta-core client: signed claim writes (MMUR2) + plain reads.
|
||||||
*
|
*
|
||||||
* Writes report success so a failed write fails the task instead of being
|
* MIRRORED byte-for-byte across every `metamesh-plugin-*` TypeScript plugin and
|
||||||
* swallowed. Key-sets are written as individual `prefix/member = "true"`
|
* meta-sort-core (`src/kv/meta-core-client.ts`) — guarded by
|
||||||
* fields through PATCH — never via `_add`, which stores one comma-joined
|
* `scripts/check-mirrors.sh`. Edit one copy, then copy it everywhere.
|
||||||
* string and can never produce the key-set shape.
|
*
|
||||||
|
* 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 {
|
export class MetaCoreClient {
|
||||||
constructor(private baseUrl: string) {}
|
constructor(private baseUrl: string) {}
|
||||||
|
|
||||||
@@ -19,6 +247,101 @@ export class MetaCoreClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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> {
|
async getProperty(hashId: string, key: string): Promise<string | null> {
|
||||||
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { method: 'GET' });
|
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { method: 'GET' });
|
||||||
if (!response || !response.ok) return null;
|
if (!response || !response.ok) return null;
|
||||||
@@ -27,9 +350,9 @@ export class MetaCoreClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whole record, in whatever form the endpoint serves (meta-sort's /meta is
|
* Whole merged record, in whatever form the endpoint serves (meta-sort's
|
||||||
* nested, meta-core's is flat) — callers flatten. `null` when the call
|
* /meta is nested, meta-core's is flat) — callers flatten. `null` when the
|
||||||
* itself failed, `{}` when the record does not exist.
|
* call itself failed, `{}` when the record does not exist.
|
||||||
*/
|
*/
|
||||||
async getMetadata(hashId: string): Promise<Record<string, unknown> | null> {
|
async getMetadata(hashId: string): Promise<Record<string, unknown> | null> {
|
||||||
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}`, { method: 'GET' });
|
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}`, { method: 'GET' });
|
||||||
@@ -40,29 +363,18 @@ export class MetaCoreClient {
|
|||||||
return data.metadata ?? {};
|
return data.metadata ?? {};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PATCH — merge `metadata` into the record. True on success. */
|
/**
|
||||||
async mergeMetadata(hashId: string, metadata: Record<string, string>): Promise<boolean> {
|
* Compute the CID of a file under FILES_PATH via meta-core's `POST /file/cid`.
|
||||||
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}`, {
|
* @param filePath - path relative to FILES_PATH (e.g. "poster/Movie (2024)_poster.jpg")
|
||||||
method: 'PATCH',
|
*/
|
||||||
|
async computeFileCID(filePath: string): Promise<string | null> {
|
||||||
|
const response = await this.safeFetch(`${this.baseUrl}/file/cid`, {
|
||||||
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(metadata),
|
body: JSON.stringify({ path: filePath }),
|
||||||
});
|
});
|
||||||
if (!response) return false;
|
if (!response || !response.ok) return null;
|
||||||
if (!response.ok) {
|
const data = await response.json().catch(() => null) as { cid?: string } | null;
|
||||||
console.warn(`[MetaCoreClient] Failed to merge metadata into ${hashId}: ${response.status}`);
|
return data?.cid ?? null;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** DELETE one field. A missing field counts as deleted. */
|
|
||||||
async deleteProperty(hashId: string, key: string): Promise<boolean> {
|
|
||||||
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { method: 'DELETE' });
|
|
||||||
if (!response) return false;
|
|
||||||
if (!response.ok && response.status !== 404) {
|
|
||||||
console.warn(`[MetaCoreClient] Failed to delete ${hashId}/${key}: ${response.status}`);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+22
-3
@@ -477,9 +477,21 @@ export function videoSubtitleKeys(produced: ProducedSubtitle[]): Record<string,
|
|||||||
return keys;
|
return keys;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Keys on the subtitle file's own record. */
|
/**
|
||||||
|
* Keys on the subtitle file's own record.
|
||||||
|
*
|
||||||
|
* `source/extract` (METADATA_KEYS.md §5) says the bytes came out of a video
|
||||||
|
* container. The video record already implies it through `extractedSubtitles/`,
|
||||||
|
* but that is the wrong side of the relation to store it on: a subtitle fetched
|
||||||
|
* over the swarm by CID arrives WITHOUT its video record, so a reader holding
|
||||||
|
* only the file would have no way to tell an extracted track from a sidecar
|
||||||
|
* someone dropped next to the video.
|
||||||
|
*/
|
||||||
export function subtitleRecordKeys(videoCid: string, lang3: string): Record<string, string> {
|
export function subtitleRecordKeys(videoCid: string, lang3: string): Record<string, string> {
|
||||||
const keys: Record<string, string> = { [`videos/${videoCid}`]: 'true' };
|
const keys: Record<string, string> = {
|
||||||
|
[`videos/${videoCid}`]: 'true',
|
||||||
|
'source/extract': 'true',
|
||||||
|
};
|
||||||
if (lang3 !== 'und') keys.subtitleLanguage = lang3;
|
if (lang3 !== 'und') keys.subtitleLanguage = lang3;
|
||||||
return keys;
|
return keys;
|
||||||
}
|
}
|
||||||
@@ -499,7 +511,14 @@ export function legacySubtitleMigration(existingMeta: Record<string, unknown> |
|
|||||||
const langs = legacyCsvMembers(existingMeta, 'subtitleLanguages');
|
const langs = legacyCsvMembers(existingMeta, 'subtitleLanguages');
|
||||||
if (langs) {
|
if (langs) {
|
||||||
deletes.push('subtitleLanguages');
|
deletes.push('subtitleLanguages');
|
||||||
for (const l of langs.map(toLang3)) if (l !== 'und') sets[`subtitleLanguages/${l}`] = 'true';
|
for (const l of langs.map(toLang3)) {
|
||||||
|
if (l === 'und') continue;
|
||||||
|
sets[`subtitleLanguages/${l}`] = 'true';
|
||||||
|
// …and the union (§9 rule #7). The live write path below already
|
||||||
|
// does this; the migration path did not, so records that only ever
|
||||||
|
// went through it were left half-written.
|
||||||
|
sets[`languages/${l}`] = 'true';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const subs = legacyCsvMembers(existingMeta, 'subtitles');
|
const subs = legacyCsvMembers(existingMeta, 'subtitles');
|
||||||
|
|||||||
+28
-6
@@ -284,9 +284,16 @@ describe('record keys (METADATA_KEYS.md §8)', () => {
|
|||||||
expect(keys.every((k) => k.split('/').length === 3)).toBe(true);
|
expect(keys.every((k) => k.split('/').length === 3)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('subtitle record carries the back-pointer and a determined language only', () => {
|
it('subtitle record carries the back-pointer, its origin, and a determined language only', () => {
|
||||||
expect(subtitleRecordKeys('bagvideo', 'fre')).toEqual({ 'videos/bagvideo': 'true', subtitleLanguage: 'fre' });
|
expect(subtitleRecordKeys('bagvideo', 'fre')).toEqual({
|
||||||
expect(subtitleRecordKeys('bagvideo', 'und')).toEqual({ 'videos/bagvideo': 'true' });
|
'videos/bagvideo': 'true',
|
||||||
|
'source/extract': 'true',
|
||||||
|
subtitleLanguage: 'fre',
|
||||||
|
});
|
||||||
|
expect(subtitleRecordKeys('bagvideo', 'und')).toEqual({
|
||||||
|
'videos/bagvideo': 'true',
|
||||||
|
'source/extract': 'true',
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -310,7 +317,13 @@ describe('legacySubtitleMigration', () => {
|
|||||||
subtitles: 'cidS',
|
subtitles: 'cidS',
|
||||||
})).toEqual({
|
})).toEqual({
|
||||||
deletes: ['extractedSubtitles', 'subtitleLanguages', 'subtitles'],
|
deletes: ['extractedSubtitles', 'subtitleLanguages', 'subtitles'],
|
||||||
sets: { 'subtitleLanguages/eng': 'true', 'subtitleLanguages/fre': 'true', 'subtitles/und/cidS': 'true' },
|
sets: {
|
||||||
|
'subtitleLanguages/eng': 'true',
|
||||||
|
'languages/eng': 'true',
|
||||||
|
'subtitleLanguages/fre': 'true',
|
||||||
|
'languages/fre': 'true',
|
||||||
|
'subtitles/und/cidS': 'true',
|
||||||
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -495,8 +508,17 @@ describe.skipIf(!ffmpegReady)('process — end to end against a fake core', () =
|
|||||||
expect(video.subtitleLanguages).toBeUndefined();
|
expect(video.subtitleLanguages).toBeUndefined();
|
||||||
expect(video['subtitleLanguages/und']).toBeUndefined();
|
expect(video['subtitleLanguages/und']).toBeUndefined();
|
||||||
|
|
||||||
expect(core.records.get(fre)).toEqual({ [`videos/${VIDEO_CID}`]: 'true', subtitleLanguage: 'fre' });
|
// `source/extract` rides on the subtitle's OWN record, so a peer that
|
||||||
expect(core.records.get(und)).toEqual({ [`videos/${VIDEO_CID}`]: 'true' });
|
// fetched only the file can still tell it came out of a container.
|
||||||
|
expect(core.records.get(fre)).toEqual({
|
||||||
|
[`videos/${VIDEO_CID}`]: 'true',
|
||||||
|
'source/extract': 'true',
|
||||||
|
subtitleLanguage: 'fre',
|
||||||
|
});
|
||||||
|
expect(core.records.get(und)).toEqual({
|
||||||
|
[`videos/${VIDEO_CID}`]: 'true',
|
||||||
|
'source/extract': 'true',
|
||||||
|
});
|
||||||
|
|
||||||
// The video PATCH carried only new keys — nothing the record already had.
|
// The video PATCH carried only new keys — nothing the record already had.
|
||||||
const patch = writesTo(core, VIDEO_CID).find((c) => c.method === 'PATCH')!;
|
const patch = writesTo(core, VIDEO_CID).find((c) => c.method === 'PATCH')!;
|
||||||
|
|||||||
+41
-2
@@ -1,12 +1,21 @@
|
|||||||
/**
|
/**
|
||||||
* In-process stand-in for the two HTTP surfaces a plugin talks to:
|
* In-process stand-in for the two HTTP surfaces a plugin talks to:
|
||||||
* - WebDAV at /webdav/... (JSON directory listing, HEAD, Range GET, PUT)
|
* - WebDAV at /webdav/... (JSON directory listing, HEAD, Range GET, PUT)
|
||||||
* - meta API at /meta/... (GET record / property, PATCH merge, DELETE property)
|
* - meta API at /meta/... (GET record / property)
|
||||||
|
* - POST /api/claims (signed MMUR2 claims — every signature is verified)
|
||||||
* Records are stored FLAT (`subtitles/fre/<cid>`), the way meta-core keeps them.
|
* Records are stored FLAT (`subtitles/fre/<cid>`), the way meta-core keeps them.
|
||||||
|
*
|
||||||
|
* Claims are folded back into the old call shape so tests keep asserting on
|
||||||
|
* writes per record: a batch's text claims become one `PATCH /meta/<cid>`
|
||||||
|
* (body = key → value) and each retraction a `DELETE /meta/<cid>/<key>`.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import http from 'http';
|
import http from 'http';
|
||||||
import type { AddressInfo } from 'net';
|
import type { AddressInfo } from 'net';
|
||||||
|
import { verifyClaim, type ClaimValue } from '../src/meta-core-client.js';
|
||||||
|
|
||||||
|
// Fixed test signing key (scalar 0x0101…01) — the plugin signs as this.
|
||||||
|
process.env.METAMESH_SIGNING_KEY ??= '01'.repeat(32);
|
||||||
|
|
||||||
export interface FakeCall {
|
export interface FakeCall {
|
||||||
method: string;
|
method: string;
|
||||||
@@ -99,6 +108,36 @@ export async function startFakeCore(): Promise<FakeCore> {
|
|||||||
return send(200, data, { 'Content-Length': String(data.length), 'Accept-Ranges': 'bytes' });
|
return send(200, data, { 'Content-Length': String(data.length), 'Accept-Ranges': 'bytes' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (pathname === '/api/claims' && req.method === 'POST') {
|
||||||
|
const claims = JSON.parse((await readBody(req)).toString('utf8')) as Array<{
|
||||||
|
cid: string; uid: string; key: string; value: string | { b64: string } | null; ts: number; sig: string;
|
||||||
|
}>;
|
||||||
|
if (core.failPatch) return send(500, { error: 'boom' });
|
||||||
|
const statuses: Array<{ status: string }> = [];
|
||||||
|
const sets = new Map<string, Record<string, string>>();
|
||||||
|
for (const c of claims) {
|
||||||
|
const value: ClaimValue = c.value === null ? null
|
||||||
|
: typeof c.value === 'string' ? c.value : Buffer.from(c.value.b64, 'base64');
|
||||||
|
if (!verifyClaim({ ...c, value, sig: Buffer.from(c.sig, 'base64') })) {
|
||||||
|
statuses.push({ status: 'bad_signature' });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
statuses.push({ status: 'accepted' });
|
||||||
|
if (value === null) {
|
||||||
|
core.calls.push({ method: 'DELETE', path: `/meta/${c.cid}/${c.key}` });
|
||||||
|
const record = core.records.get(c.cid);
|
||||||
|
if (record) delete record[c.key];
|
||||||
|
} else {
|
||||||
|
sets.set(c.cid, { ...(sets.get(c.cid) ?? {}), [c.key]: String(value) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [cid, body] of sets) {
|
||||||
|
core.calls.push({ method: 'PATCH', path: `/meta/${cid}`, body });
|
||||||
|
core.records.set(cid, { ...(core.records.get(cid) ?? {}), ...body });
|
||||||
|
}
|
||||||
|
return send(200, statuses);
|
||||||
|
}
|
||||||
|
|
||||||
const m = /^\/meta\/([^/]+)(?:\/(.+))?$/.exec(pathname);
|
const m = /^\/meta\/([^/]+)(?:\/(.+))?$/.exec(pathname);
|
||||||
if (m) {
|
if (m) {
|
||||||
const [, hash, key] = m;
|
const [, hash, key] = m;
|
||||||
@@ -141,7 +180,7 @@ export async function startFakeCore(): Promise<FakeCore> {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Mutating calls (PATCH / DELETE) against one record. */
|
/** Mutating calls (claims folded to PATCH / DELETE) against one record. */
|
||||||
export function writesTo(core: FakeCore, hash: string): FakeCall[] {
|
export function writesTo(core: FakeCore, hash: string): FakeCall[] {
|
||||||
return core.calls.filter((c) => c.path === `/meta/${hash}` || c.path.startsWith(`/meta/${hash}/`));
|
return core.calls.filter((c) => c.path === `/meta/${hash}` || c.path.startsWith(`/meta/${hash}/`));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user