import { randomBytes } from 'node:crypto'; import { Hono } from 'hono'; import { oauth, isLoopback, billingDisabled } from './oauth.js'; import * as discord from './discord-oauth.js'; import { searchGuildMembers } from './discord-oauth.js'; import { setSession, getSession, clearSession, SESSION_MAX_AGE_LONG } from './cookies.js'; import { upsertUserByDiscord, getUserByDiscord, getUserByCustomer, upsertJob, listJobsForUser, getJobByUserAndDid, getJobById, setJobProfile, deleteJob, listRulesForJob, getRuleForJob, insertRule, updateRuleForJob, deleteRuleForJob, toggleRuleForJob, getCounter, listCounters, setUserSubscription, setActiveByCustomer, setActiveByDiscord, deactivateUserAndDisableRules, clearStripeCustomer, tryRecordWebhookEvent, oauthStores, graceUntilEpoch, isWithinGrace, insertBackfillJob, getActiveBackfillJobForRule, getLatestBackfillJobForRule, listBackfillJobsForRule, getActiveBackfillJobForRuleChannel, cancelBackfillJob, } from './db.js'; import { resolveDidProfile } from './atproto-identity.js'; import { client as botClient } from './bot.js'; import { stripe, priceInfo } from './stripe.js'; import { KNOWN_DESTINATIONS, CATALOG, metaFor } from './destinations/index.js'; import { listSembleCollections } from './destinations/bookmark.js'; import { refreshActiveGuilds } from './active-guilds.js'; import { validateMatchPattern } from './match.js'; const PUBLIC_URL = process.env.PUBLIC_URL; const SESSION_SECRET = process.env.SESSION_SECRET; const DISCORD_REDIRECT = `${PUBLIC_URL}/discord/callback`; if (!PUBLIC_URL) throw new Error('PUBLIC_URL is required'); if (!SESSION_SECRET) throw new Error('SESSION_SECRET is required'); const errorPage = (c, message, status = 400) => c.html(` something went wrong

something went wrong

${message}

Start over

`, status); export const app = new Hono(); // Resolves the request to its (account, job, session) triple. Returns null // if the user is not signed in OR has no job for the DID in their cookie. // In loopback dev mode the atproto OAuth flow is disabled, so there is never // a job — callers should treat ctx.job as nullable and degrade the UI for // loopback (no rules editing). function requireActiveJob(c) { const s = getSession(c, SESSION_SECRET); if (!s?.discord?.userId) return null; if (!isLoopback && !s?.did) return null; let user = getUserByDiscord.get(s.discord.userId); if (!user) return null; if (billingDisabled && !user.active) { setActiveByDiscord(user.discord_id, 1); refreshActiveGuilds(); user = getUserByDiscord.get(s.discord.userId); } if (isLoopback) return { user, job: null, session: s }; const job = getJobByUserAndDid(user.id, s.did); if (!job) return null; return { user, job, session: s }; } function botGuildsForUser(userGuildIds) { if (!botClient.isReady?.()) return []; const cache = botClient.guilds.cache; return (userGuildIds ?? []) .map(id => cache.get(id)) .filter(Boolean) .map(g => ({ id: g.id, name: g.name })); } // IDs of guilds the bot AND the user are both in, computed against the bot's // live cache. Cookie-stored list is the user's full guild membership. function sharedGuildIdsFor(userGuildIds) { if (!botClient.isReady?.() || !userGuildIds?.length) return []; const cache = botClient.guilds.cache; return userGuildIds.filter(id => cache.has(id)); } app.get('/', async (c) => { const s = getSession(c, SESSION_SECRET); const discordLinked = !!s?.discord; const sharedGuildIds = sharedGuildIdsFor(s?.discord?.guildIds); const sharedGuildCount = sharedGuildIds.length; const discordReady = discordLinked && sharedGuildCount > 0; const account = discordLinked ? getUserByDiscord.get(s.discord.userId) : null; const jobs = account ? listJobsForUser.all(account.id) : []; const activeJob = (account && s?.did) ? jobs.find(j => j.did === s.did) ?? null : null; const didLinked = !!activeJob; const discordWho = discordLinked ? renderDiscordWho(s.discord) : ''; const discordCard = !discordLinked ? `

So we know which Discord ID's messages are yours.

` : !discordReady ? ` ${discordWho}

The bot isn't in any of your servers yet — without that, no rules can fire.

Click "Add bot to a server", then "Refresh after invite" once it's in.

` : ` ${discordWho}

${sharedGuildCount} shared server${sharedGuildCount === 1 ? '' : 's'} with the bot

`; const atmoCard = isLoopback ? `

atproto OAuth is disabled in loopback dev mode. Switch PUBLIC_URL to a tunneled HTTPS URL to enable this step.

` : !discordReady ? `

Complete the Discord step first.

` : await renderAtmoCard({ jobs, activeJob }); // Identity-stage gating. In loopback dev mode, atproto link is optional. const identityComplete = discordReady && (didLinked || isLoopback); const isActive = !!account?.active; // Third card states. // - billingDisabled (test period / loopback): auto-activated, no payment. // - grace window (BILLING_DISABLED=0 + within GRACE_UNTIL): active without a // stripe customer; show the grace deadline so users know it's transitional. // - paid mode: Subscribe / Manage based on account.active. const subscribeButtonLabel = priceInfo?.label ? `Subscribe — ${priceInfo.label}` : 'Subscribe'; const inGraceWindow = !billingDisabled && isWithinGrace() && !account?.stripe_customer_id; const graceUntilDate = graceUntilEpoch != null ? new Date(graceUntilEpoch * 1000).toISOString().slice(0, 10) : null; let paymentCard; if (!identityComplete) { paymentCard = `

Complete the previous steps to enable subscription.

`; } else if (billingDisabled) { paymentCard = `

Active — test period.

Payment is not required while disjecta is in early testing. Rules and dispatch are fully functional.

`; } else if (isActive && account?.stripe_customer_id) { paymentCard = `

Active — subscribed.

`; } else if (inGraceWindow) { paymentCard = `

Active — free until ${esc(graceUntilDate)}.

You've been carried over from the test period. After ${esc(graceUntilDate)}, rules will stop firing until you subscribe.

`; } else { paymentCard = `

Final step — subscribe to enable rule processing.

`; } const cardClass = (enabled) => enabled ? 'card' : 'card card-disabled'; const arrow = (active) => ``; const ctx = identityComplete ? requireActiveJob(c) : null; const rulesSection = (ctx && ctx.job) ? renderRulesSection(ctx) : ''; return c.html(layout('disjecta', ` ${helpButton()}

