Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f5b3cefc9 | ||
|
|
ecb30e1633 | ||
|
|
8194541f1c | ||
|
|
cc96350b67 | ||
|
|
98897cd59d | ||
|
|
d9b21fcd1f |
@@ -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=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
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ This plugin analyzes video filenames using the `@metazla/filename-tools` library
|
||||
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| `originalTitle` | Extracted title from filename |
|
||||
| `parsedTitle` | Title guessed from the filename (its own key — never `title` / `originalTitle`, which catalogue plugins own) |
|
||||
| `videoType` | `movie` or `tvshow` |
|
||||
| `season` | Season number (TV shows) |
|
||||
| `episode` | Episode number (TV shows) |
|
||||
|
||||
+355
-48
@@ -1,73 +1,380 @@
|
||||
/**
|
||||
* meta-core API Client for writing metadata
|
||||
* Fails gracefully if meta-core is unavailable (returns without throwing)
|
||||
* 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(5000) });
|
||||
} catch {
|
||||
// meta-core unavailable - fail silently (expected in standalone/test mode)
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
async setProperty(hashId: string, key: string, value: string): Promise<void> {
|
||||
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, {
|
||||
method: 'PUT',
|
||||
/**
|
||||
* 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({ value }),
|
||||
body: JSON.stringify(claims),
|
||||
});
|
||||
if (response && !response.ok) {
|
||||
console.warn(`[MetaCoreClient] Failed to set property: ${response.status}`);
|
||||
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.status === 404) return null;
|
||||
if (!response.ok) return null;
|
||||
const data = await response.json() as { value?: string };
|
||||
return data.value ?? null;
|
||||
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);
|
||||
}
|
||||
|
||||
async mergeMetadata(hashId: string, metadata: Record<string, string>): Promise<void> {
|
||||
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(metadata),
|
||||
});
|
||||
if (response && !response.ok) {
|
||||
console.warn(`[MetaCoreClient] Failed to merge metadata: ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteProperty(hashId: string, key: string): Promise<void> {
|
||||
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { method: 'DELETE' });
|
||||
if (response && !response.ok && response.status !== 404) {
|
||||
console.warn(`[MetaCoreClient] Failed to delete property: ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async addToSet(hashId: string, key: string, value: string): Promise<void> {
|
||||
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/_add/${key}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ value }),
|
||||
});
|
||||
if (response && !response.ok) {
|
||||
console.warn(`[MetaCoreClient] Failed to add to set: ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getMetadata(hashId: string): Promise<Record<string, string>> {
|
||||
/**
|
||||
* 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 || response.status === 404) return {};
|
||||
if (!response.ok) return {};
|
||||
const data = await response.json() as { metadata?: Record<string, string> };
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
+5
-2
@@ -30,7 +30,7 @@ export const manifest: PluginManifest = {
|
||||
defaultQueue: 'fast',
|
||||
timeout: 30000,
|
||||
schema: {
|
||||
originalTitle: { label: 'Original Title', type: 'string' },
|
||||
parsedTitle: { label: 'Parsed Title', type: 'string', hint: 'title guessed from the filename; never written to title/originalTitle' },
|
||||
videoType: { label: 'Video Type', type: 'string', hint: 'movie or tvshow' },
|
||||
season: { label: 'Season', type: 'string' },
|
||||
episode: { label: 'Episode', type: 'string' },
|
||||
@@ -90,7 +90,10 @@ export async function process(
|
||||
|
||||
// Convert to record for merging
|
||||
const result: Record<string, string> = {};
|
||||
if (metadata.originalTitle) result.originalTitle = metadata.originalTitle;
|
||||
// A filename guess is a different fact from a catalogue title, so it gets
|
||||
// its own key (METADATA_KEYS.md rule #8): written to `originalTitle` it
|
||||
// would compete with tmdb as a separate signer and, being older, win.
|
||||
if (metadata.originalTitle) result.parsedTitle = metadata.originalTitle;
|
||||
if (metadata.season) result.season = metadata.season;
|
||||
if (metadata.episode) result.episode = metadata.episode;
|
||||
if (metadata.increment) result.increment = metadata.increment;
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* `addToSet` keeps the legacy csv-set shape under claims: it rewrites THIS
|
||||
* signer's own comma-joined vote, ignoring other signers' claims. fetch is
|
||||
* stubbed with a tiny meta-core.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { MetaCoreClient, ClaimSigner, verifyClaim, resetSignerForTests } from '../src/meta-core-client.js';
|
||||
|
||||
const KEY = '01'.repeat(32);
|
||||
const own = new ClaimSigner(KEY);
|
||||
const other = new ClaimSigner('02'.repeat(32));
|
||||
|
||||
/** Claims meta-core holds for the cid, and every batch posted. */
|
||||
let stored: Array<Record<string, unknown>>;
|
||||
let posted: Array<Array<Record<string, unknown>>>;
|
||||
let claimReads: string[];
|
||||
|
||||
function json(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.METAMESH_SIGNING_KEY = KEY;
|
||||
resetSignerForTests();
|
||||
stored = [];
|
||||
posted = [];
|
||||
claimReads = [];
|
||||
vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {
|
||||
const u = new URL(url);
|
||||
if (init?.method === 'GET' && u.pathname.endsWith('/claims')) {
|
||||
claimReads.push(u.pathname + u.search);
|
||||
const key = u.searchParams.get('key');
|
||||
return json({ claims: stored.filter((c) => c.key === key) });
|
||||
}
|
||||
if (init?.method === 'POST' && u.pathname === '/api/claims') {
|
||||
const batch = JSON.parse(String(init.body)) as Array<Record<string, unknown>>;
|
||||
posted.push(batch);
|
||||
return json(batch.map(() => ({ status: 'accepted' })));
|
||||
}
|
||||
return json({ error: 'no route' }, 404);
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
delete process.env.METAMESH_SIGNING_KEY;
|
||||
resetSignerForTests();
|
||||
});
|
||||
|
||||
const client = () => new MetaCoreClient('http://core');
|
||||
const claimOf = (s: ClaimSigner, value: string, ts: number) =>
|
||||
({ cid: 'bafycid', uid: s.uid, key: 'genres', value, ts, sig: 'x' });
|
||||
|
||||
function postedValue(): string {
|
||||
expect(posted).toHaveLength(1);
|
||||
const [c] = posted[0];
|
||||
expect(c.key).toBe('genres');
|
||||
expect(c.uid).toBe(own.uid);
|
||||
expect(verifyClaim({ ...(c as never), sig: Buffer.from(String(c.sig), 'base64') })).toBe(true);
|
||||
return String(c.value);
|
||||
}
|
||||
|
||||
describe('addToSet (csv-set over this signer\'s own claim)', () => {
|
||||
it('writes the first member when this signer has no claim yet', async () => {
|
||||
stored = [claimOf(other, 'Comedy', 5)];
|
||||
expect(await client().addToSet('bafycid', 'genres', 'Drama')).toBe(true);
|
||||
expect(claimReads).toEqual(['/api/meta/bafycid/claims?key=genres']);
|
||||
expect(postedValue()).toBe('Drama');
|
||||
});
|
||||
|
||||
it('appends to its own newest value and ignores other signers', async () => {
|
||||
stored = [claimOf(own, 'Action', 1), claimOf(own, 'Drama, Thriller', 9), claimOf(other, 'Comedy,Horror', 20)];
|
||||
expect(await client().addToSet('bafycid', 'genres', 'Sci-Fi/Fantasy')).toBe(true);
|
||||
expect(postedValue()).toBe('Drama,Thriller,Sci-Fi/Fantasy');
|
||||
});
|
||||
|
||||
it('writes nothing when the member is already in its own value', async () => {
|
||||
stored = [claimOf(own, 'Drama,Thriller', 9)];
|
||||
expect(await client().addToSet('bafycid', 'genres', 'Thriller')).toBe(true);
|
||||
expect(posted).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('refuses to write when its own claims cannot be read', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {
|
||||
if (init?.method === 'GET') return json({ error: 'nope' }, 500);
|
||||
return json([{ status: 'accepted' }]);
|
||||
}));
|
||||
expect(await client().addToSet('bafycid', 'genres', 'Drama')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* MMUR2 conformance of the shared meta-core-client.ts against meta-core's
|
||||
* golden vectors (test/claim-vectors.json, canonical copy in meta-core
|
||||
* internal/claim/testdata). Node signs with a random nonce, so our own
|
||||
* signatures cannot equal sigHex — they must verify and be low-S instead.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { readFileSync } from 'fs';
|
||||
import { signedBytes, verifyClaim, ClaimSigner, type ClaimValue } from '../src/meta-core-client.js';
|
||||
|
||||
const f = JSON.parse(readFileSync(new URL('./claim-vectors.json', import.meta.url), 'utf8'));
|
||||
const HALF_N = BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141') >> 1n;
|
||||
|
||||
const valueOf = (v: { value?: string | null; valueBytesHex?: string }): ClaimValue =>
|
||||
v.valueBytesHex ? Buffer.from(v.valueBytesHex, 'hex') : (v.value ?? null);
|
||||
|
||||
describe('MMUR2 claim vectors', () => {
|
||||
const signer = new ClaimSigner(f.privateKeyHex);
|
||||
|
||||
it('derives the vector uid from the test key', () => {
|
||||
expect(signer.uid).toBe(f.uid);
|
||||
});
|
||||
|
||||
for (const v of f.vectors) {
|
||||
it(`${v.name}: canonical bytes, reference signature, own signature`, () => {
|
||||
const value = valueOf(v);
|
||||
expect(signedBytes(v.cid, v.uid, v.key, value, v.ts).toString('hex')).toBe(v.signedBytesHex);
|
||||
expect(verifyClaim({ cid: v.cid, uid: v.uid, key: v.key, value, ts: v.ts, sig: Buffer.from(v.sigHex, 'hex') })).toBe(true);
|
||||
const own = signer.sign(v.cid, v.key, value, v.ts);
|
||||
expect(verifyClaim(own)).toBe(true);
|
||||
expect(BigInt('0x' + Buffer.from(own.sig).subarray(32).toString('hex')) <= HALF_N).toBe(true);
|
||||
});
|
||||
}
|
||||
|
||||
it('refuses the high-S twin of a valid signature', () => {
|
||||
const v = f.vectors.find((x: { name: string }) => x.name === f.highS.vector);
|
||||
expect(verifyClaim({ cid: v.cid, uid: v.uid, key: v.key, value: valueOf(v), ts: v.ts, sig: Buffer.from(f.highS.sigHex, 'hex') })).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses a tampered value', () => {
|
||||
const c = signer.sign('bafy', 'title', 'A');
|
||||
expect(verifyClaim({ ...c, value: 'B' })).toBe(false);
|
||||
});
|
||||
|
||||
it('issues strictly increasing ts', () => {
|
||||
const a = signer.nextTs();
|
||||
expect(signer.nextTs()).toBeGreaterThan(a);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
{
|
||||
"_comment": "MMUR2 golden vectors. Canonical copy: meta-core internal/claim/testdata. Do not edit by hand; see claim_test.go.",
|
||||
"privateKeyHex": "0101010101010101010101010101010101010101010101010101010101010101",
|
||||
"uid": "zvYNYVRtXSSDCi1rZtPP3ieuoh8cG5AscesGPYESa4VpJ",
|
||||
"vectors": [
|
||||
{
|
||||
"name": "text",
|
||||
"cid": "bafkreih5kapbjzq",
|
||||
"uid": "zvYNYVRtXSSDCi1rZtPP3ieuoh8cG5AscesGPYESa4VpJ",
|
||||
"key": "title",
|
||||
"value": "The Matrix",
|
||||
"ts": 1793001234567,
|
||||
"signedBytesHex": "4d4d5552320a85706261666b72656968356b6170626a7a71782d7a76594e5956527458535344436931725a745050336965756f683863473541736365734750594553613456704a657469746c656a546865204d61747269781b000001a17733a087",
|
||||
"sigHex": "3ecac653f63cfc981564b5a5cc0db0459f2b4f19b810b6391d8f487216da0f3d2e560a2b61f4a81e320287cde753e1990d7949f4f518127f6505b8fb698ee8a8"
|
||||
},
|
||||
{
|
||||
"name": "empty-text",
|
||||
"cid": "bafkreih5kapbjzq",
|
||||
"uid": "zvYNYVRtXSSDCi1rZtPP3ieuoh8cG5AscesGPYESa4VpJ",
|
||||
"key": "title",
|
||||
"value": "",
|
||||
"ts": 1,
|
||||
"signedBytesHex": "4d4d5552320a85706261666b72656968356b6170626a7a71782d7a76594e5956527458535344436931725a745050336965756f683863473541736365734750594553613456704a657469746c656001",
|
||||
"sigHex": "6eeb9ace8afe3987006c166eb0ec564b71e23d6a1c6211fdd55e8b4779c12dbb4f38c443faa3255c2ce7c6592e9d024e4ea57b5fa23446d1d4df647947e37642"
|
||||
},
|
||||
{
|
||||
"name": "unicode",
|
||||
"cid": "bafkreih5kapbjzq",
|
||||
"uid": "zvYNYVRtXSSDCi1rZtPP3ieuoh8cG5AscesGPYESa4VpJ",
|
||||
"key": "titles/jpn/攻殻機動隊",
|
||||
"value": "true",
|
||||
"ts": 1793001234567,
|
||||
"signedBytesHex": "4d4d5552320a85706261666b72656968356b6170626a7a71782d7a76594e5956527458535344436931725a745050336965756f683863473541736365734750594553613456704a781a7469746c65732f6a706e2fe694bbe6aebbe6a99fe58b95e99a8a64747275651b000001a17733a087",
|
||||
"sigHex": "64ec6342c598782df278b49636a34da4f4c009423a584454a3284efad5426aa517d83873b09a4fdd3fd32a5e9a5fef0880126edd11db773045caeb6e634bc207"
|
||||
},
|
||||
{
|
||||
"name": "keyset-member",
|
||||
"cid": "bagacbabaec7v3",
|
||||
"uid": "zvYNYVRtXSSDCi1rZtPP3ieuoh8cG5AscesGPYESa4VpJ",
|
||||
"key": "cids/bafkreih5kapbjzq",
|
||||
"value": "true",
|
||||
"ts": 23,
|
||||
"signedBytesHex": "4d4d5552320a856e6261676163626162616563377633782d7a76594e5956527458535344436931725a745050336965756f683863473541736365734750594553613456704a75636964732f6261666b72656968356b6170626a7a71647472756517",
|
||||
"sigHex": "8f707847895ccb522f1507dbab23330bd2c567d6fd1882df3bfae65bef6601024832f0b181146dcfb089aae91f5beac47da970373ab14370c4ac41410f3bf761"
|
||||
},
|
||||
{
|
||||
"name": "bytes",
|
||||
"cid": "bafkreih5kapbjzq",
|
||||
"uid": "zvYNYVRtXSSDCi1rZtPP3ieuoh8cG5AscesGPYESa4VpJ",
|
||||
"key": "seek",
|
||||
"value": null,
|
||||
"valueBytesHex": "00ff10ab",
|
||||
"ts": 24,
|
||||
"signedBytesHex": "4d4d5552320a85706261666b72656968356b6170626a7a71782d7a76594e5956527458535344436931725a745050336965756f683863473541736365734750594553613456704a647365656b4400ff10ab1818",
|
||||
"sigHex": "09671b27c03edd510029ec550b35e95e3900dd37a5d688ea04c3f0409979c7236bc4a1b5fa9d1b76265da85df24693a51f0ced528a6171c90a70b92db9f246e4"
|
||||
},
|
||||
{
|
||||
"name": "retraction",
|
||||
"cid": "bafkreih5kapbjzq",
|
||||
"uid": "zvYNYVRtXSSDCi1rZtPP3ieuoh8cG5AscesGPYESa4VpJ",
|
||||
"key": "genres/Drama",
|
||||
"value": null,
|
||||
"ts": 255,
|
||||
"signedBytesHex": "4d4d5552320a85706261666b72656968356b6170626a7a71782d7a76594e5956527458535344436931725a745050336965756f683863473541736365734750594553613456704a6c67656e7265732f4472616d61f618ff",
|
||||
"sigHex": "d0c29d8edac4b78005eaf895cd9d534cb080b22ba9f7e79a5abf4d9bd906dc494464a2b388653452bca16e351132a9a92370953fa047e693459e55b7965449ac"
|
||||
},
|
||||
{
|
||||
"name": "long-value",
|
||||
"cid": "bafkreih5kapbjzq",
|
||||
"uid": "zvYNYVRtXSSDCi1rZtPP3ieuoh8cG5AscesGPYESa4VpJ",
|
||||
"key": "plot/eng",
|
||||
"value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
"ts": 65536,
|
||||
"signedBytesHex": "4d4d5552320a85706261666b72656968356b6170626a7a71782d7a76594e5956527458535344436931725a745050336965756f683863473541736365734750594553613456704a68706c6f742f656e6779012c6161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161611a00010000",
|
||||
"sigHex": "383b2e40f913eb5240e1eae2cfa392f967321d3701623c2b3df344984686d888198bce1c78847d1898b35f991ec3465c382c45e03b9a77f2ae7d1fd740391dd2"
|
||||
},
|
||||
{
|
||||
"name": "ts-64bit",
|
||||
"cid": "bafkreih5kapbjzq",
|
||||
"uid": "zvYNYVRtXSSDCi1rZtPP3ieuoh8cG5AscesGPYESa4VpJ",
|
||||
"key": "year",
|
||||
"value": "1999",
|
||||
"ts": 1099511627776,
|
||||
"signedBytesHex": "4d4d5552320a85706261666b72656968356b6170626a7a71782d7a76594e5956527458535344436931725a745050336965756f683863473541736365734750594553613456704a647965617264313939391b0000010000000000",
|
||||
"sigHex": "2b9b42ef4ebd7fc8d3ca0a514679ca4104f2e627da3a84c7b9664b27ebbdf73946cc37a04e4ea15dbed23a0e48e8797c92fcba5598b012305a314bf776398e0d"
|
||||
}
|
||||
],
|
||||
"highS": {
|
||||
"note": "same claim as `vector`, S replaced by n-S: valid ECDSA, but MMUR2 verifiers must refuse it",
|
||||
"vector": "text",
|
||||
"sigHex": "3ecac653f63cfc981564b5a5cc0db0459f2b4f19b810b6391d8f487216da0f3dd1a9f5d49e0b57e1cdfd783218ac1e65ad3592f1ba308dbc5acca59166a75899"
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,8 @@ describe('Filename Parser Plugin Integration Tests', () => {
|
||||
});
|
||||
|
||||
it('declares correct schema', () => {
|
||||
expect(manifest.schema).toHaveProperty('originalTitle');
|
||||
expect(manifest.schema).toHaveProperty('parsedTitle');
|
||||
expect(manifest.schema).not.toHaveProperty('originalTitle');
|
||||
expect(manifest.schema).toHaveProperty('videoType');
|
||||
expect(manifest.schema).toHaveProperty('season');
|
||||
expect(manifest.schema).toHaveProperty('episode');
|
||||
|
||||
Reference in New Issue
Block a user