Something went wrong. Try again.
Browser extension: detect and subscribe to standard.site publications on ATProto substandard.blog
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270// Reads the standard.site corpus from the network itself.//// A publication or document record lives in its author's repository, and a// repository lives on a PDS. Nothing enumerates publications directly, but the// relay can answer "which repositories hold a record in this collection?" — so// discovery is one endpoint per collection, followed by one listRecords per// repository. Each run reads current records, which means edits and deletions// are handled without an event log or a stored cursor.//// The only third-party services are the relay (an index of repository// collections) and plc.directory (DID documents). Neither sees a credential:// every read here is public.
import { createHash } from 'node:crypto'
export const DEFAULT_RELAY = 'https://relay1.us-east.bsky.network'export const PLC_DIRECTORY = 'https://plc.directory'export const PUBLIC_API = 'https://public.api.bsky.app'
export const COLLECTIONS = { publication: 'site.standard.publication', document: 'site.standard.document', subscription: 'site.standard.graph.subscription', recommend: 'site.standard.graph.recommend',}
/** atproto's listRecords maximum; the page size, not the walk's limit. */const RECORDS_PAGE = 100
const DID = /^did:[a-z0-9]+:[^/?#]+$/const AT_URI = /^at:\/\/([^/]+)\/([^/]+)\/([^/?#]+)$/const DID_WEB_HOST = /^[a-z0-9-]+(\.[a-z0-9-]+)*(:\d{1,5})?$/i
export function isDid(value) { return typeof value === 'string' && DID.test(value)}
export function parseAtUri(uri) { if (typeof uri !== 'string') return null const match = AT_URI.exec(uri.trim()) if (!match) return null return { authority: match[1], collection: match[2], rkey: match[3] }}
export function listReposByCollectionUrl(relay, collection, cursor, limit) { const url = new URL('/xrpc/com.atproto.sync.listReposByCollection', relay) url.searchParams.set('collection', collection) url.searchParams.set('limit', String(limit)) if (cursor) url.searchParams.set('cursor', cursor) return url.toString()}
export function listRecordsUrl(pds, did, collection, cursor) { const url = new URL('/xrpc/com.atproto.repo.listRecords', pds) url.searchParams.set('repo', did) url.searchParams.set('collection', collection) url.searchParams.set('limit', String(RECORDS_PAGE)) if (cursor) url.searchParams.set('cursor', cursor) return url.toString()}
export function resolveHandleUrl(handle) { const url = new URL('/xrpc/com.atproto.identity.resolveHandle', PUBLIC_API) url.searchParams.set('handle', handle) return url.toString()}
export function blobUrl(pds, did, blob) { const cid = blob?.ref?.$link if (typeof cid !== 'string') return undefined const url = new URL('/xrpc/com.atproto.sync.getBlob', pds) url.searchParams.set('did', did) url.searchParams.set('cid', cid) return url.toString()}
class RetryableError extends Error {}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
/** * JSON over HTTP with a timeout and bounded retries. * * 429 and 5xx are retried because they mean "not now"; every other status is * final. Network errors and timeouts are retried too. A caller walking tens of * thousands of repositories cannot let one slow PDS end the run, so retries are * small and the failure is returned to the caller rather than thrown through * the whole walk. */export async function requestJson( url, { fetchImpl = fetch, timeoutMs = 15_000, retries = 3, signal } = {},) { for (let attempt = 0; ; attempt++) { const controller = new AbortController() const forwardAbort = () => controller.abort(signal?.reason) signal?.addEventListener('abort', forwardAbort, { once: true }) const timer = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs) try { const res = await fetchImpl(url, { signal: controller.signal, headers: { 'user-agent': 'substandard-panoptiblog/1 (+https://substandard.blog)' }, }) if (res.ok) return await res.json() const body = await res.text().catch(() => '') const message = `${res.status} ${res.statusText} for ${url}${body ? `: ${body.slice(0, 200)}` : ''}` if (res.status === 429 || res.status >= 500) throw new RetryableError(message) throw new Error(message) } catch (err) { if (signal?.aborted) throw err const retryable = err instanceof RetryableError || err.name === 'AbortError' || err.name === 'TypeError' if (!retryable || attempt >= retries) throw err // Full jitter, capped: a whole walk hitting one rate limit should spread // out rather than retry in a thundering herd. await sleep(Math.min(4_000, 100 * 2 ** attempt) * (0.5 + Math.random())) } finally { clearTimeout(timer) signal?.removeEventListener('abort', forwardAbort) } }}
/** * Every DID whose repository holds a record in `collection`, as pages. * * A generator rather than one array: the caller folds each page into state as * it arrives, so discovery never holds the whole network's DID list twice. */export async function* listRepoDids( collection, { relay = DEFAULT_RELAY, limit = 2_000, maxPages = Infinity, fetchImpl, signal } = {},) { let cursor for (let page = 0; page < maxPages; page++) { const body = await requestJson(listReposByCollectionUrl(relay, collection, cursor, limit), { fetchImpl, signal, }) const dids = (body.repos ?? []).map((repo) => repo.did).filter(isDid) yield dids cursor = body.cursor if (!cursor) return }}
/** * Every record in one collection in one repository, newest page first as the * PDS returns them. `truncated` says the walk stopped at `limit`, so callers * can tell a complete repository from a prefix. */export async function listCollection( pds, did, collection, { limit = 10_000, fetchImpl, signal, timeoutMs = 10_000, retries = 1 } = {},) { const records = [] let cursor let truncated = false do { const body = await requestJson(listRecordsUrl(pds, did, collection, cursor), { fetchImpl, signal, timeoutMs, retries, }) records.push(...(body.records ?? [])) cursor = body.cursor if (records.length >= limit) { truncated = !!cursor break } } while (cursor) return { records: records.slice(0, limit), truncated }}
function didWebHost(did) { let host try { host = decodeURIComponent(did.slice('did:web:'.length)) } catch { throw new Error(`Malformed did:web: ${did}`) } if (!DID_WEB_HOST.test(host)) throw new Error(`Unsupported did:web host: ${did}`) return host}
/** * A DID's PDS endpoint and the handle its document claims. * * The endpoint is third-party input on its way into every subsequent fetch, so * it must be https. The handle is unverified here; it is a display name, not * an identity claim. */export async function resolveDid( did, { fetchImpl, signal, timeoutMs = 8_000, retries = 1 } = {},) { if (!isDid(did)) throw new Error(`Not a DID: ${did}`) let document if (did.startsWith('did:plc:')) { document = await requestJson(`${PLC_DIRECTORY}/${did}`, { fetchImpl, signal, timeoutMs, retries, }) } else if (did.startsWith('did:web:')) { document = await requestJson(`https://${didWebHost(did)}/.well-known/did.json`, { fetchImpl, signal, timeoutMs, retries, }) } else { throw new Error(`Unsupported DID method: ${did}`) } const endpoint = (document.service ?? []).find((service) => String(service.id).endsWith('#atproto_pds'), )?.serviceEndpoint if (typeof endpoint !== 'string') throw new Error(`No PDS service for ${did}`) let url try { url = new URL(endpoint) } catch { throw new Error(`Malformed PDS endpoint for ${did}: ${endpoint}`) } if (url.protocol !== 'https:') throw new Error(`Refusing non-https PDS for ${did}`) const aka = (document.alsoKnownAs ?? []).find( (value) => typeof value === 'string' && value.startsWith('at://'), ) return { did, pds: (url.origin + url.pathname).replace(/\/$/, ''), handle: typeof aka === 'string' ? aka.slice('at://'.length) : undefined, }}
/** Handle to DID, through the public AppView. Kept separate so callers cache it. */export async function resolveHandle(handle, { fetchImpl, signal } = {}) { const body = await requestJson(resolveHandleUrl(handle), { fetchImpl, signal }) if (!isDid(body.did)) throw new Error(`Could not resolve handle: ${handle}`) return body.did}
/** * An at-uri with its authority in DID form. Returns null for anything that is * not an at-uri, including the https URLs loose documents use as `site`. */export async function normalizeAtUri(uri, { fetchImpl, signal, handleCache } = {}) { const parsed = parseAtUri(uri) if (!parsed) return null let authority = parsed.authority if (!authority.startsWith('did:')) { const cached = handleCache?.get(authority) if (cached) { authority = cached } else { authority = await resolveHandle(authority, { fetchImpl, signal }) handleCache?.set(parsed.authority, authority) } } return `at://${authority}/${parsed.collection}/${parsed.rkey}`}
/** A short, stable digest. Only used to notice identical text, never as an id. */export function digest(value) { return createHash('sha256').update(value).digest('hex').slice(0, 16)}