disjecta

Route Discord messages — full content or just URLs — into atproto-shaped destinations.

1. Discord

${discordCard}
${arrow(discordReady)}

2. Atmosphere

${atmoCard}
${arrow(identityComplete)}

3. ${billingDisabled ? 'Account' : 'Subscription'}

${paymentCard}
${rulesSection} `)); }); function discordAvatarUrl(userId, hash) { if (!userId || !hash) return null; const ext = hash.startsWith('a_') ? 'gif' : 'png'; return `https://cdn.discordapp.com/avatars/${userId}/${hash}.${ext}?size=64`; } function renderDiscordWho(d) { const avatarUrl = discordAvatarUrl(d.userId, d.avatar); const label = d.globalName ?? d.username ?? d.userId; return `
${avatarUrl ? `` : ``} ${esc(label)}
`; } function renderJobWho(job) { return `
${job.did_avatar ? `` : ``} ${esc(job.did_handle ?? job.did)}
`; } // Probe whether the atproto OAuth session for a given DID is still live. We // check by reading the session-store row (cheap, local) — a missing row means // the user revoked OR we never had one yet. Note: this does NOT prove the // refresh token is still accepted by the PDS; if it's been revoked upstream // we'll only discover that on the next dispatch. Good enough as a UI hint. async function jobOauthLive(did) { try { const v = await oauthStores.session.get(did); return v != null; } catch { return false; } } async function renderAtmoCard({ jobs, activeJob }) { if (jobs.length === 0) { return `
`; } const liveness = new Map(); await Promise.all(jobs.map(async (j) => liveness.set(j.id, await jobOauthLive(j.did)))); const activePill = activeJob ? `
${renderJobWho(activeJob)}
` : ''; const others = jobs.filter(j => activeJob ? j.id !== activeJob.id : true); const otherRows = others.map(j => { const live = liveness.get(j.id); const switchAction = live ? `
` : `
`; const badge = live ? '' : `re-auth needed`; return `
${renderJobWho(j)}
${badge} ${switchAction}
`; }).join(''); const addAnother = `
`; // When the cookie's did doesn't match any job (e.g. you just deleted the // active one), prompt to pick one from the list above or sign in fresh. const noActive = !activeJob ? `

No identity selected. Switch to one above or link a new identity.

` : ''; return `${activePill}${noActive}${otherRows}${addAnother}`; } // Construct the bot install URL from the Discord client id. Permissions // bitmask: View Channels + Read Message History + Send Messages + Use // Application (Slash) Commands. Matches what we configured in the developer // portal's Installation tab. function botInstallUrl() { const clientId = process.env.DISCORD_CLIENT_ID ?? ''; const PERMS = 2147552256; // 0x400 + 0x800 + 0x10000 + 0x80000000 const params = new URLSearchParams({ client_id: clientId, permissions: String(PERMS), scope: 'bot applications.commands', }); return `https://discord.com/api/oauth2/authorize?${params}`; } function helpButton() { return `
?

How this works

  1. Link Discord. We learn your Discord user ID and which servers you're in.
  2. Sign in with an Atmosphere account. Fine-grained OAuth.
  3. Configure rules. Pick which server/channel/author to listen to, what to extract (URLs or full message content), and where to route the result.
  4. Subscribe. $2/month flat. The bot only acts on rules belonging to active subscribers.

Pass-through. Messages flow through disjecta and out to your destinations; we don't store them.

`; } // Defaults object consumed by renderRuleForm. Used for both the empty add // form and the pre-filled edit form so the two paths share rendering. const EMPTY_RULE_DEFAULTS = { guild_id: '', channel_id_display: '', author_mode: 'self', author_id_display: '', mode: 'urls', match_kind: '', match_value: '', destination_kind: '', bookmark_lexicons: [], semble_collection_uri: '', destination_config_raw: '', }; function ruleToFormDefaults(rule) { if (!rule) return { ...EMPTY_RULE_DEFAULTS }; const d = { guild_id: rule.guild_id ?? '', channel_id_display: rule.channel_id ?? '', author_mode: rule.author_id === 'self' ? 'self' : rule.author_id == null ? 'any' : 'id', author_id_display: (rule.author_id && rule.author_id !== 'self') ? rule.author_id : '', mode: rule.mode ?? 'urls', match_kind: rule.match_kind ?? '', match_value: rule.match_value ?? '', destination_kind: rule.destination_kind ?? '', bookmark_lexicons: [], semble_collection_uri: '', destination_config_raw: '', }; if (rule.destination_kind === 'bookmark' && rule.destination_config) { try { const cfg = JSON.parse(rule.destination_config); if (Array.isArray(cfg?.lexicons)) d.bookmark_lexicons = cfg.lexicons; d.semble_collection_uri = cfg?.lexiconConfig?.['semble-card']?.collectionUri ?? ''; } catch {} } else if (rule.destination_kind === 'atproto-record' && rule.destination_config) { d.destination_config_raw = rule.destination_config; } return d; } function renderRuleForm({ action, submitLabel, defaults, guilds, cancelHref }) { const d = defaults; const sel = (a, b) => a === b ? 'selected' : ''; const chk = (a, b) => a === b ? 'checked' : ''; const chkSet = (arr, v) => arr.includes(v) ? 'checked' : ''; const effectiveDest = d.destination_kind || CATALOG[0].id; const guildOptions = guilds.length === 0 ? `` : guilds.map(g => `` ).join(''); const destOptions = CATALOG.map(meta => `` ).join(''); return `

Type a channel name like #general or general; we'll resolve it inside the selected server. Numeric IDs are kept as-is.

Author

Username works without Discord developer mode — right-click a user → Copy Username. We resolve it to an ID inside the selected server.
Extract One record per URL found. Messages with no URLs are skipped.
One record per message, with the entire message text. Empty messages are skipped.
Message must match (optional)


Applied to the whole message before extraction. Useful for narrowing to messages containing a keyword like "announcement" or matching a pattern.

