// Detecting whether a page belongs to a standard.site publication. // // Per https://standard.site/docs/verification/ the authoritative check for a // publication is the /.well-known/site.standard.publication endpoint (with the // publication's base path appended for non-root publications), which returns // the publication's at:// URI. tags are // hints only. Documents are verified by their // tag. import { blobUrl, getRecord, isBlobRef, type ListedRecord, listRecords, normalizeAtUri, parseAtUri, resolveDid, resolveHandleToDid, } from './atproto' import { cached } from './cache' import { PROBE_OPTIONS, requestText } from './http' import { ext } from './platform' import { parseTheme } from './theme' import type { DocInfo, DocumentRecord, PubInfo, PublicationRecord } from './types' const WK_SUFFIX = '/.well-known/site.standard.publication' /** How deep a hinted page's path is followed for a publication base. */ const MAX_BASE_SEGMENTS = 3 // The two outcomes deserve different lifetimes. A hit means this origin *is* a // publication, so the user is on a site we already talk to and freshness is // what matters — a publisher who fixes a record should not wait a quarter of an // hour to see it. A miss means the origin has nothing to do with us, and it is // the answer nearly every site on the web gives: re-asking costs a request to a // stranger and buys almost nothing, since sites rarely become publications // mid-session. Anyone who cannot wait has the popup's Refresh button, which // bypasses this cache entirely (see the `force` argument). const CACHE_TTL_HIT = 5 * 60 * 1000 const CACHE_TTL_MISS = 60 * 60 * 1000 /** What every stored probe answer is keyed under; see `dropProbes`. */ const WK_CACHE_PREFIX = 'wk:' /** * Probes already in flight, so two tabs opening on one origin ask once. Keyed * by well-known URL and cleared as soon as the probe settles; the storage cache * below is what spans anything longer. */ const inFlight = new Map>() /** The well-known URL for a publication base: origin, plus its path if any. */ export function wellKnownUrl(base: string): string { const url = new URL(base) const path = url.pathname.replace(/\/$/, '') return url.origin + WK_SUFFIX + path } /** * Probe a well-known URL for a publication at-uri. Cached in storage.session; * `force` skips the read (not the write) so the popup's Refresh actually * re-asks the origin instead of handing back the answer it is trying to * replace. */ export async function probeWellKnown(base: string, force = false): Promise { const wkUrl = wellKnownUrl(base) const cacheKey = WK_CACHE_PREFIX + wkUrl if (!force) { const cached = (await ext.storage.session.get(cacheKey))[cacheKey] as | { uri: string | null; at: number } | undefined if (cached) { const ttl = cached.uri ? CACHE_TTL_HIT : CACHE_TTL_MISS if (Date.now() - cached.at < ttl) return cached.uri } const pending = inFlight.get(wkUrl) if (pending) return pending } const probe = (async () => { let uri: string | null = null try { const text = (await requestText(wkUrl, PROBE_OPTIONS)).trim() // May be handle-based (e.g. at://example.com/...); normalize to DID form. if (text.startsWith('at://')) uri = await normalizeAtUri(text) } catch (err) { // A miss and a failure are the same to a caller here — neither yields a // publication — but they are not the same to a reader of the logs. console.debug('[substandard] well-known probe failed', wkUrl, err) } await ext.storage.session.set({ [cacheKey]: { uri, at: Date.now() } }) return uri })() inFlight.set(wkUrl, probe) try { return await probe } finally { inFlight.delete(wkUrl) } } /** * Forget every stored probe answer, so the next detection asks the origins * again. For the dev channel's Drop cache (src/popup/popup.ts), which drops * this alongside the caches in src/lib/cache.ts; ordinary users have Refresh, * which bypasses this cache for the one page they are looking at instead of * making every origin worth re-probing. * * Probes already in flight are left alone. `inFlight` is only a dedup for the * seconds a request is out, and cancelling one would strand its callers. * * Returns how many answers went, so the caller can say. */ export async function dropProbes(): Promise { const all = await ext.storage.session.get(null) const keys = Object.keys(all).filter((k) => k.startsWith(WK_CACHE_PREFIX)) if (keys.length > 0) await ext.storage.session.remove(keys) return keys.length } /** * Load and resolve a publication record from its at-uri. Null for a uri that * is not a publication; throws when the record exists but cannot be fetched, * so callers can tell "no publication" from "could not look". */ async function loadPublication(uri: string): Promise { const parsed = parseAtUri(uri) if (!parsed || parsed.collection !== 'site.standard.publication') return null const { pds, handle } = await resolveDid(parsed.did) const rec = await getRecord( pds, parsed.did, parsed.collection, parsed.rkey, ) const icon = rec.value.icon if (icon !== undefined && !isBlobRef(icon)) { console.debug('[substandard] publication icon is not a blob ref', uri, icon) } return { uri, did: parsed.did, handle, pds, record: rec.value, iconUrl: isBlobRef(icon) ? blobUrl(pds, parsed.did, icon) : undefined, theme: parseTheme(rec.value.basicTheme), verified: false, } } const PROFILE_PUB_COLLECTION = 'site.standard.publication' // A profile has one publication in every case seen so far; a small cap keeps a // misbehaving repo from paging forever without pretending to find them all. const PROFILE_PUB_LIMIT = 10 /** Publication records as they are stored, where `createdAt` is optional. */ interface ProfilePublicationRecord extends PublicationRecord { createdAt?: unknown } function createdAtMs(value: ProfilePublicationRecord): number | undefined { if (typeof value.createdAt !== 'string') return undefined const at = Date.parse(value.createdAt) return Number.isNaN(at) ? undefined : at } /** * The first record, or the newest by `createdAt` when one carries it. Listing * order is the PDS's business, and a repo may legitimately hold more than one * publication, so the one we show should be the account's most recent. */ function newestPublication( records: ListedRecord[], ): ListedRecord | undefined { const first = records[0] if (!first) return undefined let best = first let bestAt = createdAtMs(first.value) for (const record of records.slice(1)) { const at = createdAtMs(record.value) if (at === undefined) continue if (bestAt === undefined || at > bestAt) { best = record bestAt = at } } return best } /** * A publication belonging to the account a Bluesky profile URL names. * * bsky.app serves no standard.site well-known, so there is no page-side * verification to be had: this reads the account's own repo and returns the * record unverified. Named here rather than in src/background.ts so the read * policy and the failure modes live next to the rest of detection. * * Cached under `world` with the DID as subject — the account's publication * changes no more often than any other stranger's data, and repeat visits to * one profile should not re-list the repo. `force` is the popup's Refresh. * * Null when the account has no publication or any read fails, including a * handle that does not resolve; the caller draws absence, not an error. */ export async function publicationForProfile( handleOrDid: string, force = false, ): Promise { const subject = handleOrDid.trim() if (!subject) return null let did: string try { did = subject.startsWith('did:') ? subject : await resolveHandleToDid(subject) } catch (err) { console.debug('[substandard] profile handle did not resolve', subject, err) return null } try { return await cached( { scope: 'world', subject: did, name: 'profile-pub' }, async () => { const { pds, handle } = await resolveDid(did) const records = await listRecords( pds, did, PROFILE_PUB_COLLECTION, PROFILE_PUB_LIMIT, ) const found = newestPublication(records) if (!found) { console.debug('[substandard] no publication on profile', did) return null } const icon = found.value.icon if (icon !== undefined && !isBlobRef(icon)) { console.debug( '[substandard] profile publication icon is not a blob ref', found.uri, icon, ) } console.debug('[substandard] publication found from profile', did, found.uri) return { uri: found.uri, did, handle, pds, record: found.value, iconUrl: isBlobRef(icon) ? blobUrl(pds, did, icon) : undefined, theme: parseTheme(found.value.basicTheme), // A profile page is not the publication's verified home. Keeping the // flag false is what shows the `*` and the popup's caveat, which is // the honest answer: the record was found, not verified from here. verified: false, } }, { refresh: force }, ) } catch (err) { console.debug('[substandard] profile publication read failed', did, err) return null } } async function loadDocument(uri: string): Promise { const parsed = parseAtUri(uri) if (!parsed || parsed.collection !== 'site.standard.document') return null const { pds } = await resolveDid(parsed.did) const rec = await getRecord( pds, parsed.did, parsed.collection, parsed.rkey, ) return { uri, record: rec.value } } /** * Full detection for a page. Candidate publication at-uris come from the page's * link-tag hints, the document record's `site` field, and well-known probes of * the origin and the page's first path segment. A candidate only counts as * verified once the well-known endpoint at the publication record's own `url` * returns its at-uri. */ export async function detectPage( pageUrl: string, pubHint?: string, docHint?: string, force = false, ): Promise<{ pub?: PubInfo; doc?: DocInfo }> { const url = new URL(pageUrl) const candidates: string[] = [] const push = (uri: string | null | undefined) => { if (uri && parseAtUri(uri) && !candidates.includes(uri)) candidates.push(uri) } let doc: DocInfo | undefined if (docHint) { try { const normDoc = await normalizeAtUri(docHint) if (normDoc) doc = (await loadDocument(normDoc)) ?? undefined } catch (err) { // A dead document hint should not sink publication detection. console.debug('[substandard] document load failed', docHint, err) } if (doc?.record.site.startsWith('at://')) { push(await normalizeAtUri(doc.record.site)) } } if (pubHint) push(await normalizeAtUri(pubHint)) // Probe the origin, then path prefixes. Root and one level are the shapes // most publications use, so the first segment is always worth a probe. // Deeper bases are only followed when the page carries a standard.site // hint: it has said it belongs to this network, and a publication under // /journal/2026 would otherwise be invisible. Probing every prefix on every // page instead would multiply requests across the web for a shape that is // still rare. push(await probeWellKnown(url.origin, force)) const segments = url.pathname.split('/').filter(Boolean) const depth = Math.min(segments.length, doc || pubHint ? MAX_BASE_SEGMENTS : 1) for (let n = 1; n <= depth && candidates.length === 0; n++) { push(await probeWellKnown(`${url.origin}/${segments.slice(0, n).join('/')}`, force)) } // A document may point at its publication by https URL instead of at-uri. if (candidates.length === 0 && doc?.record.site.startsWith('https://')) { push(await probeWellKnown(doc.record.site, force)) } let fallback: PubInfo | undefined let loadFailures = 0 for (const uri of candidates) { let pub: PubInfo | null try { pub = await loadPublication(uri) } catch (err) { console.debug('[substandard] publication load failed', uri, err) loadFailures++ continue } if (!pub) continue // Bidirectional check: the well-known endpoint at the record's own URL // must return this at-uri, and that URL must be on the page's origin. try { if (new URL(pub.record.url).origin === url.origin) { pub.verified = (await probeWellKnown(pub.record.url, force)) === uri } } catch { // bad record.url — leave unverified } if (pub.verified) return { pub, doc } fallback ??= pub } // Candidates existed but none could even be loaded: that is a lookup // failure, not a page without a publication. if (!fallback && loadFailures > 0) { throw new Error(`all ${loadFailures} publication candidate(s) failed to load`) } return { pub: fallback, doc } }