Something went wrong. Try again.
Browser extension: detect and subscribe to standard.site publications on ATProto substandard.blog
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189// 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.dirnameconst 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_FILEconst 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)) })}