${CATALOG.map(meta => `${esc(meta.name)}: ${esc(meta.description)}`).join('
')}

Bookmark: which lexicons to write ${(metaFor('bookmark')?.lexicons ?? []).map(l => ` ${esc(l.description)}
`).join('')} Pick at least one. Each selected lexicon gets its own record per URL — you can write only the community standard, only an app-specific collection, or fan out to several.
Loading your Semble collections…
Raw atproto record config Provide an NSID under the "collection" key.

${cancelHref ? `Cancel` : ''}

`; } function renderRulesSection({ user, job, session }) { const rules = listRulesForJob.all(job.id); const userGuildIds = session.discord.guildIds ?? []; const guilds = botGuildsForUser(sharedGuildIdsFor(userGuildIds)); const thisMonth = getCounter(job.id); const recent = listCounters(job.id, 6); const backfillEnabled = canUseBackfill(user); const usageBlock = `
Writes this month: ${thisMonth} ${recent.length > 1 ? `recent: ${ recent.map(r => `${esc(r.period)}=${r.count}`).join(', ') }` : ''}
`; const ruleRows = rules.length === 0 ? `

No rules yet — nothing is being captured. Add one below to start.

` : ` ${rules.map(r => ruleRow(r, guilds, backfillEnabled)).join('')}
ServerChannelAuthorMatchExtractDestinationState
`; return `

Rules for ${esc(job.did_handle ?? job.did)}

Each rule tells the bot to act on messages matching its filters and route the result to a destination. The bot does nothing in a server until you have at least one rule pointing at it.

${usageBlock} ${ruleRows}

Add rule

${renderRuleForm({ action: '/rules', submitLabel: 'Add rule', defaults: { ...EMPTY_RULE_DEFAULTS }, guilds, })} ${backfillEnabled ? `

Backfill — available once the rule exists

After you add the rule, you can replay a channel's history through it from here. We keep it disabled until then so you can add the rule, confirm its filters and destination look right, and only then run the backfill. A Backfill button appears on the rule's row once it's saved.

` : ''}

The "Server" dropdown shows servers where the bot is present and you are a member. If a server is missing, invite the bot and re-link your Discord account here.

Examples

GoalServerChannelAuthorExtract
Save URLs I post in #links to my PDS my server#linksjust meURLs only
Mirror every message in #announcements my server#announcementsanyonefull content
Capture Boris's posts anywhere in a server my server(any)Boris's Discord IDfull content
Bookmark every URL anyone shares in a server my server(any)anyoneURLs only
Log just my messages from one channel my server#my-channeljust mefull content
`; } app.post('/cancel', (c) => { clearSession(c); return c.redirect('/'); }); // Clear the OAuth session for the currently-active DID without deleting the // job. Rules stay configured; they'll go dormant until the user re-auths via // the "Re-auth" button on the switcher. app.post('/atmo/sign-out-current', async (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.redirect('/'); try { await oauth?.revoke?.(ctx.job.did); } catch {} try { await oauthStores.session.del(ctx.job.did); } catch {} setSession(c, { discord: ctx.session.discord }, SESSION_SECRET, SESSION_MAX_AGE_LONG); return c.redirect('/'); }); // Switch the cookie's "active job" to a different one the same account owns. // Doesn't touch OAuth sessions; if the target's session has lapsed the UI // will surface the re-auth prompt on the next render. app.post('/jobs/:id/switch', (c) => { const s = getSession(c, SESSION_SECRET); if (!s?.discord?.userId) return c.redirect('/'); const account = getUserByDiscord.get(s.discord.userId); if (!account) return c.redirect('/'); const id = Number(c.req.param('id')); if (!Number.isInteger(id)) return errorPage(c, 'Bad job id.'); const job = getJobById.get(id); if (!job || job.user_id !== account.id) return errorPage(c, 'Job not found.', 404); setSession(c, { discord: s.discord, did: job.did }, SESSION_SECRET, SESSION_MAX_AGE_LONG); return c.redirect('/'); }); // Destructive: drops the job and its rules + counters (FK cascade), revokes // the OAuth session for its DID, and clears session.did if we just deleted // the active one. app.post('/jobs/:id/delete', async (c) => { const s = getSession(c, SESSION_SECRET); if (!s?.discord?.userId) return c.redirect('/'); const account = getUserByDiscord.get(s.discord.userId); if (!account) return c.redirect('/'); const id = Number(c.req.param('id')); if (!Number.isInteger(id)) return errorPage(c, 'Bad job id.'); const job = getJobById.get(id); if (!job || job.user_id !== account.id) return errorPage(c, 'Job not found.', 404); try { await oauth?.revoke?.(job.did); } catch {} try { await oauthStores.session.del(job.did); } catch {} deleteJob(job.id, account.id); refreshActiveGuilds(); const next = (s.did === job.did) ? { discord: s.discord } : { discord: s.discord, did: s.did }; setSession(c, next, SESSION_SECRET, SESSION_MAX_AGE_LONG); return c.redirect('/'); }); app.get('/api/semble/collections', async (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.json({ error: 'not linked' }, 401); try { const collections = await listSembleCollections(ctx.job.did); return c.json({ collections }); } catch (err) { console.error('semble collections fetch failed', err); return c.json({ error: err.message }, 502); } }); app.get('/client-metadata.json', (c) => oauth ? c.json(oauth.clientMetadata) : c.notFound() ); app.get('/jwks.json', (c) => oauth ? c.json(oauth.jwks) : c.notFound() ); app.get('/discord/start', (c) => { const discordState = randomBytes(16).toString('hex'); setSession(c, { discordState }, SESSION_SECRET); return c.redirect(discord.authUrl({ state: discordState, redirectUri: DISCORD_REDIRECT })); }); app.get('/discord/callback', async (c) => { const s = getSession(c, SESSION_SECRET); const code = c.req.query('code'); const state = c.req.query('state'); if (!code) return errorPage(c, 'Missing Discord authorization code.'); if (!s?.discordState || state !== s.discordState) { return errorPage(c, 'Discord state mismatch — possible CSRF.'); } let user, guildsRaw; try { const token = await discord.exchangeCode({ code, redirectUri: DISCORD_REDIRECT }); user = await discord.getUser(token.access_token); guildsRaw = await discord.getGuilds(token.access_token); } catch (err) { console.error('discord oauth failed', err); return errorPage(c, 'Could not verify Discord account.'); } // Persist the user's full guild ID list; we intersect with the bot's live // cache on each page render so newly-shared servers (bot was added later) // surface without requiring another OAuth round-trip. Capped to avoid // overflowing the cookie size limit on power users. const guildIds = guildsRaw.map(g => g.id).slice(0, 250); upsertUserByDiscord({ discordId: user.id }); setSession(c, { discord: { userId: user.id, username: user.username, globalName: user.global_name ?? null, avatar: user.avatar ?? null, guildIds, }, }, SESSION_SECRET, SESSION_MAX_AGE_LONG); return c.redirect('/'); }); const normalizeHandle = (raw) => { let h = raw.trim(); if (h.startsWith('@')) h = h.slice(1); if (h.includes('/')) { try { const u = new URL(h.includes('://') ? h : `https://${h}`); if (u.pathname.startsWith('/profile/')) { h = decodeURIComponent(u.pathname.slice('/profile/'.length).split('/')[0]); if (h.startsWith('@')) h = h.slice(1); } } catch {} } if (h.endsWith('.')) h = h.slice(0, -1); return h; }; app.get('/login', async (c) => { if (!oauth) return errorPage(c, 'atproto OAuth is disabled in loopback dev mode. Set PUBLIC_URL to a tunneled HTTPS URL or deploy.', 503); const s = getSession(c, SESSION_SECRET); if (!s?.discord) return c.redirect('/'); const raw = c.req.query('handle'); if (!raw) return errorPage(c, 'Missing handle.'); const handle = normalizeHandle(raw); const state = randomBytes(16).toString('hex'); try { const url = await oauth.authorize(handle, { state }); return c.redirect(url.toString()); } catch (err) { console.error('oauth authorize failed', err); return errorPage(c, `Could not resolve “${esc(handle)}”. Enter a handle like you.bsky.social or a DID.`); } }); app.get('/oauth/callback', async (c) => { if (!oauth) return errorPage(c, 'atproto OAuth is disabled in loopback dev mode.', 503); const s = getSession(c, SESSION_SECRET); if (!s?.discord) { clearSession(c); return errorPage(c, 'Missing flow state. Start over.'); } let session; try { const params = new URLSearchParams(c.req.url.split('?')[1]); ({ session } = await oauth.callback(params)); } catch (err) { console.error('atproto oauth callback failed', err); clearSession(c); return errorPage(c, 'Sign-in with Atmosphere account failed. Try again.'); } const account = upsertUserByDiscord({ discordId: s.discord.userId }); const job = upsertJob({ userId: account.id, did: session.did }); const profile = await resolveDidProfile(session.did).catch(() => null); if (profile) setJobProfile(job.id, profile.handle, profile.avatar); setSession(c, { discord: s.discord, did: session.did, }, SESSION_SECRET, SESSION_MAX_AGE_LONG); return c.redirect('/'); }); // ───── Rules mutations (rendered inline on /) ───────────────────────────── app.get('/rules', (c) => c.redirect('/')); // Form parsing + validation shared by /rules (insert) and /rules/:id/edit // (update). Returns either { ok: true, fields } where `fields` is the row // payload for insertRule/updateRuleForUser, or { ok: false, status, error } // describing why we rejected the submission. async function parseRuleForm(form, session) { const guildIdRaw = (form.get('guild_id') ?? '').toString().trim(); const channelIdRaw = (form.get('channel_id') ?? '').toString().trim(); const authorMode = (form.get('author_mode') ?? 'self').toString(); const authorIdRaw = (form.get('author_id') ?? '').toString().trim(); const mode = (form.get('mode') ?? 'urls').toString(); const matchKindRaw = (form.get('match_kind') ?? '').toString(); const matchValueRaw = (form.get('match_value') ?? '').toString(); const destKind = (form.get('destination_kind') ?? 'stdout').toString(); const destConfigRaw = (form.get('destination_config') ?? '').toString().trim(); if (!['urls', 'content'].includes(mode)) { return { ok: false, status: 400, error: `Invalid extract mode: ${esc(mode)}.` }; } let match_kind = null, match_value = null; if (matchKindRaw) { if (!matchValueRaw.trim()) { return { ok: false, status: 400, error: 'Match pattern is required when a content filter is selected.' }; } const v = validateMatchPattern(matchKindRaw, matchValueRaw); if (!v.ok) return { ok: false, status: 400, error: esc(v.reason) }; match_kind = matchKindRaw; match_value = matchValueRaw; } let author_id; if (authorMode === 'self') author_id = 'self'; else if (authorMode === 'any') author_id = null; else if (authorMode === 'id') { const trimmed = authorIdRaw.replace(/^@/, '').trim(); if (!trimmed) return { ok: false, status: 400, error: 'Specify a user (numeric ID or @username).' }; if (/^\d+$/.test(trimmed)) { author_id = trimmed; } else { const guildForLookup = guildIdRaw; if (!guildForLookup) { return { ok: false, status: 400, error: 'Pick a server before entering a username (we resolve usernames within the selected server).' }; } let matches; try { matches = await searchGuildMembers(guildForLookup, trimmed); } catch (err) { console.error('member search failed', err); return { ok: false, status: 502, error: `Couldn't reach Discord to resolve username "${esc(trimmed)}".` }; } if (!Array.isArray(matches) || matches.length === 0) { return { ok: false, status: 400, error: `No member matching "${esc(trimmed)}" in that server. Try the exact username (Discord username, not display name).` }; } const exact = matches.find(m => m?.user?.username?.toLowerCase() === trimmed.toLowerCase()); author_id = (exact ?? matches[0]).user.id; } } else { return { ok: false, status: 400, error: 'Invalid author mode.' }; } const guild_id = guildIdRaw || null; if (!guild_id) { return { ok: false, status: 400, error: 'Every rule must specify a server.' }; } const sharedSet = new Set(sharedGuildIdsFor(session.discord.guildIds)); if (!sharedSet.has(guild_id)) { return { ok: false, status: 403, error: 'You must be a member of that server and the bot must be in it. Re-link Discord if your guild list is stale.' }; } let channel_id = null; if (channelIdRaw) { if (/^\d+$/.test(channelIdRaw)) { channel_id = channelIdRaw; } else { const name = channelIdRaw.replace(/^#/, '').trim().toLowerCase(); if (name) { const guild = botClient.isReady?.() ? botClient.guilds.cache.get(guild_id) : null; if (!guild) { return { ok: false, status: 502, error: 'Could not access that server (the bot may not be in it yet).' }; } const channel = guild.channels.cache.find(ch => ch?.isTextBased?.() && ch.name?.toLowerCase() === name ); if (!channel) { return { ok: false, status: 400, error: `No text channel named "#${esc(name)}" in that server.` }; } channel_id = channel.id; } } } if (!KNOWN_DESTINATIONS.includes(destKind)) { return { ok: false, status: 400, error: `Unknown destination kind: ${esc(destKind)}` }; } let destination_config = null; if (destKind === 'bookmark') { if (mode !== 'urls') { return { ok: false, status: 400, error: 'The Bookmark destination only supports URL extraction mode (it writes one bookmark per URL).' }; } const knownLexicons = new Set((metaFor('bookmark')?.lexicons ?? []).map(l => l.id)); const picked = form.getAll('bookmark_lexicon').map(v => v.toString()).filter(id => knownLexicons.has(id)); if (picked.length === 0) { return { ok: false, status: 400, error: 'Pick at least one bookmark lexicon to write to.' }; } const lexiconConfig = {}; if (picked.includes('semble-card')) { const collectionUri = (form.get('semble_collection_uri') ?? '').toString().trim(); if (collectionUri) { if (!/^at:\/\/[^/]+\/network\.cosmik\.collection\/[^/]+$/.test(collectionUri)) { return { ok: false, status: 400, error: 'Semble collection URI looks malformed.' }; } lexiconConfig['semble-card'] = { collectionUri }; } } destination_config = JSON.stringify({ lexicons: picked, lexiconConfig }); } else if (destKind === 'atproto-record') { if (!destConfigRaw) { return { ok: false, status: 400, error: 'atproto-record requires a config (e.g. { "collection": "com.example.bookmark" }).' }; } let parsed; try { parsed = JSON.parse(destConfigRaw); } catch { return { ok: false, status: 400, error: 'Destination config must be valid JSON.' }; } if (!parsed?.collection || typeof parsed.collection !== 'string') { return { ok: false, status: 400, error: 'atproto-record requires a "collection" string (an NSID) in the config.' }; } if (!/^[a-z][a-z0-9]*(\.[a-z0-9-]+)+$/i.test(parsed.collection)) { return { ok: false, status: 400, error: 'collection must look like an NSID (e.g. "com.example.bookmark").' }; } destination_config = destConfigRaw; } return { ok: true, fields: { guild_id, channel_id, author_id, mode, match_kind, match_value, destination_kind: destKind, destination_config, }, }; } app.post('/rules', async (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.redirect('/'); const { job, session } = ctx; const form = await c.req.formData(); const parsed = await parseRuleForm(form, session); if (!parsed.ok) return errorPage(c, parsed.error, parsed.status); insertRule({ job_id: job.id, ...parsed.fields, enabled: 1 }); refreshActiveGuilds(); return c.redirect('/'); }); app.post('/rules/:id/delete', (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.redirect('/'); const id = Number(c.req.param('id')); if (!Number.isInteger(id)) return errorPage(c, 'Bad rule id.'); deleteRuleForJob.run(id, ctx.job.id); refreshActiveGuilds(); return c.redirect('/'); }); app.post('/rules/:id/toggle', (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.redirect('/'); const id = Number(c.req.param('id')); if (!Number.isInteger(id)) return errorPage(c, 'Bad rule id.'); toggleRuleForJob.run(id, ctx.job.id); refreshActiveGuilds(); return c.redirect('/'); }); app.get('/rules/:id/edit', (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.redirect('/'); const id = Number(c.req.param('id')); if (!Number.isInteger(id)) return errorPage(c, 'Bad rule id.'); const rule = getRuleForJob.get(id, ctx.job.id); if (!rule) return errorPage(c, 'Rule not found.', 404); const userGuildIds = ctx.session.discord.guildIds ?? []; const guilds = botGuildsForUser(sharedGuildIdsFor(userGuildIds)); return c.html(layout(`Edit rule #${rule.id}`, `

← Back to rules

Edit rule #${rule.id}

${renderRuleForm({ action: `/rules/${rule.id}/edit`, submitLabel: 'Save changes', defaults: ruleToFormDefaults(rule), guilds, cancelHref: '/', })} ${canUseBackfill(ctx.user) ? `

Backfill

Replay this rule over a channel's history. Save any changes above first so the backfill uses the rule's current filters and destination.

` : ''} `)); }); app.post('/rules/:id/edit', async (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.redirect('/'); const id = Number(c.req.param('id')); if (!Number.isInteger(id)) return errorPage(c, 'Bad rule id.'); const existing = getRuleForJob.get(id, ctx.job.id); if (!existing) return errorPage(c, 'Rule not found.', 404); const form = await c.req.formData(); const parsed = await parseRuleForm(form, ctx.session); if (!parsed.ok) return errorPage(c, parsed.error, parsed.status); const ok = updateRuleForJob({ id: existing.id, job_id: ctx.job.id, ...parsed.fields }); if (!ok) return errorPage(c, 'Update failed — rule may have been deleted in another tab.', 409); refreshActiveGuilds(); return c.redirect('/'); }); // ───── Backfill ──────────────────────────────────────────────────────────── // Backfill runs each historical Discord message through the same pipeline as // live MessageCreate. PDS records use deterministic rkeys (see destinations/ // bookmark.js) so a replay overwrites instead of duplicating. // // Gated to a single allowlisted Discord account via env until we've shaken // out the worst-case behaviors (huge channels, rate limits, billing-meter // surprises). Unset → backfill is disabled for everyone. const BACKFILL_ALLOWED_DISCORD_ID = process.env.BACKFILL_ALLOWED_DISCORD_ID ?? null; function canUseBackfill(user) { return !!BACKFILL_ALLOWED_DISCORD_ID && user?.discord_id === BACKFILL_ALLOWED_DISCORD_ID; } function listTextChannelsForGuild(guildId) { if (!botClient.isReady?.()) return []; const guild = botClient.guilds.cache.get(guildId); if (!guild) return []; return [...guild.channels.cache.values()] .filter(ch => ch?.isTextBased?.() && typeof ch.name === 'string') .map(ch => ({ id: ch.id, name: ch.name })) .sort((a, b) => a.name.localeCompare(b.name)); } // Discord snowflakes embed their creation time in the high 42 bits. A channel // can't contain messages older than itself, so this is the true floor of a // backfill's content window — derivable with no API call. const DISCORD_EPOCH_MS = 1420070400000; function channelCreatedSec(channelId) { try { const ms = Number(BigInt(channelId) >> 22n) + DISCORD_EPOCH_MS; return Number.isFinite(ms) ? Math.floor(ms / 1000) : null; } catch { return null; } } function jobPercent(job) { if (!job) return 0; if (job.status === 'done') return 100; if (!job.cursor_ts) return 0; // Measure progress against the span that can actually hold messages, not the // raw since_ts. With an "Everything" window (since_ts ~10y ago) but a channel // created last year, the cursor blows through all real content while covering // only a few percent of the calendar window — pinning the bar near 0 for the // whole run. Clamping the floor to the channel's creation time fixes that. const created = channelCreatedSec(job.channel_id); const since = created != null ? Math.max(job.since_ts, created) : job.since_ts; const span = job.until_ts - since; if (span <= 0) return 100; const walked = job.until_ts - job.cursor_ts; return Math.max(0, Math.min(100, Math.round((walked / span) * 100))); } // Latest backfill job per channel for a rule. listBackfillJobsForRule is // ordered newest-first, so the first row seen for a channel_id is its current // state — older re-runs of the same channel are ignored. function latestBackfillJobByChannel(ruleId) { const map = new Map(); for (const j of listBackfillJobsForRule.all(ruleId)) { if (!map.has(j.channel_id)) map.set(j.channel_id, j); } return map; } // Roll a set of per-channel jobs up into the numbers the batch view shows. function summarizeBackfill(jobs) { const s = { total: jobs.length, done: 0, running: 0, pending: 0, error: 0, cancelled: 0, scanned: 0, records_written: 0, error_count: 0, active: false, }; for (const j of jobs) { if (j.status in s) s[j.status] += 1; s.scanned += j.scanned ?? 0; s.records_written += j.records_written ?? 0; s.error_count += j.error_count ?? 0; if (j.status === 'pending' || j.status === 'running') s.active = true; } return s; } app.get('/rules/:id/backfill', (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.redirect('/'); if (!canUseBackfill(ctx.user)) { return errorPage(c, 'Backfill is currently restricted to a single allowlisted account while the feature is being shaken out.', 403); } const id = Number(c.req.param('id')); if (!Number.isInteger(id)) return errorPage(c, 'Bad rule id.'); const rule = getRuleForJob.get(id, ctx.job.id); if (!rule) return errorPage(c, 'Rule not found.', 404); if (!rule.guild_id) { return errorPage(c, 'Backfill needs a rule scoped to a specific server. Edit the rule or create a new one with a server selected.'); } const channels = listTextChannelsForGuild(rule.guild_id); const guild = botClient.isReady?.() ? botClient.guilds.cache.get(rule.guild_id) : null; const guildLabel = guild?.name ?? rule.guild_id; const header = `

← Back to rules

Backfill rule #${rule.id}

Server: ${esc(guildLabel)} · Extract: ${esc(rule.mode)} · Destination: ${esc(rule.destination_kind)}

`; const daysSelect = (disabled) => ` `; const replaySafetyNote = `

Replays are safe: bookmark and atproto-record destinations use deterministic record keys, so re-running a backfill over the same range overwrites in place rather than creating duplicates.

`; // ── Wildcard (server-wide) rule: channel-centric batch view ────────────── // The rule matches every channel, so backfill can fan out one job per // channel. The worker drains them FIFO; write-pacing is process-global so // the queue stays under the PDS rate limit across jobs. if (!rule.channel_id) { const byChannel = latestBackfillJobByChannel(rule.id); const jobs = [...byChannel.values()]; const summary = summarizeBackfill(jobs); // One row per visible channel, plus any channel that has a job but is no // longer visible to the bot (left server / lost read access). const rowChannels = [ ...channels.map(ch => ({ id: ch.id, name: ch.name })), ...[...byChannel.keys()] .filter(chId => !channels.some(ch => ch.id === chId)) .map(chId => ({ id: chId, name: null })), ]; const channelRows = rowChannels.map(ch => { const j = byChannel.get(ch.id); const label = ch.name ? `#${esc(ch.name)}` : `${esc(ch.id)} (not visible)`; const statusCell = j ? `${esc(j.status)}${j.error ? ` — ${esc(j.error)}` : ''}` : 'never'; const pct = j ? jobPercent(j) : 0; return ` ${label} ${statusCell} ${pct}% ${j?.records_written ?? 0} ${j?.error_count ?? 0} `; }).join(''); const overallPct = summary.total ? Math.round((summary.done / summary.total) * 100) : 0; const noChannels = channels.length === 0; return c.html(layout('Backfill rule', ` ${header}

Channels: ${summary.done}/${summary.total} complete · running: ${summary.running} · queued: ${summary.pending} · failed: ${summary.error}

records written: ${summary.records_written} · failed writes: ${summary.error_count}

${summary.active ? `
` : ''}
${summary.total === 0 ? '

No channels backfilled yet.

' : ` ${channelRows}
ChannelStatusProgressWrittenFailed
`} ${summary.active ? ` ` : ''}

Backfill every channel

Queues a backfill for all ${channels.length} channel${channels.length === 1 ? '' : 's'} the bot can read in this server, processed one at a time. Channels already queued or running are skipped, so it's safe to re-run.

${noChannels ? '

No channels visible to the bot in this server. Make sure the bot has read access.

' : `

${daysSelect(false)}

`}

Backfill a single channel

${noChannels ? '' : `

${daysSelect(false)}

`} ${replaySafetyNote} `)); } // ── Channel-scoped rule: single-channel view ───────────────────────────── const ruleChannel = channels.find(ch => ch.id === rule.channel_id); const active = getActiveBackfillJobForRule.get(rule.id); const latest = active ?? getLatestBackfillJobForRule.get(rule.id); const channelPicker = `

