Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(automation): reply to Instagram comments with a private message

spacesdrive43bc22eca62e
diff --git a/backend/container.ts b/backend/container.ts
index eea170a..7fc229b 100644
--- a/backend/container.ts
+++ b/backend/container.ts
@@ -4,6 +4,10 @@ import { createScheduledPostRepository } from './repositories/scheduledPostRepos
import { createTrackedPostRepository } from './repositories/trackedPostRepository.ts';
import { createSettingsRepository } from './repositories/settingsRepository.ts';
import { createEmailQuotaRepository } from './repositories/emailQuotaRepository.ts';
+import { createAuditRepository } from './repositories/auditRepository.ts';
+import { createAutomationRuleRepository } from './repositories/automationRuleRepository.ts';
+import { createAutomationCommentRepository } from './repositories/automationCommentRepository.ts';
+import { createAutomationAccountRepository } from './repositories/automationAccountRepository.ts';
import { createAccountService } from './services/accountService.ts';
import { createYouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';
import { createInstagramAnalyticsService } from './services/instagramAnalyticsService.ts';
@@ -17,6 +21,10 @@ import { createOverviewService } from './services/overviewService.ts';
import { createSettingsService } from './services/settingsService.ts';
import { createInstagramConnectService } from './services/instagramConnectService.ts';
import { createAuthEmailService } from './services/authEmailService.ts';
+import { createAutomationService } from './services/automationService.ts';
+import { createAutomationWebhookService } from './services/automationWebhookService.ts';
+import { createAutomationProcessor } from './services/automationProcessor.ts';
+import { createRetentionService } from './services/retentionService.ts';
import type { AccountService } from './services/accountService.ts';
import type { YouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';
import type { InstagramAnalyticsService } from './services/instagramAnalyticsService.ts';
@@ -30,6 +38,10 @@ import type { OverviewService } from './services/overviewService.ts';
import type { SettingsService } from './services/settingsService.ts';
import type { InstagramConnectService } from './services/instagramConnectService.ts';
import type { AuthEmailService } from './services/authEmailService.ts';
+import type { AutomationService } from './services/automationService.ts';
+import type { AutomationWebhookService } from './services/automationWebhookService.ts';
+import type { AutomationProcessor } from './services/automationProcessor.ts';
+import type { RetentionService } from './services/retentionService.ts';
import type { AppConfig } from './lib/config.ts';
import type { RequestContext } from './types/context.ts';
import type { Redis, SupabaseClient } from './types/app.ts';
@@ -55,6 +67,10 @@ export interface Services {
settings: SettingsService;
instagramConnect: InstagramConnectService;
authEmail: AuthEmailService;
+ automations: AutomationService;
+ automationWebhook: AutomationWebhookService;
+ automationProcessor: AutomationProcessor;
+ retention: RetentionService;
}
// the composition root: wires repositories into services for one request or one cron run; building them is cheap
@@ -64,9 +80,14 @@ export function createServices(clients: Clients, config: AppConfig, context: Req
const posts = createScheduledPostRepository(clients.supabase);
const tracked = createTrackedPostRepository(clients.supabase);
const settings = createSettingsRepository(clients.supabase);
+ const audit = createAuditRepository(clients.supabase);
+ const rules = createAutomationRuleRepository(clients.supabase);
+ const comments = createAutomationCommentRepository(clients.supabase);
+ const automationAccounts = createAutomationAccountRepository(clients.supabase);
+ const { automation } = config;
const scheduledPublisher = createScheduledPublisher({ accounts, posts, context });
return {
- accounts: createAccountService({ accounts, cache, config, context }),
+ accounts: createAccountService({ accounts, cache, audit, config, context }),
youtubeAnalytics: createYouTubeAnalyticsService({ accounts, cache, config, context }),
instagramAnalytics: createInstagramAnalyticsService({ accounts, cache, context }),
redditAnalytics: createRedditAnalyticsService({ accounts, cache, context }),
@@ -77,7 +98,11 @@ export function createServices(clients: Clients, config: AppConfig, context: Req
trackedContent: createTrackedContentService({ accounts, tracked, config, context }),
overview: createOverviewService({ accounts, tracked, cache, config }),
settings: createSettingsService({ settings, config }),
- instagramConnect: createInstagramConnectService({ accounts, config, context }),
+ instagramConnect: createInstagramConnectService({ accounts, audit, config, context }),
authEmail: createAuthEmailService({ quota: createEmailQuotaRepository(clients.rateLimitRedis), config, context }),
+ automations: createAutomationService({ accounts, rules, comments, automationAccounts, audit, automation, context }),
+ automationWebhook: createAutomationWebhookService({ rules, comments, automation, context }),
+ automationProcessor: createAutomationProcessor({ comments, automation, context }),
+ retention: createRetentionService({ comments, audit, context }),
};
}
diff --git a/backend/controllers/automationController.ts b/backend/controllers/automationController.ts
new file mode 100644
index 0000000..53ac872
--- /dev/null
+++ b/backend/controllers/automationController.ts
@@ -0,0 +1,68 @@
+import { controller, inBackground, pathParam, servicesFor } from './http.ts';
+import { jsonBody, queryParams } from '../middleware/validate.ts';
+import {
+ parseActivityQuery, parseAutomationAccount, parseAutomationRule, parseAutomationRuleUpdate, parseAutomationTest, parseStatsQuery,
+} from '../validators/automationValidators.ts';
+import type { SuccessMessageResponse } from '../../shared/types/domain.ts';
+import type {
+ AutomationAccountResponse, AutomationActivityItemResponse, AutomationActivityResponse, AutomationOverviewResponse,
+ AutomationRuleResponse, AutomationStatsResponse, AutomationTestResponse,
+} from '../../shared/types/automation.ts';
+
+export const getAutomations = controller.createHandlers(async c => {
+ const overview = await servicesFor(c).automations.overview(c.get('userId'));
+ return c.json({ success: true, ...overview } satisfies AutomationOverviewResponse);
+});
+
+export const createAutomationRule = controller.createHandlers(jsonBody(parseAutomationRule), async c => {
+ const rule = await servicesFor(c).automations.createRule(c.get('userId'), c.req.valid('json'));
+ return c.json({ success: true, rule } satisfies AutomationRuleResponse);
+});
+
+export const updateAutomationRule = controller.createHandlers(jsonBody(parseAutomationRuleUpdate), async c => {
+ const rule = await servicesFor(c).automations.updateRule(c.get('userId'), pathParam(c, 'id'), c.req.valid('json'));
+ return c.json({ success: true, rule } satisfies AutomationRuleResponse);
+});
+
+export const duplicateAutomationRule = controller.createHandlers(async c => {
+ const rule = await servicesFor(c).automations.duplicateRule(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true, rule } satisfies AutomationRuleResponse);
+});
+
+export const deleteAutomationRule = controller.createHandlers(async c => {
+ await servicesFor(c).automations.deleteRule(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true, message: 'Automation rule deleted' } satisfies SuccessMessageResponse);
+});
+
+// matches a sample comment against a draft rule; nothing is stored or sent
+export const testAutomationRule = controller.createHandlers(jsonBody(parseAutomationTest), async c => {
+ const result = servicesFor(c).automations.test(c.req.valid('json'));
+ return c.json({ success: true, ...result } satisfies AutomationTestResponse);
+});
+
+export const listAutomationActivity = controller.createHandlers(queryParams(parseActivityQuery), async c => {
+ const page = await servicesFor(c).automations.activity(c.get('userId'), c.req.valid('query'));
+ return c.json({ success: true, ...page } satisfies AutomationActivityResponse);
+});
+
+export const getAutomationStats = controller.createHandlers(queryParams(parseStatsQuery), async c => {
+ const period = await servicesFor(c).automations.stats(c.get('userId'), c.req.valid('query'));
+ return c.json({ success: true, ...period } satisfies AutomationStatsResponse);
+});
+
+// the item goes back in the queue and this request starts sending it, instead of waiting for the next sweep
+export const retryAutomationActivity = controller.createHandlers(async c => {
+ const item = await servicesFor(c).automations.retry(c.get('userId'), pathParam(c, 'id'));
+ inBackground(c, 'automation retry', services => services.automationProcessor.run({ ids: [item.id] }));
+ return c.json({ success: true, item } satisfies AutomationActivityItemResponse);
+});
+
+export const updateAutomationAccount = controller.createHandlers(jsonBody(parseAutomationAccount), async c => {
+ const account = await servicesFor(c).automations.setPaused(c.get('userId'), pathParam(c, 'accountId'), c.req.valid('json').paused);
+ return c.json({ success: true, account } satisfies AutomationAccountResponse);
+});
+
+export const subscribeAutomationAccount = controller.createHandlers(async c => {
+ const account = await servicesFor(c).automations.subscribe(c.get('userId'), pathParam(c, 'accountId'));
+ return c.json({ success: true, account } satisfies AutomationAccountResponse);
+});
diff --git a/backend/controllers/http.ts b/backend/controllers/http.ts
index 34d6d61..a2f8cfa 100644
--- a/backend/controllers/http.ts
+++ b/backend/controllers/http.ts
@@ -2,6 +2,7 @@ import { createFactory } from 'hono/factory';
import { createServices } from '../container.ts';
import { readConfig } from '../lib/config.ts';
import { ValidationError } from '../lib/errors.ts';
+import { createLogger, errorFields } from '../lib/logger.ts';
import { requestContextOf } from '../middleware/requestContext.ts';
import type { Services } from '../container.ts';
import type { AppContext, AppEnv } from '../types/app.ts';
@@ -21,3 +22,17 @@ export function servicesFor(c: AppContext): Services {
const clients = { supabase: c.get('supabase'), redis: c.get('redis'), rateLimitRedis: c.get('rateLimitRedis') };
return createServices(clients, readConfig(c.env), requestContextOf(c));
}
+
+// work after the response gets its own deadline: the request's signal ends with the response, and the Worker keeps
+// running waitUntil work for at most 30 seconds after it
+const BACKGROUND_DEADLINE_MS = 25_000;
+
+// runs work after the response is sent, with services of its own; a failure is logged, since nobody is waiting for it
+export function inBackground(c: AppContext, label: string, work: (services: Services) => Promise<unknown>): void {
+ const requestId = c.get('requestId');
+ const log = createLogger({ requestId, background: label });
+ const context = { requestId, signal: AbortSignal.timeout(BACKGROUND_DEADLINE_MS), log };
+ const clients = { supabase: c.get('supabase'), redis: c.get('redis'), rateLimitRedis: c.get('rateLimitRedis') };
+ const services = createServices(clients, readConfig(c.env), context);
+ c.executionCtx.waitUntil(work(services).catch(err => log.error(`${label} failed`, errorFields(err))));
+}
diff --git a/backend/controllers/instagramAuthController.ts b/backend/controllers/instagramAuthController.ts
index fce02f2..20f0ae2 100644
--- a/backend/controllers/instagramAuthController.ts
+++ b/backend/controllers/instagramAuthController.ts
@@ -24,7 +24,7 @@ export const handleInstagramCallback = controller.createHandlers(queryParams(par
const userId = await connect.userIdFromState(state);
if (!userId) return backToAccounts('ig_error=invalid_state');
const outcome = await connect.connect(userId, code);
- return backToAccounts(outcome === 'already_added' ? 'ig_error=already_added' : 'ig_connected=true');
+ return backToAccounts(outcome === 'reconnected' ? 'ig_connected=reconnected' : 'ig_connected=true');
} catch (err) {
requestLogger(c).error('instagram connection failed', errorFields(err));
return backToAccounts(`ig_error=${encodeURIComponent((err as Error).message.substring(0, 100))}`);
diff --git a/backend/controllers/instagramWebhookController.ts b/backend/controllers/instagramWebhookController.ts
new file mode 100644
index 0000000..2da4640
--- /dev/null
+++ b/backend/controllers/instagramWebhookController.ts
@@ -0,0 +1,18 @@
+import { controller, inBackground, servicesFor } from './http.ts';
+import { jsonBody, queryParams } from '../middleware/validate.ts';
+import { parseWebhookVerification } from '../validators/automationValidators.ts';
+import { parseInstagramWebhook } from '../validators/instagramWebhookValidators.ts';
+
+// called by Meta when the webhook is saved in its dashboard; the answer is the bare challenge, not JSON
+export const verifyInstagramWebhook = controller.createHandlers(queryParams(parseWebhookVerification), async c => {
+ const challenge = await servicesFor(c).automationWebhook.challengeAnswer(c.req.valid('query'));
+ return c.text(challenge);
+});
+
+// called by Meta, not a browser: verifyMetaWebhook has already checked the signature. The comments are stored before
+// the 200, so Meta keeps retrying for 36 hours if storing fails; the replies go out after the response
+export const receiveInstagramWebhook = controller.createHandlers(jsonBody(body => parseInstagramWebhook(body)), async c => {
+ const { queuedIds } = await servicesFor(c).automationWebhook.ingest(c.req.valid('json'));
+ if (queuedIds.length > 0) inBackground(c, 'automation replies', services => services.automationProcessor.run({ ids: queuedIds }));
+ return c.json({ success: true });
+});
diff --git a/backend/jobs/scheduled.ts b/backend/jobs/scheduled.ts
index b191a00..07e8505 100644
--- a/backend/jobs/scheduled.ts
+++ b/backend/jobs/scheduled.ts
@@ -3,12 +3,19 @@ import { getSupabase } from '../database/supabase.ts';
import { getRedis, getRateLimitRedis } from '../database/redis.ts';
import { readConfig } from '../lib/config.ts';
import { createLogger } from '../lib/logger.ts';
+import type { Services } from '../container.ts';
import type { Env } from '../types/env.ts';
import type { RequestContext } from '../types/context.ts';
// must match the crons in wrangler.toml character for character
-export const PUBLISH_DUE_POSTS_CRON = '*/15 * * * *';
-export const REFRESH_TOKENS_CRON = '0 0 * * *';
+export const EVERY_FIVE_MINUTES_CRON = '*/5 * * * *';
+export const DAILY_CRON = '0 0 * * *';
+
+// the Cloudflare account's five cron triggers are all in use, so one trigger carries two jobs: due posts on the
+// quarter hour, as before, and the comment reply queue on every run
+const PUBLISH_EVERY_MINUTES = 15;
+// a run that published has spent part of its 50 subrequests, so the replies wait five minutes for the next run
+const SWEEP_AFTER_QUIET_PUBLISH = 3;
// a cron run gets its own id and a deadline under the Worker's 15 minute limit for scheduled events
const CRON_DEADLINE_MS = 14 * 60 * 1000;
@@ -18,17 +25,36 @@ function cronContext(cron: string): RequestContext {
return { requestId, signal: AbortSignal.timeout(CRON_DEADLINE_MS), log: createLogger({ requestId, cron }) };
}
+export type CronPlan = 'sweep' | 'publish_then_sweep' | 'daily' | 'none';
+
+// which work a trigger firing at scheduledTime carries
+export function cronPlan(cron: string, scheduledTime: number): CronPlan {
+ if (cron === DAILY_CRON) return 'daily';
+ if (cron !== EVERY_FIVE_MINUTES_CRON) return 'none';
+ return new Date(scheduledTime).getUTCMinutes() % PUBLISH_EVERY_MINUTES === 0 ? 'publish_then_sweep' : 'sweep';
+}
+
+async function sweepReplies(services: Services, context: RequestContext, limit?: number): Promise<void> {
+ const run = await services.automationProcessor.run({ limit });
+ if (run.claimed > 0) context.log.info('automation sweep', { claimed: run.claimed, ...run.outcomes });
+}
+
// the cron entry point: the same services the API uses, built from the Worker env instead of a request
-export async function runScheduledJob(cron: string, env: Env): Promise<void> {
+export async function runScheduledJob(cron: string, env: Env, scheduledTime = Date.now()): Promise<void> {
const context = cronContext(cron);
const clients = { supabase: getSupabase(env), redis: getRedis(env), rateLimitRedis: getRateLimitRedis(env) };
const services = createServices(clients, readConfig(env), context);
- if (cron === PUBLISH_DUE_POSTS_CRON) {
+ const plan = cronPlan(cron, scheduledTime);
+ if (plan === 'sweep') {
+ await sweepReplies(services, context);
+ } else if (plan === 'publish_then_sweep') {
const run = await services.scheduledPublisher.publishDue();
context.log.info('scheduled publish run', { processed: run.processed, failed: run.errors.length });
- } else if (cron === REFRESH_TOKENS_CRON) {
+ if (run.processed === 0) await sweepReplies(services, context, SWEEP_AFTER_QUIET_PUBLISH);
+ } else if (plan === 'daily') {
await services.tokenRefresh.refreshExpiringInstagramTokens();
+ await services.retention.purge();
} else {
context.log.warn('no job for this cron', { cron });
}
diff --git a/backend/lib/automationDelivery.ts b/backend/lib/automationDelivery.ts
new file mode 100644
index 0000000..1454430
--- /dev/null
+++ b/backend/lib/automationDelivery.ts
@@ -0,0 +1,252 @@
+import type { AutomationAttemptOutcome, AutomationCommentStatus } from '../../shared/types/automation.ts';
+
+// Instagram refuses message text longer than 1,000 bytes
+export const MAX_MESSAGE_BYTES = 1000;
+
+// Instagram accepts a private reply for 7 days after the comment
+export const REPLY_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
+
+// a run holding a job longer than this has stopped: a sweep ends within 15 minutes and a webhook's work within 30 seconds
+export const CLAIM_LEASE_SECONDS = 20 * 60;
+
+// five tries over about half an hour give a passing Instagram problem time to clear without retrying forever
+export const MAX_SEND_ATTEMPTS = 5;
+
+// a reply held by a pause is looked at again on a later sweep, not every five minutes for a week
+const HOLD_RECHECK_MS = 15 * 60 * 1000;
+
+// backoff: 1, 2, 4, 8 minutes, then at most an hour, plus up to 30 seconds so retries of one burst spread out
+const BACKOFF_BASE_MS = 60 * 1000;
+const BACKOFF_MAX_MS = 60 * 60 * 1000;
+const BACKOFF_JITTER_MS = 30 * 1000;
+
+// the next sweep, when a run could not start the request
+const NOT_SENT_RETRY_MS = 5 * 60 * 1000;
+// used when Instagram limits the account without saying for how long
+const DEFAULT_COOLDOWN_MS = 15 * 60 * 1000;
+// code 368 is a temporary block for activity Instagram considers abusive, so the account rests for a day
+const BLOCKED_COOLDOWN_MS = 24 * 60 * 60 * 1000;
+
+// Graph API codes Meta documents for throttling: app, user, page and business use case limits
+const RATE_LIMIT_CODES = new Set([4, 17, 32, 613, 80002, 80006]);
+// unknown and service errors that Meta says to retry later
+const TRANSIENT_CODES = new Set([1, 2]);
+// the comment is deleted, too old, or its author does not accept messages
+const NOT_ELIGIBLE_CODES = new Set([551, 10903]);
+const NOT_ELIGIBLE_SUBCODES = new Set([2534014, 2534022, 2534025, 2018001]);
+// a second private reply to one comment
+const ALREADY_REPLIED_CODE = 10900;
+const ALREADY_REPLIED_SUBCODE = 2534023;
+// the token is invalid, or the account does not grant or allow messaging
+const NOT_AUTHORIZED_CODES = new Set([3, 190, 200]);
+const NOT_AUTHORIZED_SUBCODES = new Set([2534041]);
+
+export type SendErrorKind = 'rate_limited' | 'blocked' | 'transient' | 'already_replied' | 'not_authorized' | 'not_eligible' | 'refused';
+
+export interface GraphSendError {
+ code?: number;
+ subcode?: number;
+ httpStatus: number;
+ message: string;
+}
+
+// what one request to Instagram's messages endpoint came back as; ambiguous means it may have been delivered,
+// not_sent that the Worker refused to start the request
+export type SendResult =
+ | { kind: 'accepted'; messageId: string | null }
+ | ({ kind: 'error'; usageHeader: string | null } & GraphSendError)
+ | { kind: 'ambiguous'; message: string }
+ | { kind: 'not_sent'; message: string };
+
+// a claimed job, as the delivery rules need it; attempts already counts the send being settled
+export interface DeliveryJob {
+ attempts: number;
+ expiresAt: string;
+}
+
+// one finish_automation_send call
+export interface FinishPlan {
+ status: AutomationCommentStatus;
+ outcome: AutomationAttemptOutcome;
+ reason: string | null;
+ errorMessage: string | null;
+ messageId: string | null;
+ errorCode: number | null;
+ errorSubcode: number | null;
+ httpStatus: number | null;
+ nextAttemptAt: string | null;
+ cooldownUntil: string | null;
+ cooldownReason: string | null;
+ pauseReason: string | null;
+}
+
+// a job given back without sending: where it goes and why
+export interface ReleasePlan {
+ status: AutomationCommentStatus;
+ reason: string;
+ errorMessage: string | null;
+ nextAttemptAt: string | null;
+}
+
+export type ReserveOutcome =
+ | 'ok' | 'gone' | 'paused' | 'cooldown' | 'recipient_limit'
+ | 'rule_limit' | 'account_limit' | 'user_limit' | 'global_limit';
+
+export const SEND_ERROR_MESSAGES: Record<SendErrorKind, string> = {
+ rate_limited: 'Instagram is limiting replies from this account for now. The reply goes out after the cooldown.',
+ blocked: 'Instagram has temporarily blocked private replies from this account. Replies wait a day; check the account in the Instagram app.',
+ transient: 'Instagram had a temporary problem. The reply is tried again.',
+ already_replied: 'Instagram says this comment already has a private reply, so a second one was not sent.',
+ not_authorized: 'Instagram refused this account\'s permission to send messages. Replies are held: reconnect the account on the Accounts page, check that it allows access to messages in the Instagram app, then resume it.',
+ not_eligible: 'Instagram does not allow a private reply to this comment: it may be deleted or older than 7 days, or its author does not accept messages.',
+ refused: 'Instagram refused the reply.',
+};
+
+const LIMIT_MESSAGES: Record<Exclude<ReserveOutcome, 'ok' | 'gone' | 'paused' | 'recipient_limit'>, string> = {
+ cooldown: 'Waiting for Instagram\'s cooldown on this account to end.',
+ rule_limit: 'Waiting: this rule reached its hourly reply limit.',
+ account_limit: 'Waiting: this account reached its hourly reply limit.',
+ user_limit: 'Waiting: your accounts reached their combined hourly reply limit.',
+ global_limit: 'Waiting: this Twiligent instance reached its hourly reply limit.',
+};
+
+const EXPIRED_MESSAGE = 'The 7 days in which Instagram allows a private reply to this comment ran out.';
+
+export function composeReply(replyText: string, linkUrl: string | null): string {
+ return linkUrl ? `${replyText}\n\n${linkUrl}` : replyText;
+}
+
+export function messageBytes(message: string): number {
+ return new TextEncoder().encode(message).length;
+}
+
+export function expiresAtFor(notifiedAt: Date): string {
+ return new Date(notifiedAt.getTime() + REPLY_WINDOW_MS).toISOString();
+}
+
+export function classifySendError({ code, subcode, httpStatus }: GraphSendError): SendErrorKind {
+ if (httpStatus === 429 || (code !== undefined && RATE_LIMIT_CODES.has(code))) return 'rate_limited';
+ if (code === 368) return 'blocked';
+ if (code === ALREADY_REPLIED_CODE || subcode === ALREADY_REPLIED_SUBCODE) return 'already_replied';
+ if (subcode !== undefined && NOT_ELIGIBLE_SUBCODES.has(subcode)) return 'not_eligible';
+ if (code !== undefined && NOT_ELIGIBLE_CODES.has(code)) return 'not_eligible';
+ if (subcode !== undefined && NOT_AUTHORIZED_SUBCODES.has(subcode)) return 'not_authorized';
+ // a bare code 10 is a missing permission; with a subcode it is about the recipient, handled above
+ if ((code !== undefined && NOT_AUTHORIZED_CODES.has(code)) || (code === 10 && subcode === undefined)) return 'not_authorized';
+ if ((code !== undefined && TRANSIENT_CODES.has(code)) || httpStatus >= 500) return 'transient';
+ return 'refused';
+}
+
+// waits 1, 2, 4 and 8 minutes after the first four tries, never more than an hour
+export function retryDelayMs(attempts: number, random: () => number = Math.random): number {
+ const backoff = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** Math.max(0, attempts - 1));
+ return backoff + Math.floor(random() * BACKOFF_JITTER_MS);
+}
+
+// Meta's X-Business-Use-Case-Usage header says, per business, how many minutes until calls are allowed again
+export function cooldownFromUsage(usageHeader: string | null): number {
+ if (!usageHeader) return DEFAULT_COOLDOWN_MS;
+ try {
+ const usage = JSON.parse(usageHeader) as Record<string, { estimated_time_to_regain_access?: number }[]>;
+ const minutes = Object.values(usage).flat().map(entry => entry.estimated_time_to_regain_access ?? 0);
+ const longest = Math.max(0, ...minutes);
+ return longest > 0 ? Math.min(BLOCKED_COOLDOWN_MS, longest * 60 * 1000) : DEFAULT_COOLDOWN_MS;
+ } catch {
+ // a header Meta changed is not a reason to stop; the default cooldown still protects the account
+ return DEFAULT_COOLDOWN_MS;
+ }
+}
+
+function emptyPlan(): Omit<FinishPlan, 'status' | 'outcome'> {
+ return {
+ reason: null, errorMessage: null, messageId: null, errorCode: null, errorSubcode: null, httpStatus: null,
+ nextAttemptAt: null, cooldownUntil: null, cooldownReason: null, pauseReason: null,
+ };
+}
+
+// a wait that ends after Instagram's reply window would only fail, so the job expires instead
+function waitUntil(at: number, job: DeliveryJob, reason: string, message: string): Pick<FinishPlan, 'status' | 'reason' | 'errorMessage' | 'nextAttemptAt'> {
+ if (at >= Date.parse(job.expiresAt)) return { status: 'expired', reason: 'expired', errorMessage: EXPIRED_MESSAGE, nextAttemptAt: null };
+ return { status: 'retry_wait', reason, errorMessage: message, nextAttemptAt: new Date(at).toISOString() };
+}
+
+// what to record for the answer to one send
+export function finishPlan(result: SendResult, job: DeliveryJob, now: number, random: () => number = Math.random): FinishPlan {
+ if (result.kind === 'accepted') {
+ return { ...emptyPlan(), status: 'accepted', outcome: 'accepted', messageId: result.messageId };
+ }
+ if (result.kind === 'not_sent') {
+ return { ...emptyPlan(), ...waitUntil(now + NOT_SENT_RETRY_MS, job, 'not_sent', `The reply was not sent (${result.message}). It is tried again on the next run.`), outcome: 'rejected' };
+ }
+ if (result.kind === 'ambiguous') {
+ return {
+ ...emptyPlan(),
+ status: 'needs_review',
+ outcome: 'ambiguous',
+ reason: 'no_answer',
+ errorMessage: `Instagram did not answer (${result.message}), so the reply may or may not have been sent. Check the conversation on Instagram before you retry.`,
+ };
+ }
+
+ const kind = classifySendError(result);
+ const details = { ...emptyPlan(), errorCode: result.code ?? null, errorSubcode: result.subcode ?? null, httpStatus: result.httpStatus };
+ const message = kind === 'refused' ? `${SEND_ERROR_MESSAGES.refused} ${result.message}`.trim() : SEND_ERROR_MESSAGES[kind];
+
+ if (kind === 'rate_limited' || kind === 'blocked') {
+ const until = now + (kind === 'blocked' ? BLOCKED_COOLDOWN_MS : cooldownFromUsage(result.usageHeader));
+ const cooldownUntil = new Date(until).toISOString();
+ return {
+ ...details,
+ ...waitUntil(until, job, kind, message),
+ outcome: kind === 'rate_limited' ? 'rate_limited' : 'rejected',
+ cooldownUntil,
+ cooldownReason: SEND_ERROR_MESSAGES[kind],
+ };
+ }
+ if (kind === 'transient' && job.attempts < MAX_SEND_ATTEMPTS) {
+ return { ...details, ...waitUntil(now + retryDelayMs(job.attempts, random), job, kind, message), outcome: 'rejected' };
+ }
+ if (kind === 'already_replied') {
+ return { ...details, status: 'skipped', outcome: 'rejected', reason: kind, errorMessage: message };
+ }
+ if (kind === 'not_authorized') {
+ // the reply did not go out, so it waits with the account's other replies until the owner fixes the account
+ return {
+ ...details,
+ status: 'queued',
+ outcome: 'rejected',
+ reason: 'paused',
+ errorMessage: message,
+ nextAttemptAt: new Date(now + HOLD_RECHECK_MS).toISOString(),
+ pauseReason: SEND_ERROR_MESSAGES.not_authorized,
+ };
+ }
+ const finalMessage = kind === 'transient' ? `${message.replace(/ The reply is tried again\.$/, '')} Sending stopped after ${MAX_SEND_ATTEMPTS} tries.` : message;
+ return { ...details, status: 'failed', outcome: 'rejected', reason: kind, errorMessage: finalMessage };
+}
+
+// a claimed job that cannot be sent as it is, checked before any limit is spent; null means it may go ahead
+export function readinessPlan(job: { ruleEnabled: boolean; accessToken: string | null; expiresAt: string }, now: number): ReleasePlan | null {
+ if (now >= Date.parse(job.expiresAt)) return { status: 'expired', reason: 'expired', errorMessage: EXPIRED_MESSAGE, nextAttemptAt: null };
+ if (!job.ruleEnabled) {
+ return { status: 'skipped', reason: 'rule_disabled', errorMessage: 'The rule was turned off or removed before the reply was sent.', nextAttemptAt: null };
+ }
+ if (!job.accessToken) {
+ return { status: 'failed', reason: 'not_connected', errorMessage: 'The Instagram account has no access token. Reconnect it on the Accounts page, then retry.', nextAttemptAt: null };
+ }
+ return null;
+}
+
+// where a job goes when the reservation says no; null when it was sent (ok) or is no longer this run's (gone)
+export function releasePlan(outcome: ReserveOutcome, retryAt: string | null, job: DeliveryJob, now: number): ReleasePlan | null {
+ if (outcome === 'ok' || outcome === 'gone') return null;
+ if (outcome === 'paused') {
+ return { status: 'queued', reason: 'paused', errorMessage: 'Held while automation for this account is paused.', nextAttemptAt: new Date(now + HOLD_RECHECK_MS).toISOString() };
+ }
+ if (outcome === 'recipient_limit') {
+ return { status: 'skipped', reason: outcome, errorMessage: 'This person already received the most private replies allowed in a day, so no more were sent.', nextAttemptAt: null };
+ }
+ const at = retryAt ? Date.parse(retryAt) : now + DEFAULT_COOLDOWN_MS;
+ const { status, reason, errorMessage, nextAttemptAt } = waitUntil(at, job, outcome, LIMIT_MESSAGES[outcome]);
+ return { status, reason: reason ?? outcome, errorMessage, nextAttemptAt };
+}
diff --git a/backend/lib/automationMatching.ts b/backend/lib/automationMatching.ts
new file mode 100644
index 0000000..1b3cbae
--- /dev/null
+++ b/backend/lib/automationMatching.ts
@@ -0,0 +1,57 @@
+import type { AutomationMatchMode } from '../../shared/types/automation.ts';
+
+export interface MatchableRule {
+ keywords: string[];
+ matchMode: AutomationMatchMode;
+ caseSensitive: boolean;
+ mediaIds: string[];
+}
+
+export interface RuleMatch<T extends MatchableRule> {
+ rule: T;
+ keyword: string;
+}
+
+// what surrounds a comment's words without changing them: spaces, punctuation and emoji
+const EDGES = /^[\s\p{P}\p{S}]+|[\s\p{P}\p{S}]+$/gu;
+
+// NFKC folds look-alike characters such as full-width letters, so "GUIDE" matches GUIDE
+function normalize(text: string, caseSensitive: boolean): string {
+ const folded = text.normalize('NFKC').replace(/\s+/g, ' ').trim();
+ return caseSensitive ? folded : folded.toLowerCase();
+}
+
+function escapeRegExp(text: string): string {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+// the first keyword the comment carries, or null; contains means whole words only, so GUIDE never matches GUIDELINES
+export function matchedKeyword(comment: string, rule: MatchableRule): string | null {
+ const text = normalize(comment, rule.caseSensitive);
+ for (const keyword of rule.keywords) {
+ const wanted = normalize(keyword, rule.caseSensitive);
+ if (!wanted) continue;
+ if (rule.matchMode === 'exact') {
+ if (text.replace(EDGES, '') === wanted.replace(EDGES, '')) return keyword;
+ continue;
+ }
+ const wholeWord = new RegExp(`(?<![\\p{L}\\p{N}])${escapeRegExp(wanted)}(?![\\p{L}\\p{N}])`, 'u');
+ if (wholeWord.test(text)) return keyword;
+ }
+ return null;
+}
+
+export function coversMedia(rule: MatchableRule, mediaId: string | null): boolean {
+ return rule.mediaIds.length === 0 || (mediaId !== null && rule.mediaIds.includes(mediaId));
+}
+
+// a rule aimed at this post wins over a rule for every post; within each group the order given (oldest first) decides
+export function pickRule<T extends MatchableRule>(rules: T[], comment: string, mediaId: string | null): RuleMatch<T> | null {
+ const ordered = [...rules.filter(rule => rule.mediaIds.length > 0), ...rules.filter(rule => rule.mediaIds.length === 0)];
+ for (const rule of ordered) {
+ if (!coversMedia(rule, mediaId)) continue;
+ const keyword = matchedKeyword(comment, rule);
+ if (keyword !== null) return { rule, keyword };
+ }
+ return null;
+}
diff --git a/backend/lib/config.ts b/backend/lib/config.ts
index 7f992f3..f58feae 100644
--- a/backend/lib/config.ts
+++ b/backend/lib/config.ts
@@ -1,4 +1,5 @@
import type { Env } from '../types/env.ts';
+import type { AutomationLimits } from '../../shared/types/automation.ts';
const DEFAULT_BACKEND_URL = 'http://localhost:8787';
const DEFAULT_FRONTEND_URL = 'http://localhost:5173';
@@ -7,6 +8,12 @@ const LOCAL_HOSTNAMES = ['localhost', '127.0.0.1'];
const CALLBACK_PATH = '/api/auth/instagram/callback';
// Resend's free plan sends 100 emails a day
const DEFAULT_EMAIL_DAILY_LIMIT = 100;
+// Instagram allows 750 private replies an hour per account for posts and reels; the default keeps well under it
+const DEFAULT_AUTOMATION_LIMITS: AutomationLimits = { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3 };
+const INSTAGRAM_ACCOUNT_HOURLY_MAX = 750;
+// each reply costs three subrequests and a run gets 50 on the Workers Free plan, so 15 leaves room for the claim
+const DEFAULT_AUTOMATION_BATCH_SIZE = 10;
+const MAX_AUTOMATION_BATCH_SIZE = 15;
export interface CloudinaryConfig {
cloudName: string;
@@ -31,12 +38,23 @@ export interface AuthEmailConfig {
supabaseUrl: string;
}
+// comment-to-DM automation: the webhook's secrets and the sending limits
+export interface AutomationConfig {
+ verifyToken: string | undefined;
+ // the secrets a webhook signature may be made with, the Instagram app secret first
+ appSecrets: string[];
+ paused: boolean;
+ limits: AutomationLimits;
+ batchSize: number;
+}
+
export interface AppConfig {
youtubeApiKey: string | undefined;
instagram: InstagramOAuthConfig;
cloudinary: CloudinaryConfig | null;
allowedOrigins: string[];
authEmail: AuthEmailConfig;
+ automation: AutomationConfig;
}
// pasted secrets can carry a byte order mark or stray whitespace
@@ -100,6 +118,28 @@ export function readAuthEmailConfig(env: Env): AuthEmailConfig {
};
}
+// a missing, malformed or out of range value falls back to the default instead of stopping replies
+function positiveIntegerOf(value: string | undefined, fallback: number, max = Number.MAX_SAFE_INTEGER): number {
+ const number = Number(cleanSecret(value));
+ return Number.isInteger(number) && number > 0 && number <= max ? number : fallback;
+}
+
+export function readAutomationConfig(env: Env): AutomationConfig {
+ const defaults = DEFAULT_AUTOMATION_LIMITS;
+ return {
+ verifyToken: cleanSecret(env.INSTAGRAM_WEBHOOK_VERIFY_TOKEN),
+ appSecrets: [cleanSecret(env.INSTAGRAM_APP_SECRET), cleanSecret(env.META_APP_SECRET)].filter((secret): secret is string => !!secret),
+ paused: cleanSecret(env.AUTOMATION_PAUSED)?.toLowerCase() === 'true',
+ limits: {
+ accountHourly: positiveIntegerOf(env.AUTOMATION_ACCOUNT_HOURLY_LIMIT, defaults.accountHourly, INSTAGRAM_ACCOUNT_HOURLY_MAX),
+ userHourly: positiveIntegerOf(env.AUTOMATION_USER_HOURLY_LIMIT, defaults.userHourly),
+ globalHourly: positiveIntegerOf(env.AUTOMATION_GLOBAL_HOURLY_LIMIT, defaults.globalHourly),
+ recipientDaily: positiveIntegerOf(env.AUTOMATION_RECIPIENT_DAILY_LIMIT, defaults.recipientDaily),
+ },
+ batchSize: positiveIntegerOf(env.AUTOMATION_BATCH_SIZE, DEFAULT_AUTOMATION_BATCH_SIZE, MAX_AUTOMATION_BATCH_SIZE),
+ };
+}
+
export function readConfig(env: Env): AppConfig {
const cloudName = cleanSecret(env.CLOUDINARY_CLOUD_NAME);
const uploadPreset = cleanSecret(env.CLOUDINARY_UPLOAD_PRESET);
@@ -109,5 +149,6 @@ export function readConfig(env: Env): AppConfig {
cloudinary: cloudName && uploadPreset ? { cloudName, uploadPreset } : null,
allowedOrigins: allowedOrigins(env),
authEmail: readAuthEmailConfig(env),
+ automation: readAutomationConfig(env),
};
}
diff --git a/backend/lib/metaWebhookSignature.ts b/backend/lib/metaWebhookSignature.ts
new file mode 100644
index 0000000..85b3fdf
--- /dev/null
+++ b/backend/lib/metaWebhookSignature.ts
@@ -0,0 +1,32 @@
+// Meta signs each webhook with HMAC-SHA256 over the raw body and the app secret, sent as "sha256=<hex>" in X-Hub-Signature-256
+const SIGNATURE_PREFIX = 'sha256=';
+
+function fromHex(text: string): Uint8Array<ArrayBuffer> | null {
+ if (!/^[0-9a-f]+$/i.test(text) || text.length % 2 !== 0) return null;
+ const bytes = new Uint8Array(text.length / 2);
+ for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(text.slice(i * 2, i * 2 + 2), 16);
+ return bytes;
+}
+
+// true when any of the secrets made the signature; Instagram Login apps sign with the Instagram app secret,
+// and the Meta app secret is accepted too because the dashboard shows both
+export async function verifyMetaSignature(secrets: string[], header: string | undefined, body: ArrayBuffer): Promise<boolean> {
+ if (!header?.startsWith(SIGNATURE_PREFIX)) return false;
+ const signature = fromHex(header.slice(SIGNATURE_PREFIX.length));
+ if (!signature) return false;
+ for (const secret of secrets) {
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
+ // subtle.verify compares in constant time
+ if (await crypto.subtle.verify('HMAC', key, signature, body)) return true;
+ }
+ return false;
+}
+
+// compares digests, so the time taken does not reveal how much of the token was right
+export async function verifyTokenMatches(expected: string, given: string): Promise<boolean> {
+ const digest = async (text: string) => new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)));
+ const [a, b] = await Promise.all([digest(expected), digest(given)]);
+ let difference = 0;
+ for (let i = 0; i < a.length; i++) difference |= a[i] ^ b[i];
+ return difference === 0;
+}
diff --git a/backend/lib/rateLimit/rules.ts b/backend/lib/rateLimit/rules.ts
index aedb88e..cff3880 100644
--- a/backend/lib/rateLimit/rules.ts
+++ b/backend/lib/rateLimit/rules.ts
@@ -51,6 +51,7 @@ export const QUOTA_ROUTES: readonly RouteMatcher[] = [
{ methods: ['POST'], path: /^\/api\/tracked-content$/ },
{ methods: ['POST'], path: /^\/api\/tracked-content\/[^/]+\/refresh$/ },
{ methods: ['GET', 'POST'], path: /^\/api\/process-scheduled$/ },
+ { methods: ['POST'], path: /^\/api\/automations\/accounts\/[^/]+\/subscribe$/ },
];
export const PUBLISH_ROUTES: readonly RouteMatcher[] = [
diff --git a/backend/middleware/metaWebhook.ts b/backend/middleware/metaWebhook.ts
new file mode 100644
index 0000000..b65ba02
--- /dev/null
+++ b/backend/middleware/metaWebhook.ts
@@ -0,0 +1,25 @@
+import type { Next } from 'hono';
+import { readAutomationConfig } from '../lib/config.ts';
+import { NotConfiguredError, UnauthorizedError, ValidationError } from '../lib/errors.ts';
+import { verifyMetaSignature } from '../lib/metaWebhookSignature.ts';
+import type { AppContext } from '../types/app.ts';
+
+// Meta batches at most 1,000 changes into one notification, far below this
+const MAX_BODY_BYTES = 1024 * 1024;
+
+// the webhook route is public, so the signature over the raw body is what proves the notification came from Meta
+export async function verifyMetaWebhook(c: AppContext, next: Next): Promise<void> {
+ const { appSecrets } = readAutomationConfig(c.env);
+ if (appSecrets.length === 0) throw new NotConfiguredError('Instagram webhooks are not set up: the INSTAGRAM_APP_SECRET Worker secret is missing');
+
+ const declared = Number(c.req.header('Content-Length') ?? 0);
+ if (declared > MAX_BODY_BYTES) throw new ValidationError('The notification is larger than 1 MB');
+ // hono caches the body, so the validator after this parses the same bytes
+ const body = await c.req.arrayBuffer();
+ if (body.byteLength > MAX_BODY_BYTES) throw new ValidationError('The notification is larger than 1 MB');
+
+ if (!await verifyMetaSignature(appSecrets, c.req.header('X-Hub-Signature-256'), body)) {
+ throw new UnauthorizedError('The webhook signature is missing or invalid');
+ }
+ await next();
+}
diff --git a/backend/repositories/auditRepository.ts b/backend/repositories/auditRepository.ts
new file mode 100644
index 0000000..3b15462
--- /dev/null
+++ b/backend/repositories/auditRepository.ts
@@ -0,0 +1,43 @@
+import { execute, rows } from './query.ts';
+import { newRowId } from '../lib/ids.ts';
+import type { SupabaseClient } from '../types/app.ts';
+
+export type AuditSubjectType = 'account' | 'automation_rule' | 'automation_account' | 'automation_comment';
+
+// action is "<subject>.<verb>", such as account.removed or automation_rule.updated
+export interface AuditEvent {
+ action: string;
+ subjectType: AuditSubjectType;
+ subjectId: string | null;
+ details?: Record<string, unknown>;
+}
+
+// recordForUser keeps who did what; deleteCreatedBefore is the daily retention across all users
+export interface AuditRepository {
+ recordForUser(userId: string, event: AuditEvent): Promise<void>;
+ deleteCreatedBefore(cutoff: string): Promise<number>;
+}
+
+export function createAuditRepository(db: SupabaseClient): AuditRepository {
+ return {
+ async recordForUser(userId, { action, subjectType, subjectId, details = {} }) {
+ await execute('auditEvents.record', () => db.from('audit_events').insert({
+ id: newRowId(),
+ user_id: userId,
+ action,
+ subject_type: subjectType,
+ subject_id: subjectId,
+ details,
+ }));
+ },
+
+ async deleteCreatedBefore(cutoff) {
+ const deleted = await rows<{ id: string }>('auditEvents.deleteOld', () => db
+ .from('audit_events')
+ .delete()
+ .lt('created_at', cutoff)
+ .select('id'));
+ return deleted.length;
+ },
+ };
+}
diff --git a/backend/repositories/automationAccountRepository.ts b/backend/repositories/automationAccountRepository.ts
new file mode 100644
index 0000000..fe617e7
--- /dev/null
+++ b/backend/repositories/automationAccountRepository.ts
@@ -0,0 +1,85 @@
+import { maybeRow, rows } from './query.ts';
+import type { SupabaseClient } from '../types/app.ts';
+
+interface AutomationAccountRow {
+ account_id: string;
+ paused: boolean;
+ paused_reason: string | null;
+ cooldown_until: string | null;
+ cooldown_reason: string | null;
+ subscribed_at: string | null;
+}
+
+// an account has no row until its automation is paused, subscribed or cooled down; these are the defaults then
+export interface AutomationAccountControls {
+ accountId: string;
+ paused: boolean;
+ pausedReason: string | null;
+ cooldownUntil: string | null;
+ cooldownReason: string | null;
+ subscribedAt: string | null;
+}
+
+const COLUMNS = 'account_id, paused, paused_reason, cooldown_until, cooldown_reason, subscribed_at';
+
+function toControls(row: AutomationAccountRow): AutomationAccountControls {
+ return {
+ accountId: row.account_id,
+ paused: row.paused,
+ pausedReason: row.paused_reason,
+ cooldownUntil: row.cooldown_until,
+ cooldownReason: row.cooldown_reason,
+ subscribedAt: row.subscribed_at,
+ };
+}
+
+export function defaultControls(accountId: string): AutomationAccountControls {
+ return { accountId, paused: false, pausedReason: null, cooldownUntil: null, cooldownReason: null, subscribedAt: null };
+}
+
+// every method is scoped to the verified user; the services check the account belongs to them before writing
+export interface AutomationAccountRepository {
+ listForUser(userId: string): Promise<AutomationAccountControls[]>;
+ findForUser(accountId: string, userId: string): Promise<AutomationAccountControls | null>;
+ setPausedForUser(accountId: string, userId: string, paused: boolean): Promise<AutomationAccountControls>;
+ markSubscribedForUser(accountId: string, userId: string): Promise<AutomationAccountControls>;
+}
+
+export function createAutomationAccountRepository(db: SupabaseClient): AutomationAccountRepository {
+ // one upsert, so the first change to an account creates its row and later ones update it
+ async function save(operation: string, accountId: string, userId: string, values: Partial<AutomationAccountRow>) {
+ const saved = await rows<AutomationAccountRow>(operation, () => db
+ .from('automation_accounts')
+ .upsert({ account_id: accountId, user_id: userId, ...values }, { onConflict: 'account_id' })
+ .select(COLUMNS));
+ const fallback: AutomationAccountRow = {
+ account_id: accountId, paused: false, paused_reason: null, cooldown_until: null, cooldown_reason: null, subscribed_at: null, ...values,
+ };
+ return toControls(saved[0] ?? fallback);
+ }
+
+ return {
+ async listForUser(userId) {
+ const found = await rows<AutomationAccountRow>('automationAccounts.listForUser', () => db
+ .from('automation_accounts')
+ .select(COLUMNS)
+ .eq('user_id', userId));
+ return found.map(toControls);
+ },
+
+ async findForUser(accountId, userId) {
+ const row = await maybeRow<AutomationAccountRow>('automationAccounts.findForUser', () => db
+ .from('automation_accounts')
+ .select(COLUMNS)
+ .eq('account_id', accountId)
+ .eq('user_id', userId)
+ .maybeSingle());
+ return row ? toControls(row) : null;
+ },
+
+ // pausing or resuming by hand clears a hold the Worker set, because the owner has dealt with it
+ setPausedForUser: (accountId, userId, paused) => save('automationAccounts.setPaused', accountId, userId, { paused, paused_reason: null }),
+
+ markSubscribedForUser: (accountId, userId) => save('automationAccounts.markSubscribed', accountId, userId, { subscribed_at: new Date().toISOString() }),
+ };
+}
diff --git a/backend/repositories/automationCommentRepository.ts b/backend/repositories/automationCommentRepository.ts
new file mode 100644
index 0000000..cd73e54
--- /dev/null
+++ b/backend/repositories/automationCommentRepository.ts
@@ -0,0 +1,325 @@
+import { execute, maybeRow, rows } from './query.ts';
+import type { FinishPlan, ReleasePlan, ReserveOutcome } from '../lib/automationDelivery.ts';
+import type { SupabaseClient } from '../types/app.ts';
+import type { AutomationActivityItem, AutomationCommentStatus, AutomationLimits, AutomationStats } from '../../shared/types/automation.ts';
+
+interface AutomationCommentRow {
+ id: string;
+ account_id: string;
+ rule_id: string | null;
+ comment_id: string;
+ media_id: string | null;
+ from_username: string | null;
+ text: string | null;
+ status: AutomationCommentStatus;
+ status_reason: string | null;
+ error_message: string | null;
+ attempts: number;
+ next_attempt_at: string | null;
+ accepted_at: string | null;
+ expires_at: string;
+ created_at: string;
+}
+
+interface ClaimedRow {
+ id: string;
+ user_id: string;
+ account_id: string;
+ rule_id: string | null;
+ ig_user_id: string;
+ comment_id: string;
+ from_id: string | null;
+ attempts: number;
+ expires_at: string;
+ rule_enabled: boolean;
+ reply_text: string | null;
+ link_url: string | null;
+ access_token: string | null;
+}
+
+// a comment as the webhook stores it
+export interface NewAutomationComment {
+ id: string;
+ userId: string;
+ accountId: string;
+ ruleId: string | null;
+ igUserId: string;
+ commentId: string;
+ mediaId: string | null;
+ fromId: string | null;
+ fromUsername: string | null;
+ text: string | null;
+ status: 'ignored' | 'queued';
+ statusReason: string | null;
+ nextAttemptAt: string | null;
+ notifiedAt: string;
+ expiresAt: string;
+}
+
+// a job one run holds, with what it needs to send: the rule's reply and the account's token
+export interface ClaimedComment {
+ id: string;
+ userId: string;
+ accountId: string;
+ ruleId: string | null;
+ igUserId: string;
+ commentId: string;
+ fromId: string | null;
+ attempts: number;
+ expiresAt: string;
+ ruleEnabled: boolean;
+ replyText: string | null;
+ linkUrl: string | null;
+ accessToken: string | null;
+}
+
+export interface ClaimOptions {
+ limit: number;
+ perAccount: number;
+ leaseSeconds: number;
+ // only these comments, as the webhook stored them
+ ids?: string[];
+}
+
+export interface Reservation {
+ outcome: ReserveOutcome;
+ retryAt: string | null;
+}
+
+export interface ActivityFilter {
+ accountId?: string;
+ ruleId?: string;
+ status?: AutomationCommentStatus;
+ from?: string;
+ to?: string;
+ // created_at of the last item on the previous page
+ before?: string;
+ limit: number;
+}
+
+export interface StatsFilter {
+ from: string;
+ to: string;
+ accountId?: string;
+ ruleId?: string;
+}
+
+// a person may ask for these to be tried again; an expired one can never be sent
+const RETRYABLE: AutomationCommentStatus[] = ['failed', 'needs_review', 'skipped'];
+
+const COLUMNS = 'id, account_id, rule_id, comment_id, media_id, from_username, text, status, status_reason, error_message, attempts, next_attempt_at, accepted_at, expires_at, created_at';
+
+function toItem(row: AutomationCommentRow): AutomationActivityItem {
+ return {
+ id: row.id,
+ accountId: row.account_id,
+ ruleId: row.rule_id,
+ commentId: row.comment_id,
+ mediaId: row.media_id,
+ fromUsername: row.from_username,
+ text: row.text,
+ status: row.status,
+ statusReason: row.status_reason,
+ errorMessage: row.error_message,
+ attempts: row.attempts,
+ nextAttemptAt: row.next_attempt_at,
+ acceptedAt: row.accepted_at,
+ expiresAt: row.expires_at,
+ createdAt: row.created_at,
+ };
+}
+
+function toClaimed(row: ClaimedRow): ClaimedComment {
+ return {
+ id: row.id,
+ userId: row.user_id,
+ accountId: row.account_id,
+ ruleId: row.rule_id,
+ igUserId: row.ig_user_id,
+ commentId: row.comment_id,
+ fromId: row.from_id,
+ attempts: row.attempts,
+ expiresAt: row.expires_at,
+ ruleEnabled: row.rule_enabled,
+ replyText: row.reply_text,
+ linkUrl: row.link_url,
+ accessToken: row.access_token,
+ };
+}
+
+// methods named ...ForUser filter by the verified user id; insertMany, claim, reserve, finish, release and
+// deleteCreatedBefore serve the webhook and the sweep across all users
+export interface AutomationCommentRepository {
+ insertMany(comments: NewAutomationComment[]): Promise<NewAutomationComment[]>;
+ claim(options: ClaimOptions): Promise<ClaimedComment[]>;
+ reserve(id: string, attemptId: string, limits: AutomationLimits): Promise<Reservation>;
+ finish(id: string, attemptId: string, plan: FinishPlan): Promise<boolean>;
+ release(id: string, plan: ReleasePlan): Promise<boolean>;
+ listForUser(userId: string, filter: ActivityFilter): Promise<AutomationActivityItem[]>;
+ findForUser(id: string, userId: string): Promise<AutomationActivityItem | null>;
+ requeueForUser(id: string, userId: string): Promise<AutomationActivityItem | null>;
+ releaseHeldForAccount(accountId: string, userId: string): Promise<void>;
+ statsForUser(userId: string, filter: StatsFilter): Promise<AutomationStats>;
+ deleteCreatedBefore(cutoff: string): Promise<number>;
+}
+
+export function createAutomationCommentRepository(db: SupabaseClient): AutomationCommentRepository {
+ return {
+ // the unique (ig_user_id, comment_id) drops a notification Meta delivered again; only new rows come back
+ async insertMany(comments) {
+ if (comments.length === 0) return [];
+ const inserted = await rows<{ id: string }>('automationComments.insertMany', () => db
+ .from('automation_comments')
+ .upsert(comments.map(comment => ({
+ id: comment.id,
+ user_id: comment.userId,
+ account_id: comment.accountId,
+ rule_id: comment.ruleId,
+ ig_user_id: comment.igUserId,
+ comment_id: comment.commentId,
+ media_id: comment.mediaId,
+ from_id: comment.fromId,
+ from_username: comment.fromUsername,
+ text: comment.text,
+ status: comment.status,
+ status_reason: comment.statusReason,
+ next_attempt_at: comment.nextAttemptAt,
+ notified_at: comment.notifiedAt,
+ expires_at: comment.expiresAt,
+ })), { onConflict: 'ig_user_id,comment_id', ignoreDuplicates: true })
+ .select('id'));
+ const insertedIds = new Set(inserted.map(row => row.id));
+ return comments.filter(comment => insertedIds.has(comment.id));
+ },
+
+ async claim({ limit, perAccount, leaseSeconds, ids }) {
+ const { data } = await execute('automationComments.claim', () => db.rpc('claim_automation_comments', {
+ p_limit: limit,
+ p_per_account: perAccount,
+ p_lease_seconds: leaseSeconds,
+ p_ids: ids ?? null,
+ }));
+ return ((data ?? []) as ClaimedRow[]).map(toClaimed);
+ },
+
+ async reserve(id, attemptId, limits) {
+ const { data } = await execute('automationComments.reserve', () => db.rpc('reserve_automation_send', {
+ p_id: id,
+ p_attempt_id: attemptId,
+ p_global_limit: limits.globalHourly,
+ p_user_limit: limits.userHourly,
+ p_account_limit: limits.accountHourly,
+ p_recipient_limit: limits.recipientDaily,
+ }));
+ const [row] = (data ?? []) as { outcome: ReserveOutcome; retry_at: string | null }[];
+ return row ? { outcome: row.outcome, retryAt: row.retry_at } : { outcome: 'gone', retryAt: null };
+ },
+
+ async finish(id, attemptId, plan) {
+ const { data } = await execute('automationComments.finish', () => db.rpc('finish_automation_send', {
+ p_id: id,
+ p_attempt_id: attemptId,
+ p_status: plan.status,
+ p_outcome: plan.outcome,
+ p_reason: plan.reason,
+ p_error_message: plan.errorMessage,
+ p_message_id: plan.messageId,
+ p_error_code: plan.errorCode,
+ p_error_subcode: plan.errorSubcode,
+ p_http_status: plan.httpStatus,
+ p_next_attempt_at: plan.nextAttemptAt,
+ p_cooldown_until: plan.cooldownUntil,
+ p_cooldown_reason: plan.cooldownReason,
+ p_pause_reason: plan.pauseReason,
+ }));
+ return data === true;
+ },
+
+ // only a job this run still holds is given back
+ async release(id, plan) {
+ const released = await rows<{ id: string }>('automationComments.release', () => db
+ .from('automation_comments')
+ .update({
+ status: plan.status,
+ status_reason: plan.reason,
+ error_message: plan.errorMessage,
+ next_attempt_at: plan.nextAttemptAt,
+ claimed_at: null,
+ })
+ .eq('id', id)
+ .eq('status', 'processing')
+ .select('id'));
+ return released.length > 0;
+ },
+
+ // newest first; a full page may have more after it, and the next page asks for rows before the last one's time
+ async listForUser(userId, { accountId, ruleId, status, from, to, before, limit }) {
+ const found = await rows<AutomationCommentRow>('automationComments.listForUser', () => {
+ let query = db.from('automation_comments').select(COLUMNS).eq('user_id', userId);
+ if (accountId) query = query.eq('account_id', accountId);
+ if (ruleId) query = query.eq('rule_id', ruleId);
+ if (status) query = query.eq('status', status);
+ if (from) query = query.gte('created_at', from);
+ if (to) query = query.lt('created_at', to);
+ if (before) query = query.lt('created_at', before);
+ return query.order('created_at', { ascending: false }).limit(limit);
+ });
+ return found.map(toItem);
+ },
+
+ async findForUser(id, userId) {
+ const row = await maybeRow<AutomationCommentRow>('automationComments.findForUser', () => db
+ .from('automation_comments')
+ .select(COLUMNS)
+ .eq('id', id)
+ .eq('user_id', userId)
+ .maybeSingle());
+ return row ? toItem(row) : null;
+ },
+
+ // checked in the update itself, so a job a sweep picked up in between is never sent twice
+ async requeueForUser(id, userId) {
+ const now = new Date().toISOString();
+ const requeued = await rows<AutomationCommentRow>('automationComments.requeue', () => db
+ .from('automation_comments')
+ .update({ status: 'queued', status_reason: 'retry', error_message: null, next_attempt_at: now, claimed_at: null })
+ .eq('id', id)
+ .eq('user_id', userId)
+ .in('status', RETRYABLE)
+ .gt('expires_at', now)
+ .select(COLUMNS));
+ return requeued[0] ? toItem(requeued[0]) : null;
+ },
+
+ async releaseHeldForAccount(accountId, userId) {
+ await execute('automationComments.releaseHeld', () => db
+ .from('automation_comments')
+ .update({ next_attempt_at: new Date().toISOString(), error_message: null })
+ .eq('account_id', accountId)
+ .eq('user_id', userId)
+ .eq('status', 'queued')
+ .eq('status_reason', 'paused'));
+ },
+
+ async statsForUser(userId, { from, to, accountId, ruleId }) {
+ const { data } = await execute('automationComments.stats', () => db.rpc('automation_stats', {
+ p_user_id: userId,
+ p_from: from,
+ p_to: to,
+ p_account_id: accountId ?? null,
+ p_rule_id: ruleId ?? null,
+ }));
+ const stats = (data ?? {}) as Partial<AutomationStats>;
+ return { comments: stats.comments ?? {}, attempts: stats.attempts ?? {} };
+ },
+
+ async deleteCreatedBefore(cutoff) {
+ const deleted = await rows<{ id: string }>('automationComments.deleteOld', () => db
+ .from('automation_comments')
+ .delete()
+ .lt('created_at', cutoff)
+ .select('id'));
+ return deleted.length;
+ },
+ };
+}
diff --git a/backend/repositories/automationRuleRepository.ts b/backend/repositories/automationRuleRepository.ts
new file mode 100644
index 0000000..707eef5
--- /dev/null
+++ b/backend/repositories/automationRuleRepository.ts
@@ -0,0 +1,153 @@
+import { execute, maybeRow, rows } from './query.ts';
+import type { SupabaseClient } from '../types/app.ts';
+import type { AutomationMatchMode, AutomationRule } from '../../shared/types/automation.ts';
+
+interface AutomationRuleRow {
+ id: string;
+ account_id: string;
+ name: string;
+ keywords: string[];
+ match_mode: AutomationMatchMode;
+ case_sensitive: boolean;
+ media_ids: string[];
+ reply_text: string;
+ link_url: string | null;
+ enabled: boolean;
+ hourly_limit: number | null;
+ created_at: string;
+ updated_at: string;
+}
+
+// a rule as the webhook needs it to match a comment, with the member and account it belongs to
+export interface WebhookRule {
+ id: string;
+ userId: string;
+ accountId: string;
+ keywords: string[];
+ matchMode: AutomationMatchMode;
+ caseSensitive: boolean;
+ mediaIds: string[];
+}
+
+interface WebhookRuleRow {
+ id: string;
+ user_id: string;
+ account_id: string;
+ keywords: string[];
+ match_mode: AutomationMatchMode;
+ case_sensitive: boolean;
+ media_ids: string[];
+}
+
+export type AutomationRuleChanges = Partial<Omit<AutomationRule, 'id' | 'accountId' | 'createdAt' | 'updatedAt'>>;
+
+const COLUMNS = 'id, account_id, name, keywords, match_mode, case_sensitive, media_ids, reply_text, link_url, enabled, hourly_limit, created_at, updated_at';
+
+function toRule(row: AutomationRuleRow): AutomationRule {
+ return {
+ id: row.id,
+ accountId: row.account_id,
+ name: row.name,
+ keywords: row.keywords,
+ matchMode: row.match_mode,
+ caseSensitive: row.case_sensitive,
+ mediaIds: row.media_ids,
+ replyText: row.reply_text,
+ linkUrl: row.link_url,
+ enabled: row.enabled,
+ hourlyLimit: row.hourly_limit,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ };
+}
+
+// undefined fields are left out, so an update only touches the columns it names
+function toColumns(changes: AutomationRuleChanges): Record<string, unknown> {
+ const columns: Record<string, unknown> = {
+ name: changes.name,
+ keywords: changes.keywords,
+ match_mode: changes.matchMode,
+ case_sensitive: changes.caseSensitive,
+ media_ids: changes.mediaIds,
+ reply_text: changes.replyText,
+ link_url: changes.linkUrl,
+ enabled: changes.enabled,
+ hourly_limit: changes.hourlyLimit,
+ };
+ return Object.fromEntries(Object.entries(columns).filter(([, value]) => value !== undefined));
+}
+
+// methods named ...ForUser filter by the verified user id; listEnabledForInstagramUser serves the webhook across all users
+export interface AutomationRuleRepository {
+ listForUser(userId: string): Promise<AutomationRule[]>;
+ findForUser(id: string, userId: string): Promise<AutomationRule | null>;
+ create(rule: AutomationRule, userId: string): Promise<AutomationRule>;
+ updateForUser(id: string, changes: AutomationRuleChanges, userId: string): Promise<AutomationRule | null>;
+ deleteForUser(id: string, userId: string): Promise<boolean>;
+ listEnabledForInstagramUser(igUserId: string): Promise<WebhookRule[]>;
+}
+
+export function createAutomationRuleRepository(db: SupabaseClient): AutomationRuleRepository {
+ return {
+ async listForUser(userId) {
+ const found = await rows<AutomationRuleRow>('automationRules.listForUser', () => db
+ .from('automation_rules')
+ .select(COLUMNS)
+ .eq('user_id', userId)
+ .order('created_at', { ascending: true })
+ .order('id', { ascending: true }));
+ return found.map(toRule);
+ },
+
+ async findForUser(id, userId) {
+ const row = await maybeRow<AutomationRuleRow>('automationRules.findForUser', () => db
+ .from('automation_rules')
+ .select(COLUMNS)
+ .eq('id', id)
+ .eq('user_id', userId)
+ .maybeSingle());
+ return row ? toRule(row) : null;
+ },
+
+ async create(rule, userId) {
+ const created = await rows<AutomationRuleRow>('automationRules.create', () => db
+ .from('automation_rules')
+ .insert({ id: rule.id, user_id: userId, account_id: rule.accountId, ...toColumns(rule) })
+ .select(COLUMNS));
+ return created[0] ? toRule(created[0]) : rule;
+ },
+
+ async updateForUser(id, changes, userId) {
+ const updated = await rows<AutomationRuleRow>('automationRules.update', () => db
+ .from('automation_rules')
+ .update(toColumns(changes))
+ .eq('id', id)
+ .eq('user_id', userId)
+ .select(COLUMNS));
+ return updated[0] ? toRule(updated[0]) : null;
+ },
+
+ async deleteForUser(id, userId) {
+ const deleted = await rows<{ id: string }>('automationRules.delete', () => db
+ .from('automation_rules')
+ .delete()
+ .eq('id', id)
+ .eq('user_id', userId)
+ .select('id'));
+ return deleted.length > 0;
+ },
+
+ async listEnabledForInstagramUser(igUserId) {
+ const { data } = await execute('automationRules.listForInstagramUser', () => db.rpc('automation_rules_for_ig_user', { p_ig_user_id: igUserId }));
+ return ((data ?? []) as WebhookRuleRow[]).map(row => ({
+ id: row.id,
+ userId: row.user_id,
+ accountId: row.account_id,
+ keywords: row.keywords,
+ matchMode: row.match_mode,
+ caseSensitive: row.case_sensitive,
+ mediaIds: row.media_ids,
+ }));
+ },
+ };
+}
diff --git a/backend/routes/automationRoutes.ts b/backend/routes/automationRoutes.ts
new file mode 100644
index 0000000..8d7ce18
--- /dev/null
+++ b/backend/routes/automationRoutes.ts
@@ -0,0 +1,22 @@
+import { Hono } from 'hono';
+import {
+ getAutomations, createAutomationRule, updateAutomationRule, duplicateAutomationRule, deleteAutomationRule, testAutomationRule,
+ listAutomationActivity, getAutomationStats, retryAutomationActivity, updateAutomationAccount, subscribeAutomationAccount,
+} from '../controllers/automationController.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+router.get('/automations', ...getAutomations);
+router.post('/automations/rules', ...createAutomationRule);
+router.put('/automations/rules/:id', ...updateAutomationRule);
+router.delete('/automations/rules/:id', ...deleteAutomationRule);
+router.post('/automations/rules/:id/duplicate', ...duplicateAutomationRule);
+router.post('/automations/test', ...testAutomationRule);
+router.get('/automations/activity', ...listAutomationActivity);
+router.post('/automations/activity/:id/retry', ...retryAutomationActivity);
+router.get('/automations/stats', ...getAutomationStats);
+router.put('/automations/accounts/:accountId', ...updateAutomationAccount);
+router.post('/automations/accounts/:accountId/subscribe', ...subscribeAutomationAccount);
+
+export default router;
diff --git a/backend/routes/index.ts b/backend/routes/index.ts
index 13bd9b7..924503f 100644
--- a/backend/routes/index.ts
+++ b/backend/routes/index.ts
@@ -1,8 +1,10 @@
import { Hono } from 'hono';
import accountRoutes from './accountRoutes.ts';
import authHookRoutes from './authHookRoutes.ts';
+import automationRoutes from './automationRoutes.ts';
import analyticsRoutes from './analyticsRoutes.ts';
import instagramAuthRoutes from './instagramAuthRoutes.ts';
+import instagramWebhookRoutes from './instagramWebhookRoutes.ts';
import overviewRoutes from './overviewRoutes.ts';
import publishingRoutes from './publishingRoutes.ts';
import redditRoutes from './redditRoutes.ts';
@@ -16,17 +18,18 @@ import { RATE_LIMIT_RULES } from '../lib/rateLimit/rules.ts';
import type { AppEnv } from '../types/app.ts';
// reachable without a token: the health check, the OAuth redirect, whose signed state names the user,
-// and Supabase Auth's email hook, whose signature proves where it came from
+// and the Supabase Auth email hook and Instagram webhook, whose signatures prove where they came from
export const publicRoutes = new Hono<AppEnv>();
publicRoutes.get('/health', ...getHealth);
publicRoutes.get('/auth/instagram/callback', rateLimit(RATE_LIMIT_RULES.oauth, clientIp), ...handleInstagramCallback);
publicRoutes.route('/', authHookRoutes);
+publicRoutes.route('/', instagramWebhookRoutes);
// mounted behind requireAuth and the per-user rate limits in app.ts
export const protectedRoutes = new Hono<AppEnv>();
for (const routes of [
accountRoutes, analyticsRoutes, redditRoutes, publishingRoutes, scheduledPostRoutes, trackedContentRoutes,
- overviewRoutes, settingsRoutes, instagramAuthRoutes,
+ overviewRoutes, settingsRoutes, instagramAuthRoutes, automationRoutes,
]) {
protectedRoutes.route('/', routes);
}
diff --git a/backend/routes/instagramWebhookRoutes.ts b/backend/routes/instagramWebhookRoutes.ts
new file mode 100644
index 0000000..949b54b
--- /dev/null
+++ b/backend/routes/instagramWebhookRoutes.ts
@@ -0,0 +1,12 @@
+import { Hono } from 'hono';
+import { verifyInstagramWebhook, receiveInstagramWebhook } from '../controllers/instagramWebhookController.ts';
+import { verifyMetaWebhook } from '../middleware/metaWebhook.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+// Meta's dashboard calls the GET once to check the callback URL; every notification is a signed POST
+router.get('/webhooks/instagram', ...verifyInstagramWebhook);
+router.post('/webhooks/instagram', verifyMetaWebhook, ...receiveInstagramWebhook);
+
+export default router;
diff --git a/backend/server.ts b/backend/server.ts
index a4d10f1..5ce95ca 100644
--- a/backend/server.ts
+++ b/backend/server.ts
@@ -6,8 +6,8 @@ import type { Env } from './types/env.ts';
export default {
fetch: app.fetch,
- // wrangler.toml schedules: due posts every 15 minutes, token refresh daily
+ // wrangler.toml schedules: the reply queue every 5 minutes with due posts on the quarter hour, and daily upkeep
async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {
- ctx.waitUntil(runScheduledJob(event.cron, env));
+ ctx.waitUntil(runScheduledJob(event.cron, env, event.scheduledTime));
},
} satisfies ExportedHandler<Env>;
diff --git a/backend/services/accountService.ts b/backend/services/accountService.ts
index 4d05a93..638f92d 100644
--- a/backend/services/accountService.ts
+++ b/backend/services/accountService.ts
@@ -6,6 +6,7 @@ import { buildYouTubeAccount, buildRedditAccount, buildInstagramAccount } from '
import { ConflictError, NotConfiguredError, NotFoundError, ValidationError } from '../lib/errors.ts';
import type { AccountRepository } from '../repositories/accountRepository.ts';
import type { AnalyticsCacheRepository } from '../repositories/analyticsCacheRepository.ts';
+import type { AuditRepository } from '../repositories/auditRepository.ts';
import type { AppConfig } from '../lib/config.ts';
import type { RequestContext } from '../types/context.ts';
import type { Account, AccountRefreshResult, NewAccount } from '../../shared/types/domain.ts';
@@ -16,6 +17,7 @@ import type { InstagramProfile } from '../../shared/types/instagram.ts';
export interface AccountServiceDeps {
accounts: AccountRepository;
cache: AnalyticsCacheRepository;
+ audit: AuditRepository;
config: AppConfig;
context: RequestContext;
}
@@ -91,7 +93,7 @@ function youtubeUpdates(channelData: YouTubeChannelData, full: boolean): Partial
};
}
-export function createAccountService({ accounts, cache, config, context }: AccountServiceDeps): AccountService {
+export function createAccountService({ accounts, cache, audit, config, context }: AccountServiceDeps): AccountService {
const { signal, log } = context;
function youtubeKey(): string {
@@ -216,12 +218,14 @@ export function createAccountService({ accounts, cache, config, context }: Accou
return tokenExpiresAt;
},
+ // removing an account also removes its automation rules, received comments and reply history (foreign keys)
async remove(userId, accountId) {
- await findOwned(userId, accountId);
+ const account = await findOwned(userId, accountId);
await Promise.all([
accounts.deleteForUser(accountId, userId),
cache.deleteAllForAccount(userId, accountId),
]);
+ await audit.recordForUser(userId, { action: 'account.removed', subjectType: 'account', subjectId: accountId, details: { platform: account.platform } });
},
};
}
diff --git a/backend/services/automationProcessor.ts b/backend/services/automationProcessor.ts
new file mode 100644
index 0000000..ca87714
--- /dev/null
+++ b/backend/services/automationProcessor.ts
@@ -0,0 +1,98 @@
+import { sendPrivateReply } from './instagram/instagramMessaging.ts';
+import { CLAIM_LEASE_SECONDS, composeReply, finishPlan, readinessPlan, releasePlan } from '../lib/automationDelivery.ts';
+import { newRowId } from '../lib/ids.ts';
+import { errorFields } from '../lib/logger.ts';
+import type { AutomationCommentRepository, ClaimedComment } from '../repositories/automationCommentRepository.ts';
+import type { AutomationConfig } from '../lib/config.ts';
+import type { RequestContext } from '../types/context.ts';
+import type { AutomationCommentStatus } from '../../shared/types/automation.ts';
+
+export interface AutomationProcessorDeps {
+ comments: AutomationCommentRepository;
+ automation: AutomationConfig;
+ context: RequestContext;
+}
+
+export interface ProcessOptions {
+ // only these comments, as a webhook just stored them; otherwise whatever is due
+ ids?: string[];
+ // fewer than the configured batch, when a run has already spent part of its subrequests
+ limit?: number;
+}
+
+export interface ProcessRun {
+ claimed: number;
+ // the status each claimed job ended in this run; gone means another run settled it first
+ outcomes: Partial<Record<AutomationCommentStatus | 'gone' | 'error', number>>;
+}
+
+export interface AutomationProcessor {
+ run(options?: ProcessOptions): Promise<ProcessRun>;
+}
+
+// sends the private replies that are due, one at a time so each account's replies keep their order and the
+// Worker's six open connections are never exceeded; every job is settled in the database before the next starts
+export function createAutomationProcessor({ comments, automation, context }: AutomationProcessorDeps): AutomationProcessor {
+ const { signal, log } = context;
+
+ async function settle(job: ClaimedComment): Promise<AutomationCommentStatus | 'gone'> {
+ const now = Date.now();
+ const notReady = readinessPlan(job, now);
+ if (notReady) {
+ await comments.release(job.id, notReady);
+ return notReady.status;
+ }
+
+ const attemptId = newRowId();
+ const reservation = await comments.reserve(job.id, attemptId, automation.limits);
+ if (reservation.outcome === 'gone') return 'gone';
+ const held = releasePlan(reservation.outcome, reservation.retryAt, job, now);
+ if (held) {
+ await comments.release(job.id, held);
+ return held.status;
+ }
+
+ // readinessPlan checked that the rule is on and the token is there
+ const result = await sendPrivateReply(job.igUserId, job.accessToken!, job.commentId, composeReply(job.replyText!, job.linkUrl), signal);
+ const plan = finishPlan(result, { attempts: job.attempts + 1, expiresAt: job.expiresAt }, Date.now());
+ await comments.finish(job.id, attemptId, plan);
+ log.info('automation reply settled', {
+ commentRowId: job.id,
+ accountId: job.accountId,
+ ruleId: job.ruleId,
+ status: plan.status,
+ outcome: plan.outcome,
+ errorCode: plan.errorCode,
+ errorSubcode: plan.errorSubcode,
+ });
+ return plan.status;
+ }
+
+ return {
+ async run({ ids, limit } = {}) {
+ const outcomes: ProcessRun['outcomes'] = {};
+ if (automation.paused) {
+ log.info('automation paused on this instance; nothing sent');
+ return { claimed: 0, outcomes };
+ }
+ const batch = Math.max(1, Math.min(limit ?? automation.batchSize, automation.batchSize));
+ // a sweep shares its batch between accounts; a webhook's own comments are all from the accounts it named
+ const perAccount = ids ? batch : Math.max(1, Math.ceil(batch / 2));
+ const jobs = await comments.claim({ limit: batch, perAccount, leaseSeconds: CLAIM_LEASE_SECONDS, ids });
+
+ for (const job of jobs) {
+ // a job left claimed is picked up again after its lease, so stopping early loses nothing
+ if (signal.aborted) break;
+ try {
+ const status = await settle(job);
+ outcomes[status] = (outcomes[status] ?? 0) + 1;
+ } catch (err) {
+ // one job's database failure must not stop the others; its claim or reservation expires and recovers it
+ outcomes.error = (outcomes.error ?? 0) + 1;
+ log.error('automation reply failed', { commentRowId: job.id, accountId: job.accountId, ...errorFields(err) });
+ }
+ }
+ return { claimed: jobs.length, outcomes };
+ },
+ };
+}
diff --git a/backend/services/automationService.ts b/backend/services/automationService.ts
new file mode 100644
index 0000000..5d5a424
--- /dev/null
+++ b/backend/services/automationService.ts
@@ -0,0 +1,270 @@
+import { subscribeToComments } from './instagram/instagramMessaging.ts';
+import { coversMedia, matchedKeyword } from '../lib/automationMatching.ts';
+import { MAX_MESSAGE_BYTES, composeReply, messageBytes } from '../lib/automationDelivery.ts';
+import { ConflictError, NotFoundError, ValidationError } from '../lib/errors.ts';
+import { newRowId } from '../lib/ids.ts';
+import { errorFields } from '../lib/logger.ts';
+import { defaultControls } from '../repositories/automationAccountRepository.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { AutomationAccountControls, AutomationAccountRepository } from '../repositories/automationAccountRepository.ts';
+import type { AutomationCommentRepository } from '../repositories/automationCommentRepository.ts';
+import type { AutomationRuleRepository } from '../repositories/automationRuleRepository.ts';
+import type { AuditRepository } from '../repositories/auditRepository.ts';
+import type { ActivityQuery, StatsQuery } from '../validators/automationValidators.ts';
+import type { AutomationConfig } from '../lib/config.ts';
+import type { RequestContext } from '../types/context.ts';
+import type { Account } from '../../shared/types/domain.ts';
+import type {
+ AutomationAccountState, AutomationActivityItem, AutomationRule, AutomationRuleRequest, AutomationRuleUpdateRequest,
+ AutomationSettings, AutomationStats, AutomationTestRequest, AutomationTestResponse,
+} from '../../shared/types/automation.ts';
+
+export interface AutomationServiceDeps {
+ accounts: AccountRepository;
+ rules: AutomationRuleRepository;
+ comments: AutomationCommentRepository;
+ automationAccounts: AutomationAccountRepository;
+ audit: AuditRepository;
+ automation: AutomationConfig;
+ context: RequestContext;
+}
+
+export interface AutomationOverview {
+ rules: AutomationRule[];
+ accounts: AutomationAccountState[];
+ settings: AutomationSettings;
+}
+
+export interface ActivityPage {
+ items: AutomationActivityItem[];
+ nextBefore: string | null;
+}
+
+export interface StatsPeriod {
+ from: string;
+ to: string;
+ stats: AutomationStats;
+}
+
+export type AutomationTestResult = Omit<AutomationTestResponse, 'success'>;
+
+export interface AutomationService {
+ overview(userId: string): Promise<AutomationOverview>;
+ createRule(userId: string, input: AutomationRuleRequest): Promise<AutomationRule>;
+ updateRule(userId: string, id: string, changes: AutomationRuleUpdateRequest): Promise<AutomationRule>;
+ duplicateRule(userId: string, id: string): Promise<AutomationRule>;
+ deleteRule(userId: string, id: string): Promise<void>;
+ test(input: AutomationTestRequest): AutomationTestResult;
+ activity(userId: string, query: ActivityQuery): Promise<ActivityPage>;
+ stats(userId: string, query: StatsQuery): Promise<StatsPeriod>;
+ retry(userId: string, commentRowId: string): Promise<AutomationActivityItem>;
+ setPaused(userId: string, accountId: string, paused: boolean): Promise<AutomationAccountState>;
+ subscribe(userId: string, accountId: string): Promise<AutomationAccountState>;
+}
+
+// the dashboard's default period
+const DEFAULT_STATS_DAYS = 7;
+const DAY_MS = 24 * 60 * 60 * 1000;
+const MAX_NAME = 80;
+const COPY_SUFFIX = ' (copy)';
+
+function toState(account: Account, controls: AutomationAccountControls): AutomationAccountState {
+ return {
+ accountId: account.id,
+ username: account.username ?? '',
+ profilePictureUrl: account.profilePictureUrl ?? '',
+ // a hold the Worker set shows as paused, with its reason in place of a cooldown reason
+ paused: controls.paused,
+ cooldownUntil: controls.cooldownUntil && Date.parse(controls.cooldownUntil) > Date.now() ? controls.cooldownUntil : null,
+ cooldownReason: controls.pausedReason ?? controls.cooldownReason,
+ subscribedAt: controls.subscribedAt,
+ };
+}
+
+function checkMessageSize(replyText: string, linkUrl: string | null): void {
+ const bytes = messageBytes(composeReply(replyText, linkUrl));
+ if (bytes > MAX_MESSAGE_BYTES) {
+ throw new ValidationError(`The reply with its link is ${bytes} bytes; Instagram accepts at most ${MAX_MESSAGE_BYTES}. Shorten the text or the link.`);
+ }
+}
+
+// the user's rules, the controls of their Instagram accounts, and the API that lists, tests and retries replies
+export function createAutomationService(deps: AutomationServiceDeps): AutomationService {
+ const { accounts, rules, comments, automationAccounts, audit, automation, context } = deps;
+
+ async function instagramAccount(userId: string, accountId: string): Promise<Account> {
+ const account = await accounts.findForUser(accountId, userId);
+ if (!account || account.platform !== 'instagram') throw new NotFoundError('Instagram account not found');
+ return account;
+ }
+
+ async function ownedRule(userId: string, id: string): Promise<AutomationRule> {
+ const rule = await rules.findForUser(id, userId);
+ if (!rule) throw new NotFoundError('Automation rule not found');
+ return rule;
+ }
+
+ async function state(userId: string, account: Account): Promise<AutomationAccountState> {
+ return toState(account, await automationAccounts.findForUser(account.id, userId) ?? defaultControls(account.id));
+ }
+
+ async function subscribeAccount(userId: string, account: Account): Promise<AutomationAccountControls> {
+ if (!account.accessToken || !account.igUserId) {
+ throw new ValidationError('This Instagram account has no access token. Reconnect it on the Accounts page.');
+ }
+ await subscribeToComments(account.igUserId, account.accessToken, context.signal);
+ const controls = await automationAccounts.markSubscribedForUser(account.id, userId);
+ await audit.recordForUser(userId, { action: 'automation_account.subscribed', subjectType: 'automation_account', subjectId: account.id });
+ return controls;
+ }
+
+ // turning a rule on is also when Instagram is asked for the account's comments; if that fails the rule is still
+ // saved, and the page shows the account as not receiving comments with a button to try again
+ async function ensureSubscribed(userId: string, account: Account): Promise<void> {
+ const controls = await automationAccounts.findForUser(account.id, userId);
+ if (controls?.subscribedAt) return;
+ try {
+ await subscribeAccount(userId, account);
+ } catch (err) {
+ context.log.warn('comment webhook subscription failed', { accountId: account.id, ...errorFields(err) });
+ }
+ }
+
+ return {
+ async overview(userId) {
+ const [allAccounts, userRules, controls] = await Promise.all([
+ accounts.listForUser(userId),
+ rules.listForUser(userId),
+ automationAccounts.listForUser(userId),
+ ]);
+ const byAccount = new Map(controls.map(item => [item.accountId, item]));
+ return {
+ rules: userRules,
+ accounts: allAccounts
+ .filter(account => account.platform === 'instagram')
+ .map(account => toState(account, byAccount.get(account.id) ?? defaultControls(account.id))),
+ settings: {
+ webhookConfigured: !!automation.verifyToken && automation.appSecrets.length > 0,
+ paused: automation.paused,
+ limits: automation.limits,
+ },
+ };
+ },
+
+ async createRule(userId, input) {
+ const account = await instagramAccount(userId, input.accountId);
+ checkMessageSize(input.replyText, input.linkUrl ?? null);
+ const now = new Date().toISOString();
+ const rule = await rules.create({
+ id: newRowId(),
+ accountId: account.id,
+ name: input.name,
+ keywords: input.keywords,
+ matchMode: input.matchMode ?? 'contains',
+ caseSensitive: input.caseSensitive ?? false,
+ mediaIds: input.mediaIds ?? [],
+ replyText: input.replyText,
+ linkUrl: input.linkUrl ?? null,
+ enabled: input.enabled ?? false,
+ hourlyLimit: input.hourlyLimit ?? null,
+ createdAt: now,
+ updatedAt: now,
+ }, userId);
+ await audit.recordForUser(userId, {
+ action: 'automation_rule.created', subjectType: 'automation_rule', subjectId: rule.id,
+ details: { accountId: account.id, enabled: rule.enabled },
+ });
+ if (rule.enabled) await ensureSubscribed(userId, account);
+ return rule;
+ },
+
+ async updateRule(userId, id, changes) {
+ const current = await ownedRule(userId, id);
+ checkMessageSize(changes.replyText ?? current.replyText, changes.linkUrl === undefined ? current.linkUrl : changes.linkUrl);
+ const rule = await rules.updateForUser(id, changes, userId);
+ if (!rule) throw new NotFoundError('Automation rule not found');
+ await audit.recordForUser(userId, {
+ action: 'automation_rule.updated', subjectType: 'automation_rule', subjectId: id,
+ details: { fields: Object.keys(changes), enabled: rule.enabled },
+ });
+ if (rule.enabled && !current.enabled) await ensureSubscribed(userId, await instagramAccount(userId, rule.accountId));
+ return rule;
+ },
+
+ // the copy starts off, so two identical rules never answer the same comments by surprise
+ async duplicateRule(userId, id) {
+ const source = await ownedRule(userId, id);
+ const now = new Date().toISOString();
+ const rule = await rules.create({
+ ...source,
+ id: newRowId(),
+ name: `${source.name.slice(0, MAX_NAME - COPY_SUFFIX.length)}${COPY_SUFFIX}`,
+ enabled: false,
+ createdAt: now,
+ updatedAt: now,
+ }, userId);
+ await audit.recordForUser(userId, {
+ action: 'automation_rule.duplicated', subjectType: 'automation_rule', subjectId: rule.id, details: { from: source.id },
+ });
+ return rule;
+ },
+
+ async deleteRule(userId, id) {
+ if (!await rules.deleteForUser(id, userId)) throw new NotFoundError('Automation rule not found');
+ await audit.recordForUser(userId, { action: 'automation_rule.deleted', subjectType: 'automation_rule', subjectId: id });
+ },
+
+ test(input) {
+ const rule = {
+ keywords: input.keywords,
+ matchMode: input.matchMode ?? 'contains',
+ caseSensitive: input.caseSensitive ?? false,
+ mediaIds: input.mediaIds ?? [],
+ };
+ const message = composeReply(input.replyText, input.linkUrl ?? null);
+ const keyword = coversMedia(rule, input.mediaId ?? null) ? matchedKeyword(input.comment, rule) : null;
+ return { matched: keyword !== null, keyword, message, messageBytes: messageBytes(message), maxMessageBytes: MAX_MESSAGE_BYTES };
+ },
+
+ async activity(userId, query) {
+ const items = await comments.listForUser(userId, query);
+ return { items, nextBefore: items.length === query.limit ? items[items.length - 1].createdAt : null };
+ },
+
+ async stats(userId, query) {
+ const to = query.to ?? new Date().toISOString();
+ const from = query.from ?? new Date(Date.parse(to) - DEFAULT_STATS_DAYS * DAY_MS).toISOString();
+ if (Date.parse(from) >= Date.parse(to)) throw new ValidationError('from must be earlier than to');
+ const stats = await comments.statsForUser(userId, { from, to, accountId: query.accountId, ruleId: query.ruleId });
+ return { from, to, stats };
+ },
+
+ async retry(userId, commentRowId) {
+ const item = await comments.requeueForUser(commentRowId, userId);
+ if (!item) {
+ const existing = await comments.findForUser(commentRowId, userId);
+ if (!existing) throw new NotFoundError('Activity item not found');
+ throw new ConflictError('Only a failed, skipped or review item inside the 7 days Instagram allows can be retried');
+ }
+ await audit.recordForUser(userId, { action: 'automation_comment.retried', subjectType: 'automation_comment', subjectId: commentRowId });
+ return item;
+ },
+
+ async setPaused(userId, accountId, paused) {
+ const account = await instagramAccount(userId, accountId);
+ const controls = await automationAccounts.setPausedForUser(account.id, userId, paused);
+ // held replies go out on the next run instead of waiting for their next check
+ if (!paused) await comments.releaseHeldForAccount(account.id, userId);
+ await audit.recordForUser(userId, {
+ action: paused ? 'automation_account.paused' : 'automation_account.resumed', subjectType: 'automation_account', subjectId: account.id,
+ });
+ return toState(account, controls);
+ },
+
+ async subscribe(userId, accountId) {
+ const account = await instagramAccount(userId, accountId);
+ await subscribeAccount(userId, account);
+ return state(userId, account);
+ },
+ };
+}
diff --git a/backend/services/automationWebhookService.ts b/backend/services/automationWebhookService.ts
new file mode 100644
index 0000000..ac1cde7
--- /dev/null
+++ b/backend/services/automationWebhookService.ts
@@ -0,0 +1,109 @@
+import { pickRule } from '../lib/automationMatching.ts';
+import { expiresAtFor } from '../lib/automationDelivery.ts';
+import { ForbiddenError, NotConfiguredError } from '../lib/errors.ts';
+import { newRowId } from '../lib/ids.ts';
+import { verifyTokenMatches } from '../lib/metaWebhookSignature.ts';
+import type { InstagramCommentEvent, InstagramWebhook } from '../validators/instagramWebhookValidators.ts';
+import type { WebhookVerification } from '../validators/automationValidators.ts';
+import type { AutomationConfig } from '../lib/config.ts';
+import type { AutomationRuleRepository, WebhookRule } from '../repositories/automationRuleRepository.ts';
+import type { AutomationCommentRepository, NewAutomationComment } from '../repositories/automationCommentRepository.ts';
+import type { RequestContext } from '../types/context.ts';
+
+export interface AutomationWebhookDeps {
+ rules: AutomationRuleRepository;
+ comments: AutomationCommentRepository;
+ automation: AutomationConfig;
+ context: RequestContext;
+}
+
+export interface IngestResult {
+ stored: number;
+ duplicates: number;
+ // the new comments that matched a rule, for the request to start sending right away
+ queuedIds: string[];
+}
+
+export interface AutomationWebhookService {
+ challengeAnswer(verification: WebhookVerification): Promise<string>;
+ ingest(webhook: InstagramWebhook): Promise<IngestResult>;
+}
+
+// Instagram comments are at most 2,200 characters; the column has the same limit
+const MAX_TEXT = 2200;
+
+function newComment(event: InstagramCommentEvent, owner: WebhookRule, fields: Pick<NewAutomationComment, 'ruleId' | 'status' | 'statusReason'>): NewAutomationComment {
+ const queued = fields.status === 'queued';
+ return {
+ id: newRowId(),
+ userId: owner.userId,
+ accountId: owner.accountId,
+ igUserId: event.igUserId,
+ commentId: event.commentId,
+ mediaId: event.mediaId,
+ fromId: event.fromId,
+ // the words and the author are kept only for comments a rule answers
+ fromUsername: queued ? event.fromUsername : null,
+ text: queued ? event.text?.slice(0, MAX_TEXT) ?? null : null,
+ nextAttemptAt: queued ? new Date().toISOString() : null,
+ notifiedAt: new Date(event.notifiedAt).toISOString(),
+ expiresAt: expiresAtFor(new Date(event.notifiedAt)),
+ ...fields,
+ };
+}
+
+// the first rule of the oldest connected account owns a comment no rule answers, so it is still counted once
+function classify(event: InstagramCommentEvent, rules: WebhookRule[]): NewAutomationComment {
+ const owner = rules[0];
+ if (event.fromId !== null && event.fromId === event.igUserId) return newComment(event, owner, { ruleId: null, status: 'ignored', statusReason: 'own_comment' });
+ if (!event.text) return newComment(event, owner, { ruleId: null, status: 'ignored', statusReason: 'no_text' });
+ const match = pickRule(rules, event.text, event.mediaId);
+ if (!match) return newComment(event, owner, { ruleId: null, status: 'ignored', statusReason: 'no_match' });
+ return newComment(event, match.rule, { ruleId: match.rule.id, status: 'queued', statusReason: null });
+}
+
+// stores what a webhook delivered before it is acknowledged; comments for accounts without an enabled rule are not kept
+export function createAutomationWebhookService({ rules, comments, automation, context }: AutomationWebhookDeps): AutomationWebhookService {
+ return {
+ // Meta checks the callback by sending the Verify Token from its dashboard and expects the challenge back
+ async challengeAnswer({ mode, verifyToken, challenge }) {
+ if (!automation.verifyToken) {
+ throw new NotConfiguredError('Instagram webhooks are not set up: the INSTAGRAM_WEBHOOK_VERIFY_TOKEN Worker secret is missing');
+ }
+ if (mode !== 'subscribe' || !challenge || !verifyToken || !await verifyTokenMatches(automation.verifyToken, verifyToken)) {
+ throw new ForbiddenError('The verify token does not match the one set on this server');
+ }
+ return challenge;
+ },
+
+ async ingest(webhook) {
+ const byAccount = new Map<string, InstagramCommentEvent[]>();
+ for (const event of webhook.comments) byAccount.set(event.igUserId, [...(byAccount.get(event.igUserId) ?? []), event]);
+
+ const rows: NewAutomationComment[] = [];
+ for (const [igUserId, events] of byAccount) {
+ const accountRules = await rules.listEnabledForInstagramUser(igUserId);
+ if (accountRules.length === 0) continue;
+ // one notification can repeat a comment; the first copy is the one kept
+ const seen = new Set<string>();
+ for (const event of events) {
+ if (seen.has(event.commentId)) continue;
+ seen.add(event.commentId);
+ rows.push(classify(event, accountRules));
+ }
+ }
+
+ const inserted = await comments.insertMany(rows);
+ const queuedIds = inserted.filter(row => row.status === 'queued').map(row => row.id);
+ const result = { stored: inserted.length, duplicates: rows.length - inserted.length, queuedIds };
+ context.log.info('instagram webhook stored', {
+ comments: webhook.comments.length,
+ unsupported: webhook.unsupported,
+ stored: result.stored,
+ duplicates: result.duplicates,
+ queued: queuedIds.length,
+ });
+ return result;
+ },
+ };
+}
diff --git a/backend/services/instagram/instagramApi.ts b/backend/services/instagram/instagramApi.ts
index d838aef..9b01288 100644
--- a/backend/services/instagram/instagramApi.ts
+++ b/backend/services/instagram/instagramApi.ts
@@ -48,7 +48,7 @@ interface InstagramApiProfile {
website?: string;
}
-function buildGraphUrl(endpoint: string, params: GraphParams): URL {
+export function buildGraphUrl(endpoint: string, params: GraphParams = {}): URL {
const needsVersion = !UNVERSIONED_PREFIXES.some(prefix => endpoint.startsWith(prefix));
const base = needsVersion ? `${IG_GRAPH_URL}/${IG_API_VERSION}` : IG_GRAPH_URL;
const url = new URL(`${base}${endpoint}`);
diff --git a/backend/services/instagram/instagramMessaging.ts b/backend/services/instagram/instagramMessaging.ts
new file mode 100644
index 0000000..970bef9
--- /dev/null
+++ b/backend/services/instagram/instagramMessaging.ts
@@ -0,0 +1,66 @@
+import { buildGraphUrl, igPost } from './instagramApi.ts';
+import { UpstreamError, isAbortError } from '../../lib/errors.ts';
+import { redactUrls } from '../../lib/redact.ts';
+import type { SendResult } from '../../lib/automationDelivery.ts';
+import type { InstagramApiErrorBody } from './instagramApi.ts';
+
+// a webhook's background work has 30 seconds in all, so one send may take a third of it
+const SEND_TIMEOUT_MS = 10_000;
+// the Workers runtime refuses a fetch past the run's subrequest allowance before anything leaves
+const SUBREQUEST_LIMIT = /too many subrequests/i;
+// the webhook fields the automation needs; Instagram sends every field the app subscribes to in the Meta dashboard
+const SUBSCRIBED_FIELDS = 'comments';
+
+interface PrivateReplyBody extends InstagramApiErrorBody {
+ recipient_id?: string;
+ message_id?: string;
+}
+
+interface SubscribeBody {
+ success?: boolean;
+}
+
+// answers instead of throwing, because each failure needs its code to decide between retrying, waiting and stopping;
+// the request is never repeated here, since a repeat after a lost answer could message the person twice
+export async function sendPrivateReply(igUserId: string, accessToken: string, commentId: string, text: string, signal?: AbortSignal): Promise<SendResult> {
+ const timeout = AbortSignal.timeout(SEND_TIMEOUT_MS);
+ let response: Response;
+ try {
+ response = await fetch(buildGraphUrl(`/${igUserId}/messages`).toString(), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` },
+ body: JSON.stringify({ recipient: { comment_id: commentId }, message: { text } }),
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
+ });
+ } catch (err) {
+ if (SUBREQUEST_LIMIT.test((err as Error).message ?? '')) return { kind: 'not_sent', message: 'this run reached its request limit' };
+ return { kind: 'ambiguous', message: isAbortError(err) ? 'the request timed out' : 'the connection failed' };
+ }
+
+ const usageHeader = response.headers.get('x-business-use-case-usage');
+ let body: PrivateReplyBody;
+ try {
+ body = await response.json() as PrivateReplyBody;
+ } catch {
+ // an accepted request whose answer cannot be read may still have delivered the message
+ if (response.ok) return { kind: 'ambiguous', message: 'its answer could not be read' };
+ return { kind: 'error', httpStatus: response.status, message: `HTTP ${response.status}`, usageHeader };
+ }
+
+ if (response.ok && !body.error) return { kind: 'accepted', messageId: body.message_id ?? null };
+ const error = body.error ?? {};
+ return {
+ kind: 'error',
+ code: error.code,
+ subcode: error.error_subcode,
+ httpStatus: response.status,
+ message: redactUrls(error.message || body.error_message || `HTTP ${response.status}`),
+ usageHeader,
+ };
+}
+
+// asks Instagram to send this account's comments to the app's webhook
+export async function subscribeToComments(igUserId: string, accessToken: string, signal?: AbortSignal): Promise<void> {
+ const result = await igPost<SubscribeBody>(`/${igUserId}/subscribed_apps`, { subscribed_fields: SUBSCRIBED_FIELDS, access_token: accessToken }, signal);
+ if (result.success !== true) throw new UpstreamError('Instagram did not confirm the webhook subscription for this account. Try again in a moment.');
+}
diff --git a/backend/services/instagramConnectService.ts b/backend/services/instagramConnectService.ts
index 491ac97..9c89ddf 100644
--- a/backend/services/instagramConnectService.ts
+++ b/backend/services/instagramConnectService.ts
@@ -1,20 +1,22 @@
import { buildAuthorizationUrl, exchangeCodeForToken, isOAuthConfigured, upgradeToLongLivedToken } from './instagram/instagramOAuth.ts';
import { fetchInstagramProfile } from './instagram/instagramApi.ts';
-import { buildInstagramAccount } from './accountFactory.ts';
+import { buildInstagramAccount, tokenExpiryIso } from './accountFactory.ts';
import { verifyOAuthState } from '../lib/oauthState.ts';
import { NotConfiguredError, ValidationError } from '../lib/errors.ts';
import type { ConfiguredInstagramOAuth } from './instagram/instagramOAuth.ts';
import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { AuditRepository } from '../repositories/auditRepository.ts';
import type { AppConfig } from '../lib/config.ts';
import type { RequestContext } from '../types/context.ts';
export interface InstagramConnectDeps {
accounts: AccountRepository;
+ audit: AuditRepository;
config: AppConfig;
context: RequestContext;
}
-export type InstagramConnectOutcome = 'already_added' | 'connected';
+export type InstagramConnectOutcome = 'reconnected' | 'connected';
export interface InstagramConnectService {
readonly configured: boolean;
@@ -25,7 +27,7 @@ export interface InstagramConnectService {
}
// connects an account through Instagram's OAuth: the user id travels in the signed state, not in a session
-export function createInstagramConnectService({ accounts, config, context }: InstagramConnectDeps): InstagramConnectService {
+export function createInstagramConnectService({ accounts, audit, config, context }: InstagramConnectDeps): InstagramConnectService {
const { signal } = context;
const oauth = config.instagram;
@@ -50,10 +52,18 @@ export function createInstagramConnectService({ accounts, config, context }: Ins
const profile = await fetchInstagramProfile(null, token, signal);
if (!profile.igUserId) throw new ValidationError('Could not get Instagram User ID. Account must be a Business or Creator account.');
- const existing = await accounts.listForUser(userId);
- if (existing.some(account => account.platform === 'instagram' && account.igUserId === profile.igUserId)) return 'already_added';
+ // connecting an account again renews its token in place, which keeps its rules and history
+ const existing = (await accounts.listForUser(userId)).find(account => account.platform === 'instagram' && account.igUserId === profile.igUserId);
+ if (existing) {
+ const now = new Date().toISOString();
+ await accounts.updateForUser(existing.id, { accessToken: token, tokenExpiresAt: tokenExpiryIso(expiresIn), lastUpdated: now }, userId);
+ await audit.recordForUser(userId, { action: 'account.reconnected', subjectType: 'account', subjectId: existing.id, details: { platform: 'instagram' } });
+ return 'reconnected';
+ }
- await accounts.create(buildInstagramAccount(profile, token, expiresIn), userId);
+ const account = buildInstagramAccount(profile, token, expiresIn);
+ await accounts.create(account, userId);
+ await audit.recordForUser(userId, { action: 'account.connected', subjectType: 'account', subjectId: account.id, details: { platform: 'instagram' } });
return 'connected';
},
};
diff --git a/backend/services/retentionService.ts b/backend/services/retentionService.ts
new file mode 100644
index 0000000..7354045
--- /dev/null
+++ b/backend/services/retentionService.ts
@@ -0,0 +1,38 @@
+import type { AutomationCommentRepository } from '../repositories/automationCommentRepository.ts';
+import type { AuditRepository } from '../repositories/auditRepository.ts';
+import type { RequestContext } from '../types/context.ts';
+
+export interface RetentionDeps {
+ comments: AutomationCommentRepository;
+ audit: AuditRepository;
+ context: RequestContext;
+}
+
+export interface RetentionRun {
+ comments: number;
+ auditEvents: number;
+}
+
+export interface RetentionService {
+ purge(now?: number): Promise<RetentionRun>;
+}
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+// received comments and their reply attempts are kept 90 days: long enough to answer "did they get it?", short for personal data
+export const COMMENT_RETENTION_DAYS = 90;
+// who connected, removed or changed what is kept a year
+export const AUDIT_RETENTION_DAYS = 365;
+
+// the daily cron's deletes across all users; a comment's attempts go with it through the foreign key
+export function createRetentionService({ comments, audit, context }: RetentionDeps): RetentionService {
+ return {
+ async purge(now = Date.now()) {
+ const run = {
+ comments: await comments.deleteCreatedBefore(new Date(now - COMMENT_RETENTION_DAYS * DAY_MS).toISOString()),
+ auditEvents: await audit.deleteCreatedBefore(new Date(now - AUDIT_RETENTION_DAYS * DAY_MS).toISOString()),
+ };
+ context.log.info('retention purge', { ...run });
+ return run;
+ },
+ };
+}
diff --git a/backend/tests/fixtures/accountsRoutes.delete.golden.json b/backend/tests/fixtures/accountsRoutes.delete.golden.json
index 50b92ae..04727ee 100644
--- a/backend/tests/fixtures/accountsRoutes.delete.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.delete.golden.json
@@ -78,6 +78,21 @@
]
]
},
+ {
+ "type": "insert",
+ "table": "audit_events",
+ "values": {
+ "id": "00000000-0000-4000-8000-000000000001",
+ "user_id": "user-1",
+ "action": "account.removed",
+ "subject_type": "account",
+ "subject_id": "rd2",
+ "details": {
+ "platform": "reddit"
+ }
+ },
+ "filters": []
+ },
{
"type": "select",
"table": "accounts",
diff --git a/backend/tests/fixtures/fakeAutomationQueue.ts b/backend/tests/fixtures/fakeAutomationQueue.ts
new file mode 100644
index 0000000..307448d
--- /dev/null
+++ b/backend/tests/fixtures/fakeAutomationQueue.ts
@@ -0,0 +1,205 @@
+// an in-memory twin of claim_automation_comments, reserve_automation_send, finish_automation_send and the release update,
+// following the same rules as the SQL in supabase/migrations (checked there on a local Postgres), so the processor can be
+// run against concurrency, limits and crashes without a database
+import type { AutomationCommentRepository, ClaimedComment, NewAutomationComment } from '../../repositories/automationCommentRepository.ts';
+import type { AutomationCommentStatus } from '../../../shared/types/automation.ts';
+
+export interface QueueRow {
+ id: string;
+ userId: string;
+ accountId: string;
+ ruleId: string | null;
+ igUserId: string;
+ commentId: string;
+ fromId: string | null;
+ status: AutomationCommentStatus;
+ statusReason: string | null;
+ errorMessage: string | null;
+ attempts: number;
+ nextAttemptAt: string | null;
+ claimedAt: string | null;
+ messageId: string | null;
+ expiresAt: string;
+}
+
+export interface QueueAttempt {
+ id: string;
+ commentRowId: string;
+ userId: string;
+ accountId: string;
+ ruleId: string | null;
+ recipientId: string | null;
+ outcome: string;
+ startedAt: number;
+}
+
+export interface QueueRule {
+ id: string;
+ enabled: boolean;
+ replyText: string;
+ linkUrl: string | null;
+ hourlyLimit: number | null;
+}
+
+export interface QueueControls {
+ paused: boolean;
+ pausedReason: string | null;
+ cooldownUntil: string | null;
+}
+
+export interface FakeQueue extends AutomationCommentRepository {
+ rows: QueueRow[];
+ attempts: QueueAttempt[];
+ rules: Map<string, QueueRule>;
+ controls: Map<string, QueueControls>;
+ tokens: Map<string, string | null>;
+ // makes the next calls of one method throw, as a database outage would
+ failNext(method: 'claim' | 'reserve' | 'finish' | 'release', times?: number): void;
+}
+
+const HOUR = 60 * 60 * 1000;
+
+export function queueRow(id: string, overrides: Partial<QueueRow> = {}): QueueRow {
+ return {
+ id, userId: 'user-1', accountId: 'ig1', ruleId: 'rule-guide', igUserId: '1784', commentId: `c-${id}`, fromId: `fan-${id}`,
+ status: 'queued', statusReason: null, errorMessage: null, attempts: 0, nextAttemptAt: new Date(Date.now() - 1000).toISOString(),
+ claimedAt: null, messageId: null, expiresAt: new Date(Date.now() + 6 * 24 * HOUR).toISOString(), ...overrides,
+ };
+}
+
+export function fakeAutomationQueue(rows: QueueRow[] = []): FakeQueue {
+ const failures = new Map<string, number>();
+ const rules = new Map<string, QueueRule>([['rule-guide', { id: 'rule-guide', enabled: true, replyText: 'Here is your guide', linkUrl: 'https://example.com/guide', hourlyLimit: null }]]);
+ const controls = new Map<string, QueueControls>();
+ const tokens = new Map<string, string | null>([['ig1', 'TOKEN-1'], ['ig2', 'TOKEN-2']]);
+ const attempts: QueueAttempt[] = [];
+
+ function failing(method: string): void {
+ const left = failures.get(method) ?? 0;
+ if (left > 0) {
+ failures.set(method, left - 1);
+ throw new Error(`database unavailable during ${method}`);
+ }
+ }
+
+ const now = () => Date.now();
+ const iso = (ms: number) => new Date(ms).toISOString();
+ const isDue = (row: QueueRow, staleBefore: number) =>
+ ((row.status === 'queued' || row.status === 'retry_wait') && Date.parse(row.nextAttemptAt!) <= now())
+ || (row.status === 'processing' && Date.parse(row.claimedAt!) < staleBefore);
+
+ function freeAt(window: QueueAttempt[], limit: number): string | null {
+ return window.length >= limit ? iso(Math.min(...window.map(attempt => attempt.startedAt)) + HOUR) : null;
+ }
+
+ const queue: FakeQueue = {
+ rows,
+ attempts,
+ rules,
+ controls,
+ tokens,
+ failNext(method, times = 1) { failures.set(method, times); },
+
+ async insertMany(comments: NewAutomationComment[]) {
+ const inserted = comments.filter(comment => !rows.some(row => row.igUserId === comment.igUserId && row.commentId === comment.commentId));
+ for (const comment of inserted) {
+ rows.push(queueRow(comment.id, {
+ userId: comment.userId, accountId: comment.accountId, ruleId: comment.ruleId, igUserId: comment.igUserId,
+ commentId: comment.commentId, fromId: comment.fromId, status: comment.status, statusReason: comment.statusReason,
+ nextAttemptAt: comment.nextAttemptAt, expiresAt: comment.expiresAt,
+ }));
+ }
+ return inserted;
+ },
+
+ async claim({ limit, perAccount, leaseSeconds, ids }) {
+ failing('claim');
+ const staleBefore = now() - leaseSeconds * 1000;
+ for (const row of rows) {
+ if (row.status === 'sending' && Date.parse(row.claimedAt!) < staleBefore) {
+ Object.assign(row, { status: 'needs_review', statusReason: 'interrupted', claimedAt: null });
+ attempts.filter(attempt => attempt.commentRowId === row.id && attempt.outcome === 'sending').forEach(attempt => { attempt.outcome = 'ambiguous'; });
+ }
+ }
+ const perAccountCount = new Map<string, number>();
+ const due = rows
+ .filter(row => isDue(row, staleBefore) && (!ids || ids.includes(row.id)))
+ .sort((a, b) => Date.parse(a.nextAttemptAt ?? a.claimedAt!) - Date.parse(b.nextAttemptAt ?? b.claimedAt!));
+ const claimed: ClaimedComment[] = [];
+ for (const row of due) {
+ if (claimed.length >= limit) break;
+ const taken = perAccountCount.get(row.accountId) ?? 0;
+ if (taken >= perAccount) continue;
+ perAccountCount.set(row.accountId, taken + 1);
+ Object.assign(row, { status: 'processing', claimedAt: iso(now()) });
+ const rule = row.ruleId ? rules.get(row.ruleId) : undefined;
+ claimed.push({
+ id: row.id, userId: row.userId, accountId: row.accountId, ruleId: row.ruleId, igUserId: row.igUserId, commentId: row.commentId,
+ fromId: row.fromId, attempts: row.attempts, expiresAt: row.expiresAt, ruleEnabled: rule?.enabled ?? false,
+ replyText: rule?.replyText ?? null, linkUrl: rule?.linkUrl ?? null, accessToken: tokens.get(row.accountId) ?? null,
+ });
+ }
+ return claimed;
+ },
+
+ async reserve(id, attemptId, limits) {
+ failing('reserve');
+ const row = rows.find(candidate => candidate.id === id && candidate.status === 'processing');
+ if (!row) return { outcome: 'gone', retryAt: null };
+ const control = controls.get(row.accountId);
+ if (control?.paused) return { outcome: 'paused', retryAt: null };
+ if (control?.cooldownUntil && Date.parse(control.cooldownUntil) > now()) return { outcome: 'cooldown', retryAt: control.cooldownUntil };
+ const otherReplies = new Set(attempts
+ .filter(attempt => attempt.accountId === row.accountId && attempt.recipientId === row.fromId
+ && attempt.startedAt > now() - 24 * HOUR && attempt.commentRowId !== row.id)
+ .map(attempt => attempt.commentRowId));
+ if (row.fromId && otherReplies.size >= limits.recipientDaily) return { outcome: 'recipient_limit', retryAt: null };
+ const lastHour = attempts.filter(attempt => attempt.startedAt > now() - HOUR);
+ const ruleLimit = row.ruleId ? rules.get(row.ruleId)?.hourlyLimit ?? null : null;
+ const scopes: [ReturnType<typeof freeAt>, 'rule_limit' | 'account_limit' | 'user_limit' | 'global_limit'][] = [
+ [ruleLimit === null ? null : freeAt(lastHour.filter(attempt => attempt.ruleId === row.ruleId), ruleLimit), 'rule_limit'],
+ [freeAt(lastHour.filter(attempt => attempt.accountId === row.accountId), limits.accountHourly), 'account_limit'],
+ [freeAt(lastHour.filter(attempt => attempt.userId === row.userId), limits.userHourly), 'user_limit'],
+ [freeAt(lastHour, limits.globalHourly), 'global_limit'],
+ ];
+ for (const [retryAt, outcome] of scopes) if (retryAt) return { outcome, retryAt };
+ Object.assign(row, { status: 'sending', claimedAt: iso(now()), attempts: row.attempts + 1 });
+ attempts.push({ id: attemptId, commentRowId: row.id, userId: row.userId, accountId: row.accountId, ruleId: row.ruleId, recipientId: row.fromId, outcome: 'sending', startedAt: now() });
+ return { outcome: 'ok', retryAt: null };
+ },
+
+ async finish(id, attemptId, plan) {
+ failing('finish');
+ const row = rows.find(candidate => candidate.id === id
+ && (candidate.status === 'sending' || (candidate.status === 'needs_review' && candidate.statusReason === 'interrupted')));
+ if (!row) return false;
+ Object.assign(row, {
+ status: plan.status, statusReason: plan.reason, errorMessage: plan.errorMessage, messageId: plan.messageId ?? row.messageId,
+ nextAttemptAt: plan.nextAttemptAt, claimedAt: null,
+ });
+ const attempt = attempts.find(candidate => candidate.id === attemptId && candidate.commentRowId === id);
+ if (attempt) attempt.outcome = plan.outcome;
+ const control = controls.get(row.accountId) ?? { paused: false, pausedReason: null, cooldownUntil: null };
+ if (plan.cooldownUntil) control.cooldownUntil = control.cooldownUntil && control.cooldownUntil > plan.cooldownUntil ? control.cooldownUntil : plan.cooldownUntil;
+ if (plan.pauseReason) Object.assign(control, { paused: true, pausedReason: plan.pauseReason });
+ controls.set(row.accountId, control);
+ return true;
+ },
+
+ async release(id, plan) {
+ failing('release');
+ const row = rows.find(candidate => candidate.id === id && candidate.status === 'processing');
+ if (!row) return false;
+ Object.assign(row, { status: plan.status, statusReason: plan.reason, errorMessage: plan.errorMessage, nextAttemptAt: plan.nextAttemptAt, claimedAt: null });
+ return true;
+ },
+
+ async listForUser() { return []; },
+ async findForUser() { return null; },
+ async requeueForUser() { return null; },
+ async releaseHeldForAccount() {},
+ async statsForUser() { return { comments: {}, attempts: {} }; },
+ async deleteCreatedBefore() { return 0; },
+ };
+ return queue;
+}
diff --git a/backend/tests/fixtures/fakeFetch.ts b/backend/tests/fixtures/fakeFetch.ts
index 104d97c..b65312b 100644
--- a/backend/tests/fixtures/fakeFetch.ts
+++ b/backend/tests/fixtures/fakeFetch.ts
@@ -9,6 +9,7 @@ export interface FakeReply {
body: unknown;
status: number;
statusText: string;
+ headers?: Record<string, string>;
}
export type Responder = (request: RecordedRequest, count: number) => FakeReply | Error | Promise<FakeReply | Error>;
@@ -19,8 +20,8 @@ export interface FetchMock {
}
// replaces global fetch with a scripted responder and records each request
-export function reply(body: unknown, status = 200, statusText = 'OK'): FakeReply {
- return { body, status, statusText };
+export function reply(body: unknown, status = 200, statusText = 'OK', headers?: Record<string, string>): FakeReply {
+ return headers ? { body, status, statusText, headers } : { body, status, statusText };
}
export function installFetch(respond: Responder): FetchMock {
@@ -39,6 +40,7 @@ export function installFetch(respond: Responder): FetchMock {
status: outcome.status,
statusText: outcome.statusText,
ok: outcome.status >= 200 && outcome.status < 300,
+ headers: new Headers(outcome.headers ?? {}),
json: async () => outcome.body,
} as unknown as Response;
};
diff --git a/backend/tests/fixtures/fakeSupabase.ts b/backend/tests/fixtures/fakeSupabase.ts
index cdbbd85..236bcd9 100644
--- a/backend/tests/fixtures/fakeSupabase.ts
+++ b/backend/tests/fixtures/fakeSupabase.ts
@@ -3,14 +3,15 @@ import type { SupabaseClient } from '../../types/app.ts';
export type Row = Record<string, unknown>;
-type Filter = [column: string, value: unknown, operator?: 'lte' | 'lt' | 'neq'];
+type Filter = [column: string, value: unknown, operator?: 'lte' | 'lt' | 'neq' | 'gte' | 'gt' | 'in'];
interface Action {
type: 'select' | 'update' | 'insert' | 'upsert' | 'delete' | 'rpc';
table: string;
columns?: string;
- values?: Row;
+ values?: Row | Row[];
onConflict?: string;
+ ignoreDuplicates?: boolean;
}
export type SupabaseCall = Action & { filters: Filter[] };
@@ -26,13 +27,20 @@ interface FakeQuery {
lte(column: string, value: unknown): FakeQuery;
lt(column: string, value: unknown): FakeQuery;
neq(column: string, value: unknown): FakeQuery;
+ gte(column: string, value: unknown): FakeQuery;
+ gt(column: string, value: unknown): FakeQuery;
+ in(column: string, values: unknown[]): FakeQuery;
order(): FakeQuery;
+ limit(count: number): FakeQuery;
single(): Promise<QueryResult>;
maybeSingle(): Promise<QueryResult>;
then(resolve: (result: QueryResult) => unknown, reject?: (reason: unknown) => unknown): Promise<unknown>;
}
-type Run = (action: Action, filters: Filter[]) => Row[];
+type Run = (action: Action, filters: Filter[], limit?: number) => Row[];
+
+// a database function the code calls with rpc(), run on the in-memory rows; the merge functions are built in
+export type RpcHandler = (args: Row, table: Row[]) => unknown;
// passed straight to code that expects a supabase client; calls and table expose what the fake recorded
export type FakeSupabase = SupabaseClient & { calls: SupabaseCall[]; table: Row[] };
@@ -45,6 +53,9 @@ function matchesFilter(row: Row, [column, value, operator]: Filter) {
if (operator === 'lte') return (row[column] as string) <= (value as string);
if (operator === 'lt') return row[column] != null && (row[column] as string) < (value as string);
if (operator === 'neq') return row[column] !== value;
+ if (operator === 'gte') return row[column] != null && (row[column] as string) >= (value as string);
+ if (operator === 'gt') return row[column] != null && (row[column] as string) > (value as string);
+ if (operator === 'in') return (value as unknown[]).includes(row[column]);
return row[column] === value;
}
@@ -88,6 +99,7 @@ function touch(row: Row): void {
function queryBuilder(action: Action, run: Run): FakeQuery {
const filters: Filter[] = [];
+ let limit: number | undefined;
const query: FakeQuery = {
select() { return query; },
eq(column: string, value: unknown) {
@@ -106,38 +118,73 @@ function queryBuilder(action: Action, run: Run): FakeQuery {
filters.push([column, value, 'neq']);
return query;
},
+ gte(column: string, value: unknown) {
+ filters.push([column, value, 'gte']);
+ return query;
+ },
+ gt(column: string, value: unknown) {
+ filters.push([column, value, 'gt']);
+ return query;
+ },
+ in(column: string, values: unknown[]) {
+ filters.push([column, values, 'in']);
+ return query;
+ },
+ // rows come back in the order they were stored; tests that page seed rows newest first
order() { return query; },
+ limit(count: number) {
+ limit = count;
+ return query;
+ },
maybeSingle() {
- const found = run(action, filters);
+ const found = run(action, filters, limit);
return Promise.resolve({ data: found[0] ?? null, error: null });
},
single() {
- const found = run(action, filters);
+ const found = run(action, filters, limit);
if (found.length === 0) return Promise.resolve({ data: null, error: { message: 'no rows' } });
return Promise.resolve({ data: found[0], error: null });
},
then(resolve: (result: QueryResult) => unknown, reject?: (reason: unknown) => unknown) {
- return Promise.resolve({ data: run(action, filters), error: null }).then(resolve, reject);
+ return Promise.resolve({ data: run(action, filters, limit), error: null }).then(resolve, reject);
},
};
return query;
}
-export function fakeSupabase(rows: Row[] = []): FakeSupabase {
+function asRows(values: Row | Row[] | undefined): Row[] {
+ return Array.isArray(values) ? values : [values!];
+}
+
+export function fakeSupabase(rows: Row[] = [], rpcHandlers: Record<string, RpcHandler> = {}): FakeSupabase {
const table = rows.map(copy);
const calls: SupabaseCall[] = [];
- function run(action: Action, filters: Filter[]) {
+ function run(action: Action, filters: Filter[], limit?: number) {
calls.push({ ...copy(action), filters: copy(filters) });
- const found = table.filter(row => inTable(row, action.table) && matchesFilters(row, filters));
+ const found = table.filter(row => inTable(row, action.table) && matchesFilters(row, filters)).slice(0, limit);
if (action.type === 'update') found.forEach(row => touch(Object.assign(row, copy(action.values))));
- if (action.type === 'insert') table.push({ _table: action.table, ...copy(action.values!) });
+ if (action.type === 'insert') {
+ const added = asRows(action.values).map(values => ({ _table: action.table, ...copy(values) }));
+ table.push(...added);
+ // insert().select() returns the inserted rows, as PostgREST does
+ return added.map(copy);
+ }
if (action.type === 'upsert') {
- const values = action.values!;
const keys = (action.onConflict ?? 'id').split(',');
- const existing = table.find(row => inTable(row, action.table) && keys.every(key => row[key] === values[key]));
- if (existing) touch(Object.assign(existing, copy(values)));
- else table.push({ _table: action.table, ...copy(values) });
+ const added: Row[] = [];
+ const written: Row[] = [];
+ for (const values of asRows(action.values)) {
+ const existing = table.find(row => inTable(row, action.table) && keys.every(key => row[key] === values[key]));
+ if (existing && !action.ignoreDuplicates) {
+ touch(Object.assign(existing, copy(values)));
+ written.push(existing);
+ }
+ if (!existing) added.push({ _table: action.table, ...copy(values) });
+ }
+ table.push(...added);
+ // upsert().select() returns the rows it wrote; with ignoreDuplicates that is only the inserted ones
+ return [...written, ...added].map(copy);
}
if (action.type === 'delete') {
found.forEach(row => table.splice(table.indexOf(row), 1));
@@ -150,14 +197,23 @@ export function fakeSupabase(rows: Row[] = []): FakeSupabase {
table,
rpc(name: string, args: Row) {
calls.push({ type: 'rpc', table: name, values: copy(args), filters: [] });
+ const handler = rpcHandlers[name];
+ if (handler) {
+ try {
+ return Promise.resolve({ data: copy(handler(args, table)), error: null });
+ } catch (err) {
+ return Promise.resolve({ data: null, error: { message: (err as Error).message } });
+ }
+ }
return Promise.resolve({ data: mergeInto(table, name, args), error: null });
},
from(name: string) {
return {
select: (columns: string) => queryBuilder({ type: 'select', table: name, columns }, run),
update: (values: Row) => queryBuilder({ type: 'update', table: name, values }, run),
- insert: (values: Row) => queryBuilder({ type: 'insert', table: name, values }, run),
- upsert: (values: Row, options: { onConflict?: string } = {}) => queryBuilder({ type: 'upsert', table: name, values, onConflict: options.onConflict }, run),
+ insert: (values: Row | Row[]) => queryBuilder({ type: 'insert', table: name, values }, run),
+ upsert: (values: Row | Row[], options: { onConflict?: string; ignoreDuplicates?: boolean } = {}) =>
+ queryBuilder({ type: 'upsert', table: name, values, onConflict: options.onConflict, ignoreDuplicates: options.ignoreDuplicates }, run),
delete: () => queryBuilder({ type: 'delete', table: name }, run),
};
},
diff --git a/backend/tests/fixtures/instagramAuth.callback.golden.json b/backend/tests/fixtures/instagramAuth.callback.golden.json
index e46a2b2..e41d937 100644
--- a/backend/tests/fixtures/instagramAuth.callback.golden.json
+++ b/backend/tests/fixtures/instagramAuth.callback.golden.json
@@ -43,7 +43,7 @@
{
"status": 302,
"body": "",
- "location": "https://app.example.com/accounts?ig_error=already_added"
+ "location": "https://app.example.com/accounts?ig_connected=reconnected"
},
{
"status": 302,
@@ -198,6 +198,21 @@
},
"filters": []
},
+ {
+ "type": "insert",
+ "table": "audit_events",
+ "values": {
+ "id": "00000000-0000-4000-8000-000000000002",
+ "user_id": "user-1",
+ "action": "account.connected",
+ "subject_type": "account",
+ "subject_id": "00000000-0000-4000-8000-000000000001",
+ "details": {
+ "platform": "instagram"
+ }
+ },
+ "filters": []
+ },
{
"type": "select",
"table": "accounts",
@@ -213,7 +228,7 @@
"type": "insert",
"table": "accounts",
"values": {
- "id": "00000000-0000-4000-8000-000000000002",
+ "id": "00000000-0000-4000-8000-000000000003",
"user_id": "user-1",
"platform": "instagram",
"data": {
@@ -234,6 +249,21 @@
},
"filters": []
},
+ {
+ "type": "insert",
+ "table": "audit_events",
+ "values": {
+ "id": "00000000-0000-4000-8000-000000000004",
+ "user_id": "user-1",
+ "action": "account.connected",
+ "subject_type": "account",
+ "subject_id": "00000000-0000-4000-8000-000000000003",
+ "details": {
+ "platform": "instagram"
+ }
+ },
+ "filters": []
+ },
{
"type": "select",
"table": "accounts",
@@ -244,6 +274,35 @@
"user-1"
]
]
+ },
+ {
+ "type": "rpc",
+ "table": "merge_account_data",
+ "values": {
+ "p_id": "ig1",
+ "p_user_id": "user-1",
+ "p_patch": {
+ "accessToken": "SHORT_DUP",
+ "tokenExpiresAt": null,
+ "lastUpdated": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ "filters": []
+ },
+ {
+ "type": "insert",
+ "table": "audit_events",
+ "values": {
+ "id": "00000000-0000-4000-8000-000000000005",
+ "user_id": "user-1",
+ "action": "account.reconnected",
+ "subject_type": "account",
+ "subject_id": "ig1",
+ "details": {
+ "platform": "instagram"
+ }
+ },
+ "filters": []
}
],
"logs": [
diff --git a/backend/tests/fixtures/metaWebhook.ts b/backend/tests/fixtures/metaWebhook.ts
new file mode 100644
index 0000000..33d7891
--- /dev/null
+++ b/backend/tests/fixtures/metaWebhook.ts
@@ -0,0 +1,36 @@
+// signs and builds Instagram webhook notifications the way Meta sends them, for the webhook tests
+
+export async function metaSignature(secret: string, body: ArrayBuffer | string): Promise<string> {
+ const bytes = typeof body === 'string' ? new TextEncoder().encode(body) : new Uint8Array(body);
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
+ const signature = new Uint8Array(await crypto.subtle.sign('HMAC', key, bytes));
+ return `sha256=${[...signature].map(byte => byte.toString(16).padStart(2, '0')).join('')}`;
+}
+
+export interface CommentChange {
+ id: string;
+ text?: string;
+ fromId?: string;
+ fromUsername?: string;
+ mediaId?: string;
+}
+
+// one notification for one professional account, with a comments change per comment
+export function commentNotification(igUserId: string, time: number, changes: CommentChange[]): Record<string, unknown> {
+ return {
+ object: 'instagram',
+ entry: [{
+ id: igUserId,
+ time,
+ changes: changes.map(change => ({
+ field: 'comments',
+ value: {
+ id: change.id,
+ text: change.text,
+ from: { id: change.fromId ?? `fan-${change.id}`, username: change.fromUsername ?? `fan_${change.id}` },
+ media: { id: change.mediaId ?? '9001', media_product_type: 'REELS' },
+ },
+ })),
+ }],
+ };
+}
diff --git a/backend/tests/fixtures/routeHarness.ts b/backend/tests/fixtures/routeHarness.ts
index 64e673e..7ca4b46 100644
--- a/backend/tests/fixtures/routeHarness.ts
+++ b/backend/tests/fixtures/routeHarness.ts
@@ -7,6 +7,8 @@ export interface CallOptions {
json?: unknown;
headers?: Record<string, string>;
env?: Partial<Env>;
+ // collects waitUntil work, for routes that answer first and work after
+ executionCtx?: ExecutionContext;
}
export type RouteStep = [method: string, path: string, json?: unknown, env?: Partial<Env>];
@@ -43,7 +45,7 @@ export async function callRoute(app: Hono<AppEnv>, method: string, path: string,
init.headers = { 'Content-Type': 'application/json' };
}
if (options.headers) init.headers = { ...init.headers, ...options.headers };
- const response = await app.request(path, init, options.env ?? {});
+ const response = await app.request(path, init, options.env ?? {}, options.executionCtx);
const result: RouteResult = { status: response.status, body: await response.text() };
const location = response.headers.get('location');
if (location !== null) result.location = location;
@@ -57,3 +59,16 @@ export function fakeRedis(): FakeRedis {
async del(key: string) { deleted.push(key); },
} as unknown as FakeRedis;
}
+
+export type BackgroundWork = ExecutionContext & { settle(): Promise<void> };
+
+// an execution context whose waitUntil work a test can wait for after the response
+export function backgroundWork(): BackgroundWork {
+ const pending: Promise<unknown>[] = [];
+ return {
+ waitUntil(promise: Promise<unknown>) { pending.push(promise); },
+ passThroughOnException() {},
+ props: {},
+ async settle() { await Promise.all(pending); },
+ } as unknown as BackgroundWork;
+}
diff --git a/backend/tests/jobs/scheduled.test.ts b/backend/tests/jobs/scheduled.test.ts
new file mode 100644
index 0000000..e57a0e2
--- /dev/null
+++ b/backend/tests/jobs/scheduled.test.ts
@@ -0,0 +1,25 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { DAILY_CRON, EVERY_FIVE_MINUTES_CRON, cronPlan } from '../../jobs/scheduled.ts';
+
+const at = (time: string) => Date.parse(`2026-10-16T${time}:00Z`);
+
+test('the five minute trigger publishes on the quarter hour and sweeps the reply queue on every other run', () => {
+ assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:00')), 'publish_then_sweep');
+ assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:15')), 'publish_then_sweep');
+ assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:45')), 'publish_then_sweep');
+ assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:05')), 'sweep');
+ assert.equal(cronPlan(EVERY_FIVE_MINUTES_CRON, at('12:50')), 'sweep');
+});
+
+test('the daily trigger runs the upkeep and an unknown cron runs nothing', () => {
+ assert.equal(cronPlan(DAILY_CRON, at('00:00')), 'daily');
+ assert.equal(cronPlan('*/15 * * * *', at('12:15')), 'none');
+});
+
+test('the crons in wrangler.toml are the ones the Worker dispatches', () => {
+ const toml = readFileSync(new URL('../../wrangler.toml', import.meta.url), 'utf8');
+ assert.match(toml, /crons = \["\*\/5 \* \* \* \*", "0 0 \* \* \*"\]/);
+ assert.deepEqual([EVERY_FIVE_MINUTES_CRON, DAILY_CRON], ['*/5 * * * *', '0 0 * * *']);
+});
diff --git a/backend/tests/lib/automationDelivery.test.ts b/backend/tests/lib/automationDelivery.test.ts
new file mode 100644
index 0000000..fbef59c
--- /dev/null
+++ b/backend/tests/lib/automationDelivery.test.ts
@@ -0,0 +1,162 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ MAX_SEND_ATTEMPTS, REPLY_WINDOW_MS, classifySendError, composeReply, cooldownFromUsage, expiresAtFor, finishPlan, messageBytes,
+ readinessPlan, releasePlan, retryDelayMs,
+} from '../../lib/automationDelivery.ts';
+import type { SendResult } from '../../lib/automationDelivery.ts';
+
+const NOW = Date.parse('2026-10-16T12:00:00Z');
+const MINUTE = 60 * 1000;
+const job = (attempts = 1, expiresIn = 6 * 24 * 60 * MINUTE) => ({ attempts, expiresAt: new Date(NOW + expiresIn).toISOString() });
+const graphError = (code: number | undefined, subcode?: number, httpStatus = 400, usageHeader: string | null = null): SendResult =>
+ ({ kind: 'error', code, subcode, httpStatus, message: 'Graph said no', usageHeader });
+
+test('the reply puts the link on its own line after the text', () => {
+ assert.equal(composeReply('Here it is', 'https://example.com/g'), 'Here it is\n\nhttps://example.com/g');
+ assert.equal(composeReply('Here it is', null), 'Here it is');
+});
+
+test('message size is counted in bytes, so accented and non-Latin letters count more than once', () => {
+ assert.equal(messageBytes('abc'), 3);
+ assert.equal(messageBytes('é'), 2);
+});
+
+test('a comment can be answered for seven days after Meta sent it', () => {
+ assert.equal(Date.parse(expiresAtFor(new Date(NOW))) - NOW, REPLY_WINDOW_MS);
+});
+
+test('Graph API codes are sorted into what the Worker does next', () => {
+ assert.equal(classifySendError({ code: 4, httpStatus: 400, message: '' }), 'rate_limited');
+ assert.equal(classifySendError({ code: 613, subcode: 2534040, httpStatus: 400, message: '' }), 'rate_limited');
+ assert.equal(classifySendError({ code: 80002, httpStatus: 400, message: '' }), 'rate_limited');
+ assert.equal(classifySendError({ httpStatus: 429, message: '' }), 'rate_limited');
+ assert.equal(classifySendError({ code: 368, subcode: 1404169, httpStatus: 400, message: '' }), 'blocked');
+ assert.equal(classifySendError({ code: 10900, httpStatus: 400, message: '' }), 'already_replied');
+ assert.equal(classifySendError({ code: 100, subcode: 2534025, httpStatus: 400, message: '' }), 'not_eligible');
+ assert.equal(classifySendError({ code: 10, subcode: 2534022, httpStatus: 400, message: '' }), 'not_eligible');
+ assert.equal(classifySendError({ code: 551, httpStatus: 400, message: '' }), 'not_eligible');
+ assert.equal(classifySendError({ code: 10, httpStatus: 403, message: '' }), 'not_authorized');
+ assert.equal(classifySendError({ code: 190, httpStatus: 400, message: '' }), 'not_authorized');
+ assert.equal(classifySendError({ code: 200, subcode: 2534041, httpStatus: 403, message: '' }), 'not_authorized');
+ assert.equal(classifySendError({ code: 2, httpStatus: 503, message: '' }), 'transient');
+ assert.equal(classifySendError({ httpStatus: 502, message: '' }), 'transient');
+ assert.equal(classifySendError({ code: 100, subcode: 2534015, httpStatus: 400, message: '' }), 'refused');
+});
+
+test('retries wait 1, 2, 4 and 8 minutes, at most an hour, plus up to 30 seconds of jitter', () => {
+ assert.equal(retryDelayMs(1, () => 0), MINUTE);
+ assert.equal(retryDelayMs(2, () => 0), 2 * MINUTE);
+ assert.equal(retryDelayMs(4, () => 0), 8 * MINUTE);
+ assert.equal(retryDelayMs(20, () => 0), 60 * MINUTE);
+ assert.equal(retryDelayMs(1, () => 0.999999), MINUTE + 29_999);
+});
+
+test('the cooldown follows Meta\'s usage header, and falls back to 15 minutes when it is missing or unreadable', () => {
+ const header = JSON.stringify({ '123': [{ type: 'instagram', call_count: 100, estimated_time_to_regain_access: 7 }, { estimated_time_to_regain_access: 3 }] });
+ assert.equal(cooldownFromUsage(header), 7 * MINUTE);
+ assert.equal(cooldownFromUsage(JSON.stringify({ '1': [{ estimated_time_to_regain_access: 0 }] })), 15 * MINUTE);
+ assert.equal(cooldownFromUsage(null), 15 * MINUTE);
+ assert.equal(cooldownFromUsage('not json'), 15 * MINUTE);
+ assert.equal(cooldownFromUsage(JSON.stringify({ '1': [{ estimated_time_to_regain_access: 99999 }] })), 24 * 60 * MINUTE);
+});
+
+test('an accepted send records Instagram\'s message id and nothing else', () => {
+ const plan = finishPlan({ kind: 'accepted', messageId: 'm1' }, job(), NOW);
+ assert.equal(plan.status, 'accepted');
+ assert.equal(plan.outcome, 'accepted');
+ assert.equal(plan.messageId, 'm1');
+ assert.equal(plan.nextAttemptAt, null);
+ assert.equal(plan.cooldownUntil, null);
+});
+
+test('a send with no answer is held for a person and never retried on its own', () => {
+ const plan = finishPlan({ kind: 'ambiguous', message: 'the request timed out' }, job(), NOW);
+ assert.equal(plan.status, 'needs_review');
+ assert.equal(plan.outcome, 'ambiguous');
+ assert.equal(plan.nextAttemptAt, null);
+ assert.match(plan.errorMessage!, /may or may not have been sent/);
+});
+
+test('a send the Worker refused to start waits for the next run instead of a review', () => {
+ const plan = finishPlan({ kind: 'not_sent', message: 'this run reached its request limit' }, job(), NOW);
+ assert.equal(plan.status, 'retry_wait');
+ assert.equal(plan.nextAttemptAt, new Date(NOW + 5 * MINUTE).toISOString());
+});
+
+test('a rate limit waits for the cooldown and cools the whole account down', () => {
+ const header = JSON.stringify({ '1': [{ estimated_time_to_regain_access: 20 }] });
+ const plan = finishPlan(graphError(4, undefined, 400, header), job(), NOW);
+ assert.equal(plan.status, 'retry_wait');
+ assert.equal(plan.outcome, 'rate_limited');
+ assert.equal(plan.nextAttemptAt, new Date(NOW + 20 * MINUTE).toISOString());
+ assert.equal(plan.cooldownUntil, plan.nextAttemptAt);
+ assert.equal(plan.errorCode, 4);
+});
+
+test('a temporary block rests the account for a day', () => {
+ const plan = finishPlan(graphError(368, 1404169), job(), NOW);
+ assert.equal(plan.status, 'retry_wait');
+ assert.equal(plan.cooldownUntil, new Date(NOW + 24 * 60 * MINUTE).toISOString());
+});
+
+test('a cooldown that ends after the reply window expires the comment instead', () => {
+ const plan = finishPlan(graphError(368), job(1, 60 * MINUTE), NOW);
+ assert.equal(plan.status, 'expired');
+ assert.equal(plan.nextAttemptAt, null);
+ assert.ok(plan.cooldownUntil);
+});
+
+test('a temporary Instagram error is retried with backoff until the last try fails it', () => {
+ const retried = finishPlan(graphError(2, undefined, 503), job(2), NOW, () => 0);
+ assert.equal(retried.status, 'retry_wait');
+ assert.equal(retried.nextAttemptAt, new Date(NOW + 2 * MINUTE).toISOString());
+ const last = finishPlan(graphError(2, undefined, 503), job(MAX_SEND_ATTEMPTS), NOW);
+ assert.equal(last.status, 'failed');
+ assert.match(last.errorMessage!, /Sending stopped after 5 tries\.$/);
+});
+
+test('a comment that already has a private reply is skipped, not failed', () => {
+ const plan = finishPlan(graphError(10900), job(), NOW);
+ assert.equal(plan.status, 'skipped');
+ assert.equal(plan.reason, 'already_replied');
+});
+
+test('a refused token holds the reply and pauses the account until the owner fixes it', () => {
+ const plan = finishPlan(graphError(190, undefined, 400), job(), NOW);
+ assert.equal(plan.status, 'queued');
+ assert.equal(plan.reason, 'paused');
+ assert.ok(plan.pauseReason);
+ assert.ok(plan.nextAttemptAt);
+});
+
+test('a comment Instagram will not allow a reply to fails with a reason a person can read', () => {
+ const plan = finishPlan(graphError(100, 2534025), job(), NOW);
+ assert.equal(plan.status, 'failed');
+ assert.equal(plan.reason, 'not_eligible');
+ assert.equal(plan.errorSubcode, 2534025);
+ const other = finishPlan(graphError(100, 2534015), job(), NOW);
+ assert.equal(other.errorMessage, 'Instagram refused the reply. Graph said no');
+});
+
+test('before any limit is spent, an expired comment, a disabled rule or a missing token stops the job', () => {
+ const ready = { ruleEnabled: true, accessToken: 'T', expiresAt: job().expiresAt };
+ assert.equal(readinessPlan(ready, NOW), null);
+ assert.equal(readinessPlan({ ...ready, expiresAt: new Date(NOW).toISOString() }, NOW)?.status, 'expired');
+ assert.equal(readinessPlan({ ...ready, ruleEnabled: false }, NOW)?.reason, 'rule_disabled');
+ assert.equal(readinessPlan({ ...ready, accessToken: null }, NOW)?.reason, 'not_connected');
+});
+
+test('a full limit waits until a send frees up, a pause holds, and a recipient limit skips', () => {
+ const freeAt = new Date(NOW + 30 * MINUTE).toISOString();
+ assert.deepEqual(releasePlan('account_limit', freeAt, job(), NOW), {
+ status: 'retry_wait', reason: 'account_limit', errorMessage: 'Waiting: this account reached its hourly reply limit.', nextAttemptAt: freeAt,
+ });
+ assert.equal(releasePlan('cooldown', freeAt, job(), NOW)?.status, 'retry_wait');
+ assert.equal(releasePlan('global_limit', null, job(), NOW)?.nextAttemptAt, new Date(NOW + 15 * MINUTE).toISOString());
+ assert.equal(releasePlan('paused', null, job(), NOW)?.status, 'queued');
+ assert.equal(releasePlan('recipient_limit', null, job(), NOW)?.status, 'skipped');
+ assert.equal(releasePlan('rule_limit', freeAt, job(1, 10 * MINUTE), NOW)?.status, 'expired');
+ assert.equal(releasePlan('ok', null, job(), NOW), null);
+ assert.equal(releasePlan('gone', null, job(), NOW), null);
+});
diff --git a/backend/tests/lib/automationMatching.test.ts b/backend/tests/lib/automationMatching.test.ts
new file mode 100644
index 0000000..c794a5e
--- /dev/null
+++ b/backend/tests/lib/automationMatching.test.ts
@@ -0,0 +1,77 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { coversMedia, matchedKeyword, pickRule } from '../../lib/automationMatching.ts';
+import type { MatchableRule } from '../../lib/automationMatching.ts';
+
+function rule(overrides: Partial<MatchableRule> = {}): MatchableRule {
+ return { keywords: ['GUIDE'], matchMode: 'contains', caseSensitive: false, mediaIds: [], ...overrides };
+}
+
+test('contains matches the keyword as a whole word anywhere in the comment, ignoring case', () => {
+ assert.equal(matchedKeyword('Please send the guide!', rule()), 'GUIDE');
+ assert.equal(matchedKeyword('GUIDE', rule()), 'GUIDE');
+ assert.equal(matchedKeyword('guide pls', rule()), 'GUIDE');
+ assert.equal(matchedKeyword('#guide', rule()), 'GUIDE');
+});
+
+test('contains never matches inside a longer word', () => {
+ assert.equal(matchedKeyword('read the guidelines', rule()), null);
+ assert.equal(matchedKeyword('misguided', rule()), null);
+ assert.equal(matchedKeyword('guide2', rule()), null);
+});
+
+test('a phrase keyword matches across any run of spaces', () => {
+ assert.equal(matchedKeyword('send me the free guide', rule({ keywords: ['free guide'] })), 'free guide');
+});
+
+test('exact matches only a comment that is the keyword, apart from punctuation, emoji and spaces', () => {
+ const exact = rule({ matchMode: 'exact' });
+ // a folded-hands emoji, written as an escape
+ assert.equal(matchedKeyword(' Guide!! \u{1F64F} ', exact), 'GUIDE');
+ assert.equal(matchedKeyword('guide please', exact), null);
+});
+
+test('case sensitive rules compare the letters as written', () => {
+ const sensitive = rule({ caseSensitive: true });
+ assert.equal(matchedKeyword('GUIDE', sensitive), 'GUIDE');
+ assert.equal(matchedKeyword('guide', sensitive), null);
+});
+
+test('full-width and other look-alike characters fold to the plain keyword', () => {
+ assert.equal(matchedKeyword('GUIDE', rule()), 'GUIDE');
+});
+
+test('keywords with regular expression characters are matched literally', () => {
+ assert.equal(matchedKeyword('price? $9.99', rule({ keywords: ['$9.99'] })), '$9.99');
+ assert.equal(matchedKeyword('price? $9x99', rule({ keywords: ['$9.99'] })), null);
+});
+
+test('the first keyword of a rule that appears wins, and blank keywords never match', () => {
+ assert.equal(matchedKeyword('course and guide', rule({ keywords: ['', 'course', 'guide'] })), 'course');
+ assert.equal(matchedKeyword('anything', rule({ keywords: [' '] })), null);
+});
+
+test('a rule with no posts covers every post; one with posts covers only those', () => {
+ assert.equal(coversMedia(rule(), '1'), true);
+ assert.equal(coversMedia(rule(), null), true);
+ assert.equal(coversMedia(rule({ mediaIds: ['1', '2'] }), '2'), true);
+ assert.equal(coversMedia(rule({ mediaIds: ['1'] }), '3'), false);
+ assert.equal(coversMedia(rule({ mediaIds: ['1'] }), null), false);
+});
+
+test('a comment on one reel never triggers a rule meant only for another reel', () => {
+ const reelA = { ...rule({ keywords: ['GUIDE'], mediaIds: ['A'] }), id: 'a' };
+ const reelB = { ...rule({ keywords: ['COURSE'], mediaIds: ['B'] }), id: 'b' };
+ assert.equal(pickRule([reelA, reelB], 'COURSE please', 'A'), null);
+ assert.equal(pickRule([reelA, reelB], 'COURSE please', 'B')?.rule.id, 'b');
+ assert.equal(pickRule([reelA, reelB], 'GUIDE', 'A')?.rule.id, 'a');
+});
+
+test('a rule for this post wins over a rule for every post, then the earlier rule wins', () => {
+ const everywhere = { ...rule(), id: 'all' };
+ const older = { ...rule({ mediaIds: ['A'] }), id: 'older' };
+ const newer = { ...rule({ mediaIds: ['A'] }), id: 'newer' };
+ assert.deepEqual(pickRule([everywhere, older, newer], 'guide', 'A'), { rule: older, keyword: 'GUIDE' });
+ assert.equal(pickRule([everywhere, older], 'guide', 'B')?.rule.id, 'all');
+ assert.equal(pickRule([everywhere], 'hello', 'B'), null);
+});
diff --git a/backend/tests/lib/config.test.ts b/backend/tests/lib/config.test.ts
index 1c56fe3..8c948b8 100644
--- a/backend/tests/lib/config.test.ts
+++ b/backend/tests/lib/config.test.ts
@@ -40,3 +40,34 @@ test('the local Vite server is allowed only when the Worker itself runs on local
assert.deepEqual(corsOrigins(settings, 'https://api.example.workers.dev/api/health'), ['https://app.example.com']);
assert.deepEqual(corsOrigins(settings, 'http://localhost:8787/api/health'), ['https://app.example.com', 'http://localhost:5173', 'http://127.0.0.1:5173']);
});
+
+test('automation limits fall back to their defaults when missing, malformed or out of range', () => {
+ assert.deepEqual(config({}).automation, {
+ verifyToken: undefined,
+ appSecrets: [],
+ paused: false,
+ limits: { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3 },
+ batchSize: 10,
+ });
+ const set = config({
+ AUTOMATION_ACCOUNT_HOURLY_LIMIT: ' 50 ', AUTOMATION_USER_HOURLY_LIMIT: 'lots', AUTOMATION_GLOBAL_HOURLY_LIMIT: '-1',
+ AUTOMATION_RECIPIENT_DAILY_LIMIT: '1.5', AUTOMATION_BATCH_SIZE: '4',
+ }).automation;
+ assert.deepEqual(set.limits, { accountHourly: 50, userHourly: 500, globalHourly: 1000, recipientDaily: 3 });
+ assert.equal(set.batchSize, 4);
+});
+
+test('the account limit and the batch never exceed what Instagram and the free Workers plan allow', () => {
+ const capped = config({ AUTOMATION_ACCOUNT_HOURLY_LIMIT: '751', AUTOMATION_BATCH_SIZE: '16' }).automation;
+ assert.equal(capped.limits.accountHourly, 200);
+ assert.equal(capped.batchSize, 10);
+ assert.equal(config({ AUTOMATION_ACCOUNT_HOURLY_LIMIT: '750', AUTOMATION_BATCH_SIZE: '15' }).automation.batchSize, 15);
+});
+
+test('webhooks are signed with the Instagram app secret first and the Meta app secret second; only "true" pauses', () => {
+ const automation = config({ INSTAGRAM_APP_SECRET: ' IG ', META_APP_SECRET: `${BOM}META`, INSTAGRAM_WEBHOOK_VERIFY_TOKEN: ' tok ', AUTOMATION_PAUSED: 'TRUE' }).automation;
+ assert.deepEqual(automation.appSecrets, ['IG', 'META']);
+ assert.equal(automation.verifyToken, 'tok');
+ assert.equal(automation.paused, true);
+ assert.equal(config({ AUTOMATION_PAUSED: 'yes' }).automation.paused, false);
+});
diff --git a/backend/tests/lib/metaWebhookSignature.test.ts b/backend/tests/lib/metaWebhookSignature.test.ts
new file mode 100644
index 0000000..5ff947f
--- /dev/null
+++ b/backend/tests/lib/metaWebhookSignature.test.ts
@@ -0,0 +1,36 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { verifyMetaSignature, verifyTokenMatches } from '../../lib/metaWebhookSignature.ts';
+import { metaSignature } from '../fixtures/metaWebhook.ts';
+
+const body = new TextEncoder().encode('{"object":"instagram","entry":[]}').buffer as ArrayBuffer;
+
+test('a body signed with the app secret is accepted', async () => {
+ assert.equal(await verifyMetaSignature(['IGSECRET'], await metaSignature('IGSECRET', body), body), true);
+});
+
+test('the Meta app secret is accepted alongside the Instagram app secret', async () => {
+ assert.equal(await verifyMetaSignature(['IGSECRET', 'METASECRET'], await metaSignature('METASECRET', body), body), true);
+});
+
+test('a signature from another secret, a changed body or a missing header is refused', async () => {
+ const signature = await metaSignature('IGSECRET', body);
+ assert.equal(await verifyMetaSignature(['OTHER'], signature, body), false);
+ const changed = new TextEncoder().encode('{"object":"instagram","entry":[1]}').buffer as ArrayBuffer;
+ assert.equal(await verifyMetaSignature(['IGSECRET'], signature, changed), false);
+ assert.equal(await verifyMetaSignature(['IGSECRET'], undefined, body), false);
+ assert.equal(await verifyMetaSignature([], signature, body), false);
+});
+
+test('a header without the sha256 prefix or with hex that is not hex is refused', async () => {
+ const signature = await metaSignature('IGSECRET', body);
+ assert.equal(await verifyMetaSignature(['IGSECRET'], signature.replace('sha256=', ''), body), false);
+ assert.equal(await verifyMetaSignature(['IGSECRET'], 'sha256=zz', body), false);
+ assert.equal(await verifyMetaSignature(['IGSECRET'], 'sha256=abc', body), false);
+});
+
+test('the verify token must match exactly', async () => {
+ assert.equal(await verifyTokenMatches('token-1', 'token-1'), true);
+ assert.equal(await verifyTokenMatches('token-1', 'token-2'), false);
+ assert.equal(await verifyTokenMatches('token-1', 'token-1 '), false);
+});
diff --git a/backend/tests/repositories/automationCommentRepository.test.ts b/backend/tests/repositories/automationCommentRepository.test.ts
new file mode 100644
index 0000000..a4b9a48
--- /dev/null
+++ b/backend/tests/repositories/automationCommentRepository.test.ts
@@ -0,0 +1,117 @@
+import { test, describe } from 'node:test';
+import assert from 'node:assert/strict';
+import { createAutomationCommentRepository } from '../../repositories/automationCommentRepository.ts';
+import { fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';
+import type { Row } from '../fixtures/fakeSupabase.ts';
+import type { FinishPlan } from '../../lib/automationDelivery.ts';
+import type { NewAutomationComment } from '../../repositories/automationCommentRepository.ts';
+
+const LIMITS = { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3 };
+
+function newComment(id: string, commentId: string): NewAutomationComment {
+ return {
+ id, userId: 'user-1', accountId: 'ig1', ruleId: 'rule-1', igUserId: '1784', commentId, mediaId: '9', fromId: 'f', fromUsername: 'fan',
+ text: 'GUIDE', status: 'queued', statusReason: null, nextAttemptAt: '2026-10-16T00:00:00Z', notifiedAt: '2026-10-16T00:00:00Z', expiresAt: '2026-10-23T00:00:00Z',
+ };
+}
+
+const rpcArgs = (supabase: ReturnType<typeof fakeSupabase>, name: string) => supabase.calls.find(call => call.type === 'rpc' && call.table === name)!.values as Row;
+
+describe('automation comment repository', () => {
+ test('storing comments ignores ones already stored for the same Instagram account and returns only the new ones', async () => {
+ const supabase = fakeSupabase([tableRow('automation_comments', { id: 'old', ig_user_id: '1784', comment_id: 'c1' })]);
+ const repo = createAutomationCommentRepository(supabase);
+ const inserted = await repo.insertMany([newComment('a', 'c1'), newComment('b', 'c2')]);
+ assert.deepEqual(inserted.map(comment => comment.id), ['b']);
+ const call = supabase.calls[0];
+ assert.deepEqual([call.type, call.onConflict, call.ignoreDuplicates], ['upsert', 'ig_user_id,comment_id', true]);
+ assert.deepEqual(await repo.insertMany([]), []);
+ assert.equal(supabase.calls.length, 1);
+ });
+
+ test('claim, reserve and finish pass every field to the database functions', async () => {
+ const supabase = fakeSupabase([], {
+ claim_automation_comments: () => [{
+ id: 'a', user_id: 'user-1', account_id: 'ig1', rule_id: 'r', ig_user_id: '1784', comment_id: 'c', from_id: 'f', attempts: 2,
+ expires_at: 'E', rule_enabled: true, reply_text: 'T', link_url: null, access_token: 'TOK',
+ }],
+ reserve_automation_send: () => [{ outcome: 'account_limit', retry_at: 'R' }],
+ finish_automation_send: () => true,
+ });
+ const repo = createAutomationCommentRepository(supabase);
+ const [claimed] = await repo.claim({ limit: 10, perAccount: 5, leaseSeconds: 1200 });
+ assert.deepEqual(claimed, {
+ id: 'a', userId: 'user-1', accountId: 'ig1', ruleId: 'r', igUserId: '1784', commentId: 'c', fromId: 'f', attempts: 2,
+ expiresAt: 'E', ruleEnabled: true, replyText: 'T', linkUrl: null, accessToken: 'TOK',
+ });
+ assert.deepEqual(rpcArgs(supabase, 'claim_automation_comments'), { p_limit: 10, p_per_account: 5, p_lease_seconds: 1200, p_ids: null });
+ assert.deepEqual(await repo.reserve('a', 'att', LIMITS), { outcome: 'account_limit', retryAt: 'R' });
+ assert.deepEqual(rpcArgs(supabase, 'reserve_automation_send'), {
+ p_id: 'a', p_attempt_id: 'att', p_global_limit: 1000, p_user_limit: 500, p_account_limit: 200, p_recipient_limit: 3,
+ });
+ const plan: FinishPlan = {
+ status: 'retry_wait', outcome: 'rate_limited', reason: 'rate_limited', errorMessage: 'm', messageId: null, errorCode: 4, errorSubcode: null,
+ httpStatus: 400, nextAttemptAt: 'N', cooldownUntil: 'C', cooldownReason: 'why', pauseReason: null,
+ };
+ assert.equal(await repo.finish('a', 'att', plan), true);
+ assert.deepEqual(rpcArgs(supabase, 'finish_automation_send'), {
+ p_id: 'a', p_attempt_id: 'att', p_status: 'retry_wait', p_outcome: 'rate_limited', p_reason: 'rate_limited', p_error_message: 'm',
+ p_message_id: null, p_error_code: 4, p_error_subcode: null, p_http_status: 400, p_next_attempt_at: 'N', p_cooldown_until: 'C',
+ p_cooldown_reason: 'why', p_pause_reason: null,
+ });
+ });
+
+ test('a reservation with no answer counts as gone, so the job is never sent', async () => {
+ const repo = createAutomationCommentRepository(fakeSupabase([], { reserve_automation_send: () => [] }));
+ assert.deepEqual(await repo.reserve('a', 'att', LIMITS), { outcome: 'gone', retryAt: null });
+ });
+
+ test('a job is released only while this run still holds it', async () => {
+ const supabase = fakeSupabase([
+ tableRow('automation_comments', { id: 'held', status: 'processing', claimed_at: 'x' }),
+ tableRow('automation_comments', { id: 'taken', status: 'sending', claimed_at: 'x' }),
+ ]);
+ const repo = createAutomationCommentRepository(supabase);
+ const plan = { status: 'skipped' as const, reason: 'rule_disabled', errorMessage: 'off', nextAttemptAt: null };
+ assert.equal(await repo.release('held', plan), true);
+ assert.equal(await repo.release('taken', plan), false);
+ assert.deepEqual([supabase.table[0].status, supabase.table[0].claimed_at, supabase.table[1].status], ['skipped', null, 'sending']);
+ });
+
+ test('a retry requeues only the user\'s failed, skipped or review items that have not expired', async () => {
+ const future = new Date(Date.now() + 60_000).toISOString();
+ const supabase = fakeSupabase([
+ tableRow('automation_comments', { id: 'a', user_id: 'user-1', status: 'needs_review', expires_at: future }),
+ tableRow('automation_comments', { id: 'b', user_id: 'user-1', status: 'sending', expires_at: future }),
+ ]);
+ const repo = createAutomationCommentRepository(supabase);
+ assert.equal((await repo.requeueForUser('a', 'user-1'))?.status, 'queued');
+ assert.equal(await repo.requeueForUser('b', 'user-1'), null);
+ assert.equal(await repo.requeueForUser('a', 'user-2'), null);
+ });
+
+ test('activity filters by user first, then by every filter given', async () => {
+ const supabase = fakeSupabase([]);
+ await createAutomationCommentRepository(supabase).listForUser('user-1', { accountId: 'ig1', status: 'failed', before: 'B', from: 'F', limit: 20 });
+ assert.deepEqual(supabase.calls[0].filters, [['user_id', 'user-1'], ['account_id', 'ig1'], ['status', 'failed'], ['created_at', 'F', 'gte'], ['created_at', 'B', 'lt']]);
+ });
+
+ test('stats come from the database function, with empty groups when nothing happened', async () => {
+ const repo = createAutomationCommentRepository(fakeSupabase([], { automation_stats: () => ({ comments: { accepted: 2 } }) }));
+ assert.deepEqual(await repo.statsForUser('user-1', { from: 'F', to: 'T' }), { comments: { accepted: 2 }, attempts: {} });
+ });
+
+ test('retention deletes comments created before the cutoff across all users', async () => {
+ const supabase = fakeSupabase([
+ tableRow('automation_comments', { id: 'old', created_at: '2026-01-01T00:00:00Z' }),
+ tableRow('automation_comments', { id: 'new', created_at: '2026-10-01T00:00:00Z' }),
+ ]);
+ assert.equal(await createAutomationCommentRepository(supabase).deleteCreatedBefore('2026-07-01T00:00:00Z'), 1);
+ assert.deepEqual(supabase.table.map(row => row.id), ['new']);
+ });
+
+ test('a failed query becomes a DatabaseError', async () => {
+ const repo = createAutomationCommentRepository(fakeSupabase([], { claim_automation_comments: () => { throw new Error('boom'); } }));
+ await assert.rejects(repo.claim({ limit: 1, perAccount: 1, leaseSeconds: 1 }), { name: 'DatabaseError' });
+ });
+});
diff --git a/backend/tests/repositories/automationRuleRepository.test.ts b/backend/tests/repositories/automationRuleRepository.test.ts
new file mode 100644
index 0000000..81d68cf
--- /dev/null
+++ b/backend/tests/repositories/automationRuleRepository.test.ts
@@ -0,0 +1,49 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createAutomationRuleRepository } from '../../repositories/automationRuleRepository.ts';
+import { createAutomationAccountRepository } from '../../repositories/automationAccountRepository.ts';
+import { createAuditRepository } from '../../repositories/auditRepository.ts';
+import { fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';
+import { mockRowIds } from '../fixtures/rowIds.ts';
+
+test('a rule update writes only the columns it names and is scoped to the user', async () => {
+ const supabase = fakeSupabase([tableRow('automation_rules', { id: 'r', user_id: 'user-1', name: 'Old', enabled: false })]);
+ const repo = createAutomationRuleRepository(supabase);
+ const updated = await repo.updateForUser('r', { name: 'New', enabled: true, linkUrl: null }, 'user-1');
+ assert.deepEqual(supabase.calls[0].values, { name: 'New', link_url: null, enabled: true });
+ assert.deepEqual(supabase.calls[0].filters, [['id', 'r'], ['user_id', 'user-1']]);
+ assert.equal(updated?.name, 'New');
+ assert.equal(await repo.updateForUser('r', { name: 'x' }, 'user-2'), null);
+ assert.equal(await repo.deleteForUser('r', 'user-2'), false);
+});
+
+test('the webhook lookup maps the database function\'s rows to rules with their owner', async () => {
+ const supabase = fakeSupabase([], {
+ automation_rules_for_ig_user: () => [{ id: 'r', user_id: 'u', account_id: 'a', keywords: ['K'], match_mode: 'exact', case_sensitive: true, media_ids: ['1'] }],
+ });
+ assert.deepEqual(await createAutomationRuleRepository(supabase).listEnabledForInstagramUser('1784'), [
+ { id: 'r', userId: 'u', accountId: 'a', keywords: ['K'], matchMode: 'exact', caseSensitive: true, mediaIds: ['1'] },
+ ]);
+ assert.deepEqual(supabase.calls[0].values, { p_ig_user_id: '1784' });
+});
+
+test('pausing or resuming by hand creates the account\'s row once and clears a hold the Worker set', async () => {
+ const supabase = fakeSupabase([tableRow('automation_accounts', { account_id: 'ig1', user_id: 'user-1', paused: true, paused_reason: 'token refused' })]);
+ const repo = createAutomationAccountRepository(supabase);
+ const controls = await repo.setPausedForUser('ig1', 'user-1', false);
+ assert.deepEqual([controls.paused, controls.pausedReason], [false, null]);
+ assert.equal(supabase.calls[0].onConflict, 'account_id');
+ assert.equal(supabase.table.filter(row => row._table === 'automation_accounts').length, 1);
+ assert.ok((await repo.markSubscribedForUser('ig2', 'user-1')).subscribedAt);
+});
+
+test('audit events are written for the user and old ones are deleted by date', async () => {
+ mockRowIds();
+ const supabase = fakeSupabase([tableRow('audit_events', { id: 'old', created_at: '2025-01-01T00:00:00Z' })]);
+ const repo = createAuditRepository(supabase);
+ await repo.recordForUser('user-1', { action: 'account.removed', subjectType: 'account', subjectId: 'ig1' });
+ assert.deepEqual(supabase.calls[0].values, {
+ id: '00000000-0000-4000-8000-000000000001', user_id: 'user-1', action: 'account.removed', subject_type: 'account', subject_id: 'ig1', details: {},
+ });
+ assert.equal(await repo.deleteCreatedBefore('2025-06-01T00:00:00Z'), 1);
+});
diff --git a/backend/tests/routes/automationRoutes.test.ts b/backend/tests/routes/automationRoutes.test.ts
new file mode 100644
index 0000000..0e6e3c3
--- /dev/null
+++ b/backend/tests/routes/automationRoutes.test.ts
@@ -0,0 +1,203 @@
+import { test, describe, beforeEach, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import automationRouter from '../../routes/automationRoutes.ts';
+import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';
+import { accountRow, fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';
+import type { FakeSupabase, Row } from '../fixtures/fakeSupabase.ts';
+import { backgroundWork, callRoute, mountWithContext } from '../fixtures/routeHarness.ts';
+import { mockRowIds } from '../fixtures/rowIds.ts';
+import type { Env } from '../../types/env.ts';
+
+const ENV: Partial<Env> = { INSTAGRAM_APP_SECRET: 'IGSECRET', INSTAGRAM_WEBHOOK_VERIFY_TOKEN: 'tok' };
+const FUTURE = new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString();
+const PAST = new Date(Date.now() - 60 * 1000).toISOString();
+
+function ruleRow(id: string, userId: string, accountId: string, extra: Row = {}): Row {
+ return tableRow('automation_rules', {
+ id, user_id: userId, account_id: accountId, name: id, keywords: ['GUIDE'], match_mode: 'contains', case_sensitive: false, media_ids: [],
+ reply_text: 'Here it is', link_url: null, enabled: false, hourly_limit: null, created_at: '2026-10-01T00:00:00Z', updated_at: '2026-10-01T00:00:00Z', ...extra,
+ });
+}
+
+function commentRow(id: string, userId: string, status: string, extra: Row = {}): Row {
+ return tableRow('automation_comments', {
+ id, user_id: userId, account_id: userId === 'user-1' ? 'ig1' : 'ig-theirs', rule_id: null, comment_id: `c-${id}`, media_id: '1',
+ from_username: 'fan', text: 'GUIDE', status, status_reason: null, error_message: 'x', attempts: 1, next_attempt_at: null, accepted_at: null,
+ expires_at: FUTURE, created_at: '2026-10-15T00:00:00Z', ...extra,
+ });
+}
+
+function seed(): Row[] {
+ return [
+ tableRow('accounts', accountRow({ id: 'ig1', platform: 'instagram', igUserId: '1784', username: 'mine', accessToken: 'TOKEN-1' })),
+ tableRow('accounts', accountRow({ id: 'yt1', platform: 'youtube', channelId: 'UC1' })),
+ tableRow('accounts', accountRow({ id: 'ig-theirs', platform: 'instagram', igUserId: '2000', username: 'theirs', accessToken: 'THEIRS' }, 'user-2')),
+ ruleRow('rule-mine', 'user-1', 'ig1'),
+ ruleRow('rule-theirs', 'user-2', 'ig-theirs'),
+ commentRow('failed-mine', 'user-1', 'failed'),
+ commentRow('accepted-mine', 'user-1', 'accepted'),
+ commentRow('expired-mine', 'user-1', 'failed', { expires_at: PAST }),
+ commentRow('failed-theirs', 'user-2', 'failed'),
+ ];
+}
+
+let fetchMock: FetchMock | null = null;
+let graph: RecordedRequest[] = [];
+let subscribeAnswer: () => ReturnType<typeof reply> = () => reply({ success: true });
+
+beforeEach(() => {
+ graph = [];
+ subscribeAnswer = () => reply({ success: true });
+ mockRowIds();
+ mock.method(console, 'log', () => {});
+ mock.method(console, 'warn', () => {});
+ mock.method(console, 'error', () => {});
+ fetchMock = installFetch(request => {
+ graph.push(request);
+ return request.url.includes('/subscribed_apps') ? subscribeAnswer() : reply({ message_id: 'm' });
+ });
+});
+afterEach(() => {
+ fetchMock?.restore();
+ mock.restoreAll();
+});
+
+function server(supabase: FakeSupabase = fakeSupabase(seed(), {
+ automation_stats: args => ({ comments: { accepted: 1, failed: args.p_account_id ? 0 : 2 }, attempts: { accepted: 1 } }),
+ claim_automation_comments: () => [],
+})) {
+ return { supabase, app: mountWithContext(app => app.route('/', automationRouter), { supabase, userId: 'user-1' }) };
+}
+
+async function call(target: ReturnType<typeof server>, method: string, path: string, json?: unknown) {
+ const work = backgroundWork();
+ const result = await callRoute(target.app, method, path, { json, env: ENV, executionCtx: work });
+ await work.settle();
+ return { status: result.status, body: JSON.parse(result.body) };
+}
+
+const audits = (supabase: FakeSupabase) => supabase.table.filter(row => row._table === 'audit_events').map(row => row.action);
+
+describe('automation routes', () => {
+ test('the overview lists only this user\'s rules and Instagram accounts, and whether the webhook can work', async () => {
+ const { body } = await call(server(), 'GET', '/automations');
+ assert.deepEqual(body.rules.map((rule: { id: string }) => rule.id), ['rule-mine']);
+ assert.deepEqual(body.accounts, [{
+ accountId: 'ig1', username: 'mine', profilePictureUrl: '', paused: false, cooldownUntil: null, cooldownReason: null, subscribedAt: null,
+ }]);
+ assert.deepEqual(body.settings, { webhookConfigured: true, paused: false, limits: { accountHourly: 200, userHourly: 500, globalHourly: 1000, recipientDaily: 3 } });
+ });
+
+ test('creating an enabled rule saves it, asks Instagram for the account\'s comments and records both', async () => {
+ const target = server();
+ const { status, body } = await call(target, 'POST', '/automations/rules', {
+ accountId: 'ig1', name: 'Guide', keywords: ['GUIDE'], replyText: 'Here it is', linkUrl: 'https://example.com/g', enabled: true,
+ });
+ assert.equal(status, 200);
+ assert.equal(body.rule.enabled, true);
+ assert.equal(body.rule.accountId, 'ig1');
+ assert.equal(new URL(graph[0].url).pathname, '/v25.0/1784/subscribed_apps');
+ assert.equal(new URL(graph[0].url).searchParams.get('subscribed_fields'), 'comments');
+ assert.ok(target.supabase.table.some(row => row._table === 'automation_accounts' && row.subscribed_at));
+ assert.deepEqual(audits(target.supabase), ['automation_rule.created', 'automation_account.subscribed']);
+ });
+
+ test('a rule is still saved when Instagram refuses the subscription, and the account shows as not receiving comments', async () => {
+ subscribeAnswer = () => reply({ error: { message: 'Application does not have permission', code: 10 } }, 403);
+ const target = server();
+ const { status } = await call(target, 'POST', '/automations/rules', { accountId: 'ig1', name: 'G', keywords: ['G'], replyText: 'x', enabled: true });
+ assert.equal(status, 200);
+ assert.equal((await call(target, 'GET', '/automations')).body.accounts[0].subscribedAt, null);
+ });
+
+ test('a rule can only use the user\'s own Instagram account', async () => {
+ const target = server();
+ for (const accountId of ['ig-theirs', 'yt1', 'missing']) {
+ const { status, body } = await call(target, 'POST', '/automations/rules', { accountId, name: 'G', keywords: ['G'], replyText: 'x' });
+ assert.equal(status, 404);
+ assert.equal(body.message, 'Instagram account not found');
+ }
+ });
+
+ test('a reply and link over Instagram\'s 1,000 bytes is refused with the size', async () => {
+ const { status, body } = await call(server(), 'POST', '/automations/rules', {
+ accountId: 'ig1', name: 'G', keywords: ['G'], replyText: 'é'.repeat(500), linkUrl: 'https://example.com/guide',
+ });
+ assert.equal(status, 400);
+ assert.match(body.message, /is 1027 bytes; Instagram accepts at most 1000/);
+ });
+
+ test('editing, copying and deleting work on the user\'s rules and answer 404 for anyone else\'s', async () => {
+ const target = server();
+ assert.equal((await call(target, 'PUT', '/automations/rules/rule-mine', { name: 'Renamed' })).body.rule.name, 'Renamed');
+ const copy = (await call(target, 'POST', '/automations/rules/rule-mine/duplicate')).body.rule;
+ assert.deepEqual([copy.name, copy.enabled, copy.accountId], ['Renamed (copy)', false, 'ig1']);
+ assert.equal((await call(target, 'DELETE', '/automations/rules/rule-mine')).status, 200);
+ for (const [method, path] of [['PUT', '/automations/rules/rule-theirs'], ['POST', '/automations/rules/rule-theirs/duplicate'], ['DELETE', '/automations/rules/rule-theirs']] as const) {
+ const { status } = await call(target, method, path, method === 'PUT' ? { name: 'x' } : undefined);
+ assert.equal(status, 404, `${method} ${path}`);
+ }
+ assert.ok(target.supabase.table.some(row => row.id === 'rule-theirs'));
+ assert.deepEqual(audits(target.supabase), ['automation_rule.updated', 'automation_rule.duplicated', 'automation_rule.deleted']);
+ });
+
+ test('testing a rule draft shows whether a sample comment matches and the exact reply, and sends nothing', async () => {
+ const { body } = await call(server(), 'POST', '/automations/test', { keywords: ['GUIDE'], replyText: 'Hi', linkUrl: 'https://e.com', comment: 'the guide please' });
+ assert.deepEqual(body, { success: true, matched: true, keyword: 'GUIDE', message: 'Hi\n\nhttps://e.com', messageBytes: 17, maxMessageBytes: 1000 });
+ const scoped = await call(server(), 'POST', '/automations/test', { keywords: ['GUIDE'], replyText: 'Hi', mediaIds: ['1'], mediaId: '2', comment: 'GUIDE' });
+ assert.equal(scoped.body.matched, false);
+ assert.equal(graph.length, 0);
+ });
+
+ test('activity lists only the user\'s comments, newest page first', async () => {
+ const { body } = await call(server(), 'GET', '/automations/activity?status=failed&limit=1');
+ assert.deepEqual(body.items.map((item: { id: string }) => item.id), ['failed-mine']);
+ assert.equal(body.nextBefore, '2026-10-15T00:00:00Z');
+ });
+
+ test('a failed reply can be retried once inside its 7 days; sent, expired and other users\' items cannot', async () => {
+ const target = server();
+ const retried = await call(target, 'POST', '/automations/activity/failed-mine/retry');
+ assert.equal(retried.status, 200);
+ assert.deepEqual([retried.body.item.status, retried.body.item.errorMessage], ['queued', null]);
+ assert.equal((await call(target, 'POST', '/automations/activity/failed-mine/retry')).status, 409);
+ assert.equal((await call(target, 'POST', '/automations/activity/accepted-mine/retry')).status, 409);
+ assert.equal((await call(target, 'POST', '/automations/activity/expired-mine/retry')).status, 409);
+ assert.equal((await call(target, 'POST', '/automations/activity/failed-theirs/retry')).status, 404);
+ assert.equal(target.supabase.table.find(row => row.id === 'failed-theirs')!.status, 'failed');
+ assert.ok(target.supabase.calls.some(call => call.type === 'rpc' && call.table === 'claim_automation_comments'));
+ });
+
+ test('stats default to the last 7 days and pass the filters on', async () => {
+ const target = server();
+ const { body } = await call(target, 'GET', '/automations/stats?accountId=ig1');
+ assert.deepEqual(body.stats, { comments: { accepted: 1, failed: 0 }, attempts: { accepted: 1 } });
+ assert.equal(Date.parse(body.to) - Date.parse(body.from), 7 * 24 * 60 * 60 * 1000);
+ const sent = target.supabase.calls.find(call => call.table === 'automation_stats')!.values as Row;
+ assert.deepEqual([sent.p_user_id, sent.p_account_id, sent.p_rule_id], ['user-1', 'ig1', null]);
+ assert.equal((await call(target, 'GET', '/automations/stats?from=2026-10-10&to=2026-10-01')).status, 400);
+ });
+
+ test('pausing and resuming an account is recorded, and resuming releases its held replies; other accounts answer 404', async () => {
+ const target = server();
+ assert.equal((await call(target, 'PUT', '/automations/accounts/ig1', { paused: true })).body.account.paused, true);
+ assert.equal((await call(target, 'PUT', '/automations/accounts/ig1', { paused: false })).body.account.paused, false);
+ assert.ok(target.supabase.calls.some(call => call.table === 'automation_comments' && call.type === 'update'
+ && call.filters.some(([column, value]) => column === 'status_reason' && value === 'paused')));
+ assert.equal((await call(target, 'PUT', '/automations/accounts/ig-theirs', { paused: true })).status, 404);
+ assert.deepEqual(audits(target.supabase), ['automation_account.paused', 'automation_account.resumed']);
+ });
+
+ test('turning on comment events calls Instagram with the account\'s token and reports Instagram\'s refusal', async () => {
+ const target = server();
+ const { body } = await call(target, 'POST', '/automations/accounts/ig1/subscribe');
+ assert.ok(body.account.subscribedAt);
+ assert.equal(new URL(graph[0].url).searchParams.get('access_token'), 'TOKEN-1');
+ subscribeAnswer = () => reply({ success: false });
+ const refused = await call(target, 'POST', '/automations/accounts/ig1/subscribe');
+ assert.equal(refused.status, 502);
+ assert.match(refused.body.message, /did not confirm the webhook subscription/);
+ assert.equal((await call(target, 'POST', '/automations/accounts/ig-theirs/subscribe')).status, 404);
+ });
+});
diff --git a/backend/tests/routes/instagramWebhookRoutes.test.ts b/backend/tests/routes/instagramWebhookRoutes.test.ts
new file mode 100644
index 0000000..5b365b4
--- /dev/null
+++ b/backend/tests/routes/instagramWebhookRoutes.test.ts
@@ -0,0 +1,167 @@
+import { test, describe, beforeEach, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import instagramWebhookRouter from '../../routes/instagramWebhookRoutes.ts';
+import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
+import { accountRow, fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';
+import type { Row, RpcHandler } from '../fixtures/fakeSupabase.ts';
+import { commentNotification, metaSignature } from '../fixtures/metaWebhook.ts';
+import { backgroundWork, callRoute, mountWithContext } from '../fixtures/routeHarness.ts';
+import { mockRowIds } from '../fixtures/rowIds.ts';
+import type { Env } from '../../types/env.ts';
+
+const ENV: Partial<Env> = { INSTAGRAM_APP_SECRET: 'IGSECRET', INSTAGRAM_WEBHOOK_VERIFY_TOKEN: 'verify-me' };
+const SENT_AT = Math.floor(Date.now() / 1000);
+
+const inTable = (row: Row, name: string) => row._table === name;
+
+// the queue functions, reduced to what one webhook request does: look up rules, claim its comments, reserve, finish
+const RPC: Record<string, RpcHandler> = {
+ automation_rules_for_ig_user: (args, table) => table
+ .filter(row => inTable(row, 'automation_rules') && row.enabled)
+ .filter(row => table.some(account => inTable(account, 'accounts') && account.id === row.account_id && (account.data as Row).igUserId === args.p_ig_user_id)),
+ claim_automation_comments: (args, table) => table
+ .filter(row => inTable(row, 'automation_comments') && row.status === 'queued' && (args.p_ids as string[]).includes(row.id as string))
+ .map(row => {
+ row.status = 'processing';
+ const rule = table.find(candidate => inTable(candidate, 'automation_rules') && candidate.id === row.rule_id)!;
+ const account = table.find(candidate => inTable(candidate, 'accounts') && candidate.id === row.account_id)!;
+ return { ...row, rule_enabled: rule.enabled, reply_text: rule.reply_text, link_url: rule.link_url, access_token: (account.data as Row).accessToken };
+ }),
+ reserve_automation_send: (args, table) => {
+ const row = table.find(candidate => inTable(candidate, 'automation_comments') && candidate.id === args.p_id && candidate.status === 'processing');
+ if (!row) return [{ outcome: 'gone', retry_at: null }];
+ row.status = 'sending';
+ return [{ outcome: 'ok', retry_at: null }];
+ },
+ finish_automation_send: (args, table) => {
+ const row = table.find(candidate => inTable(candidate, 'automation_comments') && candidate.id === args.p_id && candidate.status === 'sending');
+ if (!row) return false;
+ Object.assign(row, { status: args.p_status, message_id: args.p_message_id });
+ return true;
+ },
+};
+
+function seed(): Row[] {
+ return [
+ tableRow('accounts', accountRow({ id: 'ig1', platform: 'instagram', igUserId: '1784', accessToken: 'TOKEN-1' })),
+ tableRow('automation_rules', { id: 'rule-1', user_id: 'user-1', account_id: 'ig1', keywords: ['GUIDE'], match_mode: 'contains', case_sensitive: false, media_ids: [], reply_text: 'Here it is', link_url: 'https://example.com/g', enabled: true }),
+ ];
+}
+
+let fetchMock: FetchMock | null = null;
+let sends: string[] = [];
+
+beforeEach(() => {
+ sends = [];
+ mockRowIds();
+ mock.method(console, 'log', () => {});
+ mock.method(console, 'warn', () => {});
+ mock.method(console, 'error', () => {});
+ fetchMock = installFetch(request => {
+ sends.push(request.body ?? '');
+ return reply({ recipient_id: 'r', message_id: 'mid-1' });
+ });
+});
+afterEach(() => {
+ fetchMock?.restore();
+ mock.restoreAll();
+});
+
+function app(supabase = fakeSupabase(seed(), RPC)) {
+ return { supabase, app: mountWithContext(server => server.route('/', instagramWebhookRouter), { supabase }) };
+}
+
+async function post(target: ReturnType<typeof app>, body: string, signature: string | null, env: Partial<Env> = ENV) {
+ const work = backgroundWork();
+ const headers: Record<string, string> = signature ? { 'X-Hub-Signature-256': signature } : {};
+ const result = await callRoute(target.app, 'POST', '/webhooks/instagram', { json: body, headers, env, executionCtx: work });
+ await work.settle();
+ return result;
+}
+
+describe('instagram webhook routes', () => {
+ test('the verification request gets the bare challenge back only with the right verify token', async () => {
+ const { app: server } = app();
+ const ok = await callRoute(server, 'GET', '/webhooks/instagram?hub.mode=subscribe&hub.verify_token=verify-me&hub.challenge=1158201444', { env: ENV });
+ assert.deepEqual(ok, { status: 200, body: '1158201444' });
+ const wrong = await callRoute(server, 'GET', '/webhooks/instagram?hub.mode=subscribe&hub.verify_token=guess&hub.challenge=1', { env: ENV });
+ assert.equal(wrong.status, 403);
+ assert.equal(JSON.parse(wrong.body).code, 'FORBIDDEN');
+ const unset = await callRoute(server, 'GET', '/webhooks/instagram?hub.mode=subscribe&hub.verify_token=verify-me&hub.challenge=1', { env: {} });
+ assert.equal(unset.status, 503);
+ });
+
+ test('a signed comment is stored before the answer, and the reply is sent after it', async () => {
+ const target = app();
+ const body = JSON.stringify(commentNotification('1784', SENT_AT, [{ id: '555', text: 'send the guide', mediaId: '9001' }]));
+ const result = await post(target, body, await metaSignature('IGSECRET', body));
+ assert.deepEqual(result, { status: 200, body: '{"success":true}' });
+ const stored = target.supabase.table.filter(row => inTable(row, 'automation_comments'));
+ assert.equal(stored.length, 1);
+ assert.deepEqual([stored[0].comment_id, stored[0].status, stored[0].message_id], ['555', 'accepted', 'mid-1']);
+ assert.deepEqual(JSON.parse(sends[0]), { recipient: { comment_id: '555' }, message: { text: 'Here it is\n\nhttps://example.com/g' } });
+ });
+
+ test('the same notification delivered twice sends one reply', async () => {
+ const target = app();
+ const body = JSON.stringify(commentNotification('1784', SENT_AT, [{ id: '555', text: 'GUIDE' }]));
+ const signature = await metaSignature('IGSECRET', body);
+ assert.equal((await post(target, body, signature)).status, 200);
+ assert.equal((await post(target, body, signature)).status, 200);
+ assert.equal(sends.length, 1);
+ assert.equal(target.supabase.table.filter(row => inTable(row, 'automation_comments')).length, 1);
+ });
+
+ test('a notification signed with the Meta app secret is accepted when META_APP_SECRET is set', async () => {
+ const target = app();
+ const body = JSON.stringify(commentNotification('1784', SENT_AT, [{ id: '556', text: 'nothing here' }]));
+ const result = await post(target, body, await metaSignature('METASECRET', body), { ...ENV, META_APP_SECRET: 'METASECRET' });
+ assert.equal(result.status, 200);
+ assert.equal(sends.length, 0);
+ });
+
+ test('a missing or wrong signature is refused with 401 and nothing is stored', async () => {
+ const target = app();
+ const body = JSON.stringify(commentNotification('1784', SENT_AT, [{ id: '555', text: 'GUIDE' }]));
+ for (const signature of [null, await metaSignature('WRONG', body), 'sha256=00']) {
+ const result = await post(target, body, signature);
+ assert.equal(result.status, 401);
+ assert.equal(JSON.parse(result.body).code, 'UNAUTHORIZED');
+ }
+ assert.equal(target.supabase.calls.length, 0);
+ });
+
+ test('a body that is not an Instagram notification, or is not JSON, is refused with 400 after the signature check', async () => {
+ const target = app();
+ const page = JSON.stringify({ object: 'page', entry: [] });
+ assert.equal((await post(target, page, await metaSignature('IGSECRET', page))).status, 400);
+ assert.equal((await post(target, '{not json', await metaSignature('IGSECRET', '{not json'))).status, 400);
+ });
+
+ test('a notification over 1 MB is refused before the signature is computed', async () => {
+ const target = app();
+ const work = backgroundWork();
+ const result = await callRoute(target.app, 'POST', '/webhooks/instagram', {
+ json: '{}', headers: { 'Content-Length': String(2 * 1024 * 1024), 'X-Hub-Signature-256': 'sha256=00' }, env: ENV, executionCtx: work,
+ });
+ assert.equal(result.status, 400);
+ assert.match(JSON.parse(result.body).message, /larger than 1 MB/);
+ });
+
+ test('without the app secret the webhook answers 503 naming the missing secret', async () => {
+ const body = '{}';
+ const result = await post(app(), body, await metaSignature('IGSECRET', body), {});
+ assert.equal(result.status, 503);
+ assert.match(JSON.parse(result.body).message, /INSTAGRAM_APP_SECRET/);
+ });
+
+ test('when the comments cannot be stored the webhook fails, so Meta delivers it again', async () => {
+ const broken = fakeSupabase(seed(), { ...RPC, automation_rules_for_ig_user: () => { throw new Error('connection refused'); } });
+ const body = JSON.stringify(commentNotification('1784', SENT_AT, [{ id: '555', text: 'GUIDE' }]));
+ const result = await post(app(broken), body, await metaSignature('IGSECRET', body));
+ assert.equal(result.status, 500);
+ assert.equal(JSON.parse(result.body).code, 'DATABASE_ERROR');
+ assert.equal(sends.length, 0);
+ });
+});
diff --git a/backend/tests/services/automationProcessor.test.ts b/backend/tests/services/automationProcessor.test.ts
new file mode 100644
index 0000000..23216c3
--- /dev/null
+++ b/backend/tests/services/automationProcessor.test.ts
@@ -0,0 +1,278 @@
+import { test, describe, beforeEach, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import { createAutomationProcessor } from '../../services/automationProcessor.ts';
+import { CLAIM_LEASE_SECONDS } from '../../lib/automationDelivery.ts';
+import { readAutomationConfig } from '../../lib/config.ts';
+import { createLogger } from '../../lib/logger.ts';
+import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock, FakeReply, RecordedRequest } from '../fixtures/fakeFetch.ts';
+import { fakeAutomationQueue, queueRow } from '../fixtures/fakeAutomationQueue.ts';
+import type { FakeQueue } from '../fixtures/fakeAutomationQueue.ts';
+import { mockRowIds } from '../fixtures/rowIds.ts';
+import type { AutomationConfig } from '../../lib/config.ts';
+import type { Env } from '../../types/env.ts';
+
+const MINUTE = 60 * 1000;
+
+interface SentMessage {
+ igUserId: string;
+ commentId: string;
+ text: string;
+ token: string;
+}
+
+let fetchMock: FetchMock | null = null;
+let sent: SentMessage[] = [];
+
+function readSend(request: RecordedRequest): SentMessage {
+ const body = JSON.parse(request.body!) as { recipient: { comment_id: string }; message: { text: string } };
+ const headers = request.headers as Record<string, string>;
+ return {
+ igUserId: new URL(request.url).pathname.split('/')[2],
+ commentId: body.recipient.comment_id,
+ text: body.message.text,
+ token: headers.Authorization,
+ };
+}
+
+// Instagram's messages endpoint, answering each comment id with the scripted reply, accepted by default
+function instagram(script: Record<string, (count: number) => FakeReply | Error> = {}) {
+ fetchMock = installFetch(request => {
+ const message = readSend(request);
+ sent.push(message);
+ const answer = script[message.commentId];
+ return answer ? answer(sent.filter(item => item.commentId === message.commentId).length) : reply({ recipient_id: 'r', message_id: `m-${message.commentId}` });
+ });
+}
+
+function automation(env: Partial<Env> = {}): AutomationConfig {
+ return readAutomationConfig(env as Env);
+}
+
+function processor(queue: FakeQueue, config = automation(), signal = new AbortController().signal) {
+ return createAutomationProcessor({ comments: queue, automation: config, context: { requestId: 'req-test', signal, log: createLogger() } });
+}
+
+const statuses = (queue: FakeQueue) => Object.fromEntries(queue.rows.map(row => [row.id, row.status]));
+
+beforeEach(() => {
+ sent = [];
+ mockRowIds();
+ mock.method(console, 'log', () => {});
+ mock.method(console, 'warn', () => {});
+ mock.method(console, 'error', () => {});
+});
+afterEach(() => {
+ fetchMock?.restore();
+ fetchMock = null;
+ mock.restoreAll();
+});
+
+describe('automation processor', () => {
+ test('two comments on the same reel at the same moment each get one reply with the rule\'s text and link', async () => {
+ instagram();
+ const queue = fakeAutomationQueue([queueRow('a'), queueRow('b')]);
+ const run = await processor(queue).run();
+ assert.deepEqual(run, { claimed: 2, outcomes: { accepted: 2 } });
+ assert.deepEqual(sent.map(item => item.commentId).sort(), ['c-a', 'c-b']);
+ assert.deepEqual(sent[0], { igUserId: '1784', commentId: 'c-a', text: 'Here is your guide\n\nhttps://example.com/guide', token: 'Bearer TOKEN-1' });
+ assert.equal(queue.rows[0].messageId, 'm-c-a');
+ assert.deepEqual(queue.attempts.map(attempt => attempt.outcome), ['accepted', 'accepted']);
+ });
+
+ test('comments on different reels keep their own rule, account and reply', async () => {
+ instagram();
+ const queue = fakeAutomationQueue([
+ queueRow('guide', { ruleId: 'rule-guide' }),
+ queueRow('course', { ruleId: 'rule-course', accountId: 'ig2', igUserId: '2000' }),
+ queueRow('source', { ruleId: 'rule-source' }),
+ ]);
+ queue.rules.set('rule-course', { id: 'rule-course', enabled: true, replyText: 'Course link', linkUrl: null, hourlyLimit: null });
+ queue.rules.set('rule-source', { id: 'rule-source', enabled: true, replyText: 'Source link', linkUrl: null, hourlyLimit: null });
+ await processor(queue).run();
+ const byComment = Object.fromEntries(sent.map(item => [item.commentId, `${item.igUserId} ${item.token} ${item.text.split('\n')[0]}`]));
+ assert.deepEqual(byComment, {
+ 'c-guide': '1784 Bearer TOKEN-1 Here is your guide',
+ 'c-course': '2000 Bearer TOKEN-2 Course link',
+ 'c-source': '1784 Bearer TOKEN-1 Source link',
+ });
+ });
+
+ test('two runs competing for the same jobs send each reply exactly once', async () => {
+ instagram();
+ const queue = fakeAutomationQueue(Array.from({ length: 8 }, (_, i) => queueRow(`j${i}`)));
+ const [first, second] = await Promise.all([processor(queue).run(), processor(queue).run()]);
+ assert.equal(first.claimed + second.claimed, 8);
+ assert.equal(sent.length, 8);
+ assert.equal(new Set(sent.map(item => item.commentId)).size, 8);
+ });
+
+ test('a burst larger than the batch is spread over runs, and one busy account cannot take a sweep from another', async () => {
+ instagram();
+ const busy = Array.from({ length: 12 }, (_, i) => queueRow(`busy${i}`));
+ const quiet = queueRow('quiet', { accountId: 'ig2', igUserId: '2000' });
+ const queue = fakeAutomationQueue([...busy, quiet]);
+ const run = await processor(queue, automation({ AUTOMATION_BATCH_SIZE: '4' })).run();
+ assert.equal(run.claimed, 3);
+ assert.ok(sent.some(item => item.commentId === 'c-quiet'));
+ assert.equal(queue.rows.filter(row => row.status === 'queued').length, 10);
+ });
+
+ test('a webhook\'s own comments are claimed by id, all at once, leaving older jobs to the sweep', async () => {
+ instagram();
+ const queue = fakeAutomationQueue([queueRow('old'), queueRow('new1'), queueRow('new2')]);
+ const run = await processor(queue).run({ ids: ['new1', 'new2'] });
+ assert.equal(run.claimed, 2);
+ assert.equal(statuses(queue).old, 'queued');
+ });
+
+ test('a timeout after the request left marks the reply for review, and later sweeps never send it again', async () => {
+ instagram({ 'c-lost': () => Object.assign(new Error('The operation was aborted due to timeout'), { name: 'TimeoutError' }) });
+ const queue = fakeAutomationQueue([queueRow('lost')]);
+ await processor(queue).run();
+ assert.equal(statuses(queue).lost, 'needs_review');
+ assert.equal(queue.attempts[0].outcome, 'ambiguous');
+ await processor(queue).run();
+ await processor(queue).run();
+ assert.equal(sent.length, 1);
+ });
+
+ test('a run that stops after claiming returns the job on the next run; one that stops mid-send never resends it', async () => {
+ instagram();
+ const stale = new Date(Date.now() - (CLAIM_LEASE_SECONDS + 60) * 1000).toISOString();
+ const queue = fakeAutomationQueue([
+ queueRow('claimed', { status: 'processing', claimedAt: stale, nextAttemptAt: null }),
+ queueRow('mid-send', { status: 'sending', claimedAt: stale, nextAttemptAt: null, attempts: 1 }),
+ queueRow('held', { status: 'processing', claimedAt: new Date().toISOString(), nextAttemptAt: null }),
+ ]);
+ queue.attempts.push({ id: 'old', commentRowId: 'mid-send', userId: 'user-1', accountId: 'ig1', ruleId: 'rule-guide', recipientId: 'x', outcome: 'sending', startedAt: Date.now() - 30 * MINUTE });
+ await processor(queue).run();
+ assert.deepEqual(statuses(queue), { claimed: 'accepted', 'mid-send': 'needs_review', held: 'processing' });
+ assert.deepEqual(sent.map(item => item.commentId), ['c-claimed']);
+ assert.equal(queue.attempts[0].outcome, 'ambiguous');
+ });
+
+ test('an Instagram rate limit cools the account down; its other replies wait while another account keeps sending', async () => {
+ const usage = JSON.stringify({ '1': [{ estimated_time_to_regain_access: 30 }] });
+ instagram({ 'c-first': () => reply({ error: { message: 'Calls to this api have exceeded the rate limit.', code: 613 } }, 400, 'Bad Request', { 'X-Business-Use-Case-Usage': usage }) });
+ const queue = fakeAutomationQueue([
+ queueRow('first'),
+ queueRow('second', { nextAttemptAt: new Date(Date.now() - 500).toISOString() }),
+ queueRow('other', { accountId: 'ig2', igUserId: '2000' }),
+ ]);
+ const run = await processor(queue).run();
+ assert.deepEqual(run.outcomes, { retry_wait: 2, accepted: 1 });
+ assert.deepEqual(sent.map(item => item.commentId), ['c-first', 'c-other']);
+ const cooldown = Date.parse(queue.controls.get('ig1')!.cooldownUntil!);
+ assert.ok(Math.abs(cooldown - (Date.now() + 30 * MINUTE)) < 5000);
+ assert.equal(queue.rows[1].nextAttemptAt, queue.controls.get('ig1')!.cooldownUntil);
+ assert.equal(queue.attempts[0].outcome, 'rate_limited');
+ });
+
+ test('the account\'s hourly limit holds the rest of a burst until a send frees up, without asking Instagram', async () => {
+ instagram();
+ const queue = fakeAutomationQueue(Array.from({ length: 4 }, (_, i) => queueRow(`b${i}`)));
+ await processor(queue, automation({ AUTOMATION_ACCOUNT_HOURLY_LIMIT: '2', AUTOMATION_BATCH_SIZE: '4' })).run({ ids: ['b0', 'b1', 'b2', 'b3'] });
+ assert.equal(sent.length, 2);
+ assert.deepEqual(queue.rows.map(row => row.statusReason), [null, null, 'account_limit', 'account_limit']);
+ assert.ok(Date.parse(queue.rows[2].nextAttemptAt!) > Date.now() + 59 * MINUTE);
+ });
+
+ test('a person who triggers many rules gets only the daily number of replies', async () => {
+ instagram();
+ const queue = fakeAutomationQueue(['r1', 'r2', 'r3', 'r4'].map(id => queueRow(id, { fromId: 'same-fan' })));
+ await processor(queue).run();
+ assert.equal(sent.length, 3);
+ assert.equal(statuses(queue).r4, 'skipped');
+ });
+
+ test('a temporary Instagram error is retried with backoff and fails for good after five tries', async () => {
+ instagram({ 'c-flaky': () => reply({ error: { message: 'An unexpected error has occurred.', code: 2 } }, 503) });
+ const queue = fakeAutomationQueue([queueRow('flaky')]);
+ for (let run = 1; run <= 5; run++) {
+ await processor(queue).run();
+ const row = queue.rows[0];
+ if (run < 5) {
+ assert.equal(row.status, 'retry_wait');
+ row.nextAttemptAt = new Date(Date.now() - 1000).toISOString();
+ }
+ }
+ assert.equal(statuses(queue).flaky, 'failed');
+ assert.equal(queue.rows[0].attempts, 5);
+ assert.equal(sent.length, 5);
+ await processor(queue).run();
+ assert.equal(sent.length, 5);
+ });
+
+ test('a rule turned off while its replies wait skips them without sending', async () => {
+ instagram();
+ const queue = fakeAutomationQueue([queueRow('waiting')]);
+ queue.rules.get('rule-guide')!.enabled = false;
+ await processor(queue).run();
+ assert.equal(sent.length, 0);
+ assert.equal(queue.rows[0].statusReason, 'rule_disabled');
+ });
+
+ test('a comment Instagram no longer allows a reply to, such as one on a deleted reel, fails with the reason', async () => {
+ instagram({ 'c-gone': () => reply({ error: { message: 'The comment is invalid for a private reply', code: 100, error_subcode: 2534025 } }, 400) });
+ const queue = fakeAutomationQueue([queueRow('gone')]);
+ await processor(queue).run();
+ assert.equal(statuses(queue).gone, 'failed');
+ assert.match(queue.rows[0].errorMessage!, /deleted or older than 7 days/);
+ });
+
+ test('a reply whose 7 days ran out while it waited expires without a send', async () => {
+ instagram();
+ const queue = fakeAutomationQueue([queueRow('late', { expiresAt: new Date(Date.now() - 1000).toISOString() })]);
+ await processor(queue).run();
+ assert.equal(statuses(queue).late, 'expired');
+ assert.equal(sent.length, 0);
+ });
+
+ test('a refused token holds the account\'s replies instead of failing each of them', async () => {
+ instagram({ 'c-t1': () => reply({ error: { message: 'Error validating access token', code: 190 } }, 400) });
+ const queue = fakeAutomationQueue([queueRow('t1'), queueRow('t2')]);
+ await processor(queue, automation({ AUTOMATION_BATCH_SIZE: '1' })).run();
+ await processor(queue, automation({ AUTOMATION_BATCH_SIZE: '1' })).run();
+ assert.equal(queue.controls.get('ig1')!.paused, true);
+ assert.deepEqual(queue.rows.map(row => [row.status, row.statusReason]), [['queued', 'paused'], ['queued', 'paused']]);
+ assert.equal(sent.length, 1);
+ });
+
+ test('pausing this instance sends nothing and claims nothing', async () => {
+ instagram();
+ const queue = fakeAutomationQueue([queueRow('a')]);
+ assert.deepEqual(await processor(queue, automation({ AUTOMATION_PAUSED: 'true' })).run(), { claimed: 0, outcomes: {} });
+ assert.equal(statuses(queue).a, 'queued');
+ });
+
+ test('a database failure on one job leaves it to its lease and the others still go out; recovery sends it once', async () => {
+ instagram();
+ const queue = fakeAutomationQueue([queueRow('a'), queueRow('b')]);
+ queue.failNext('reserve');
+ const run = await processor(queue).run();
+ assert.deepEqual(run.outcomes, { error: 1, accepted: 1 });
+ assert.equal(statuses(queue).a, 'processing');
+ queue.rows[0].claimedAt = new Date(Date.now() - (CLAIM_LEASE_SECONDS + 1) * 1000).toISOString();
+ await processor(queue).run();
+ assert.deepEqual(sent.map(item => item.commentId).sort(), ['c-a', 'c-b']);
+ });
+
+ test('a database that cannot be reached for the claim fails the run, which sends nothing', async () => {
+ instagram();
+ const queue = fakeAutomationQueue([queueRow('a')]);
+ queue.failNext('claim');
+ await assert.rejects(processor(queue).run(), /database unavailable during claim/);
+ assert.equal(sent.length, 0);
+ });
+
+ test('a run whose deadline passed stops before the next job, leaving it for later', async () => {
+ instagram();
+ const queue = fakeAutomationQueue([queueRow('a')]);
+ const controller = new AbortController();
+ controller.abort();
+ const run = await processor(queue, automation(), controller.signal).run();
+ assert.equal(run.claimed, 1);
+ assert.equal(sent.length, 0);
+ });
+});
diff --git a/backend/tests/services/automationWebhookService.test.ts b/backend/tests/services/automationWebhookService.test.ts
new file mode 100644
index 0000000..bd0a80d
--- /dev/null
+++ b/backend/tests/services/automationWebhookService.test.ts
@@ -0,0 +1,125 @@
+import { test, describe, beforeEach, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import { createAutomationWebhookService } from '../../services/automationWebhookService.ts';
+import { readAutomationConfig } from '../../lib/config.ts';
+import { createLogger } from '../../lib/logger.ts';
+import { parseInstagramWebhook } from '../../validators/instagramWebhookValidators.ts';
+import { commentNotification } from '../fixtures/metaWebhook.ts';
+import { fakeAutomationQueue } from '../fixtures/fakeAutomationQueue.ts';
+import type { FakeQueue } from '../fixtures/fakeAutomationQueue.ts';
+import { mockRowIds } from '../fixtures/rowIds.ts';
+import type { AutomationRuleRepository, WebhookRule } from '../../repositories/automationRuleRepository.ts';
+import type { NewAutomationComment } from '../../repositories/automationCommentRepository.ts';
+import type { Env } from '../../types/env.ts';
+
+const SENT_AT = 1792152000;
+
+const RULES: Record<string, WebhookRule[]> = {
+ '1784': [
+ { id: 'reel-a', userId: 'user-1', accountId: 'ig1', keywords: ['GUIDE'], matchMode: 'contains', caseSensitive: false, mediaIds: ['A'] },
+ { id: 'reel-b', userId: 'user-1', accountId: 'ig1', keywords: ['COURSE'], matchMode: 'contains', caseSensitive: false, mediaIds: ['B'] },
+ { id: 'any', userId: 'user-1', accountId: 'ig1', keywords: ['SOURCE'], matchMode: 'contains', caseSensitive: false, mediaIds: [] },
+ ],
+};
+
+function rulesRepository(): AutomationRuleRepository {
+ return { listEnabledForInstagramUser: async (igUserId: string) => RULES[igUserId] ?? [] } as unknown as AutomationRuleRepository;
+}
+
+let inserted: NewAutomationComment[][] = [];
+
+function service(queue: FakeQueue, env: Partial<Env> = {}) {
+ const comments = { ...queue, insertMany: async (rows: NewAutomationComment[]) => { inserted.push(rows); return queue.insertMany(rows); } };
+ return createAutomationWebhookService({
+ rules: rulesRepository(),
+ comments,
+ automation: readAutomationConfig(env as Env),
+ context: { requestId: 'req-test', signal: new AbortController().signal, log: createLogger() },
+ });
+}
+
+const ingest = (queue: FakeQueue, body: Record<string, unknown>) => service(queue).ingest(parseInstagramWebhook(body, SENT_AT * 1000 + 5000));
+
+beforeEach(() => {
+ inserted = [];
+ mockRowIds();
+ mock.method(console, 'log', () => {});
+});
+afterEach(() => mock.restoreAll());
+
+describe('instagram webhook intake', () => {
+ test('comments on three reels at once are stored with the rule meant for each reel', async () => {
+ const queue = fakeAutomationQueue();
+ const result = await ingest(queue, commentNotification('1784', SENT_AT, [
+ { id: '1', text: 'GUIDE please', mediaId: 'A' },
+ { id: '2', text: 'course?', mediaId: 'B' },
+ { id: '3', text: 'source', mediaId: 'C' },
+ ]));
+ assert.equal(result.stored, 3);
+ assert.equal(result.queuedIds.length, 3);
+ assert.deepEqual(queue.rows.map(row => [row.commentId, row.ruleId, row.status]), [['1', 'reel-a', 'queued'], ['2', 'reel-b', 'queued'], ['3', 'any', 'queued']]);
+ assert.equal(inserted[0][0].expiresAt, new Date(SENT_AT * 1000 + 7 * 24 * 60 * 60 * 1000).toISOString());
+ assert.equal(inserted[0][0].text, 'GUIDE please');
+ assert.equal(inserted[0][0].fromUsername, 'fan_1');
+ });
+
+ test('a keyword meant for another reel is counted as no match, and keeps neither the words nor the author', async () => {
+ const queue = fakeAutomationQueue();
+ const result = await ingest(queue, commentNotification('1784', SENT_AT, [{ id: '1', text: 'COURSE', mediaId: 'A' }]));
+ assert.deepEqual(result.queuedIds, []);
+ assert.deepEqual(inserted[0][0], {
+ ...inserted[0][0], ruleId: null, status: 'ignored', statusReason: 'no_match', text: null, fromUsername: null, nextAttemptAt: null,
+ });
+ });
+
+ test('the account\'s own comments and comments without words are never answered', async () => {
+ const queue = fakeAutomationQueue();
+ await ingest(queue, commentNotification('1784', SENT_AT, [
+ { id: '1', text: 'GUIDE', mediaId: 'A', fromId: '1784' },
+ { id: '2', mediaId: 'A' },
+ ]));
+ assert.deepEqual(queue.rows.map(row => [row.status, row.statusReason]), [['ignored', 'own_comment'], ['ignored', 'no_text']]);
+ });
+
+ test('a notification Meta delivers again stores nothing new and queues nothing', async () => {
+ const queue = fakeAutomationQueue();
+ const body = commentNotification('1784', SENT_AT, [{ id: '1', text: 'GUIDE', mediaId: 'A' }, { id: '2', text: 'GUIDE', mediaId: 'A' }]);
+ await ingest(queue, body);
+ const again = await ingest(queue, body);
+ assert.deepEqual(again, { stored: 0, duplicates: 2, queuedIds: [] });
+ assert.equal(queue.rows.length, 2);
+ });
+
+ test('a comment repeated inside one notification is stored once', async () => {
+ const queue = fakeAutomationQueue();
+ const result = await ingest(queue, commentNotification('1784', SENT_AT, [{ id: '1', text: 'GUIDE', mediaId: 'A' }, { id: '1', text: 'GUIDE', mediaId: 'A' }]));
+ assert.equal(result.stored, 1);
+ assert.equal(inserted[0].length, 1);
+ });
+
+ test('comments for an account with no enabled rule are not kept at all', async () => {
+ const queue = fakeAutomationQueue();
+ const result = await ingest(queue, commentNotification('5555', SENT_AT, [{ id: '1', text: 'GUIDE' }]));
+ assert.deepEqual(result, { stored: 0, duplicates: 0, queuedIds: [] });
+ assert.deepEqual(inserted, [[]]);
+ });
+
+ test('a failed insert fails the intake, so the webhook answers with an error and Meta sends it again', async () => {
+ const queue = fakeAutomationQueue();
+ const broken = { ...queue, insertMany: async () => { throw new Error('database unavailable'); } };
+ const intake = createAutomationWebhookService({
+ rules: rulesRepository(), comments: broken, automation: readAutomationConfig({} as Env),
+ context: { requestId: 'req-test', signal: new AbortController().signal, log: createLogger() },
+ });
+ await assert.rejects(intake.ingest(parseInstagramWebhook(commentNotification('1784', SENT_AT, [{ id: '1', text: 'GUIDE', mediaId: 'A' }]))), /database unavailable/);
+ });
+
+ test('the verification challenge is answered only for the configured verify token', async () => {
+ const intake = service(fakeAutomationQueue(), { INSTAGRAM_WEBHOOK_VERIFY_TOKEN: 'tok' });
+ assert.equal(await intake.challengeAnswer({ mode: 'subscribe', verifyToken: 'tok', challenge: '42' }), '42');
+ await assert.rejects(intake.challengeAnswer({ mode: 'subscribe', verifyToken: 'nope', challenge: '42' }), /verify token does not match/);
+ await assert.rejects(intake.challengeAnswer({ mode: 'unsubscribe', verifyToken: 'tok', challenge: '42' }), /verify token does not match/);
+ await assert.rejects(intake.challengeAnswer({ mode: 'subscribe', verifyToken: 'tok' }), /verify token does not match/);
+ await assert.rejects(service(fakeAutomationQueue()).challengeAnswer({ mode: 'subscribe', verifyToken: 'tok', challenge: '1' }), /INSTAGRAM_WEBHOOK_VERIFY_TOKEN/);
+ });
+});
diff --git a/backend/tests/services/retentionService.test.ts b/backend/tests/services/retentionService.test.ts
new file mode 100644
index 0000000..057e099
--- /dev/null
+++ b/backend/tests/services/retentionService.test.ts
@@ -0,0 +1,20 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { AUDIT_RETENTION_DAYS, COMMENT_RETENTION_DAYS, createRetentionService } from '../../services/retentionService.ts';
+import type { AutomationCommentRepository } from '../../repositories/automationCommentRepository.ts';
+import type { AuditRepository } from '../../repositories/auditRepository.ts';
+
+test('comments older than 90 days and audit events older than a year are deleted each day', async () => {
+ const cutoffs: Record<string, string> = {};
+ const comments = { deleteCreatedBefore: async (cutoff: string) => { cutoffs.comments = cutoff; return 4; } } as unknown as AutomationCommentRepository;
+ const audit = { deleteCreatedBefore: async (cutoff: string) => { cutoffs.audit = cutoff; return 1; } } as unknown as AuditRepository;
+ const logged: unknown[] = [];
+ const log = { info: (...args: unknown[]) => logged.push(args), warn() {}, error() {}, with() { return log; } };
+ const now = Date.parse('2026-10-16T00:00:00Z');
+ const run = await createRetentionService({ comments, audit, context: { requestId: 'r', signal: new AbortController().signal, log } }).purge(now);
+ assert.deepEqual(run, { comments: 4, auditEvents: 1 });
+ assert.equal(COMMENT_RETENTION_DAYS, 90);
+ assert.equal(AUDIT_RETENTION_DAYS, 365);
+ assert.deepEqual(cutoffs, { comments: '2026-07-18T00:00:00.000Z', audit: '2025-10-16T00:00:00.000Z' });
+ assert.equal(logged.length, 1);
+});
diff --git a/backend/tests/validators/automationValidators.test.ts b/backend/tests/validators/automationValidators.test.ts
new file mode 100644
index 0000000..ddc43ea
--- /dev/null
+++ b/backend/tests/validators/automationValidators.test.ts
@@ -0,0 +1,88 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ parseActivityQuery, parseAutomationAccount, parseAutomationRule, parseAutomationRuleUpdate, parseAutomationTest, parseStatsQuery,
+ parseWebhookVerification,
+} from '../../validators/automationValidators.ts';
+
+const valid = { accountId: 'ig1', name: 'Guide', keywords: ['GUIDE'], replyText: 'Here it is' };
+
+test('a new rule gets its defaults: contains, ignoring case, every post, off, no link and no own limit', () => {
+ assert.deepEqual(parseAutomationRule(valid), {
+ accountId: 'ig1', name: 'Guide', keywords: ['GUIDE'], matchMode: 'contains', caseSensitive: false, mediaIds: [],
+ replyText: 'Here it is', linkUrl: null, enabled: false, hourlyLimit: null,
+ });
+});
+
+test('keywords are trimmed, blanks dropped and repeats removed, ignoring case unless the rule is case sensitive', () => {
+ assert.deepEqual(parseAutomationRule({ ...valid, keywords: [' guide ', 'GUIDE', '', 'Course'] }).keywords, ['guide', 'Course']);
+ assert.deepEqual(parseAutomationRule({ ...valid, caseSensitive: true, keywords: ['guide', 'GUIDE'] }).keywords, ['guide', 'GUIDE']);
+});
+
+test('a rule needs an account, a name, a keyword and a reply, each with a message saying what to add', () => {
+ assert.throws(() => parseAutomationRule({ ...valid, accountId: '' }), /Choose the Instagram account/);
+ assert.throws(() => parseAutomationRule({ ...valid, name: ' ' }), /Give the rule a name/);
+ assert.throws(() => parseAutomationRule({ ...valid, keywords: [' '] }), /Add at least one keyword/);
+ assert.throws(() => parseAutomationRule({ ...valid, keywords: 'GUIDE' }), /keywords must be a list of words/);
+ assert.throws(() => parseAutomationRule({ ...valid, replyText: '' }), /Write the reply to send/);
+});
+
+test('sizes are capped: name, keyword count and length, reply and posts', () => {
+ assert.throws(() => parseAutomationRule({ ...valid, name: 'x'.repeat(81) }), /at most 80/);
+ assert.throws(() => parseAutomationRule({ ...valid, keywords: Array.from({ length: 11 }, (_, i) => `k${i}`) }), /at most 10 keywords/);
+ assert.throws(() => parseAutomationRule({ ...valid, keywords: ['x'.repeat(101)] }), /at most 100/);
+ assert.throws(() => parseAutomationRule({ ...valid, replyText: 'x'.repeat(1001) }), /at most 1000/);
+ assert.throws(() => parseAutomationRule({ ...valid, mediaIds: Array.from({ length: 51 }, (_, i) => String(i)) }), /at most 50 posts/);
+ assert.throws(() => parseAutomationRule({ ...valid, mediaIds: ['abc'] }), /Instagram post ids/);
+});
+
+test('the link must be https, without a user name or password', () => {
+ assert.equal(parseAutomationRule({ ...valid, linkUrl: ' https://example.com/guide ' }).linkUrl, 'https://example.com/guide');
+ assert.equal(parseAutomationRule({ ...valid, linkUrl: '' }).linkUrl, null);
+ assert.throws(() => parseAutomationRule({ ...valid, linkUrl: 'http://example.com' }), /must start with https/);
+ assert.throws(() => parseAutomationRule({ ...valid, linkUrl: 'javascript:alert(1)' }), /must start with https/);
+ assert.throws(() => parseAutomationRule({ ...valid, linkUrl: 'example.com' }), /full address/);
+ assert.throws(() => parseAutomationRule({ ...valid, linkUrl: 'https://user:[email protected]' }), /user name or password/);
+});
+
+test('the hourly limit is a whole number up to Instagram\'s 750, or null for none', () => {
+ assert.equal(parseAutomationRule({ ...valid, hourlyLimit: 30 }).hourlyLimit, 30);
+ assert.equal(parseAutomationRule({ ...valid, hourlyLimit: null }).hourlyLimit, null);
+ assert.throws(() => parseAutomationRule({ ...valid, hourlyLimit: 751 }), /from 1 to 750/);
+ assert.throws(() => parseAutomationRule({ ...valid, hourlyLimit: 2.5 }), /from 1 to 750/);
+ assert.throws(() => parseAutomationRule({ ...valid, matchMode: 'regex' }), /contains or exact/);
+});
+
+test('an update keeps only the fields sent, can clear the link and the limit, and refuses an empty body', () => {
+ assert.deepEqual(parseAutomationRuleUpdate({ enabled: true }), { enabled: true });
+ assert.deepEqual(parseAutomationRuleUpdate({ linkUrl: null, hourlyLimit: null, accountId: 'other' }), { linkUrl: null, hourlyLimit: null });
+ assert.deepEqual(parseAutomationRuleUpdate({ keywords: ['a', 'A'], caseSensitive: true }), { keywords: ['a', 'A'], caseSensitive: true });
+ assert.throws(() => parseAutomationRuleUpdate({}), /Nothing to change/);
+ assert.throws(() => parseAutomationRuleUpdate({ name: '' }), /Give the rule a name/);
+});
+
+test('a test needs a sample comment besides the rule draft', () => {
+ const parsed = parseAutomationTest({ keywords: ['GUIDE'], replyText: 'Hi', comment: ' guide ', mediaId: '' });
+ assert.equal(parsed.comment, 'guide');
+ assert.equal(parsed.mediaId, undefined);
+ assert.throws(() => parseAutomationTest({ keywords: ['GUIDE'], replyText: 'Hi' }), /Type a sample comment/);
+});
+
+test('activity filters are checked and dates normalised; the page size defaults to 50 and stops at 100', () => {
+ assert.deepEqual(parseActivityQuery({ status: 'failed', from: '2026-10-01', before: '2026-10-10T00:00:00Z' }), {
+ accountId: undefined, ruleId: undefined, status: 'failed', from: '2026-10-01T00:00:00.000Z', to: undefined,
+ before: '2026-10-10T00:00:00.000Z', limit: 50,
+ });
+ assert.equal(parseActivityQuery({ limit: '100' }).limit, 100);
+ assert.throws(() => parseActivityQuery({ limit: '101' }), /from 1 to 100/);
+ assert.throws(() => parseActivityQuery({ status: 'lost' }), /status must be one of/);
+ assert.throws(() => parseStatsQuery({ from: 'yesterday' }), /from must be a date/);
+});
+
+test('pausing needs a true or false, and the webhook check reads the hub parameters', () => {
+ assert.deepEqual(parseAutomationAccount({ paused: false }), { paused: false });
+ assert.throws(() => parseAutomationAccount({}), /paused must be true or false/);
+ assert.deepEqual(parseWebhookVerification({ 'hub.mode': 'subscribe', 'hub.verify_token': 'tok', 'hub.challenge': '123' }), {
+ mode: 'subscribe', verifyToken: 'tok', challenge: '123',
+ });
+});
diff --git a/backend/tests/validators/instagramWebhookValidators.test.ts b/backend/tests/validators/instagramWebhookValidators.test.ts
new file mode 100644
index 0000000..2fb8025
--- /dev/null
+++ b/backend/tests/validators/instagramWebhookValidators.test.ts
@@ -0,0 +1,57 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { parseInstagramWebhook } from '../../validators/instagramWebhookValidators.ts';
+
+const NOW = Date.parse('2026-10-16T12:00:00Z');
+
+test('a comments notification becomes one event per comment, with the time Meta sent it', () => {
+ const parsed = parseInstagramWebhook({
+ object: 'instagram',
+ entry: [{
+ id: '1784',
+ time: 1792152000,
+ changes: [{
+ field: 'comments',
+ value: { id: '555', text: 'GUIDE', parent_id: '444', from: { id: '77', username: 'fan' }, media: { id: '9001', media_product_type: 'REELS' } },
+ }],
+ }],
+ }, NOW);
+ assert.deepEqual(parsed, {
+ comments: [{
+ igUserId: '1784', commentId: '555', text: 'GUIDE', fromId: '77', fromUsername: 'fan', mediaId: '9001',
+ mediaProductType: 'REELS', parentId: '444', notifiedAt: 1792152000 * 1000,
+ }],
+ unsupported: 0,
+ });
+});
+
+test('the comment id is read from comment_id too, and numeric ids are kept as text', () => {
+ const parsed = parseInstagramWebhook({ object: 'instagram', entry: [{ id: 1784, time: 1, changes: [{ field: 'comments', value: { comment_id: 556 } }] }] }, NOW);
+ assert.equal(parsed.comments[0].commentId, '556');
+ assert.equal(parsed.comments[0].igUserId, '1784');
+ assert.equal(parsed.comments[0].text, null);
+ assert.equal(parsed.comments[0].fromId, null);
+});
+
+test('other fields, messaging entries and comments without an id are counted and dropped, never an error', () => {
+ const parsed = parseInstagramWebhook({
+ object: 'instagram',
+ entry: [
+ { id: '1', time: 1, changes: [{ field: 'mentions', value: { media_id: '1' } }, { field: 'comments', value: { text: 'no id' } }] },
+ { id: '2', time: 1, messaging: [{ sender: { id: '3' } }] },
+ { id: 'not valid id!', changes: [] },
+ 'junk',
+ ],
+ }, NOW);
+ assert.deepEqual(parsed, { comments: [], unsupported: 5 });
+});
+
+test('a missing or future time falls back to now', () => {
+ const parsed = parseInstagramWebhook({ object: 'instagram', entry: [{ id: '1', time: 9_999_999_999, changes: [{ field: 'comments', value: { id: '5' } }] }] }, NOW);
+ assert.equal(parsed.comments[0].notifiedAt, NOW);
+});
+
+test('a body that is not an Instagram notification is refused', () => {
+ assert.throws(() => parseInstagramWebhook({ object: 'page', entry: [] }), /Only Instagram webhook notifications/);
+ assert.throws(() => parseInstagramWebhook({ object: 'instagram' }), /no entry list/);
+});
diff --git a/backend/types/env.ts b/backend/types/env.ts
index 1df22fb..35be62e 100644
--- a/backend/types/env.ts
+++ b/backend/types/env.ts
@@ -21,4 +21,17 @@ export interface Env {
EMAIL_FROM?: string;
// emails a day across all users; defaults to 100, Resend's free daily quota
EMAIL_DAILY_LIMIT?: string;
+ // the Verify Token typed into the Meta dashboard's webhook settings
+ INSTAGRAM_WEBHOOK_VERIFY_TOKEN?: string;
+ // the Meta app secret (App settings, Basic); webhooks are checked against it as well as INSTAGRAM_APP_SECRET
+ META_APP_SECRET?: string;
+ // "true" holds every comment-to-DM reply on this instance; comments are still recorded
+ AUTOMATION_PAUSED?: string;
+ // private replies per hour and per day; each falls back to its default when missing or invalid
+ AUTOMATION_ACCOUNT_HOURLY_LIMIT?: string;
+ AUTOMATION_USER_HOURLY_LIMIT?: string;
+ AUTOMATION_GLOBAL_HOURLY_LIMIT?: string;
+ AUTOMATION_RECIPIENT_DAILY_LIMIT?: string;
+ // replies sent by one webhook request or one sweep
+ AUTOMATION_BATCH_SIZE?: string;
}
diff --git a/backend/validators/automationValidators.ts b/backend/validators/automationValidators.ts
new file mode 100644
index 0000000..f1fd64a
--- /dev/null
+++ b/backend/validators/automationValidators.ts
@@ -0,0 +1,219 @@
+import { ValidationError } from '../lib/errors.ts';
+import { isString, optionalArray, optionalBoolean, optionalNumber, optionalString, presentField, requiredString } from './fields.ts';
+import type { Fields } from './fields.ts';
+import type {
+ AutomationAccountRequest, AutomationCommentStatus, AutomationMatchMode, AutomationRuleRequest, AutomationRuleUpdateRequest,
+ AutomationTestRequest,
+} from '../../shared/types/automation.ts';
+
+const MATCH_MODES: AutomationMatchMode[] = ['contains', 'exact'];
+const STATUSES: AutomationCommentStatus[] = ['ignored', 'queued', 'processing', 'retry_wait', 'sending', 'accepted', 'failed', 'needs_review', 'skipped', 'expired'];
+const MAX_NAME = 80;
+const MAX_KEYWORDS = 10;
+const MAX_KEYWORD = 100;
+const MAX_MEDIA = 50;
+const MAX_REPLY = 1000;
+const MAX_URL = 2000;
+// Instagram allows 750 private replies an hour per account
+const MAX_HOURLY_LIMIT = 750;
+const MAX_TEST_COMMENT = 2200;
+const DEFAULT_PAGE = 50;
+const MAX_PAGE = 100;
+
+export interface ActivityQuery {
+ accountId?: string;
+ ruleId?: string;
+ status?: AutomationCommentStatus;
+ from?: string;
+ to?: string;
+ before?: string;
+ limit: number;
+}
+
+export interface StatsQuery {
+ accountId?: string;
+ ruleId?: string;
+ from?: string;
+ to?: string;
+}
+
+export interface WebhookVerification {
+ mode?: string;
+ verifyToken?: string;
+ challenge?: string;
+}
+
+function name(body: Fields): string {
+ const value = requiredString(body, 'name', 'Give the rule a name');
+ if (value.length > MAX_NAME) throw new ValidationError(`The rule name can be at most ${MAX_NAME} characters`);
+ return value;
+}
+
+// trimmed, without blanks or repeats, so "guide" and "GUIDE " count once when matching ignores case
+function keywords(body: Fields, caseSensitive: boolean): string[] {
+ const list = optionalArray(body, 'keywords', isString, 'words') ?? [];
+ const seen = new Set<string>();
+ const kept: string[] = [];
+ for (const keyword of list.map(item => item.trim()).filter(Boolean)) {
+ if (keyword.length > MAX_KEYWORD) throw new ValidationError(`A keyword can be at most ${MAX_KEYWORD} characters`);
+ const key = caseSensitive ? keyword : keyword.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ kept.push(keyword);
+ }
+ if (kept.length === 0) throw new ValidationError('Add at least one keyword');
+ if (kept.length > MAX_KEYWORDS) throw new ValidationError(`A rule can have at most ${MAX_KEYWORDS} keywords`);
+ return kept;
+}
+
+function matchMode(body: Fields): AutomationMatchMode | undefined {
+ const value = optionalString(body, 'matchMode');
+ if (!value) return undefined;
+ if (!MATCH_MODES.includes(value as AutomationMatchMode)) throw new ValidationError('matchMode must be contains or exact');
+ return value as AutomationMatchMode;
+}
+
+function mediaIds(body: Fields): string[] | undefined {
+ const list = optionalArray(body, 'mediaIds', isString, 'post ids');
+ if (!list) return undefined;
+ const ids = [...new Set(list.map(item => item.trim()).filter(Boolean))];
+ if (ids.some(id => !/^\d+$/.test(id))) throw new ValidationError('mediaIds must be Instagram post ids');
+ if (ids.length > MAX_MEDIA) throw new ValidationError(`A rule can name at most ${MAX_MEDIA} posts; leave the list empty to cover every post`);
+ return ids;
+}
+
+function replyText(body: Fields): string {
+ const value = requiredString(body, 'replyText', 'Write the reply to send');
+ if (value.length > MAX_REPLY) throw new ValidationError(`The reply can be at most ${MAX_REPLY} characters`);
+ return value;
+}
+
+// only https links without a user name or password, since the link goes to strangers in a private message
+function linkUrl(body: Fields): string | null | undefined {
+ if (!presentField(body, 'linkUrl')) return undefined;
+ const value = optionalString(body, 'linkUrl');
+ if (!value) return null;
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ throw new ValidationError('The link must be a full address starting with https://');
+ }
+ if (url.protocol !== 'https:') throw new ValidationError('The link must start with https://');
+ if (url.username || url.password) throw new ValidationError('The link cannot contain a user name or password');
+ if (value.length > MAX_URL) throw new ValidationError(`The link can be at most ${MAX_URL} characters`);
+ return value;
+}
+
+function hourlyLimit(body: Fields): number | null | undefined {
+ if (!presentField(body, 'hourlyLimit')) return undefined;
+ const value = optionalNumber(body, 'hourlyLimit');
+ if (value === undefined) return null;
+ if (!Number.isInteger(value) || value < 1 || value > MAX_HOURLY_LIMIT) {
+ throw new ValidationError(`The hourly limit must be a whole number from 1 to ${MAX_HOURLY_LIMIT}`);
+ }
+ return value;
+}
+
+function isoDate(query: Fields, field: string): string | undefined {
+ const value = optionalString(query, field);
+ if (!value) return undefined;
+ const time = Date.parse(value);
+ if (Number.isNaN(time)) throw new ValidationError(`${field} must be a date`);
+ return new Date(time).toISOString();
+}
+
+function status(query: Fields): AutomationCommentStatus | undefined {
+ const value = optionalString(query, 'status');
+ if (!value) return undefined;
+ if (!STATUSES.includes(value as AutomationCommentStatus)) throw new ValidationError(`status must be one of ${STATUSES.join(', ')}`);
+ return value as AutomationCommentStatus;
+}
+
+export function parseAutomationRule(body: Fields): AutomationRuleRequest {
+ const caseSensitive = optionalBoolean(body, 'caseSensitive') ?? false;
+ return {
+ accountId: requiredString(body, 'accountId', 'Choose the Instagram account'),
+ name: name(body),
+ keywords: keywords(body, caseSensitive),
+ matchMode: matchMode(body) ?? 'contains',
+ caseSensitive,
+ mediaIds: mediaIds(body) ?? [],
+ replyText: replyText(body),
+ linkUrl: linkUrl(body) ?? null,
+ enabled: optionalBoolean(body, 'enabled') ?? false,
+ hourlyLimit: hourlyLimit(body) ?? null,
+ };
+}
+
+// only the fields present in the body change; accountId is ignored, a rule stays on its account
+export function parseAutomationRuleUpdate(body: Fields): AutomationRuleUpdateRequest {
+ const changes: AutomationRuleUpdateRequest = {};
+ const caseSensitive = optionalBoolean(body, 'caseSensitive');
+ if (presentField(body, 'name')) changes.name = name(body);
+ if (presentField(body, 'keywords')) changes.keywords = keywords(body, caseSensitive ?? false);
+ if (presentField(body, 'matchMode')) changes.matchMode = matchMode(body);
+ if (caseSensitive !== undefined) changes.caseSensitive = caseSensitive;
+ if (presentField(body, 'mediaIds')) changes.mediaIds = mediaIds(body);
+ if (presentField(body, 'replyText')) changes.replyText = replyText(body);
+ if (presentField(body, 'linkUrl')) changes.linkUrl = linkUrl(body);
+ if (presentField(body, 'enabled')) changes.enabled = optionalBoolean(body, 'enabled');
+ if (presentField(body, 'hourlyLimit')) changes.hourlyLimit = hourlyLimit(body);
+ if (Object.keys(changes).length === 0) throw new ValidationError('Nothing to change: send at least one rule field');
+ return changes;
+}
+
+export function parseAutomationTest(body: Fields): AutomationTestRequest {
+ const caseSensitive = optionalBoolean(body, 'caseSensitive') ?? false;
+ const comment = requiredString(body, 'comment', 'Type a sample comment to test');
+ if (comment.length > MAX_TEST_COMMENT) throw new ValidationError(`A comment can be at most ${MAX_TEST_COMMENT} characters`);
+ return {
+ keywords: keywords(body, caseSensitive),
+ matchMode: matchMode(body) ?? 'contains',
+ caseSensitive,
+ mediaIds: mediaIds(body) ?? [],
+ replyText: replyText(body),
+ linkUrl: linkUrl(body) ?? null,
+ comment,
+ mediaId: optionalString(body, 'mediaId') || undefined,
+ };
+}
+
+export function parseActivityQuery(query: Fields): ActivityQuery {
+ const limitText = optionalString(query, 'limit');
+ const limit = limitText ? Number(limitText) : DEFAULT_PAGE;
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_PAGE) throw new ValidationError(`limit must be a whole number from 1 to ${MAX_PAGE}`);
+ return {
+ accountId: optionalString(query, 'accountId') || undefined,
+ ruleId: optionalString(query, 'ruleId') || undefined,
+ status: status(query),
+ from: isoDate(query, 'from'),
+ to: isoDate(query, 'to'),
+ before: isoDate(query, 'before'),
+ limit,
+ };
+}
+
+export function parseStatsQuery(query: Fields): StatsQuery {
+ return {
+ accountId: optionalString(query, 'accountId') || undefined,
+ ruleId: optionalString(query, 'ruleId') || undefined,
+ from: isoDate(query, 'from'),
+ to: isoDate(query, 'to'),
+ };
+}
+
+export function parseAutomationAccount(body: Fields): AutomationAccountRequest {
+ const paused = optionalBoolean(body, 'paused');
+ if (paused === undefined) throw new ValidationError('paused must be true or false');
+ return { paused };
+}
+
+// Meta's verification request: GET with hub.mode, hub.verify_token and hub.challenge
+export function parseWebhookVerification(query: Fields): WebhookVerification {
+ return {
+ mode: optionalString(query, 'hub.mode') || undefined,
+ verifyToken: optionalString(query, 'hub.verify_token') || undefined,
+ challenge: optionalString(query, 'hub.challenge') || undefined,
+ };
+}
diff --git a/backend/validators/instagramWebhookValidators.ts b/backend/validators/instagramWebhookValidators.ts
new file mode 100644
index 0000000..ba29c39
--- /dev/null
+++ b/backend/validators/instagramWebhookValidators.ts
@@ -0,0 +1,81 @@
+import { ValidationError } from '../lib/errors.ts';
+import { isObject } from './fields.ts';
+import type { Fields } from './fields.ts';
+
+// one comment on a post or reel of a connected professional account, as Meta's comments webhook describes it
+export interface InstagramCommentEvent {
+ // the professional account the comment was made on (the entry id)
+ igUserId: string;
+ commentId: string;
+ text: string | null;
+ fromId: string | null;
+ fromUsername: string | null;
+ mediaId: string | null;
+ mediaProductType: string | null;
+ parentId: string | null;
+ // when Meta sent the notification, in milliseconds
+ notifiedAt: number;
+}
+
+export interface InstagramWebhook {
+ comments: InstagramCommentEvent[];
+ // changes for other fields, or comments missing their id, which are acknowledged and dropped
+ unsupported: number;
+}
+
+function text(value: unknown): string | null {
+ return typeof value === 'string' && value !== '' ? value : null;
+}
+
+// Meta's ids are numeric strings, but a number is read the same way rather than dropped
+function id(value: unknown): string | null {
+ if (typeof value === 'number' && Number.isSafeInteger(value)) return String(value);
+ return typeof value === 'string' && /^[0-9A-Za-z_-]{1,64}$/.test(value) ? value : null;
+}
+
+function comment(entryId: string, notifiedAt: number, value: Fields): InstagramCommentEvent | null {
+ // Meta's examples name the comment id both id and comment_id
+ const commentId = id(value.id) ?? id(value.comment_id);
+ if (!commentId) return null;
+ const from = isObject(value.from) ? value.from : {};
+ const media = isObject(value.media) ? value.media : {};
+ return {
+ igUserId: entryId,
+ commentId,
+ text: text(value.text),
+ fromId: id(from.id),
+ fromUsername: text(from.username),
+ mediaId: id(media.id),
+ mediaProductType: text(media.media_product_type),
+ parentId: id(value.parent_id),
+ notifiedAt,
+ };
+}
+
+// a body that is not an Instagram notification at all is refused; inside one, anything but a comment is skipped
+export function parseInstagramWebhook(body: Fields, now = Date.now()): InstagramWebhook {
+ if (body.object !== 'instagram') throw new ValidationError('Only Instagram webhook notifications are accepted here');
+ if (!Array.isArray(body.entry)) throw new ValidationError('The notification has no entry list');
+
+ const comments: InstagramCommentEvent[] = [];
+ let unsupported = 0;
+ for (const entry of body.entry) {
+ const entryId = isObject(entry) ? id(entry.id) : null;
+ if (!isObject(entry) || !entryId) {
+ unsupported++;
+ continue;
+ }
+ // time is in seconds; a missing or odd value falls back to now, and a reply sent after Instagram's window is refused there
+ const sentAt = typeof entry.time === 'number' && entry.time > 0 ? Math.min(entry.time * 1000, now) : now;
+ const changes = Array.isArray(entry.changes) ? entry.changes : [];
+ if (changes.length === 0) unsupported++;
+ for (const change of changes) {
+ const parsed = isObject(change) && change.field === 'comments' && isObject(change.value)
+ ? comment(entryId, sentAt, change.value)
+ : null;
+ if (parsed) comments.push(parsed);
+ else unsupported++;
+ }
+ }
+ return { comments, unsupported };
+}
diff --git a/backend/wrangler.toml b/backend/wrangler.toml
index db4ed76..94989a9 100644
--- a/backend/wrangler.toml
+++ b/backend/wrangler.toml
@@ -3,4 +3,4 @@ main = "server.ts"
compatibility_date = "2025-01-01"
[triggers]
-crons = ["*/15 * * * *", "0 0 * * *"]
+crons = ["*/5 * * * *", "0 0 * * *"]
diff --git a/frontend/src/features/accounts/accountManagerData.ts b/frontend/src/features/accounts/accountManagerData.ts
index bf7a0f8..b17e657 100644
--- a/frontend/src/features/accounts/accountManagerData.ts
+++ b/frontend/src/features/accounts/accountManagerData.ts
@@ -27,6 +27,8 @@ export interface AccountSectionInfo {
export interface OAuthReturn {
connected: boolean;
+ // the account was already connected, and connecting it again renewed its token
+ reconnected: boolean;
errorMessage: string | null;
openAdd: boolean;
}
@@ -55,7 +57,7 @@ export function instagramErrorMessage(code: string): string {
return IG_ERRORS[code] || `Instagram connection failed: ${code}. ${TESTER_HINT}`;
}
-// oauth returns ?ig_connected=true or ?ig_error=...; ?add=1 opens the add flow
+// oauth returns ?ig_connected=true, ?ig_connected=reconnected or ?ig_error=...; ?add=1 opens the add flow
export function readOAuthReturn(searchParams: URLSearchParams): OAuthReturn | null {
const connected = searchParams.get('ig_connected');
const igError = searchParams.get('ig_error');
@@ -63,7 +65,8 @@ export function readOAuthReturn(searchParams: URLSearchParams): OAuthReturn | nu
if (!connected && !igError && !add) return null;
return {
- connected: connected === 'true',
+ connected: connected === 'true' || connected === 'reconnected',
+ reconnected: connected === 'reconnected',
errorMessage: igError ? instagramErrorMessage(igError) : null,
openAdd: Boolean(add),
};
diff --git a/frontend/src/features/accounts/useInstagramOAuthReturn.ts b/frontend/src/features/accounts/useInstagramOAuthReturn.ts
index c27c906..c2bdb36 100644
--- a/frontend/src/features/accounts/useInstagramOAuthReturn.ts
+++ b/frontend/src/features/accounts/useInstagramOAuthReturn.ts
@@ -15,7 +15,7 @@ export function useInstagramOAuthReturn({ showToast, loadAccounts, setDialogOpen
if (!result) return;
if (result.connected) {
- showToast('Instagram account connected');
+ showToast(result.reconnected ? 'Instagram account reconnected' : 'Instagram account connected');
loadAccounts();
} else if (result.errorMessage) {
showToast(result.errorMessage, 'error');
diff --git a/frontend/tests/features/accounts/accountManagerData.test.ts b/frontend/tests/features/accounts/accountManagerData.test.ts
index 2b9016c..4e8d0a8 100644
--- a/frontend/tests/features/accounts/accountManagerData.test.ts
+++ b/frontend/tests/features/accounts/accountManagerData.test.ts
@@ -21,11 +21,15 @@ test('a return without OAuth or add parameters does nothing', () => {
});
test('a successful connection is reported without an error', () => {
- assert.deepEqual(readOAuthReturn(params('ig_connected=true')), { connected: true, errorMessage: null, openAdd: false });
+ assert.deepEqual(readOAuthReturn(params('ig_connected=true')), { connected: true, reconnected: false, errorMessage: null, openAdd: false });
+});
+
+test('connecting an account that was already there is reported as a reconnection', () => {
+ assert.deepEqual(readOAuthReturn(params('ig_connected=reconnected')), { connected: true, reconnected: true, errorMessage: null, openAdd: false });
});
test('connected values other than true are dropped silently', () => {
- assert.deepEqual(readOAuthReturn(params('ig_connected=false')), { connected: false, errorMessage: null, openAdd: false });
+ assert.deepEqual(readOAuthReturn(params('ig_connected=false')), { connected: false, reconnected: false, errorMessage: null, openAdd: false });
});
test('errors and the add flag are read together', () => {