From d35f2aec4b6460e90da89aa1d3900f52f9d91269 Mon Sep 17 00:00:00 2001 From: ankurmans <12939357+ankurmans@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:05:54 +0300 Subject: [PATCH] Close the agent capability gaps: approval by default, approvers, key limits, activity audit - New accounts start every newsletter with "Ask me before an agent sends" on, which now also holds billing changes, for every key, MCP session and OAuth app; older accounts keep their behavior and the Approvals page offers it. - Team approvers per newsletter and an optional code by email to approve sends and deletes; the log names who decided and how. - Activity log: owner-chosen retention (30/90/180/365), filter by client, CSV export, auditRead keys, team members' changes recorded by name and role. - API keys can be limited to a list of actions and to IP addresses or CIDR ranges; OAuth apps can be limited to one newsletter on the consent page. - RateLimit-* headers on every API and MCP answer; team roles documented from the table the check reads. docs/capability-gaps/STATUS.md has the per-gap status, the plan report (G9), behavior changes and the rollout order. --- AGENTS.md | 2 +- README.md | 6 +- SECURITY.md | 8 +- app/(app)/agent-activity/actions.js | 10 + app/(app)/agent-activity/export/route.js | 28 ++ app/(app)/agent-activity/page.js | 33 +- app/(app)/approvals/actions.js | 17 +- app/(app)/approvals/page.js | 33 +- app/oauth/consent/actions.js | 2 +- app/oauth/consent/page.js | 27 ++ components/CardAgentApproval.jsx | 23 +- components/CardApproval.jsx | 29 +- components/CardApprovalPeople.jsx | 84 +++++ components/SelectActivityRetention.jsx | 49 +++ docs/capability-gaps/STATUS.md | 48 +++ lib/accounts.js | 2 +- lib/action-scopes.js | 30 +- lib/actions/agent-safety.js | 160 +++++++-- lib/actions/agents.js | 17 +- lib/actions/api-keys.js | 49 ++- lib/actions/connected-apps.js | 2 + lib/actions/manifest.js | 4 + lib/actions/newsletters.js | 3 +- lib/actions/run-action.js | 25 ++ lib/actions/team.js | 33 +- lib/agent-activity-rules.js | 28 ++ lib/agent-activity.js | 83 ++++- lib/agent-guard.js | 33 +- lib/api-keys.js | 21 +- lib/api/rest.js | 25 +- lib/approval-rules.js | 10 + lib/approvals.js | 84 ++++- lib/docs/agent-safety.js | 54 ++- lib/ip-allowlist.js | 80 +++++ lib/mcp/server.js | 15 +- lib/oauth-apps.js | 2 + lib/oauth.js | 12 +- lib/rate-limit.js | 49 ++- lib/team.js | 24 +- migrations/0051_agent_activity_client.sql | 1 + models/Account.js | 7 + models/AgentActivity.js | 18 +- models/AgentDay.js | 2 + models/ApiKey.js | 6 + models/ApprovalRequest.js | 4 + models/Newsletter.js | 3 + models/TeamSeat.js | 2 + tests/agent-activity.test.mjs | 10 +- tests/capability-gaps.test.mjs | 385 ++++++++++++++++++++++ tests/helpers/agents.mjs | 6 +- tests/helpers/app.mjs | 5 +- tests/oauth.test.mjs | 2 +- 52 files changed, 1537 insertions(+), 158 deletions(-) create mode 100644 app/(app)/agent-activity/actions.js create mode 100644 app/(app)/agent-activity/export/route.js create mode 100644 components/CardApprovalPeople.jsx create mode 100644 components/SelectActivityRetention.jsx create mode 100644 docs/capability-gaps/STATUS.md create mode 100644 lib/ip-allowlist.js create mode 100644 migrations/0051_agent_activity_client.sql create mode 100644 tests/capability-gaps.test.mjs diff --git a/AGENTS.md b/AGENTS.md index 3f82d14d..d3e0aaca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ Next.js App Router in JavaScript, Tailwind CSS with shadcn/ui, Cloudflare D1 thr - **Actions**: every customer action is one `defineAction` in `lib/actions/.js` (schemas, permission, handler). `runAction` is the only way to run one: from the dashboard's server actions, the REST API (`app/api/v1`) and MCP (`/mcp`, `lib/mcp/server.js`). The docs, the OpenAPI document and the llms files are generated from the same schemas, and `tests/parity.test.mjs` fails when an action is missing from any of them. - **Accounts**: `scoped(account, filter)` (`lib/account-scope.js`) adds the account to every query, and `lib/docdb/model.js` refuses customer queries without one. `requireAccount()` for pages and server actions, `authenticateRequest()` for the API and MCP (`lib/auth.js`, `lib/api-keys.js`). - **MCP and OAuth**: API keys, or OAuth access tokens from Better Auth's OAuth provider (`lib/auth.js`, `lib/oauth.js`, `lib/oauth-rules.js`), with the consent page at `app/oauth/consent`. A rotation of `BETTER_AUTH_SECRET` keeps the old value in `BETTER_AUTH_SECRET_PREVIOUS` (`docs/AUTH-ROTATION.md`, `scripts/rotate-auth-secret.sh`): anything that checks a signature made from the secret tries `getAppSecrets()` (`lib/app-keys.js` for links), never signs with a previous one, and the OAuth signing key is kept readable by `lib/auth-keyring.js`. A new token or link kind uses `lib/app-keys.js`, not its own `hkdfSync` of `getAppSecret()`. `scripts/check-mcp-auth.mjs` is the post-deploy check. -- **Agent safety**: a key or an OAuth grant has a level (`read_only`, `drafts`, `send_with_approval`, `full`, `signups`) that allows some scope classes, and every action has a class in `lib/action-scopes.js` (the one table: a test fails for an action without one, or without a newsletter target). `runAction` sends keys and apps through `lib/agent-guard.js`: level, the key's one newsletter, daily cap, then either the action or an approval request (`lib/approvals.js`, `ApprovalRequest`, answered `202`/`approval_required`) when its class is send or destructive for a send with approval key or a newsletter that asks (`Newsletter.agentApproval`). Deciding an approval and that setting are `dashboardOnly` actions: in the registry, but not in `ACTIONS`, so no route, tool or docs page. Calls that change something or read contacts go in `AgentActivity` (ids and counts, never bodies), the cron purges it (`lib/agent-housekeeping.js`). A new action needs its class in `lib/action-scopes.js`. +- **Agent safety**: a key or an OAuth grant has a level (`read_only`, `drafts`, `send_with_approval`, `full`, `signups`) that allows some scope classes, and every action has a class in `lib/action-scopes.js` (the one table: a test fails for an action without one, or without a newsletter target). `runAction` sends keys and apps through `lib/agent-guard.js`: level, the key's one newsletter, daily cap, then either the action or an approval request (`lib/approvals.js`, `ApprovalRequest`, answered `202`/`approval_required`) when its class is send or destructive for a send with approval key or a newsletter that asks (`Newsletter.agentApproval`, on from the start for accounts with `agentApprovalByDefault`, and also holding billing changes). A key's `allowedActions` and `allowedIps` (`lib/ip-allowlist.js`) and an app's one newsletter (from the consent page) are checked there too. Deciding an approval (by the owner or a team approver, `lib/team.js` `getApproverNewsletters`, optionally with a code by email) and those settings are `dashboardOnly` actions: in the registry, but not in `ACTIONS`, so no route, tool or docs page. Calls that change something or read contacts go in `AgentActivity` (ids and counts, never bodies), with team members' dashboard changes (`lib/actions/run-action.js`), and the cron purges it by each account's retention (`lib/agent-housekeeping.js`). A new action needs its class in `lib/action-scopes.js`. - **Jobs**: QStash calls `app/api/jobs/*`: sending batches, scheduled sends, first-send checks, the purge of deleted accounts, the steps of an account export (`lib/account-export.js`: each step publishes the next, and the files wait in the private `EXPORTS` bucket for a signed download), the steps of taking a deleted tag or custom field off a large list (`lib/bulk-removal.js`, `remove-from-contacts`), the steps of a post import (`lib/post-import.js`: Substack, beehiiv, WordPress or Ghost posts become sent issues, the export waiting in `EXPORTS` under `imports/`, and their old addresses become redirects that `proxy.js` serves through `lib/redirect-routing.js`), the steps of an audio version (`lib/audio.js`, `make-audio`: one part of an issue read per step, the parts waiting in `EXPORTS` under `audio/`), the steps of saving a large segment as a list (`lib/segment-snapshots.js`, `snapshot-segment`) and `run-automations`, which a QStash schedule calls every 5 minutes (`lib/automations.js`: automation steps are a tree in `lib/automation-rules.js`, and an enrolment points at a step by its stable ID; segment conditions are one engine, `lib/segment-rules.js` and `lib/segments.js`, for segments, campaign audiences and automation branches). `run-series` is the same for recurring series (`lib/series.js`): the active ones that are due read their feed (`lib/feed-fetch.js`, the only fetch of a customer's address besides webhooks and the subfolder check, guarded by `lib/feed-url.js`) and make a draft or a send of its new items; an RSS block in an issue is read once as the send starts (`lib/feed-resolve.js`, called from `queueCampaign`). A cron calls `app/api/cron/hourly` with `CRON_SECRET`: PostShiba's team status, the extra emails Polar hasn't been told about (`lib/extra-emails.js`) dedicated IPs out of line with their add-on (`lib/dedicated-ip.js`), the day of every dedicated IP's warm-up (`lib/ip-warmup.js`) and the stock of spare IPs (`lib/ip-inventory.js`). Another calls `app/api/cron/postmaster` every day: Gmail's spam rates from Google Postmaster Tools (`lib/postmaster.js`), connected on `/admin`. - **Email providers**: `lib/email-provider` switches between `ses.js` and `postshiba.js` (tenants, domains, sends), and their events become one shape (`lib/email-event-rules.js`). FlockStack's own emails (sign-in codes, alerts) go through `lib/platform-email.js`: Resend, or the provider. - **Webhooks**: outgoing events leave only through `emitWebhookEvent` (`lib/webhooks.js`), and every type is in `lib/webhook-events.js` with its example, which the actions, docs, dashboard and tests read. Each delivery attempt is a QStash job (`app/api/jobs/deliver-webhook`) that signs the body Standard Webhooks style (`lib/webhook-signing.js`) and publishes its own retry; addresses pass `lib/webhook-url.js` at creation and before every attempt. The delivery log keeps the latest deliveries per endpoint only. `integrations/` holds the Zapier and Make apps, separate packages that call the REST API and aren't part of the build. diff --git a/README.md b/README.md index 9e7ba1dd..ccfdf930 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ FlockStack is a newsletter app: write an issue, send it to your list, publish it ## Features - **AI agents and the dashboard.** Everything the dashboard does also works from an AI agent through the MCP server, and from code through the REST API, with the same checks and limits. ChatGPT, Claude and Grok Bot connect with OAuth; Claude Code, Codex and Cursor with an API key. MCP marks sending as an action that can't be undone, so agents ask you first. -- **Built for agents you can trust.** Agents propose, you approve: a key or connected app can be read only, drafts only, send with approval or full access, limited to one newsletter, capped at a number of calls a day and set to expire. With send with approval, the sends, schedules and deletes an agent asks for wait on an Approvals page with the exact input and who asked, and run once, as that key, when you approve (an agent can never approve its own request). Everything an agent changes is in an Agent activity log (ids and counts only, kept 90 days). See [Agent safety](#agent-safety). +- **Built for agents you can trust.** Agents propose, you approve: a key or connected app can be read only, drafts only, send with approval or full access, limited to one newsletter, capped at a number of calls a day and set to expire. With send with approval, or on a newsletter that asks (the default for new accounts), the sends, schedules, deletes and billing changes an agent asks for wait on an Approvals page with the exact input and who asked, and run once, as that key, when you approve (an agent can never approve its own request). Team members you name can approve too, and approving can take a code by email. A key can also be limited to some actions and some IP addresses. Everything an agent changes is in an Agent activity log you can filter by client and export (ids and counts only, kept 90 days unless you choose 30, 180 or 365). See [Agent safety](#agent-safety). - **Write, review, send.** Write in an editor with slash commands, images and boxes, or send Markdown or a complete HTML email through the API and MCP. Review shows what to fix before sending: subject, preview text, unsubscribe link, Gmail's 100 KB clip, postal address, sender. Then send it, schedule it, or start with your most engaged readers and send to more later. Send by email and web, email only or web only, under the issue's own sender name, with test emails to up to 10 people. - **Undo send.** After you press Send in the dashboard, the send waits 30 seconds (off, 10, 30 or 60 per newsletter, in its settings). A bar at the bottom of every dashboard page counts down, "Sending to 4,812 readers in 28 s", with Undo, which gives back the draft exactly as it was, and Send now. Nothing is queued, counted against your plan or emailed until the wait is over, the bar comes back on a reload and shows in a second tab, and sends from the API and AI agents (which have their own approval) go out at once. The plan's limits are checked when you press Send and again when it goes out. - **A ready-to-send check.** The review step lists what to fix and what to look at before you send, each with one plain sentence and a link to the fix: the subject (blocked when empty, flagged past about 60 characters or when it shouts), preview text, the sender address and domain, the postal address, the unsubscribe link and Gmail's 100 KB clipping, the first 20 links (opened from the server by a short job, with the same limits as a webhook: public hosts only, three redirects at most), pictures with no alt text or over 1 MB, merge tags some contacts have no value for (how many, and what they see instead), who it goes to, the plan's limits and the Free plan's footer. A blocker keeps Send off; a warning never does. "Send a test to me" and phone and desktop previews, light and dark, sit beside it. `check_campaign` returns the same list to the REST API and MCP, so an agent can look before it asks to send, and the approval page shows it under an agent's request. @@ -653,9 +653,9 @@ ChatGPT, Claude and Grok Bot add `https:///mcp` as a connector or cust ### Agent safety -Every action has a scope class (read, write-draft, write, send, destructive, admin) in `lib/action-scopes.js`, and a key's or app's level allows some of them: read only, drafts only (campaigns, templates, segments and automations as drafts, and the content plan), send with approval (all but keys, billing and money; its send and destructive classes wait for the owner) and full. `tests/agent-scopes.test.mjs` fails when an action has no class, and checks each level over the whole registry. A key can be limited to one newsletter, capped at calls a day and given an expiry (`create_api_key`). Keys and apps from before levels keep their meaning. +Every action has a scope class (read, write-draft, write, send, destructive, admin) in `lib/action-scopes.js`, and a key's or app's level allows some of them: read only, drafts only (campaigns, templates, segments and automations as drafts, and the content plan), send with approval (all but keys, billing and money; its send and destructive classes wait for the owner) and full. `tests/agent-scopes.test.mjs` fails when an action has no class, and checks each level over the whole registry. A key can be limited to one newsletter, capped at calls a day, given an expiry, limited to a list of actions and to IP addresses (`create_api_key`); a connected app can be limited to one newsletter on the consent page. Keys and apps from before levels keep their meaning. -An action that waits for approval answers `202` with `status: "approval_required"` (REST) or a tool result with the same fields (MCP) and is stored in `ApprovalRequest` (`lib/agent-guard.js`, `lib/approvals.js`): the owner approves or rejects it on **Approvals** (`/approvals`), approving runs it once as the key that asked, requests expire after 24 hours, and `get_approval_status` and the `approval.decided` webhook tell the agent. "Ask me before an agent sends" is a per-newsletter switch on the same page that makes even a full access key wait. Deciding is a registry action marked `dashboardOnly`, so no key, app or tool can do it. **Agent activity** (`/agent-activity`, `list_agent_activity`) logs what keys and apps changed or read of contacts, with ids and counts only, for 90 days; the hourly cron purges it. The docs page is `/docs/agent-safety`. +An action that waits for approval answers `202` with `status: "approval_required"` (REST) or a tool result with the same fields (MCP) and is stored in `ApprovalRequest` (`lib/agent-guard.js`, `lib/approvals.js`): the owner approves or rejects it on **Approvals** (`/approvals`), approving runs it once as the key that asked, requests expire after 24 hours, and `get_approval_status` and the `approval.decided` webhook tell the agent. "Ask me before an agent sends" is a per-newsletter switch on the same page that makes even a full access key wait, billing changes included; accounts made since it became the default (`Account.agentApprovalByDefault`) start every newsletter with it on. The owner can name team approvers per newsletter and ask for a code by email to approve sends and deletes. Deciding and these settings are registry actions marked `dashboardOnly`, so no key, app or tool can do them. **Agent activity** (`/agent-activity`, `list_agent_activity`, `export_agent_activity`) logs what keys and apps changed or read of contacts, team members' dashboard changes and the owner's changes to these settings, with ids and counts only, for 90 days or the owner's choice; the hourly cron purges it. The docs page is `/docs/agent-safety`. ## Contributing diff --git a/SECURITY.md b/SECURITY.md index 3400cf20..ac267a81 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -24,10 +24,10 @@ Report it privately by email to hello@flockstack.io, with "Security" in the subj - Only the signup endpoint answers browsers (CORS), so a full access key in a web page doesn't work from it. - Errors outside the documented codes answer `internal_error` without detail; the detail goes to the server log. - The MCP send tools are annotated destructive and say sending can't be undone. Sending a campaign that is already sending or sent answers `conflict`. -- Every action has a scope class (`lib/action-scopes.js`; read, write-draft, write, send, destructive, admin) and every key and connected app a level that allows some classes: read only, drafts only, send with approval, full, or signups only. A key can be limited to one newsletter, to a number of calls a day, and to a date. A test fails when an action has no class or where its newsletter comes from isn't said. -- A send with approval key's send and destructive actions (and any key's, on a newsletter that asks) are stored in `ApprovalRequest` with their exact input and its SHA-256 hash and not run (`lib/agent-guard.js`, `lib/approvals.js`). Only a signed-in person approves, through `decide_approval`, which is a registry action marked `dashboardOnly`: it has no REST route, OpenAPI entry or MCP tool, and `runAction` refuses it to anything but the dashboard. Approving claims the request with a conditional update (one winner), checks the hash and that the key or app still exists, and runs the action once as that key or app with the stored input. Requests expire after 24 hours; their inputs go a week after the decision, the requests after 90 days. +- Every action has a scope class (`lib/action-scopes.js`; read, write-draft, write, send, destructive, admin) and every key and connected app a level that allows some classes: read only, drafts only, send with approval, full, or signups only. A key can be limited to one newsletter, to a number of calls a day, to a date, to a list of actions and to IP addresses or CIDR ranges (checked against `cf-connecting-ip`, never X-Forwarded-For, before anything else; outside it answers 403 without naming the list and the attempt is logged). A connected app can be limited to one newsletter on the consent page, checked the same way. A test fails when an action has no class or where its newsletter comes from isn't said. +- A send with approval key's send and destructive actions (and any key's or app's, on a newsletter that asks, plus billing changes there) are stored in `ApprovalRequest` with their exact input and its SHA-256 hash and not run (`lib/agent-guard.js`, `lib/approvals.js`). Only a signed-in person approves (the owner, or a team member the owner named for that newsletter, who can never approve billing or change approval settings), optionally with a 6-digit code emailed for sends and deletes (10 minutes, 5 tries, bound to the request), through `decide_approval`, which is a registry action marked `dashboardOnly`: it has no REST route, OpenAPI entry or MCP tool, and `runAction` refuses it to anything but the dashboard. Approving claims the request with a conditional update (one winner), checks the hash and that the key or app still exists, and runs the action once as that key or app with the stored input. Requests expire after 24 hours; their inputs go a week after the decision, the requests after 90 days. - A key below full access can't create keys, open billing, change prices, manage webhooks or export the account, so it can't widen itself. An agent can't edit a campaign once it is scheduled, or an active automation, until it is unscheduled or paused, so what the owner approved can't change before it goes out. -- The agent activity log (`AgentActivity`) holds ids, names, option names and counts per call, never a subject, a body or an address, and is deleted after 90 days by the hourly cron; the per-day counts (`AgentDay`) go with it. +- The agent activity log (`AgentActivity`) holds ids, names, option names and counts per call, never a subject, a body or an address, and is deleted after the account's retention (90 days, or 30, 180 or 365 as the owner chooses) by the hourly cron; the per-day counts (`AgentDay`) go with it. Team members are named by name and role, never email. A key reads only its own entries unless it was created with `auditRead`. - OAuth (ChatGPT, Claude): Better Auth issues access tokens signed RS256 with a key it keeps encrypted with `BETTER_AUTH_SECRET`. `/mcp` accepts a token only with FlockStack's issuer, `/mcp` as its audience, the `at+jwt` type, an unexpired `exp`, one of the `flockstack:` scopes, a valid DPoP proof when it's bound to a key, and the id of a consent that still exists for its user and app. Tokens last an hour; refresh tokens are stored hashed, rotate on use, and expire 90 days after the last use. - An app gets the access its user picks on the consent page, at the levels of an API key and no more than it asked for (`flockstack:read`, `:drafts`, `:send`, `:full`), in its user's account only, after the user signs in and allows it there; the page names the app's host. Connections made before levels had none stored and keep full access. PKCE (S256) is required, redirect URIs must match the app's client metadata document or registration exactly (loopback ports aside), and responses carry the issuer (RFC 9207). Disconnecting an app on the API keys page deletes its tokens and consent; its access tokens answer 401 from the next request. - Client metadata documents are fetched over https with the address resolved once and pinned, private and reserved addresses refused, redirects refused, 5 KB at most. Better Auth's client and consent management routes are closed. @@ -110,7 +110,7 @@ Without `FLOCKSTACK_CLOUD=true` (only that exact value counts), a server is self - The first account to add a domain holds it until it removes it, verified or not; its real owner has to ask support. - On PostShiba, Gmail sees PostShiba's own `Feedback-ID` (`mc-:…:postshiba`) in place of FlockStack's, so its feedback loop reports accounts, not campaigns. - Gmail's data comes a day or two late, only for domains that send to at least 50 Gmail users a day, and only for feedback IDs with enough emails and spam reports: a small account's complaints at Gmail stay out of sight. -- A full access key can do anything the owner can, billing links included, and an approval only protects what goes through it: turn on "Ask me before an agent sends" for a newsletter to make even a full access key's sends and deletes wait. A key limited to one newsletter is checked per action (`lib/action-scopes.js`); an action added later without an entry there is refused to it, and a test fails until it has one. +- A full access key can do anything the owner can, billing links included, and an approval only protects what goes through it. "Ask me before an agent sends" makes even a full access key's sends, deletes and billing changes wait; it is on from the start for accounts made since it became the default, and off on older accounts' newsletters until the owner turns it on. A key limited to one newsletter is checked per action (`lib/action-scopes.js`); an action added later without an entry there is refused to it, and a test fails until it has one. - Invalid keys aren't rate limited by IP before their database lookup (a unique index on the hash, so each costs one indexed read). - Tenants separate suppression lists and provider pauses, but capacity and IP reputation are still shared: SES's account quota and reputation, and on PostShiba each cluster's shared IP and hourly cap, used by every account on it. - Vercel tokens can't be limited to DNS (a project-scoped token can't edit it): the helper's token can do anything in the team, and only the helper's code and its own project keep it to flockstack.io's records. Anyone with `DNS_BROKER_SECRET` can create or delete shared address records within those rules, up to the daily cap. diff --git a/app/(app)/agent-activity/actions.js b/app/(app)/agent-activity/actions.js new file mode 100644 index 00000000..ab8050c6 --- /dev/null +++ b/app/(app)/agent-activity/actions.js @@ -0,0 +1,10 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { runDashboardAction, toFormError } from "@/lib/actions/dashboard"; + +export async function setActivityRetention(days) { + const { output, failure } = await runDashboardAction("set_agent_activity_retention", { days: Number(days) }); + revalidatePath("/agent-activity"); + return failure ? toFormError(failure) : { days: output.days }; +} diff --git a/app/(app)/agent-activity/export/route.js b/app/(app)/agent-activity/export/route.js new file mode 100644 index 00000000..3ee70cef --- /dev/null +++ b/app/(app)/agent-activity/export/route.js @@ -0,0 +1,28 @@ +import { getErrorStatus, toActionError } from "@/lib/actions/errors"; +import { runAction } from "@/lib/actions/run-action"; +import { getCurrentAccount } from "@/lib/auth"; + +const FILTERS = ["actor", "actorType", "client", "action", "newsletter", "status"]; + +// The Agent activity page's Export CSV: export_agent_activity with the page's filters, as a file. The signed-in account's own log only. +export async function GET(request) { + const current = await getCurrentAccount(); + if (!current) return Response.json({ error: "Unauthorized" }, { status: 401 }); + const params = new URL(request.url).searchParams; + const input = Object.fromEntries(FILTERS.map((name) => [name, params.get(name)]).filter(([, value]) => value)); + if (params.get("days")) input.days = Number(params.get("days")); + try { + const { csv } = await runAction("export_agent_activity", { ...current, via: "dashboard", input }); + return new Response(csv, { + headers: { + "content-type": "text/csv; charset=utf-8", + "content-disposition": `attachment; filename="agent-activity-${new Date().toISOString().slice(0, 10)}.csv"`, + "cache-control": "private, no-store", + "x-content-type-options": "nosniff", + }, + }); + } catch (error) { + const { code, message } = toActionError(error); + return Response.json({ error: message, code }, { status: getErrorStatus(code) }); + } +} diff --git a/app/(app)/agent-activity/page.js b/app/(app)/agent-activity/page.js index 95ee281e..ab6d56c3 100644 --- a/app/(app)/agent-activity/page.js +++ b/app/(app)/agent-activity/page.js @@ -2,26 +2,27 @@ import Link from "next/link"; import { Activity, ArrowUpRight } from "lucide-react"; import BadgeStatus from "@/components/BadgeStatus"; import HeaderPage from "@/components/HeaderPage"; +import SelectActivityRetention from "@/components/SelectActivityRetention"; import StateEmpty from "@/components/StateEmpty"; import { Button } from "@/components/ui/button"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { scoped } from "@/lib/account-scope"; import { PRESET_INFO } from "@/lib/action-scopes"; import { afterCursor, encodeCursor } from "@/lib/actions/cursor"; -import { ACTIVITY_PAGE_SIZE, getDayCounts, listActivity, listDayCounts } from "@/lib/agent-activity"; -import { ACTIVITY_RETENTION_DAYS } from "@/lib/agent-activity-rules"; +import { ACTIVITY_PAGE_SIZE, getDayCounts, listActivity, listActivityClients, listDayCounts } from "@/lib/agent-activity"; +import { getRetentionDays } from "@/lib/agent-activity-rules"; import { getKeyLevel, listApiKeys } from "@/lib/api-keys"; import { requireAccount } from "@/lib/auth"; import { connectDb } from "@/lib/db"; import { formatDate, formatRelative } from "@/lib/format"; import { listConnectedApps } from "@/lib/oauth-apps"; +import { isAccountOwner } from "@/lib/team"; import { isObjectIdString } from "@/lib/validation"; import { ACTIVITY_STATUSES } from "@/models/AgentActivity"; import Newsletter from "@/models/Newsletter"; export const metadata = { title: "Agent activity" }; -const DAY_CHOICES = [1, 7, 30, ACTIVITY_RETENTION_DAYS]; function pick(value) { return typeof value === "string" && value ? value : undefined; @@ -31,19 +32,24 @@ function pick(value) { // ?actor= is the per-key view. export default async function AgentActivityPage({ searchParams }) { const params = await searchParams; - const { account } = await requireAccount(); + const { account, user } = await requireAccount(); await connectDb(); + const retention = getRetentionDays(account); + const dayChoices = [...new Set([1, 7, 30, retention])].filter((value) => value <= retention); + const isOwner = isAccountOwner(account, user); const actor = pick(params.actor); + const client = pick(params.client)?.slice(0, 100); const action = pick(params.action)?.slice(0, 100); const newsletter = isObjectIdString(pick(params.newsletter) ?? "") ? pick(params.newsletter) : undefined; const status = ACTIVITY_STATUSES.includes(params.status) ? params.status : undefined; - const days = DAY_CHOICES.includes(Number(params.days)) ? Number(params.days) : ACTIVITY_RETENTION_DAYS; + const days = dayChoices.includes(Number(params.days)) ? Number(params.days) : retention; const cursor = pick(params.cursor); - const [keys, apps, newsletters] = await Promise.all([ + const [keys, apps, newsletters, clients] = await Promise.all([ listApiKeys(account), listConnectedApps(account), Newsletter.find(scoped(account)).sort({ createdAt: 1, _id: 1 }).select({ name: 1 }).lean(), + listActivityClients(account, retention), ]); const actors = [ ...keys.map((key) => ({ id: String(key._id), name: key.name, kind: "API key", level: getKeyLevel(key), key })), @@ -53,6 +59,7 @@ export default async function AgentActivityPage({ searchParams }) { const names = new Map(newsletters.map(({ _id, name }) => [String(_id), name])); const { entries, hasMore } = await listActivity(account, { actorId: actor, + client, action, newsletterId: newsletter, status, @@ -79,18 +86,26 @@ export default async function AgentActivityPage({ searchParams }) {
[name, name])} any="All" /> [value, value.replaceAll("_", " ")])} any="Any" /> - [String(value), value === 1 ? "Today" : `${value} days`])} /> +
+ {isOwner && } + {selected && (

@@ -118,7 +133,7 @@ export default async function AgentActivityPage({ searchParams }) { {entries.length === 0 ? (

- Calls from API keys and connected apps that change something or show contact data are listed here for {ACTIVITY_RETENTION_DAYS} days. + Calls from API keys and connected apps that change something or show contact data, and team members' changes, are listed here for {retention} days.

) : ( @@ -165,7 +180,7 @@ export default async function AgentActivityPage({ searchParams }) {

)}

- {ACTIVITY_PAGE_SIZE} entries a page. The log keeps ids, names and counts, never what an email says or who it went to, and is deleted after {ACTIVITY_RETENTION_DAYS} days. + {ACTIVITY_PAGE_SIZE} entries a page. The log keeps ids, names and counts, never what an email says or who it went to, and is deleted after {retention} days.

diff --git a/app/(app)/approvals/actions.js b/app/(app)/approvals/actions.js index d0fe6550..100e7ed7 100644 --- a/app/(app)/approvals/actions.js +++ b/app/(app)/approvals/actions.js @@ -4,16 +4,29 @@ import { revalidatePath } from "next/cache"; import { runDashboardAction, toFormError } from "@/lib/actions/dashboard"; // Approve or reject what an agent asked to do. Approving runs it, once, as the key or app that asked. -export async function decideApproval(id, decision, note = "", acknowledgeChanges = false) { +export async function decideApproval(id, decision, note = "", acknowledgeChanges = false, code = "") { const { output, failure } = await runDashboardAction("decide_approval", { id: String(id), decision: decision === "approve" ? "approve" : "reject", note: String(note ?? "").slice(0, 500), acknowledgeChanges: acknowledgeChanges === true, + ...(code && { code: String(code).trim() }), }); revalidatePath("/approvals"); if (failure) return toFormError(failure); - return { approval: output.approval, stale: output.stale }; + return { approval: output.approval, stale: output.stale, stepUp: output.stepUp }; +} + +export async function setApprovalStepUp(required) { + const { output, failure } = await runDashboardAction("set_approval_step_up", { required: required === true }); + revalidatePath("/approvals"); + return failure ? toFormError(failure) : { required: output.required }; +} + +export async function setTeamApprover(id, newsletters) { + const { output, failure } = await runDashboardAction("set_team_approver", { id: String(id), newsletters: (newsletters ?? []).map(String) }); + revalidatePath("/approvals"); + return failure ? toFormError(failure) : { approverFor: output.approverFor }; } export async function setAgentApproval(newsletter, required) { diff --git a/app/(app)/approvals/page.js b/app/(app)/approvals/page.js index 9f1dcb25..75bb42e9 100644 --- a/app/(app)/approvals/page.js +++ b/app/(app)/approvals/page.js @@ -3,6 +3,7 @@ import { ArrowUpRight, ShieldCheck } from "lucide-react"; import BadgeStatus from "@/components/BadgeStatus"; import CardAgentApproval from "@/components/CardAgentApproval"; import CardApproval from "@/components/CardApproval"; +import CardApprovalPeople from "@/components/CardApprovalPeople"; import HeaderPage from "@/components/HeaderPage"; import StateEmpty from "@/components/StateEmpty"; import { Button } from "@/components/ui/button"; @@ -12,6 +13,7 @@ import { getStaleness, listApprovals, toApprovalView } from "@/lib/approvals"; import { requireAccount } from "@/lib/auth"; import { connectDb } from "@/lib/db"; import { formatRelative } from "@/lib/format"; +import { getApproverNewsletters, listTeam } from "@/lib/team"; import Newsletter from "@/models/Newsletter"; export const metadata = { title: "Approvals" }; @@ -19,20 +21,28 @@ export const metadata = { title: "Approvals" }; const HISTORY_LIMIT = 30; export default async function ApprovalsPage() { - const { account } = await requireAccount(); + const { account, user } = await requireAccount(); await connectDb(); - const [pendingRows, decidedRows, newsletters] = await Promise.all([ + // A team approver sees the requests of their newsletters, and none of the owner's settings. + const approverFor = await getApproverNewsletters(account, user); + const isOwner = approverFor === null; + const mayDecide = (approval) => isOwner || (approval.className !== "admin" && approverFor.includes(String(approval.newsletterId ?? ""))); + const [pendingRows, decidedRows, newsletters, seats] = await Promise.all([ listApprovals(account, { status: "pending", limit: 50 }), listApprovals(account, { limit: HISTORY_LIMIT + 50 }), - Newsletter.find(scoped(account)).sort({ createdAt: 1, _id: 1 }).select({ name: 1, agentApproval: 1 }).lean(), + Newsletter.find(scoped(account)).sort({ createdAt: 1, _id: 1 }).select({ name: 1, agentApproval: 1, agentApprovalChangedAt: 1 }).lean(), + isOwner ? listTeam(account, user).then(({ seats }) => seats.filter(({ status }) => status === "active")) : [], ]); const pending = await Promise.all( - pendingRows.map(async (approval) => ({ approval: toApprovalView(approval, { includeInput: true }), staleness: await getStaleness(account, approval) })) + pendingRows.filter(mayDecide).map(async (approval) => ({ approval: toApprovalView(approval, { includeInput: true }), staleness: await getStaleness(account, approval) })) ); const history = decidedRows + .filter(mayDecide) .map((approval) => toApprovalView(approval)) .filter(({ status }) => status !== "pending") .slice(0, HISTORY_LIMIT); + // Newsletters nobody chose for: they keep what keys did before approval became the default, until the owner turns it on. + const unchosen = newsletters.filter(({ agentApproval, agentApprovalChangedAt }) => !agentApproval && !agentApprovalChangedAt); return ( <> @@ -62,7 +72,20 @@ export default async function ApprovalsPage() { )} - ({ id: String(_id), name, required: Boolean(agentApproval) }))} /> + {isOwner && ( + ({ id: String(_id), name, required: Boolean(agentApproval) }))} + unchosen={unchosen.map(({ _id }) => String(_id))} + /> + )} + + {isOwner && ( + ({ id: String(_id), name }))} + /> + )} {history.length > 0 && (
diff --git a/app/oauth/consent/actions.js b/app/oauth/consent/actions.js index e3dd3a75..7f2991d4 100644 --- a/app/oauth/consent/actions.js +++ b/app/oauth/consent/actions.js @@ -29,7 +29,7 @@ export async function answerConsentRequest(_state, formData) { } if (!url) return { error: EXPIRED_MESSAGE }; if (accept) { - await saveConsentAccess({ account: current.account, query, access: String(formData.get("access") ?? "") }); + await saveConsentAccess({ account: current.account, query, access: String(formData.get("access") ?? ""), newsletter: String(formData.get("newsletter") ?? "") }); await notifyActivity(["App connected", readOAuthQuery(query).clientId], { accountId: current.account._id }); } redirect(url); diff --git a/app/oauth/consent/page.js b/app/oauth/consent/page.js index 09164d3a..67f50d29 100644 --- a/app/oauth/consent/page.js +++ b/app/oauth/consent/page.js @@ -5,10 +5,13 @@ import ButtonSignout from "@/components/ButtonSignout"; import FormConsent from "@/components/FormConsent"; import LogoFlockstack from "@/components/LogoFlockstack"; import { PRESET_INFO, getPresetOfScopes, getPresetsUpTo } from "@/lib/action-scopes"; +import { scoped } from "@/lib/account-scope"; import { isDeletionPending } from "@/lib/account-state"; import { getPersonalAccount } from "@/lib/auth"; +import { connectDb } from "@/lib/db"; import { readOAuthRequest } from "@/lib/oauth"; import { isLoopbackRedirect } from "@/lib/oauth-rules"; +import Newsletter from "@/models/Newsletter"; export const metadata = { title: "Connect an app" }; @@ -31,6 +34,8 @@ export default async function ConsentPage({ searchParams }) { const choices = getPresetsUpTo(asked).toReversed(); const selected = choices.includes(SUGGESTED) ? SUGGESTED : asked; const hasProfile = scopes.some((scope) => scope === "email" || scope === "profile"); + await connectDb(); + const newsletters = await Newsletter.find(scoped(current.account)).sort({ createdAt: 1, _id: 1 }).select({ name: 1 }).limit(100).lean(); return (
@@ -78,6 +83,28 @@ export default async function ConsentPage({ searchParams }) { Same levels as an API key. You can disconnect it anytime, and approve or reject what it asks to do on the Approvals page.

+ {newsletters.length > 1 && ( +
+ + +

Limited to one, it can't see or change the others, or anything of the whole account.

+
+ )}

diff --git a/components/CardAgentApproval.jsx b/components/CardAgentApproval.jsx index e48a218c..3d4044ad 100644 --- a/components/CardAgentApproval.jsx +++ b/components/CardAgentApproval.jsx @@ -2,11 +2,13 @@ import { useState, useTransition } from "react"; import { setAgentApproval } from "@/app/(app)/approvals/actions"; +import { Button } from "@/components/ui/button"; import { Switch } from "@/components/ui/switch"; import { toast } from "@/lib/toast"; -// "Ask me before an agent sends", for each newsletter. Dashboard only: no key or app can change it. -export default function CardAgentApproval({ newsletters }) { +// "Ask me before an agent sends", for each newsletter. Dashboard only: no key or app can change it. unchosen: the newsletters +// from before it was on by default, which nobody switched: the card offers to turn it on for them. +export default function CardAgentApproval({ newsletters, unchosen = [] }) { const [values, setValues] = useState(() => Object.fromEntries(newsletters.map(({ id, required }) => [id, required]))); const [, startTransition] = useTransition(); @@ -21,13 +23,26 @@ export default function CardAgentApproval({ newsletters }) { }); } + const offered = unchosen.filter((id) => !values[id]); + return (

+ {offered.length > 0 && ( +
+ + Safer default. New newsletters ask before an agent sends, deletes or changes billing. {offered.length === 1 ? "One of yours doesn't" : `${offered.length} of yours don't`} yet: + a full access key there sends with no review. + + +
+ )}

Ask me before an agent sends

- When it is on, anything an API key or connected app does that sends, schedules or deletes waits here for you, whatever the key's level. Keys that - already ask (send with approval) always do. + When it is on, anything an API key or connected app does that sends, schedules, deletes or changes billing waits here for you, whatever the key's + level, full access included. Keys that already ask (send with approval) always do. Every change is in the agent activity log.

    diff --git a/components/CardApproval.jsx b/components/CardApproval.jsx index 33b960c3..4bae9859 100644 --- a/components/CardApproval.jsx +++ b/components/CardApproval.jsx @@ -6,6 +6,7 @@ import { Bot, Check, Loader2, TriangleAlert, X } from "lucide-react"; import { decideApproval } from "@/app/(app)/approvals/actions"; import ApprovalCheck from "@/components/ApprovalCheck"; import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { formatRelative } from "@/lib/format"; import { toast } from "@/lib/toast"; @@ -26,14 +27,21 @@ export default function CardApproval({ approval, staleness = null }) { const [note, setNote] = useState(""); const [warning, setWarning] = useState(staleness); const [decision, setDecision] = useState(null); + // Step-up: the account asks for a code by email before a send or a delete is approved. + const [isAskingCode, setIsAskingCode] = useState(false); + const [code, setCode] = useState(""); const input = approval.input ? JSON.stringify(approval.input, null, 2) : ""; function decide(choice) { setDecision(choice); startTransition(async () => { - const result = await decideApproval(approval.id, choice, note, choice === "approve" && Boolean(warning)); + const result = await decideApproval(approval.id, choice, note, choice === "approve" && Boolean(warning), choice === "approve" ? code : ""); if (result?.error) return void toast.error(result.error); if (result?.stale) return void setWarning(result.stale); + if (result?.stepUp === "code_sent") { + setIsAskingCode(true); + return void toast.success("We emailed you a code. Enter it to approve."); + } if (choice === "reject") return void toast.success("Rejected. Nothing was done."); if (result.approval.execution.state === "failed") toast.error(`Approved, but it failed: ${result.approval.execution.error?.message}`); else toast.success("Approved. It ran."); @@ -104,12 +112,29 @@ export default function CardApproval({ approval, staleness = null }) { aria-label="A note for the agent" /> + {isAskingCode && ( +
    + + setCode(event.target.value.replace(/\D/g, "").slice(0, 6))} + inputMode="numeric" + autoComplete="one-time-code" + placeholder="6 digits" + className="max-w-40 font-mono tracking-widest" + /> +
    + )} +