Channel: #${esc(ruleChannel?.name ?? rule.channel_id)} (from the rule)

`; let latestSamples = null; if (latest?.error_samples) { try { latestSamples = JSON.parse(latest.error_samples); } catch { latestSamples = null; } } const samplesBlock = latestSamples && latestSamples.length > 0 ? `
${latestSamples.length} distinct write-error sample${latestSamples.length === 1 ? '' : 's'}
${esc(JSON.stringify(latestSamples, null, 2))}
` : ''; const statusBlock = latest ? `

Latest job: ${esc(latest.status)} ${latest.error ? ` — ${esc(latest.error)}` : ''}

${jobPercent(latest)}% · messages processed: ${latest.scanned} · records written: ${latest.records_written ?? 0} · failed writes: ${latest.error_count ?? 0} ${latest.cursor_ts ? `· at ${esc(new Date(latest.cursor_ts * 1000).toISOString().slice(0,16).replace('T',' '))} UTC` : ''}

${samplesBlock} ${active ? `
` : ''}
${active ? ` ` : ''} ` : '

No backfill has been run for this rule yet.

'; const formDisabled = active ? 'disabled' : ''; return c.html(layout('Backfill rule', `

← Back to rules

Backfill rule #${rule.id}

Server: ${esc(guildLabel)} · Extract: ${esc(rule.mode)} · Destination: ${esc(rule.destination_kind)}

