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(`
${message}
`, 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.
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()}Route Discord messages — full content or just URLs — into atproto-shaped destinations.
${esc(label)}
${esc(job.did_handle ?? job.did)}
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 `Pass-through. Messages flow through disjecta and out to your destinations; we don't store them.
No rules yet — nothing is being captured. Add one below to start.
` : `| Server | Channel | Author | Match | Extract | Destination | State |
|---|
${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}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.
| Goal | Server | Channel | Author | Extract |
|---|---|---|---|---|
| Save URLs I post in #links to my PDS | my server | #links | just me | URLs only |
| Mirror every message in #announcements | my server | #announcements | anyone | full content |
| Capture Boris's posts anywhere in a server | my server | (any) | Boris's Discord ID | full content |
| Bookmark every URL anyone shares in a server | my server | (any) | anyone | URLs only |
| Log just my messages from one channel | my server | #my-channel | just me | full content |
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}`, `
Replay this rule over a channel's history. Save any changes above first so the backfill uses the rule's current filters and destination.
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 `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 ? ` ` : ''}No channels backfilled yet.
' : `| Channel | Status | Progress | Written | Failed |
|---|
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.
' : ``}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 ? `${esc(JSON.stringify(latestSamples, null, 2))}
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 ? ` ` : ''}No backfill has been run for this rule yet.
'; const formDisabled = active ? 'disabled' : ''; return c.html(layout('Backfill rule', `Server: ${esc(guildLabel)} · Extract: ${esc(rule.mode)} · Destination: ${esc(rule.destination_kind)}
${statusBlock}This form re-enables once the current backfill finishes (or you cancel it 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( `${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 `