Something went wrong. Try again.
Browser extension: detect and subscribe to standard.site publications on ATProto substandard.blog
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264// MV3 service worker: detection state per tab, toolbar badge states, and// public reads (publication records, the user's subscription list). OAuth and// PDS writes happen in extension pages (see src/lib/oauth.ts) because the// OAuth client cannot run in a worker; the pages mirror {did, handle} into// chrome.storage.local under `session` for the worker to use.
import { listRecords, parseAtUri, resolveDid } from './lib/atproto'import { detectPage } from './lib/detection'import { ICON_SIZES, type IconState, badgeFor, iconStateFor, renderBaseIcon } from './lib/icon'import { CoalescingQueue } from './lib/scheduler'import type { Msg, PageState, SessionInfo } from './lib/types'
const SUB_COLLECTION = 'site.standard.graph.subscription'const SUBS_TTL = 5 * 60 * 1000
// --- per-tab state, kept in storage.session so it survives worker restarts ---
async function getTabState(tabId: number): Promise<PageState | undefined> { const key = `tab:${tabId}` return (await chrome.storage.session.get(key))[key] as PageState | undefined}
async function setTabState(tabId: number, state: PageState | undefined): Promise<void> { const key = `tab:${tabId}` if (state) await chrome.storage.session.set({ [key]: state }) else await chrome.storage.session.remove(key) await setBadge(tabId, iconStateFor(state))}
// --- toolbar badge -----------------------------------------------------------//// The icon is always the bare logo; per-tab state is shown with Chrome's// native badge layer, which the toolbar draws on top of the icon at full// size instead of us cramming a dot into the 16px canvas.
/** Last state set per tab; only for transition debug logs. */const lastBadge = new Map<number, IconState>()
async function setBadge(tabId: number, state: IconState): Promise<void> { const prev = lastBadge.get(tabId) if (prev !== state) { console.debug('[substandard] badge', tabId, `${prev ?? '(unset)'} -> ${state}`) lastBadge.set(tabId, state) } try { const badge = badgeFor(state) if (!badge) { await chrome.action.setBadgeText({ tabId, text: '' }) return } await chrome.action.setBadgeBackgroundColor({ tabId, color: badge.background }) await chrome.action.setBadgeTextColor({ tabId, color: badge.color }) await chrome.action.setBadgeText({ tabId, text: badge.text }) } catch { // tab may be gone }}
// The toolbar icon: the logo with slight overscan so the mark reads larger.// Set once globally per worker start; the manifest PNGs are the fallback.async function applyBaseIcon(): Promise<void> { try { const imageData: Record<number, ImageData> = {} for (const size of ICON_SIZES) imageData[size] = await renderBaseIcon(size) await chrome.action.setIcon({ imageData }) } catch (err) { console.debug('[substandard] base icon render failed; keeping manifest icon', err) }}void applyBaseIcon()
// --- subscriptions -----------------------------------------------------------
interface SubsCache { at: number /** publication at-uri -> our subscription record rkey */ byPub: Record<string, string>}
async function getSession(): Promise<SessionInfo | undefined> { return (await chrome.storage.local.get('session')).session as SessionInfo | undefined}
async function getSubscriptions(refresh: boolean): Promise<SubsCache | null> { const session = await getSession() if (!session) return null const key = `subs:${session.did}` const cached = (await chrome.storage.session.get(key))[key] as SubsCache | undefined if (cached && !refresh && Date.now() - cached.at < SUBS_TTL) return cached
const { pds } = await resolveDid(session.did) const records = await listRecords<{ publication?: string }>( pds, session.did, SUB_COLLECTION, ) const byPub: Record<string, string> = {} for (const r of records) { const rkey = parseAtUri(r.uri)?.rkey if (rkey && r.value.publication) byPub[r.value.publication] = rkey } const fresh: SubsCache = { at: Date.now(), byPub } await chrome.storage.session.set({ [key]: fresh }) return fresh}
// --- detection orchestration -------------------------------------------------
/** Detection is network-bound and the reinjection sweep after an extension * update makes every open tab report hints at once; run a few at a time, * newest request per tab wins, user-facing requests jump the queue. */const detections = new CoalescingQueue<number, PageState>(3)
function scheduleDetection( tabId: number, url: string, hints: { pubHint?: string; docHint?: string }, opts: { refreshSubs?: boolean; urgent?: boolean } = {},): Promise<PageState> { if (detections.depth > 0) { console.debug('[substandard] detection queued', tabId, 'depth', detections.depth) } // Immediate feedback even while the tab waits for a slot. void setBadge(tabId, 'checking') return detections.run(tabId, () => computeState(tabId, url, hints, !!opts.refreshSubs), { urgent: opts.urgent, })}
async function computeState( tabId: number, url: string, hints: { pubHint?: string; docHint?: string }, refreshSubs: boolean,): Promise<PageState> { await setBadge(tabId, 'checking') let state: PageState try { const { pub, doc } = await detectPage(url, hints.pubHint, hints.docHint) state = { url, fetchedAt: Date.now(), pub, doc } if (!pub && !doc && !navigator.onLine) { // Every probe misses while offline; that is absence of signal, not a // page without a publication. state.error = 'offline' } if (pub) { const subs = await getSubscriptions(refreshSubs).catch(() => null) state.subscriptionRkey = subs ? (subs.byPub[pub.uri] ?? null) : undefined } } catch (err) { // Detection itself blew up (network, resolver, ...): record why, don't // claim "not on standard.site". const kind = navigator.onLine === false ? 'offline' : 'fetch-failed' console.debug('[substandard] detection error', tabId, kind, err) state = { url, fetchedAt: Date.now(), error: kind } } await setTabState(tabId, state) return state}
function isHttpUrl(url: string | undefined): url is string { return !!url && /^https?:\/\//.test(url)}
// --- message handling --------------------------------------------------------
chrome.runtime.onMessage.addListener((msg: Msg, sender, sendResponse) => { handle(msg, sender) .then(sendResponse) .catch((err: unknown) => { sendResponse({ __error: err instanceof Error ? err.message : String(err) }) }) return true})
async function handle(msg: Msg, sender: chrome.runtime.MessageSender): Promise<unknown> { switch (msg.type) { case 'page-hints': { const tabId = sender.tab?.id const url = sender.tab?.url ?? sender.url if (tabId === undefined || !isHttpUrl(url)) return return scheduleDetection(tabId, url, msg, { urgent: sender.tab?.active }) } case 'get-state': { const cached = await getTabState(msg.tabId) // Error states are transient; recheck them on every popup open rather // than pinning a stale failure until the user finds Refresh. if (cached && !cached.error && !msg.refresh) return cached const tab = await chrome.tabs.get(msg.tabId).catch(() => undefined) if (!isHttpUrl(tab?.url)) return undefined // Re-read hints from the page so remote edits show up on refresh. const hints = await chrome.tabs .sendMessage(msg.tabId, { type: 'read-hints' }) .catch(() => undefined) return scheduleDetection(msg.tabId, tab.url, hints ?? {}, { refreshSubs: !!msg.refresh, urgent: true, }) } }}
// Manifest content scripts are only injected at document load, so an extension// install or update leaves every already-open tab with no live copy (updates// orphan the old one): 'read-hints' has no receiver and the tab would read as// publication-free until reloaded. Put the script back into matching tabs; its// report() then repopulates badges through the detection queue.chrome.runtime.onInstalled.addListener(() => { void reinjectContentScripts()})
async function reinjectContentScripts(): Promise<void> { for (const cs of chrome.runtime.getManifest().content_scripts ?? []) { if (!cs.js?.length) continue const tabs = await chrome.tabs.query({ url: cs.matches }) let injected = 0 for (const tab of tabs) { // Discarded tabs get the manifest injection when they reload on focus. if (tab.id === undefined || !isHttpUrl(tab.url) || tab.discarded) continue try { await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: cs.js }) injected++ } catch (err) { // e.g. policy-blocked page; it self-heals on next navigation console.debug('[substandard] could not reinject into tab', tab.id, err) } } console.debug(`[substandard] reinjected content script into ${injected}/${tabs.length} tabs`) }}
chrome.tabs.onRemoved.addListener((tabId) => { void chrome.storage.session.remove(`tab:${tabId}`) lastBadge.delete(tabId)})
// Clear stale state on plain navigations; the content script re-reports.chrome.tabs.onUpdated.addListener((tabId, changeInfo) => { if (changeInfo.status === 'loading' && changeInfo.url) { void chrome.storage.session.remove(`tab:${tabId}`) void setBadge(tabId, isHttpUrl(changeInfo.url) ? 'checking' : 'idle') }})
// Sign-in/sign-out happens in extension pages, which mirror {did, handle} into// storage.local under `session`. Re-resolve subscription state for every tab we// know about so icons flip between detected/signedout/subscribed.chrome.storage.onChanged.addListener((changes, area) => { if (area === 'local' && 'session' in changes) void refreshSubscriptionStates()})
async function refreshSubscriptionStates(): Promise<void> { console.debug('[substandard] session changed; refreshing subscription state') const all = await chrome.storage.session.get(null) const subs = await getSubscriptions(true).catch(() => null) for (const [key, value] of Object.entries(all)) { if (!key.startsWith('tab:')) continue const state = value as PageState if (!state.pub) continue state.subscriptionRkey = subs ? (subs.byPub[state.pub.uri] ?? null) : undefined await setTabState(Number(key.slice(4)), state) }}