${statusBlock}

Start a new backfill

${active ? '

This form re-enables once the current backfill finishes (or you cancel it above).

' : ''}
${channelPicker}

The bot reads pages of 100 messages with a 1s pause between pages, so a year of an active channel can take a while. Progress updates live above.

Replays are safe: bookmark and atproto-record destinations use deterministic record keys, so re-running a backfill over the same range overwrites in place rather than creating duplicates.

`)); }); app.post('/rules/:id/backfill', async (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.redirect('/'); if (!canUseBackfill(ctx.user)) { return errorPage(c, 'Backfill is currently restricted to a single allowlisted account.', 403); } const id = Number(c.req.param('id')); if (!Number.isInteger(id)) return errorPage(c, 'Bad rule id.'); const rule = getRuleForJob.get(id, ctx.job.id); if (!rule) return errorPage(c, 'Rule not found.', 404); if (!rule.guild_id) return errorPage(c, 'Backfill requires a server-scoped rule.'); const form = await c.req.formData(); const days = Math.max(1, Math.min(3650, Number(form.get('days') ?? 7))); const channelIdRaw = (form.get('channel_id') ?? '').toString().trim(); const channelId = rule.channel_id ?? channelIdRaw; if (!channelId) return errorPage(c, 'Pick a channel to backfill.'); // The bot must actually be able to read the channel — fail fast rather than // letting the worker fail at messages.fetch time. const channels = listTextChannelsForGuild(rule.guild_id); if (!channels.some(ch => ch.id === channelId)) { return errorPage(c, 'Channel not visible to the bot. Make sure the bot has read access to it.'); } const existing = getActiveBackfillJobForRuleChannel.get(rule.id, channelId); if (existing) { return errorPage(c, 'A backfill job is already pending or running for this channel.'); } const now = Math.floor(Date.now() / 1000); const since = now - days * 24 * 60 * 60; insertBackfillJob({ rule_id: rule.id, channel_id: channelId, since_ts: since, until_ts: now, }); return c.redirect(`/rules/${rule.id}/backfill`); }); // Fan-out: enqueue one backfill job per readable channel in the rule's server. // Only meaningful for a wildcard (server-wide) rule — a channel-scoped rule // already targets exactly one channel. The worker drains the queue FIFO. app.post('/rules/:id/backfill/all', async (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.redirect('/'); if (!canUseBackfill(ctx.user)) { return errorPage(c, 'Backfill is currently restricted to a single allowlisted account.', 403); } const id = Number(c.req.param('id')); if (!Number.isInteger(id)) return errorPage(c, 'Bad rule id.'); const rule = getRuleForJob.get(id, ctx.job.id); if (!rule) return errorPage(c, 'Rule not found.', 404); if (!rule.guild_id) return errorPage(c, 'Backfill requires a server-scoped rule.'); if (rule.channel_id) { return errorPage(c, 'This rule targets a single channel — use the single-channel backfill.'); } const form = await c.req.formData(); const days = Math.max(1, Math.min(3650, Number(form.get('days') ?? 7))); const channels = listTextChannelsForGuild(rule.guild_id); if (channels.length === 0) { return errorPage(c, 'No channels visible to the bot in this server. Make sure the bot has read access.'); } const now = Math.floor(Date.now() / 1000); const since = now - days * 24 * 60 * 60; for (const ch of channels) { // Skip channels that already have a pending/running job so re-running the // fan-out tops up newly-added channels without double-queuing. if (getActiveBackfillJobForRuleChannel.get(rule.id, ch.id)) continue; insertBackfillJob({ rule_id: rule.id, channel_id: ch.id, since_ts: since, until_ts: now }); } return c.redirect(`/rules/${rule.id}/backfill`); }); app.get('/api/rules/:id/backfill', (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.json({ error: 'unauthorized' }, 401); if (!canUseBackfill(ctx.user)) return c.json({ error: 'forbidden' }, 403); const id = Number(c.req.param('id')); if (!Number.isInteger(id)) return c.json({ error: 'bad id' }, 400); const rule = getRuleForJob.get(id, ctx.job.id); if (!rule) return c.json({ error: 'not found' }, 404); // Wildcard rule → aggregate the per-channel fan-out for the batch view. if (!rule.channel_id) { const jobs = [...latestBackfillJobByChannel(rule.id).values()]; const s = summarizeBackfill(jobs); return c.json({ batch: true, ...s }); } const job = getActiveBackfillJobForRule.get(rule.id) ?? getLatestBackfillJobForRule.get(rule.id); if (!job) return c.json(null); let error_samples = null; if (job.error_samples) { try { error_samples = JSON.parse(job.error_samples); } catch { error_samples = null; } } return c.json({ id: job.id, status: job.status, scanned: job.scanned, dispatched: job.dispatched, records_written: job.records_written ?? 0, error_count: job.error_count ?? 0, error_samples, cursor_ts: job.cursor_ts, since_ts: job.since_ts, until_ts: job.until_ts, error: job.error, percent: jobPercent(job), }); }); app.post('/rules/:id/backfill/cancel', (c) => { const ctx = requireActiveJob(c); if (!ctx || !ctx.job) return c.redirect('/'); if (!canUseBackfill(ctx.user)) { return errorPage(c, 'Backfill is currently restricted to a single allowlisted account.', 403); } const id = Number(c.req.param('id')); if (!Number.isInteger(id)) return errorPage(c, 'Bad rule id.'); const rule = getRuleForJob.get(id, ctx.job.id); if (!rule) return errorPage(c, 'Rule not found.', 404); // Cancel every non-terminal job for the rule — covers both a single job and // a fan-out batch. The running one stops at its next page boundary; pending // ones are flipped to cancelled before the worker ever claims them. const cancellable = listBackfillJobsForRule.all(rule.id) .filter(j => j.status === 'pending' || j.status === 'running'); if (cancellable.length === 0) { return errorPage(c, 'No active backfill job to cancel for this rule.'); } for (const j of cancellable) cancelBackfillJob(j.id); return c.redirect(`/rules/${rule.id}/backfill`); }); // ───── Stripe ────────────────────────────────────────────────────────────── app.post('/subscribe', async (c) => { const ctx = requireActiveJob(c); if (!ctx) return c.redirect('/'); if (!stripe) return errorPage(c, 'Subscriptions are not configured on this instance.', 503); const priceId = process.env.STRIPE_PRICE_ID; if (!priceId) return errorPage(c, 'Subscriptions are not configured on this instance.', 503); // Already-active users with a Stripe customer get routed to the portal; // otherwise clicking Subscribe twice creates a second subscription billed // independently. if (ctx.user.active && ctx.user.stripe_customer_id) { return c.redirect('/portal-redirect'); } try { const session = await stripe.checkout.sessions.create({ mode: 'subscription', line_items: [{ price: priceId, quantity: 1 }], client_reference_id: String(ctx.user.id), customer: ctx.user.stripe_customer_id || undefined, success_url: `${PUBLIC_URL}/?subscribed=1`, cancel_url: `${PUBLIC_URL}/`, allow_promotion_codes: true, }); return c.redirect(session.url); } catch (err) { console.error('checkout session create failed', err); return errorPage(c, 'Could not start subscription.', 500); } }); // GET shim so the /subscribe POST handler can redirect already-active users to // the portal (which is itself a POST endpoint). app.get('/portal-redirect', (c) => c.html( `Opening portal…
` )); app.post('/portal', async (c) => { const ctx = requireActiveJob(c); if (!ctx) return c.redirect('/'); if (!ctx.user.stripe_customer_id) return c.redirect('/'); if (!stripe) return errorPage(c, 'Subscriptions are not configured on this instance.', 503); try { const session = await stripe.billingPortal.sessions.create({ customer: ctx.user.stripe_customer_id, return_url: `${PUBLIC_URL}/`, }); return c.redirect(session.url); } catch (err) { console.error('portal session create failed', err); return errorPage(c, 'Could not open the customer portal.', 500); } }); app.post('/webhooks/stripe', async (c) => { if (!stripe) return c.text('not configured', 503); const secret = process.env.STRIPE_WEBHOOK_SECRET; if (!secret) return c.text('webhook secret not configured', 503); const sig = c.req.header('stripe-signature'); const body = await c.req.text(); let event; try { event = stripe.webhooks.constructEvent(body, sig, secret); } catch (err) { console.error('stripe webhook signature verification failed', err.message); return c.text('bad signature', 400); } // Idempotency: if we've already processed this event.id, ack and skip. // Stripe retries on any non-2xx and occasionally on success; without this, // any side effect added later would double-fire. if (!tryRecordWebhookEvent(event.id)) { return c.text('ok'); } try { switch (event.type) { case 'checkout.session.completed': { const s = event.data.object; const userId = Number(s.client_reference_id); const customerId = typeof s.customer === 'string' ? s.customer : s.customer?.id; if (Number.isInteger(userId) && customerId) { setUserSubscription(userId, customerId, 1); refreshActiveGuilds(); } break; } case 'customer.subscription.deleted': { // Subscription canceled. Mark inactive AND disable every rule the user // owns — re-subscribing flips active=1 but rules stay off so the user // re-enables them deliberately. const sub = event.data.object; const customerId = typeof sub.customer === 'string' ? sub.customer : sub.customer?.id; if (customerId) { const user = getUserByCustomer(customerId); if (user) deactivateUserAndDisableRules(user.id); refreshActiveGuilds(); } break; } case 'customer.subscription.updated': case 'customer.subscription.created': { const sub = event.data.object; const customerId = typeof sub.customer === 'string' ? sub.customer : sub.customer?.id; const active = ['active', 'trialing'].includes(sub.status); if (customerId) { const user = getUserByCustomer(customerId); if (user) { if (active) { // Re-activation. Don't touch rules — user re-enables manually. setActiveByCustomer(customerId, 1); } else if (user.active) { // Past-due / canceled / unpaid — same teardown as a delete. deactivateUserAndDisableRules(user.id); } refreshActiveGuilds(); } } break; } case 'customer.deleted': { // Stripe customer record itself was removed. Drop our reference, // deactivate, and disable rules. const cust = event.data.object; const customerId = cust.id; if (customerId) { const user = getUserByCustomer(customerId); if (user) { deactivateUserAndDisableRules(user.id); clearStripeCustomer(user.id); } refreshActiveGuilds(); } break; } default: break; } } catch (err) { console.error('stripe webhook handler failed', { type: event.type, err: err.message }); return c.text('handler error', 500); } return c.text('ok'); }); // ───── helpers ───────────────────────────────────────────────────────────── function ruleRow(r, guilds, backfillEnabled = false) { const guildLabel = r.guild_id ? (guilds.find(g => g.id === r.guild_id)?.name ?? r.guild_id) : '(any)'; let channelLabel = '(any)'; if (r.channel_id) { const guild = botClient.isReady?.() ? botClient.guilds.cache.get(r.guild_id) : null; const ch = guild?.channels?.cache?.get(r.channel_id); channelLabel = ch?.name ? `#${ch.name}` : r.channel_id; } const authorLabel = r.author_id === 'self' ? 'just me' : r.author_id === null ? '(anyone)' : r.author_id; const matchLabel = r.match_kind ? `${r.match_kind}: ${esc(r.match_value ?? '')}` : '(any)'; const modeLabel = r.mode === 'content' ? 'full content' : 'URLs only'; const destMeta = metaFor(r.destination_kind); const destName = destMeta?.name ?? r.destination_kind; let destDetail = ''; if (r.destination_config) { if (r.destination_kind === 'bookmark') { try { const cfg = JSON.parse(r.destination_config); const ids = cfg?.lexicons ?? []; const byId = new Map((destMeta?.lexicons ?? []).map(l => [l.id, l])); const labels = ids.map(id => { const nsid = byId.get(id)?.nsid ?? id; if (id === 'semble-card' && cfg?.lexiconConfig?.['semble-card']?.collectionUri) { const rkey = cfg.lexiconConfig['semble-card'].collectionUri.split('/').pop(); return `${esc(nsid)} → collection ${esc(rkey)}`; } return esc(nsid); }); if (labels.length) destDetail = ` → ${labels.join(', ')}`; } catch {} } else { destDetail = ` ${esc(r.destination_config)}`; } } const destLabel = `${esc(destName)}${destDetail}`; return ` ${esc(guildLabel)} ${esc(channelLabel)} ${esc(authorLabel)} ${matchLabel} ${esc(modeLabel)} ${destLabel} ${r.enabled ? 'on' : 'off'}
${backfillEnabled ? `` : ''}
`; } function layout(title, body) { return ` ${esc(title)} ${body}`; } function esc(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }[c])); }