// The stansite labeler service. // // It reads the panoptiblog dataset, turns each account's labels into signed // atproto labels, and serves the two endpoints a labeler must have: // com.atproto.label.queryLabels and com.atproto.label.subscribeLabels. The // signing key comes from the deployment's secret; nothing here creates one. // // Config: // LABELER_DID the labeler account's DID (did:web:...) // LABELER_SIGNING_KEY secp256k1 private key, hex // LABELER_PDS the account's PDS, for the DID document // LABELER_ENDPOINT public base URL (defaults to the did:web host) // PANOPTIBLOG_DATA_URL dataset URL (defaults to substandard.blog) // LABELER_REFRESH_MS dataset refresh interval (default 15 minutes) // PORT listen port (default 3000) import { readFileSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { createServer, ResponseType, XRPCError } from '@atproto/xrpc-server' import express from 'express' import { didDocument, diffLabels, keypairFromHex, labelsFromDataset, queryLabels, signLabel, } from './labels.mjs' import { LabelStore } from './store.mjs' const HERE = import.meta.dirname const PORT = Number(process.env.PORT ?? 3000) const DID = process.env.LABELER_DID ?? '' const PDS = process.env.LABELER_PDS ?? '' const DATA_URL = process.env.PANOPTIBLOG_DATA_URL ?? 'https://substandard.blog/panoptiblog/accounts.json' const DATA_FILE = process.env.PANOPTIBLOG_DATA_FILE const REFRESH_MS = Number(process.env.LABELER_REFRESH_MS ?? 15 * 60 * 1000) if (!DID.startsWith('did:web:')) { throw new Error('LABELER_DID must be a did:web identity') } const host = decodeURIComponent(DID.slice('did:web:'.length)) const ENDPOINT = process.env.LABELER_ENDPOINT ?? `https://${host}` const lexicons = ['com.atproto.label.defs', 'com.atproto.label.queryLabels', 'com.atproto.label.subscribeLabels'].map( (name) => JSON.parse(readFileSync(join(HERE, '..', 'lexicons', `${name}.json`), 'utf8')), ) const keypair = await keypairFromHex(process.env.LABELER_SIGNING_KEY) const publicKeyMultibase = keypair.did().replace(/^did:key:/, '') const store = new LabelStore() let previousPositive = [] function log(...parts) { console.log('[stansite-labeler]', ...parts) } /** * Replace the current positive label set with the dataset's. The first load * emits every label; later loads emit only changes, with a negation for a * value that has gone away. */ let etag async function loadDataset() { if (DATA_FILE) return JSON.parse(await readFile(DATA_FILE, 'utf8')) const response = await fetch(DATA_URL, { headers: { accept: 'application/json', ...(etag ? { 'if-none-match': etag } : {}), }, }) // The scheduled job replaces the object at most once a day. CloudFront // carries the origin ETag, so a refresh that has not changed costs a 304 // rather than the whole corpus. if (response.status === 304) return undefined if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${DATA_URL}`) etag = response.headers.get('etag') ?? etag return response.json() } async function refresh() { const dataset = await loadDataset() if (!dataset) return const next = labelsFromDataset(dataset) const cts = typeof dataset.generatedAt === 'string' ? dataset.generatedAt : new Date().toISOString() let pending if (previousPositive.length === 0) { pending = next } else { const { added, removed } = diffLabels(previousPositive, next) pending = [...added, ...removed.map((label) => ({ ...label, cts }))] } if (pending.length > 0) { const signed = await Promise.all( pending.map((label) => signLabel(label, { src: DID, keypair })), ) // A full first load can be tens of thousands of labels; keep each frame // small enough for a subscriber to decode without a multi-megabyte burst. for (let i = 0; i < signed.length; i += 500) { const frame = store.append(signed.slice(i, i + 500)) if (frame) log(`emitted ${frame.labels.length} label(s) in frame ${frame.seq}`) } } previousPositive = next } const server = createServer(lexicons, { validateResponse: false }) server.method('com.atproto.label.queryLabels', ({ params }) => ({ encoding: 'application/json', body: queryLabels(store.all, params), })) server.streamMethod('com.atproto.label.subscribeLabels', async function* ({ params, signal }) { const cursor = Number(params.cursor ?? 0) if (cursor > store.seq) { throw new XRPCError(ResponseType.InvalidRequest, 'cursor is in the future', 'FutureCursor') } for (const frame of store.since(cursor)) { yield { $type: '#labels', seq: frame.seq, labels: frame.labels } } // Wait for the next append, and wake on shutdown so the generator ends. const queue = [] let wake const unsubscribe = store.subscribe((frame) => { queue.push(frame) wake?.() }) try { while (!signal.aborted) { if (queue.length === 0) { await new Promise((resolve) => { wake = resolve signal.addEventListener('abort', resolve, { once: true }) }) wake = undefined } while (queue.length > 0) { const frame = queue.shift() yield { $type: '#labels', seq: frame.seq, labels: frame.labels } } } } finally { unsubscribe() } }) server.router.get('/health', (_req, res) => { res.json({ status: 'ok', labels: store.all.length, seq: store.seq }) }) server.router.get('/.well-known/did.json', (_req, res) => { res.json( didDocument({ did: DID, publicKeyMultibase, pds: PDS || undefined, endpoint: ENDPOINT, }), ) }) await refresh().catch((err) => log('initial dataset load failed:', err.message)) // Mounted rather than listened to directly: xrpc-server enables the WebSocket // upgrade on its router's `mount` event, so subscribeLabels needs an Express // app above it. const app = express() app.use(server.router) const http = app.listen(PORT, () => { log(`listening on ${PORT} as ${DID}, ${store.all.length} label(s)`) }) const timer = setInterval(() => { refresh().catch((err) => log('dataset refresh failed:', err.message)) }, REFRESH_MS) for (const signal of ['SIGTERM', 'SIGINT']) { process.on(signal, () => { clearInterval(timer) http.close(() => process.exit(0)) }) }