62 Commits
Author SHA1 Message Date
davidandClaude Opus 5.5 d97568feca Add the Mozilla Public License 2.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 09:18:59 -07:00
davidandClaude Opus 5.5 cd2dc6145b Sign-ins finish only in the browser that started them
A Core sign-in, and a posting account's or Search Console's OAuth sign-in,
now sets a short-lived cookie whose hash the flow keeps on the server. The
callback refuses one without it (constant-time compare), clears the cookie
either way, and the flow is used up regardless. This stops login CSRF: a
callback URL brought to another browser signs nobody in.

The cookie uses the __Host- prefix over https, so its Path is "/".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 08:07:21 -07:00
davidandClaude Opus 5.5 005c4ac800 Posting accounts: the grid lays out as a table
Its "grid" class was also the cards' CSS grid, which set the table's
header and rows side by side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 15:37:13 -07:00
davidandClaude Opus 5.5 df4759afb5 Settings: All connections, Posting accounts and Activity open on the local edition
Their admin check wanted someone signed in, so the local owner got a 404.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 15:29:37 -07:00
davidandClaude Opus 5.5 1bad4deed6 PLAN.md and TEST.md: the Market import filled in from websites
Where things stand records how the import fills entries in and what it
skips; TEST.md gets checks for the "-url:" list and a run stopped by a
restart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 07:23:26 -07:00
davidandClaude Opus 5.5 32d69c4a80 Market import: read "-url:" typed without a space after the dash
A hand-typed list with no space after its dashes was an error about a
key defined twice. It's now read as meant; a list that still can't be
read says what an entry looks like.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 06:50:00 -07:00
davidandClaude Opus 5.5 4692d72d58 Market import: fill entries in from their websites
A list of just websites and relationships (url:, website:, or a bare
address) can be imported with "Fill in the empty boxes from each
website": each entry is filled in as on New entry, in the background a
few at a time, and saved straight into the Market. Entries already there,
by name or website, are skipped before their site is read; the plan's
limit is kept. The import page shows the progress and each entry's result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 06:41:54 -07:00
davidandClaude Opus 5.5 185522c0c3 PLAN.md, TEST.md and README: the Metrics changes from testing
Total spend from charges, MRR and cohorts on paid invoices, renewals as
existing customers, cohorts in full with dollars, and the start month's
cohort labelled. TEST.md gets checks for each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:07:46 -07:00
davidandClaude Opus 5.5 e320a64166 Metrics: the first month counted is labelled as the existing customers
With a "Count from" month set, that month's cohort is everyone already
paying then, not only those new that month. Both cohort tables now say
"existing customers" under it, the help text explains, and both cohort
CSVs add an existing_customers column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:06:04 -07:00
davidandClaude Opus 5.5 a49d49713d Metrics: every cohort over every month, percentages and dollars aligned
Both cohort tables (MRR retention on Metrics, revenue per customer on
CLV) and their CSVs now show every cohort, each followed to the latest
month, instead of the last 12 or 18 for 12 or 24 months.

Each MRR cohort is now two rows, the share of starting MRR and the
dollars under it, so the numbers line up across months; the month,
customers and starting MRR span both rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:02:24 -07:00
davidandClaude Opus 5.5 ea94324c3b Metrics: cohorts show each month's dollars beside the percentage
Each cohort cell now gives what the same customers pay that month, in
dollars, under the share of their starting MRR. The cohorts CSV adds
month_N_mrr columns after the month_N_pct ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:58:38 -07:00
davidandClaude Opus 5.5 06b17b9eab Metrics: a customer whose first invoice is a renewal is an existing one
When the earliest recurring invoice Stripe has for a customer is a renewal
(billing_reason subscription_cycle), they were a customer already, their
first year free or billed elsewhere. That first payment now counts as
reactivation (movement "existing"), not new: it stays out of New, the
cohorts and CAC, and the month's movements still add up. The customers
export gives the month first seen paying as first_paid. A $0 trial signup
before the first payment still makes a customer new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:56:34 -07:00
davidandClaude Opus 5.5 fab349d166 Metrics: MRR and cohorts count only paid invoices
Open (unpaid) invoices no longer count toward MRR, so they don't put a
customer in a cohort either; an invoice counts once it's paid. This
matches the customer count, which takes only those who have spent more
than $0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:47:30 -07:00
davidandClaude Opus 5.5 739f85fde1 Metrics: total spend from Stripe's charges, as Stripe counts it
Customers who paid without an invoice (one-off Checkout payments) were
missed, and the Stripe card counted every customer record, deleted ones
too. The sync now reads charges (and follows their events); a customer's
total spend is their successful charges, captured less refunded. A
database synced before reads everything once (sync state version 2).
Until charges are in, paid invoices less refunds stand in.

The Stripe card's Customers now counts those who spent more than $0, "of
N in Stripe", and a Payments count is added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:35:00 -07:00
davidandClaude Opus 5.5 6f2fbdf63a Metrics → Customers: only customers who have spent more than $0
A customer counts when their paid invoices' amount_paid, less refunds,
is above zero. Trials ($0 invoices), fully discounted invoices, only-open
invoices and payments refunded in full no longer put someone on the list.

Also ticks the Market Fetch check in TEST.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:27:27 -07:00
davidandClaude Opus 5.5 5451fe6d63 Reddit: posted by hand, with the rules pasted
Reddit's API isn't open to apps like this one, so Supermarket no longer
signs in to Reddit, publishes or schedules there, or reads subreddits and
the account's posts. The internal/api/reddit client, Reddit's OAuth, its
keys and its Social accounts card are gone.

Supermarket still writes the post. Each Reddit draft in Posts has a box
for its subreddit's rules, with a link to them on Reddit: pasted once,
they're kept (subreddits.data, as pasted_rules) and given to the model
for later drafts. Open in Reddit saves the edits and opens the submit
page filled in; Copy title and Copy text (with the tagged source link)
cover a box that comes up empty; Mark as posted records it. Warnings come
from the pasted rules and the posts marked as posted. Fill's subreddit
suggestions are kept unchecked, and say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:48:54 -07:00
davidandClaude Opus 5.5 bae468e01c Social accounts: the redirect address at the top of each card
It sat under the Save button, while the keys' help pointed below to it.
Now it comes first, with a Copy button, ahead of the keys that need it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:21:37 -07:00
davidandClaude Opus 5.5 bd5e754317 TEST.md: a check for the light and dark switch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:20:53 -07:00
davidandClaude Opus 5.5 19476edea2 Light and dark: a switch in the top bar
Three choices: as the device is (the default), light, or dark, kept in
a "theme" cookie per browser. The dark colours move to dark.css, linked
with a media attribute from the cookie, so the server renders the page
in the chosen colours with no flash (the CSP allows no inline script).
app.js sets the cookie and switches the media at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 06:44:38 -07:00
davidandClaude Opus 5.5 a7162acb03 PLAN.md: where things stand, every phase built
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:26:51 -07:00
davidandClaude Opus 5.5 2f235ad260 Phase 12, part 5: roles from the Core's groups
Settings → Sign-in: roles follow the Core's groups, with a prefix.
<prefix>-admins makes an admin, <prefix>-<module> edits a module,
<prefix>-<module>-view reads it. Set at each sign-in with the Core; someone
in a group joins; the owner never changes; someone in none of them keeps
the access set here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:13:45 -07:00
davidandClaude Opus 5.5 6d3eb18b5e Phase 14, parts 5 and 6: seats, and moving down to Free
Seats: inviting past the seats paid for offers the owner to add one
(Stripe prorates it); admins are told to ask the owner; Free has two.
Moving down: past the plan's seats, the owner and one other (the owner's
pick, or the first to join) edit and the rest read; storage is measured
hourly, and past the plan's, photo uploads and the SEO crawl stop.
Nothing is deleted. TEST.md section 18.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:34:22 -07:00
davidandClaude Opus 5.5 aa0408fb14 Phase 14, part 4: what happens when it lapses
An hourly platform job: a trial over without a subscription goes to Free;
past due, the owner is told and every page has a banner; at 14 days
read-only; at 53 days everyone is warned; at 60 days the team is deleted
with 30 days to undo. Each email once. Undoing a deletion for not paying
gives a week more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:27:03 -07:00
davidandClaude Opus 5.5 acdb44fcc9 gofmt access.go
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:21:28 -07:00
davidandClaude Opus 5.5 4833f53e0d Phase 14, part 3: Stripe's events
/billing/stripe takes Stripe's webhooks, signatures checked, each event
handled once, and keeps each team's subscription up to date: checkout, its
status, seats and period, failed and paid invoices, cancellation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:21:25 -07:00
davidandClaude Opus 5.5 8fb79220e3 Phase 14, part 2: the owner's Billing page
Settings → Billing shows the team's plan, trial, people, agents, storage
and next invoice. The owner subscribes through Stripe Checkout (monthly, or
yearly when there's a price) and pays or reads invoices in Stripe's
Customer Portal; admins see the plan only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:19:30 -07:00
davidandClaude Opus 5.5 a47990f9bf Phase 14, part 1: plans, each team's account, and their limits
The multi-tenant edition's plans (Free and Paid as decided, or a plans
file) and each team's billing account, with a 14-day trial of Paid. A
team's plan caps what its people and agents may change: modules outside it
stay readable, a lapsed team changes nothing, and agents, Market entries,
crawls and background jobs keep to it. Without a Stripe key, no billing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:15:00 -07:00
davidandClaude Opus 5.5 e47764a78e TEST.md: three passes (local, server with the Core, multi-tenant), and checks for Phases 11–13
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:07:21 -07:00
davidandClaude Opus 5.5 07233e8d85 gofmt coresignin.go
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:00:40 -07:00
davidandClaude Opus 5.5 962dbe3286 Phase 12: signing in with the Core's Authelia
Admins make the client's secret under Settings → Sign-in, which shows the
entry for the Core's idproviders.yml (the secret's PBKDF2-SHA512 hash, the
redirect address, PKCE). People sign in with their Core account: invited
ones are matched by verified email, then by subject; optionally anyone at
the Core's domain joins. Passwords can be turned off but for the owner's,
and signing out ends the Core's session where it can. On multi-tenant, the
team is found by its proved domain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:00:36 -07:00
davidandClaude Opus 5.5 637ef1cc25 PLAN.md: what the Core's idproviders.yml shows about adding a client
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:52:40 -07:00
davidandClaude Opus 5.5 0de5ab6698 PLAN.md: Phase 13 is built, and was run for real with Garage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:47:14 -07:00
davidandClaude Opus 5.5 f4c31c9fa3 Phase 13, part 9: running at scale, and the proof
The multi-tenant edition starts. compose.multi.yaml runs several copies
behind Caddy, with the managed Postgres and Garage outside. A test walks
every page and fragment, with ids filled in, and every MCP tool, as one
team, and none shows another team's data or changes it; another has three
copies share six teams' work, each team's turn once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:46:01 -07:00
davidandClaude Opus 5.5 b8a64e258a Phase 13, part 8: a team's data is theirs
The owner exports everything from Settings → Your data (the keys only with
their password), and can delete the team: it closes at once, everyone in it
is told, it can be undone for 30 days, and then its schema, files, agents
and memberships go for good.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:40:28 -07:00
davidandClaude Opus 5.5 d35ed7cbb2 Phase 13, part 7: the platform's own admin
The people running the multi-tenant service (SUPERMARKET_PLATFORM_ADMINS,
with two-factor sign-in) see every team at /platform with its size, people
and what failed lately, and can suspend or restore a team, resend its
invitations and release its domain. They don't see a team's data unless
they view as it: with a reason, for at most an hour, read-only, recorded in
the team's own audit log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:35:53 -07:00
davidandClaude Opus 5.5 76407cdea8 gofmt pages.go
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:29:48 -07:00
davidandClaude Opus 5.5 1865140507 Phase 13, part 6: each team's Core
On the server and multi-tenant editions a team's admin enters its Core's
domain and account under Settings → Core & Hermes, instead of core.conf;
Hermes connects from the team's side with an agent's key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:29:44 -07:00
davidandClaude Opus 5.5 af6598271c Phase 13, part 5: each team's jobs, locks, files and sign-ins
Background jobs run for each active team on its own Server and under its
own locks, a few teams at a time and from a different team each round, so
the work is shared between copies of the app and no team holds up another.
Each team's files are under its own prefix, and an OAuth sign-in comes
back only to the team that started it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:26:33 -07:00
davidandClaude Opus 5.5 47cc8b2b10 Phase 13, part 4: proving a team's domain
Before Supermarket crawls a team's website, reads its Search Console data
or publishes to it, the team proves the domain is theirs: a DNS TXT
record, a file on the site, or owning its Search Console property. One
team holds a domain at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:21:42 -07:00
davidandClaude Opus 5.5 d5fb1898e8 Phase 13, part 3: signing up, and several teams per person
On the multi-tenant edition anyone can set up a team: their account, the
company and its website, whose registered domain the team works on (the
profile keeps to it). A person can belong to several teams and switch
between them from the sidebar, or set up another. Inviting someone who has
an account adds them to the team.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:17:15 -07:00
davidandClaude Opus 5.5 210b1e57fc Phase 13, part 2: each team's own database role
A team's connections take a Postgres role that owns its schema and may
use the shared tables, nothing else: even SQL naming another team's
schema is refused. The second guard behind the search_path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:11:57 -07:00
davidandClaude Opus 5.5 0e695ac810 Phase 13, part 1: a Postgres schema per team
On the multi-tenant edition each team's data is in its own schema; the
tables every team shares (people, sessions, memberships, keys, locks, and
a new teams table) stay in the main one. A team's connection pool searches
its own schema first, so the app's SQL runs unchanged and can't reach
another team's tables. Each request is served by a copy of the Server for
the viewer's team, with that team's database, secrets and caches; agents
work on their own team's. The local and server editions are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:08:47 -07:00
davidandClaude Opus 5.5 ff5eaa9784 PLAN.md: Phase 12 waits for the Core's idproviders.yml
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 11:47:52 -07:00
davidandClaude Opus 5.5 aa6c3ca390 Phase 11, part 5: the JSON API
/api/v1 offers the MCP tools as plain HTTP for scripts: GET /api/v1/tools
lists what a key may call, POST /api/v1/<tool> calls one with JSON. Each
call goes through /mcp internally, so keys, scopes, limits, logging and
approvals are the same. /api/v1/docs documents every tool.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 11:22:22 -07:00
davidandClaude Opus 5.5 6bf0517163 Phase 11, part 4: agents' limits, recent calls and a pause switch
Each agent has calls a minute and things it may ask to send out a day,
checked on every tool call and every request to send; every call is
recorded (tool, outcome, time) and the agent's page lists the last 50 and
what it's waiting on. Pause refuses all its calls at once. Also fixes each
agent's MCP server being shared with others that had the same scopes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 11:09:18 -07:00
davidandClaude Opus 5.5 311d2e815b Phase 11, part 3: approvals for what agents send out
Agents can now ask to publish or schedule a post, send an email, add
someone to a mailing list, or apply an SEO change. Each waits on the
Approvals page (with a count in the sidebar) for an admin or a member with
edit on its module, who can edit it first, approve or refuse it, and let
the agent take that class of action on its own with a cap per day. A
rotation after a leak revokes the old keys and withdraws everything
allowed. All of it is in the audit log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:54:53 -07:00
davidandClaude Opus 5.5 bfb74e7700 Phase 11, part 2: module tools over MCP
Agents get each module's tools by their scopes: reading tools with read,
the others with read and act. Content (drafts and items; writing, editing
and discarding drafts), Prospects (signals, review, outreach, suppression;
outreach drafts and edits), SEO (the morning check, What to write next,
links, changes; editing a proposal), Sites and Metrics (reading) and the
Market (list, get, save). They call what the pages call, and what an agent
changes is in the audit log as the agent. Nothing that leaves Supermarket
is offered yet: that waits for approvals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:31:43 -07:00
davidandClaude Opus 5.5 da2d56f8d2 Phase 11, part 1: agents and their keys
Agents are users of kind agent, each given modules to read, or to read
and act on, and the CRM scope. Admins make them under Settings → Agents,
on every edition; keys (sm_…) are shown once and kept as hashes, can
expire, be rotated (the old one works a day) or revoked, and record their
last use. /mcp takes agent keys and offers each agent only the tools its
scopes allow. On the local edition, mcp-token is the key of a built-in
Hermes agent with the CRM and the Market.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:26:31 -07:00
davidandClaude Opus 5.5 da16736fb4 Phase 10, part 9: the server package
compose.server.yaml runs Supermarket behind Caddy (HTTPS from Let's
Encrypt, Caddy's own CA or the team's), with Postgres on an internal
network and a nightly pg_dump kept two weeks. install-server.sh asks for
the domain, certificate and mail server, makes the secret key and database
password, starts it all and prints the setup link. Settings → Backups lists
the dumps on a server, and how the operator restores one. Checked end to
end in Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:37:34 -07:00
davidandClaude Opus 5.5 c8964cec12 Phase 10, part 8: the audit log, and who made what
Sign-ins and failed ones, everything admins do to users, connections,
posting accounts, each post published and email sent, pull requests and
deletions go in an audit log (schema 36), kept two years; admins read it
under Settings → Activity. Drafts, published posts and outreach emails
show who made them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:31:33 -07:00
davidandClaude Opus 5.5 bb4772637c Phase 10, part 7: posting accounts, and who may post to which
Social accounts become posting accounts: several per network, the
company's and each person's own, with their tokens kept per account. The
old sign-ins are adopted as the company's. Admins say who may post to which
(Settings → Posting accounts); a draft can go out from one account or a
copy to several, each recording who posted it and as what. Signing an
account out, or removing its owner, holds the posts scheduled to it and
tells whoever scheduled them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:26:34 -07:00
davidandClaude Opus 5.5 a4dd36f5a4 Phase 10, part 6: Settings → Connections, with who connected each
Admins see every service Supermarket uses, whether it's connected,
failing or not set up, when it was last tested (every Test button now
records its result), and who connected or removed it and when. Keys and
sign-ins saved from the settings pages record the person; refreshed
tokens don't.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:15:43 -07:00
davidandClaude Opus 5.5 2b9d04297f Phase 10, part 5: access enforced on every page, form and fragment
One table maps every address to an area (a module, Settings, anything
signed in, or public); each route is checked against it, and the app won't
start with a route missing from it. Changing needs edit on the module. For
members who may only view, forms that would change something are shown
disabled and htmx buttons hidden. The menu, the Overview, Search and the
SEO emails follow each person's modules; Settings is for admins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:13:16 -07:00
davidandClaude Opus 5.5 47a504b7b2 Phase 10, part 4: inviting users, and what admins can change
Settings → Users lists everyone with their access and status. Admins
invite people by email (a link for 7 days), as admins or as members with
modules each to view or edit; the invitation's page sets the password,
profile and emails wanted. Admins can resend or withdraw invitations,
change access, turn accounts off and on, unlock, reset two-factor, sign
someone out, and remove them; never the owner, nor themselves. Your
account gets the emails wanted and a photo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:07:32 -07:00
davidandClaude Opus 5.5 8040512a18 Phase 10, part 3: signing in and out, resets, locks and two-factor
The server edition now starts. Sign-in by email and password, limited per
address and per IP; ten failures in a row lock the account and email its
owner, and a reset by email (or an admin) unlocks it. Settings → Your
account has the profile, the password, where you're signed in, and
two-factor sign-in with an authenticator app (TOTP, from a QR code) and
ten recovery codes. The app's own mail goes through SUPERMARKET_MAIL_URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:01:29 -07:00
davidandClaude Opus 5.5 72455438c9 Phase 10, part 2: the first owner, from a one-time setup link
A new server prints a link to create its owner (supermarket setup-link
makes another); until it's used, every page says the setup isn't
finished. One-time links (schema 33) are kept as hashes and used up in
one statement; resets and invitations will use them too. The server
edition opens Postgres.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:53:14 -07:00
davidandClaude Opus 5.5 96404a3580 Phase 10, part 1: users, sessions and form tokens
Schema 32 adds users, memberships and sessions, on both databases.
internal/users keeps accounts (Argon2id passwords), roles and modules,
and sessions whose rows hold only a hash of the cookie's value; they end
after a week unused or 30 days. On the server edition, every page but the
public ones needs a session and sends others to /signin. Every edition's
forms now carry a CSRF token (a cookie repeated in each form, added as
pages render; htmx sends it as a header), besides the same-origin check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:49:45 -07:00
davidandClaude Opus 5.5 d537fb367f PLAN.md: where things stand after Phase 9, and how to pick up again
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:37:45 -07:00
davidandClaude Opus 5.5 5f1b8d59ce Phase 9, part 7: export and import, between SQLite and Postgres
supermarket export [--with-secrets] writes a whole Supermarket as a
.tar.gz (a manifest, each table as JSON lines, secrets if asked for) to
the file storage. supermarket import loads one into an empty database at
the same schema, SQLite or Postgres, in one transaction, parents first,
checking row counts and moving Postgres' identity counters past the
imported ids.

Checked on Federated's 112,543 rows: imported into Postgres and SQLite,
every table and total matches, and TestPagesOnRealData renders all 57
pages the same from both. That found unsettled ordering (case-alike
campaigns, customers with the same name, metrics' float sums), now fixed
with ORDER BY and tie-breakers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:09:14 -07:00
davidandClaude Opus 5.5 c6c4c40600 Phase 9, part 6: background work shared safely between copies of the app
internal/jobs keeps named locks as leases in the database (schema 31:
locks, instances), taken with one conditional UPDATE on SQLite or Postgres,
renewed while the work runs and lapsing if its copy stops. Each background
loop's turn, sending an email, audits, discovery runs and imports run
under a lock; OAuth sign-ins under way are kept in the database. Copies
check in, and work marked running is recovered at start only when no
other copy is alive. Settings -> About lists the copies and work under
way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:56:47 -07:00
davidandClaude Opus 5.5 ba6114f367 go.mod: minio-go is a direct dependency
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:42:22 -07:00
davidandClaude Opus 5.5 d2f1658708 Phase 9, part 5: file storage, a folder or an S3 bucket
internal/storage keeps files that must outlast the app's disk (exports,
uploads) behind one interface: a folder (<data>/files) or an S3-compatible
bucket (minio-go, path-style, for Garage). Names that would reach outside
the store are refused. An S3 store is checked at start; supermarket config
checks the storage and Postgres for real. The same tests run on a folder
and on Garage (SUPERMARKET_TEST_S3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:42:11 -07:00
205 changed files with 26554 additions and 2058 deletions
+5
View File
@@ -14,3 +14,8 @@ dismissed.json
# Build output
/supermarket
# The server edition's settings and certificates (install-server.sh).
server.env
server/certs/*
!server/certs/.keep
multi.env
+4
View File
@@ -24,6 +24,10 @@ FROM alpine:3.22
RUN apk add --no-cache ca-certificates tzdata git
COPY --from=hugo /go/bin/hugo /usr/local/bin/hugo
COPY --from=build /out/supermarket /usr/local/bin/supermarket
# The server edition runs as 10001 (compose.server.yaml): a new volume at
# /data takes this folder's owner. The local edition runs as you, with your
# own folder mounted there instead.
RUN mkdir -p /data /backups && chown 10001:10001 /data
LABEL org.opencontainers.image.title="supermarket"
ENV SUPERMARKET_DATA=/data
EXPOSE 8080
+373
View File
@@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+944 -21
View File
File diff suppressed because it is too large Load Diff
+112 -17
View File
@@ -6,13 +6,13 @@ Everything starts from your **company profile** (what you sell, to whom, in what
| Module | What it does | Status |
|--------|--------------|--------|
| Content | Drafts posts from partner and competitor news and your own products; you review them and publish to X, LinkedIn and Reddit | Phase 1: done |
| Content | Drafts posts from partner and competitor news and your own products; you review them and publish to X and LinkedIn, and post Reddit ones yourself | Phase 1: done |
| Prospects | Finds companies and people who fit your targets; the ones you approve go into your Core's EspoCRM through Hermes | Phase 2 |
| SEO | Audits your websites for Google, Bing/DuckDuckGo and Brave, and opens fixes as pull requests on your Hugo repositories | Phase 3 |
| Metrics | Pipeline influence, CAC, CLV and NRR, from Stripe, EspoCRM and Plausible | Phase 4 |
| Sites | Builds pages and sites from a component library and publishes them through Gitea | Phase 5 |
This version has the foundation (Phase 0): the web app, the company profile, the inventory, the AI provider, credentials, and the bridge to your Core through Hermes. It also has the Content module (Phase 1): posts about partners, competitors and your own products, a Posts page for approval, scheduled publishing to X, LinkedIn and Reddit, and UTM tags. See [PLAN.md](PLAN.md) for the whole plan.
This version has the foundation (Phase 0): the web app, the company profile, the inventory, the AI provider, credentials, and the bridge to your Core through Hermes. It also has the Content module (Phase 1): posts about partners, competitors and your own products, a Posts page for approval, scheduled publishing to X and LinkedIn, Reddit posts written for you to post yourself, and UTM tags. See [PLAN.md](PLAN.md) for the whole plan.
## Install
@@ -36,8 +36,8 @@ Then open Supermarket and:
1. **Settings → AI**: Anthropic, with Hermes' key (shared by `supermarket hermes`) or your own, or an LLM server on your network, such as Ollama. Servers found by CoreDesktop's `configure ai-servers` are offered.
2. **Settings → Profile**: enter your website and press *Draft*. Correct the draft and save it.
3. **Inventory**: add your partners and competitors, or import a list. On an entry, *Fill in the empty boxes* reads their website: links, accounts and feeds come straight from the pages, and the AI drafts a description, talking points set against your profile, keywords, hashtags and subreddits. Suggested subreddits are checked with Reddit first (with the Reddit client ID and secret saved), and ones that don't exist, are private or are restricted are left out. What you typed stays; nothing is saved until you press Save.
4. **Settings → Social accounts**: connect X, LinkedIn and Reddit.
3. **Inventory**: add your partners and competitors, or import a list. On an entry, *Fill in the empty boxes* reads their website: links, accounts and feeds come straight from the pages, and the AI drafts a description, talking points set against your profile, keywords, hashtags and subreddits. Suggested subreddits aren't checked with Reddit: open each before posting there. What you typed stays; nothing is saved until you press Save. To add many at once, *Import* a list of just websites and relationships (`- url: https://…` / `relationship: competitor`) and tick *Fill in the empty boxes from each website*: each is filled in the same way in the background, a few at a time, and saved straight into the Market; ones already there (by name or website) are skipped without reading their site.
4. **Settings → Social accounts**: connect X and LinkedIn. Reddit needs nothing: you post Reddit drafts yourself.
The menu on the left has a search box at the top (press `/` to jump to it), then the **Overview** with a card per module, the **Inventory**, and the modules: **Content** (Posts, Sources, Scheduled, Published), and the ones still to come. **Settings**, at the bottom, holds the Profile, Social accounts, Core & Hermes, and AI. Search finds posts, fetched items, inventory entries, your products and settings pages. The look follows brain (Federated's superbrain), including a dark theme that follows your system's setting.
@@ -144,10 +144,11 @@ Edit the brief and answer those questions ("not tested" is a fine answer), then
- **Bing:** with a Bing Webmaster API key (Settings → Search engines), Bing's weekly clicks and impressions, its top searches, and its crawl issues.
**Metrics (Metrics).** With the Stripe key from Settings → Website & sales (give it read access to Customers, Invoices, Credit notes, Charges and Refunds, and Events too), Supermarket reads your whole Stripe history once, then the changes every hour. Under *Gross margin by product*, each product shows what it billed over the last 12 months; give each its margin (what you keep after the cost of delivering it), or leave it at the default, 60%. CLV uses them. Metrics shows:
- MRR today, ARR, the number of paying customers, the average per customer, and NRR for the month and over 12 months;
- MRR today, ARR, the number of paying customers, the average per customer, and NRR for the month and over 12 months (MRR counts paid invoices only);
- a 24-month chart;
- each month's movements (new, expansion, contraction, churn, reactivation), with a page per month listing each customer's move;
- cohorts by the month customers first paid, with the share of their starting MRR they still pay.
- cohorts by the month customers first paid, followed to the latest month: the share of their starting MRR they still pay, and the dollars. With a start month set, its cohort is the existing customers; a customer whose first invoice in Stripe is a renewal was a customer already, and counts as reactivation, not new;
- a customer count that, like Stripe's, takes only customers who have spent more than $0 (payments less refunds).
MRR is built from the invoice lines (each recurring line's amount after discounts, spread over its billing period), so past months are exact. *Spend and CAC* (under Metrics): log what marketing and sales cost each month, by channel, by hand or by pasting a CSV (`month,channel,amount,note`). origami.chat and explee.com campaign spend comes in on its own. CAC is the month's spend over the customers who first paid that month, with a steadier three-month figure. Over the last 12 months it's also shown per channel, using each new customer's first step in the funnel (a reply, a visit, an outreach email), matched by email.
@@ -187,32 +188,111 @@ Reading X needs a bearer token from an X API plan with read access; YouTube need
### Reddit
A Reddit draft is a title and a text for one subreddit, which you choose when writing (suggestions come from the entry's and the profile's subreddits). The subreddit's rules and posting guidelines are read, given to the model, and shown with the draft in Posts. Reddit drafts are written as a community member who says where they work, without hashtags or marketing language. The source link goes at the end of the text; a subreddit that only takes links gets the title and the link.
Reddit's API isn't open to apps like Supermarket, so Reddit posts are written by Supermarket and posted by you. A Reddit draft is a title and a text for one subreddit, which you choose when writing (suggestions come from the entry's and the profile's subreddits). It's written as a community member who says where they work, without hashtags or marketing language. The source link goes at the end of the text.
Before you publish, Posts warns, without blocking, when:
- the subreddit has a rule about self-promotion, is restricted, or doesn't take that kind of post,
- you posted in that subreddit in the past week,
- more than 1 in 10 of your posts in the past 30 days would link to your own sites (Reddit's guideline),
- the account has no posts yet.
Supermarket can't read a subreddit's rules either, so you paste them: each Reddit draft in Posts has a box for its subreddit's rules, with a link to them on Reddit. Pasted once, they're given to the model for every later draft for that subreddit.
Reddit's Data API terms need Reddit's approval for commercial use. Supermarket is meant for a few hand-approved posts, never volume or automation: every post needs you to press Publish or Schedule.
To post: *Open in Reddit* saves your edits and opens the subreddit's submit page with the title and text filled in (links to your sites tagged); *Copy title* and *Copy text* are there for a box that comes up empty. Post it on Reddit, then *Mark as posted*, with the post's link if you like: it moves to Published.
## Signing in to X, LinkedIn and Reddit
Posts warns, without blocking, when:
- the draft promotes your own work,
- the pasted rules have a line about self-promotion, advertising or spam,
- you marked a post in that subreddit as posted in the past week.
## Signing in to X and LinkedIn
Sign-ins come back to Supermarket at `http://localhost:8470/auth/<provider>/callback` (X: `127.0.0.1` instead of `localhost`). Register these callback URLs in your apps:
- X developer portal, your app's *User authentication settings*: `http://127.0.0.1:8470/auth/x/callback`. X refuses `localhost` in callback URLs; `127.0.0.1` is the same machine, and Supermarket sends X this address.
- LinkedIn developer portal, your app's *Auth* tab: `http://localhost:8470/auth/linkedin/callback`
- Reddit, [reddit.com/prefs/apps](https://www.reddit.com/prefs/apps): create a **web app** with the redirect URI `http://localhost:8470/auth/reddit/callback`, and put its client ID and secret under Settings → Social accounts
The old terminal app used `http://localhost:8080/callback`; you can remove that one.
## Security
- The port is published on `127.0.0.1` only, so other machines can't reach it, whatever the firewall says.
- The app has no login, so it protects itself from web pages open in the same browser: it only answers requests addressed to `localhost` (against DNS rebinding), and refuses form posts that don't come from its own pages.
- The local edition has no login, so it protects itself from web pages open in the same browser: it only answers requests addressed to `localhost` (against DNS rebinding), and refuses form posts that don't come from its own pages: each form carries a random token that another site can't know, and the browser's `Origin` must be the app's own.
- The container runs as you, with a read-only filesystem, no Linux capabilities and `no-new-privileges`. It can write only its data folder.
- `/mcp` requires the bearer token in `mcp-token`.
- `/mcp`, and the same tools as a JSON API at `/api/v1` (documented at `/api/v1/docs`), require an agent's key (Settings → Agents). Anything an agent asks to send out waits on Approvals for a person, unless that kind was allowed on its own. The key in `mcp-token` belongs to the built-in Hermes agent, which may work the CRM queue and read the Market; each agent gets only the tools for what it was given.
## The server edition
Supermarket also runs on a server, for a team that signs in: one company,
at its own domain, with Postgres for its database and Caddy for HTTPS.
**Installing.** On a server with Docker and the compose plugin, clone this
repository and run `./install-server.sh`. It asks for:
- the domain people will open, pointed at the server
- how the certificate is made: from Let's Encrypt (the server must be
reachable from the internet on ports 80 and 443), from Caddy's own
certificate authority (a private network or VPN), or from your own CA
(`cert.pem` and `key.pem` in `server/certs/`)
- the mail server for invitations and password resets
(`smtp://user:password@host:587`, STARTTLS, or `smtps://…:465`)
It makes the database password and the secret key, writes them to
`server.env` (readable only by you), and starts Supermarket, Postgres, a
nightly backup and Caddy (`compose.server.yaml`). **Keep a copy of
`SUPERMARKET_SECRET_KEY`**: the keys and tokens in the database are encrypted
with it. Run `./install-server.sh` again after `git pull` to update.
**The first owner.** A new server prints a link to create its owner, once,
for a day (`install-server.sh` shows it; `supermarket setup-link` makes a new
one). The owner fills in the company's profile, then invites the others
under Settings → Users.
**People.** Admins can do everything; members get the modules they're given,
each to view or to edit, and see nothing else: their menu, the Overview,
Search and the SEO emails follow it, and the server refuses the rest. Each
person can turn on two-factor sign-in (an authenticator app) under Settings →
Your account, see where they're signed in, and connect their own social
accounts to post as. Sign-ins are limited per address and per IP, and an
account locks after 10 failures in a row (a password reset or an admin
unlocks it). Settings → Activity shows who did what.
**Social accounts and Search Console.** Each service's developer app needs the
server's addresses as its redirect URLs: `https://<domain>/auth/x/callback`,
`…/auth/linkedin/callback`, `…/auth/linkedin-page/callback` and
`…/auth/google/callback`.
**Backups.** Postgres is dumped every night at 03:00, and two weeks of dumps
are kept, in the `pgbackups` volume; Settings → Backups lists them and says
how to restore one, which is done on the server.
**A private network.** With Caddy's CA or your own, nothing on the internet
needs to reach the server; browsers need to trust the CA. Services that call
in (none yet) wouldn't reach it, so Supermarket polls instead, as on a
computer.
Hermes and the CRM bridge use the local edition's socket; on a server, agents
come with their own keys (Phase 11 in PLAN.md).
## The multi-tenant edition
Many teams at one address, each working on one website domain, with its
data in its own Postgres schema and its own database role. People sign up
at `/signup`, belong to as many teams as they like, and switch between them
from the sidebar. A team proves its domain (a DNS record, a file on the
site, or its Search Console property) before Supermarket crawls, reads or
publishes to the site.
`compose.multi.yaml` runs several copies of the app (3 by default) behind
Caddy; the cloud's managed Postgres and the object storage (Garage) are
outside it, named in `multi.env` (the file's top lists what it holds). The
database user needs `CREATEROLE`, to give each team its role. Everything a
request needs is in Postgres and the files are in the object storage, so
any copy answers any request; background work is shared between the copies
team by team.
Connection pooling: each team has a small pool of its own (4 connections,
idle ones closed after a minute). A PgBouncer in front must use session
pooling, since each connection carries its team's role and search path.
The people running the service, listed in `SUPERMARKET_PLATFORM_ADMINS`,
see every team at `/platform` (with two-factor sign-in): their size, people
and what failed lately; they can suspend a team, resend its invitations,
release a domain, and *view as* a team with a reason, for at most an hour,
recorded in the team's own log.
## Development
@@ -241,6 +321,18 @@ collation. New SQL should run on both: use `db.Insert` (not `LastInsertId`),
`ON CONFLICT … DO NOTHING` (not `INSERT OR IGNORE`), table-qualified columns
in an upsert's `DO UPDATE`, and every selected column in `GROUP BY`.
File storage (`internal/storage`) is tested on a folder, and on an
S3-compatible bucket when `SUPERMARKET_TEST_S3` names one, such as a Garage in
Docker: `SUPERMARKET_TEST_S3='http://ACCESS_KEY:SECRET_KEY@127.0.0.1:3900/bucket'`.
To check every page renders the same from real data on both databases:
`supermarket export`, import the file into a new Postgres database and a new
SQLite one (`supermarket import`, with each edition's settings), then
`SUPERMARKET_TEST_PAGES_DB=postgres://… SUPERMARKET_TEST_PAGES_SQLITE=…/app.db
go test -run TestPagesOnRealData ./internal/web`. Queries whose rows are
summed or shown in order need an `ORDER BY` that settles every tie: the two
databases break ties differently.
**Changing the schema.** Add a `db.Migration` to `both` in
`internal/db/migrations.go`, written in SQLite's SQL. Postgres gets the same
statements translated (`INTEGER` → `BIGINT`, `INTEGER PRIMARY KEY` → an identity
@@ -258,6 +350,9 @@ together), and each is recorded in `schema_migrations`.
| `cmd/supermarket` | The server |
| `internal/config` | The edition (local, server, multi-tenant) and its settings |
| `internal/db` | The database: SQLite or Postgres, the schema and its migrations |
| `internal/transfer` | Export and import: a whole Supermarket as a `.tar.gz`, between SQLite and Postgres |
| `internal/jobs` | Locks shared by copies of the app, so only one does each job |
| `internal/storage` | Files that must last (exports, uploads): a folder, or an S3 bucket (Garage) |
| `internal/web` | Pages (Go templates + [htmx](https://htmx.org), no JavaScript build) |
| `internal/profile`, `internal/inventory` | The company profile and the inventory |
| `internal/ai` | AI providers: Anthropic (official Go SDK) and OpenAI-compatible servers |
+263 -13
View File
@@ -12,10 +12,26 @@ and emails, pushes and pull requests on your Gitea, restores. Leave them
for last, or skip them. Before a session, make a backup:
`supermarket backup "before testing"`.
**Three passes, one per edition.** Sections 1–13 are the app itself, and
are run first on the local edition, on this computer. Then:
| Pass | Run it with | Sections |
|---|---|---|
| **Local** | `install.sh` / `./update.sh`, at <http://localhost:8470> | 1–13, 14 (local part), 15 |
| **Server, with the Core** | `./install-server.sh` on a server (or a test machine, with Caddy's own CA), its Core's domain entered under Settings → Core & Hermes | 14, 15 (agents on a server), 16, and a quick run through 2–10 as a member with only some modules |
| **Multi-tenant** | `compose.multi.yaml` with a Postgres and a Garage bucket (`multi.env`), `SUPERMARKET_PLATFORM_ADMINS` set | 17, 18 (with Stripe's test mode), and 16 for a team's Core sign-in |
On the server and multi-tenant passes, sign in as different people (an
owner, an admin, a member with one module) in separate browser profiles or
private windows, so their sessions don't mix.
Throughout, also notice:
- [x] Every page loads without an error, in both light and dark mode
(follows the system setting).
- [ ] The theme switch in the top bar offers *as the device is*, light and
dark; the choice applies at once, stays after a reload and a new
page, with no flash of the other colours, and is kept per browser.
- [x] The sidebar shows where you are, and the Posts, Review and Outreach
counts match what's on those pages.
- [ ] After every Save or action, a short message confirms it at the top of
@@ -163,12 +179,27 @@ Throughout, also notice:
rest from its website.
- [x] Edit and delete an entry.
- [x] *Export*, then *Import* the file again: nothing is duplicated.
- [ ] **(costs)** On *Import*, paste a list of only `url:` and
`relationship:` (say three, one already in the Market, one a site
that doesn't exist) and tick *Fill in the empty boxes from each
website*. The page counts them off as they're done; the new ones are
in the Market, filled in, with the relationship given. The one already
there is skipped without its site being read; the bad site fails with
the reason.
- [ ] Without the AI set up, the box can't be ticked; a list of websites
only, imported without it, says to tick it.
- [ ] A list typed with no space after the dashes (`-url: https://…`)
imports as if it had them; YAML that still isn't a list says each
entry starts with a dash and a space.
- [ ] Leave a list filling and restart the app (`./update.sh`): the
import page says it stopped after so many, and importing the list
again skips the ones added.
## 5. Content
### Sources
- [ ] *Fetch* on a Market entry finds new items from its feeds and
- [x] *Fetch* on a Market entry finds new items from its feeds and
sitemap, and the list shows when it was last checked.
- [x] Items can be dismissed and restored.
- [ ] Your own products (`/content/own`) show your sites' and feeds' new
@@ -185,16 +216,27 @@ Throughout, also notice:
- [ ] Editing a draft and saving keeps the edit.
- [ ] Links to your own sites get UTM tags when published; other links
don't.
- [ ] For Reddit, choosing a subreddit shows its rules, and the draft
respects them.
- [ ] A Reddit draft in Posts has a box for its subreddit's rules, open
while none are pasted, with a link that opens them on Reddit. Paste
them and *Save rules*: they're kept, and a rule about
self-promotion shows as a warning. Write another draft for that
subreddit: it respects them.
- [ ] Choosing Reddit when writing says "(you post it yourself)", and the
Market entry's suggested subreddits say they aren't checked.
### Publishing
- [ ] **(real)** *Publish* on an X draft posts it, and it moves to
Published with a link to the post.
- [ ] **(real)** The same for LinkedIn.
- [ ] Reddit: *Open in Reddit* opens the submit page filled in; *Mark as
posted* moves it to Published.
- [ ] Reddit drafts have no *Publish now* or *Schedule*. *Open in Reddit*
saves the edits and opens the subreddit's submit page with the title
and text filled in (source link at the end, tagged). *Copy title* and
*Copy text* copy what's on screen, the text with the source link.
- [ ] **(real)** Post it on Reddit, paste the post's link and *Mark as
posted*: it moves to Published. A later draft for the same
subreddit warns that you posted there in the past week.
- [ ] Settings → Social accounts has no Reddit card.
- [ ] *Schedule* a draft for a few minutes ahead: it shows under Scheduled,
and goes out at that time (in your local time zone).
- [ ] *Unschedule* puts it back in Posts.
@@ -484,8 +526,12 @@ Throughout, also notice:
- [ ] With the Stripe key's read access widened (Customers, Invoices, Credit
notes, Charges and Refunds, Events), Metrics → *Sync now* reads your
whole history the first time and says so.
- [ ] The counts of customers, invoices, credit notes and refunds match
Stripe's dashboard (draft invoices aren't counted).
- [ ] The counts of invoices, credit notes and refunds match Stripe's
dashboard (draft invoices aren't counted).
- [ ] After the first sync with this version (it reads everything once,
charges included), *Customers* matches Stripe's customer list
filtered to total spend above $0, and says "of N in Stripe" (deleted
customers left out). *Payments* counts the charges.
- [ ] A later *Sync now* applies only the changes since the last one; a
payment or refund made in Stripe shows up within the hour.
- [ ] The currencies listed are the ones you bill in.
@@ -497,8 +543,13 @@ Throughout, also notice:
### MRR, movements and NRR
- [ ] Metrics shows MRR today, close to Stripe's own MRR figure (Billing →
Overview). Small differences come from how each counts prorations and
open invoices.
Overview). Small differences come from how each counts prorations,
and Supermarket counts only paid invoices.
- [ ] A customer with only an unpaid (open) invoice isn't in MRR or any
cohort; once it's paid, they are.
- [ ] A customer whose first invoice in Stripe is a renewal shows as
*existing* in that month's moves, counted under reactivation, not
new, and is in no cohort. One with a $0 trial before paying is new.
- [x] The month-by-month table's net change adds up: new + expansion +
reactivation − contraction − churn.
- [ ] Open a month: each customer's move is listed with the MRR before
@@ -507,6 +558,11 @@ Throughout, also notice:
from that month appears; *Count from …* makes those customers the
starting base, and the suggestion goes away.
- [x] Cohorts start at 100% in their first month.
- [ ] Cohorts list every cohort, each followed to the latest month. Each
is two rows: the percentages, and the dollars lined up under them;
the month, customers and starting MRR sit across both.
- [ ] With *Count from* set, that month's cohort says *existing
customers*; with it cleared, none does.
### Spend and CAC
@@ -549,6 +605,8 @@ Throughout, also notice:
- [x] Before Hermes has copied the CRM, Metrics → Customers and the CRM says
no Accounts are copied, and lists every customer with billing.
- [ ] It lists only customers who have spent more than $0: not trials,
not ones with only unpaid invoices, not ones refunded in full.
- [ ] Once Accounts are copied (after the CRM bridge works), customers are
matched by stored ID, email or domain; check a few against EspoCRM.
Gmail-style addresses never match by domain.
@@ -771,7 +829,10 @@ Throughout, also notice:
## 11. Agents (MCP)
- [x] `supermarket token` prints a token.
The detailed checks for agents (Phase 11) are in section 15.
- [x] `supermarket token` prints a token. (Since Phase 11 it's the key of
the built-in *Hermes* agent, under Settings → Agents.)
- [ ] Claude Code (`claude mcp list`) shows Supermarket connected, and can
read the company profile, the Market and the CRM queue through it
(`profile_get`, `inventory_list`, `crm_pending_actions`).
@@ -797,6 +858,195 @@ Throughout, also notice:
64-digit key each time.
- [ ] Started with `SUPERMARKET_MODE=server` and nothing else, Supermarket
doesn't start: its log names each missing setting (database, secret
key, mail, an https:// address). With them all set, it says the
server edition isn't built yet. `supermarket config` never shows a
password or the key.
key, mail, an https:// address). With them all set, it starts. The
multi-tenant edition also needs an S3 bucket. `supermarket config`
never shows a password or the key.
- [ ] `supermarket config` also checks the file storage ("writable"), and on
the other editions that Postgres can be reached. With a wrong S3 key or
Postgres password, it says which and why.
- [ ] After the update to schema 30, Settings → Backups shows the "before
schema 30" backup, and `~/.local/share/supermarket/files` exists, empty.
- [ ] Settings → About → Running lists one copy, "(this one)", seen just
now. While an audit runs, `audit:<site>` shows under *Under way*.
- [ ] Connecting a social account or Search Console still works (sign-ins
under way are now kept in the database).
- [ ] `supermarket export` writes `files/exports/supermarket-<date>.tar.gz`
in the data folder, readable only by you, and says keys and tokens
aren't in it. With `--with-secrets`, it says how many are, and warns.
- [ ] `supermarket import <that file>` on this install refuses: the database
isn't empty. Nothing changes.
## 14. The server edition (Phase 10)
On the local edition first:
- [ ] Nothing asks anyone to sign in; Settings has no Users or Your account.
Every form still works (each now carries a hidden `csrf` field).
- [ ] Your old X and LinkedIn sign-ins show under Social accounts as
the company's accounts, with *Sign out*; Settings → Posting accounts
lists them. A LinkedIn draft's *Post as* lists the member and the page.
- [ ] Settings → All connections lists every service, who connected it, and
the last Test; a failing Test shows there as *Failing*.
- [ ] Settings → Activity shows what you published and deleted.
On a server (`./install-server.sh`; with Caddy's own CA on a test machine):
- [ ] The setup link from the install creates the owner and opens the
company profile; the link doesn't work twice. Before it's used, every
page says Supermarket isn't set up yet.
- [ ] Signing out and in works; a wrong password says so without saying
whether the address has an account. Five wrong tries for an address
make it wait; ten in a row lock the account and email its owner.
- [ ] *Forgotten your password?* emails a link that works once, for an hour;
afterwards the old sessions are signed out.
- [ ] Your account: turn on two-factor sign-in from the QR code; signing in
then asks for the code; a recovery code works once.
- [ ] Settings → Users: invite an admin and a member with only SEO (edit).
Both get emails; the invitation's page sets their password.
- [ ] The member sees only SEO in the menu and on the Overview; every
other module and Settings answer *No access*. With SEO as *view*,
SEO's pages show their forms greyed, without buttons.
- [ ] The member connects their own X under Your account and posts as it;
they can't choose the company's account until it's ticked for them on
Settings → Posting accounts.
- [ ] Settings → Activity shows each step above, with who and from where.
- [ ] Settings → Backups lists the nightly dump the morning after.
## 15. Agents, approvals and the API (Phase 11)
On the local edition (and again on a server, with an agent made there):
- [ ] Settings → Agents lists *Hermes*, built in, with the CRM (read and
act) and the Market (read); its key is `mcp-token`. Hermes' CRM job
and Claude Code still work as before.
- [ ] *New agent*: a name, what it's for, Content *read and act* and SEO
*read*. Its key (`sm_…`) is shown once; the agent's page shows only
its first characters afterwards.
- [ ] Claude Code with that key (`claude mcp add --transport http …`, as the
key's page shows): it's offered the Content and SEO reading tools and
the Content tools that change things, and no SEO tool that changes
anything, nor the CRM's.
- [ ] Ask it to read the morning check and What to write next, write a
draft, and schedule it (`content_publish` with a time). The draft is in
Posts *by* the agent; the schedule waits on **Approvals**, with a count
in the sidebar.
- [ ] On Approvals, edit the text, then *Approve*, ticking *let it do this
on its own, up to 1 a day*. It's scheduled. The agent's next post to
that account goes on its own; the one after waits again.
- [ ] *Refuse* one: nothing goes out; `approvals_status` tells the agent.
- [ ] The agent's page: its recent calls (tool, result, time), what it's
waiting on, its limits. Set *calls a minute* to 2: its third call in a
minute is refused. *Pause*: every call is refused at once; *Resume*.
- [ ] *Rotate the key* (old key works a day); *Rotate* with *it leaked*:
the old key stops at once, and what it was allowed on its own is
withdrawn. *Revoke* stops a key at once.
- [ ] `/api/v1/docs` lists every tool. With the key:
`curl -H "Authorization: Bearer sm_…" http://localhost:8470/api/v1/tools`
lists the agent's, and `curl -X POST … /api/v1/content_drafts -d '{}'`
answers with the drafts as JSON.
- [ ] Settings → Activity shows the agent's actions, marked as an agent.
## 16. Signing in with the Core (Phase 12)
On the server pass, with the Core's domain entered under Settings → Core &
Hermes:
- [ ] Settings → Sign-in shows the issuer (`https://authelia.<Core
domain>`) and the redirect address. *Make the client's secret* shows
the entry for `idproviders.yml`, with a `$pbkdf2-sha512$310000$…` hash
like the other clients'.
- [ ] **(real)** The Core's admin adds it to `idproviders.yml` and restarts
Authelia; *Test* says Authelia answers.
- [ ] Turn it on: the sign-in page offers *Sign in with <Core>*.
- [ ] Invite someone by their Core address; they open the invitation and
choose *Sign in with <Core>*: Authelia (with its own two-factor, if
set), then they're in, and Users shows them active.
- [ ] They sign in with the Core again later: straight in. Someone with a
Core account who wasn't invited is refused.
- [ ] *Anyone at <Core domain> may join* with one module: a new Core user
signs in and joins as a member with just that module.
- [ ] *Only with the Core*: a member's password is refused, with a pointer
to the Core; the owner's still works.
- [ ] Signing out of Supermarket also signs out of the Core, if Authelia
offers it (*Test* says so).
- [ ] **(real)** *Roles follow the Core's groups*: in the Core's
Authelia users, put someone in `supermarket-admins`; they sign in
with the Core and are an admin. Move them to `supermarket-content`
and `supermarket-seo-view`: at their next sign-in they edit Content
and read SEO, nothing else. Someone never invited but in
`supermarket-content` joins. Someone in none of these groups keeps
the access set in Users. The owner's role never changes.
- [ ] Activity shows the sign-ins *with the Core*, and the refusals.
## 17. Multi-tenant (Phase 13)
- [ ] `supermarket config` (in a copy) finds Postgres and the bucket; the
app starts as the multi-tenant edition, with several copies behind
Caddy.
- [ ] `/signup`: two teams, each with its own company and website (e.g.
`acme.example`, `bolt.example`). Each lands on its company profile.
The same address can't sign up twice.
- [ ] The profile refuses a website on another domain, saying to set up
another team for it.
- [ ] Before the domain is proved, an audit or a Search Console sync leads
to Settings → Domain. Prove it with the TXT record (or the file, or
Search Console). A second team can't prove a domain the first holds.
- [ ] Team A's owner invites team B's owner: they're added to A with the
account they have, and the team menu at the top of the sidebar
switches between A and B, each showing only its own data.
- [ ] Nothing of one team shows in the other: the Market, Posts, Search,
Activity, Settings, a photo's address, and an agent's tools.
- [ ] Settings → Core & Hermes takes a team's own Core; Hermes connects
with an agent's key (section 15).
- [ ] Settings → Your data (owner): *Export* (keys only with the password),
download it. *Delete the team*: it closes, everyone in it gets an
email, *Undo* brings it back.
- [ ] As a platform admin (`SUPERMARKET_PLATFORM_ADMINS`): `/platform`
asks for two-factor first, then lists the teams with their size,
people and failures. *Suspend* one: its people see it's suspended;
*Restore*. *View as* with a reason: read-only, a banner, it ends by
itself, and the team's Activity records it.
- [ ] Restart one copy: people stay signed in, and the others carry on
the background work.
## 18. Billing (Phase 14)
Multi-tenant only, with Stripe in **test mode**: `SUPERMARKET_STRIPE_KEY`
(`sk_test_…`), `SUPERMARKET_STRIPE_PRICE` (a monthly per-person price),
and `SUPERMARKET_STRIPE_WEBHOOK_SECRET` from `stripe listen --forward-to
https://<domain>/billing/stripe` (or a webhook endpoint in the dashboard
with `checkout.session.completed`, `customer.subscription.*`,
`invoice.paid` and `invoice.payment_failed`). Pay with Stripe's test card
4242 4242 4242 4242. Some steps need time to pass: set the dates in the
`billing` table, then wait for the hourly turn (or restart a copy).
- [ ] Without the Stripe key, a team has everything and there's no
Settings → Billing.
- [ ] A new team is on a 14-day trial of Paid: Settings → Billing says so,
with people, agents, storage and the crawl against the plan's.
Admins see the plan without the buttons.
- [ ] *Subscribe with Stripe* (the owner) goes to Checkout with the
people as the quantity; paying brings you back, and the page soon
shows *Active*, the seats paid for, and the next invoice.
- [ ] *Open Stripe's billing page* opens the Customer Portal; cancelling
there ends the subscription at the period's end, and the page
follows.
- [ ] Each change shows in Activity ("billing changed"). Sending the same
event again (`stripe events resend`) changes nothing.
- [ ] A trial that ends without a subscription drops to Free, and the
owner gets an email. Prospects, Metrics and Sites can be read, not
changed ("The Free plan doesn't include…"); their jobs stop. One
agent, ten Market entries, a 500-page weekly crawl.
- [ ] A failed payment (test card 4000 0000 0000 0341, then a renewal):
a banner on every page (*Pay now* for the owner), and an email.
14 days on: read-only, agents refused, an email. 53 days: everyone
warned. 60: the team closes as being deleted, everyone emailed;
the owner's *Undo* gives a week more to pay.
- [ ] Paying the overdue invoice clears the banner and read-only.
- [ ] Seats: inviting past the seats paid for offers the owner *Add a seat
for them* (Stripe's next invoice shows the proration); an admin is
told to ask the owner. On Free, past two people: *subscribe*.
- [ ] Moving down to Free with more than two people: the owner and one
other edit (the first to join, until the owner chooses under
Settings → Billing); the rest read, and are told why. No one is
removed.
- [ ] Storage: Settings → Billing shows what the team stores (within the
hour). Past the plan's (set `storage_used` high to try it), a photo
upload says the storage is full and the SEO crawl waits. Exports
still work.
+27 -1
View File
@@ -20,6 +20,9 @@ Usage: supermarket [command]
token Print the token agents use to reach Supermarket's MCP endpoint
data Print where its data is kept
config Show its edition and settings, and any problems with them
export [--with-secrets] Export everything (to move to a server, or
another computer); with --with-secrets, keys and tokens too
import <file> Load an export into a new, empty Supermarket
backup [note] Back up the database now (it also backs up daily)
backup --with-secrets The same, with your keys and tokens, for moving
to another computer (keep the file safe)
@@ -64,7 +67,30 @@ case "${1:-open}" in
logs) compose logs -f --tail 200 ;;
hermes) shift; bash "$REPO/hermes/setup.sh" "$@" ;;
token) cat "$DATA/mcp-token" ;;
backup|backups|config)
import)
if ! docker exec supermarket true 2> /dev/null; then
echo "Supermarket isn't running: start it first (supermarket start)."
exit 1
fi
if [ -z "${2:-}" ]; then
echo "Usage: supermarket import <export file>"
exit 1
fi
target="$2"
# A file elsewhere on this computer is copied in, where the app sees it.
if [ -f "$target" ]; then
case "$(realpath "$target")" in
"$(realpath "$DATA")"/*) ;;
*)
mkdir -p "$DATA/files/imports"
install -m 600 "$target" "$DATA/files/imports/$(basename "$target")"
target="imports/$(basename "$target")"
;;
esac
fi
docker exec supermarket supermarket import "$target"
;;
backup|backups|config|export)
if ! docker exec supermarket true 2> /dev/null; then
echo "Supermarket isn't running: start it first (supermarket start)."
exit 1
+363 -13
View File
@@ -25,6 +25,7 @@ import (
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
@@ -35,16 +36,22 @@ import (
"time"
"supermarket/internal/ai"
"supermarket/internal/appmail"
"supermarket/internal/backup"
"supermarket/internal/billing"
"supermarket/internal/config"
"supermarket/internal/content"
"supermarket/internal/core"
"supermarket/internal/crm"
"supermarket/internal/db"
"supermarket/internal/fileutil"
"supermarket/internal/jobs"
"supermarket/internal/legacy"
"supermarket/internal/mcpserver"
"supermarket/internal/secrets"
"supermarket/internal/storage"
"supermarket/internal/transfer"
"supermarket/internal/users"
"supermarket/internal/web"
)
@@ -68,6 +75,20 @@ func main() {
if len(os.Args) > 1 && os.Args[1] == "config" {
os.Exit(configCommand())
}
if len(os.Args) > 1 && os.Args[1] == "setup-link" {
if err := setupLinkCommand(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if len(os.Args) > 1 && (os.Args[1] == "export" || os.Args[1] == "import") {
if err := transferCommand(os.Args[1], os.Args[2:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if len(os.Args) > 1 && (os.Args[1] == "backup" || os.Args[1] == "backups" || os.Args[1] == "restore") {
if err := backupCommand(os.Args[1], os.Args[2:]); err != nil {
fmt.Fprintln(os.Stderr, err)
@@ -96,6 +117,10 @@ func configCommand() int {
for _, it := range cfg.Summary() {
fmt.Printf("%-9s %s\n", it.Name+":", it.Value)
}
if err == nil {
fmt.Println()
err = liveChecks(cfg)
}
if err == nil {
err = cfg.Ready()
}
@@ -111,6 +136,43 @@ func configCommand() int {
return 0
}
// liveChecks reaches what the settings name: Postgres, and file storage
// (writing, reading and deleting a small file).
func liveChecks(cfg *config.Config) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
var problems []string
if cfg.DatabaseURL != "" {
fmt.Print("Checking the database… ")
d, err := sql.Open("pgx", cfg.DatabaseURL)
if err == nil {
err = d.PingContext(ctx)
d.Close()
}
if err != nil {
fmt.Println("no")
problems = append(problems, "Postgres can't be reached: "+err.Error())
} else {
fmt.Println("reachable")
}
}
fmt.Print("Checking the file storage… ")
st, err := storage.Open(cfg.Storage)
if err == nil {
err = storage.Check(ctx, st)
}
if err != nil {
fmt.Println("no")
problems = append(problems, "The file storage doesn't work: "+err.Error())
} else {
fmt.Println("writable")
}
if len(problems) > 0 {
return errors.New(strings.Join(problems, "\n"))
}
return nil
}
func run(log *slog.Logger) error {
cfg, err := config.Load(os.Getenv)
if err != nil {
@@ -156,7 +218,12 @@ func run(log *slog.Logger) error {
return err
}
db.AppVersion = version
database, err := db.Open(filepath.Join(dataDir, "app.db"))
var database *db.DB
if cfg.DatabaseURL != "" {
database, err = db.OpenPostgres(cfg.DatabaseURL)
} else {
database, err = db.Open(filepath.Join(dataDir, "app.db"))
}
if err != nil {
return err
}
@@ -165,7 +232,22 @@ func run(log *slog.Logger) error {
log.Info("database: migrated", "database", database.Dialect, "from", database.MigratedFrom, "to", db.Schema())
}
if n, err := content.RecoverInterrupted(database); err != nil {
// This copy of the app, for the locks it shares with any others.
runner, err := jobs.New(database, version, log)
if err != nil {
return err
}
defer runner.Stop() // before the database closes
alone, err := runner.Alone()
if err != nil {
return err
}
multi := cfg.Edition == config.Multi
if !alone {
log.Info("jobs: other copies of Supermarket are running; work they have under way is left to them")
} else if multi {
// Each team's, once the teams are open (below).
} else if n, err := content.RecoverInterrupted(database); err != nil {
return err
} else if n > 0 {
log.Warn("drafts were being published when Supermarket stopped; marked failed for review", "count", n)
@@ -174,9 +256,12 @@ func run(log *slog.Logger) error {
// Hermes' Anthropic key and model, if the user chose to share them
ai.SharedFile = filepath.Join(dataDir, "hermes-ai.json")
// What Hermes' CRM job checks before it runs; see internal/crm.
crm.StateFile = filepath.Join(dataDir, "crm-state")
if err := crm.WriteState(database, time.Now()); err != nil {
log.Error("writing the CRM state file", "err", err)
local := cfg.Edition == config.Local
if local {
crm.StateFile = filepath.Join(dataDir, "crm-state")
if err := crm.WriteState(database, time.Now()); err != nil {
log.Error("writing the CRM state file", "err", err)
}
}
// The local edition keeps its keys and tokens in a file beside the
@@ -193,6 +278,21 @@ func run(log *slog.Logger) error {
if err != nil {
return err
}
// Files that must outlast this copy of the app: a folder, or S3,
// checked now so a wrong key is found at the start.
files, err := storage.Open(cfg.Storage)
if err != nil {
return err
}
if cfg.Storage.S3() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
err = storage.Check(ctx, files)
cancel()
if err != nil {
return err
}
}
token, err := mcpToken(filepath.Join(dataDir, "mcp-token"))
if err != nil {
return err
@@ -205,13 +305,17 @@ func run(log *slog.Logger) error {
// The import never stops the app: a bad old file is reported on the
// overview page instead.
status, importErr := legacy.Import(database, sec, filepath.Join(dataDir, "import"))
var status *legacy.Status
var importErr error
if !multi {
status, importErr = legacy.Import(database, sec, filepath.Join(dataDir, "import"))
}
if importErr != nil {
log.Error("importing the old app's data", "err", importErr)
} else if status != nil {
log.Info("imported the old app's data", "summary", strings.Join(status.Summary, "; "))
}
if status == nil && importErr == nil {
if status == nil && importErr == nil && !multi {
status, _ = legacy.LoadStatus(database)
}
@@ -221,20 +325,58 @@ func run(log *slog.Logger) error {
Secrets: sec,
Core: c,
DataDir: dataDir,
Files: files,
Jobs: runner,
PublicURL: publicURL,
Version: version,
MCPToken: token,
MCPSocket: filepath.Join(hostData, filepath.Base(mcpSocket)),
MCP: mcpserver.Handler(database, token, version),
Mail: appMail(cfg),
Log: log,
ImportStatus: status,
ImportErr: importErr,
}
// The multi-tenant edition: each team's data in its own schema.
if multi {
teams, err := database.Teams()
if err != nil {
return err
}
defer teams.Close()
srv.Teams, srv.Platform = teams, database
if cfg.StripeKey != "" {
plans, err := billing.Load(cfg.PlansFile, cfg.StripePrice, cfg.StripePriceYear, cfg.StripePriceStorage)
if err != nil {
return err
}
srv.Plans = plans
}
if alone {
srv.RecoverTeams(context.Background())
}
}
// Agents reach /mcp with their keys. On the local edition, mcp-token is
// the key of the built-in Hermes agent.
srv.MCP = mcpserver.Handler(database, version, srv.AgentAuth, srv.AgentTools)
if local {
if err := srv.EnsureHermes(token); err != nil {
return err
}
}
handler, err := srv.Handler()
if err != nil {
return err
}
// A new server has no owner yet: a link to create one.
if cfg.Edition == config.Server {
if link, err := setupLink(database, publicURL); err != nil {
return err
} else if link != "" {
log.Warn("Supermarket isn't set up yet. To create its owner, open this link (it works once, for a day): " + link)
}
}
httpServer := &http.Server{
Addr: addr,
Handler: handler,
@@ -247,11 +389,16 @@ func run(log *slog.Logger) error {
srv.Restart = stop
errCh := make(chan error, 2)
go func() {
if err := mcpserver.ServeSocket(ctx, database, version, mcpSocket, log); err != nil {
errCh <- fmt.Errorf("MCP socket %s: %w", mcpSocket, err)
}
}()
// Hermes on this computer reaches the app through a socket in the data
// folder; on a server, agents use /mcp (Phase 11).
if local {
go func() {
if err := mcpserver.ServeSocket(ctx, database, version, mcpSocket, log); err != nil {
errCh <- fmt.Errorf("MCP socket %s: %w", mcpSocket, err)
}
}()
}
go runner.CheckIns(ctx)
go srv.RunScheduler(ctx)
go srv.RunImports(ctx)
go srv.RunDiscovery(ctx)
@@ -260,9 +407,14 @@ func run(log *slog.Logger) error {
go srv.RunSEO(ctx)
go srv.RunMetrics(ctx)
go srv.RunBackups(ctx)
go srv.RunAccounts(ctx)
go srv.RunTeams(ctx)
// A sync falls due, and a claim times out, without anything being
// written: refresh the state file each minute.
go func() {
if !local {
return
}
t := time.NewTicker(time.Minute)
defer t.Stop()
for {
@@ -297,6 +449,55 @@ func run(log *slog.Logger) error {
return nil
}
// appMail sends the app's own mail, where there's a mail server.
func appMail(cfg *config.Config) appmail.Sender {
if cfg.Mail == nil {
return nil
}
return &appmail.SMTP{Conf: cfg.Mail}
}
// setupLink makes a new one-time link to create the owner, or returns ""
// if there's an owner already.
func setupLink(d *db.DB, publicURL string) (string, error) {
done, err := users.HasOwner(d, users.Team)
if err != nil || done {
return "", err
}
token, err := users.NewLink(d, users.SetupLink, 0, time.Now())
if err != nil {
return "", err
}
return publicURL + "/setup/" + token, nil
}
// setupLinkCommand runs `supermarket setup-link`: a new link to create the
// owner, replacing the one in the start-up log.
func setupLinkCommand() error {
cfg, err := config.Load(os.Getenv)
if err != nil {
return fmt.Errorf("the settings need fixing (supermarket config shows them):\n%w", err)
}
if cfg.Edition == config.Local {
return errors.New("the local edition has no sign-in, so nothing to set up: open " + cfg.PublicURL)
}
d, _, err := openForCommand(cfg)
if err != nil {
return err
}
defer d.Close()
link, err := setupLink(d, cfg.PublicURL)
if err != nil {
return err
}
if link == "" {
return errors.New("Supermarket is set up already: its owner signs in, and invites the others (Settings → Users)")
}
fmt.Println("Open this link to create Supermarket's owner. It works once, for a day, and replaces any earlier link:")
fmt.Println(link)
return nil
}
// mcpToken reads the bearer token agents use for /mcp, creating it if there
// is none. install.sh may create it first, to give it to Hermes.
func mcpToken(path string) (string, error) {
@@ -388,3 +589,152 @@ func backupCommand(cmd string, args []string) error {
fmt.Printf("Backed up to %s (%.1f MB)\n", b.Name, float64(b.Size)/(1<<20))
return nil
}
// openForCommand opens the edition's database and secrets, for commands
// run beside the app (export, import).
func openForCommand(cfg *config.Config) (*db.DB, *secrets.Store, error) {
if cfg.Edition == config.Local {
d, err := db.OpenSQLite(filepath.Join(cfg.DataDir, "app.db"))
if err != nil {
return nil, nil, err
}
sec, err := secrets.Open(filepath.Join(cfg.DataDir, "secrets.json"))
if err != nil {
d.Close()
return nil, nil, err
}
return d, sec, nil
}
db.AppVersion = version
d, err := db.OpenPostgres(cfg.DatabaseURL)
if err != nil {
return nil, nil, err
}
sec, err := secrets.OpenDB(d, cfg.SecretKey, cfg.OldKey)
if err != nil {
d.Close()
return nil, nil, err
}
return d, sec, nil
}
// hostPath is where a stored file is on the host, for the local edition's
// folder; else its name in the store.
func hostPath(cfg *config.Config, key string) string {
if !cfg.Storage.S3() && cfg.Storage.Dir == filepath.Join(cfg.DataDir, "files") {
return filepath.Join(cfg.HostData, "files", filepath.FromSlash(key))
}
if !cfg.Storage.S3() {
return filepath.Join(cfg.Storage.Dir, filepath.FromSlash(key))
}
return cfg.Storage.String() + "/" + key
}
// transferCommand runs `supermarket export [--with-secrets]` and
// `supermarket import <file>`.
func transferCommand(cmd string, args []string) error {
cfg, err := config.Load(os.Getenv)
if err != nil {
return fmt.Errorf("the settings need fixing (supermarket config shows them):\n%w", err)
}
files, err := storage.Open(cfg.Storage)
if err != nil {
return err
}
d, sec, err := openForCommand(cfg)
if err != nil {
return err
}
defer d.Close()
ctx := context.Background()
if cmd == "export" {
withSecrets := len(args) > 0 && args[0] == "--with-secrets"
if len(args) > 1 || (len(args) == 1 && !withSecrets) {
return errors.New("usage: supermarket export [--with-secrets]")
}
tmp, err := os.CreateTemp("", "export-*.tar.gz")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
defer tmp.Close()
var from *secrets.Store
if withSecrets {
from = sec
}
m, err := transfer.Export(ctx, d, from, version, tmp)
if err != nil {
return err
}
size, _ := tmp.Seek(0, io.SeekCurrent)
tmp.Seek(0, io.SeekStart)
key := "exports/supermarket-" + time.Now().Format("20060102-150405")
if withSecrets {
key += "-with-secrets"
}
key += ".tar.gz"
if err := files.Put(ctx, key, tmp, size); err != nil {
return err
}
rows := 0
for _, n := range m.Tables {
rows += n
}
fmt.Printf("Exported %d rows from %d tables (schema %d) to %s (%.1f MB)\n", rows, len(m.Tables), m.Schema, hostPath(cfg, key), float64(size)/(1<<20))
if withSecrets {
fmt.Printf("It holds %d keys and tokens: keep it as safe as they are, and delete it once you've moved.\n", m.Secrets)
} else {
fmt.Println("Keys and tokens aren't in it: add --with-secrets to take them too, or enter them again after the move.")
}
return nil
}
if len(args) != 1 {
return errors.New("usage: supermarket import <export file, or its name from supermarket export>")
}
open, where, err := exportOpener(ctx, cfg, files, args[0])
if err != nil {
return err
}
res, err := transfer.Import(ctx, d, sec, open)
if err != nil {
return err
}
rows := 0
for _, n := range res.Tables {
rows += n
}
fmt.Printf("Imported %d rows into %d tables, and %d keys and tokens, from %s (made %s on %s, schema %d).\n",
rows, len(res.Tables), res.Secrets, where, res.Manifest.Created.Local().Format("2 Jan 2006 15:04"), res.Manifest.From, res.Manifest.Schema)
if cfg.Edition == config.Local {
fmt.Println("Restart Supermarket to see it: supermarket restart")
}
return nil
}
// exportOpener finds an export: a file, or a name in the file storage
// (as supermarket export printed it, or under exports/ or imports/).
func exportOpener(ctx context.Context, cfg *config.Config, files storage.Store, arg string) (func() (io.ReadCloser, error), string, error) {
// A path on the host, in the data folder, is /data inside the container.
p := arg
if rel, err := filepath.Rel(cfg.HostData, arg); err == nil && filepath.IsAbs(arg) && !strings.HasPrefix(rel, "..") {
p = filepath.Join(cfg.DataDir, rel)
}
if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
return func() (io.ReadCloser, error) { return os.Open(p) }, arg, nil
}
name := filepath.ToSlash(arg)
if i := strings.Index(name, "/files/"); i >= 0 { // as export printed it
name = name[i+len("/files/"):]
}
for _, key := range []string{name, "exports/" + name, "imports/" + name} {
if storage.CheckKey(key) != nil {
continue
}
if _, err := files.Stat(ctx, key); err == nil {
return func() (io.ReadCloser, error) { return files.Get(ctx, key) }, hostPath(cfg, key), nil
}
}
return nil, "", fmt.Errorf("no export at %s", arg)
}
+79
View File
@@ -0,0 +1,79 @@
# Supermarket's multi-tenant edition: many teams at one address, each
# working on its own domain, with its data in its own Postgres schema.
# Several copies of the app run behind Caddy; Postgres and the object
# storage are outside (the cloud's managed Postgres, and Garage), named in
# multi.env:
#
# docker compose -f compose.multi.yaml --env-file multi.env up -d --build
#
# multi.env holds:
# SUPERMARKET_DOMAIN the address people open, e.g. app.example.com
# SUPERMARKET_DATABASE_URL postgres://…; its user needs CREATEROLE
# SUPERMARKET_SECRET_KEY supermarket secret-key makes one: keep a copy
# SUPERMARKET_MAIL_URL smtp://… or smtps://…
# SUPERMARKET_STORAGE s3://bucket/prefix
# SUPERMARKET_S3_ENDPOINT https://… (Garage's S3 API)
# SUPERMARKET_S3_ACCESS_KEY, SUPERMARKET_S3_SECRET_KEY
# SUPERMARKET_PLATFORM_ADMINS the platform admins' emails, comma-separated
# SUPERMARKET_COPIES how many copies of the app (default 3)
name: supermarket-multi
services:
supermarket:
build:
context: .
args:
VERSION: ${SUPERMARKET_VERSION:-dev}
image: supermarket:multi
restart: unless-stopped
init: true
user: "10001:10001"
deploy:
replicas: ${SUPERMARKET_COPIES:-3}
environment:
SUPERMARKET_MODE: multi
SUPERMARKET_PUBLIC_URL: https://${SUPERMARKET_DOMAIN:?}
SUPERMARKET_DATABASE_URL: ${SUPERMARKET_DATABASE_URL:?}
SUPERMARKET_SECRET_KEY: ${SUPERMARKET_SECRET_KEY:?}
SUPERMARKET_MAIL_URL: ${SUPERMARKET_MAIL_URL:?}
SUPERMARKET_MAIL_FROM: ${SUPERMARKET_MAIL_FROM:-}
SUPERMARKET_STORAGE: ${SUPERMARKET_STORAGE:?}
SUPERMARKET_S3_ENDPOINT: ${SUPERMARKET_S3_ENDPOINT:?}
SUPERMARKET_S3_REGION: ${SUPERMARKET_S3_REGION:-garage}
SUPERMARKET_S3_ACCESS_KEY: ${SUPERMARKET_S3_ACCESS_KEY:?}
SUPERMARKET_S3_SECRET_KEY: ${SUPERMARKET_S3_SECRET_KEY:?}
SUPERMARKET_PLATFORM_ADMINS: ${SUPERMARKET_PLATFORM_ADMINS:-}
TZ: ${SUPERMARKET_TZ:-UTC}
# Scratch only (sites' clones, previews): everything a request needs is
# in Postgres, and files are in the object storage, so any copy can
# answer any request.
tmpfs:
- /data:uid=10001,gid=10001,mode=0700
- /tmp
read_only: true
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
caddy:
image: caddy:2-alpine
restart: unless-stopped
ports:
- "${SUPERMARKET_HTTP_PORT:-80}:80"
- "${SUPERMARKET_HTTPS_PORT:-443}:443"
- "${SUPERMARKET_HTTPS_PORT:-443}:443/udp"
environment:
SUPERMARKET_DOMAIN: ${SUPERMARKET_DOMAIN:?}
SUPERMARKET_ACME: ${SUPERMARKET_ACME:-}
SUPERMARKET_TLS: ${SUPERMARKET_TLS:-}
volumes:
- ./server/Caddyfile.multi:/etc/caddy/Caddyfile:ro
- ./server/certs:/certs:ro
- caddydata:/data
- caddyconfig:/config
depends_on: [supermarket]
volumes:
caddydata:
caddyconfig:
+116
View File
@@ -0,0 +1,116 @@
# Supermarket's server edition: one team, signing in, on its own domain.
# install-server.sh writes server.env (the domain, the mail server, the
# secret key and the database password) and starts it:
#
# docker compose -f compose.server.yaml --env-file server.env up -d --build
#
# Caddy answers on ports 80 and 443 and gets the certificate; Supermarket
# itself is published only to Caddy, on the compose network.
name: supermarket-server
services:
supermarket:
build:
context: .
args:
VERSION: ${SUPERMARKET_VERSION:-dev}
image: supermarket:server
restart: unless-stopped
init: true
user: "10001:10001"
environment:
SUPERMARKET_MODE: server
SUPERMARKET_PUBLIC_URL: https://${SUPERMARKET_DOMAIN:?}${SUPERMARKET_PUBLIC_PORT:-}
SUPERMARKET_DATABASE_URL: postgres://supermarket:${SUPERMARKET_DB_PASSWORD:?}@db:5432/supermarket?sslmode=disable
SUPERMARKET_SECRET_KEY: ${SUPERMARKET_SECRET_KEY:?}
SUPERMARKET_MAIL_URL: ${SUPERMARKET_MAIL_URL:?}
SUPERMARKET_MAIL_FROM: ${SUPERMARKET_MAIL_FROM:-}
SUPERMARKET_PG_BACKUPS: /backups
TZ: ${SUPERMARKET_TZ:-UTC}
volumes:
- appdata:/data # scratch: the sites' clones and previews
- pgbackups:/backups:ro # the nightly dumps, for Settings → Backups
depends_on:
db:
condition: service_healthy
networks: [internal, web]
read_only: true
tmpfs:
- /tmp
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
db:
image: postgres:18-alpine
restart: unless-stopped
environment:
POSTGRES_DB: supermarket
POSTGRES_USER: supermarket
POSTGRES_PASSWORD: ${SUPERMARKET_DB_PASSWORD:?}
volumes:
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD", "pg_isready", "-U", "supermarket", "-d", "supermarket"]
interval: 5s
timeout: 5s
retries: 20
networks: [internal]
# A dump of the database every night at 03:00 (the server's TZ), kept for
# two weeks: supermarket-YYYY-MM-DD.dump, in pg_dump's custom format.
# Restoring is the operator's: see server/README.md.
backup:
image: postgres:18-alpine
restart: unless-stopped
environment:
PGHOST: db
PGUSER: supermarket
PGDATABASE: supermarket
PGPASSWORD: ${SUPERMARKET_DB_PASSWORD:?}
TZ: ${SUPERMARKET_TZ:-UTC}
volumes:
- pgbackups:/backups
- ./server/backup.sh:/usr/local/bin/backup.sh:ro
entrypoint: ["/bin/sh", "/usr/local/bin/backup.sh"]
depends_on:
db:
condition: service_healthy
networks: [internal]
caddy:
image: caddy:2-alpine
restart: unless-stopped
ports:
- "${SUPERMARKET_HTTP_PORT:-80}:80"
- "${SUPERMARKET_HTTPS_PORT:-443}:443"
- "${SUPERMARKET_HTTPS_PORT:-443}:443/udp"
environment:
SUPERMARKET_DOMAIN: ${SUPERMARKET_DOMAIN:?}
# "email you@example.com", for Let's Encrypt's notices; or empty.
SUPERMARKET_ACME: ${SUPERMARKET_ACME:-}
# Empty: a certificate from Let's Encrypt (the server must be reachable
# from the internet on ports 80 and 443). "tls internal": Caddy's own
# CA, for a private network or VPN. "tls /certs/cert.pem
# /certs/key.pem": your own CA's certificate, put in server/certs/.
SUPERMARKET_TLS: ${SUPERMARKET_TLS:-}
volumes:
- ./server/Caddyfile:/etc/caddy/Caddyfile:ro
- ./server/certs:/certs:ro
- caddydata:/data
- caddyconfig:/config
depends_on: [supermarket]
networks: [web]
volumes:
appdata:
pgdata:
pgbackups:
caddydata:
caddyconfig:
networks:
internal:
internal: true # the database has no way out
web:
+15
View File
@@ -7,7 +7,9 @@ require (
github.com/emersion/go-imap v1.2.1
github.com/emersion/go-message v0.18.2
github.com/jackc/pgx/v5 v5.13.0
github.com/minio/minio-go/v7 v7.4.1
github.com/modelcontextprotocol/go-sdk v1.8.0
golang.org/x/crypto v0.59.0
golang.org/x/net v0.63.0
golang.org/x/text v0.44.0
gopkg.in/yaml.v3 v3.0.1
@@ -17,6 +19,7 @@ require (
require (
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/buger/jsonparser v1.1.2 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dustin/go-humanize v1.1.0 // indirect
github.com/emersion/go-sasl v0.0.0-20200509203442-7bfe0ed36a21 // indirect
github.com/go-logr/logr v1.4.2 // indirect
@@ -27,10 +30,17 @@ require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.3 // indirect
github.com/klauspost/compress v1.19.2 // indirect
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
github.com/klauspost/crc32 v1.3.0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/minio/crc64nvme v1.1.1 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/pb33f/ordered-map/v2 v2.3.1 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rs/xid v1.6.0 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect
@@ -38,17 +48,22 @@ require (
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
github.com/tinylib/msgp v1.6.4 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
github.com/zeebo/xxh3 v1.1.0 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/otel v1.33.0 // indirect
go.opentelemetry.io/otel/metric v1.33.0 // indirect
go.opentelemetry.io/otel/trace v1.33.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/time v0.15.0 // indirect
gopkg.in/ini.v1 v1.67.3 // indirect
modernc.org/libc v1.80.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
rsc.io/qr v0.2.0 // indirect
)
+45 -9
View File
@@ -38,8 +38,9 @@ github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPn
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk=
github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
@@ -90,24 +91,40 @@ github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI=
github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.4.1 h1:PtU/zIOfQRWZ+QydXAZysc+xZYHdG+BBR4Z6TUvy73w=
github.com/minio/minio-go/v7 v7.4.1/go.mod h1:nQnQi7zTfXR4lREtYXZQWqo5aw0Rqv+ZqCGrTORygRk=
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY=
github.com/pb33f/ordered-map/v2 v2.3.1/go.mod h1:qxFQgd0PkVUtOMCkTapqotNgzRhMPL7VvaHKbd1HnmQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g=
github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
@@ -115,10 +132,17 @@ github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJn
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 h1:uOfcYT+3QungH6tIGSVCR/Y3KJmgJiHcojJbMTPDZAI=
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1/go.mod h1:L1MQhA6x4dn9r007T033lsaZMv9EmBAdXyU/+EF40fo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
@@ -129,9 +153,15 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ=
github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
@@ -148,6 +178,8 @@ go.opentelemetry.io/otel/sdk v1.33.0 h1:iax7M131HuAm9QkZotNHEfstof92xM+N8sr3uHXc
go.opentelemetry.io/otel/sdk v1.33.0/go.mod h1:A1Q5oi7/9XaMlIWzPSxLRWOI8nG3FnzHJNbiENQuihM=
go.opentelemetry.io/otel/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s=
go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s=
go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
@@ -205,13 +237,15 @@ google.golang.org/genproto/googleapis/rpc v0.0.0-20240722135656-d784300faade h1:
google.golang.org/genproto/googleapis/rpc v0.0.0-20240722135656-d784300faade/go.mod h1:Ue6ibwXGpU+dqIcODieyLOcgj7z8+IcskoNIgZxtrFY=
google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA=
google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw=
gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
@@ -243,3 +277,5 @@ modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=
rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=
+118
View File
@@ -0,0 +1,118 @@
#!/bin/bash
#
# Purpose : Install Supermarket's server edition on this machine: one team,
# signing in, at its own domain, with Postgres and Caddy (HTTPS),
# all in Docker (compose.server.yaml). Safe to run again: it keeps
# the settings it wrote, and only rebuilds and restarts.
#
# Usage : ./install-server.sh
#
# It asks for the domain, how the certificate is made, and the mail server
# (for invitations and password resets), and makes the secret key and the
# database password. They go in server.env, readable only by you: keep a
# copy of SUPERMARKET_SECRET_KEY somewhere safe, as nothing encrypted in the
# database can be read without it.
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
ENV_FILE=server.env
COMPOSE=(docker compose -f compose.server.yaml --env-file "$ENV_FILE")
if ! command -v docker > /dev/null || ! docker compose version > /dev/null 2>&1; then
echo "Supermarket's server edition needs Docker with the compose plugin."
exit 1
fi
if ! docker info > /dev/null 2>&1; then
echo "Docker isn't running, or you can't use it: start it, or run this as a user in the docker group."
exit 1
fi
ask() { # ask <prompt> [default]
local answer
if [ -n "${2:-}" ]; then
read -r -p "$1 [$2]: " answer
echo "${answer:-$2}"
else
while [ -z "${answer:-}" ]; do read -r -p "$1: " answer; done
echo "$answer"
fi
}
random_hex() { head -c "$1" /dev/urandom | od -An -tx1 | tr -d ' \n'; }
if [ -f "$ENV_FILE" ]; then
echo "Using the settings in $ENV_FILE (delete it to start again)."
else
echo "Supermarket's server edition: a team signs in to it at its own address."
echo
domain=$(ask "The domain people will open (e.g. supermarket.example.com)")
echo
echo "The HTTPS certificate:"
echo " 1) From Let's Encrypt: this server can be reached from the internet on ports 80 and 443 (the usual)"
echo " 2) Caddy's own certificate authority: a private network or VPN (browsers will warn until you trust its root)"
echo " 3) Your own certificate authority's: put cert.pem and key.pem in server/certs/"
tls_choice=$(ask "Which" "1")
tls="" acme=""
case "$tls_choice" in
2) tls="tls internal" ;;
3) tls="tls /certs/cert.pem /certs/key.pem" ;;
*) email=$(ask "An email for Let's Encrypt's notices (or leave empty)" "-")
[ "$email" != "-" ] && acme="email $email" ;;
esac
echo
echo "The mail server Supermarket sends invitations and password resets through,"
echo "as smtp://user:password@host:587 (STARTTLS) or smtps://user:password@host:465."
echo "Write @ in the user name as %40."
mail=$(ask "Mail server")
from=$(ask "Send as" "Supermarket <no-reply@$domain>")
tz=$(ask "Time zone" "$(cat /etc/timezone 2>/dev/null || echo UTC)")
umask 077
cat > "$ENV_FILE" <<EOF
# Supermarket's server edition (install-server.sh). Readable only by you.
SUPERMARKET_DOMAIN=$domain
SUPERMARKET_TLS=$tls
SUPERMARKET_ACME=$acme
SUPERMARKET_MAIL_URL='$mail'
SUPERMARKET_MAIL_FROM='$from'
SUPERMARKET_TZ=$tz
SUPERMARKET_DB_PASSWORD=$(random_hex 24)
# Keep a copy of this key somewhere safe: the keys and tokens in the
# database are encrypted with it, and can't be read without it.
SUPERMARKET_SECRET_KEY=$(random_hex 32)
SUPERMARKET_VERSION=$(git describe --tags --always --dirty 2>/dev/null || echo dev)
EOF
echo
echo "Wrote $ENV_FILE. Keep a copy of its SUPERMARKET_SECRET_KEY somewhere safe."
fi
# The version, from git, each time.
if version=$(git describe --tags --always --dirty 2>/dev/null); then
sed -i "s/^SUPERMARKET_VERSION=.*/SUPERMARKET_VERSION=$version/" "$ENV_FILE"
fi
echo "Building and starting Supermarket, Postgres and Caddy…"
"${COMPOSE[@]}" up -d --build
echo "Waiting for Supermarket to start…"
for _ in $(seq 1 60); do
if "${COMPOSE[@]}" exec -T supermarket wget -q -O /dev/null http://127.0.0.1:8080/healthz 2> /dev/null; then
break
fi
sleep 2
done
domain=$(grep '^SUPERMARKET_DOMAIN=' "$ENV_FILE" | cut -d= -f2-)
if link=$("${COMPOSE[@]}" exec -T supermarket supermarket setup-link 2> /dev/null | tail -1) && [[ "$link" == https://* ]]; then
echo
echo "Supermarket is running. To create its owner, open this link (it works once, for a day):"
echo " $link"
else
echo
echo "Supermarket is running at https://$domain"
fi
echo
echo "Its logs: docker compose -f compose.server.yaml --env-file $ENV_FILE logs -f supermarket"
echo "Its settings: docker compose -f compose.server.yaml --env-file $ENV_FILE exec supermarket supermarket config"
echo "To update: git pull && ./install-server.sh"
-309
View File
@@ -1,309 +0,0 @@
// Package reddit talks to Reddit's API: the signed-in user, submitting
// posts, a subreddit's rules, and the account's recent posts (for the
// posting-too-often warnings).
package reddit
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// Hosts. Authenticated calls go to oauth.reddit.com.
const (
apiBase = "https://oauth.reddit.com"
// TitleLimit and BodyLimit are Reddit's limits for a post.
TitleLimit = 300
BodyLimit = 40000
)
// TokenRefresher gets a new access token after a 401.
type TokenRefresher func(ctx context.Context) (string, error)
// Client calls Reddit as one user (or as the app, for reading).
type Client struct {
token string
userAgent string
refresh TokenRefresher
http *http.Client
base string // for tests
}
// New returns a client. Reddit asks every client for a unique User-Agent;
// see UserAgent.
func New(accessToken, userAgent string, refresh TokenRefresher) *Client {
return &Client{token: accessToken, userAgent: userAgent, refresh: refresh,
http: &http.Client{Timeout: 20 * time.Second}, base: apiBase}
}
// UserAgent is the User-Agent Reddit's rules ask for.
func UserAgent(version, username string) string {
ua := "web:supermarket:" + version
if username != "" {
ua += " (by /u/" + username + ")"
}
return ua
}
// ErrUnauthorized means the token was refused even after a refresh.
var ErrUnauthorized = errors.New("Reddit refused the sign-in: connect Reddit again under Settings → Social accounts")
// ErrNotFound and ErrForbidden are what Reddit answers for a subreddit or
// user that doesn't exist (or was banned), and for a private one.
var (
ErrNotFound = errors.New("Reddit said 404: no such subreddit or user")
ErrForbidden = errors.New("Reddit said 403 Forbidden: the subreddit may be private, or the account banned from it")
)
func (c *Client) do(ctx context.Context, method, path string, form url.Values, out any) error {
for attempt := 0; ; attempt++ {
var body io.Reader
if form != nil {
body = strings.NewReader(form.Encode())
}
req, err := http.NewRequestWithContext(ctx, method, c.base+path, body)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("User-Agent", c.userAgent)
if form != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
res, err := c.http.Do(req)
if err != nil {
return err
}
raw, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20))
res.Body.Close()
if res.StatusCode == http.StatusUnauthorized && attempt == 0 && c.refresh != nil {
tok, err := c.refresh(ctx)
if err != nil {
return fmt.Errorf("%w (%v)", ErrUnauthorized, err)
}
c.token = tok
continue
}
switch {
case res.StatusCode == http.StatusUnauthorized:
return ErrUnauthorized
case res.StatusCode == http.StatusForbidden:
return ErrForbidden
case res.StatusCode == http.StatusNotFound:
return ErrNotFound
case res.StatusCode == http.StatusTooManyRequests:
return fmt.Errorf("Reddit is rate-limiting this app; try again in a few minutes")
case res.StatusCode != http.StatusOK:
return fmt.Errorf("reddit HTTP %d: %.300s", res.StatusCode, raw)
}
if out == nil {
return nil
}
return json.Unmarshal(raw, out)
}
}
// Me returns the signed-in user's name.
func (c *Client) Me(ctx context.Context) (string, error) {
var me struct {
Name string `json:"name"`
}
if err := c.do(ctx, http.MethodGet, "/api/v1/me", nil, &me); err != nil {
return "", err
}
if me.Name == "" {
return "", errors.New("Reddit didn't say who is signed in")
}
return me.Name, nil
}
// Post is a submission.
type Post struct {
Subreddit string
Title string
Text string // a text ("self") post's body
URL string // set for a link post; then Text is ignored
}
// Submit posts to a subreddit and returns the post's URL.
func (c *Client) Submit(ctx context.Context, p Post) (string, error) {
form := url.Values{
"api_type": {"json"},
"sr": {p.Subreddit},
"title": {p.Title},
"resubmit": {"true"},
"sendreplies": {"true"},
}
if p.URL != "" {
form.Set("kind", "link")
form.Set("url", p.URL)
} else {
form.Set("kind", "self")
form.Set("text", p.Text)
}
var out struct {
JSON struct {
Errors [][]any `json:"errors"`
Data struct {
URL string `json:"url"`
} `json:"data"`
} `json:"json"`
}
if err := c.do(ctx, http.MethodPost, "/api/submit", form, &out); err != nil {
return "", err
}
if len(out.JSON.Errors) > 0 {
var msgs []string
for _, e := range out.JSON.Errors {
// Each error is [code, message, field].
if len(e) > 1 {
msgs = append(msgs, fmt.Sprint(e[1]))
} else if len(e) > 0 {
msgs = append(msgs, fmt.Sprint(e[0]))
}
}
return "", fmt.Errorf("Reddit refused the post: %s", strings.Join(msgs, "; "))
}
if out.JSON.Data.URL == "" {
return "", errors.New("Reddit accepted the post but didn't return its address")
}
return out.JSON.Data.URL, nil
}
// Rule is one of a subreddit's rules.
type Rule struct {
Name string `json:"name"`
Description string `json:"description"`
Kind string `json:"kind"` // link, comment, all
}
// Subreddit is what the app shows and tells the model about a subreddit.
type Subreddit struct {
Name string `json:"name"`
Title string `json:"title"`
Description string `json:"description"` // public description
SubmitText string `json:"submit_text"` // posting guidelines shown when posting
SubmissionType string `json:"submission_type"` // any, link, self
Type string `json:"type"` // public, restricted, private
Over18 bool `json:"over18"`
Subscribers int `json:"subscribers"`
Rules []Rule `json:"rules"`
FetchedAt time.Time `json:"fetched_at"`
}
// AllowsText reports whether text posts are allowed.
func (s *Subreddit) AllowsText() bool { return s.SubmissionType != "link" }
// AllowsLinks reports whether link posts are allowed.
func (s *Subreddit) AllowsLinks() bool { return s.SubmissionType != "self" }
// SubredditInfo fetches a subreddit's description, guidelines and rules.
func (c *Client) SubredditInfo(ctx context.Context, name string) (*Subreddit, error) {
name = CleanName(name)
var about struct {
Data struct {
DisplayName string `json:"display_name"`
Title string `json:"title"`
PublicDescription string `json:"public_description"`
SubmitText string `json:"submit_text"`
SubmissionType string `json:"submission_type"`
SubredditType string `json:"subreddit_type"`
Over18 bool `json:"over18"`
Subscribers int `json:"subscribers"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/r/"+url.PathEscape(name)+"/about", nil, &about); err != nil {
return nil, err
}
if about.Data.DisplayName == "" {
// Reddit sometimes answers a missing subreddit with an empty listing
// rather than a 404.
return nil, ErrNotFound
}
var rules struct {
Rules []struct {
ShortName string `json:"short_name"`
Description string `json:"description"`
Kind string `json:"kind"`
} `json:"rules"`
}
if err := c.do(ctx, http.MethodGet, "/r/"+url.PathEscape(name)+"/about/rules", nil, &rules); err != nil {
return nil, err
}
d := about.Data
s := &Subreddit{Name: firstNonEmpty(d.DisplayName, name), Title: d.Title, Description: d.PublicDescription,
SubmitText: d.SubmitText, SubmissionType: firstNonEmpty(d.SubmissionType, "any"), Type: d.SubredditType,
Over18: d.Over18, Subscribers: d.Subscribers, FetchedAt: time.Now().UTC()}
for _, r := range rules.Rules {
s.Rules = append(s.Rules, Rule{Name: r.ShortName, Description: r.Description, Kind: r.Kind})
}
return s, nil
}
// Submission is one of the account's past posts.
type Submission struct {
Subreddit string
Title string
URL string // the link, for link posts
Text string
IsSelf bool
Created time.Time
}
// Submitted returns the user's recent posts, newest first (up to 100).
func (c *Client) Submitted(ctx context.Context, username string) ([]Submission, error) {
var out struct {
Data struct {
Children []struct {
Data struct {
Subreddit string `json:"subreddit"`
Title string `json:"title"`
URL string `json:"url"`
Selftext string `json:"selftext"`
IsSelf bool `json:"is_self"`
CreatedUTC float64 `json:"created_utc"`
} `json:"data"`
} `json:"children"`
} `json:"data"`
}
path := "/user/" + url.PathEscape(username) + "/submitted?limit=100&sort=new&raw_json=1"
if err := c.do(ctx, http.MethodGet, path, nil, &out); err != nil {
return nil, err
}
var subs []Submission
for _, ch := range out.Data.Children {
d := ch.Data
subs = append(subs, Submission{Subreddit: d.Subreddit, Title: d.Title, URL: d.URL, Text: d.Selftext,
IsSelf: d.IsSelf, Created: time.Unix(int64(d.CreatedUTC), 0).UTC()})
}
return subs, nil
}
// CleanName turns "r/selfhosted", "/r/selfhosted/" or a subreddit URL into
// "selfhosted".
func CleanName(s string) string {
s = strings.TrimSpace(s)
if i := strings.Index(s, "/r/"); i >= 0 {
s = s[i+3:]
}
s = strings.TrimPrefix(s, "r/")
if i := strings.IndexAny(s, "/?#"); i >= 0 {
s = s[:i]
}
return s
}
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if v != "" {
return v
}
}
return ""
}
-85
View File
@@ -1,85 +0,0 @@
package reddit
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestClient(t *testing.T) {
var submitted string
refreshed := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-Agent") != "web:supermarket:test (by /u/pat)" {
t.Errorf("User-Agent = %q", r.Header.Get("User-Agent"))
}
if r.Header.Get("Authorization") == "Bearer old" {
w.WriteHeader(http.StatusUnauthorized)
return
}
switch r.URL.Path {
case "/api/v1/me":
w.Write([]byte(`{"name":"pat"}`))
case "/api/submit":
r.ParseForm()
submitted = r.PostForm.Encode()
if r.PostForm.Get("sr") == "strict" {
w.Write([]byte(`{"json":{"errors":[["SUBREDDIT_NOTALLOWED","you aren't allowed to post there.","sr"]]}}`))
return
}
w.Write([]byte(`{"json":{"errors":[],"data":{"url":"https://www.reddit.com/r/selfhosted/comments/abc/hi/"}}}`))
case "/r/selfhosted/about":
w.Write([]byte(`{"data":{"display_name":"selfhosted","public_description":"Self-hosting","submit_text":"No spam.","submission_type":"self","subreddit_type":"public","subscribers":500000}}`))
case "/r/selfhosted/about/rules":
w.Write([]byte(`{"rules":[{"short_name":"No self-promotion","description":"Limit it to 10%.","kind":"link"}]}`))
case "/user/pat/submitted":
w.Write([]byte(`{"data":{"children":[{"data":{"subreddit":"selfhosted","title":"T","url":"https://acme.example/x","is_self":false,"created_utc":1794000000}}]}}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
c := New("old", UserAgent("test", "pat"), func(context.Context) (string, error) {
refreshed++
return "new", nil
})
c.base = srv.URL
ctx := context.Background()
if name, err := c.Me(ctx); err != nil || name != "pat" || refreshed != 1 {
t.Fatalf("Me = %q, %v (refreshed %d)", name, err, refreshed)
}
u, err := c.Submit(ctx, Post{Subreddit: "selfhosted", Title: "Hi", Text: "Body"})
if err != nil || !strings.Contains(u, "/comments/abc/") || !strings.Contains(submitted, "kind=self") || !strings.Contains(submitted, "text=Body") {
t.Errorf("Submit = %q, %v; sent %s", u, err, submitted)
}
if _, err := c.Submit(ctx, Post{Subreddit: "selfhosted", Title: "Hi", URL: "https://acme.example"}); err != nil || !strings.Contains(submitted, "kind=link") {
t.Errorf("link post sent %s (%v)", submitted, err)
}
if _, err := c.Submit(ctx, Post{Subreddit: "strict", Title: "Hi", Text: "x"}); err == nil || !strings.Contains(err.Error(), "aren't allowed") {
t.Errorf("refused submit: %v", err)
}
s, err := c.SubredditInfo(ctx, "/r/selfhosted/")
if err != nil || s.SubmitText != "No spam." || len(s.Rules) != 1 || s.Rules[0].Name != "No self-promotion" || s.AllowsLinks() || !s.AllowsText() {
t.Errorf("SubredditInfo = %+v, %v", s, err)
}
subs, err := c.Submitted(ctx, "pat")
if err != nil || len(subs) != 1 || subs[0].Subreddit != "selfhosted" || subs[0].Created.Year() != 2026 {
t.Errorf("Submitted = %+v, %v", subs, err)
}
if _, err := c.SubredditInfo(ctx, "nope"); err == nil {
t.Error("expected 404")
}
}
func TestCleanName(t *testing.T) {
for in, want := range map[string]string{"selfhosted": "selfhosted", "r/selfhosted": "selfhosted", "/r/selfhosted/": "selfhosted",
"https://www.reddit.com/r/homelab/top?t=week": "homelab", " r/Go ": "Go"} {
if got := CleanName(in); got != want {
t.Errorf("CleanName(%q) = %q, want %q", in, got, want)
}
}
}
+2 -1
View File
@@ -227,7 +227,8 @@ var EventTypes = []string{
"customer.created", "customer.updated", "customer.deleted",
"invoice.created", "invoice.finalized", "invoice.updated", "invoice.paid", "invoice.voided", "invoice.marked_uncollectible",
"credit_note.created", "credit_note.updated", "credit_note.voided",
"refund.created", "refund.updated", "charge.refunded",
"refund.created", "refund.updated",
"charge.succeeded", "charge.captured", "charge.updated", "charge.refunded", "charge.failed",
}
// Event is one change, with the object as it was after it.
+173
View File
@@ -0,0 +1,173 @@
// Package appmail sends the app's own mail on the server editions:
// invitations, password-reset links, and notices about someone's account.
// It goes through the mail server in SUPERMARKET_MAIL_URL, not the
// outreach mailbox a team sets up under Settings → Email.
package appmail
import (
"bytes"
"context"
"crypto/rand"
"crypto/tls"
"encoding/hex"
"errors"
"fmt"
"mime"
"mime/quotedprintable"
"net"
"net/mail"
"net/smtp"
"strings"
"sync"
"time"
"supermarket/internal/config"
)
// Message is a plain-text email to one person.
type Message struct {
To string // an address
ToName string
Subject string
Body string
}
// Sender sends messages.
type Sender interface {
Send(ctx context.Context, m Message) error
}
// SMTP sends through a mail server.
type SMTP struct {
Conf *config.Mail
}
// Send hands one message to the mail server.
func (s *SMTP) Send(ctx context.Context, m Message) error {
from, err := mail.ParseAddress(s.Conf.From)
if err != nil {
return err
}
raw, err := compose(from, m, time.Now())
if err != nil {
return err
}
host, _, err := net.SplitHostPort(s.Conf.Host)
if err != nil {
return err
}
dialer := &net.Dialer{Timeout: 30 * time.Second}
tlsConf := &tls.Config{ServerName: host}
var conn net.Conn
if s.Conf.TLS {
conn, err = (&tls.Dialer{NetDialer: dialer, Config: tlsConf}).DialContext(ctx, "tcp", s.Conf.Host)
} else {
conn, err = dialer.DialContext(ctx, "tcp", s.Conf.Host)
}
if err != nil {
return fmt.Errorf("connecting to %s: %w", s.Conf.Host, err)
}
_ = conn.SetDeadline(time.Now().Add(time.Minute))
c, err := smtp.NewClient(conn, host)
if err != nil {
conn.Close()
return err
}
defer c.Close()
if !s.Conf.TLS {
ok, _ := c.Extension("STARTTLS")
if !ok {
return fmt.Errorf("%s doesn't offer STARTTLS: use smtps:// (port 465) or a server that does", s.Conf.Host)
}
if err := c.StartTLS(tlsConf); err != nil {
return fmt.Errorf("starting TLS with %s: %w", s.Conf.Host, err)
}
}
if s.Conf.User != "" {
if err := c.Auth(smtp.PlainAuth("", s.Conf.User, s.Conf.Password, host)); err != nil {
return fmt.Errorf("signing in to %s: %w", s.Conf.Host, err)
}
}
if err := c.Mail(from.Address); err != nil {
return err
}
if err := c.Rcpt(m.To); err != nil {
return fmt.Errorf("the mail server refused %s: %w", m.To, err)
}
w, err := c.Data()
if err != nil {
return err
}
if _, err := w.Write(raw); err != nil {
return err
}
if err := w.Close(); err != nil {
return err
}
return c.Quit()
}
func compose(from *mail.Address, m Message, now time.Time) ([]byte, error) {
to, err := mail.ParseAddress(m.To)
if err != nil {
return nil, err
}
to.Name = m.ToName
if strings.ContainsAny(m.Subject, "\r\n") {
return nil, errors.New("a subject has one line")
}
id := make([]byte, 12)
_, _ = rand.Read(id)
domain := from.Address[strings.LastIndex(from.Address, "@")+1:]
var b bytes.Buffer
h := func(k, v string) { b.WriteString(k + ": " + v + "\r\n") }
h("From", from.String())
h("To", to.String())
h("Subject", mime.QEncoding.Encode("utf-8", m.Subject))
h("Date", now.Format(time.RFC1123Z))
h("Message-ID", "<"+hex.EncodeToString(id)+"@"+domain+">")
h("Auto-Submitted", "auto-generated")
h("MIME-Version", "1.0")
h("Content-Type", "text/plain; charset=utf-8")
h("Content-Transfer-Encoding", "quoted-printable")
b.WriteString("\r\n")
text := strings.ReplaceAll(strings.ReplaceAll(strings.TrimSpace(m.Body), "\r\n", "\n"), "\n", "\r\n") + "\r\n"
qp := quotedprintable.NewWriter(&b)
_, _ = qp.Write([]byte(text))
_ = qp.Close()
return b.Bytes(), nil
}
// Outbox keeps messages instead of sending them: for tests.
type Outbox struct {
mu sync.Mutex
Sent []Message
}
// Send keeps the message.
func (o *Outbox) Send(_ context.Context, m Message) error {
o.mu.Lock()
defer o.mu.Unlock()
o.Sent = append(o.Sent, m)
return nil
}
// Last is the last message sent to an address, or nil.
func (o *Outbox) Last(to string) *Message {
o.mu.Lock()
defer o.mu.Unlock()
for i := len(o.Sent) - 1; i >= 0; i-- {
if strings.EqualFold(o.Sent[i].To, to) {
m := o.Sent[i]
return &m
}
}
return nil
}
// Count is how many messages were sent.
func (o *Outbox) Count() int {
o.mu.Lock()
defer o.mu.Unlock()
return len(o.Sent)
}
+262
View File
@@ -0,0 +1,262 @@
// Package approvals holds what agents ask to send out of Supermarket (a
// post, an email, a mailing-list add, a change to a site) until a person
// says yes or no, and the kinds of action a person has let an agent take
// on its own, each with a cap per day.
package approvals
import (
"database/sql"
"encoding/json"
"errors"
"time"
"supermarket/internal/db"
)
// Statuses.
const (
Waiting = "waiting"
Done = "done" // approved and carried out (or done on its own)
Refused = "refused"
Failed = "failed" // approved, but carrying it out failed
)
// Request is something an agent asked to do.
type Request struct {
ID int64
Agent int64
Class string
Module string
Target int64
Params map[string]string
Summary string
Status string
Created time.Time
Decided time.Time
DecidedBy int64 // 0 with Done: on its own
Result string
}
// OnItsOwn says whether the agent did it without asking.
func (r *Request) OnItsOwn() bool {
return r.Status != Waiting && r.Status != Refused && r.DecidedBy == 0
}
// Grant lets an agent take a class of action on its own.
type Grant struct {
Agent int64
Class string
Label string
Module string
DailyCap int // 0: none
GrantedBy int64
Granted time.Time
}
const timeFormat = "2006-01-02T15:04:05.000Z"
func ts(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format(timeFormat)
}
func parseTS(s string) time.Time {
t, _ := time.Parse(timeFormat, s)
return t
}
var ErrNotFound = errors.New("no such request")
// ErrDecided is a request someone has already decided.
var ErrDecided = errors.New("this request was already decided")
// Add records a request, waiting (or, done on its own, with its result).
func Add(d *db.DB, r *Request, now time.Time) error {
params, _ := json.Marshal(r.Params)
if r.Status == "" {
r.Status = Waiting
}
r.Created = now
decided := ""
if r.Status != Waiting {
r.Decided = now
decided = ts(now)
}
var err error
r.ID, err = d.Insert(`INSERT INTO approvals (agent_id, class, module, target_id, params, summary, status, created_at, decided_at, decided_by, result)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, r.Agent, r.Class, r.Module, r.Target, string(params), r.Summary, r.Status, ts(now), decided, r.DecidedBy, r.Result)
return err
}
const cols = `id, agent_id, class, module, target_id, params, summary, status, created_at, decided_at, decided_by, result`
func scan(row interface{ Scan(...any) error }) (*Request, error) {
var r Request
var params, created, decided string
if err := row.Scan(&r.ID, &r.Agent, &r.Class, &r.Module, &r.Target, &params, &r.Summary, &r.Status, &created, &decided, &r.DecidedBy, &r.Result); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
_ = json.Unmarshal([]byte(params), &r.Params)
if r.Params == nil {
r.Params = map[string]string{}
}
r.Created, r.Decided = parseTS(created), parseTS(decided)
return &r, nil
}
// Get finds a request.
func Get(d *db.DB, id int64) (*Request, error) {
return scan(d.QueryRow(`SELECT `+cols+` FROM approvals WHERE id = ?`, id))
}
// List are requests with a status (all, if ""), newest first; agent 0 for
// every agent's.
func List(d *db.DB, status string, agent int64, limit int) ([]Request, error) {
q := `SELECT ` + cols + ` FROM approvals WHERE 1 = 1`
var args []any
if status != "" {
q += ` AND status = ?`
args = append(args, status)
}
if agent != 0 {
q += ` AND agent_id = ?`
args = append(args, agent)
}
q += ` ORDER BY id DESC LIMIT ?`
args = append(args, limit)
rows, err := d.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Request
for rows.Next() {
r, err := scan(rows)
if err != nil {
return nil, err
}
out = append(out, *r)
}
return out, rows.Err()
}
// Claim takes a waiting request for a decision, once: of two people
// deciding together, one gets ErrDecided.
func Claim(d *db.DB, id, by int64, status string, now time.Time) error {
res, err := d.Exec(`UPDATE approvals SET status = ?, decided_at = ?, decided_by = ? WHERE id = ? AND status = ?`,
status, ts(now), by, id, Waiting)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n != 1 {
return ErrDecided
}
return nil
}
// Finish records how carrying out an approved request went.
func Finish(d *db.DB, id int64, failed error) error {
status, result := Done, ""
if failed != nil {
status, result = Failed, failed.Error()
}
_, err := d.Exec(`UPDATE approvals SET status = ?, result = ? WHERE id = ?`, status, result, id)
return err
}
// SetResult notes what a done request led to (a post's address).
func SetResult(d *db.DB, id int64, result string) error {
_, err := d.Exec(`UPDATE approvals SET result = ? WHERE id = ?`, result, id)
return err
}
// Pending says whether there's already a waiting request for the same
// class and target: asking twice doesn't make two.
func Pending(d *db.DB, class string, target int64) (*Request, error) {
r, err := scan(d.QueryRow(`SELECT `+cols+` FROM approvals WHERE class = ? AND target_id = ? AND status = ? ORDER BY id LIMIT 1`, class, target, Waiting))
if errors.Is(err, ErrNotFound) {
return nil, nil
}
return r, err
}
// Grants.
// Allow lets an agent take a class of action on its own (or changes its cap).
func Allow(d *db.DB, g Grant, now time.Time) error {
_, err := d.Exec(`INSERT INTO agent_autonomy (agent_id, class, label, module, daily_cap, granted_by, granted_at) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (agent_id, class) DO UPDATE SET daily_cap = excluded.daily_cap, label = excluded.label, granted_by = excluded.granted_by, granted_at = excluded.granted_at`,
g.Agent, g.Class, g.Label, g.Module, g.DailyCap, g.GrantedBy, ts(now))
return err
}
// Withdraw takes a class back.
func Withdraw(d *db.DB, agent int64, class string) error {
_, err := d.Exec(`DELETE FROM agent_autonomy WHERE agent_id = ? AND class = ?`, agent, class)
return err
}
// WithdrawAll takes everything back from an agent (its key leaked).
func WithdrawAll(d *db.DB, agent int64) error {
_, err := d.Exec(`DELETE FROM agent_autonomy WHERE agent_id = ?`, agent)
return err
}
// Grants are what agents may do on their own: agent 0 for all.
func Grants(d *db.DB, agent int64) ([]Grant, error) {
q := `SELECT agent_id, class, label, module, daily_cap, granted_by, granted_at FROM agent_autonomy`
var args []any
if agent != 0 {
q += ` WHERE agent_id = ?`
args = append(args, agent)
}
rows, err := d.Query(q+` ORDER BY agent_id, class`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Grant
for rows.Next() {
var g Grant
var at string
if err := rows.Scan(&g.Agent, &g.Class, &g.Label, &g.Module, &g.DailyCap, &g.GrantedBy, &at); err != nil {
return nil, err
}
g.Granted = parseTS(at)
out = append(out, g)
}
return out, rows.Err()
}
// Allowed says whether an agent may take a class of action on its own
// now: it was granted, and today's count is under the cap.
func Allowed(d *db.DB, agent int64, class string, now time.Time) (bool, error) {
var cap int
err := d.QueryRow(`SELECT daily_cap FROM agent_autonomy WHERE agent_id = ? AND class = ?`, agent, class).Scan(&cap)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
if err != nil {
return false, err
}
if cap == 0 {
return true, nil
}
var n int
err = d.QueryRow(`SELECT count(*) FROM approvals WHERE agent_id = ? AND class = ? AND decided_by = 0 AND status IN (?, ?) AND decided_at >= ?`,
agent, class, Done, Failed, ts(now.Add(-24*time.Hour))).Scan(&n)
return n < cap, err
}
// AskedSince counts what an agent asked to send out since a time, approved
// or not: its cap per day.
func AskedSince(d *db.DB, agent int64, since time.Time) (int, error) {
var n int
err := d.QueryRow(`SELECT count(*) FROM approvals WHERE agent_id = ? AND created_at >= ?`, agent, ts(since)).Scan(&n)
return n, err
}
+65
View File
@@ -0,0 +1,65 @@
package approvals
import (
"errors"
"path/filepath"
"testing"
"time"
"supermarket/internal/db"
)
func TestRequestsAndGrants(t *testing.T) {
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
defer d.Close()
now := time.Now()
r := &Request{Agent: 5, Class: "post:2", Module: "content", Target: 11, Params: map[string]string{"at": "x"}, Summary: "Publish draft 11"}
if err := Add(d, r, now); err != nil {
t.Fatal(err)
}
if p, _ := Pending(d, "post:2", 11); p == nil || p.ID != r.ID {
t.Error("not pending")
}
if err := Claim(d, r.ID, 1, Done, now); err != nil {
t.Fatal(err)
}
if err := Claim(d, r.ID, 2, Refused, now); !errors.Is(err, ErrDecided) {
t.Errorf("decided twice: %v", err)
}
Finish(d, r.ID, errors.New("X said no"))
got, _ := Get(d, r.ID)
if got.Status != Failed || got.Result != "X said no" || got.DecidedBy != 1 || got.Params["at"] != "x" || got.OnItsOwn() {
t.Errorf("%+v", got)
}
if list, _ := List(d, Waiting, 0, 10); len(list) != 0 {
t.Error("still waiting")
}
// On its own, with a cap of 2 a day.
if ok, _ := Allowed(d, 5, "email-first", now); ok {
t.Error("allowed without a grant")
}
Allow(d, Grant{Agent: 5, Class: "email-first", Label: "send a first email", Module: "prospects", DailyCap: 2, GrantedBy: 1}, now)
for i := 0; i < 2; i++ {
if ok, _ := Allowed(d, 5, "email-first", now); !ok {
t.Fatalf("call %d refused", i)
}
Add(d, &Request{Agent: 5, Class: "email-first", Module: "prospects", Target: int64(i), Summary: "x", Status: Done}, now)
}
if ok, _ := Allowed(d, 5, "email-first", now); ok {
t.Error("over the cap")
}
if ok, _ := Allowed(d, 5, "email-first", now.Add(25*time.Hour)); !ok {
t.Error("the cap is per day")
}
if gs, _ := Grants(d, 5); len(gs) != 1 || gs[0].DailyCap != 2 {
t.Errorf("grants %+v", gs)
}
WithdrawAll(d, 5)
if ok, _ := Allowed(d, 5, "email-first", now.Add(25*time.Hour)); ok {
t.Error("withdrawn")
}
}
+117
View File
@@ -0,0 +1,117 @@
// Package audit is the record of who did what: sign-ins, invitations and
// roles, connections, everything sent or published, and deletions. Admins
// read it under Settings → Activity.
package audit
import (
"strings"
"time"
"supermarket/internal/db"
)
// Entry is one thing someone did.
type Entry struct {
ID int64
At time.Time
UserID int64 // 0: Supermarket itself, or the local edition's owner
UserName string // as they were called then
Kind string // person, agent or system
Action string
Target string
Detail string
IP string
}
// Kinds of actor.
const (
Person = "person"
Agent = "agent"
System = "system"
)
const timeFormat = "2006-01-02T15:04:05.000Z"
// Record adds an entry. Long fields are cut short.
func Record(d *db.DB, e Entry) error {
if e.At.IsZero() {
e.At = time.Now()
}
if e.Kind == "" {
e.Kind = Person
}
_, err := d.Exec(`INSERT INTO audit_log (at, user_id, user_name, kind, action, target, detail, ip) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
e.At.UTC().Format(timeFormat), e.UserID, cut(e.UserName, 200), e.Kind, cut(e.Action, 100), cut(e.Target, 500), cut(e.Detail, 2000), cut(e.IP, 64))
return err
}
func cut(s string, n int) string {
if r := []rune(s); len(r) > n {
return string(r[:n-1]) + "…"
}
return s
}
// Filter narrows the list.
type Filter struct {
UserID int64 // 0: everyone
Action string // a prefix: "signin" matches signin and signin-failed
Text string // in the target or detail
Before int64 // entries older than this ID (paging); 0: the newest
}
// List is the newest entries first.
func List(d *db.DB, f Filter, limit int) ([]Entry, error) {
q := `SELECT id, at, user_id, user_name, kind, action, target, detail, ip FROM audit_log WHERE 1 = 1`
var args []any
if f.UserID != 0 {
q += ` AND user_id = ?`
args = append(args, f.UserID)
}
if f.Action != "" {
q += ` AND action LIKE ?`
args = append(args, escapeLike(f.Action)+"%")
}
if t := strings.TrimSpace(f.Text); t != "" {
q += ` AND (target LIKE ? OR detail LIKE ? OR user_name LIKE ?)`
like := "%" + escapeLike(t) + "%"
args = append(args, like, like, like)
}
if f.Before != 0 {
q += ` AND id < ?`
args = append(args, f.Before)
}
q += ` ORDER BY id DESC LIMIT ?`
args = append(args, limit)
rows, err := d.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Entry
for rows.Next() {
var e Entry
var at string
if err := rows.Scan(&e.ID, &at, &e.UserID, &e.UserName, &e.Kind, &e.Action, &e.Target, &e.Detail, &e.IP); err != nil {
return nil, err
}
e.At, _ = time.Parse(timeFormat, at)
out = append(out, e)
}
return out, rows.Err()
}
// escapeLike makes % and _ match themselves (with ESCAPE-less LIKE, by
// dropping them: a search for them finds nothing special).
func escapeLike(s string) string {
return strings.NewReplacer("%", "", "_", "").Replace(s)
}
// Prune deletes entries older than keep.
func Prune(d *db.DB, keep time.Duration, now time.Time) (int64, error) {
res, err := d.Exec(`DELETE FROM audit_log WHERE at < ?`, now.Add(-keep).UTC().Format(timeFormat))
if err != nil {
return 0, err
}
return res.RowsAffected()
}
+49
View File
@@ -0,0 +1,49 @@
package audit
import (
"path/filepath"
"testing"
"time"
"supermarket/internal/db"
)
func TestRecordAndList(t *testing.T) {
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
defer d.Close()
now := time.Now()
for _, e := range []Entry{
{At: now.Add(-400 * 24 * time.Hour), UserID: 1, UserName: "Olu", Action: "signin"},
{At: now.Add(-time.Hour), UserID: 1, UserName: "Olu", Action: "signin", IP: "203.0.113.1"},
{At: now.Add(-30 * time.Minute), UserID: 2, UserName: "Sam", Action: "signin-failed", Target: "sam@example.com"},
{At: now, UserID: 1, UserName: "Olu", Action: "invited", Target: "sam@example.com", Detail: "Member: SEO"},
{At: now, Kind: System, Action: "published", Target: "X @acme"},
} {
if err := Record(d, e); err != nil {
t.Fatal(err)
}
}
all, _ := List(d, Filter{}, 10)
if len(all) != 5 || all[0].Action != "published" || all[0].Kind != System || all[4].Kind != Person {
t.Fatalf("all: %+v", all)
}
if l, _ := List(d, Filter{Action: "signin"}, 10); len(l) != 3 {
t.Errorf("signin*: %d", len(l))
}
if l, _ := List(d, Filter{UserID: 2}, 10); len(l) != 1 {
t.Errorf("Sam: %d", len(l))
}
if l, _ := List(d, Filter{Text: "SAM@"}, 10); len(l) != 2 {
t.Errorf("text: %d", len(l))
}
page2, _ := List(d, Filter{Before: all[1].ID}, 2)
if len(page2) != 2 || page2[0].ID != all[2].ID {
t.Errorf("paging: %+v", page2)
}
if n, _ := Prune(d, 365*24*time.Hour, now); n != 1 {
t.Errorf("pruned %d", n)
}
}
+158
View File
@@ -0,0 +1,158 @@
package billing
import (
"database/sql"
"errors"
"time"
"supermarket/internal/db"
)
// Subscription statuses, as Stripe's (and free: no subscription).
const (
Trialing = "trialing"
Active = "active"
PastDue = "past_due"
Canceled = "canceled"
Free = "free"
)
// How long a lapse lasts before what.
const (
ReadOnlyAfter = 14 * 24 * time.Hour // past due this long: read-only
DeleteAfter = 60 * 24 * time.Hour // past due this long: deleted (Phase 13, part 8)
)
// Account is a team's billing.
type Account struct {
Team int64
Plan string
Status string
TrialEnds time.Time
Customer string
Subscription string
Seats int
StorageBlocks int
PeriodEnd time.Time
PastDueSince time.Time
KeptMember int64
StorageUsed int64
Warned string
Updated time.Time
}
const timeFormat = "2006-01-02T15:04:05.000Z"
func ts(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format(timeFormat)
}
func parseTS(s string) time.Time {
t, _ := time.Parse(timeFormat, s)
return t
}
const cols = `team_id, plan, status, trial_ends, customer, subscription, seats, storage_blocks, period_end, past_due_since, kept_member, storage_used, warned, updated_at`
func scan(row interface{ Scan(...any) error }) (*Account, error) {
var a Account
var trial, period, pastDue, updated string
err := row.Scan(&a.Team, &a.Plan, &a.Status, &trial, &a.Customer, &a.Subscription, &a.Seats, &a.StorageBlocks, &period, &pastDue, &a.KeptMember, &a.StorageUsed, &a.Warned, &updated)
if err != nil {
return nil, err
}
a.TrialEnds, a.PeriodEnd, a.PastDueSince, a.Updated = parseTS(trial), parseTS(period), parseTS(pastDue), parseTS(updated)
return &a, nil
}
// StartTrial gives a new team its trial of the paid plan.
func StartTrial(d *db.DB, team int64, p *Plans, now time.Time) error {
_, err := d.Exec(`INSERT INTO billing (team_id, plan, status, trial_ends, updated_at) VALUES (?, ?, ?, ?, ?)
ON CONFLICT (team_id) DO NOTHING`, team, p.Paid, Trialing, ts(now.Add(time.Duration(p.TrialDays)*24*time.Hour)), ts(now))
return err
}
// Get is a team's account; a team with none (made before billing) is on
// the free plan.
func Get(d *db.DB, team int64) (*Account, error) {
a, err := scan(d.QueryRow(`SELECT `+cols+` FROM billing WHERE team_id = ?`, team))
if errors.Is(err, sql.ErrNoRows) {
return &Account{Team: team, Plan: "", Status: Free}, nil
}
return a, err
}
// All are every team's accounts.
func All(d *db.DB) ([]*Account, error) {
rows, err := d.Query(`SELECT ` + cols + ` FROM billing ORDER BY team_id`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Account
for rows.Next() {
a, err := scan(rows)
if err != nil {
return nil, err
}
out = append(out, a)
}
return out, rows.Err()
}
// Save writes an account.
func Save(d *db.DB, a *Account, now time.Time) error {
a.Updated = now
_, err := d.Exec(`INSERT INTO billing (`+cols+`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (team_id) DO UPDATE SET plan = excluded.plan, status = excluded.status, trial_ends = excluded.trial_ends,
customer = excluded.customer, subscription = excluded.subscription, seats = excluded.seats, storage_blocks = excluded.storage_blocks,
period_end = excluded.period_end, past_due_since = excluded.past_due_since, kept_member = excluded.kept_member,
storage_used = excluded.storage_used, warned = excluded.warned, updated_at = excluded.updated_at`,
a.Team, a.Plan, a.Status, ts(a.TrialEnds), a.Customer, a.Subscription, a.Seats, a.StorageBlocks, ts(a.PeriodEnd),
ts(a.PastDueSince), a.KeptMember, a.StorageUsed, a.Warned, ts(now))
return err
}
// ByCustomer finds a team's account by its Stripe customer.
func ByCustomer(d *db.DB, customer string) (*Account, error) {
if customer == "" {
return nil, sql.ErrNoRows
}
return scan(d.QueryRow(`SELECT `+cols+` FROM billing WHERE customer = ?`, customer))
}
// Effective is the plan a team has now, and whether it's read-only:
// - a trial before its end, or a subscription active or past due (for
// under ReadOnlyAfter): the plan subscribed to
// - past due longer: the plan, but read-only
// - otherwise (the trial ended, canceled, free): the free plan
func (a *Account) Effective(p *Plans, now time.Time) (plan *Plan, readOnly bool) {
switch a.Status {
case Trialing:
if now.Before(a.TrialEnds) {
return p.Get(a.Plan), false
}
if a.Subscription != "" { // a trial with a subscription behind it: Stripe says when it ends
return p.Get(a.Plan), false
}
case Active:
return p.Get(a.Plan), false
case PastDue:
return p.Get(a.Plan), !a.PastDueSince.IsZero() && now.Sub(a.PastDueSince) >= ReadOnlyAfter
}
return p.Get(p.Free), false
}
// SeenEvent records a Stripe event, and says whether it was new: each is
// handled once, whichever copy of the app it reaches.
func SeenEvent(d *db.DB, id, typ string, now time.Time) (bool, error) {
res, err := d.Exec(`INSERT INTO stripe_events (id, type, received_at) VALUES (?, ?, ?) ON CONFLICT (id) DO NOTHING`, id, typ, ts(now))
if err != nil {
return false, err
}
n, _ := res.RowsAffected()
return n == 1, nil
}
+152
View File
@@ -0,0 +1,152 @@
package billing
import (
"os"
"path/filepath"
"testing"
"time"
"supermarket/internal/db"
)
func TestPlans(t *testing.T) {
p, err := Load("", "price_m", "", "price_b")
if err != nil {
t.Fatal(err)
}
free, paid := p.Get("free"), p.Get("paid")
if !free.Includes("seo") || free.Includes("prospects") || !paid.Includes("prospects") || free.Paid() || !paid.Paid() {
t.Error("modules")
}
if free.Seats != 2 || free.Agents != 1 || paid.Agents != 5 || free.StorageBytes(0, 0) != 1<<30 || paid.StorageBytes(3, 1) != 40<<30 {
t.Errorf("limits %+v %+v", free, paid)
}
if free.CrawlInterval() != 7*24*time.Hour || paid.CrawlInterval() != 24*time.Hour || paid.PriceMonth != "price_m" {
t.Error("crawl or price")
}
if p.Get("nonsense") != free {
t.Error("unknown plan isn't free")
}
f := filepath.Join(t.TempDir(), "plans.yaml")
os.WriteFile(f, []byte("trial_days: 30\ntax: true\nplans:\n free: {name: Free, modules: [content], seats: 1}\n paid: {name: Team, modules: [all], price_month: price_x, price_year: price_y}\n"), 0o600)
p, err = Load(f, "price_m", "", "")
if err != nil || p.TrialDays != 30 || !p.Tax || p.Get("paid").PriceMonth != "price_x" || p.Get("paid").PriceYear != "price_y" {
t.Errorf("file: %+v %v", p, err)
}
os.WriteFile(f, []byte("plans:\n basic: {name: B, modules: [all]}\n"), 0o600)
if _, err := Load(f, "", "", ""); err == nil {
t.Error("no free plan accepted")
}
}
func TestAccounts(t *testing.T) {
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
defer d.Close()
p := Defaults()
now := time.Now()
if a, _ := Get(d, 9); a.Status != Free {
t.Errorf("no account: %+v", a)
}
StartTrial(d, 1, p, now)
a, _ := Get(d, 1)
if pl, ro := a.Effective(p, now); pl.ID != "paid" || ro {
t.Errorf("trial: %s %v", pl.ID, ro)
}
if pl, _ := a.Effective(p, now.Add(15*24*time.Hour)); pl.ID != "free" {
t.Errorf("after the trial: %s", pl.ID)
}
a.Status, a.PastDueSince = PastDue, now
Save(d, a, now)
if pl, ro := a.Effective(p, now.Add(13*24*time.Hour)); pl.ID != "paid" || ro {
t.Error("past due, under 14 days")
}
if _, ro := a.Effective(p, now.Add(15*24*time.Hour)); !ro {
t.Error("past due 15 days: not read-only")
}
a.Status, a.Customer = Canceled, "cus_1"
Save(d, a, now)
if b, err := ByCustomer(d, "cus_1"); err != nil || b.Team != 1 {
t.Errorf("by customer: %v", err)
}
if pl, _ := a.Effective(p, now); pl.ID != "free" {
t.Error("canceled isn't free")
}
if n, _ := SeenEvent(d, "evt_1", "x", now); !n {
t.Error("first event")
}
if n, _ := SeenEvent(d, "evt_1", "x", now); n {
t.Error("event twice")
}
}
func TestWebhookSignature(t *testing.T) {
body := []byte(`{"id":"evt_1"}`)
now := time.Now()
h := Sign(body, "whsec_x", now)
if err := VerifySignature(h, body, "whsec_x", now); err != nil {
t.Fatal(err)
}
if VerifySignature(h, body, "whsec_y", now) == nil || VerifySignature(h, []byte(`{"id":"evt_2"}`), "whsec_x", now) == nil {
t.Error("a wrong secret or body passed")
}
if VerifySignature(h, body, "whsec_x", now.Add(10*time.Minute)) == nil {
t.Error("an old event passed")
}
if VerifySignature("t=1,v0=abc", body, "whsec_x", now) == nil || VerifySignature("", body, "whsec_x", now) == nil {
t.Error("a malformed header passed")
}
// Stripe may send two signatures while a secret is rolled.
if err := VerifySignature(h+",v1=00ff", body, "whsec_x", now); err != nil {
t.Error("two signatures")
}
}
func TestApplyEvents(t *testing.T) {
p := Defaults()
now := time.Now()
acct := &Account{Team: 7, Status: Trialing, TrialEnds: now.Add(time.Hour)}
load := func(team int64, customer string) (*Account, error) {
if team == 7 || (customer != "" && customer == acct.Customer) {
return acct, nil
}
return nil, nil
}
ev := func(typ, obj string) *Event {
e := &Event{ID: "evt", Type: typ}
e.Data.Object = []byte(obj)
return e
}
a, c, err := Apply(load, p, ev("checkout.session.completed", `{"client_reference_id":"7","customer":"cus_1","subscription":"sub_1"}`), now)
if err != nil || a.Customer != "cus_1" || a.Subscription != "sub_1" || c.Team != 7 {
t.Fatalf("checkout: %+v %v", a, err)
}
a, c, _ = Apply(load, p, ev("customer.subscription.updated", `{"id":"sub_1","customer":"cus_1","status":"active","metadata":{"team":"7"},"items":{"data":[{"quantity":4,"current_period_end":1900000000}]}}`), now)
if a.Status != Active || a.Seats != 4 || a.PeriodEnd.Unix() != 1900000000 || c.Before != Trialing {
t.Errorf("updated: %+v", a)
}
a, _, _ = Apply(load, p, ev("invoice.payment_failed", `{"customer":"cus_1"}`), now)
if a.Status != PastDue || !a.PastDueSince.Equal(now) {
t.Errorf("failed: %+v", a)
}
a, _, _ = Apply(load, p, ev("invoice.payment_failed", `{"customer":"cus_1"}`), now.Add(time.Hour))
if !a.PastDueSince.Equal(now) {
t.Error("past due since moved")
}
a, _, _ = Apply(load, p, ev("invoice.paid", `{"customer":"cus_1"}`), now)
if a.Status != Active || !a.PastDueSince.IsZero() {
t.Errorf("paid: %+v", a)
}
a, _, _ = Apply(load, p, ev("customer.subscription.deleted", `{"id":"sub_1","customer":"cus_1","status":"canceled","metadata":{"team":"7"}}`), now)
if a.Status != Canceled || a.Subscription != "" {
t.Errorf("deleted: %+v", a)
}
if a, c, err := Apply(load, p, ev("invoice.paid", `{"customer":"cus_other"}`), now); a != nil || c != nil || err != nil {
t.Error("another product's customer")
}
if a, _, _ := Apply(load, p, ev("charge.refunded", `{}`), now); a != nil {
t.Error("an event billing doesn't follow")
}
}
+150
View File
@@ -0,0 +1,150 @@
// Package billing is the multi-tenant edition's plans and each team's
// subscription to one, through the platform's own Stripe account (Stripe
// Billing): Checkout to subscribe, the Customer Portal to pay and see
// invoices, webhooks to follow the subscription. Separate from a team's own
// Stripe connection, which the Metrics module reads.
package billing
import (
"errors"
"fmt"
"os"
"time"
"gopkg.in/yaml.v3"
)
// Plan is what a team may do.
type Plan struct {
ID string `yaml:"-"`
Name string `yaml:"name"`
Modules []string `yaml:"modules"` // "all", or module IDs
// Seats: how many people; 0 on a paid plan means as many as are paid
// for (Stripe's quantity).
Seats int `yaml:"seats"`
Agents int `yaml:"agents"` // not counted as people
// Storage: StorageGB for the team, or StorageGBPerSeat for each paid
// person, pooled; more in blocks of StorageBlockGB.
StorageGB int `yaml:"storage_gb"`
StorageGBPerSeat int `yaml:"storage_gb_per_seat"`
StorageBlockGB int `yaml:"storage_block_gb"`
CrawlPages int `yaml:"crawl_pages"`
CrawlEvery string `yaml:"crawl_every"` // daily or weekly
Sources int `yaml:"sources"` // Market entries watched; 0: no limit beyond fair use
// Stripe's prices: per person a month, and (if offered) a year; and
// per extra storage block a month.
PriceMonth string `yaml:"price_month"`
PriceYear string `yaml:"price_year"`
PriceStorageBlock string `yaml:"price_storage_block"`
PerSeatCents int `yaml:"per_seat_cents"` // to show: 1500 is $15
}
// Paid says whether the plan is paid for.
func (p *Plan) Paid() bool { return p.PriceMonth != "" || p.PriceYear != "" || p.PerSeatCents > 0 }
// Includes says whether a module is in the plan.
func (p *Plan) Includes(module string) bool {
for _, m := range p.Modules {
if m == "all" || m == module {
return true
}
}
return false
}
// CrawlInterval is how often a site is audited.
func (p *Plan) CrawlInterval() time.Duration {
if p.CrawlEvery == "daily" {
return 24 * time.Hour
}
return 7 * 24 * time.Hour
}
// StorageBytes is the plan's storage for a team with seats paid people
// and blocks extra blocks.
func (p *Plan) StorageBytes(seats, blocks int) int64 {
gb := p.StorageGB + p.StorageGBPerSeat*seats + p.StorageBlockGB*blocks
return int64(gb) << 30
}
// Plans are the platform's.
type Plans struct {
Plans map[string]*Plan `yaml:"plans"`
Free string `yaml:"free"` // the plan a team drops to
Paid string `yaml:"paid"` // the plan a trial is of
TrialDays int `yaml:"trial_days"` // a new team's trial of Paid
Tax bool `yaml:"tax"` // Stripe Tax on Checkout (automatic_tax)
}
// Defaults are the plans decided on 2026-11-25 (PLAN.md, Phase 14), without
// Stripe's price IDs, which come from SUPERMARKET_PLANS or the environment.
func Defaults() *Plans {
return &Plans{
Free: "free", Paid: "paid", TrialDays: 14,
Plans: map[string]*Plan{
"free": {ID: "free", Name: "Free", Modules: []string{"content", "seo", "market"}, Seats: 2, Agents: 1,
StorageGB: 1, CrawlPages: 500, CrawlEvery: "weekly", Sources: 10},
"paid": {ID: "paid", Name: "Paid", Modules: []string{"all"}, Agents: 5,
StorageGBPerSeat: 5, StorageBlockGB: 25, CrawlPages: 10000, CrawlEvery: "daily", PerSeatCents: 1500},
},
}
}
// Load reads the plans: a YAML file (SUPERMARKET_PLANS), or the defaults.
// priceMonth, priceYear and priceBlock fill the paid plan's Stripe prices
// when the file doesn't.
func Load(path, priceMonth, priceYear, priceBlock string) (*Plans, error) {
p := Defaults()
if path != "" {
raw, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var f Plans
if err := yaml.Unmarshal(raw, &f); err != nil {
return nil, fmt.Errorf("the plans file: %w", err)
}
if len(f.Plans) > 0 {
p.Plans = f.Plans
}
if f.Free != "" {
p.Free = f.Free
}
if f.Paid != "" {
p.Paid = f.Paid
}
if f.TrialDays != 0 {
p.TrialDays = f.TrialDays
}
p.Tax = f.Tax
}
for id, pl := range p.Plans {
pl.ID = id
if len(pl.Modules) == 0 {
return nil, fmt.Errorf("plan %s has no modules", id)
}
}
paid, free := p.Plans[p.Paid], p.Plans[p.Free]
if paid == nil || free == nil {
return nil, errors.New("the plans need a free plan and a paid one (free:, paid:)")
}
if paid.PriceMonth == "" {
paid.PriceMonth = priceMonth
}
if paid.PriceYear == "" {
paid.PriceYear = priceYear
}
if paid.PriceStorageBlock == "" {
paid.PriceStorageBlock = priceBlock
}
return p, nil
}
// Get is a plan by ID, or the free one.
func (p *Plans) Get(id string) *Plan {
if pl, ok := p.Plans[id]; ok {
return pl
}
return p.Plans[p.Free]
}
+148
View File
@@ -0,0 +1,148 @@
package billing
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// Stripe is the platform's Stripe account: the few calls billing needs.
type Stripe struct {
Key string
Base string // https://api.stripe.com/v1; tests point it elsewhere
HTTP *http.Client
}
// NewStripe is a client for a secret key.
func NewStripe(key string) *Stripe {
return &Stripe{Key: key, Base: "https://api.stripe.com/v1", HTTP: &http.Client{Timeout: 30 * time.Second}}
}
func (s *Stripe) call(ctx context.Context, method, path string, form url.Values, out any) error {
var body io.Reader
u := s.Base + path
if method == http.MethodGet && form != nil {
u += "?" + form.Encode()
} else if form != nil {
body = strings.NewReader(form.Encode())
}
req, err := http.NewRequestWithContext(ctx, method, u, body)
if err != nil {
return err
}
req.SetBasicAuth(s.Key, "")
if body != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
resp, err := s.HTTP.Do(req)
if err != nil {
return fmt.Errorf("reaching Stripe: %w", err)
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode >= 300 {
var e struct {
Error struct{ Message string } `json:"error"`
}
_ = json.Unmarshal(raw, &e)
if e.Error.Message == "" {
e.Error.Message = resp.Status
}
return errors.New("Stripe said: " + e.Error.Message)
}
if out == nil {
return nil
}
return json.Unmarshal(raw, out)
}
// CreateCustomer makes the team's customer.
func (s *Stripe) CreateCustomer(ctx context.Context, email, name string, team int64) (string, error) {
var c struct{ ID string }
err := s.call(ctx, http.MethodPost, "/customers", url.Values{"email": {email}, "name": {name}, "metadata[team]": {strconv.FormatInt(team, 10)}}, &c)
return c.ID, err
}
// Checkout is a Stripe Checkout session for subscribing.
type Checkout struct {
Customer, Price string
Quantity int
Team int64
Success, Cancel string
Tax bool
}
// CheckoutURL starts Checkout: the address to send the owner to.
func (s *Stripe) CheckoutURL(ctx context.Context, c Checkout) (string, error) {
team := strconv.FormatInt(c.Team, 10)
form := url.Values{
"mode": {"subscription"}, "customer": {c.Customer},
"line_items[0][price]": {c.Price}, "line_items[0][quantity]": {strconv.Itoa(max(c.Quantity, 1))},
"success_url": {c.Success}, "cancel_url": {c.Cancel},
"client_reference_id": {team}, "subscription_data[metadata][team]": {team},
}
if c.Tax {
form.Set("automatic_tax[enabled]", "true")
form.Set("customer_update[address]", "auto")
}
var out struct{ URL string }
err := s.call(ctx, http.MethodPost, "/checkout/sessions", form, &out)
return out.URL, err
}
// PortalURL is the Customer Portal, for paying and the invoices.
func (s *Stripe) PortalURL(ctx context.Context, customer, back string) (string, error) {
var out struct{ URL string }
err := s.call(ctx, http.MethodPost, "/billing_portal/sessions", url.Values{"customer": {customer}, "return_url": {back}}, &out)
return out.URL, err
}
// Invoice is the next one.
type Invoice struct {
AmountDue int64 // in the currency's smallest unit
Currency string
Date time.Time // when it's charged
}
// Upcoming is the customer's next invoice, or nil if there's none.
func (s *Stripe) Upcoming(ctx context.Context, customer string) (*Invoice, error) {
var out struct {
AmountDue int64 `json:"amount_due"`
Currency string `json:"currency"`
NextPaymentAttempt int64 `json:"next_payment_attempt"`
PeriodEnd int64 `json:"period_end"`
}
if err := s.call(ctx, http.MethodGet, "/invoices/upcoming", url.Values{"customer": {customer}}, &out); err != nil {
return nil, err
}
when := out.NextPaymentAttempt
if when == 0 {
when = out.PeriodEnd
}
return &Invoice{AmountDue: out.AmountDue, Currency: out.Currency, Date: time.Unix(when, 0)}, nil
}
// SetQuantity changes how many people the subscription pays for, with
// Stripe prorating the difference.
func (s *Stripe) SetQuantity(ctx context.Context, subscription string, quantity int) error {
var sub struct {
Items struct {
Data []struct{ ID string } `json:"data"`
} `json:"items"`
}
if err := s.call(ctx, http.MethodGet, "/subscriptions/"+url.PathEscape(subscription), nil, &sub); err != nil {
return err
}
if len(sub.Items.Data) == 0 {
return errors.New("the subscription has nothing in it")
}
return s.call(ctx, http.MethodPost, "/subscription_items/"+url.PathEscape(sub.Items.Data[0].ID),
url.Values{"quantity": {strconv.Itoa(max(quantity, 1))}, "proration_behavior": {"create_prorations"}}, nil)
}
+204
View File
@@ -0,0 +1,204 @@
package billing
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"strconv"
"strings"
"time"
)
// Stripe's webhooks.
// Tolerance is how old a signed event may be.
const Tolerance = 5 * time.Minute
// ErrSignature is an event whose signature doesn't check.
var ErrSignature = errors.New("the event's signature doesn't match")
// VerifySignature checks Stripe's Stripe-Signature header (t=…,v1=…) on a
// body: an HMAC-SHA256, with the webhook's secret, of "<t>.<body>".
func VerifySignature(header string, body []byte, secret string, now time.Time) error {
var t int64
var sigs []string
for _, part := range strings.Split(header, ",") {
k, v, ok := strings.Cut(strings.TrimSpace(part), "=")
if !ok {
continue
}
switch k {
case "t":
t, _ = strconv.ParseInt(v, 10, 64)
case "v1":
sigs = append(sigs, v)
}
}
if t == 0 || len(sigs) == 0 || secret == "" {
return ErrSignature
}
if d := now.Sub(time.Unix(t, 0)); d > Tolerance || d < -Tolerance {
return errors.New("the event is too old, or from the future")
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(strconv.FormatInt(t, 10) + "." + string(body)))
want := mac.Sum(nil)
for _, s := range sigs {
got, err := hex.DecodeString(s)
if err == nil && hmac.Equal(got, want) {
return nil
}
}
return ErrSignature
}
// Sign makes a Stripe-Signature header: for tests.
func Sign(body []byte, secret string, at time.Time) string {
t := strconv.FormatInt(at.Unix(), 10)
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(t + "." + string(body)))
return "t=" + t + ",v1=" + hex.EncodeToString(mac.Sum(nil))
}
// Event is a Stripe event, as far as billing reads it.
type Event struct {
ID string `json:"id"`
Type string `json:"type"`
Data struct {
Object json.RawMessage `json:"object"`
} `json:"data"`
}
// The objects billing reads.
type checkoutSession struct {
ClientReference string `json:"client_reference_id"`
Customer string `json:"customer"`
Subscription string `json:"subscription"`
}
type subscription struct {
ID string `json:"id"`
Customer string `json:"customer"`
Status string `json:"status"`
CurrentPeriodEnd int64 `json:"current_period_end"`
TrialEnd int64 `json:"trial_end"`
Metadata map[string]string `json:"metadata"`
Items struct {
Data []struct {
Quantity int `json:"quantity"`
CurrentPeriodEnd int64 `json:"current_period_end"`
Price struct {
ID string `json:"id"`
} `json:"price"`
} `json:"data"`
} `json:"items"`
}
type invoice struct {
Customer string `json:"customer"`
Subscription string `json:"subscription"`
}
// Change is what an event did to a team's account, for the log.
type Change struct {
Team int64
Before string // the status before
After string
Note string
}
// Apply updates the accounts for an event. Events about customers
// Supermarket doesn't know (another product on the same Stripe account)
// are ignored: a nil Change.
func Apply(load func(team int64, customer string) (*Account, error), p *Plans, e *Event, now time.Time) (*Account, *Change, error) {
switch e.Type {
case "checkout.session.completed":
var cs checkoutSession
if err := json.Unmarshal(e.Data.Object, &cs); err != nil {
return nil, nil, err
}
team, _ := strconv.ParseInt(cs.ClientReference, 10, 64)
a, err := load(team, cs.Customer)
if err != nil || a == nil {
return nil, nil, err
}
before := a.Status
a.Customer = cs.Customer
if cs.Subscription != "" {
a.Subscription = cs.Subscription
}
return a, &Change{Team: a.Team, Before: before, After: a.Status, Note: "subscribed through Checkout"}, nil
case "customer.subscription.created", "customer.subscription.updated", "customer.subscription.deleted":
var sub subscription
if err := json.Unmarshal(e.Data.Object, &sub); err != nil {
return nil, nil, err
}
team, _ := strconv.ParseInt(sub.Metadata["team"], 10, 64)
a, err := load(team, sub.Customer)
if err != nil || a == nil {
return nil, nil, err
}
before := a.Status
a.Customer, a.Subscription, a.Plan = sub.Customer, sub.ID, p.Paid
status := sub.Status
switch status {
case "unpaid", "incomplete":
status = PastDue
case "incomplete_expired", "paused":
status = Canceled
}
if e.Type == "customer.subscription.deleted" {
status, a.Subscription = Canceled, ""
}
a.Status = status
if len(sub.Items.Data) > 0 {
a.Seats = sub.Items.Data[0].Quantity
}
end := sub.CurrentPeriodEnd
if end == 0 && len(sub.Items.Data) > 0 {
end = sub.Items.Data[0].CurrentPeriodEnd // newer API versions keep it on the item
}
if end > 0 {
a.PeriodEnd = time.Unix(end, 0)
}
if sub.TrialEnd > 0 {
a.TrialEnds = time.Unix(sub.TrialEnd, 0)
}
markPastDue(a, now)
return a, &Change{Team: a.Team, Before: before, After: a.Status}, nil
case "invoice.payment_failed", "invoice.paid":
var inv invoice
if err := json.Unmarshal(e.Data.Object, &inv); err != nil {
return nil, nil, err
}
a, err := load(0, inv.Customer)
if err != nil || a == nil {
return nil, nil, err
}
before := a.Status
if e.Type == "invoice.payment_failed" && a.Subscription != "" {
a.Status = PastDue
} else if e.Type == "invoice.paid" && a.Status == PastDue {
a.Status = Active
}
markPastDue(a, now)
return a, &Change{Team: a.Team, Before: before, After: a.Status, Note: strings.ReplaceAll(e.Type, "_", " ")}, nil
}
return nil, nil, nil // not an event billing follows
}
// markPastDue notes when a team fell behind, and forgets it when it's
// caught up.
func markPastDue(a *Account, now time.Time) {
if a.Status == PastDue {
if a.PastDueSince.IsZero() {
a.PastDueSince = now
}
return
}
a.PastDueSince, a.Warned = time.Time{}, ""
}
+60 -15
View File
@@ -93,7 +93,18 @@ type Config struct {
SecretKey []byte // 32 bytes that encrypt secrets in the database; nil if not set
OldKey []byte // the key being replaced: secrets under it are encrypted again with SecretKey
Storage Storage
Mail *Mail // nil if not set
Mail *Mail // nil if not set
PGBackups string // where the server's nightly dumps are, to list them; "" if not known
// PlatformAdmins are the email addresses of the people running the
// multi-tenant service (its /platform area).
PlatformAdmins []string
// Billing (multi-tenant): the platform's own Stripe account; empty, no
// billing (every team has everything).
StripeKey, StripeWebhookSecret string
StripePrice, StripePriceYear string // per person, a month and a year
StripePriceStorage string // an extra storage block, a month
PlansFile string // the plans, if not the defaults
}
// Environment variables.
@@ -115,6 +126,14 @@ const (
EnvS3SecretKey = "SUPERMARKET_S3_SECRET_KEY"
EnvMailURL = "SUPERMARKET_MAIL_URL"
EnvMailFrom = "SUPERMARKET_MAIL_FROM"
EnvPGBackups = "SUPERMARKET_PG_BACKUPS"
EnvPlatform = "SUPERMARKET_PLATFORM_ADMINS"
EnvStripeKey = "SUPERMARKET_STRIPE_KEY"
EnvStripeHook = "SUPERMARKET_STRIPE_WEBHOOK_SECRET"
EnvStripePrice = "SUPERMARKET_STRIPE_PRICE"
EnvStripeYear = "SUPERMARKET_STRIPE_PRICE_YEAR"
EnvStripeStore = "SUPERMARKET_STRIPE_PRICE_STORAGE"
EnvPlans = "SUPERMARKET_PLANS"
)
// Load reads the settings through getenv (os.Getenv) and checks them. All
@@ -208,6 +227,38 @@ func Load(getenv func(string) string) (*Config, error) {
bad("%s is needed on the %s edition, to send invitations and password resets: smtp://user:password@mail.example.com:587", EnvMailURL, c.Edition.Name())
}
c.PGBackups = get(EnvPGBackups, "")
for _, a := range strings.Split(get(EnvPlatform, ""), ",") {
if a = strings.ToLower(strings.TrimSpace(a)); a == "" {
continue
}
if _, err := mail.ParseAddress(a); err != nil {
bad("%s: %q isn't an email address", EnvPlatform, a)
continue
}
c.PlatformAdmins = append(c.PlatformAdmins, a)
}
if len(c.PlatformAdmins) > 0 && c.Edition != Multi {
bad("%s is for the multi-tenant edition", EnvPlatform)
}
// Billing.
c.StripeKey, c.StripeWebhookSecret = get(EnvStripeKey, ""), get(EnvStripeHook, "")
c.StripePrice, c.StripePriceYear, c.StripePriceStorage = get(EnvStripePrice, ""), get(EnvStripeYear, ""), get(EnvStripeStore, "")
c.PlansFile = get(EnvPlans, "")
if c.StripeKey != "" {
switch {
case c.Edition != Multi:
bad("%s is for the multi-tenant edition: it bills its teams", EnvStripeKey)
case !strings.HasPrefix(c.StripeKey, "sk_") && !strings.HasPrefix(c.StripeKey, "rk_"):
bad("%s isn't a Stripe secret key (sk_…)", EnvStripeKey)
case c.StripeWebhookSecret == "":
bad("%s is needed with %s: the webhook's signing secret (whsec_…), from Stripe's dashboard", EnvStripeHook, EnvStripeKey)
case c.StripePrice == "" && c.PlansFile == "":
bad("%s is needed with %s: the paid plan's price per person a month (price_…)", EnvStripePrice, EnvStripeKey)
}
}
if len(problems) > 0 {
return c, errors.New(strings.Join(problems, "\n"))
}
@@ -217,7 +268,7 @@ func Load(getenv func(string) string) (*Config, error) {
func loadStorage(get func(string, string) string, bad func(string, ...any), dataDir string) Storage {
v := get(EnvStorage, "")
if v == "" {
return Storage{Dir: dataDir}
return Storage{Dir: filepath.Join(dataDir, "files")}
}
if !strings.HasPrefix(v, "s3://") {
if !filepath.IsAbs(v) {
@@ -303,15 +354,9 @@ func NewKey() (string, error) {
return hex.EncodeToString(b), nil
}
// Ready says whether this version of Supermarket can run the edition. The
// server and multi-tenant editions are planned (PLAN.md, Phases 9–14) and
// come in steps; until they're built, only the settings are checked.
func (c *Config) Ready() error {
if c.Edition == Local {
return nil
}
return fmt.Errorf("This version of Supermarket runs only the local edition: the %s edition isn't built yet. Its settings are fine", c.Edition.Name())
}
// Ready says whether this version of Supermarket can run the edition:
// every edition, since Phase 13.
func (c *Config) Ready() error { return nil }
// Item is one line of the settings, to show.
type Item struct {
@@ -333,10 +378,10 @@ func (c *Config) Summary() []Item {
default:
items = append(items, Item{"Database", "Postgres: " + RedactURL(c.DatabaseURL), EnvDatabaseURL + "."})
}
files := Item{"Files", c.Storage.String(), "Backups, exports and uploads (" + EnvStorage + ")."}
if !c.Storage.S3() && c.Storage.Dir == c.DataDir {
files.Value = c.HostData
files.Help = "The data folder."
files := Item{"Files", c.Storage.String(), "Exports and uploaded files (" + EnvStorage + ")."}
if !c.Storage.S3() && c.Storage.Dir == filepath.Join(c.DataDir, "files") {
files.Value = filepath.Join(c.HostData, "files")
files.Help = "Exports and uploaded files, in the data folder."
}
items = append(items, files)
switch {
+6 -3
View File
@@ -17,7 +17,7 @@ func TestLocalDefaults(t *testing.T) {
t.Fatal(err)
}
if c.Edition != Local || c.DataDir != "/data" || c.Addr != ":8080" || c.PublicURL != "http://localhost:8470" ||
c.Storage.Dir != "/data" || c.Storage.S3() || c.Mail != nil || c.SecretKey != nil || c.DatabaseURL != "" {
c.Storage.Dir != "/data/files" || c.Storage.S3() || c.Mail != nil || c.SecretKey != nil || c.DatabaseURL != "" {
t.Fatalf("%+v", c)
}
if c.CoreConf != "/data/core.conf" || c.MCPSocket != "/data/mcp.sock" || c.HostData != "/data" {
@@ -76,14 +76,14 @@ func TestServer(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if c.Edition != Server || len(c.SecretKey) != 32 || c.Storage.Dir != "/data" {
if c.Edition != Server || len(c.SecretKey) != 32 || c.Storage.Dir != "/data/files" {
t.Fatalf("%+v", c)
}
m := c.Mail
if m.Host != "mail.example.com:587" || m.TLS || m.User != "sm@example.com" || m.Password != "pw" || m.From != "Supermarket <no-reply@sm.example.com>" {
t.Fatalf("%+v", m)
}
if err := c.Ready(); err == nil || !strings.Contains(err.Error(), "isn't built yet") {
if err := c.Ready(); err != nil {
t.Fatal(err)
}
// The summary never shows a password.
@@ -121,6 +121,9 @@ func TestMulti(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if err := c.Ready(); err != nil {
t.Fatal(err)
}
s := c.Storage
if s.Bucket != "supermarket" || s.Prefix != "prod" || s.Endpoint != "https://s3.example.com" || s.Region != "garage" || s.String() != "s3://supermarket/prod at https://s3.example.com" {
t.Fatalf("%+v", s)
+8 -8
View File
@@ -132,13 +132,13 @@ func TestDraftsAndPublish(t *testing.T) {
ctx := context.Background()
// LinkedIn isn't connected: refused, and nothing changes.
pub := &fakePub{}
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, li.ID); err == nil || !strings.Contains(err.Error(), "isn't connected") {
if _, err := Publish(ctx, d, ChannelPublishers{ChannelX: pub}, nil, li.ID); err == nil || !strings.Contains(err.Error(), "isn't connected") {
t.Errorf("publishing without a connection: %v", err)
}
// A failure is recorded; the draft can be fixed and published again.
pub.err = errors.New("HTTP 503")
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, x.ID); err == nil {
if _, err := Publish(ctx, d, ChannelPublishers{ChannelX: pub}, nil, x.ID); err == nil {
t.Fatal("expected the failure")
}
got, _ := GetDraft(d, x.ID)
@@ -149,7 +149,7 @@ func TestDraftsAndPublish(t *testing.T) {
t.Fatal(err)
}
pub.err = nil
got, err = Publish(ctx, d, Publishers{ChannelX: pub}, nil, x.ID)
got, err = Publish(ctx, d, ChannelPublishers{ChannelX: pub}, nil, x.ID)
if err != nil || got.Status != StatusPublished || got.PostURL == "" || got.Error != "" {
t.Fatalf("publish: %+v, %v", got, err)
}
@@ -157,7 +157,7 @@ func TestDraftsAndPublish(t *testing.T) {
t.Errorf("published %q", last)
}
// Published once: a second click doesn't post again, and it can't be edited.
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, x.ID); !errors.Is(err, ErrBusy) {
if _, err := Publish(ctx, d, ChannelPublishers{ChannelX: pub}, nil, x.ID); !errors.Is(err, ErrBusy) {
t.Errorf("second publish: %v", err)
}
if err := UpdateDraft(d, x.ID, "again"); !errors.Is(err, ErrNotEditable) {
@@ -170,7 +170,7 @@ func TestDraftsAndPublish(t *testing.T) {
// Too long for X: refused before calling X.
_, _ = CreateDrafts(d, []Draft{{Channel: ChannelX, Content: strings.Repeat("a", 270), SourceURL: "https://example.com"}})
long, _ := ListDrafts(d, 1, StatusDraft)
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, long[0].ID); err == nil || !strings.Contains(err.Error(), "295 characters including the link") {
if _, err := Publish(ctx, d, ChannelPublishers{ChannelX: pub}, nil, long[0].ID); err == nil || !strings.Contains(err.Error(), "295 characters including the link") {
t.Errorf("over-long post: %v", err)
}
@@ -314,7 +314,7 @@ func TestScheduleAndDue(t *testing.T) {
// Publishing tags only the company's links, and stores the draft untagged.
pub := &fakePub{}
tags := utm.NewTagger([]string{"acme.example"})
got, err := Publish(context.Background(), d, Publishers{ChannelLinkedIn: pub}, tags, soon.ID)
got, err := Publish(context.Background(), d, ChannelPublishers{ChannelLinkedIn: pub}, tags, soon.ID)
if err != nil || got.Status != StatusPublished {
t.Fatalf("publish scheduled: %+v, %v", got, err)
}
@@ -405,7 +405,7 @@ func TestLinkedInAuthor(t *testing.T) {
t.Error("an unknown author was taken")
}
pub := &fakePub{}
if _, err := Publish(ctx, d, Publishers{ChannelLinkedIn: pub}, nil, li.ID); err != nil {
if _, err := Publish(ctx, d, ChannelPublishers{ChannelLinkedIn: pub}, nil, li.ID); err != nil {
t.Fatal(err)
}
if !pub.got.AsPage {
@@ -419,7 +419,7 @@ func TestLinkedInAuthor(t *testing.T) {
if err := SetLinkedInAs(d, dr.ID, ""); err != nil {
t.Fatal(err)
}
Publish(ctx, d, Publishers{ChannelLinkedIn: pub}, nil, dr.ID)
Publish(ctx, d, ChannelPublishers{ChannelLinkedIn: pub}, nil, dr.ID)
}
}
if pub.got.AsPage {
+77 -9
View File
@@ -80,7 +80,11 @@ type Draft struct {
PublishAt time.Time // when a scheduled draft goes out
SignalID int64 // the buying signal it was written for; 0: none
SignalSlug string // that signal's campaign tag
LinkedInAs string // LinkedIn: "" posts as you, AsPage as the company page
LinkedInAs string // LinkedIn: "" posts as you, AsPage as the company page (before posting accounts)
AccountID int64 // the posting account it goes out from; 0: the company's for its channel
WrittenBy int64 // who wrote it (asked the AI for it); 0: unknown, or the local edition
PostedBy int64 // who published or scheduled it
PostedAs string // the account it went out as, once it did
}
// AsPage is the LinkedIn author choice for the company page.
@@ -193,9 +197,9 @@ func CreateDrafts(d *db.DB, drafts []Draft) (string, error) {
if dr.Channel != ChannelLinkedIn {
as = ""
}
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id, linkedin_as)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids), sig, as); err != nil {
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id, linkedin_as, account_id, written_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids), sig, as, dr.AccountID, dr.WrittenBy); err != nil {
return "", err
}
for _, id := range dr.ItemIDs {
@@ -220,7 +224,8 @@ func nonNil(s []string) []string {
const draftColumns = `id, batch, inventory_name, kind, channel, content, source_url, item_ids, status, error,
post_url, created_at, updated_at, COALESCE(published_at, ''), COALESCE(publish_at, ''), title, target,
COALESCE(signal_id, 0), COALESCE((SELECT slug FROM signals WHERE signals.id = drafts.signal_id), ''), linkedin_as`
COALESCE(signal_id, 0), COALESCE((SELECT slug FROM signals WHERE signals.id = drafts.signal_id), ''), linkedin_as,
account_id, written_by, posted_by, posted_as`
func scanDrafts(rows *sql.Rows) ([]Draft, error) {
defer rows.Close()
@@ -230,7 +235,7 @@ func scanDrafts(rows *sql.Rows) ([]Draft, error) {
var ids, created, updated, published, publishAt string
if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content,
&dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt, &dr.Title, &dr.Target,
&dr.SignalID, &dr.SignalSlug, &dr.LinkedInAs); err != nil {
&dr.SignalID, &dr.SignalSlug, &dr.LinkedInAs, &dr.AccountID, &dr.WrittenBy, &dr.PostedBy, &dr.PostedAs); err != nil {
return nil, err
}
_ = json.Unmarshal([]byte(ids), &dr.ItemIDs)
@@ -288,6 +293,10 @@ func GetDraft(d *db.DB, id int64) (*Draft, error) {
// published.
var ErrNotEditable = errors.New("this draft can't be changed any more")
// ErrByHand is the answer to publishing or scheduling a Reddit draft: you
// post those yourself.
var ErrByHand = errors.New("Reddit posts are posted by hand: open the subreddit's submit page from the draft, post it there, then mark it as posted")
// UpdateDraft saves edited text.
func UpdateDraft(d *db.DB, id int64, text string) error {
text = strings.TrimSpace(text)
@@ -365,9 +374,15 @@ func Schedule(d *db.DB, id int64, at time.Time) error {
return errors.New("that's more than a year away")
}
res, err := d.Exec(`UPDATE drafts SET status = ?, publish_at = ?, error = '', updated_at = ?
WHERE id = ? AND status IN (?, ?)`,
StatusScheduled, formatTime(at), formatTime(time.Now()), id, StatusDraft, StatusFailed)
return oneRow(res, err)
WHERE id = ? AND status IN (?, ?) AND channel <> ?`,
StatusScheduled, formatTime(at), formatTime(time.Now()), id, StatusDraft, StatusFailed, ChannelReddit)
err = oneRow(res, err)
if errors.Is(err, ErrNotEditable) {
if dr, gerr := GetDraft(d, id); gerr == nil && dr.Channel == ChannelReddit {
return ErrByHand
}
}
return err
}
// Unschedule sends a scheduled draft back to Posts, to edit or drop.
@@ -417,3 +432,56 @@ func UpdateTitle(d *db.DB, id int64, title string) error {
title, formatTime(time.Now()), id, ChannelReddit, StatusDraft, StatusFailed)
return oneRow(res, err)
}
// SetAccount chooses the posting account a draft goes out from (0: the
// company's for its channel).
func SetAccount(d *db.DB, id, account int64) error {
res, err := d.Exec(`UPDATE drafts SET account_id = ?, updated_at = ? WHERE id = ? AND status IN (?, ?, ?)`,
account, formatTime(time.Now()), id, StatusDraft, StatusFailed, StatusScheduled)
return oneRow(res, err)
}
// SetPostedBy records who published or scheduled a draft.
func SetPostedBy(d *db.DB, id, user int64) error {
_, err := d.Exec(`UPDATE drafts SET posted_by = ? WHERE id = ?`, user, id)
return err
}
// Copy makes a copy of a draft for another posting account, in the same
// batch, waiting in Posts; it returns the copy's ID.
func Copy(d *db.DB, id, account int64) (int64, error) {
dr, err := GetDraft(d, id)
if err != nil {
return 0, err
}
ids, _ := json.Marshal(nonNil(dr.ItemIDs))
var sig any
if dr.SignalID != 0 {
sig = dr.SignalID
}
return d.Insert(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id, linkedin_as, account_id, written_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, dr.Batch, dr.InventoryName, dr.Kind, dr.Channel, dr.Title, dr.Target, dr.Content,
dr.SourceURL, string(ids), sig, dr.LinkedInAs, account, dr.WrittenBy)
}
// HoldForAccount sends the scheduled drafts going out from an account back
// to Posts, with the reason: the account was signed out or removed. It
// returns them, to tell their writers.
func HoldForAccount(d *db.DB, account int64, reason string) ([]Draft, error) {
rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE account_id = ? AND status = ?`, account, StatusScheduled)
if err != nil {
return nil, err
}
held, err := scanDrafts(rows)
if err != nil {
return nil, err
}
_, err = d.Exec(`UPDATE drafts SET status = ?, error = ?, account_id = 0, updated_at = ? WHERE account_id = ? AND status = ?`,
StatusFailed, reason, formatTime(time.Now()), account, StatusScheduled)
if err != nil {
return nil, err
}
// Drafts waiting in Posts for it fall back to the company's account.
_, err = d.Exec(`UPDATE drafts SET account_id = 0 WHERE account_id = ? AND status IN (?, ?)`, account, StatusDraft, StatusFailed)
return held, err
}
+9 -18
View File
@@ -8,7 +8,6 @@ import (
"strings"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/inventory"
"supermarket/internal/profile"
@@ -24,7 +23,7 @@ type Request struct {
// Reddit: the subreddit to write for, and what's known about it (nil
// if its rules couldn't be read).
Subreddit string
SubredditInfo *reddit.Subreddit
SubredditInfo *Subreddit // the rules pasted for it; nil if none
// Signal, if set, is the buying signal the posts are written for.
Signal *signals.Signal
}
@@ -133,7 +132,7 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro
title = string(r[:RedditTitleLimit-1]) + "…"
}
drafts = append(drafts, Draft{InventoryName: name, Kind: req.Entry.Relationship, Channel: ch, SignalID: req.signalID(),
Title: title, Target: reddit.CleanName(req.Subreddit), Content: strings.TrimSpace(rp.Body),
Title: title, Target: CleanSubreddit(req.Subreddit), Content: strings.TrimSpace(rp.Body),
SourceURL: src, ItemIDs: ids, Status: StatusDraft})
continue
}
@@ -314,7 +313,7 @@ func oneLine(s string) string {
// punishes marketing, so the rules are stricter than for other channels.
func redditInstructions(req Request) string {
var b strings.Builder
sub := reddit.CleanName(req.Subreddit)
sub := CleanSubreddit(req.Subreddit)
fmt.Fprintf(&b, "- reddit: an object with a title (at most %d characters) and a body, for r/%s. "+
"Write as a member of the community who works at %s, and say so plainly in the body (\"I work at %s\"). "+
"Lead with what's useful or interesting to this community, not with the company. No hashtags, no emoji, no marketing language, "+
@@ -326,20 +325,12 @@ func redditInstructions(req Request) string {
"about it, and invite questions and feedback.\n")
}
if info := req.SubredditInfo; info != nil {
b.WriteString("<subreddit>\n")
if info.Description != "" {
fmt.Fprintf(&b, "About r/%s: %s\n", sub, oneLine(info.Description))
}
if info.SubmitText != "" {
fmt.Fprintf(&b, "Posting guidelines: %s\n", oneLine(truncateRunes(info.SubmitText, 1500)))
}
for i, r := range info.Rules {
if r.Kind == "comment" {
continue
}
fmt.Fprintf(&b, "Rule %d: %s. %s\n", i+1, r.Name, oneLine(truncateRunes(r.Description, 400)))
}
b.WriteString("</subreddit>\n")
b.WriteString("<subreddit_rules>\n")
b.WriteString(truncateRunes(info.Rules, 6000))
b.WriteString("\n</subreddit_rules>\n")
} else {
fmt.Fprintf(&b, " r/%s's rules weren't given: follow Reddit's usual norms (no self-promotion beyond one post in ten, no spam), "+
"and keep the post useful even if promotion turns out to be forbidden.\n", sub)
}
return b.String()
}
+26 -7
View File
@@ -24,8 +24,24 @@ type Publisher interface {
Publish(ctx context.Context, p Post) (string, error)
}
// Publishers are the channels that can post now, by channel ID.
type Publishers map[string]Publisher
// Publishers find where a draft goes out: its publisher and the account's
// name, or why it can't.
type Publishers interface {
For(dr *Draft) (Publisher, string, error)
}
// ChannelPublishers is a publisher per channel: for tests, and anything
// without posting accounts.
type ChannelPublishers map[string]Publisher
// For is the draft's channel's publisher.
func (c ChannelPublishers) For(dr *Draft) (Publisher, string, error) {
p := c[dr.Channel]
if p == nil {
return nil, "", fmt.Errorf("%s isn't connected: sign in under Settings → Social accounts", dr.ChannelName())
}
return p, "", nil
}
// ErrBusy means the draft is already being published.
var ErrBusy = errors.New("this draft is already being published, or was published")
@@ -44,9 +60,12 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i
if !dr.Editable() && dr.Status != StatusScheduled {
return dr, ErrBusy
}
pub := pubs[dr.Channel]
if pub == nil {
return dr, fmt.Errorf("%s isn't connected: sign in under Settings → Social accounts", dr.ChannelName())
if dr.Channel == ChannelReddit {
return dr, ErrByHand
}
pub, as, err := pubs.For(dr)
if err != nil {
return dr, err
}
if problem := dr.Problem(); problem != "" {
return dr, fmt.Errorf("%s. Fix it first", problem)
@@ -73,8 +92,8 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i
dr.Status, dr.Error = StatusFailed, pubErr.Error()
return dr, pubErr
}
if _, err := d.Exec(`UPDATE drafts SET status = ?, post_url = ?, published_at = ?, updated_at = ? WHERE id = ?`,
StatusPublished, postURL, now, now, id); err != nil {
if _, err := d.Exec(`UPDATE drafts SET status = ?, post_url = ?, published_at = ?, updated_at = ?, posted_as = ? WHERE id = ?`,
StatusPublished, postURL, now, now, as, id); err != nil {
// It went out: say so, so the user doesn't post it again.
return dr, fmt.Errorf("published to %s (%s), but couldn't record it: %w", dr.ChannelName(), postURL, err)
}
+91 -103
View File
@@ -9,153 +9,141 @@ import (
"strings"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/db"
)
// SubredditMaxAge is how long a subreddit's cached rules are used before
// they're fetched again.
const SubredditMaxAge = 24 * time.Hour
// Reddit posts are always posted by hand: Reddit's API isn't open to
// apps like this one. Supermarket writes the post, opens the subreddit's
// submit page filled in, and records the post once the user marks it as
// posted. A subreddit's rules can't be read either, so the user pastes
// them; drafting and the warnings use what was pasted.
// GetSubreddit returns the cached subreddit, or nil.
func GetSubreddit(d *db.DB, name string) (*reddit.Subreddit, error) {
var raw string
err := d.QueryRow(`SELECT data FROM subreddits WHERE name = ?`, reddit.CleanName(name)).Scan(&raw)
// Subreddit is what the user told Supermarket about a subreddit: its rules,
// as pasted from Reddit.
type Subreddit struct {
Name string `json:"name"`
Rules string `json:"pasted_rules"`
SavedAt time.Time `json:"-"`
}
// MaxRules is the most rules text kept for a subreddit.
const MaxRules = 20000
// CleanSubreddit turns "r/selfhosted", "/r/selfhosted/" or a subreddit URL
// into "selfhosted".
func CleanSubreddit(s string) string {
s = strings.TrimSpace(s)
if i := strings.Index(s, "/r/"); i >= 0 {
s = s[i+3:]
}
s = strings.TrimPrefix(s, "r/")
if i := strings.IndexAny(s, "/?#"); i >= 0 {
s = s[:i]
}
return s
}
// RulesURL is where Reddit shows a subreddit's rules.
func RulesURL(name string) string {
return "https://www.reddit.com/r/" + CleanSubreddit(name) + "/about/rules"
}
// GetSubreddit returns the subreddit's pasted rules, or nil if none were
// pasted. (Rows from before, read through Reddit's API, have none.)
func GetSubreddit(d *db.DB, name string) (*Subreddit, error) {
var raw, at string
err := d.QueryRow(`SELECT data, fetched_at FROM subreddits WHERE name = ?`, CleanSubreddit(name)).Scan(&raw, &at)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
var s reddit.Subreddit
var s Subreddit
if err := json.Unmarshal([]byte(raw), &s); err != nil {
return nil, err
}
if strings.TrimSpace(s.Rules) == "" {
return nil, nil
}
s.SavedAt = parseTime(at)
return &s, nil
}
// SaveSubreddit caches a subreddit's rules.
func SaveSubreddit(d *db.DB, s *reddit.Subreddit) error {
raw, err := json.Marshal(s)
// SaveRules keeps the rules pasted for a subreddit. Empty rules forget them.
func SaveRules(d *db.DB, name, rules string, now time.Time) error {
name = CleanSubreddit(name)
if name == "" {
return errors.New("no subreddit")
}
rules = strings.TrimSpace(strings.ReplaceAll(rules, "\r\n", "\n"))
if len([]rune(rules)) > MaxRules {
return fmt.Errorf("that's more than %d characters: paste just the rules", MaxRules)
}
if rules == "" {
_, err := d.Exec(`DELETE FROM subreddits WHERE name = ?`, name)
return err
}
raw, err := json.Marshal(Subreddit{Name: name, Rules: rules})
if err != nil {
return err
}
_, err = d.Exec(`INSERT INTO subreddits (name, data, fetched_at) VALUES (?, ?, ?)
ON CONFLICT (name) DO UPDATE SET data = excluded.data, fetched_at = excluded.fetched_at`,
s.Name, string(raw), formatTime(s.FetchedAt))
name, string(raw), formatTime(now))
return err
}
// Reddit's self-promotion guideline: at most one post in ten about your own
// work. Posting to the same subreddit more than about weekly reads as spam.
const (
ownShareLimit = 0.10
sameSubWindow = 7 * 24 * time.Hour
historyWindow = 30 * 24 * time.Hour
)
// Posting to the same subreddit more than about weekly reads as spam.
const sameSubWindow = 7 * 24 * time.Hour
var promoRule = regexp.MustCompile(`(?i)promot|advertis|spam|marketing|self-?post|affiliat|commercial|vendor|blogspam`)
// RedditPost is a Reddit post Supermarket knows of: one the user marked as
// posted (or, before, one it published).
type RedditPost struct {
Subreddit string
Created time.Time
}
// RedditCheck is what the warnings are worked out from.
type RedditCheck struct {
Target string
HasLink bool // the draft carries a link
OwnLink bool // to the company's own site
Promo bool // it promotes the company's own product
Info *reddit.Subreddit // nil if the rules couldn't be read
History []reddit.Submission // the account's recent posts; nil if unknown
// Recorded is the Reddit posts Supermarket knows of (published or
// marked as posted), used for the same-subreddit check when History
// is unknown. They're not the whole account, so they don't count for
// the own-link share or the new-account warning.
Recorded []reddit.Submission
Own func(url string) bool
Target string
Promo bool // it promotes the company's own product
Info *Subreddit // nil if no rules were pasted
Recorded []RedditPost
Now time.Time
}
// RedditWarnings lists reasons to think twice before posting. They never
// block publishing: the user decides.
// block posting: the user decides.
func RedditWarnings(c RedditCheck) []string {
var w []string
sub := "r/" + c.Target
if c.Promo {
w = append(w, "This promotes your own work. Many subreddits allow that only in designated threads, or not at all: check the rules.")
}
if c.Info == nil {
w = append(w, "Couldn't read "+sub+"'s rules: check them on Reddit before posting.")
} else {
if c.Info.Type == "restricted" || c.Info.Type == "private" {
w = append(w, fmt.Sprintf("%s is %s: only approved users can post.", sub, c.Info.Type))
}
if !c.Info.AllowsText() && !c.HasLink {
w = append(w, sub+" only takes link posts, and this draft has no link.")
} else if !c.Info.AllowsText() {
w = append(w, sub+" only takes link posts: it will be posted as the title and the link, without the text.")
}
for _, r := range c.Info.Rules {
if promoRule.MatchString(r.Name + " " + r.Description) {
w = append(w, fmt.Sprintf("%s has a rule about this: “%s”.", sub, r.Name))
if c.Info != nil {
for _, line := range strings.Split(c.Info.Rules, "\n") {
line = strings.TrimSpace(line)
if promoRule.MatchString(line) {
w = append(w, fmt.Sprintf("%s has a rule about this: “%s”.", sub, truncateRunes(line, 200)))
}
}
}
if c.History == nil {
var inSub []time.Time
for _, s := range c.Recorded {
if strings.EqualFold(s.Subreddit, c.Target) && c.Now.Sub(s.Created) < sameSubWindow {
inSub = append(inSub, s.Created)
}
}
if len(inSub) > 0 {
w = append(w, fmt.Sprintf("You posted in %s %d time%s in the past week through Supermarket, last on %s. Most communities expect less.",
sub, len(inSub), plural(len(inSub)), inSub[0].Local().Format("2 Jan")))
}
return w
}
if len(c.History) == 0 {
w = append(w, "This account hasn't posted before. Communities often remove a new account's first posts, especially promotional ones: take part in discussions first.")
return w
}
var inSub []time.Time
recent, own := 0, 0
for _, s := range c.History {
age := c.Now.Sub(s.Created)
if strings.EqualFold(s.Subreddit, c.Target) && age < sameSubWindow {
for _, s := range c.Recorded {
if strings.EqualFold(s.Subreddit, c.Target) && c.Now.Sub(s.Created) < sameSubWindow {
inSub = append(inSub, s.Created)
}
if age < historyWindow {
recent++
if c.Own != nil && (c.Own(s.URL) || containsOwnLink(s.Text, c.Own)) {
own++
}
}
}
if len(inSub) > 0 {
w = append(w, fmt.Sprintf("You posted in %s %d time%s in the past week, last on %s. Most communities expect less.",
w = append(w, fmt.Sprintf("You posted in %s %d time%s in the past week through Supermarket, last on %s. Most communities expect less.",
sub, len(inSub), plural(len(inSub)), inSub[0].Local().Format("2 Jan")))
}
// Count this post as one more own link, if it has one.
if c.OwnLink {
share := float64(own+1) / float64(recent+1)
if share > ownShareLimit && own+1 > 1 {
w = append(w, fmt.Sprintf("With this one, %d of your %d posts in the past 30 days link to your own sites. Reddit's guideline is at most 1 in 10.",
own+1, recent+1))
}
}
return w
}
var urlPattern = regexp.MustCompile(`https?://[^\s)\]>"]+`)
func containsOwnLink(text string, own func(string) bool) bool {
for _, u := range urlPattern.FindAllString(text, -1) {
if own(u) {
return true
}
}
return false
}
func plural(n int) string {
if n == 1 {
return ""
@@ -163,24 +151,24 @@ func plural(n int) string {
return "s"
}
// RecordedRedditPosts are the Reddit posts Supermarket published, or the
// user marked as posted, since then, newest first.
func RecordedRedditPosts(d *db.DB, since time.Time) ([]reddit.Submission, error) {
rows, err := d.Query(`SELECT target, title, content, source_url, published_at FROM drafts
// RecordedRedditPosts are the Reddit posts marked as posted (or published)
// since then, newest first.
func RecordedRedditPosts(d *db.DB, since time.Time) ([]RedditPost, error) {
rows, err := d.Query(`SELECT target, published_at FROM drafts
WHERE channel = ? AND status = ? AND published_at >= ? ORDER BY published_at DESC`,
ChannelReddit, StatusPublished, formatTime(since))
if err != nil {
return nil, err
}
defer rows.Close()
var out []reddit.Submission
var out []RedditPost
for rows.Next() {
var s reddit.Submission
var s RedditPost
var at string
if err := rows.Scan(&s.Subreddit, &s.Title, &s.Text, &s.URL, &at); err != nil {
if err := rows.Scan(&s.Subreddit, &at); err != nil {
return nil, err
}
s.IsSelf, s.Created = true, parseTime(at)
s.Created = parseTime(at)
out = append(out, s)
}
return out, rows.Err()
+58 -38
View File
@@ -2,20 +2,18 @@ package content
import (
"context"
"errors"
"strings"
"testing"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/inventory"
"supermarket/internal/utm"
)
func TestGenerateReddit(t *testing.T) {
entry := &inventory.Entry{Name: "Jitsi", Relationship: inventory.Partner}
items := []Item{{ContentItem: item("1", "Jitsi", time.Now())}}
info := &reddit.Subreddit{Name: "selfhosted", Description: "Self-hosting", SubmitText: "Flair your post.",
Rules: []reddit.Rule{{Name: "No spam", Description: "10% rule", Kind: "link"}, {Name: "Be civil", Kind: "comment"}}}
info := &Subreddit{Name: "selfhosted", Rules: "1. No spam: the 10% rule\n2. Flair your post."}
f := &fakeAI{replies: []string{`{"x": "Short", "reddit": {"title": " Jitsi 3 is out ", "body": "I work at Acme. Details."}}`}}
drafts, err := Generate(context.Background(), f, Request{Profile: testProfile(), Entry: entry, Items: items,
Channels: []string{ChannelX, ChannelReddit}, Subreddit: "r/selfhosted", SubredditInfo: info})
@@ -27,13 +25,19 @@ func TestGenerateReddit(t *testing.T) {
t.Fatalf("reddit draft = %+v", r)
}
prompt := f.reqs[0].Prompt
for _, want := range []string{"r/selfhosted", "I work at Acme", "No hashtags", "Flair your post.", "Rule 1: No spam"} {
for _, want := range []string{"r/selfhosted", "I work at Acme", "No hashtags", "2. Flair your post.", "1. No spam: the 10% rule"} {
if !strings.Contains(prompt, want) {
t.Errorf("prompt lacks %q", want)
}
}
if strings.Contains(prompt, "Be civil") {
t.Error("comment-only rules needn't go in the prompt")
// Without rules, the model is told they weren't given.
f = &fakeAI{replies: []string{`{"reddit": {"title": "T", "body": "B"}}`}}
if _, err := Generate(context.Background(), f, Request{Profile: testProfile(), Entry: entry, Items: items,
Channels: []string{ChannelReddit}, Subreddit: "selfhosted"}); err != nil {
t.Fatal(err)
}
if !strings.Contains(f.reqs[0].Prompt, "rules weren't given") {
t.Error("no note about missing rules")
}
props := f.reqs[0].Schema["properties"].(map[string]any)
if props["reddit"].(map[string]any)["type"] != "object" {
@@ -71,33 +75,56 @@ func TestRedditDraftsAndCache(t *testing.T) {
t.Errorf("problem = %q", got.Problem())
}
// Reddit drafts are posted by hand: never published or scheduled.
pub := &fakePub{}
if _, err := Publish(context.Background(), d, Publishers{ChannelReddit: pub}, utm.NewTagger([]string{"acme.example"}), dr.ID); err != nil {
if _, err := Publish(context.Background(), d, ChannelPublishers{ChannelReddit: pub}, nil, dr.ID); !errors.Is(err, ErrByHand) || len(pub.calls) != 0 {
t.Errorf("publish: %v, %d calls", err, len(pub.calls))
}
if err := Schedule(d, dr.ID, time.Now().Add(time.Hour)); !errors.Is(err, ErrByHand) {
t.Errorf("schedule: %v", err)
}
if err := MarkPosted(d, dr.ID, "https://www.reddit.com/r/selfhosted/comments/abc"); err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(pub.calls[0], "r/selfhosted|New title|Body|https://acme.example/a?utm_") ||
!strings.Contains(pub.calls[0], "utm_source=reddit") {
t.Errorf("published %q", pub.calls[0])
if rec, _ := RecordedRedditPosts(d, time.Now().Add(-time.Hour)); len(rec) != 1 || rec[0].Subreddit != "selfhosted" {
t.Errorf("recorded = %+v", rec)
}
if s, err := GetSubreddit(d, "selfhosted"); s != nil || err != nil {
t.Fatalf("empty cache: %v %v", s, err)
t.Fatalf("no rules yet: %v %v", s, err)
}
at := time.Now().UTC().Truncate(time.Second)
if err := SaveSubreddit(d, &reddit.Subreddit{Name: "selfhosted", SubmissionType: "self", Rules: []reddit.Rule{{Name: "R"}}, FetchedAt: at}); err != nil {
// A row from before, read through Reddit's API, counts as no rules.
if _, err := d.Exec(`INSERT INTO subreddits (name, data, fetched_at) VALUES ('selfhosted', '{"name":"selfhosted","rules":[{"name":"R"}]}', '')`); err != nil {
t.Fatal(err)
}
s, err := GetSubreddit(d, "r/SelfHosted")
if err != nil || s == nil || len(s.Rules) != 1 || !s.FetchedAt.Equal(at) || s.AllowsLinks() {
t.Errorf("cached = %+v, %v", s, err)
if s, err := GetSubreddit(d, "selfhosted"); s != nil || err != nil {
t.Fatalf("old row: %v %v", s, err)
}
at := time.Now().UTC().Truncate(time.Second)
if err := SaveRules(d, "r/selfhosted", " 1. Be nice\r\n2. No ads ", at); err != nil {
t.Fatal(err)
}
s, err := GetSubreddit(d, "https://www.reddit.com/r/selfhosted/about/rules")
if err != nil || s == nil || s.Rules != "1. Be nice\n2. No ads" || !s.SavedAt.Equal(at) {
t.Errorf("saved = %+v, %v", s, err)
}
if err := SaveRules(d, "selfhosted", strings.Repeat("x", MaxRules+1), at); err == nil {
t.Error("too long accepted")
}
if err := SaveRules(d, "selfhosted", " ", at); err != nil {
t.Fatal(err)
}
if s, _ := GetSubreddit(d, "selfhosted"); s != nil {
t.Error("emptied rules kept")
}
if RulesURL("r/selfhosted") != "https://www.reddit.com/r/selfhosted/about/rules" {
t.Error(RulesURL("r/selfhosted"))
}
}
func TestRedditWarnings(t *testing.T) {
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
own := utm.NewTagger([]string{"acme.example"}).Own
info := &reddit.Subreddit{Name: "selfhosted", SubmissionType: "link", Type: "restricted",
Rules: []reddit.Rule{{Name: "No self-promotion"}, {Name: "Be nice"}}}
info := &Subreddit{Name: "selfhosted", Rules: "1. No self-promotion\n2. Be nice"}
has := func(ws []string, sub string) bool {
for _, w := range ws {
@@ -109,29 +136,22 @@ func TestRedditWarnings(t *testing.T) {
}
w := RedditWarnings(RedditCheck{Target: "selfhosted", Info: info, Now: now})
if !has(w, "restricted") || !has(w, "has no link") || !has(w, "“No self-promotion”") || has(w, "Be nice") || has(w, "past week") {
if !has(w, "“1. No self-promotion”") || has(w, "Be nice") || has(w, "past week") {
t.Errorf("rules warnings = %q", w)
}
if w := RedditWarnings(RedditCheck{Target: "x", Now: now}); !has(w, "Couldn't read r/x's rules") {
t.Errorf("no info = %q", w)
if w := RedditWarnings(RedditCheck{Target: "x", Promo: true, Now: now}); !has(w, "promotes your own work") {
t.Errorf("promo = %q", w)
}
if w := RedditWarnings(RedditCheck{Target: "x", Info: &reddit.Subreddit{}, History: []reddit.Submission{}, Now: now}); !has(w, "hasn't posted before") {
t.Errorf("new account = %q", w)
recorded := []RedditPost{
{Subreddit: "SelfHosted", Created: now.Add(-2 * 24 * time.Hour)},
{Subreddit: "selfhosted", Created: now.Add(-20 * 24 * time.Hour)},
{Subreddit: "homelab", Created: now.Add(-1 * 24 * time.Hour)},
}
history := []reddit.Submission{
{Subreddit: "SelfHosted", URL: "https://acme.example/1", Created: now.Add(-2 * 24 * time.Hour)},
{Subreddit: "homelab", Text: "see https://acme.example/2)", IsSelf: true, Created: now.Add(-10 * 24 * time.Hour)},
{Subreddit: "golang", Created: now.Add(-20 * 24 * time.Hour)},
{Subreddit: "selfhosted", URL: "https://acme.example/old", Created: now.Add(-60 * 24 * time.Hour)},
w = RedditWarnings(RedditCheck{Target: "selfhosted", Recorded: recorded, Now: now})
if !has(w, "posted in r/selfhosted 1 time in the past week") {
t.Errorf("recorded warnings = %q", w)
}
w = RedditWarnings(RedditCheck{Target: "selfhosted", Info: &reddit.Subreddit{}, History: history, Own: own, OwnLink: true, HasLink: true, Now: now})
if !has(w, "posted in r/selfhosted 1 time in the past week") || !has(w, "3 of your 4 posts") {
t.Errorf("history warnings = %q", w)
}
// Without a link of our own, the share isn't the issue.
w = RedditWarnings(RedditCheck{Target: "golang", Info: &reddit.Subreddit{}, History: history, Own: own, Now: now})
if len(w) != 0 {
if w := RedditWarnings(RedditCheck{Target: "golang", Recorded: recorded, Now: now}); len(w) != 0 {
t.Errorf("clean post = %q", w)
}
}
+5
View File
@@ -35,12 +35,17 @@ type DB struct {
SQL *sql.DB
Dialect Dialect
// Team is the team whose schema this is (Teams.Open); 0 for the main
// database.
Team int64
// MigratedFrom is the schema version the database was at when opened,
// if Open migrated it (0 if it was new or already current), for the
// log.
MigratedFrom int
closeHook func() error // tests on Postgres: drop the test's schema
url string // Postgres: where it was opened, for teams' schemas
}
func (d *DB) query(q string) string {
+296
View File
@@ -17,8 +17,18 @@ type Migration struct {
Note string // what it does, for the record (Postgres' schema_migrations)
SQLite string
Postgres string // empty: PostgresSQL(SQLite)
// Platform marks a migration that only touches the tables every team
// shares (people, sessions, keys, locks): on the multi-tenant edition
// it runs in the main schema, never in a team's (see Teams). A
// migration is one or the other, never both.
Platform bool
}
// PlatformTables are the tables every team shares on the multi-tenant
// edition, in the main schema; every other table is a team's, in its own
// schema.
var PlatformTables = []string{"instances", "locks", "users", "memberships", "sessions", "links", "throttle", "agent_keys", "teams", "billing", "stripe_events"}
// both are the migrations after schema 29, on both databases: schema 30
// is both[0]. (migrations, before them, are SQLite's own; Postgres starts
// from postgres.sql, which is schema 29 as a whole.)
@@ -33,6 +43,292 @@ CREATE TABLE secrets (
key_id TEXT NOT NULL, -- which key sealed it: a fingerprint, never the key
updated_at TEXT NOT NULL
);
`,
},
// 31
{
Note: "copies of the app, and the locks that let only one of them do a job",
Platform: true,
SQLite: `
CREATE TABLE instances (
id TEXT PRIMARY KEY, -- a copy of the app, while it runs
host TEXT NOT NULL DEFAULT '',
version TEXT NOT NULL DEFAULT '',
started_at TEXT NOT NULL,
seen_at TEXT NOT NULL -- its last check-in (every 30 seconds)
);
CREATE TABLE locks (
name TEXT PRIMARY KEY, -- the work, e.g. job:seo, outreach:send, audit:<site>
holder TEXT NOT NULL DEFAULT '', -- <instance>:<random>, or '' when free
taken_at TEXT NOT NULL DEFAULT '',
expires_at TEXT NOT NULL DEFAULT '' -- renewed while the work runs; free after it
);
`,
},
// 32
{
Note: "users, their memberships of the team, and their sign-in sessions (server and multi-tenant editions)",
Platform: true,
SQLite: `
CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
name TEXT NOT NULL DEFAULT '',
kind TEXT NOT NULL DEFAULT 'person', -- person or agent
status TEXT NOT NULL DEFAULT 'invited', -- invited, active or disabled
password_hash TEXT NOT NULL DEFAULT '', -- Argon2id, in the PHC string format; '' for none
title TEXT NOT NULL DEFAULT '',
time_zone TEXT NOT NULL DEFAULT '', -- an IANA name, such as Europe/Paris
photo TEXT NOT NULL DEFAULT '', -- a name in the file storage
emails TEXT NOT NULL DEFAULT '[]', -- the emails they want, as a JSON list
created_at TEXT NOT NULL,
signed_in_at TEXT NOT NULL DEFAULT '' -- their last sign-in
);
CREATE TABLE memberships (
team_id INTEGER NOT NULL DEFAULT 1, -- one team until the multi-tenant edition
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
role TEXT NOT NULL, -- owner, admin or member
modules TEXT NOT NULL DEFAULT '{}', -- a member's modules: {"seo":"edit","metrics":"view"}
created_at TEXT NOT NULL,
PRIMARY KEY (team_id, user_id)
);
CREATE TABLE sessions (
id TEXT PRIMARY KEY, -- the SHA-256 of the cookie's random ID, never the ID itself
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TEXT NOT NULL,
seen_at TEXT NOT NULL,
expires_at TEXT NOT NULL,
ip TEXT NOT NULL DEFAULT '',
user_agent TEXT NOT NULL DEFAULT ''
);
CREATE INDEX sessions_user ON sessions(user_id);
`,
},
// 33
{
Note: "one-time links: setting up the first owner, password resets, invitations",
Platform: true,
SQLite: `
CREATE TABLE links (
id TEXT PRIMARY KEY, -- the SHA-256 of the link's random token
purpose TEXT NOT NULL, -- setup, reset or invite
user_id INTEGER NOT NULL DEFAULT 0, -- whose it is; 0 for setup
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL
);
CREATE INDEX links_user ON links(user_id, purpose);
`,
},
// 34
{
Note: "signing in: failed attempts and locks, two-factor sign-in, and limits on tries",
Platform: true,
SQLite: `
ALTER TABLE users ADD COLUMN failed_signins INTEGER NOT NULL DEFAULT 0; -- in a row, since the last sign-in
ALTER TABLE users ADD COLUMN locked_at TEXT NOT NULL DEFAULT ''; -- locked after too many; '' when not
ALTER TABLE users ADD COLUMN two_factor INTEGER NOT NULL DEFAULT 0; -- an authenticator app is on (its secret is in secrets, totp:<id>)
ALTER TABLE users ADD COLUMN totp_step INTEGER NOT NULL DEFAULT 0; -- the last code's time step: each code works once
ALTER TABLE users ADD COLUMN recovery_codes TEXT NOT NULL DEFAULT '[]'; -- SHA-256s of the unused recovery codes
CREATE TABLE throttle (
key TEXT PRIMARY KEY, -- what's counted, e.g. signin:ip:203.0.113.5
count INTEGER NOT NULL DEFAULT 0,
since TEXT NOT NULL -- when the count started
);
`,
},
// 35
{
Note: "posting accounts (several per network, the company's and people's own), who may post to them, and who wrote and posted each draft",
SQLite: `
CREATE TABLE posting_accounts (
id INTEGER PRIMARY KEY,
network TEXT NOT NULL, -- x, linkedin, linkedin_page, reddit
name TEXT NOT NULL DEFAULT '', -- as shown: @acme, u/jo, the page's or the member's name
external TEXT NOT NULL DEFAULT '', -- the network's ID for it: a URN, a username
owner_id INTEGER NOT NULL DEFAULT 0, -- 0: the company's; else the user whose own account it is
created_by INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL DEFAULT '' -- when the sign-in runs out (LinkedIn); '' if renewed
);
CREATE TABLE posting_grants (
account_id INTEGER NOT NULL REFERENCES posting_accounts(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL,
PRIMARY KEY (account_id, user_id)
);
ALTER TABLE drafts ADD COLUMN account_id INTEGER NOT NULL DEFAULT 0; -- 0: the company's account for the channel
ALTER TABLE drafts ADD COLUMN written_by INTEGER NOT NULL DEFAULT 0;
ALTER TABLE drafts ADD COLUMN posted_by INTEGER NOT NULL DEFAULT 0;
ALTER TABLE drafts ADD COLUMN posted_as TEXT NOT NULL DEFAULT ''; -- the account it went out as, when it did
`,
},
// 36
{
Note: "the audit log: who did what, and who made each outreach email",
SQLite: `
CREATE TABLE audit_log (
id INTEGER PRIMARY KEY,
at TEXT NOT NULL,
user_id INTEGER NOT NULL DEFAULT 0, -- 0: Supermarket itself, or the local edition's owner
user_name TEXT NOT NULL DEFAULT '', -- as they were called then
kind TEXT NOT NULL DEFAULT 'person', -- person, agent or system
action TEXT NOT NULL, -- e.g. signin, signin-failed, invited, published, deleted
target TEXT NOT NULL DEFAULT '', -- what it was done to: an address, an account, a page
detail TEXT NOT NULL DEFAULT '',
ip TEXT NOT NULL DEFAULT ''
);
CREATE INDEX audit_log_at ON audit_log(at);
CREATE INDEX audit_log_user ON audit_log(user_id, at);
ALTER TABLE outreach ADD COLUMN created_by INTEGER NOT NULL DEFAULT 0;
`,
},
// 37
{
Note: "agents' keys, and a description for each agent",
Platform: true,
SQLite: `
CREATE TABLE agent_keys (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
hash TEXT NOT NULL UNIQUE, -- the SHA-256 of the key; the key itself is shown once
prefix TEXT NOT NULL, -- its first characters, to tell keys apart
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL DEFAULT '', -- '' for never
retires_at TEXT NOT NULL DEFAULT '', -- replaced by a newer key: works until then
revoked_at TEXT NOT NULL DEFAULT '',
used_at TEXT NOT NULL DEFAULT '',
used_from TEXT NOT NULL DEFAULT '' -- the address of its last use
);
CREATE INDEX agent_keys_user ON agent_keys(user_id);
ALTER TABLE users ADD COLUMN description TEXT NOT NULL DEFAULT '';
`,
},
// 38
{
Note: "approvals: what agents ask to send out, and what they may do on their own",
SQLite: `
CREATE TABLE approvals (
id INTEGER PRIMARY KEY,
agent_id INTEGER NOT NULL,
class TEXT NOT NULL, -- post:<account>, email-first, email-reply, list:<id>, seo-change:<site>
module TEXT NOT NULL, -- whose members decide: content, prospects, seo
target_id INTEGER NOT NULL, -- the draft, message, contact or change
params TEXT NOT NULL DEFAULT '{}', -- what else it needs: when, which list…
summary TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'waiting', -- waiting, done, refused, failed
created_at TEXT NOT NULL,
decided_at TEXT NOT NULL DEFAULT '',
decided_by INTEGER NOT NULL DEFAULT 0, -- 0 with done: the agent did it on its own
result TEXT NOT NULL DEFAULT ''
);
CREATE INDEX approvals_status ON approvals(status, created_at);
CREATE INDEX approvals_agent ON approvals(agent_id, class, decided_at);
CREATE TABLE agent_autonomy (
agent_id INTEGER NOT NULL,
class TEXT NOT NULL,
label TEXT NOT NULL, -- what it is, in words
module TEXT NOT NULL,
daily_cap INTEGER NOT NULL DEFAULT 0, -- 0: no cap
granted_by INTEGER NOT NULL,
granted_at TEXT NOT NULL,
PRIMARY KEY (agent_id, class)
);
`,
},
// 39
{
Note: "agents' limits and pause switch, and the calls they make",
SQLite: `
CREATE TABLE agent_limits (
agent_id INTEGER PRIMARY KEY,
per_minute INTEGER NOT NULL DEFAULT 60, -- tool calls a minute
out_per_day INTEGER NOT NULL DEFAULT 50, -- things it asks to send out, in 24 hours
paused_at TEXT NOT NULL DEFAULT '', -- '' when running
paused_by INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE agent_calls (
id INTEGER PRIMARY KEY,
agent_id INTEGER NOT NULL,
at TEXT NOT NULL,
tool TEXT NOT NULL,
outcome TEXT NOT NULL, -- ok, error, refused (over the rate)
detail TEXT NOT NULL DEFAULT '', -- the error, or the start of the answer
ms INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX agent_calls_agent ON agent_calls(agent_id, at);
`,
},
// 40
{
Note: "teams, and which team each sign-in session works in (multi-tenant edition)",
Platform: true,
SQLite: `
CREATE TABLE teams (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
domain TEXT NOT NULL DEFAULT '', -- the one website domain it works on, such as example.com
status TEXT NOT NULL DEFAULT 'active', -- active, suspended or deleting
created_at TEXT NOT NULL,
delete_at TEXT NOT NULL DEFAULT '' -- deleting: when its data goes for good
);
ALTER TABLE sessions ADD COLUMN team_id INTEGER NOT NULL DEFAULT 1;
`,
},
// 41
{
Note: "proving a team's domain is theirs (multi-tenant edition)",
Platform: true,
SQLite: `
ALTER TABLE teams ADD COLUMN verify_token TEXT NOT NULL DEFAULT ''; -- what the TXT record or the file must hold
ALTER TABLE teams ADD COLUMN verified_at TEXT NOT NULL DEFAULT ''; -- '' until proved
ALTER TABLE teams ADD COLUMN verified_by TEXT NOT NULL DEFAULT ''; -- dns, file or search-console
CREATE UNIQUE INDEX teams_proved_domain ON teams(domain) WHERE verified_at <> '';
`,
},
// 42
{
Note: "the platform's admins looking at a team, with a reason, for a while",
Platform: true,
SQLite: `
ALTER TABLE sessions ADD COLUMN view_until TEXT NOT NULL DEFAULT ''; -- a platform admin viewing a team: until then
ALTER TABLE sessions ADD COLUMN view_reason TEXT NOT NULL DEFAULT '';
`,
},
// 43
{
Note: "signing in with the Core (OpenID Connect): who each person is there, and how a session signed in",
Platform: true,
SQLite: `
ALTER TABLE users ADD COLUMN oidc_subject TEXT NOT NULL DEFAULT ''; -- <issuer>|<subject>: who they are at the Core
CREATE UNIQUE INDEX users_oidc_subject ON users(oidc_subject) WHERE oidc_subject <> '';
ALTER TABLE sessions ADD COLUMN via TEXT NOT NULL DEFAULT 'password'; -- password or core
`,
},
// 44
{
Note: "billing: each team's plan and Stripe subscription, and the Stripe events seen (multi-tenant edition)",
Platform: true,
SQLite: `
CREATE TABLE billing (
team_id INTEGER PRIMARY KEY,
plan TEXT NOT NULL DEFAULT 'paid', -- the plan subscribed to (or trialed)
status TEXT NOT NULL DEFAULT 'trialing', -- trialing, active, past_due, canceled, free
trial_ends TEXT NOT NULL DEFAULT '',
customer TEXT NOT NULL DEFAULT '', -- Stripe's customer
subscription TEXT NOT NULL DEFAULT '', -- Stripe's subscription
seats INTEGER NOT NULL DEFAULT 0, -- people paid for
storage_blocks INTEGER NOT NULL DEFAULT 0, -- extra storage blocks paid for
period_end TEXT NOT NULL DEFAULT '', -- the subscription's current period: when the next invoice comes
past_due_since TEXT NOT NULL DEFAULT '',
kept_member INTEGER NOT NULL DEFAULT 0, -- on Free with too many people: the one besides the owner who keeps their access
storage_used INTEGER NOT NULL DEFAULT 0, -- bytes, measured hourly
warned TEXT NOT NULL DEFAULT '', -- the last lapse email sent: past-due, read-only, deleting
updated_at TEXT NOT NULL
);
CREATE TABLE stripe_events (
id TEXT PRIMARY KEY, -- Stripe's event ID: each is handled once
type TEXT NOT NULL,
received_at TEXT NOT NULL
);
`,
},
}
+35 -7
View File
@@ -37,7 +37,7 @@ func OpenPostgres(url string) (*DB, error) {
sqldb.Close()
return nil, fmt.Errorf("opening Postgres: %w", err)
}
d := &DB{SQL: sqldb, Dialect: Postgres}
d := &DB{SQL: sqldb, Dialect: Postgres, url: url}
if err := d.migratePostgres(); err != nil {
sqldb.Close()
return nil, err
@@ -53,7 +53,12 @@ var AppVersion = "dev"
// transaction: a failure leaves the database as it was. One copy of the
// app at a time does it (an advisory lock), so several can start
// together. Each step is recorded in schema_migrations.
func (d *DB) migratePostgres() error {
func (d *DB) migratePostgres() error { return d.migrateSchema(false) }
// migrateSchema migrates the schema the connection's search_path names
// first: the main one, or (team) a team's, which skips the platform's
// migrations and never has the platform's tables.
func (d *DB) migrateSchema(team bool) error {
if err := checkMigrations(); err != nil {
return err
}
@@ -62,7 +67,7 @@ func (d *DB) migratePostgres() error {
return err
}
defer tx.Rollback()
if _, err := tx.Exec(`SELECT pg_advisory_xact_lock(4708421)`); err != nil { // any fixed number: "the schema"
if _, err := tx.Exec(`SELECT pg_advisory_xact_lock(4708421, hashtext(current_schema()))`); err != nil { // any fixed number: "the schema", then which
return err
}
if _, err := tx.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
@@ -77,8 +82,10 @@ func (d *DB) migratePostgres() error {
_, err := tx.Exec(`INSERT INTO schema_migrations (version, note, app) VALUES ($1, $2, $3)`, version, note, AppVersion)
return err
}
// In this schema itself: a team's search_path falls back to the main
// schema, which has its own.
var exists bool
if err := tx.QueryRow(`SELECT to_regclass('schema_version') IS NOT NULL`).Scan(&exists); err != nil {
if err := tx.QueryRow(`SELECT to_regclass(quote_ident(current_schema()) || '.schema_version') IS NOT NULL`).Scan(&exists); err != nil {
return err
}
version := pgBaseline
@@ -109,8 +116,13 @@ func (d *DB) migratePostgres() error {
}
for i := version; i < Schema(); i++ {
m, q := postgresStep(i)
if _, err := tx.Exec(q); err != nil {
return fmt.Errorf("migration %d (%s): %w", i+1, m.Note, err)
if team && m.Platform {
q = "" // the platform's tables aren't in a team's schema
}
if q != "" {
if _, err := tx.Exec(q); err != nil {
return fmt.Errorf("migration %d (%s): %w", i+1, m.Note, err)
}
}
if _, err := tx.Exec(`UPDATE schema_version SET version = $1`, i+1); err != nil {
return err
@@ -174,7 +186,23 @@ func openTestSchema(base string) (*DB, error) {
d.SQL.SetMaxOpenConns(4)
d.closeHook = func() error {
defer admin.Close()
_, err := admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
// Its teams' schemas too (Teams names them after it).
rows, err := admin.Query(`SELECT nspname FROM pg_namespace WHERE nspname LIKE $1`, schema+`\_team\_%`)
if err == nil {
var teams []string
for rows.Next() {
var n string
if rows.Scan(&n) == nil {
teams = append(teams, n)
}
}
rows.Close()
for _, n := range teams {
admin.Exec(`DROP SCHEMA ` + n + ` CASCADE`)
dropRole(admin, n) // a team's role is named as its schema
}
}
_, err = admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
return err
}
return d, nil
+232
View File
@@ -0,0 +1,232 @@
package db
import (
"context"
"database/sql"
"errors"
"fmt"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
)
// Teams keeps each team's data in a Postgres schema of its own (the
// multi-tenant edition). The main schema has what every team shares (see
// PlatformTables); a team's schema has the rest, made by the same
// migrations. A team's DB is a connection pool whose search_path is its
// schema, then the main one: the app's SQL runs unchanged, finds the
// team's tables, and the shared ones behind them, and can't reach another
// team's tables without naming them.
type Teams struct {
platform *DB
base string // the main database's address
main string // the main schema
prefix string // teams' schemas are <prefix><id>
mu sync.Mutex
open map[int64]*DB
}
// Teams opens the teams of a Postgres database.
func (d *DB) Teams() (*Teams, error) {
if d.Dialect != Postgres || d.url == "" {
return nil, errors.New("teams need Postgres")
}
var main string
if err := d.SQL.QueryRow(`SELECT current_schema()`).Scan(&main); err != nil {
return nil, err
}
prefix := "team_"
if main != "public" {
prefix = main + "_team_" // tests: each in its own schema, its teams named after it
}
return &Teams{platform: d, base: d.url, main: main, prefix: prefix, open: map[int64]*DB{}}, nil
}
// Schema is a team's schema's name.
func (t *Teams) Schema(id int64) string { return t.prefix + strconv.FormatInt(id, 10) }
// Role is the Postgres role a team's connections use: it owns the team's
// schema, and may use the shared tables, nothing else. The second guard:
// even SQL that named another team's schema would be refused.
func (t *Teams) Role(id int64) string { return t.Schema(id) }
// connect opens a pool with a search_path, as a team's role.
func (t *Teams) connect(path, role string) (*sql.DB, error) {
u, err := url.Parse(t.base)
if err != nil {
return nil, err
}
q := u.Query()
q.Set("search_path", path)
u.RawQuery = q.Encode()
cfg, err := pgx.ParseConfig(u.String())
if err != nil {
return nil, err
}
return stdlib.OpenDB(*cfg, stdlib.OptionAfterConnect(func(ctx context.Context, c *pgx.Conn) error {
_, err := c.Exec(ctx, `SET ROLE `+role)
return err
})), nil
}
// grant lets a team's role use the shared tables (and their identity
// sequences) in the main schema: again each time the team opens, so
// shared tables added later are covered.
func (t *Teams) grant(role string) error {
var tables []string
rows, err := t.platform.SQL.Query(`SELECT tablename FROM pg_tables WHERE schemaname = $1`, t.main)
if err != nil {
return err
}
shared := map[string]bool{}
for _, n := range PlatformTables {
shared[n] = true
}
for rows.Next() {
var n string
if err := rows.Scan(&n); err != nil {
rows.Close()
return err
}
if shared[n] {
tables = append(tables, t.main+"."+n)
}
}
rows.Close()
stmts := []string{`GRANT USAGE ON SCHEMA ` + t.main + ` TO ` + role}
if len(tables) > 0 {
stmts = append(stmts, `GRANT SELECT, INSERT, UPDATE, DELETE ON `+strings.Join(tables, ", ")+` TO `+role,
`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA `+t.main+` TO `+role)
}
for _, q := range stmts {
if _, err := t.platform.SQL.Exec(q); err != nil {
return fmt.Errorf("granting %s the shared tables: %w", role, err)
}
}
return nil
}
// Create makes a team's schema, with its tables at the current schema
// version. Making one that exists only migrates it.
func (t *Teams) Create(id int64) error {
if id <= 0 {
return errors.New("no team")
}
schema, role := t.Schema(id), t.Role(id)
var exists bool
if err := t.platform.SQL.QueryRow(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = $1)`, role).Scan(&exists); err != nil {
return err
}
if !exists {
if _, err := t.platform.SQL.Exec(`CREATE ROLE ` + role + ` NOLOGIN`); err != nil {
return fmt.Errorf("making the team's database role (the database user needs CREATEROLE): %w", err)
}
}
// The app's own user takes the team's role on each of its connections.
if _, err := t.platform.SQL.Exec(`GRANT ` + role + ` TO CURRENT_USER`); err != nil {
return err
}
if _, err := t.platform.SQL.Exec(`CREATE SCHEMA IF NOT EXISTS ` + schema + ` AUTHORIZATION ` + role); err != nil {
return err
}
if err := t.grant(role); err != nil {
return err
}
// Only the team's schema on the path while its tables are made, so
// nothing is mistaken for the main schema's; as its role, which owns them.
sqldb, err := t.connect(schema, role)
if err != nil {
return err
}
defer sqldb.Close()
d := &DB{SQL: sqldb, Dialect: Postgres}
return d.migrateSchema(true)
}
// Open is a team's database: one pool per team, kept while the app runs.
// It migrates the team's schema to this version the first time.
func (t *Teams) Open(id int64) (*DB, error) {
t.mu.Lock()
defer t.mu.Unlock()
if d, ok := t.open[id]; ok {
return d, nil
}
var exists bool
if err := t.platform.SQL.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, t.Schema(id)+".schema_version").Scan(&exists); err != nil {
return nil, err
}
if !exists {
return nil, fmt.Errorf("team %d has no data yet", id)
}
if err := t.grant(t.Role(id)); err != nil {
return nil, err
}
sqldb, err := t.connect(t.Schema(id)+","+t.main, t.Role(id))
if err != nil {
return nil, err
}
// Small: many teams share the server's connections. An idle team holds
// none for long.
sqldb.SetMaxOpenConns(4)
sqldb.SetMaxIdleConns(1)
sqldb.SetConnMaxIdleTime(time.Minute)
d := &DB{SQL: sqldb, Dialect: Postgres, Team: id}
if err := d.migrateSchema(true); err != nil {
sqldb.Close()
return nil, fmt.Errorf("team %d: %w", id, err)
}
t.open[id] = d
return d, nil
}
// Drop deletes a team's schema and everything in it.
func (t *Teams) Drop(id int64) error {
t.mu.Lock()
if d, ok := t.open[id]; ok {
d.SQL.Close()
delete(t.open, id)
}
t.mu.Unlock()
if _, err := t.platform.SQL.Exec(`DROP SCHEMA IF EXISTS ` + t.Schema(id) + ` CASCADE`); err != nil {
return err
}
return dropRole(t.platform.SQL, t.Role(id))
}
// dropRole removes a team's role, and what it was granted.
func dropRole(d *sql.DB, role string) error {
var exists bool
if err := d.QueryRow(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = $1)`, role).Scan(&exists); err != nil || !exists {
return err
}
if _, err := d.Exec(`DROP OWNED BY ` + role); err != nil {
return err
}
_, err := d.Exec(`DROP ROLE ` + role)
return err
}
// Close closes every team's pool.
func (t *Teams) Close() {
t.mu.Lock()
defer t.mu.Unlock()
for id, d := range t.open {
d.SQL.Close()
delete(t.open, id)
}
}
// Size is how many bytes a team's schema takes: its tables, their indexes
// and what's stored beside them.
func (t *Teams) Size(id int64) (int64, error) {
var n sql.NullInt64
err := t.platform.SQL.QueryRow(`SELECT sum(pg_total_relation_size(c.oid)) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = $1 AND c.relkind IN ('r', 'm')`, t.Schema(id)).Scan(&n)
return n.Int64, err
}
+108
View File
@@ -0,0 +1,108 @@
package db
import (
"path/filepath"
"strings"
"testing"
)
func TestTeamsSchemas(t *testing.T) {
if !OnPostgres() {
t.Skip("teams are Postgres's")
}
d, err := Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
defer d.Close()
teams, err := d.Teams()
if err != nil {
t.Fatal(err)
}
defer teams.Close()
if _, err := teams.Open(1); err == nil {
t.Error("opened a team that wasn't created")
}
for _, id := range []int64{1, 2} {
if err := teams.Create(id); err != nil {
t.Fatal(err)
}
}
a, err := teams.Open(1)
if err != nil {
t.Fatal(err)
}
b, _ := teams.Open(2)
if a2, _ := teams.Open(1); a2 != a {
t.Error("a second pool")
}
if v, err := a.SchemaVersion(); err != nil || v != Schema() {
t.Errorf("team schema at %d: %v", v, err)
}
// Each team's own tables.
if err := a.PutJSON("company", "Acme"); err != nil {
t.Fatal(err)
}
if err := b.PutJSON("company", "Bolt"); err != nil {
t.Fatal(err)
}
var got string
a.GetJSON("company", &got)
if got != "Acme" {
t.Errorf("team 1 sees %q", got)
}
b.GetJSON("company", &got)
if got != "Bolt" {
t.Errorf("team 2 sees %q", got)
}
var n int
d.QueryRow(`SELECT count(*) FROM settings WHERE key = 'company'`).Scan(&n)
if n != 0 {
t.Error("a team's setting in the main schema")
}
// The shared tables: only in the main schema, reached from a team's.
for _, tbl := range PlatformTables {
var inTeam bool
d.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, teams.Schema(1)+"."+tbl).Scan(&inTeam)
if inTeam {
t.Errorf("%s is in the team's schema", tbl)
}
}
if _, err := d.Exec(`INSERT INTO teams (name, created_at) VALUES ('Acme', 'now')`); err != nil {
t.Fatal(err)
}
if err := a.QueryRow(`SELECT count(*) FROM teams`).Scan(&n); err != nil || n != 1 {
t.Errorf("the shared teams table from a team: %d %v", n, err)
}
// The second guard: a team's connections can't reach another team's
// schema, nor the main schema's own copies of the team tables, even
// by name.
for _, q := range []string{
`SELECT count(*) FROM ` + teams.Schema(2) + `.settings`,
`SELECT count(*) FROM ` + d.mainSchema(t) + `.settings`,
`INSERT INTO ` + teams.Schema(2) + `.settings (key, value) VALUES ('x', '"y"')`,
} {
if _, err := a.Exec(q); err == nil || !strings.Contains(err.Error(), "permission denied") {
t.Errorf("%s: %v", q, err)
}
}
// Creating again only migrates; dropping removes it all.
if err := teams.Create(1); err != nil {
t.Fatal(err)
}
if err := teams.Drop(2); err != nil {
t.Fatal(err)
}
if _, err := teams.Open(2); err == nil {
t.Error("a dropped team opens")
}
}
// mainSchema is the database's main schema (a test's own).
func (d *DB) mainSchema(t *testing.T) string {
var s string
if err := d.SQL.QueryRow(`SELECT current_schema()`).Scan(&s); err != nil {
t.Fatal(err)
}
return s
}
+28 -44
View File
@@ -2,12 +2,11 @@ package inventory
import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/profile"
"supermarket/internal/site"
)
@@ -18,17 +17,12 @@ const maxFeeds = 3
// maxSubreddits is how many suggested subreddits Fill puts in the box.
const maxSubreddits = 5
// SubredditCheck looks a subreddit up on Reddit. It returns reddit.ErrNotFound
// or reddit.ErrForbidden for one that doesn't exist or is private.
type SubredditCheck func(ctx context.Context, name string) (*reddit.Subreddit, error)
// Suggestion is a subreddit the AI suggested, and what Reddit said about it.
// Suggestion is a subreddit the AI suggested. Reddit can't be asked
// whether it exists, so the user looks before posting there.
type Suggestion struct {
Name string
Why string // the model's reason
Info *reddit.Subreddit // nil if not checked
Kept bool // put in the Subreddits box
Problem string // why it was left out, or why it's unchecked
Name string
Why string // the model's reason
Kept bool // put in the Subreddits box; false: more than enough already
}
// FillResult says what Fill did.
@@ -47,7 +41,7 @@ type FillResult struct {
// there is one), keywords and hashtags. If the site links to no subreddit,
// the model suggests some, and check (if not nil) drops the ones that don't
// exist or that can't be posted to; models invent believable names.
func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours *profile.Profile, check SubredditCheck) (*FillResult, error) {
func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours *profile.Profile) (*FillResult, error) {
res := &FillResult{}
st, err := site.Read(ctx, siteURL, "Supermarket/1 (inventory draft)")
if err != nil {
@@ -125,16 +119,14 @@ func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours
var keep []string
seen := map[string]bool{}
for _, sub := range d.Subreddits {
name := reddit.CleanName(sub.Name)
name := cleanSubreddit(sub.Name)
if name == "" || seen[strings.ToLower(name)] {
continue
}
seen[strings.ToLower(name)] = true
sg := checkSubreddit(ctx, check, name, sub.Why)
if sg.Kept && len(keep) < maxSubreddits {
keep = append(keep, sg.Name)
} else if sg.Kept {
sg.Kept, sg.Problem = false, "more than enough already"
sg := Suggestion{Name: name, Why: strings.TrimSpace(sub.Why), Kept: len(keep) < maxSubreddits}
if sg.Kept {
keep = append(keep, name)
}
res.Suggestions = append(res.Suggestions, sg)
}
@@ -143,34 +135,26 @@ func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours
return res, nil
}
// checkSubreddit asks Reddit about a suggested subreddit. One Reddit can't
// be asked about (no keys, rate limit) is kept, marked unchecked.
func checkSubreddit(ctx context.Context, check SubredditCheck, name, why string) Suggestion {
sg := Suggestion{Name: name, Why: strings.TrimSpace(why), Kept: true}
if check == nil {
sg.Problem = "not checked"
return sg
// cleanSubreddit turns "r/selfhosted" or a subreddit URL into
// "selfhosted", and drops what can't be a subreddit's name.
func cleanSubreddit(s string) string {
s = strings.TrimSpace(s)
if i := strings.Index(s, "/r/"); i >= 0 {
s = s[i+3:]
}
info, err := check(ctx, name)
switch {
case errors.Is(err, reddit.ErrNotFound):
sg.Kept, sg.Problem = false, "doesn't exist, or was banned"
case errors.Is(err, reddit.ErrForbidden):
sg.Kept, sg.Problem = false, "private"
case err != nil:
sg.Problem = "not checked: " + err.Error()
case info.Type == "private":
sg.Kept, sg.Problem = false, "private"
case info.Over18:
sg.Kept, sg.Problem = false, "marked 18+"
case info.Type == "restricted" || info.Type == "archived":
sg.Kept, sg.Problem = false, info.Type+": only approved accounts can post"
default:
sg.Name, sg.Info = info.Name, info // Reddit's spelling of the name
s = strings.TrimPrefix(s, "r/")
if i := strings.IndexAny(s, "/?#"); i >= 0 {
s = s[:i]
}
return sg
if !subredditName.MatchString(s) {
return ""
}
return s
}
// subredditName is what Reddit allows in a subreddit's name.
var subredditName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_]{1,20}$`)
const fillSystem = `You fill in an entry in a company's marketing inventory: another company or project it posts about, as a partner, a competitor, or one to watch. The marketing team reviews and corrects what you write.
Rules:
@@ -185,7 +169,7 @@ Rules:
Without a company profile, leave talking_points empty.
- keywords: up to eight phrases they own or compete on.
- hashtags: up to five, only ones their pages use or that name them or their product.
- subreddits: up to eight subreddits where talking about them would reach the company's audience: for a partner, where their users and the company's customers talk; for a competitor, where people compare or ask about tools like theirs; for one to watch, where their field is discussed. Names without r/, real subreddits you're confident exist, active and on topic; general ones (like technology) only if nothing narrower fits. why: one short phrase on who is there. They'll be checked against Reddit before use.`
- subreddits: up to eight subreddits where talking about them would reach the company's audience: for a partner, where their users and the company's customers talk; for a competitor, where people compare or ask about tools like theirs; for one to watch, where their field is discussed. Names without r/, real subreddits you're confident exist, active and on topic; general ones (like technology) only if nothing narrower fits. why: one short phrase on who is there. The team looks at each on Reddit before posting there.`
func fillPrompt(e *Entry, ours *profile.Profile, st *site.Site) string {
var b strings.Builder
+9 -38
View File
@@ -3,7 +3,6 @@ package inventory
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -11,7 +10,6 @@ import (
"testing"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/profile"
)
@@ -52,7 +50,7 @@ func TestFillKeepsWhatWasTyped(t *testing.T) {
}}
e := &Entry{Name: "Rival", Relationship: Competitor, TwitterHandle: "typed"}
ours := &profile.Profile{Name: "Acme", Description: "Self-hosted widgets."}
res, err := Fill(context.Background(), fake, e, srv.URL, ours, nil)
res, err := Fill(context.Background(), fake, e, srv.URL, ours)
if err != nil {
t.Fatal(err)
}
@@ -83,7 +81,7 @@ func TestFillSkipsTheModelWhenNothingIsLeft(t *testing.T) {
fake := &fakeAI{}
e := &Entry{Name: "Rival", Relationship: Partner, Description: "d", TalkingPoints: "t",
Keywords: []string{"k"}, Hashtags: []string{"#h"}, Subreddits: []string{"selfhosted"}}
if _, err := Fill(context.Background(), fake, e, srv.URL, nil, nil); err != nil {
if _, err := Fill(context.Background(), fake, e, srv.URL, nil); err != nil {
t.Fatal(err)
}
if fake.calls != 0 {
@@ -94,58 +92,31 @@ func TestFillSkipsTheModelWhenNothingIsLeft(t *testing.T) {
}
}
func TestFillChecksSuggestedSubreddits(t *testing.T) {
func TestFillSuggestsSubreddits(t *testing.T) {
srv := rivalSite(t)
fake := &fakeAI{reply: map[string]any{
"name": "", "description": "", "talking_points": "", "keywords": []string{}, "hashtags": []string{},
"subreddits": []map[string]string{
{"name": "r/selfhosted", "why": "self-hosters"},
{"name": "SelfHosted", "why": "again"},
{"name": "madeupwidgets", "why": "invented"},
{"name": "secretclub", "why": "private"},
{"name": "announcements", "why": "restricted"},
{"name": "homelab", "why": "home servers"},
{"name": "slowreddit", "why": "rate limited"},
{"name": "not a name!", "why": "junk"},
{"name": "https://www.reddit.com/r/homelab/", "why": "home servers"},
{"name": "one", "why": ""}, {"name": "two", "why": ""}, {"name": "three", "why": ""}, {"name": "four", "why": ""},
},
}}
check := func(_ context.Context, name string) (*reddit.Subreddit, error) {
switch name {
case "selfhosted":
return &reddit.Subreddit{Name: "selfhosted", Type: "public", Subscribers: 500000}, nil
case "homelab":
return &reddit.Subreddit{Name: "homelab", Type: "public"}, nil
case "secretclub":
return nil, reddit.ErrForbidden
case "announcements":
return &reddit.Subreddit{Name: "announcements", Type: "restricted"}, nil
case "slowreddit":
return nil, errors.New("rate limited")
}
return nil, reddit.ErrNotFound
}
e := &Entry{Name: "Rival", Relationship: Partner}
res, err := Fill(context.Background(), fake, e, srv.URL, nil, check)
res, err := Fill(context.Background(), fake, e, srv.URL, nil)
if err != nil {
t.Fatal(err)
}
if got := strings.Join(e.Subreddits, ","); got != "selfhosted,homelab,slowreddit" {
if got := strings.Join(e.Subreddits, ","); got != "selfhosted,homelab,one,two,three" {
t.Errorf("subreddits = %q", got)
}
var notes []string
for _, sg := range res.Suggestions {
notes = append(notes, fmt.Sprintf("%s:%v", sg.Name, sg.Kept))
}
if got := strings.Join(notes, " "); got != "selfhosted:true madeupwidgets:false secretclub:false announcements:false homelab:true slowreddit:true" {
if got := strings.Join(notes, " "); got != "selfhosted:true homelab:true one:true two:true three:true four:false" {
t.Errorf("suggestions = %s", got)
}
if res.Suggestions[5].Problem == "" || res.Suggestions[0].Info == nil {
t.Errorf("unchecked one should say so, checked one should carry its info: %+v", res.Suggestions)
}
// Without a check, suggestions are kept, marked unchecked.
e = &Entry{Name: "Rival", Relationship: Partner}
res, _ = Fill(context.Background(), fake, e, srv.URL, nil, nil)
if len(e.Subreddits) != 5 || !strings.Contains(res.Suggestions[0].Problem, "not checked") {
t.Errorf("unchecked: %q %+v", e.Subreddits, res.Suggestions)
}
}
+260
View File
@@ -0,0 +1,260 @@
package inventory
import (
"context"
"fmt"
"strings"
"sync"
"time"
"supermarket/internal/ai"
"supermarket/internal/db"
"supermarket/internal/profile"
"supermarket/internal/site"
)
// What happened to an entry of a list imported with FillImport.
const (
FillAdded = "added"
FillUpdated = "updated"
FillSkipped = "skipped"
FillFailed = "failed"
)
// FillLine is what happened to one entry of the list.
type FillLine struct {
Site string `json:"site,omitempty"` // the address it was filled in from
Name string `json:"name,omitempty"`
ID int64 `json:"id,omitempty"` // the entry in the Market, if saved
Outcome string `json:"outcome"`
Note string `json:"note,omitempty"` // why it was skipped or failed, or what went wrong on the way
Filled []string `json:"filled,omitempty"`
}
// FillOptions are how FillImport works.
type FillOptions struct {
Client ai.Client
Ours *profile.Profile // the user's own company, for talking points; may be nil
Overwrite bool // replace entries already in the Market
// Room says why the Market can't take another entry, given how many it
// has (the plan's limit), or nil. nil: no limit.
Room func(existing int) error
Workers int // websites read at once; 0: fillWorkers
Timeout time.Duration // for each entry; 0: fillTimeout
// Done is told about each entry as it's done, one at a time.
Done func(FillLine)
}
const (
fillWorkers = 3
fillTimeout = 4 * time.Minute
)
// FillImport adds the entries to the Market, each first filled in from
// its website, as Fill does on the New entry page: what the list gives is
// kept, the empty fields are filled. An entry without a website is saved as
// it is.
//
// Entries already in the Market, by name or by website, are skipped before
// their website is read (nothing spent on them) unless Overwrite is set; a
// name found only by filling in is checked again before saving.
func FillImport(ctx context.Context, d *db.DB, entries []Entry, o FillOptions) []FillLine {
if o.Workers <= 0 {
o.Workers = fillWorkers
}
if o.Timeout <= 0 {
o.Timeout = fillTimeout
}
var (
mu sync.Mutex // the maps, count, lines, and saving
lines []FillLine
)
finish := func(l FillLine) { // under mu
lines = append(lines, l)
if o.Done != nil {
o.Done(l)
}
}
existing, err := List(d, "")
if err != nil {
finish(FillLine{Outcome: FillFailed, Note: err.Error()})
return lines
}
count := len(existing)
byName := map[string]int64{}
bySite := map[string]int64{}
for _, e := range existing {
byName[strings.ToLower(e.Name)] = e.ID
for _, w := range e.Websites {
if k := siteKey(w); k != "" {
bySite[k] = e.ID
}
}
}
// save saves e (under mu), as the entry id if not 0.
save := func(e *Entry, id int64, l FillLine) {
l.Name = strings.TrimSpace(e.Name)
if l.Name == "" {
l.Outcome = FillFailed
if l.Note == "" {
l.Note = "their name wasn't found on the website"
}
finish(l)
return
}
if other, ok := byName[strings.ToLower(l.Name)]; ok && other != id {
if id != 0 || !o.Overwrite {
l.Outcome, l.Note, l.ID = FillSkipped, "already in the Market", other
finish(l)
return
}
id = other
}
if id == 0 && o.Room != nil {
if err := o.Room(count); err != nil {
l.Outcome, l.Note = FillFailed, err.Error()
finish(l)
return
}
}
e.ID = id
if err := Save(d, e); err != nil {
l.Outcome, l.Note = FillFailed, err.Error()
finish(l)
return
}
l.ID = e.ID
if id != 0 {
l.Outcome = FillUpdated
} else {
l.Outcome = FillAdded
count++
}
byName[strings.ToLower(e.Name)] = e.ID
for _, w := range e.Websites {
if k := siteKey(w); k != "" {
bySite[k] = e.ID
}
}
finish(l)
}
// First what's known without reading a website: what's already there,
// listed twice, or can't be read.
type job struct {
e Entry
id int64
}
var queue []job
seen := map[string]bool{}
mu.Lock()
for _, e := range entries {
e.Websites = profile.CleanList(e.Websites)
l := FillLine{Name: strings.TrimSpace(e.Name)}
if len(e.Websites) > 0 {
l.Site = e.Websites[0]
}
if l.Site == "" && l.Name == "" {
l.Outcome, l.Note = FillFailed, "no website or name"
finish(l)
continue
}
if l.Site != "" {
if _, err := site.Normalize(l.Site); err != nil {
l.Outcome, l.Note = FillFailed, err.Error()
finish(l)
continue
}
}
var keys []string
if l.Name != "" {
keys = append(keys, "name:"+strings.ToLower(l.Name))
}
for _, w := range e.Websites {
if k := siteKey(w); k != "" {
keys = append(keys, "site:"+k)
}
}
twice := false
for _, k := range keys {
twice = twice || seen[k]
seen[k] = true
}
if twice {
l.Outcome, l.Note = FillSkipped, "listed twice"
finish(l)
continue
}
id, found := byName[strings.ToLower(l.Name)]
if !found {
for _, w := range e.Websites {
if id, found = bySite[siteKey(w)]; found {
break
}
}
}
if found && !o.Overwrite {
l.Outcome, l.Note, l.ID = FillSkipped, "already in the Market", id
finish(l)
continue
}
if l.Site == "" {
save(&e, id, l) // nothing to fill in from
continue
}
queue = append(queue, job{e, id})
}
mu.Unlock()
work := make(chan job)
var wg sync.WaitGroup
for range min(o.Workers, len(queue)) {
wg.Add(1)
go func() {
defer wg.Done()
for j := range work {
e := j.e
l := FillLine{Site: e.Websites[0]}
fctx, cancel := context.WithTimeout(ctx, o.Timeout)
res, err := Fill(fctx, o.Client, &e, l.Site, o.Ours)
cancel()
l.Filled = res.Filled
if err != nil {
if strings.TrimSpace(e.Name) != "" {
l.Note = "only partly filled in: " + err.Error()
} else {
l.Note = err.Error()
}
}
mu.Lock()
save(&e, j.id, l)
mu.Unlock()
}
}()
}
for _, j := range queue {
if ctx.Err() != nil {
mu.Lock()
finish(FillLine{Site: j.e.Websites[0], Name: j.e.Name, Outcome: FillFailed, Note: "stopped: " + ctx.Err().Error()})
mu.Unlock()
continue
}
work <- j
}
close(work)
wg.Wait()
return lines
}
// siteKey is a website's address to compare by: host without www., and
// path, without the scheme or a trailing slash.
func siteKey(raw string) string {
u, err := site.Normalize(raw)
if err != nil {
return ""
}
host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
return fmt.Sprintf("%s%s", host, strings.TrimRight(u.Path, "/"))
}
+134
View File
@@ -0,0 +1,134 @@
package inventory
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"testing"
"supermarket/internal/db"
)
func TestParseYAMLWebsiteOnly(t *testing.T) {
doc := "- url: https://a.example\n relationship: competitor\n- website: b.example\n- https://c.example\n" +
"- name: D\n url: https://d.example\n websites: [https://d.example, https://blog.d.example]\n"
entries, err := ParseYAML([]byte(doc), Partner)
if err != nil || len(entries) != 4 {
t.Fatalf("%+v %v", entries, err)
}
var got []string
for _, e := range entries {
got = append(got, fmt.Sprintf("%s|%s|%s", e.Name, e.Relationship, strings.Join(e.Websites, ",")))
}
want := "|competitor|https://a.example |partner|b.example |partner|https://c.example D|partner|https://d.example,https://blog.d.example"
if strings.Join(got, " ") != want {
t.Errorf("got %s\nwant %s", strings.Join(got, " "), want)
}
// Exported entries don't grow a url:.
out, _ := ExportYAML(entries[:1])
if strings.Contains(string(out), "url:") {
t.Errorf("export:\n%s", out)
}
}
func TestParseYAMLDashWithoutSpace(t *testing.T) {
doc := "inventory:\n-url: https://listmonk.app/\n-url: https://matomo.org/\n relationship: competitor\n"
entries, err := ParseYAML([]byte(doc), Partner)
if err != nil || len(entries) != 2 || entries[0].Websites[0] != "https://listmonk.app/" ||
entries[0].Relationship != Partner || entries[1].Relationship != Competitor {
t.Fatalf("%+v %v", entries, err)
}
// Still not a list: the error says what one looks like.
if _, err := ParseYAML([]byte("inventory:\n url: [\n"), Partner); err == nil || !strings.Contains(err.Error(), "a dash and a space") {
t.Errorf("error: %v", err)
}
}
func testDB(t *testing.T) *db.DB {
t.Helper()
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
return d
}
func TestFillImport(t *testing.T) {
d := testDB(t)
srv := rivalSite(t)
if err := Save(d, &Entry{Name: "Old", Relationship: Partner, Websites: []string{"https://www.old.invalid/"}}); err != nil {
t.Fatal(err)
}
fake := &fakeAI{reply: map[string]any{
"name": "Rival Inc", "description": "Hosted widgets.", "talking_points": "", "keywords": []string{}, "hashtags": []string{},
"subreddits": []map[string]string{},
}}
in := []Entry{
{Websites: []string{srv.URL}, Relationship: Competitor},
{Websites: []string{srv.URL + "/"}, Relationship: Partner}, // the same site
{Websites: []string{"old.invalid"}, Relationship: Partner}, // already there: never read
{Name: "Plain", Relationship: Watch}, // nothing to fill in from
{Websites: []string{"ftp://nope"}},
{},
}
var told int
lines := FillImport(context.Background(), d, in, FillOptions{Client: fake, Workers: 1, Done: func(FillLine) { told++ }})
var got []string
for _, l := range lines {
got = append(got, l.Name+":"+l.Outcome)
}
// Those known without reading a site first, then the ones filled in.
if sum := strings.Join(got, " "); sum != ":skipped :skipped Plain:added :failed :failed Rival Inc:added" {
t.Errorf("lines = %q", sum)
}
if told != len(in) || fake.calls != 1 {
t.Errorf("told %d, model called %d times", told, fake.calls)
}
if lines[0].Note != "listed twice" || lines[1].Note != "already in the Market" || lines[1].ID == 0 {
t.Errorf("notes: %+v %+v", lines[0], lines[1])
}
e, _ := Get(d, lines[len(lines)-1].ID)
if e == nil || e.Relationship != Competitor || e.Description != "Hosted widgets." || e.TwitterHandle != "rivalhq" ||
e.Websites[0] != srv.URL || e.MentionPolicy != MentionCategory {
t.Errorf("saved: %+v", e)
}
// Again: already there, by website, before reading it.
lines = FillImport(context.Background(), d, in[:1], FillOptions{Client: fake})
if len(lines) != 1 || lines[0].Outcome != FillSkipped || fake.calls != 1 {
t.Errorf("again: %+v, %d calls", lines, fake.calls)
}
// Replacing it reads it again, and keeps its id.
id := e.ID
lines = FillImport(context.Background(), d, in[:1], FillOptions{Client: fake, Overwrite: true})
if len(lines) != 1 || lines[0].Outcome != FillUpdated || lines[0].ID != id || fake.calls != 2 {
t.Errorf("overwrite: %+v, %d calls", lines, fake.calls)
}
}
func TestFillImportLimitsAndFailures(t *testing.T) {
d := testDB(t)
srv := rivalSite(t)
fake := &fakeAI{reply: map[string]any{"name": "", "description": "", "talking_points": "", "keywords": []string{},
"hashtags": []string{}, "subreddits": []map[string]string{}}}
full := errors.New("the plan is full")
lines := FillImport(context.Background(), d, []Entry{{Name: "Named", Websites: []string{srv.URL}, Relationship: Partner}},
FillOptions{Client: fake, Room: func(int) error { return full }})
if len(lines) != 1 || lines[0].Outcome != FillFailed || lines[0].Note != full.Error() {
t.Errorf("limit: %+v", lines)
}
// No name typed and none found: not saved.
lines = FillImport(context.Background(), d, []Entry{{Websites: []string{srv.URL}, Relationship: Partner}}, FillOptions{Client: fake})
if len(lines) != 1 || lines[0].Outcome != FillFailed || !strings.Contains(lines[0].Note, "name wasn't found") {
t.Errorf("no name: %+v", lines)
}
// A site that can't be read, with a name typed: saved, with what went wrong.
lines = FillImport(context.Background(), d, []Entry{{Name: "Gone", Websites: []string{srv.URL + "/missing"}, Relationship: Watch}},
FillOptions{Client: fake})
if len(lines) != 1 || lines[0].Outcome != FillAdded || !strings.Contains(lines[0].Note, "only partly") {
t.Errorf("unreadable: %+v", lines)
}
}
+64 -8
View File
@@ -8,6 +8,7 @@ import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
"time"
@@ -54,6 +55,41 @@ type Entry struct {
Prices []Price `json:"prices,omitempty" yaml:"prices,omitempty"` // their plans' prices, as checked
}
// UnmarshalYAML reads an entry as written, and two shorter forms for a
// list to be filled in from the websites: `url:` or `website:` for one
// address, and a bare address in place of the whole entry.
func (e *Entry) UnmarshalYAML(n *yaml.Node) error {
if n.Kind == yaml.ScalarNode {
*e = Entry{Websites: []string{n.Value}}
return nil
}
type plain Entry // without this method
var aux struct {
plain `yaml:",inline"`
URL string `yaml:"url"`
Website string `yaml:"website"`
}
if err := n.Decode(&aux); err != nil {
return err
}
*e = Entry(aux.plain)
for _, u := range []string{aux.Website, aux.URL} {
if u = strings.TrimSpace(u); u != "" && !containsFold(e.Websites, u) {
e.Websites = append([]string{u}, e.Websites...)
}
}
return nil
}
func containsFold(list []string, s string) bool {
for _, v := range list {
if strings.EqualFold(strings.TrimSpace(v), s) {
return true
}
}
return false
}
// Normalize tidies an entry and checks it.
func (e *Entry) Normalize() error {
e.Name = strings.TrimSpace(e.Name)
@@ -221,17 +257,19 @@ type ImportResult struct {
// ParseYAML reads entries from YAML: a plain list, or a document with an
// `inventory:` or (old config) `applications:` list. defaultRel is used for
// entries without a relationship.
//
// A list typed by hand with no space after the dashes (`-url: …`) is read
// as if it had them.
func ParseYAML(data []byte, defaultRel string) ([]Entry, error) {
var list []Entry
if err := yaml.Unmarshal(data, &list); err != nil {
var doc struct {
Inventory []Entry `yaml:"inventory"`
Applications []Entry `yaml:"applications"`
list, err := parseList(data)
if err != nil {
fixed := dashNoSpace.ReplaceAll(data, []byte("$1- $2"))
if string(fixed) == string(data) {
return nil, err
}
if err2 := yaml.Unmarshal(data, &doc); err2 != nil {
return nil, fmt.Errorf("not a Market list: %w", err2)
if list, err = parseList(fixed); err != nil {
return nil, err
}
list = append(doc.Inventory, doc.Applications...)
}
for i := range list {
if strings.TrimSpace(list[i].Relationship) == "" {
@@ -276,6 +314,24 @@ func Import(d *db.DB, entries []Entry, overwrite bool) ImportResult {
return r
}
// dashNoSpace is a list item's dash with no space before its first key.
var dashNoSpace = regexp.MustCompile(`(?m)^([ \t]*)-([A-Za-z_]+:)`)
func parseList(data []byte) ([]Entry, error) {
var list []Entry
if err := yaml.Unmarshal(data, &list); err == nil {
return list, nil
}
var doc struct {
Inventory []Entry `yaml:"inventory"`
Applications []Entry `yaml:"applications"`
}
if err := yaml.Unmarshal(data, &doc); err != nil {
return nil, fmt.Errorf("not a Market list (each entry starts with a dash and a space, as in \"- url: https://…\"): %w", err)
}
return append(doc.Inventory, doc.Applications...), nil
}
// ExportYAML writes the entries in the format ParseYAML reads.
func ExportYAML(entries []Entry) ([]byte, error) {
return yaml.Marshal(map[string][]Entry{"inventory": entries})
+255
View File
@@ -0,0 +1,255 @@
// Package jobs lets several copies of the app share one database without
// doing the same work twice: a named lock, held as a lease in the
// database, renewed while the work runs and lapsing if its copy stops.
// It works the same on SQLite (one copy) and Postgres (several).
//
// Each copy also checks in, so one starting up can tell whether others
// are running (and so whether work marked "running" is really
// interrupted).
package jobs
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"log/slog"
"os"
"sync"
"time"
"supermarket/internal/db"
)
// Timing. A lease lasts Lease and is renewed every Renew; a copy that
// hasn't checked in for Gone is taken to have stopped.
const (
Lease = 2 * time.Minute
Renew = 30 * time.Second
CheckIn = 30 * time.Second
Gone = 2 * time.Minute
forgetDay = 24 * time.Hour
)
// ErrBusy means another copy, or another part of this one, holds the lock.
var ErrBusy = errors.New("already under way")
// timeFormat sorts as text: fixed width, UTC.
const timeFormat = "2006-01-02T15:04:05.000Z"
func ts(t time.Time) string { return t.UTC().Format(timeFormat) }
// Runner is this copy of the app.
type Runner struct {
d *db.DB
id string
log *slog.Logger
now func() time.Time // tests
}
// New registers this copy of the app.
func New(d *db.DB, version string, log *slog.Logger) (*Runner, error) {
b := make([]byte, 6)
if _, err := rand.Read(b); err != nil {
return nil, err
}
host, _ := os.Hostname()
r := &Runner{d: d, id: hex.EncodeToString(b), log: log, now: time.Now}
now := ts(r.now())
if _, err := d.Exec(`INSERT INTO instances (id, host, version, started_at, seen_at) VALUES (?, ?, ?, ?, ?)`,
r.id, host, version, now, now); err != nil {
return nil, err
}
return r, nil
}
// ID is this copy's.
func (r *Runner) ID() string { return r.id }
// Stop removes this copy's check-in and frees its locks, when it stops.
func (r *Runner) Stop() {
r.d.Exec(`DELETE FROM instances WHERE id = ?`, r.id)
r.d.Exec(`UPDATE locks SET holder = '', expires_at = '' WHERE holder LIKE ?`, r.id+":%")
}
// CheckIns keeps this copy's check-in current until ctx ends. Copies gone
// a day are forgotten.
func (r *Runner) CheckIns(ctx context.Context) {
tick := time.NewTicker(CheckIn)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
now := r.now()
if _, err := r.d.Exec(`UPDATE instances SET seen_at = ? WHERE id = ?`, ts(now), r.id); err != nil {
r.log.Warn("jobs: checking in", "err", err)
}
r.d.Exec(`DELETE FROM instances WHERE seen_at < ?`, ts(now.Add(-forgetDay)))
}
}
}
// Alone says whether no other copy of the app has checked in lately.
func (r *Runner) Alone() (bool, error) {
var n int
err := r.d.QueryRow(`SELECT count(*) FROM instances WHERE id != ? AND seen_at >= ?`, r.id, ts(r.now().Add(-Gone))).Scan(&n)
return n == 0, err
}
// Instance is a copy of the app that's running.
type Instance struct {
ID, Host, Version string
Started, Seen time.Time
This bool
}
// Instances are the copies that have checked in lately, this one first.
func (r *Runner) Instances() ([]Instance, error) {
rows, err := r.d.Query(`SELECT id, host, version, started_at, seen_at FROM instances WHERE seen_at >= ? OR id = ? ORDER BY started_at`,
ts(r.now().Add(-Gone)), r.id)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Instance
for rows.Next() {
var in Instance
var started, seen string
if err := rows.Scan(&in.ID, &in.Host, &in.Version, &started, &seen); err != nil {
return nil, err
}
in.Started, _ = time.Parse(timeFormat, started)
in.Seen, _ = time.Parse(timeFormat, seen)
in.This = in.ID == r.id
if in.This {
out = append([]Instance{in}, out...)
} else {
out = append(out, in)
}
}
return out, rows.Err()
}
// Held is a lock someone holds.
type Held struct {
Name, Instance string
Since time.Time
}
// Locks are the locks held now.
func (r *Runner) Locks() ([]Held, error) {
rows, err := r.d.Query(`SELECT name, holder, taken_at FROM locks WHERE holder != '' AND expires_at >= ? ORDER BY name`, ts(r.now()))
if err != nil {
return nil, err
}
defer rows.Close()
var out []Held
for rows.Next() {
var h Held
var holder, since string
if err := rows.Scan(&h.Name, &holder, &since); err != nil {
return nil, err
}
if i := len(holder) - 13; i > 0 { // <instance>:<12 hex>
h.Instance = holder[:i]
}
h.Since, _ = time.Parse(timeFormat, since)
out = append(out, h)
}
return out, rows.Err()
}
// TryLock takes the lock name if it's free (or its holder's lease
// lapsed), or returns ErrBusy. The returned context ends when release is
// called, when ctx ends, or if the lease is lost (the database couldn't
// renew it in time, or another copy took it after it lapsed): the work
// should stop then.
func (r *Runner) TryLock(ctx context.Context, name string) (context.Context, func(), error) {
b := make([]byte, 6)
if _, err := rand.Read(b); err != nil {
return nil, nil, err
}
holder := r.id + ":" + hex.EncodeToString(b)
now := r.now()
if _, err := r.d.Exec(`INSERT INTO locks (name) VALUES (?) ON CONFLICT DO NOTHING`, name); err != nil {
return nil, nil, err
}
res, err := r.d.Exec(`UPDATE locks SET holder = ?, taken_at = ?, expires_at = ? WHERE name = ? AND (holder = '' OR expires_at < ?)`,
holder, ts(now), ts(now.Add(Lease)), name, ts(now))
if err != nil {
return nil, nil, err
}
if n, err := res.RowsAffected(); err != nil {
return nil, nil, err
} else if n == 0 {
return nil, nil, ErrBusy
}
wctx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
go func() { // renew while held
tick := time.NewTicker(Renew)
defer tick.Stop()
for {
select {
case <-done:
return
case <-wctx.Done():
return
case <-tick.C:
res, err := r.d.Exec(`UPDATE locks SET expires_at = ? WHERE name = ? AND holder = ?`, ts(r.now().Add(Lease)), name, holder)
n := int64(0)
if err == nil {
n, _ = res.RowsAffected()
}
if n == 0 {
r.log.Warn("jobs: lost the lock; stopping the work", "lock", name, "err", err)
cancel()
return
}
}
}
}()
var once sync.Once
release := func() {
once.Do(func() {
close(done)
cancel()
if _, err := r.d.Exec(`UPDATE locks SET holder = '', expires_at = '' WHERE name = ? AND holder = ?`, name, holder); err != nil {
r.log.Warn("jobs: releasing a lock", "lock", name, "err", err)
}
})
}
return wctx, release, nil
}
// Lock waits for the lock name until ctx ends.
func (r *Runner) Lock(ctx context.Context, name string) (context.Context, func(), error) {
for {
wctx, release, err := r.TryLock(ctx, name)
if !errors.Is(err, ErrBusy) {
return wctx, release, err
}
select {
case <-ctx.Done():
return nil, nil, ErrBusy
case <-time.After(250 * time.Millisecond):
}
}
}
// Do runs fn under the lock name if it's free, and says whether it ran.
// A busy lock isn't an error: another copy is doing the work.
func (r *Runner) Do(ctx context.Context, name string, fn func(ctx context.Context)) (bool, error) {
wctx, release, err := r.TryLock(ctx, name)
if errors.Is(err, ErrBusy) {
return false, nil
}
if err != nil {
return false, err
}
defer release()
fn(wctx)
return true, nil
}
+169
View File
@@ -0,0 +1,169 @@
package jobs
import (
"context"
"errors"
"io"
"log/slog"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
"supermarket/internal/db"
)
func setup(t *testing.T) *db.DB {
t.Helper()
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
return d
}
var quiet = slog.New(slog.NewTextHandler(io.Discard, nil))
func runner(t *testing.T, d *db.DB) *Runner {
t.Helper()
r, err := New(d, "test", quiet)
if err != nil {
t.Fatal(err)
}
return r
}
// Two copies of the app: only one does a job at a time.
func TestOneAtATime(t *testing.T) {
d := setup(t)
a, b := runner(t, d), runner(t, d)
ctx := context.Background()
wctx, release, err := a.TryLock(ctx, "job:seo")
if err != nil {
t.Fatal(err)
}
if _, _, err := b.TryLock(ctx, "job:seo"); !errors.Is(err, ErrBusy) {
t.Fatalf("the other copy took it: %v", err)
}
if _, _, err := a.TryLock(ctx, "job:seo"); !errors.Is(err, ErrBusy) { // not re-entrant, even in one copy
t.Fatalf("taken twice in one copy: %v", err)
}
if ran, _ := b.Do(ctx, "job:seo", func(context.Context) {}); ran {
t.Fatal("Do ran while busy")
}
held, _ := b.Locks()
if len(held) != 1 || held[0].Name != "job:seo" || held[0].Instance != a.ID() {
t.Fatalf("held: %+v", held)
}
release()
if wctx.Err() == nil {
t.Error("the work's context goes on after release")
}
if ran, err := b.Do(ctx, "job:seo", func(context.Context) {}); !ran || err != nil {
t.Fatalf("free again: %v %v", ran, err)
}
// Many goroutines, two copies: never two at once.
var inside, most, runs int32
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
r := a
if i%2 == 1 {
r = b
}
go func() {
defer wg.Done()
_, release, err := r.Lock(ctx, "outreach:send")
if err != nil {
t.Error(err)
return
}
n := atomic.AddInt32(&inside, 1)
for {
m := atomic.LoadInt32(&most)
if n <= m || atomic.CompareAndSwapInt32(&most, m, n) {
break
}
}
time.Sleep(2 * time.Millisecond)
atomic.AddInt32(&inside, -1)
atomic.AddInt32(&runs, 1)
release()
}()
}
wg.Wait()
if most != 1 || runs != 20 {
t.Errorf("at most %d at once, %d runs", most, runs)
}
}
// A copy that stops holding a lock: once its lease lapses, another takes it.
func TestLapsedLease(t *testing.T) {
d := setup(t)
a, b := runner(t, d), runner(t, d)
clock := time.Now()
a.now = func() time.Time { return clock }
b.now = func() time.Time { return clock }
if _, _, err := a.TryLock(context.Background(), "job:metrics"); err != nil { // never released: a crashed
t.Fatal(err)
}
if _, _, err := b.TryLock(context.Background(), "job:metrics"); !errors.Is(err, ErrBusy) {
t.Fatal("taken before the lease lapsed")
}
clock = clock.Add(Lease + time.Second)
if _, release, err := b.TryLock(context.Background(), "job:metrics"); err != nil {
t.Fatalf("not taken after it lapsed: %v", err)
} else {
release()
}
}
// Lock gives up when its context ends.
func TestLockWaits(t *testing.T) {
d := setup(t)
a := runner(t, d)
_, release, _ := a.TryLock(context.Background(), "x")
defer release()
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
if _, _, err := a.Lock(ctx, "x"); !errors.Is(err, ErrBusy) {
t.Fatalf("lock: %v", err)
}
}
// Copies see each other; one that stops checking in is gone.
func TestInstances(t *testing.T) {
d := setup(t)
a := runner(t, d)
if alone, err := a.Alone(); !alone || err != nil {
t.Fatalf("alone: %v %v", alone, err)
}
b := runner(t, d)
if alone, _ := a.Alone(); alone {
t.Fatal("doesn't see the other copy")
}
list, _ := a.Instances()
if len(list) != 2 || !list[0].This || list[1].ID != b.ID() || list[1].Version != "test" {
t.Fatalf("instances: %+v", list)
}
a.now = func() time.Time { return time.Now().Add(Gone + time.Minute) } // b hasn't checked in since
if alone, _ := a.Alone(); !alone {
t.Error("a stopped copy still counts")
}
// Stopping: the check-in and the copy's locks go.
if _, _, err := b.TryLock(context.Background(), "job:seo"); err != nil {
t.Fatal(err)
}
b.Stop()
a.now = time.Now
if held, _ := a.Locks(); len(held) != 0 {
t.Errorf("still held: %+v", held)
}
if list, _ := a.Instances(); len(list) != 1 {
t.Errorf("instances: %+v", list)
}
}
+282 -127
View File
@@ -5,7 +5,6 @@ package mcpserver
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
@@ -14,6 +13,7 @@ import (
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
@@ -25,27 +25,150 @@ import (
"supermarket/internal/profile"
)
// Handler returns the /mcp handler. Requests without "Authorization: Bearer
// <token>" are refused.
func Handler(d *db.DB, token, version string) http.Handler {
server := newServer(d, version)
h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server },
&mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true})
// Caller is the agent a request comes from, and what it may do.
type Caller struct {
ID int64
Name string
// Team is the agent's team, and DB its database (multi-tenant); nil:
// the one the Handler was given.
Team int64
DB *db.DB
// Can says whether the agent may read (act false) or change things in
// a module or scope (market, crm, …).
Can func(scope string, act bool) bool
// Before is asked before each tool call (a rate limit); an error
// refuses it. After hears how it went. Either may be nil.
Before func(ctx context.Context, tool string) error
After func(tool string, res *mcp.CallToolResult, err error, took time.Duration)
}
// Refusal is an Authenticator's error that says why, with an HTTP status
// (a paused agent: 403), rather than a plain 401.
type Refusal struct {
Status int
Reason string
}
func (r *Refusal) Error() string { return r.Reason }
// Authenticator finds the caller of a request from its bearer key; an
// error refuses it.
type Authenticator func(r *http.Request, key string) (*Caller, error)
// Handler returns the /mcp handler. Each request needs an agent's key
// ("Authorization: Bearer sm_…"), and is offered only the tools the
// agent's scopes allow.
//
// more adds the app's module tools for the caller (the web package has
// them, as they call what its pages call); nil for none.
func Handler(d *db.DB, version string, auth Authenticator, more func(*mcp.Server, *Caller)) http.Handler {
var mu sync.Mutex
// One server per agent and its scopes: tools know who calls them, and a
// change of scopes makes a new one.
servers := map[string]*mcp.Server{}
h := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
c, _ := r.Context().Value(callerKey{}).(*Caller)
sig := signature(c)
if c != nil {
sig = fmt.Sprintf("%d/%p/%s", c.ID, c.DB, sig)
}
mu.Lock()
defer mu.Unlock()
if srv, ok := servers[sig]; ok {
return srv
}
srv := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil)
td := d
if c != nil && c.DB != nil {
td = c.DB
}
addTools(srv, td, c)
if more != nil {
more(srv, c)
}
if c != nil {
srv.AddReceivingMiddleware(watch(c))
}
servers[sig] = srv
return srv
}, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true})
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || token == "" || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 {
key, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
var c *Caller
var err error
if ok && key != "" {
c, err = auth(r, strings.TrimSpace(key))
}
var refusal *Refusal
if errors.As(err, &refusal) {
http.Error(w, refusal.Reason, refusal.Status)
return
}
if !ok || key == "" || err != nil || c == nil {
w.Header().Set("WWW-Authenticate", `Bearer realm="supermarket"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
h.ServeHTTP(w, r)
h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), callerKey{}, c)))
})
}
type callerKey struct{}
// watch asks the caller's Before and tells its After about each tool call.
func watch(c *Caller) mcp.Middleware {
return func(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
p, ok := req.GetParams().(*mcp.CallToolParamsRaw)
if method != "tools/call" || !ok {
return next(ctx, method, req)
}
if c.Before != nil {
if err := c.Before(ctx, p.Name); err != nil {
return nil, err
}
}
start := time.Now()
res, err := next(ctx, method, req)
if c.After != nil {
out, _ := res.(*mcp.CallToolResult)
c.After(p.Name, out, err, time.Since(start))
}
return res, err
}
}
}
// scopes are what tools are offered by: each, read or act.
var scopes = []string{"content", "prospects", "seo", "sites", "metrics", "market", "crm"}
// signature names the tools a caller gets.
func signature(c *Caller) string {
if c == nil {
return "*"
}
var b strings.Builder
for _, sc := range scopes {
switch {
case c.Can(sc, true):
b.WriteString(sc + ":act,")
case c.Can(sc, false):
b.WriteString(sc + ":read,")
}
}
return b.String()
}
// can says whether the caller (nil: the local socket, everything) may use
// a scope.
func can(c *Caller, scope string, act bool) bool {
return c == nil || c.Can(scope, act)
}
func newServer(d *db.DB, version string) *mcp.Server {
server := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil)
addTools(server, d)
addTools(server, d, nil)
return server
}
@@ -159,7 +282,8 @@ type checkinArgs struct {
Note string `json:"note,omitempty" jsonschema:"a short note on anything that failed"`
}
func addTools(s *mcp.Server, d *db.DB) {
// addTools adds the tools the caller may use (nil: all).
func addTools(s *mcp.Server, d *db.DB, c *Caller) {
mcp.AddTool(s, &mcp.Tool{
Name: "profile_get",
Description: "The company profile: what the company sells, its products, target customers, voice, websites, social accounts and keywords.",
@@ -172,123 +296,154 @@ func addTools(s *mcp.Server, d *db.DB) {
return res, nil, err
})
mcp.AddTool(s, &mcp.Tool{
Name: "inventory_list",
Description: "The Market: partners (whose news we amplify), competitors (whom we position against) and projects we watch, with their accounts, keywords and talking points.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, args inventoryArgs) (*mcp.CallToolResult, any, error) {
entries, err := inventory.List(d, strings.ToLower(strings.TrimSpace(args.Relationship)))
if err != nil {
return nil, nil, err
}
if entries == nil {
entries = []inventory.Entry{}
}
res, err := jsonResult(entries)
return res, nil, err
})
mcp.AddTool(s, &mcp.Tool{
Name: "crm_pending_actions",
Description: "The CRM work Supermarket has queued for you: records to create in EspoCRM, and whether to copy recently " +
"changed CRM records back to Supermarket. Call it at the start of each CRM run and follow its instructions exactly.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ noArgs) (*mcp.CallToolResult, any, error) {
now := time.Now()
actions, err := crm.Claim(d, now, 25)
if err != nil {
return nil, nil, err
}
out := pendingResult{Instructions: crmInstructions, Actions: []pendingAction{}}
for _, a := range actions {
out.Actions = append(out.Actions, pendingAction{ID: a.ID, Do: a.Kind, Entity: a.Entity, Fields: a.Fields, FindExisting: a.Match})
}
due, since, err := crm.SyncDue(d, now)
if err != nil {
return nil, nil, err
}
if due {
if err := crm.StartSync(d, now); err != nil {
return nil, nil, err
}
req := &syncRequest{Entities: crm.SyncEntities, Fields: crmSyncFields}
if !since.IsZero() {
// A little overlap, so nothing changed during the last sync is missed.
req.ModifiedSince = since.Add(-10 * time.Minute).UTC().Format("2006-01-02 15:04:05")
}
out.Sync = req
}
res, err := jsonResult(out)
return res, nil, err
})
mcp.AddTool(s, &mcp.Tool{
Name: "crm_report_result",
Description: "Report the result of one action from crm_pending_actions: created (with the new record's id), existing (with the matching record's id), or failed (with the error).",
}, func(ctx context.Context, _ *mcp.CallToolRequest, args reportArgs) (*mcp.CallToolResult, any, error) {
err := crm.Report(d, args.ID, crm.Result{Outcome: strings.ToLower(strings.TrimSpace(args.Outcome)), EspoID: args.EspoID, Error: args.Error}, time.Now())
if err != nil {
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: err.Error()}}}, nil, nil
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "Recorded."}}}, nil, nil
})
mcp.AddTool(s, &mcp.Tool{
Name: "crm_ingest",
Description: "Send Supermarket the CRM records crm_pending_actions asked you to sync, in batches; set done=true on the last call.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, args ingestArgs) (*mcp.CallToolResult, any, error) {
entity := strings.TrimSpace(args.Entity)
known := false
for _, e := range crm.SyncEntities {
known = known || strings.EqualFold(e, entity)
if strings.EqualFold(e, entity) {
entity = e
}
}
if !known {
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{
Text: "entity must be one of " + strings.Join(crm.SyncEntities, ", ")}}}, nil, nil
}
now := time.Now()
var recs []crm.Record
skipped := 0
for _, f := range args.Records {
r, err := crm.RecordFrom(entity, f, now)
if can(c, "market", false) {
mcp.AddTool(s, &mcp.Tool{
Name: "inventory_list",
Description: "The Market: partners (whose news we amplify), competitors (whom we position against) and projects we watch, with their accounts, keywords and talking points.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, args inventoryArgs) (*mcp.CallToolResult, any, error) {
entries, err := inventory.List(d, strings.ToLower(strings.TrimSpace(args.Relationship)))
if err != nil {
skipped++
continue
}
recs = append(recs, r)
}
if err := crm.Ingest(d, recs); err != nil {
return nil, nil, err
}
if args.Done {
if err := crm.FinishSync(d, now); err != nil {
return nil, nil, err
}
}
msg := fmt.Sprintf("Stored %d %s record(s).", len(recs), entity)
if skipped > 0 {
msg += fmt.Sprintf(" Skipped %d without an id.", skipped)
}
if args.Done {
msg += " Sync finished."
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: msg}}}, nil, nil
})
if entries == nil {
entries = []inventory.Entry{}
}
res, err := jsonResult(entries)
return res, nil, err
})
mcp.AddTool(s, &mcp.Tool{
Name: "bridge_checkin",
Description: "Tell Supermarket that the agent can reach it and the Core's mcphub MCP server. Call it with the names of the mcphub tools you have.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, args checkinArgs) (*mcp.CallToolResult, any, error) {
agent := strings.TrimSpace(args.Agent)
if agent == "" {
agent = "unknown"
}
if err := bridge.Record(d, bridge.Checkin{Agent: agent, MCPHubTools: args.MCPHubTools, Note: strings.TrimSpace(args.Note)}); err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{
Text: "Checked in. Supermarket has recorded the mcphub tools you can use.",
}}}, nil, nil
})
}
// The CRM queue, worked through the Core (Hermes' bridge).
if can(c, "crm", true) {
mcp.AddTool(s, &mcp.Tool{
Name: "crm_pending_actions",
Description: "The CRM work Supermarket has queued for you: records to create in EspoCRM, and whether to copy recently " +
"changed CRM records back to Supermarket. Call it at the start of each CRM run and follow its instructions exactly.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ noArgs) (*mcp.CallToolResult, any, error) {
now := time.Now()
actions, err := crm.Claim(d, now, 25)
if err != nil {
return nil, nil, err
}
out := pendingResult{Instructions: crmInstructions, Actions: []pendingAction{}}
for _, a := range actions {
out.Actions = append(out.Actions, pendingAction{ID: a.ID, Do: a.Kind, Entity: a.Entity, Fields: a.Fields, FindExisting: a.Match})
}
due, since, err := crm.SyncDue(d, now)
if err != nil {
return nil, nil, err
}
if due {
if err := crm.StartSync(d, now); err != nil {
return nil, nil, err
}
req := &syncRequest{Entities: crm.SyncEntities, Fields: crmSyncFields}
if !since.IsZero() {
// A little overlap, so nothing changed during the last sync is missed.
req.ModifiedSince = since.Add(-10 * time.Minute).UTC().Format("2006-01-02 15:04:05")
}
out.Sync = req
}
res, err := jsonResult(out)
return res, nil, err
})
mcp.AddTool(s, &mcp.Tool{
Name: "crm_report_result",
Description: "Report the result of one action from crm_pending_actions: created (with the new record's id), existing (with the matching record's id), or failed (with the error).",
}, func(ctx context.Context, _ *mcp.CallToolRequest, args reportArgs) (*mcp.CallToolResult, any, error) {
err := crm.Report(d, args.ID, crm.Result{Outcome: strings.ToLower(strings.TrimSpace(args.Outcome)), EspoID: args.EspoID, Error: args.Error}, time.Now())
if err != nil {
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: err.Error()}}}, nil, nil
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "Recorded."}}}, nil, nil
})
mcp.AddTool(s, &mcp.Tool{
Name: "crm_ingest",
Description: "Send Supermarket the CRM records crm_pending_actions asked you to sync, in batches; set done=true on the last call.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, args ingestArgs) (*mcp.CallToolResult, any, error) {
entity := strings.TrimSpace(args.Entity)
known := false
for _, e := range crm.SyncEntities {
known = known || strings.EqualFold(e, entity)
if strings.EqualFold(e, entity) {
entity = e
}
}
if !known {
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{
Text: "entity must be one of " + strings.Join(crm.SyncEntities, ", ")}}}, nil, nil
}
now := time.Now()
var recs []crm.Record
skipped := 0
for _, f := range args.Records {
r, err := crm.RecordFrom(entity, f, now)
if err != nil {
skipped++
continue
}
recs = append(recs, r)
}
if err := crm.Ingest(d, recs); err != nil {
return nil, nil, err
}
if args.Done {
if err := crm.FinishSync(d, now); err != nil {
return nil, nil, err
}
}
msg := fmt.Sprintf("Stored %d %s record(s).", len(recs), entity)
if skipped > 0 {
msg += fmt.Sprintf(" Skipped %d without an id.", skipped)
}
if args.Done {
msg += " Sync finished."
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: msg}}}, nil, nil
})
mcp.AddTool(s, &mcp.Tool{
Name: "bridge_checkin",
Description: "Tell Supermarket that the agent can reach it and the Core's mcphub MCP server. Call it with the names of the mcphub tools you have.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, args checkinArgs) (*mcp.CallToolResult, any, error) {
agent := strings.TrimSpace(args.Agent)
if agent == "" {
agent = "unknown"
}
if err := bridge.Record(d, bridge.Checkin{Agent: agent, MCPHubTools: args.MCPHubTools, Note: strings.TrimSpace(args.Note)}); err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{
Text: "Checked in. Supermarket has recorded the mcphub tools you can use.",
}}}, nil, nil
})
}
}
// AllTools lists every tool there is, as an agent with every scope would
// see it: for the API's documentation.
func AllTools(ctx context.Context, d *db.DB, version string, more func(*mcp.Server, *Caller)) ([]*mcp.Tool, error) {
srv := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil)
addTools(srv, d, nil)
if more != nil {
more(srv, nil)
}
ct, st := mcp.NewInMemoryTransports()
ss, err := srv.Connect(ctx, st, nil)
if err != nil {
return nil, err
}
defer ss.Close()
cs, err := mcp.NewClient(&mcp.Implementation{Name: "docs"}, nil).Connect(ctx, ct, nil)
if err != nil {
return nil, err
}
defer cs.Close()
res, err := cs.ListTools(ctx, nil)
if err != nil {
return nil, err
}
return res.Tools, nil
}
+5 -4
View File
@@ -94,7 +94,7 @@ func cashFlows(d *db.DB, currency string) ([]revenueEvent, error) {
var out []revenueEvent
rows, err := d.Query(`SELECT customer, coalesce(CAST(json_extract(data, '$.status_transitions.paid_at') AS BIGINT), created),
coalesce(CAST(json_extract(data, '$.amount_paid') AS BIGINT), 0) FROM stripe_objects
WHERE kind = 'invoice' AND status = 'paid' AND currency = ? AND customer != ''`, currency)
WHERE kind = 'invoice' AND status = 'paid' AND currency = ? AND customer != '' ORDER BY id`, currency)
if err != nil {
return nil, err
}
@@ -110,7 +110,7 @@ func cashFlows(d *db.DB, currency string) ([]revenueEvent, error) {
}
rows.Close()
rows, err = d.Query(`SELECT customer, created, amount FROM stripe_objects
WHERE kind = 'refund' AND status = 'succeeded' AND currency = ? AND customer != ''`, currency)
WHERE kind = 'refund' AND status = 'succeeded' AND currency = ? AND customer != '' ORDER BY id`, currency)
if err != nil {
return nil, err
}
@@ -125,7 +125,7 @@ func cashFlows(d *db.DB, currency string) ([]revenueEvent, error) {
}
rows.Close()
rows, err = d.Query(`SELECT customer, created, data FROM stripe_objects
WHERE kind = 'credit_note' AND status = 'issued' AND currency = ? AND customer != ''`, currency)
WHERE kind = 'credit_note' AND status = 'issued' AND currency = ? AND customer != '' ORDER BY id`, currency)
if err != nil {
return nil, err
}
@@ -172,6 +172,7 @@ type Cell struct {
// customer, k months after their first paid month.
type CohortRevenue struct {
Month string
Existing bool // the base: customers already paying when counting starts
Customers int
PerCustomer []Cell // cents, cumulative, for months 0, 1, 2…
Margin []Cell // the same, after gross margin
@@ -221,7 +222,7 @@ func RevenueByCohort(d *db.DB, m *Model, n, span int, now time.Time) ([]CohortRe
if len(cs) == 0 {
continue
}
co := CohortRevenue{Month: m.Months[i].Month, Customers: len(cs)}
co := CohortRevenue{Month: m.Months[i].Month, Existing: m.Months[i].Month == m.Base, Customers: len(cs)}
var cum float64
for k := 0; k <= span; k++ {
if i+k >= len(m.Months) {
+70 -12
View File
@@ -151,7 +151,8 @@ func manual(d *db.DB) (map[string]string, error) {
return out, rows.Err()
}
// Matches matches every Stripe customer with billing to an Account: the
// Matches matches every Stripe customer who has spent something to an
// Account: the
// user's choice first, then a stored ID (either side), then email (an
// Account's or one of its Contacts'), then the email's domain (not free
// mail). Paying customers come first, by MRR.
@@ -168,19 +169,12 @@ func Matches(d *db.DB, model *Model) ([]Match, error) {
if err != nil {
return nil, err
}
billed := map[string]bool{}
rows, err := d.Query(`SELECT DISTINCT customer FROM stripe_objects WHERE kind = 'invoice' AND status IN ('paid', 'open')`)
paying, err := Spenders(d)
if err != nil {
return nil, err
}
for rows.Next() {
var c string
rows.Scan(&c)
billed[c] = true
}
rows.Close()
prospects := map[string]string{}
rows, err = d.Query(`SELECT id, subject FROM stripe_customers WHERE subject NOT LIKE 'stripe:%'`)
rows, err := d.Query(`SELECT id, subject FROM stripe_customers WHERE subject NOT LIKE 'stripe:%'`)
if err != nil {
return nil, err
}
@@ -217,7 +211,7 @@ func Matches(d *db.DB, model *Model) ([]Match, error) {
}
var out []Match
for _, c := range custs {
if !billed[c.ID] {
if !paying[c.ID] {
continue
}
m := Match{Customer: c.Customer, MRR: now[c.ID], Prospect: prospects[c.ID]}
@@ -266,7 +260,10 @@ func Matches(d *db.DB, model *Model) ([]Match, error) {
case a.MRR < b.MRR:
return 1
}
return strings.Compare(strings.ToLower(a.Customer.Name+a.Customer.Email), strings.ToLower(b.Customer.Name+b.Customer.Email))
if c := strings.Compare(strings.ToLower(a.Customer.Name+a.Customer.Email), strings.ToLower(b.Customer.Name+b.Customer.Email)); c != 0 {
return c
}
return strings.Compare(a.Customer.ID, b.Customer.ID) // the same name and email twice: a stable order
})
return out, nil
}
@@ -309,3 +306,64 @@ func MatchSummary(ms []Match) map[string]int {
}
return out
}
// Spenders are the customers whose total spend is above $0, as Stripe's
// dashboard counts it: their successful payments (charges), less what was
// refunded. Customers who only had a trial, or have only unpaid invoices,
// aren't customers yet. Until the charges are synced, paid invoices
// (amount_paid) less refunds stand in.
func Spenders(d *db.DB) (map[string]bool, error) {
var charges int
if err := d.QueryRow(`SELECT count(*) FROM stripe_objects WHERE kind = ?`, KindCharge).Scan(&charges); err != nil {
return nil, err
}
type row struct {
kind, customer, data string
amount int64
}
q := `SELECT kind, customer, amount, '' FROM stripe_objects
WHERE kind = 'charge' AND status = 'succeeded' AND customer != ''`
if charges == 0 {
q = `SELECT kind, customer, amount, data FROM stripe_objects
WHERE customer != '' AND ((kind = 'invoice' AND status = 'paid') OR (kind = 'refund' AND status IN ('succeeded', 'pending')))`
}
rows, err := d.Query(q)
if err != nil {
return nil, err
}
var all []row
for rows.Next() {
var r row
if err := rows.Scan(&r.kind, &r.customer, &r.amount, &r.data); err != nil {
rows.Close()
return nil, err
}
all = append(all, r)
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
spend := map[string]int64{}
for _, r := range all {
switch r.kind {
case KindCharge:
spend[r.customer] += r.amount // captured, less refunded
case KindRefund:
spend[r.customer] -= r.amount
case KindInvoice:
var inv struct {
AmountPaid int64 `json:"amount_paid"`
}
_ = json.Unmarshal([]byte(r.data), &inv)
spend[r.customer] += inv.AmountPaid
}
}
out := map[string]bool{}
for c, v := range spend {
if v > 0 {
out[c] = true
}
}
return out, nil
}
+18 -3
View File
@@ -39,9 +39,22 @@ func TestMatches(t *testing.T) {
} {
exec(`INSERT INTO stripe_objects (kind, id, customer, data) VALUES ('customer', ?, ?, ?)`, c.id, c.id, c.data)
if c.id != "cus_unbilled" {
exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', ?, ?, 'paid', 'usd', '{}')`, "in_"+c.id, c.id)
exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', ?, ?, 'paid', 'usd', '{"amount_paid":1000}')`, "in_"+c.id, c.id)
}
}
// Customers who never spent anything aren't listed: a $0 trial invoice,
// only an open invoice, or a payment refunded in full.
for _, c := range []struct{ id, status, data string }{
{"cus_trial", "paid", `{"amount_paid":0}`},
{"cus_open", "open", `{"amount_paid":0}`},
{"cus_refunded", "paid", `{"amount_paid":500}`},
} {
exec(`INSERT INTO stripe_objects (kind, id, customer, data) VALUES ('customer', ?, ?, '{"name":"X","email":"x@x.example"}')`, c.id, c.id)
exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', ?, ?, ?, 'usd', ?)`, "in_"+c.id, c.id, c.status, c.data)
}
exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, amount, data) VALUES ('refund', 're_1', 'cus_refunded', 'succeeded', 'usd', 500, '{}')`)
// A partial refund leaves them a customer.
exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, amount, data) VALUES ('refund', 're_2', 'cus_beta', 'succeeded', 'usd', 400, '{}')`)
exec(`INSERT INTO crm_actions (key, kind, entity, fields, status, espo_id) VALUES ('stripe-customer:cus_new', 'create', 'Account', '{"name":"Newco"}', 'done', 'a9')`)
ms, err := Matches(d, nil)
@@ -52,8 +65,10 @@ func TestMatches(t *testing.T) {
for _, m := range ms {
got[m.Customer.ID] = m
}
if _, ok := got["cus_unbilled"]; ok {
t.Error("a customer never billed is listed")
for _, id := range []string{"cus_unbilled", "cus_trial", "cus_open", "cus_refunded"} {
if _, ok := got[id]; ok {
t.Errorf("%s spent nothing, but is listed", id)
}
}
for id, want := range map[string]struct{ account, how string }{
"cus_ann": {"a1", MatchEmail}, "cus_beta": {"a2", MatchStoredID}, "cus_meta": {"a1", MatchStoredID},
+30 -5
View File
@@ -61,28 +61,43 @@ func Export(w io.Writer, d *db.DB, name string, now time.Time) error {
}
case "nrr-cohorts":
head := []string{"first_paid", "customers", "starting_mrr"}
for k := 0; k <= 24; k++ {
span := max(len(model.Months)-1, 0) // every cohort, to the latest month
for k := 0; k <= span; k++ {
head = append(head, fmt.Sprintf("month_%d_pct", k))
}
for k := 0; k <= span; k++ {
head = append(head, fmt.Sprintf("month_%d_mrr", k))
}
head = append(head, "existing_customers")
write(head)
for _, c := range model.Cohorts(1000, 24) {
for _, c := range model.Cohorts(len(model.Months), span) {
row := []string{c.Month, strconv.Itoa(c.Customers), dollars(c.Start)}
for _, r := range c.Retained {
row = append(row, pct(r))
}
for _, v := range c.MRR {
if v < 0 {
row = append(row, "")
} else {
row = append(row, dollars(v))
}
}
row = append(row, strconv.FormatBool(c.Existing))
if err := write(row); err != nil {
return err
}
}
case "cohort-revenue":
cs, err := RevenueByCohort(d, model, 1000, 24, now)
span := max(len(model.Months)-1, 0) // every cohort, to the latest month
cs, err := RevenueByCohort(d, model, len(model.Months), span, now)
if err != nil {
return err
}
head := []string{"first_paid", "customers"}
for k := 0; k <= 24; k++ {
for k := 0; k <= span; k++ {
head = append(head, fmt.Sprintf("month_%d_revenue_per_customer", k))
}
head = append(head, "existing_customers")
write(head)
for _, c := range cs {
row := []string{c.Month, strconv.Itoa(c.Customers)}
@@ -93,6 +108,7 @@ func Export(w io.Writer, d *db.DB, name string, now time.Time) error {
row = append(row, "")
}
}
row = append(row, strconv.FormatBool(c.Existing))
if err := write(row); err != nil {
return err
}
@@ -158,7 +174,7 @@ func Export(w io.Writer, d *db.DB, name string, now time.Time) error {
}
write([]string{"customer_id", "name", "email", "mrr_now", "first_paid", "crm_account_id", "crm_account", "matched_by"})
for _, m := range ms {
if err := write([]string{m.Customer.ID, m.Customer.Name, m.Customer.Email, dollars(m.MRR), model.First[m.Customer.ID],
if err := write([]string{m.Customer.ID, m.Customer.Name, m.Customer.Email, dollars(m.MRR), firstPaid(model, m.Customer.ID),
m.Account.ID, m.Account.Name, m.How}); err != nil {
return err
}
@@ -247,3 +263,12 @@ func joinLines(lines []string) string {
}
return out
}
// firstPaid is the month a customer first paid: their cohort's, or, for one
// who was already a customer, the month first seen paying.
func firstPaid(m *Model, customer string) string {
if f := m.First[customer]; f != "" {
return f
}
return m.Existing[customer]
}
+70 -12
View File
@@ -18,6 +18,7 @@ type line struct {
intervalCount int
proration bool
product string
invoice string
}
const avgMonthSeconds = 365.25 / 12 * 24 * 3600
@@ -46,12 +47,12 @@ func (l line) monthly() float64 {
return float64(l.amount) / months
}
// loadLines reads the recurring lines of billed invoices (paid or open; not
// void, not uncollectible) in the main currency.
// loadLines reads the recurring lines of paid invoices (not open, void or
// uncollectible) in the main currency.
func loadLines(d *db.DB, currency string) ([]line, error) {
rows, err := d.Query(`SELECT customer, amount, period_start, period_end, interval, interval_count, proration, product
FROM stripe_invoice_lines WHERE recurring = 1 AND status IN ('paid', 'open') AND currency = ? AND customer != ''
AND period_end > period_start`, currency)
rows, err := d.Query(`SELECT customer, amount, period_start, period_end, interval, interval_count, proration, product, invoice
FROM stripe_invoice_lines WHERE recurring = 1 AND status = 'paid' AND currency = ? AND customer != ''
AND period_end > period_start ORDER BY invoice, id`, currency) // a fixed order: float sums come out the same everywhere
if err != nil {
return nil, err
}
@@ -59,7 +60,7 @@ func loadLines(d *db.DB, currency string) ([]line, error) {
var out []line
for rows.Next() {
var l line
if err := rows.Scan(&l.customer, &l.amount, &l.start, &l.end, &l.interval, &l.intervalCount, &l.proration, &l.product); err != nil {
if err := rows.Scan(&l.customer, &l.amount, &l.start, &l.end, &l.interval, &l.intervalCount, &l.proration, &l.product, &l.invoice); err != nil {
return nil, err
}
out = append(out, l)
@@ -83,8 +84,47 @@ const (
MoveContraction = "contraction"
MoveChurn = "churn"
MoveReactivation = "reactivation"
// MoveExisting is a customer whose first payment Stripe shows is a
// renewal: they were a customer already (their first year free, or
// billed elsewhere). Counted as reactivation, not as new.
MoveExisting = "existing"
)
// renewalFirst are the customers whose earliest recurring line is on a
// renewal invoice (billing_reason subscription_cycle).
func renewalFirst(d *db.DB, lines []line) (map[string]bool, error) {
earliest := map[string]line{}
for _, l := range lines {
if e, ok := earliest[l.customer]; !ok || l.start < e.start {
earliest[l.customer] = l
}
}
rows, err := d.Query(`SELECT id, coalesce(json_extract(data, '$.billing_reason'), '') FROM stripe_objects WHERE kind = 'invoice' AND status = 'paid'`)
if err != nil {
return nil, err
}
reason := map[string]string{}
for rows.Next() {
var id, r string
if err := rows.Scan(&id, &r); err != nil {
rows.Close()
return nil, err
}
reason[id] = r
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
out := map[string]bool{}
for c, l := range earliest {
if reason[l.invoice] == "subscription_cycle" {
out[c] = true
}
}
return out, nil
}
// Month is one month's MRR and how it moved since the month before. Amounts
// are in cents.
type Month struct {
@@ -123,8 +163,10 @@ func (m Month) NetNew() float64 {
type Model struct {
Currency string
Months []Month // oldest first, from Start
First map[string]string // customer → the month they first paid (from Start)
First map[string]string // customer → the month they first paid (from Start): their cohort
Existing map[string]string // customer → the month first seen paying, for those already customers then (a renewal): no cohort
Start string // the first month counted ("" for all)
Base string // the month whose cohort is the customers already paying when counting starts; "" if none
Suggest *Suggestion // a start month worth considering, when none is set
}
@@ -177,7 +219,7 @@ func mrrAt(lines []line, t int64) map[string]float64 {
// (the current month measured now, the others at their last second).
func Build(d *db.DB, now time.Time) (*Model, error) {
cur := MainCurrency(d)
m := &Model{Currency: cur, First: map[string]string{}, Start: StartMonth(d)}
m := &Model{Currency: cur, First: map[string]string{}, Existing: map[string]string{}, Start: StartMonth(d)}
if cur == "" {
return m, nil
}
@@ -188,6 +230,10 @@ func Build(d *db.DB, now time.Time) (*Model, error) {
if len(lines) == 0 {
return m, nil
}
renewal, err := renewalFirst(d, lines)
if err != nil {
return nil, err
}
first := lines[0].start
for _, l := range lines {
first = min(first, l.start)
@@ -199,6 +245,9 @@ func Build(d *db.DB, now time.Time) (*Model, error) {
month = s
}
startMonth := month.Format("2006-01")
if m.Start != "" {
m.Base = startMonth
}
var prev map[string]float64
ever := map[string]bool{}
for !month.After(now) {
@@ -217,6 +266,11 @@ func Build(d *db.DB, now time.Time) (*Model, error) {
case mo.Month == startMonth && m.Start != "":
// Already paying when the count starts: the base, not new.
m.First[c] = mo.Month
case p == 0 && !ever[c] && renewal[c]:
// Already a customer before Stripe shows them paying.
mo.Reactivation += v
mo.Moves[c] = MoveExisting
m.Existing[c] = mo.Month
case p == 0 && !ever[c]:
mo.New += v
mo.NewCount++
@@ -305,14 +359,16 @@ func (m *Model) Recent(n int) []Month {
return out
}
// Cohort is the customers who first paid in one month, and the share of
// their starting MRR they pay in each month after (net revenue retention by
// cohort).
// Cohort is the customers who first paid in one month, and what those same
// customers pay in each month after: in dollars, and as a share of their
// starting MRR (net revenue retention by cohort).
type Cohort struct {
Month string
Existing bool // the base: customers already paying when counting starts, not new that month
Customers int
Start float64 // their MRR in their first month
Retained []float64 // percent of Start, for month 0, 1, 2…; -1 beyond today
MRR []float64 // their MRR, in cents, for month 0, 1, 2…; -1 beyond today
}
// Cohorts are the last n signup cohorts, newest first, each followed for up
@@ -333,13 +389,14 @@ func (m *Model) Cohorts(n, span int) []Cohort {
if len(cs) == 0 {
continue
}
co := Cohort{Month: mo.Month, Customers: len(cs)}
co := Cohort{Month: mo.Month, Existing: mo.Month == m.Base, Customers: len(cs)}
for _, c := range cs {
co.Start += mo.ByCustomer[c]
}
for k := 0; k <= span; k++ {
if i+k >= len(m.Months) || co.Start == 0 {
co.Retained = append(co.Retained, -1)
co.MRR = append(co.MRR, -1)
continue
}
kept := 0.0
@@ -347,6 +404,7 @@ func (m *Model) Cohorts(n, span int) []Cohort {
kept += m.Months[i+k].ByCustomer[c]
}
co.Retained = append(co.Retained, 100*kept/co.Start)
co.MRR = append(co.MRR, kept)
}
out = append(out, co)
}
+55 -2
View File
@@ -67,8 +67,10 @@ func TestBuild(t *testing.T) {
ln{cust: "cus_a", from: "2026-04-25", to: "2026-05-10", amount: -2500, proration: true},
ln{cust: "cus_a", from: "2026-04-25", to: "2026-05-10", amount: 4000, proration: true})
d.Exec(`UPDATE stripe_invoice_lines SET amount = 8000 WHERE customer = 'cus_a' AND period_start >= ?`, day("2026-05-10"))
// A trial, a void invoice and an uncollectible one count for nothing.
// A trial, an unpaid (open) invoice, a void one and an uncollectible
// one count for nothing.
addLines(t, d, ln{cust: "cus_t", from: "2026-03-01", to: "2026-04-01", interval: "month", amount: 0},
ln{cust: "cus_o", from: "2026-03-01", to: "2026-04-01", interval: "month", amount: 9900, status: "open"},
ln{cust: "cus_v", from: "2026-03-01", to: "2026-04-01", interval: "month", amount: 9900, status: "void"},
ln{cust: "cus_u", from: "2026-03-01", to: "2026-04-01", interval: "month", amount: 9900, status: "uncollectible"})
@@ -118,6 +120,10 @@ func TestBuild(t *testing.T) {
if len(cos) != 3 || cos[0].Month != "2026-03" || cos[2].Month != "2026-01" || cos[2].Retained[0] != 100 || !near(cos[2].Retained[3], 100*(5000+3044)/5000) {
t.Errorf("cohorts: %+v", cos)
}
// The same customers' dollars, month by month; none beyond today.
if !near(cos[2].MRR[0], 5000) || !near(cos[2].MRR[3], 5000+3044) || m.Cohorts(1, 4)[0].MRR[4] != -1 {
t.Errorf("cohort MRR: %v, %v", cos[2].MRR, cos[0].MRR)
}
ch := m.Changes("2026-04", map[string]Customer{"cus_b": {ID: "cus_b", Name: "Bea"}})
if len(ch) != 2 || ch[0].Customer.Name != "" || ch[1].Customer.Name != "Bea" || ch[1].Kind != MoveChurn {
t.Errorf("changes: %+v", ch)
@@ -135,6 +141,11 @@ func TestStartMonthAndSuggestion(t *testing.T) {
if m.Suggest == nil || m.Suggest.Month != "2025-01" || m.Suggest.Customers != 25 {
t.Fatalf("suggestion: %+v", m.Suggest)
}
for _, co := range m.Cohorts(5, 2) {
if co.Existing {
t.Errorf("no start month set, yet %s is the existing customers", co.Month)
}
}
if err := SetStartMonth(d, "2025-01"); err != nil {
t.Fatal(err)
}
@@ -146,7 +157,49 @@ func TestStartMonthAndSuggestion(t *testing.T) {
if jan.Month != "2025-01" || jan.New != 0 || jan.Customers != 25 || m.Suggest != nil {
t.Errorf("counted from January: %+v", jan)
}
if cos := m.Cohorts(5, 2); len(cos) != 1 || cos[0].Customers != 25 {
if cos := m.Cohorts(5, 2); len(cos) != 1 || cos[0].Customers != 25 || !cos[0].Existing {
t.Errorf("the starting base's cohort: %+v", cos)
}
}
// A customer whose first invoice Stripe shows is a renewal was a customer
// already: their first payment counts as reactivation, not new, and puts
// them in no cohort. One whose first invoice is a signup is new.
func TestRenewalFirstIsExisting(t *testing.T) {
d := openDB(t)
addLines(t, d, monthly("cus_a", 5000, "2026-01", "2026-07")...)
for _, c := range []struct{ cust, invoice, reason string }{
{"cus_old", "in_old", "subscription_cycle"},
{"cus_new", "in_new", "subscription_create"},
} {
if _, err := d.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end,
interval, interval_count, proration, recurring) VALUES (?, ?, ?, 'paid', 'usd', 120000, ?, ?, 'year', 1, 0, 1)`,
c.invoice, "il_"+c.cust, c.cust, day("2026-03-02"), day("2027-03-02")); err != nil {
t.Fatal(err)
}
if _, err := d.Exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', ?, ?, 'paid', 'usd', ?)`,
c.invoice, c.cust, `{"billing_reason":"`+c.reason+`"}`); err != nil {
t.Fatal(err)
}
}
m, err := Build(d, time.Date(2026, 6, 20, 12, 0, 0, 0, time.UTC))
if err != nil {
t.Fatal(err)
}
mar := m.Find("2026-03")
if mar.NewCount != 1 || !near(mar.New, 10000) || !near(mar.Reactivation, 10000) ||
mar.Moves["cus_old"] != MoveExisting || mar.Moves["cus_new"] != MoveNew {
t.Errorf("march: new %d %.0f, reactivation %.0f, moves %v", mar.NewCount, mar.New, mar.Reactivation, mar.Moves)
}
if !near(mar.NetNew(), mar.MRR-m.Find("2026-02").MRR) {
t.Errorf("movements don't add up: %.0f vs %.0f", mar.NetNew(), mar.MRR-m.Find("2026-02").MRR)
}
if _, ok := m.First["cus_old"]; ok || m.Existing["cus_old"] != "2026-03" || m.First["cus_new"] != "2026-03" {
t.Errorf("first %v, existing %v", m.First, m.Existing)
}
for _, co := range m.Cohorts(12, 3) {
if co.Month == "2026-03" && co.Customers != 1 {
t.Errorf("March cohort has %d customers, want only cus_new", co.Customers)
}
}
}
+23 -5
View File
@@ -21,6 +21,7 @@ const (
KindInvoice = "invoice"
KindCreditNote = "credit_note"
KindRefund = "refund"
KindCharge = "charge" // a payment: what total spend is counted from
KindProduct = "product"
)
@@ -31,8 +32,13 @@ const eventsKept = 29 * 24 * time.Hour
type syncState struct {
Backfilled time.Time `json:"backfilled"`
LastEvent int64 `json:"last_event"` // created time of the last event applied
Version int `json:"version"` // syncVersion when last backfilled
}
// syncVersion goes up when a backfill reads a new kind of object (2:
// charges), so the next sync reads everything once.
const syncVersion = 2
const stateKey = "metrics:stripe-state"
// SyncResult is what a sync did.
@@ -78,7 +84,7 @@ func sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceF
if _, err := d.GetJSON(stateKey, &st); err != nil {
return err
}
if forceFull || st.LastEvent == 0 || now.Sub(time.Unix(st.LastEvent, 0)) > eventsKept {
if forceFull || st.LastEvent == 0 || st.Version < syncVersion || now.Sub(time.Unix(st.LastEvent, 0)) > eventsKept {
res.Full = true
// Events from the moment the backfill starts are applied next time,
// so nothing falls between the two.
@@ -91,6 +97,7 @@ func sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceF
{KindInvoice, "/v1/invoices", nil},
{KindCreditNote, "/v1/credit_notes", nil},
{KindRefund, "/v1/refunds", url.Values{"expand[]": {"data.charge"}}},
{KindCharge, "/v1/charges", nil},
{KindProduct, "/v1/products", nil},
} {
raws, err := c.ListRaw(ctx, l.path, l.q, 0)
@@ -110,7 +117,7 @@ func sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceF
res.Counts[l.kind]++
}
}
st = syncState{Backfilled: now, LastEvent: start.Unix()}
st = syncState{Backfilled: now, LastEvent: start.Unix(), Version: syncVersion}
return d.PutJSON(stateKey, st)
}
// Products change rarely and have no events followed: read them all.
@@ -157,7 +164,8 @@ func sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceF
obj = full
}
case "charge":
// charge.refunded: its refunds are what matter.
kind = KindCharge
// charge.refunded: its refunds matter too.
for _, r := range head.Refunds.Data {
var rh struct {
ID string `json:"id"`
@@ -219,6 +227,15 @@ func store(ctx context.Context, d *db.DB, c *stripe.Client, kind string, raw jso
}
_ = json.Unmarshal(o.Charge, &ch)
customer = stripe.IDOf(ch.Customer)
case KindCharge:
// What the customer was charged and kept paying: captured, less
// refunded.
var ch struct {
AmountCaptured int64 `json:"amount_captured"`
AmountRefunded int64 `json:"amount_refunded"`
}
_ = json.Unmarshal(raw, &ch)
amount = ch.AmountCaptured - ch.AmountRefunded
case KindInvoice:
if o.Status == "draft" {
return nil // not billed yet
@@ -290,9 +307,10 @@ func currencies(d *db.DB) ([]string, error) {
return out, rows.Err()
}
// Counts are how many objects of each kind are stored.
// Counts are how many objects of each kind are stored (deleted customers
// left out).
func Counts(d *db.DB) (map[string]int, error) {
rows, err := d.Query(`SELECT kind, count(*) FROM stripe_objects GROUP BY kind`)
rows, err := d.Query(`SELECT kind, count(*) FROM stripe_objects WHERE status != 'deleted' GROUP BY kind`)
if err != nil {
return nil, err
}
+41
View File
@@ -57,6 +57,12 @@ func fakeStripe(t *testing.T, events *string) *httptest.Server {
t.Errorf("refunds without their charge: %s", r.URL)
}
fmt.Fprint(w, `{"data":[{"id":"re_1","object":"refund","amount":2000,"currency":"usd","created":1760200000,"status":"succeeded","charge":{"id":"ch_1","customer":"cus_a"}}],"has_more":false}`)
case "/v1/charges":
fmt.Fprint(w, `{"data":[
{"id":"ch_1","object":"charge","customer":"cus_a","created":1760000000,"status":"succeeded","currency":"usd","amount":4500,"amount_captured":4500,"amount_refunded":2000},
{"id":"ch_3","object":"charge","customer":"cus_c","created":1760000000,"status":"succeeded","currency":"usd","amount":1000,"amount_captured":1000,"amount_refunded":0},
{"id":"ch_4","object":"charge","customer":"cus_d","created":1760000000,"status":"succeeded","currency":"usd","amount":800,"amount_captured":800,"amount_refunded":800},
{"id":"ch_5","object":"charge","customer":"cus_e","created":1760000000,"status":"failed","currency":"usd","amount":900,"amount_captured":0,"amount_refunded":0}],"has_more":false}`)
case "/v1/refunds/re_2":
fmt.Fprint(w, `{"id":"re_2","object":"refund","amount":300,"currency":"usd","created":1762000000,"status":"succeeded","charge":{"id":"ch_2","customer":"cus_b"}}`)
case "/v1/products":
@@ -113,6 +119,19 @@ func TestSync(t *testing.T) {
if sub != "sub_2" || cust != "cus_b" || !recurring {
t.Errorf("new line: %q %q %v", sub, cust, recurring)
}
// Total spend comes from the charges: cus_c paid without an invoice;
// cus_d was refunded in full; cus_e's payment failed; cus_b only has an
// open invoice.
sp, err := Spenders(d)
if err != nil {
t.Fatal(err)
}
if len(sp) != 2 || !sp["cus_a"] || !sp["cus_c"] {
t.Errorf("spenders: %v", sp)
}
if counts[KindCharge] != 4 {
t.Errorf("charges: %v", counts)
}
var refundCustomer string
d.QueryRow(`SELECT customer FROM stripe_objects WHERE kind = 'refund' AND id = 're_1'`).Scan(&refundCustomer)
if refundCustomer != "cus_a" {
@@ -163,3 +182,25 @@ func TestSync(t *testing.T) {
t.Errorf("without products: %+v %v", res, err)
}
}
// A database synced before charges were read gets one full read, then
// goes back to events.
func TestSyncReadsChargesOnce(t *testing.T) {
d := openDB(t)
events := `{"data":[],"has_more":false}`
srv := fakeStripe(t, &events)
defer srv.Close()
c := stripe.New("rk_test").WithBase(srv.URL)
now := time.Unix(1762100000, 0)
if err := d.PutJSON(stateKey, syncState{Backfilled: now.Add(-time.Hour), LastEvent: now.Add(-time.Hour).Unix()}); err != nil {
t.Fatal(err)
}
res, err := Sync(context.Background(), d, c, now, false)
if err != nil || !res.Full || res.Counts[KindCharge] != 4 {
t.Fatalf("first sync: %+v %v", res, err)
}
res, err = Sync(context.Background(), d, c, now.Add(time.Hour), false)
if err != nil || res.Full {
t.Fatalf("second sync: %+v %v", res, err)
}
}
+4 -64
View File
@@ -1,5 +1,5 @@
// Package oauth runs the OAuth 2.0 authorization-code flows for X,
// LinkedIn, Reddit and Google. The web app sends the browser to AuthURL, and its callback
// LinkedIn and Google. The web app sends the browser to AuthURL, and its callback
// handler calls Exchange with the code the provider sends back.
package oauth
@@ -33,6 +33,9 @@ type Pending struct {
Verifier string // PKCE, X only
RedirectURI string
Started time.Time
For int64 `json:",omitempty"` // a person signing in their own posting account; 0: the company's
Team int64 `json:",omitempty"` // the team it was started in (multi-tenant)
Browser string `json:",omitempty"` // the hash of the cookie that ties it to a browser
}
// --- X ---
@@ -159,69 +162,6 @@ func LinkedInExchange(ctx context.Context, clientID, clientSecret, code string,
return tokenResponse(req)
}
// --- Reddit ---
const (
redditAuthURL = "https://www.reddit.com/api/v1/authorize"
redditTokenURL = "https://www.reddit.com/api/v1/access_token"
// identity: who signed in; submit: post; read: subreddit rules and the
// account's own posts; history: the account's posts for the warnings.
redditScopes = "identity submit read history"
)
// RedditStart begins Reddit's authorization-code flow. duration=permanent
// returns a refresh token: access tokens last an hour.
func RedditStart(clientID, redirectURI string) (string, *Pending, error) {
state, err := randomString()
if err != nil {
return "", nil, err
}
params := url.Values{
"client_id": {clientID},
"response_type": {"code"},
"state": {state},
"redirect_uri": {redirectURI},
"duration": {"permanent"},
"scope": {redditScopes},
}
p := &Pending{Provider: "reddit", State: state, RedirectURI: redirectURI, Started: time.Now()}
return redditAuthURL + "?" + params.Encode(), p, nil
}
// RedditExchange swaps the callback's code for tokens.
func RedditExchange(ctx context.Context, clientID, clientSecret, userAgent, code string, p *Pending) (*Result, error) {
return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {p.RedirectURI},
})
}
// RefreshReddit gets a new access token. Reddit keeps the refresh token.
func RefreshReddit(ctx context.Context, clientID, clientSecret, userAgent, refreshToken string) (*Result, error) {
return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {refreshToken},
})
}
// RedditAppToken gets an app-only token, for reading subreddits' rules
// before anyone has signed in.
func RedditAppToken(ctx context.Context, clientID, clientSecret, userAgent string) (*Result, error) {
return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{"grant_type": {"client_credentials"}})
}
func redditToken(ctx context.Context, clientID, clientSecret, userAgent string, data url.Values) (*Result, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, redditTokenURL, strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", userAgent)
req.SetBasicAuth(clientID, clientSecret)
return tokenResponse(req)
}
// --- shared ---
func tokenResponse(req *http.Request) (*Result, error) {
+366
View File
@@ -0,0 +1,366 @@
// Package oidc signs people in with an OpenID Connect provider: the
// Federated Core's Authelia. The authorization code flow, with PKCE (S256)
// and a nonce; the client authenticates to the token endpoint with its
// secret in the form (client_secret_post).
//
// The ID token comes straight from the provider's token endpoint over TLS,
// so (as OpenID Connect Core 1.0, 3.1.3.7, allows) its issuer is trusted
// from TLS rather than by checking its signature; its claims are checked:
// the issuer, the audience, the expiry and the nonce.
package oidc
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/crypto/pbkdf2"
)
// Provider is what an issuer's discovery document says.
type Provider struct {
Issuer string `json:"issuer"`
Authorization string `json:"authorization_endpoint"`
Token string `json:"token_endpoint"`
UserInfo string `json:"userinfo_endpoint"`
EndSession string `json:"end_session_endpoint"` // empty if the provider has no sign-out
Scopes []string `json:"scopes_supported"`
PKCEMethods []string `json:"code_challenge_methods_supported"`
}
// Client is how Supermarket is registered with the provider.
type Client struct {
ID, Secret string
RedirectURI string
}
// Scopes are what Supermarket asks for.
const Scopes = "openid profile email groups"
// HTTP is the client used to reach providers; tests replace it.
var HTTP = &http.Client{Timeout: 20 * time.Second}
// Discover reads an issuer's discovery document, and checks it names the
// same issuer and the endpoints the code flow needs.
func Discover(ctx context.Context, issuer string) (*Provider, error) {
issuer = strings.TrimRight(issuer, "/")
req, err := http.NewRequestWithContext(ctx, http.MethodGet, issuer+"/.well-known/openid-configuration", nil)
if err != nil {
return nil, err
}
resp, err := HTTP.Do(req)
if err != nil {
return nil, fmt.Errorf("reaching %s: %w", issuer, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s has no OpenID Connect discovery document (%s)", issuer, resp.Status)
}
var p Provider
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&p); err != nil {
return nil, fmt.Errorf("%s's discovery document can't be read: %w", issuer, err)
}
if strings.TrimRight(p.Issuer, "/") != issuer {
return nil, fmt.Errorf("the discovery document names another issuer (%s)", p.Issuer)
}
if p.Authorization == "" || p.Token == "" {
return nil, errors.New("the discovery document lacks the authorization or token endpoint")
}
return &p, nil
}
// Flow is a sign-in under way: kept until the provider sends the browser
// back.
type Flow struct {
State string `json:"state"`
Nonce string `json:"nonce"`
Verifier string `json:"verifier"`
Started time.Time `json:"started"`
Next string `json:"next,omitempty"`
Browser string `json:"browser,omitempty"` // the hash of the cookie that ties it to a browser
}
func random() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// Start begins a sign-in: the address to send the browser to, and the
// flow to keep. statePrefix goes before the random state (the team, on
// the multi-tenant edition).
func Start(p *Provider, c Client, statePrefix string) (string, *Flow, error) {
f := &Flow{Started: time.Now()}
var err error
if f.State, err = random(); err != nil {
return "", nil, err
}
f.State = statePrefix + f.State
if f.Nonce, err = random(); err != nil {
return "", nil, err
}
if f.Verifier, err = random(); err != nil {
return "", nil, err
}
sum := sha256.Sum256([]byte(f.Verifier))
q := url.Values{
"response_type": {"code"},
"client_id": {c.ID},
"redirect_uri": {c.RedirectURI},
"scope": {Scopes},
"state": {f.State},
"nonce": {f.Nonce},
"code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])},
"code_challenge_method": {"S256"},
}
sep := "?"
if strings.Contains(p.Authorization, "?") {
sep = "&"
}
return p.Authorization + sep + q.Encode(), f, nil
}
// Identity is who signed in.
type Identity struct {
Subject string // the provider's ID for them: stable, unlike the email
Email string
Verified bool // the provider vouches for the email
Name string
Groups []string
IDToken string // for signing out of the provider
}
// Finish trades the code for tokens, checks the ID token's claims, and
// reads who it is (the ID token, completed by the userinfo endpoint).
func Finish(ctx context.Context, p *Provider, c Client, f *Flow, code string, now time.Time) (*Identity, error) {
form := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {c.RedirectURI},
"client_id": {c.ID},
"client_secret": {c.Secret},
"code_verifier": {f.Verifier},
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.Token, strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
resp, err := HTTP.Do(req)
if err != nil {
return nil, fmt.Errorf("reaching the token endpoint: %w", err)
}
defer resp.Body.Close()
var tok struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token"`
Error string `json:"error"`
Description string `json:"error_description"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&tok); err != nil {
return nil, fmt.Errorf("the token endpoint's answer can't be read (%s)", resp.Status)
}
if resp.StatusCode != http.StatusOK || tok.Error != "" {
return nil, fmt.Errorf("the provider refused the code: %s %s", tok.Error, tok.Description)
}
claims, err := parseIDToken(tok.IDToken)
if err != nil {
return nil, err
}
if err := claims.check(p.Issuer, c.ID, f.Nonce, now); err != nil {
return nil, err
}
id := &Identity{Subject: claims.Subject, Email: claims.Email, Verified: claims.EmailVerified, Name: claims.Name, Groups: claims.Groups, IDToken: tok.IDToken}
if p.UserInfo != "" && tok.AccessToken != "" {
if ui, err := userInfo(ctx, p.UserInfo, tok.AccessToken); err == nil && ui.Subject == claims.Subject {
if ui.Email != "" {
id.Email, id.Verified = ui.Email, ui.EmailVerified
}
if ui.Name != "" {
id.Name = ui.Name
}
if len(ui.Groups) > 0 {
id.Groups = ui.Groups
}
}
}
if id.Subject == "" {
return nil, errors.New("the provider sent no subject")
}
id.Email = strings.ToLower(strings.TrimSpace(id.Email))
return id, nil
}
// claims are the ID token's (and userinfo's).
type claims struct {
Issuer string `json:"iss"`
Subject string `json:"sub"`
Audience audience `json:"aud"`
Expiry int64 `json:"exp"`
IssuedAt int64 `json:"iat"`
Nonce string `json:"nonce"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
Groups []string `json:"groups"`
}
// audience is a string or a list of them.
type audience []string
func (a *audience) UnmarshalJSON(b []byte) error {
var one string
if json.Unmarshal(b, &one) == nil {
*a = []string{one}
return nil
}
var many []string
if err := json.Unmarshal(b, &many); err != nil {
return err
}
*a = many
return nil
}
func parseIDToken(tok string) (*claims, error) {
parts := strings.Split(tok, ".")
if len(parts) != 3 {
return nil, errors.New("the provider sent no ID token")
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, errors.New("the ID token can't be read")
}
var c claims
if err := json.Unmarshal(raw, &c); err != nil {
return nil, errors.New("the ID token can't be read")
}
return &c, nil
}
// leeway allows for clocks that differ a little.
const leeway = 2 * time.Minute
func (c *claims) check(issuer, clientID, nonce string, now time.Time) error {
switch {
case strings.TrimRight(c.Issuer, "/") != strings.TrimRight(issuer, "/"):
return errors.New("the ID token is from another issuer")
case !c.has(clientID):
return errors.New("the ID token is for another client")
case c.Expiry == 0 || now.After(time.Unix(c.Expiry, 0).Add(leeway)):
return errors.New("the ID token has expired: check the server's clock")
case c.IssuedAt != 0 && time.Unix(c.IssuedAt, 0).After(now.Add(leeway)):
return errors.New("the ID token is from the future: check the server's clock")
case nonce == "" || c.Nonce != nonce:
return errors.New("the ID token doesn't match this sign-in")
}
return nil
}
func (c *claims) has(clientID string) bool {
for _, a := range c.Audience {
if a == clientID {
return true
}
}
return false
}
func userInfo(ctx context.Context, endpoint, access string) (*claims, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+access)
resp, err := HTTP.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("userinfo: %s", resp.Status)
}
var c claims
return &c, json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&c)
}
// SignOutURL is where to send the browser to sign out of the provider too,
// or "" if it has no end-session endpoint.
func SignOutURL(p *Provider, idToken, back string) string {
if p == nil || p.EndSession == "" {
return ""
}
q := url.Values{"post_logout_redirect_uri": {back}}
if idToken != "" {
q.Set("id_token_hint", idToken)
}
sep := "?"
if strings.Contains(p.EndSession, "?") {
sep = "&"
}
return p.EndSession + sep + q.Encode()
}
// Secrets, as Authelia's configuration takes them.
// NewSecret is a client secret: 48 random characters.
func NewSecret() (string, error) {
b := make([]byte, 36)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// HashRounds is how many PBKDF2 rounds the Core's own clients use.
const HashRounds = 310000
// ab64 is passlib's base64: the standard alphabet with . for +, no padding.
func ab64(b []byte) string {
return strings.ReplaceAll(base64.RawStdEncoding.EncodeToString(b), "+", ".")
}
// HashSecret is a secret as Authelia's client_secret takes it:
// $pbkdf2-sha512$310000$<salt>$<key>, like the Core's other clients.
func HashSecret(secret string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
return hashWith(secret, salt, HashRounds), nil
}
func hashWith(secret string, salt []byte, rounds int) string {
key := pbkdf2.Key([]byte(secret), salt, rounds, sha512.Size, sha512.New)
return fmt.Sprintf("$pbkdf2-sha512$%d$%s$%s", rounds, ab64(salt), ab64(key))
}
// CheckHash says whether a secret matches a hash from HashSecret.
func CheckHash(secret, hash string) bool {
parts := strings.Split(hash, "$")
if len(parts) != 5 || parts[1] != "pbkdf2-sha512" {
return false
}
var rounds int
if _, err := fmt.Sscanf(parts[2], "%d", &rounds); err != nil || rounds < 1 || rounds > 10_000_000 {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(strings.ReplaceAll(parts[3], ".", "+"))
if err != nil {
return false
}
return hashWith(secret, salt, rounds) == hash
}
+131
View File
@@ -0,0 +1,131 @@
package oidc
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strings"
"testing"
"time"
)
func TestHashSecret(t *testing.T) {
// The same as Python's hashlib.pbkdf2_hmac, in passlib's base64.
if got := hashWith("correct horse", []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, 1000); got != "$pbkdf2-sha512$1000$AAECAwQFBgcICQoLDA0ODw$Xpx07WjVx4vCIvrmBRj8uOoVVtGqJqtUv2J5bhizSQs7osCteF7W4A61dZDqSIqQjO.dxO6p5FT/Uy7QRBXSXA" {
t.Errorf("hash %s", got)
}
h, err := HashSecret("s3cret")
if err != nil {
t.Fatal(err)
}
// Shaped like the Core's own clients' secrets.
if !regexp.MustCompile(`^\$pbkdf2-sha512\$310000\$[A-Za-z0-9./]{22}\$[A-Za-z0-9./]{86}$`).MatchString(h) {
t.Errorf("shape %s", h)
}
if !CheckHash("s3cret", h) || CheckHash("s3creT", h) || CheckHash("s3cret", "$pbkdf2-sha256$1$a$b") {
t.Error("check")
}
if s, _ := NewSecret(); len(s) != 48 {
t.Errorf("secret %q", s)
}
}
// fakeAuthelia is a provider for tests.
func fakeAuthelia(t *testing.T, claims map[string]any) (*httptest.Server, *string) {
t.Helper()
var challenge string
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/.well-known/openid-configuration":
json.NewEncoder(w).Encode(map[string]any{"issuer": srv.URL, "authorization_endpoint": srv.URL + "/api/oidc/authorization",
"token_endpoint": srv.URL + "/api/oidc/token", "userinfo_endpoint": srv.URL + "/api/oidc/userinfo"})
case "/api/oidc/token":
r.ParseForm()
sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier")))
if r.PostForm.Get("client_secret") != "s3cret" || r.PostForm.Get("code") != "c0de" ||
base64.RawURLEncoding.EncodeToString(sum[:]) != challenge {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant"})
return
}
c := map[string]any{"iss": srv.URL, "aud": []string{"supermarket"}, "exp": time.Now().Add(time.Minute).Unix(), "iat": time.Now().Unix()}
for k, v := range claims {
c[k] = v
}
payload, _ := json.Marshal(c)
json.NewEncoder(w).Encode(map[string]string{"access_token": "at", "id_token": "e30." + base64.RawURLEncoding.EncodeToString(payload) + ".sig"})
case "/api/oidc/userinfo":
if r.Header.Get("Authorization") != "Bearer at" {
w.WriteHeader(http.StatusUnauthorized)
return
}
json.NewEncoder(w).Encode(map[string]any{"sub": claims["sub"], "email": "Pat@Example.com", "email_verified": true, "groups": []string{"admins"}})
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return srv, &challenge
}
func TestCodeFlow(t *testing.T) {
ctx := context.Background()
claims := map[string]any{"sub": "abc-123", "name": "Pat"}
srv, challenge := fakeAuthelia(t, claims)
if _, err := Discover(ctx, srv.URL+"/other"); err == nil {
t.Error("discovered a wrong issuer")
}
p, err := Discover(ctx, srv.URL+"/")
if err != nil {
t.Fatal(err)
}
c := Client{ID: "supermarket", Secret: "s3cret", RedirectURI: "https://sm.example.com/auth/core/callback"}
addr, f, err := Start(p, c, "7.")
if err != nil {
t.Fatal(err)
}
u, _ := url.Parse(addr)
q := u.Query()
if q.Get("code_challenge_method") != "S256" || q.Get("scope") != Scopes || q.Get("nonce") != f.Nonce || !strings.HasPrefix(f.State, "7.") || q.Get("state") != f.State {
t.Errorf("authorization address %s", addr)
}
*challenge = q.Get("code_challenge")
claims["nonce"] = f.Nonce
id, err := Finish(ctx, p, c, f, "c0de", time.Now())
if err != nil {
t.Fatal(err)
}
if id.Subject != "abc-123" || id.Email != "pat@example.com" || !id.Verified || id.Name != "Pat" || len(id.Groups) != 1 {
t.Errorf("identity %+v", id)
}
// What must fail.
if _, err := Finish(ctx, p, Client{ID: "supermarket", Secret: "wrong", RedirectURI: c.RedirectURI}, f, "c0de", time.Now()); err == nil {
t.Error("a wrong secret")
}
bad := *f
bad.Verifier = "other"
if _, err := Finish(ctx, p, c, &bad, "c0de", time.Now()); err == nil {
t.Error("a wrong verifier")
}
claims["nonce"] = "replayed"
if _, err := Finish(ctx, p, c, f, "c0de", time.Now()); err == nil || !strings.Contains(err.Error(), "match") {
t.Errorf("a wrong nonce: %v", err)
}
claims["nonce"] = f.Nonce
if _, err := Finish(ctx, p, Client{ID: "other", Secret: "s3cret", RedirectURI: c.RedirectURI}, f, "c0de", time.Now()); err == nil {
t.Error("another client's token")
}
if _, err := Finish(ctx, p, c, f, "c0de", time.Now().Add(10*time.Minute)); err == nil || !strings.Contains(err.Error(), "expired") {
t.Errorf("expired: %v", err)
}
if SignOutURL(p, "x", "https://sm.example.com/signin") != "" {
t.Error("sign-out without an endpoint")
}
}
+9 -2
View File
@@ -50,6 +50,7 @@ type Message struct {
RepliedAt time.Time
Reply string
Error string
CreatedBy int64 // who drafted it; 0: unknown, or the local edition
// Filled in when listing.
Contact prospects.Contact
@@ -86,7 +87,7 @@ func nullID(id int64) any {
}
const columns = `o.id, o.contact_id, coalesce(o.signal_id, 0), o.channel, o.status, o.subject, o.body, o.to_addr,
o.message_id, o.created_at, o.queued_at, o.sent_at, o.replied_at, o.reply, o.error,
o.message_id, o.created_at, o.queued_at, o.sent_at, o.replied_at, o.reply, o.error, o.created_by,
p.first_name, p.last_name, p.title, p.email, p.email_status, p.linkedin, coalesce(p.company_id, 0),
coalesce(c.name, '')`
@@ -101,7 +102,7 @@ func scan(rows *sql.Rows) ([]Message, error) {
var created string
var queued, sent, replied sql.NullString
if err := rows.Scan(&m.ID, &m.ContactID, &m.SignalID, &m.Channel, &m.Status, &m.Subject, &m.Body, &m.To,
&m.MessageID, &created, &queued, &sent, &replied, &m.Reply, &m.Error,
&m.MessageID, &created, &queued, &sent, &replied, &m.Reply, &m.Error, &m.CreatedBy,
&m.Contact.FirstName, &m.Contact.LastName, &m.Contact.Title, &m.Contact.Email, &m.Contact.EmailStatus,
&m.Contact.LinkedIn, &m.Contact.CompanyID, &m.Company); err != nil {
return nil, err
@@ -405,3 +406,9 @@ func lastSent(d *db.DB) (time.Time, error) {
err := d.QueryRow(`SELECT max(sent_at) FROM outreach WHERE channel = 'email'`).Scan(&s)
return parseTime(s), err
}
// SetCreatedBy records who drafted a message.
func SetCreatedBy(d *db.DB, id, user int64) error {
_, err := d.Exec(`UPDATE outreach SET created_by = ? WHERE id = ?`, user, id)
return err
}
+321
View File
@@ -0,0 +1,321 @@
// Package posting keeps the social accounts posts go out from: several per
// network, the company's and people's own, each signed in once by its
// owner or an admin, and who may post to which. Their tokens are in the
// secrets store, under acct:<id>:… .
package posting
import (
"database/sql"
"errors"
"fmt"
"strings"
"time"
"supermarket/internal/db"
"supermarket/internal/secrets"
)
// Networks an account can be on.
const (
X = "x"
LinkedIn = "linkedin" // a member, posting as themselves
LinkedInPage = "linkedin_page" // a company page
Reddit = "reddit" // only from before: Reddit is now posted to by hand
)
// NetworkName is a network as people say it.
func NetworkName(n string) string {
switch n {
case X:
return "X"
case LinkedIn:
return "LinkedIn"
case LinkedInPage:
return "LinkedIn page"
case Reddit:
return "Reddit"
}
return n
}
// Channel is the draft channel an account posts for: a LinkedIn page posts
// LinkedIn drafts.
func Channel(network string) string {
if network == LinkedInPage {
return LinkedIn
}
return network
}
// Account is somewhere posts can go out from.
type Account struct {
ID int64
Network string
Name string
External string
Owner int64 // 0: the company's
CreatedBy int64
Created time.Time
Expires time.Time // zero if Supermarket renews the sign-in itself
}
// Label is the account as a list shows it: "X @acme".
func (a *Account) Label() string {
n := a.Name
if n == "" {
n = "(unnamed)"
}
return NetworkName(a.Network) + " " + n
}
// Expired says whether the sign-in has run out.
func (a *Account) Expired(now time.Time) bool { return !a.Expires.IsZero() && !now.Before(a.Expires) }
// Secret names for an account's tokens.
func AccessName(id int64) string { return fmt.Sprintf("acct:%d:access", id) }
func RefreshName(id int64) string { return fmt.Sprintf("acct:%d:refresh", id) }
const timeFormat = "2006-01-02T15:04:05.000Z"
func ts(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format(timeFormat)
}
func parseTS(s string) time.Time {
t, _ := time.Parse(timeFormat, s)
return t
}
var ErrNotFound = errors.New("no such posting account")
const cols = `id, network, name, external, owner_id, created_by, created_at, expires_at`
func scan(row interface{ Scan(...any) error }) (*Account, error) {
var a Account
var created, expires string
if err := row.Scan(&a.ID, &a.Network, &a.Name, &a.External, &a.Owner, &a.CreatedBy, &created, &expires); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
a.Created, a.Expires = parseTS(created), parseTS(expires)
return &a, nil
}
// Save signs an account in: a new one, or, for the same network, owner and
// external ID, the existing one with new tokens. refresh may be "".
func Save(d *db.DB, sec *secrets.Store, a *Account, access, refresh string, now time.Time) error {
if a.Network != X && a.Network != LinkedIn && a.Network != LinkedInPage {
return fmt.Errorf("no network %q", a.Network)
}
var id int64
err := d.QueryRow(`SELECT id FROM posting_accounts WHERE network = ? AND owner_id = ? AND external = ?`, a.Network, a.Owner, a.External).Scan(&id)
switch {
case errors.Is(err, sql.ErrNoRows):
a.Created = now
a.ID, err = d.Insert(`INSERT INTO posting_accounts (network, name, external, owner_id, created_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
a.Network, a.Name, a.External, a.Owner, a.CreatedBy, ts(now), ts(a.Expires))
case err == nil:
a.ID = id
_, err = d.Exec(`UPDATE posting_accounts SET name = ?, expires_at = ? WHERE id = ?`, a.Name, ts(a.Expires), id)
}
if err != nil {
return err
}
return sec.Set(map[string]string{AccessName(a.ID): access, RefreshName(a.ID): refresh})
}
// SaveTokens keeps refreshed tokens.
func SaveTokens(sec *secrets.Store, id int64, access, refresh string) error {
up := map[string]string{AccessName(id): access}
if refresh != "" {
up[RefreshName(id)] = refresh
}
return sec.Set(up)
}
// Rename changes what an account is called (a LinkedIn page chosen).
func Rename(d *db.DB, id int64, name, external string) error {
_, err := d.Exec(`UPDATE posting_accounts SET name = ?, external = ? WHERE id = ?`, name, external, id)
return err
}
// Get finds an account.
func Get(d *db.DB, id int64) (*Account, error) {
return scan(d.QueryRow(`SELECT `+cols+` FROM posting_accounts WHERE id = ?`, id))
}
// List is every account: the company's first, then by network and name.
func List(d *db.DB) ([]*Account, error) {
rows, err := d.Query(`SELECT ` + cols + ` FROM posting_accounts ORDER BY owner_id <> 0, network, name COLLATE NOCASE, id`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Account
for rows.Next() {
a, err := scan(rows)
if err != nil {
return nil, err
}
out = append(out, a)
}
return out, rows.Err()
}
// Company is the company's first account on a network, or nil: where a
// draft without an account goes.
func Company(d *db.DB, network string) (*Account, error) {
a, err := scan(d.QueryRow(`SELECT `+cols+` FROM posting_accounts WHERE network = ? AND owner_id = 0 ORDER BY id LIMIT 1`, network))
if errors.Is(err, ErrNotFound) {
return nil, nil
}
return a, err
}
// Remove signs an account out: its tokens and grants go.
func Remove(d *db.DB, sec *secrets.Store, id int64) error {
tx, err := d.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.Exec(`DELETE FROM posting_grants WHERE account_id = ?`, id); err != nil {
return err
}
if _, err := tx.Exec(`DELETE FROM posting_accounts WHERE id = ?`, id); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return err
}
return sec.Set(map[string]string{AccessName(id): "", RefreshName(id): ""})
}
// OwnedBy are a user's own accounts.
func OwnedBy(d *db.DB, user int64) ([]*Account, error) {
all, err := List(d)
if err != nil {
return nil, err
}
var out []*Account
for _, a := range all {
if a.Owner == user {
out = append(out, a)
}
}
return out, nil
}
// Grants are who may post to which account, beyond its owner and the
// admins: account → users.
func Grants(d *db.DB) (map[int64]map[int64]bool, error) {
rows, err := d.Query(`SELECT account_id, user_id FROM posting_grants`)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[int64]map[int64]bool{}
for rows.Next() {
var a, u int64
if err := rows.Scan(&a, &u); err != nil {
return nil, err
}
if out[a] == nil {
out[a] = map[int64]bool{}
}
out[a][u] = true
}
return out, rows.Err()
}
// SetGrants replaces who may post to which: account → users.
func SetGrants(d *db.DB, grants map[int64][]int64) error {
tx, err := d.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.Exec(`DELETE FROM posting_grants`); err != nil {
return err
}
for a, us := range grants {
for _, u := range us {
if _, err := tx.Exec(`INSERT INTO posting_grants (account_id, user_id) VALUES (?, ?)`, a, u); err != nil {
return err
}
}
}
return tx.Commit()
}
// Granted says whether a user was given an account (not counting their own
// or being an admin).
func Granted(d *db.DB, account, user int64) (bool, error) {
var n int
err := d.QueryRow(`SELECT count(*) FROM posting_grants WHERE account_id = ? AND user_id = ?`, account, user).Scan(&n)
return n > 0, err
}
// ForgetUser takes a removed user's grants away. Their own accounts are
// removed by the caller (Remove), which holds their posts first.
func ForgetUser(d *db.DB, user int64) error {
_, err := d.Exec(`DELETE FROM posting_grants WHERE user_id = ?`, user)
return err
}
// Legacy: before posting accounts, each network had one sign-in, in
// secrets named for it. Adopt makes those the company's accounts, once.
type legacy struct {
network, access, refresh, name string
}
// Adopt turns the old single sign-ins into the company's accounts, and
// clears the old secrets. names gives each one's shown name and external
// ID (from the old record of sign-ins). It returns how many it adopted.
func Adopt(d *db.DB, sec *secrets.Store, names func(network string) (name, external string, expires time.Time), now time.Time) (int, error) {
olds := []legacy{
{X, secrets.XAccessToken, secrets.XRefreshToken, ""},
{LinkedIn, secrets.LinkedInAccessToken, "", ""},
{LinkedInPage, secrets.LinkedInPageAccessToken, "", ""},
}
n := 0
for _, o := range olds {
tok := sec.Get(o.access)
if tok == "" {
continue
}
name, external, expires := names(o.network)
a := &Account{Network: o.network, Name: name, External: external, Expires: expires}
refresh := ""
if o.refresh != "" {
refresh = sec.Get(o.refresh)
}
if err := Save(d, sec, a, tok, refresh, now); err != nil {
return n, err
}
clear := map[string]string{o.access: ""}
if o.refresh != "" {
clear[o.refresh] = ""
}
if err := sec.Set(clear); err != nil {
return n, err
}
n++
}
return n, nil
}
// Label for a list of accounts: "X @acme, LinkedIn Jo".
func Labels(list []*Account) string {
var parts []string
for _, a := range list {
parts = append(parts, a.Label())
}
return strings.Join(parts, ", ")
}
+110
View File
@@ -0,0 +1,110 @@
package posting
import (
"path/filepath"
"testing"
"time"
"supermarket/internal/db"
"supermarket/internal/secrets"
)
func open(t *testing.T) (*db.DB, *secrets.Store) {
t.Helper()
dir := t.TempDir()
d, err := db.Open(filepath.Join(dir, "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
sec, err := secrets.Open(filepath.Join(dir, "secrets.json"))
if db.OnPostgres() {
sec, err = secrets.OpenDB(d, []byte("0123456789abcdef0123456789abcdef"), nil)
}
if err != nil {
t.Fatal(err)
}
return d, sec
}
func TestAccounts(t *testing.T) {
d, sec := open(t)
now := time.Now()
co := &Account{Network: X, Name: "@acme", External: "acme"}
if err := Save(d, sec, co, "tok", "ref", now); err != nil {
t.Fatal(err)
}
if sec.Get(AccessName(co.ID)) != "tok" || sec.Get(RefreshName(co.ID)) != "ref" {
t.Error("tokens")
}
// The same account signed in again: updated, not doubled.
again := &Account{Network: X, Name: "@acme", External: "acme"}
Save(d, sec, again, "tok2", "", now)
if again.ID != co.ID || sec.Get(AccessName(co.ID)) != "tok2" || sec.Has(RefreshName(co.ID)) {
t.Errorf("again: %d %q", again.ID, sec.Get(AccessName(co.ID)))
}
jo := &Account{Network: X, Name: "@jo", External: "jo", Owner: 7}
Save(d, sec, jo, "t", "", now)
if err := Save(d, sec, &Account{Network: "myspace"}, "t", "", now); err == nil {
t.Error("unknown network")
}
if c, _ := Company(d, X); c == nil || c.ID != co.ID {
t.Errorf("company: %+v", c)
}
if c, _ := Company(d, Reddit); c != nil {
t.Error("no Reddit account")
}
list, _ := List(d)
if len(list) != 2 || list[0].ID != co.ID {
t.Errorf("list: %+v", list)
}
if own, _ := OwnedBy(d, 7); len(own) != 1 || own[0].ID != jo.ID {
t.Errorf("own: %+v", own)
}
if Channel(LinkedInPage) != LinkedIn || co.Label() != "X @acme" {
t.Error("labels")
}
if err := SetGrants(d, map[int64][]int64{co.ID: {7, 8}}); err != nil {
t.Fatal(err)
}
if ok, _ := Granted(d, co.ID, 8); !ok {
t.Error("not granted")
}
ForgetUser(d, 8)
if ok, _ := Granted(d, co.ID, 8); ok {
t.Error("forgotten user still granted")
}
g, _ := Grants(d)
if !g[co.ID][7] || len(g[co.ID]) != 1 {
t.Errorf("grants %v", g)
}
if err := Remove(d, sec, co.ID); err != nil {
t.Fatal(err)
}
if _, err := Get(d, co.ID); err != ErrNotFound || sec.Has(AccessName(co.ID)) {
t.Error("not removed")
}
if g, _ := Grants(d); len(g) != 0 {
t.Error("grants outlived the account")
}
}
func TestAdopt(t *testing.T) {
d, sec := open(t)
sec.Set(map[string]string{secrets.XAccessToken: "xt", secrets.XRefreshToken: "xr", secrets.LinkedInAccessToken: "lt"})
exp := time.Now().Add(time.Hour)
n, err := Adopt(d, sec, func(network string) (string, string, time.Time) {
return "n-" + network, "e-" + network, exp
}, time.Now())
if err != nil || n != 2 {
t.Fatalf("%d %v", n, err)
}
x, _ := Company(d, X)
if x == nil || x.Name != "n-x" || sec.Get(AccessName(x.ID)) != "xt" || sec.Get(RefreshName(x.ID)) != "xr" || sec.Has(secrets.XAccessToken) {
t.Errorf("x: %+v", x)
}
if n, _ := Adopt(d, sec, func(string) (string, string, time.Time) { return "", "", time.Time{} }, time.Now()); n != 0 {
t.Error("adopted twice")
}
}
-6
View File
@@ -57,12 +57,6 @@ const (
PlausibleAPIKey = "plausible.api_key"
StripeAPIKey = "stripe.api_key" // restricted, read-only
RedditClientID = "reddit.client_id"
RedditClientSecret = "reddit.client_secret"
RedditAccessToken = "reddit.access_token"
RedditRefreshToken = "reddit.refresh_token"
RedditUsername = "reddit.username"
)
// Store is the secrets: a file, or the database. It is safe for
+9 -1
View File
@@ -106,6 +106,7 @@ type Fetcher struct {
Client *http.Client
UserAgent string
Delay time.Duration // between requests, to be polite
MaxPages int // pages an audit reads; 0: MaxAuditPages
}
// NewFetcher returns a fetcher that doesn't follow redirects itself, so
@@ -239,7 +240,7 @@ func RunAudit(ctx context.Context, d *db.DB, f *Fetcher, siteURL, property strin
seen := map[string]bool{queue[0]: true}
add := func(u string) {
n := normalize(u)
if n == "" || seen[n] || len(seen) >= MaxAuditPages {
if n == "" || seen[n] || len(seen) >= f.maxPages() {
return
}
if p, err := url.Parse(n); err != nil || strings.TrimPrefix(p.Hostname(), "www.") != host {
@@ -801,3 +802,10 @@ func LastDoneAudit(d *db.DB, site string) time.Time {
t, _ := time.Parse(time.RFC3339, s.String)
return t
}
func (f *Fetcher) maxPages() int {
if f.MaxPages > 0 {
return f.MaxPages
}
return MaxAuditPages
}
+1 -1
View File
@@ -285,7 +285,7 @@ func AssignCampaign(d *db.DB, source, id string, signalID int64) error {
// Campaigns lists the outside campaigns, unassigned first, newest sync first.
func Campaigns(d *db.DB) ([]Campaign, error) {
rows, err := d.Query(`SELECT source, id, name, status, coalesce(signal_id, 0), spend_cents, stats, synced_at
FROM outside_campaigns ORDER BY signal_id IS NOT NULL, source, name COLLATE NOCASE`)
FROM outside_campaigns ORDER BY signal_id IS NOT NULL, source, name COLLATE NOCASE, id`)
if err != nil {
return nil, err
}
+1 -1
View File
@@ -186,7 +186,7 @@ func Get(d *db.DB, id int64) (*Signal, error) {
// retired; by name within each.
func List(d *db.DB) ([]Signal, error) {
rows, err := d.Query(`SELECT ` + columns + ` FROM signals ORDER BY
CASE status WHEN 'testing' THEN 0 WHEN 'idea' THEN 1 WHEN 'proven' THEN 2 ELSE 3 END, name COLLATE NOCASE`)
CASE status WHEN 'testing' THEN 0 WHEN 'idea' THEN 1 WHEN 'proven' THEN 2 ELSE 3 END, name COLLATE NOCASE, id`)
if err != nil {
return nil, err
}
+151
View File
@@ -0,0 +1,151 @@
package storage
import (
"context"
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
)
// Dir keeps files in a folder, readable only by the app's user.
type Dir struct {
root string
}
// OpenDir opens (creating) the folder at root.
func OpenDir(root string) (*Dir, error) {
if err := os.MkdirAll(root, 0o700); err != nil {
return nil, err
}
return &Dir{root: root}, nil
}
func (d *Dir) String() string { return d.root }
func (d *Dir) path(key string) (string, error) {
if err := CheckKey(key); err != nil {
return "", err
}
return filepath.Join(d.root, filepath.FromSlash(key)), nil
}
// Put writes to a temporary file beside the target and renames it, so a
// reader never sees half a file.
func (d *Dir) Put(ctx context.Context, key string, r io.Reader, size int64) error {
p, err := d.path(key)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
return err
}
tmp, err := os.CreateTemp(filepath.Dir(p), ".put-*")
if err != nil {
return err
}
defer os.Remove(tmp.Name()) // a no-op once renamed
if _, err := io.Copy(tmp, readerCtx{ctx, r}); err != nil {
tmp.Close()
return err
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), p)
}
func (d *Dir) Get(ctx context.Context, key string) (io.ReadCloser, error) {
p, err := d.path(key)
if err != nil {
return nil, err
}
f, err := os.Open(p)
if errors.Is(err, fs.ErrNotExist) {
return nil, ErrNotExist
}
return f, err
}
func (d *Dir) Stat(ctx context.Context, key string) (Info, error) {
p, err := d.path(key)
if err != nil {
return Info{}, err
}
fi, err := os.Stat(p)
if errors.Is(err, fs.ErrNotExist) || (err == nil && fi.IsDir()) {
return Info{}, ErrNotExist
}
if err != nil {
return Info{}, err
}
return Info{Key: key, Size: fi.Size(), Modified: fi.ModTime()}, nil
}
func (d *Dir) List(ctx context.Context, prefix string) ([]Info, error) {
if err := checkPrefix(prefix); err != nil {
return nil, err
}
var out []Info
err := filepath.WalkDir(d.root, func(p string, e fs.DirEntry, err error) error {
if err != nil {
return err
}
if e.IsDir() || strings.HasPrefix(e.Name(), ".put-") {
return nil
}
rel, err := filepath.Rel(d.root, p)
if err != nil {
return err
}
key := filepath.ToSlash(rel)
if !strings.HasPrefix(key, prefix) || strings.HasPrefix(key, ".") {
return nil
}
fi, err := e.Info()
if err != nil {
return err
}
out = append(out, Info{Key: key, Size: fi.Size(), Modified: fi.ModTime()})
return nil
})
sort.Slice(out, func(i, j int) bool { return out[i].Key < out[j].Key })
return out, err
}
// Delete removes the file, and the folders it leaves empty.
func (d *Dir) Delete(ctx context.Context, key string) error {
p, err := d.path(key)
if err != nil {
return err
}
if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
for dir := filepath.Dir(p); dir != d.root && strings.HasPrefix(dir, d.root); dir = filepath.Dir(dir) {
if os.Remove(dir) != nil { // not empty
break
}
}
return nil
}
// readerCtx stops a copy when the context ends.
type readerCtx struct {
ctx context.Context
r io.Reader
}
func (r readerCtx) Read(p []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
return r.r.Read(p)
}
+128
View File
@@ -0,0 +1,128 @@
package storage
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"supermarket/internal/config"
)
// S3 keeps files in an S3-compatible bucket (Garage), under a prefix.
type S3 struct {
c *minio.Client
bucket, prefix string // prefix: "" or ending in /
desc string
}
// OpenS3 connects to the bucket. It doesn't call the server: Check does.
func OpenS3(s config.Storage) (*S3, error) {
u, err := url.Parse(s.Endpoint)
if err != nil || u.Host == "" {
return nil, fmt.Errorf("storage: the S3 address %q isn't usable", s.Endpoint)
}
c, err := minio.New(u.Host, &minio.Options{
Creds: credentials.NewStaticV4(s.AccessKey, s.SecretKey, ""),
Secure: u.Scheme == "https",
Region: s.Region,
BucketLookup: minio.BucketLookupPath, // bucket in the path: Garage's default, and no wildcard DNS needed
})
if err != nil {
return nil, err
}
prefix := strings.Trim(s.Prefix, "/")
if prefix != "" {
prefix += "/"
}
return &S3{c: c, bucket: s.Bucket, prefix: prefix, desc: s.String()}, nil
}
func (s *S3) String() string { return s.desc }
func (s *S3) object(key string) (string, error) {
if err := CheckKey(key); err != nil {
return "", err
}
return s.prefix + key, nil
}
// notFound turns S3's "no such key" into ErrNotExist.
func notFound(err error) error {
var e minio.ErrorResponse
if errors.As(err, &e) && (e.Code == "NoSuchKey" || e.StatusCode == http.StatusNotFound) {
return ErrNotExist
}
return err
}
func (s *S3) Put(ctx context.Context, key string, r io.Reader, size int64) error {
obj, err := s.object(key)
if err != nil {
return err
}
_, err = s.c.PutObject(ctx, s.bucket, obj, r, size, minio.PutObjectOptions{ContentType: "application/octet-stream"})
return err
}
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) {
obj, err := s.object(key)
if err != nil {
return nil, err
}
o, err := s.c.GetObject(ctx, s.bucket, obj, minio.GetObjectOptions{})
if err != nil {
return nil, notFound(err)
}
// GetObject doesn't ask the server until read: ask now, so a missing
// file is ErrNotExist here, as with a folder.
if _, err := o.Stat(); err != nil {
o.Close()
return nil, notFound(err)
}
return o, nil
}
func (s *S3) Stat(ctx context.Context, key string) (Info, error) {
obj, err := s.object(key)
if err != nil {
return Info{}, err
}
oi, err := s.c.StatObject(ctx, s.bucket, obj, minio.StatObjectOptions{})
if err != nil {
return Info{}, notFound(err)
}
return Info{Key: key, Size: oi.Size, Modified: oi.LastModified}, nil
}
func (s *S3) List(ctx context.Context, prefix string) ([]Info, error) {
if err := checkPrefix(prefix); err != nil {
return nil, err
}
var out []Info
for oi := range s.c.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: s.prefix + prefix, Recursive: true}) {
if oi.Err != nil {
return nil, oi.Err
}
key := strings.TrimPrefix(oi.Key, s.prefix)
if strings.HasPrefix(key, ".") {
continue
}
out = append(out, Info{Key: key, Size: oi.Size, Modified: oi.LastModified})
}
return out, nil
}
func (s *S3) Delete(ctx context.Context, key string) error {
obj, err := s.object(key)
if err != nil {
return err
}
return s.c.RemoveObject(ctx, s.bucket, obj, minio.RemoveObjectOptions{})
}
+170
View File
@@ -0,0 +1,170 @@
// Package storage keeps the files that must outlast the app's own disk:
// exports, uploaded files, images. The local and server editions keep
// them in a folder; the multi-tenant edition in an S3-compatible bucket
// (Garage), so every copy of the app sees the same files.
//
// Not for scratch: the sites' git clones and page previews stay on local
// disk, as a cache that can be made again.
package storage
import (
"context"
"errors"
"fmt"
"io"
"path"
"strings"
"time"
"supermarket/internal/config"
)
// ErrNotExist is returned for a file that isn't there.
var ErrNotExist = errors.New("no such file")
// Info describes a stored file.
type Info struct {
Key string // its name: slash-separated, such as exports/2026-11-25.tar.gz
Size int64
Modified time.Time
}
// Store keeps files by key.
type Store interface {
// Put stores r's contents as key, replacing any file there. size is
// the length, or -1 if unknown.
Put(ctx context.Context, key string, r io.Reader, size int64) error
// Get opens a file; ErrNotExist if there's none.
Get(ctx context.Context, key string) (io.ReadCloser, error)
// Stat describes a file; ErrNotExist if there's none.
Stat(ctx context.Context, key string) (Info, error)
// List lists the files whose keys start with prefix, by key.
List(ctx context.Context, prefix string) ([]Info, error)
// Delete removes a file; one that isn't there is not an error.
Delete(ctx context.Context, key string) error
// String says where the files are, without credentials.
String() string
}
// CheckKey refuses a key that isn't a plain, relative, slash-separated
// name: no "..", no leading slash, no empty parts, no backslashes.
func CheckKey(key string) error {
if key == "" || strings.HasPrefix(key, "/") || strings.HasSuffix(key, "/") || strings.Contains(key, "\\") ||
strings.ContainsRune(key, 0) || path.Clean(key) != key || key == "." || strings.HasPrefix(key, "../") || key == ".." {
return fmt.Errorf("storage: %q isn't a usable file name", key)
}
for _, part := range strings.Split(key, "/") {
if part == "." || part == ".." || part == "" {
return fmt.Errorf("storage: %q isn't a usable file name", key)
}
}
return nil
}
// checkPrefix allows "" (everything), or a key's leading part.
func checkPrefix(prefix string) error {
if prefix == "" {
return nil
}
return CheckKey(strings.TrimSuffix(prefix, "/") + "/x")
}
// Open opens the store the settings name: a folder, or an S3 bucket.
func Open(s config.Storage) (Store, error) {
if s.S3() {
return OpenS3(s)
}
return OpenDir(s.Dir)
}
// Check writes, reads and deletes a small file, to show the store works
// (the S3 server is reachable, and the key may write to the bucket).
func Check(ctx context.Context, st Store) error {
const key = ".supermarket-check"
want := "checked " + time.Now().UTC().Format(time.RFC3339Nano)
if err := st.Put(ctx, key, strings.NewReader(want), int64(len(want))); err != nil {
return fmt.Errorf("writing to %s: %w", st, err)
}
r, err := st.Get(ctx, key)
if err != nil {
return fmt.Errorf("reading from %s: %w", st, err)
}
got, err := io.ReadAll(r)
r.Close()
if err != nil {
return fmt.Errorf("reading from %s: %w", st, err)
}
if string(got) != want {
return fmt.Errorf("%s gave back something else than was written", st)
}
if err := st.Delete(ctx, key); err != nil {
return fmt.Errorf("deleting from %s: %w", st, err)
}
return nil
}
// Under is a store whose files are under prefix in another: each team's
// own place in the platform's store. Keys are checked before the prefix
// is added, so none reaches outside it.
func Under(s Store, prefix string) Store {
return &under{s: s, prefix: strings.Trim(prefix, "/") + "/"}
}
type under struct {
s Store
prefix string
}
func (u *under) key(k string) (string, error) {
if err := CheckKey(k); err != nil {
return "", err
}
return u.prefix + k, nil
}
func (u *under) Put(ctx context.Context, key string, r io.Reader, size int64) error {
k, err := u.key(key)
if err != nil {
return err
}
return u.s.Put(ctx, k, r, size)
}
func (u *under) Get(ctx context.Context, key string) (io.ReadCloser, error) {
k, err := u.key(key)
if err != nil {
return nil, err
}
return u.s.Get(ctx, k)
}
func (u *under) Stat(ctx context.Context, key string) (Info, error) {
k, err := u.key(key)
if err != nil {
return Info{}, err
}
i, err := u.s.Stat(ctx, k)
i.Key = strings.TrimPrefix(i.Key, u.prefix)
return i, err
}
func (u *under) List(ctx context.Context, prefix string) ([]Info, error) {
if strings.Contains(prefix, "..") || strings.HasPrefix(prefix, "/") || strings.Contains(prefix, "\\") {
return nil, fmt.Errorf("storage: %q isn't a usable prefix", prefix)
}
list, err := u.s.List(ctx, u.prefix+prefix)
for i := range list {
list[i].Key = strings.TrimPrefix(list[i].Key, u.prefix)
}
return list, err
}
func (u *under) Delete(ctx context.Context, key string) error {
k, err := u.key(key)
if err != nil {
return err
}
return u.s.Delete(ctx, k)
}
func (u *under) String() string { return u.s.String() + " under " + u.prefix }
+209
View File
@@ -0,0 +1,209 @@
package storage
import (
"context"
"errors"
"fmt"
"io"
"net/url"
"os"
"strings"
"testing"
"time"
"supermarket/internal/config"
)
// TestS3 names an S3 bucket to test on, as
// http://ACCESS_KEY:SECRET_KEY@host:port/bucket, e.g. a Garage in Docker.
// Each run uses its own prefix in it, and empties it afterwards.
const TestS3 = "SUPERMARKET_TEST_S3"
func stores(t *testing.T) map[string]Store {
t.Helper()
out := map[string]Store{}
d, err := OpenDir(t.TempDir())
if err != nil {
t.Fatal(err)
}
out["folder"] = d
if raw := os.Getenv(TestS3); raw != "" {
u, err := url.Parse(raw)
if err != nil || u.User == nil {
t.Fatalf("%s: %v", TestS3, err)
}
pw, _ := u.User.Password()
s, err := OpenS3(config.Storage{
Endpoint: u.Scheme + "://" + u.Host, Bucket: strings.Trim(u.Path, "/"), Region: "garage",
Prefix: fmt.Sprintf("test-%d-%d", os.Getpid(), time.Now().UnixNano()),
AccessKey: u.User.Username(), SecretKey: pw,
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
ctx := context.Background()
all, _ := s.List(ctx, "")
for _, f := range all {
s.Delete(ctx, f.Key)
}
})
out["s3"] = s
}
return out
}
func read(t *testing.T, st Store, key string) string {
t.Helper()
r, err := st.Get(context.Background(), key)
if err != nil {
t.Fatalf("get %s: %v", key, err)
}
defer r.Close()
b, err := io.ReadAll(r)
if err != nil {
t.Fatal(err)
}
return string(b)
}
// Every store behaves the same.
func TestStores(t *testing.T) {
ctx := context.Background()
for name, st := range stores(t) {
t.Run(name, func(t *testing.T) {
if err := Check(ctx, st); err != nil {
t.Fatal(err)
}
if err := st.Put(ctx, "exports/a.txt", strings.NewReader("first"), 5); err != nil {
t.Fatal(err)
}
if err := st.Put(ctx, "exports/a.txt", strings.NewReader("second, longer"), -1); err != nil { // replaced; size unknown
t.Fatal(err)
}
st.Put(ctx, "exports/2026/b.bin", strings.NewReader(strings.Repeat("x", 70000)), 70000)
st.Put(ctx, "uploads/c.png", strings.NewReader("png"), 3)
if got := read(t, st, "exports/a.txt"); got != "second, longer" {
t.Errorf("read %q", got)
}
info, err := st.Stat(ctx, "exports/2026/b.bin")
if err != nil || info.Size != 70000 || info.Key != "exports/2026/b.bin" || time.Since(info.Modified) > time.Hour {
t.Errorf("stat: %+v %v", info, err)
}
list, err := st.List(ctx, "exports/")
if err != nil {
t.Fatal(err)
}
var keys []string
for _, f := range list {
keys = append(keys, f.Key)
}
if strings.Join(keys, " ") != "exports/2026/b.bin exports/a.txt" {
t.Errorf("list: %v", keys)
}
if all, _ := st.List(ctx, ""); len(all) != 3 {
t.Errorf("everything: %v (the check file should be gone)", all)
}
// Missing files.
if _, err := st.Get(ctx, "exports/none"); !errors.Is(err, ErrNotExist) {
t.Errorf("get missing: %v", err)
}
if _, err := st.Stat(ctx, "exports"); !errors.Is(err, ErrNotExist) { // a folder isn't a file
t.Errorf("stat folder: %v", err)
}
if err := st.Delete(ctx, "exports/a.txt"); err != nil {
t.Fatal(err)
}
if err := st.Delete(ctx, "exports/a.txt"); err != nil {
t.Errorf("deleting twice: %v", err)
}
if _, err := st.Stat(ctx, "exports/a.txt"); !errors.Is(err, ErrNotExist) {
t.Errorf("after delete: %v", err)
}
// Names that would reach outside the store.
for _, bad := range []string{"", "/etc/passwd", "../x", "a/../../x", "a//b", "a/./b", "a/", `a\b`, ".."} {
if err := st.Put(ctx, bad, strings.NewReader("x"), 1); err == nil {
t.Errorf("put %q accepted", bad)
}
}
if _, err := st.List(ctx, "../"); err == nil {
t.Error("list ../ accepted")
}
})
}
}
// A folder store's files are the user's only, and a half-written file is
// never seen.
func TestDirFiles(t *testing.T) {
root := t.TempDir() + "/files"
d, err := OpenDir(root)
if err != nil {
t.Fatal(err)
}
d.Put(context.Background(), "a/b.txt", strings.NewReader("x"), 1)
for _, p := range []string{root, root + "/a", root + "/a/b.txt"} {
fi, err := os.Stat(p)
if err != nil {
t.Fatal(err)
}
if fi.Mode().Perm()&0o077 != 0 {
t.Errorf("%s is %v", p, fi.Mode().Perm())
}
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := d.Put(ctx, "a/c.txt", strings.NewReader("never"), 5); err == nil {
t.Error("a cancelled write went through")
}
if list, _ := d.List(context.Background(), ""); len(list) != 1 {
t.Errorf("left behind: %v", list)
}
d.Delete(context.Background(), "a/b.txt")
if _, err := os.Stat(root + "/a"); !os.IsNotExist(err) {
t.Error("the empty folder stayed")
}
}
// A wrong key is caught by Check, saying where.
func TestS3WrongKey(t *testing.T) {
raw := os.Getenv(TestS3)
if raw == "" {
t.Skip("set " + TestS3)
}
u, _ := url.Parse(raw)
s, err := OpenS3(config.Storage{Endpoint: u.Scheme + "://" + u.Host, Bucket: strings.Trim(u.Path, "/"), Region: "garage",
AccessKey: u.User.Username(), SecretKey: "wrong"})
if err != nil {
t.Fatal(err)
}
if err := Check(context.Background(), s); err == nil || !strings.Contains(err.Error(), "writing to s3://") {
t.Fatalf("check: %v", err)
}
}
func TestUnder(t *testing.T) {
base, err := Open(config.Storage{Dir: t.TempDir()})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
a, b := Under(base, "teams/1"), Under(base, "teams/2/")
if err := a.Put(ctx, "photos/x.png", strings.NewReader("A"), 1); err != nil {
t.Fatal(err)
}
if _, err := b.Stat(ctx, "photos/x.png"); err == nil {
t.Error("team 2 sees team 1's file")
}
if i, err := base.Stat(ctx, "teams/1/photos/x.png"); err != nil || i.Size != 1 {
t.Errorf("in the store: %+v %v", i, err)
}
if list, _ := a.List(ctx, "photos/"); len(list) != 1 || list[0].Key != "photos/x.png" {
t.Errorf("list %+v", list)
}
if err := a.Put(ctx, "../2/photos/y.png", strings.NewReader("x"), 1); err == nil {
t.Error("reached outside its prefix")
}
}
+34
View File
@@ -0,0 +1,34 @@
package transfer
import (
"archive/tar"
"bytes"
"compress/gzip"
"io"
"testing"
"time"
)
// rewrite replaces one file in an export.
func rewrite(t *testing.T, export []byte, name, body string) []byte {
t.Helper()
var out bytes.Buffer
gz := gzip.NewWriter(&out)
tw := tar.NewWriter(gz)
err := walk(bytes.NewReader(export), func(n string, r io.Reader) error {
raw, err := io.ReadAll(r)
if err != nil {
return err
}
if n == name {
raw = []byte(body)
}
return addFile(tw, n, raw, time.Now())
})
if err != nil {
t.Fatal(err)
}
tw.Close()
gz.Close()
return out.Bytes()
}
+544
View File
@@ -0,0 +1,544 @@
// Package transfer moves a whole Supermarket from one database to
// another: an export is a .tar.gz of every table's rows (as JSON lines),
// a manifest, and, if asked for, the secrets. It reads from SQLite or
// Postgres and loads into either, so a local install can move to a
// server.
package transfer
import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"slices"
"strings"
"time"
"supermarket/internal/db"
"supermarket/internal/secrets"
)
// Format is this export format's version.
const Format = 1
// Manifest describes an export.
type Manifest struct {
Format int `json:"format"`
Schema int `json:"schema"`
App string `json:"app"`
From string `json:"from"` // SQLite, Postgres
Created time.Time `json:"created"`
Tables map[string]int `json:"tables"` // rows per table
Secrets int `json:"secrets"`
}
// skipped are tables about the database or machine itself, not the
// company's data. Secrets go in secrets.json, opened, if asked for.
var skipped = map[string]bool{
"instances": true, "locks": true, "schema_version": true, "schema_migrations": true, "secrets": true,
"sessions": true, "links": true, "throttle": true, "agent_calls": true,
}
// startupSettings are settings a new install writes when it first starts:
// a database holding only those is still empty, and the export's values
// replace them (the IndexNow key the website publishes is the old one).
var startupSettings = []string{"seo:indexnow-key"}
// skipRow leaves out settings only meaningful where they were made.
func skipRow(table string, row map[string]any) bool {
if table != "settings" {
return false
}
k, _ := row["key"].(string)
return strings.HasPrefix(k, "oauth:flow:")
}
// Tables are the database's tables to move, parents before children
// (by foreign keys).
func Tables(d *db.DB) ([]string, error) {
var q string
if d.Dialect == db.Postgres {
q = `SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type = 'BASE TABLE'`
} else {
q = `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`
}
names, err := strs(d, q)
if err != nil {
return nil, err
}
deps := map[string][]string{}
for _, t := range names {
if d.Dialect == db.Postgres {
deps[t], err = strs(d, `SELECT DISTINCT ccu.table_name FROM information_schema.table_constraints tc
JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = ?`, t)
} else {
deps[t], err = strs(d, `SELECT DISTINCT "table" FROM pragma_foreign_key_list(?)`, t)
}
if err != nil {
return nil, err
}
}
slices.Sort(names)
var out []string
done := map[string]bool{}
var visit func(t string, stack []string) error
visit = func(t string, stack []string) error {
if done[t] {
return nil
}
if slices.Contains(stack, t) {
return fmt.Errorf("tables refer to each other in a loop: %v", append(stack, t))
}
for _, p := range deps[t] {
if p != t {
if err := visit(p, append(stack, t)); err != nil {
return err
}
}
}
done[t] = true
if !skipped[t] {
out = append(out, t)
}
return nil
}
for _, t := range names {
if err := visit(t, nil); err != nil {
return nil, err
}
}
return out, nil
}
func strs(d *db.DB, q string, args ...any) ([]string, error) {
rows, err := d.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var s string
if err := rows.Scan(&s); err != nil {
return nil, err
}
out = append(out, s)
}
return out, rows.Err()
}
// columns are a table's columns, in order.
func columns(d *db.DB, table string) ([]string, error) {
if d.Dialect == db.Postgres {
return strs(d, `SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position`, table)
}
return strs(d, `SELECT name FROM pragma_table_info(?) ORDER BY cid`, table)
}
// quote quotes a name for SQL (both databases).
func quote(name string) string { return `"` + strings.ReplaceAll(name, `"`, `""`) + `"` }
// Export writes d's data to w as a .tar.gz; with sec, its secrets too
// (opened: the file holds credentials).
func Export(ctx context.Context, d *db.DB, sec *secrets.Store, app string, w io.Writer) (*Manifest, error) {
version, err := d.SchemaVersion()
if err != nil {
return nil, err
}
m := &Manifest{Format: Format, Schema: version, App: app, From: d.Dialect.String(), Created: time.Now().UTC(), Tables: map[string]int{}}
tables, err := Tables(d)
if err != nil {
return nil, err
}
gz := gzip.NewWriter(w)
tw := tar.NewWriter(gz)
for _, t := range tables {
if err := ctx.Err(); err != nil {
return nil, err
}
n, err := exportTable(d, t, tw, m.Created)
if err != nil {
return nil, fmt.Errorf("%s: %w", t, err)
}
m.Tables[t] = n
}
if sec != nil {
vals := map[string]string{}
for _, name := range sec.Names() {
vals[name] = sec.Get(name)
}
m.Secrets = len(vals)
raw, _ := json.MarshalIndent(vals, "", " ")
if err := addFile(tw, "secrets.json", raw, m.Created); err != nil {
return nil, err
}
}
raw, _ := json.MarshalIndent(m, "", " ")
if err := addFile(tw, "manifest.json", raw, m.Created); err != nil {
return nil, err
}
if err := tw.Close(); err != nil {
return nil, err
}
return m, gz.Close()
}
// exportTable writes a table's rows as JSON lines. They're spooled to a
// temporary file first: tar needs the size before the contents.
func exportTable(d *db.DB, table string, tw *tar.Writer, at time.Time) (int, error) {
cols, err := columns(d, table)
if err != nil {
return 0, err
}
tmp, err := os.CreateTemp("", "export-*.jsonl")
if err != nil {
return 0, err
}
defer os.Remove(tmp.Name())
defer tmp.Close()
bw := bufio.NewWriter(tmp)
enc := json.NewEncoder(bw)
quoted := make([]string, len(cols))
for i, c := range cols {
quoted[i] = quote(c)
}
rows, err := d.Query(`SELECT ` + strings.Join(quoted, ", ") + ` FROM ` + quote(table))
if err != nil {
return 0, err
}
defer rows.Close()
n := 0
vals := make([]any, len(cols))
ptrs := make([]any, len(cols))
for i := range vals {
ptrs[i] = &vals[i]
}
for rows.Next() {
if err := rows.Scan(ptrs...); err != nil {
return n, err
}
row := make(map[string]any, len(cols))
for i, c := range cols {
v := vals[i]
if b, ok := v.([]byte); ok { // SQLite text read as bytes
v = string(b)
}
row[c] = v
}
if skipRow(table, row) {
continue
}
if err := enc.Encode(row); err != nil {
return n, err
}
n++
}
if err := rows.Err(); err != nil {
return n, err
}
if err := bw.Flush(); err != nil {
return n, err
}
size, err := tmp.Seek(0, io.SeekCurrent)
if err != nil {
return n, err
}
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return n, err
}
if err := tw.WriteHeader(&tar.Header{Name: "tables/" + table + ".jsonl", Mode: 0o600, Size: size, ModTime: at}); err != nil {
return n, err
}
_, err = io.Copy(tw, tmp)
return n, err
}
func addFile(tw *tar.Writer, name string, raw []byte, at time.Time) error {
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(raw)), ModTime: at}); err != nil {
return err
}
_, err := tw.Write(raw)
return err
}
// ReadManifest reads an export's manifest without loading it.
func ReadManifest(r io.Reader) (*Manifest, error) {
var m *Manifest
err := walk(r, func(name string, body io.Reader) error {
if name == "manifest.json" {
m = &Manifest{}
return json.NewDecoder(body).Decode(m)
}
return nil
})
if err == nil && m == nil {
err = errors.New("not a Supermarket export: it has no manifest")
}
return m, err
}
func walk(r io.Reader, fn func(name string, body io.Reader) error) error {
gz, err := gzip.NewReader(r)
if err != nil {
return fmt.Errorf("not a Supermarket export (.tar.gz): %w", err)
}
tr := tar.NewReader(gz)
for {
h, err := tr.Next()
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return err
}
if err := fn(h.Name, tr); err != nil {
return fmt.Errorf("%s: %w", h.Name, err)
}
}
}
// Imported says what an import did.
type Imported struct {
Manifest *Manifest
Tables map[string]int
Secrets int
}
// batchParams keeps a multi-row INSERT under both databases' limits on
// parameters (SQLite 32766, Postgres 65535).
const batchParams = 30000
// Import loads an export into d, which must be empty and at the same
// schema version; with sec, its secrets go there too. It reads the file
// twice (the manifest is last), so it takes a way to open it. Everything
// happens in one transaction: a failure leaves d as it was.
func Import(ctx context.Context, d *db.DB, sec *secrets.Store, open func() (io.ReadCloser, error)) (*Imported, error) {
f, err := open()
if err != nil {
return nil, err
}
m, err := ReadManifest(f)
f.Close()
if err != nil {
return nil, err
}
if m.Format != Format {
return nil, fmt.Errorf("the export is in format %d; this version reads format %d", m.Format, Format)
}
version, err := d.SchemaVersion()
if err != nil {
return nil, err
}
if m.Schema != version {
return nil, fmt.Errorf("the export is at schema %d and this database at %d: export and import with the same version of Supermarket", m.Schema, version)
}
tables, err := Tables(d)
if err != nil {
return nil, err
}
for _, t := range tables {
var n int
q, args := `SELECT count(*) FROM `+quote(t), []any{}
if t == "settings" {
q += ` WHERE key NOT IN (` + strings.TrimSuffix(strings.Repeat("?, ", len(startupSettings)), ", ") + `)`
for _, k := range startupSettings {
args = append(args, k)
}
}
if err := d.QueryRow(q, args...).Scan(&n); err != nil {
return nil, err
}
if n > 0 {
return nil, fmt.Errorf("this database isn't empty (%s has %d rows): import into a new one", t, n)
}
}
for t := range m.Tables {
if !slices.Contains(tables, t) {
return nil, fmt.Errorf("the export has a table %s that this database doesn't", t)
}
}
// Read the tables (they're small enough to hold: Federated's 110,000
// rows are some 30 MB), then insert them parents first.
data := map[string][]byte{}
var secretVals map[string]string
f, err = open()
if err != nil {
return nil, err
}
err = walk(f, func(name string, body io.Reader) error {
switch {
case strings.HasPrefix(name, "tables/") && strings.HasSuffix(name, ".jsonl"):
raw, err := io.ReadAll(body)
data[strings.TrimSuffix(strings.TrimPrefix(name, "tables/"), ".jsonl")] = raw
return err
case name == "secrets.json":
return json.NewDecoder(body).Decode(&secretVals)
}
return nil
})
f.Close()
if err != nil {
return nil, err
}
// Every table's columns, read now: SQLite has one connection, which
// the transaction will hold.
cols := map[string][]string{}
for _, t := range tables {
if cols[t], err = columns(d, t); err != nil {
return nil, err
}
}
res := &Imported{Manifest: m, Tables: map[string]int{}}
tx, err := d.Begin()
if err != nil {
return nil, err
}
defer tx.Rollback()
for _, t := range tables {
raw, ok := data[t]
if !ok {
continue
}
if err := ctx.Err(); err != nil {
return nil, err
}
n, err := importTable(tx, t, cols[t], raw)
if err != nil {
return nil, fmt.Errorf("%s: %w", t, err)
}
if n != m.Tables[t] {
return nil, fmt.Errorf("%s: read %d rows, the manifest says %d", t, n, m.Tables[t])
}
res.Tables[t] = n
}
if d.Dialect == db.Postgres {
if err := resetIdentities(tx); err != nil {
return nil, err
}
}
if err := tx.Commit(); err != nil {
return nil, err
}
if sec != nil && len(secretVals) > 0 {
if err := sec.Set(secretVals); err != nil {
return res, fmt.Errorf("the data is in, but not the secrets: %w", err)
}
res.Secrets = len(secretVals)
}
return res, nil
}
// importTable inserts a table's JSON lines, in batches.
func importTable(tx *db.Tx, table string, cols []string, raw []byte) (int, error) {
have := map[string]bool{}
quoted := make([]string, len(cols))
for i, c := range cols {
have[c] = true
quoted[i] = quote(c)
}
per := max(1, batchParams/len(cols))
one := "(" + strings.TrimSuffix(strings.Repeat("?, ", len(cols)), ", ") + ")"
var batch []any
rowsIn, n := 0, 0
flush := func() error {
if rowsIn == 0 {
return nil
}
q := `INSERT INTO ` + quote(table) + ` (` + strings.Join(quoted, ", ") + `) VALUES ` +
strings.TrimSuffix(strings.Repeat(one+", ", rowsIn), ", ")
if table == "settings" { // replacing what a new install wrote at start
q += ` ON CONFLICT (key) DO UPDATE SET value = excluded.value`
}
if _, err := tx.Exec(q, batch...); err != nil {
return err
}
batch, rowsIn = batch[:0], 0
return nil
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
for {
var row map[string]any
if err := dec.Decode(&row); errors.Is(err, io.EOF) {
break
} else if err != nil {
return n, fmt.Errorf("row %d: %w", n+1, err)
}
for c := range row {
if !have[c] {
return n, fmt.Errorf("the export has a column %s this database doesn't", c)
}
}
for _, c := range cols {
v, err := value(row[c])
if err != nil {
return n, fmt.Errorf("row %d, %s: %w", n+1, c, err)
}
batch = append(batch, v)
}
rowsIn++
n++
if rowsIn == per {
if err := flush(); err != nil {
return n, err
}
}
}
return n, flush()
}
// value turns a JSON value back into what the database takes.
func value(v any) (any, error) {
switch x := v.(type) {
case json.Number:
if i, err := x.Int64(); err == nil {
return i, nil
}
return x.Float64()
case string:
if strings.ContainsRune(x, 0) {
return strings.ReplaceAll(x, "\x00", ""), nil // Postgres' text can't hold NUL
}
return x, nil
case nil, bool:
return x, nil
}
return nil, fmt.Errorf("unexpected %T", v)
}
// resetIdentities moves Postgres' identity counters past the imported
// ids, so new rows don't collide with them.
func resetIdentities(tx *db.Tx) error {
rows, err := tx.Query(`SELECT table_name, column_name FROM information_schema.columns
WHERE table_schema = current_schema() AND is_identity = 'YES'`)
if err != nil {
return err
}
type col struct{ table, column string }
var cols []col
for rows.Next() {
var c col
if err := rows.Scan(&c.table, &c.column); err != nil {
rows.Close()
return err
}
cols = append(cols, c)
}
rows.Close()
for _, c := range cols {
if _, err := tx.Exec(`SELECT setval(pg_get_serial_sequence(?, ?), coalesce((SELECT max(`+quote(c.column)+`) FROM `+quote(c.table)+`), 0) + 1, false)`,
quote(c.table), c.column); err != nil {
return fmt.Errorf("%s: %w", c.table, err)
}
}
return nil
}
+167
View File
@@ -0,0 +1,167 @@
package transfer
import (
"bytes"
"context"
"io"
"path/filepath"
"strings"
"testing"
"time"
"supermarket/internal/db"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/signals"
)
func open(t *testing.T, sqlite bool) *db.DB {
t.Helper()
path := filepath.Join(t.TempDir(), "app.db")
var d *db.DB
var err error
if sqlite {
d, err = db.OpenSQLite(path)
} else {
d, err = db.Open(path) // Postgres when tests run on it
}
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
return d
}
// A local install (SQLite) moves to the test database (Postgres when the
// tests run on it), with its rows, ids, case-insensitive text, and
// secrets.
func TestExportImport(t *testing.T) {
src := open(t, true)
now := time.Date(2026, 11, 25, 9, 0, 0, 0, time.UTC)
sig := &signals.Signal{Name: "Leaving M365", Spot: "m365 alternative"}
if err := signals.Save(src, sig); err != nil {
t.Fatal(err)
}
co, _, err := prospects.AddCompany(src, prospects.Company{Name: "Acme", Domain: "Acme.com", Source: "manual", SignalID: sig.ID}, now)
if err != nil {
t.Fatal(err)
}
if _, _, err := prospects.AddContact(src, prospects.Contact{CompanyID: co, FirstName: "Ann", Email: "Ann@Acme.com", Source: "manual", SignalID: sig.ID}, now); err != nil {
t.Fatal(err)
}
src.PutJSON("test:setting", map[string]any{"big": int64(9007199254740993), "f": 1.5, "s": "it's \"quoted\"\nand ünïcode"})
src.PutJSON("oauth:flow:abc", map[string]string{"left": "out"})
srcSec, _ := secrets.Open(filepath.Join(t.TempDir(), "secrets.json"))
srcSec.Set(map[string]string{secrets.StripeAPIKey: "rk_1", secrets.GiteaToken: "gt"})
var buf bytes.Buffer
m, err := Export(context.Background(), src, srcSec, "test", &buf)
if err != nil {
t.Fatal(err)
}
if m.Tables["signals"] != 1 || m.Tables["prospect_contacts"] != 1 || m.Secrets != 2 || m.From != "SQLite" || m.Schema != db.Schema() {
t.Fatalf("manifest: %+v", m)
}
if _, ok := m.Tables["locks"]; ok {
t.Error("exported the locks")
}
openBuf := func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(buf.Bytes())), nil }
dst := open(t, false)
var dstSec *secrets.Store
if dst.Dialect == db.Postgres {
dstSec, err = secrets.OpenDB(dst, []byte("0123456789abcdef0123456789abcdef"), nil)
} else {
dstSec, err = secrets.Open(filepath.Join(t.TempDir(), "secrets.json"))
}
if err != nil {
t.Fatal(err)
}
dst.PutJSON("seo:indexnow-key", "written-at-start") // as a new install does
src.PutJSON("seo:indexnow-key", "the-sites-key")
buf.Reset()
if _, err := Export(context.Background(), src, srcSec, "test", &buf); err != nil {
t.Fatal(err)
}
res, err := Import(context.Background(), dst, dstSec, openBuf)
if err != nil {
t.Fatal(err)
}
if res.Tables["prospect_companies"] != 1 || res.Secrets != 2 || dstSec.Get(secrets.StripeAPIKey) != "rk_1" {
t.Fatalf("imported: %+v", res)
}
// The rows came across as they were, and still ignore case.
var name, email string
var signal int64
if err := dst.QueryRow(`SELECT c.first_name, c.email, c.signal_id FROM prospect_contacts c JOIN prospect_companies p ON p.id = c.company_id
WHERE c.email = 'ann@acme.com' AND p.domain = 'acme.com'`).Scan(&name, &email, &signal); err != nil {
t.Fatal(err)
}
if name != "Ann" || email != "ann@acme.com" || signal != sig.ID {
t.Errorf("contact: %s %s %d", name, email, signal)
}
var key string
if dst.GetJSON("seo:indexnow-key", &key); key != "the-sites-key" {
t.Errorf("IndexNow key: %q", key)
}
var got map[string]any
dst.GetJSON("test:setting", &got)
if got["s"] != "it's \"quoted\"\nand ünïcode" || got["f"] != 1.5 {
t.Errorf("setting: %#v", got)
}
var raw string
dst.QueryRow(`SELECT value FROM settings WHERE key = 'test:setting'`).Scan(&raw)
if !strings.Contains(raw, "9007199254740993") {
t.Errorf("a large number changed: %s", raw)
}
if ok, _ := dst.GetJSON("oauth:flow:abc", &got); ok {
t.Error("a sign-in under way came across")
}
// New rows get new ids, past the imported ones.
sig2 := &signals.Signal{Name: "Another", Spot: "x"}
if err := signals.Save(dst, sig2); err != nil || sig2.ID <= sig.ID {
t.Errorf("a new row after the import: id %d, %v", sig2.ID, err)
}
// Only into an empty database, at the same schema.
if _, err := Import(context.Background(), dst, nil, openBuf); err == nil || !strings.Contains(err.Error(), "isn't empty") {
t.Errorf("into a full database: %v", err)
}
if _, err := Import(context.Background(), open(t, true), nil, func() (io.ReadCloser, error) {
return io.NopCloser(strings.NewReader("not an export")), nil
}); err == nil || !strings.Contains(err.Error(), "not a Supermarket export") {
t.Errorf("a stray file: %v", err)
}
// Without secrets, there are none in the file.
buf.Reset()
if m, _ := Export(context.Background(), src, nil, "test", &buf); m.Secrets != 0 || bytes.Contains(buf.Bytes(), []byte("rk_1")) {
t.Error("secrets exported when not asked for")
}
}
// A failed import leaves the database empty.
func TestImportAllOrNothing(t *testing.T) {
src := open(t, true)
signals.Save(src, &signals.Signal{Name: "A", Spot: "a"})
var buf bytes.Buffer
if _, err := Export(context.Background(), src, nil, "test", &buf); err != nil {
t.Fatal(err)
}
// Break one table's rows: the manifest says 1, give none.
broken := rewrite(t, buf.Bytes(), "tables/signals.jsonl", "")
dst := open(t, false)
_, err := Import(context.Background(), dst, nil, func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(broken)), nil })
if err == nil || !strings.Contains(err.Error(), "manifest says 1") {
t.Fatalf("import: %v", err)
}
var n int
dst.QueryRow(`SELECT count(*) FROM settings`).Scan(&n)
tables, _ := Tables(dst)
for _, tb := range tables {
dst.QueryRow(`SELECT count(*) FROM ` + quote(tb)).Scan(&n)
if n != 0 {
t.Errorf("%s has %d rows after a failed import", tb, n)
}
}
}
+125
View File
@@ -0,0 +1,125 @@
package users
import (
"database/sql"
"errors"
"time"
"supermarket/internal/db"
)
// An agent's limits: calls a minute, things sent out a day, and whether
// it's paused. Agents without a row have the defaults.
// Default limits.
const (
DefaultPerMinute = 60
DefaultOutPerDay = 50
)
// Limits are an agent's.
type Limits struct {
PerMinute int
OutPerDay int
Paused time.Time // zero when running
PausedBy int64
}
// LimitsOf are an agent's limits.
func LimitsOf(d *db.DB, agent int64) (Limits, error) {
l := Limits{PerMinute: DefaultPerMinute, OutPerDay: DefaultOutPerDay}
var paused string
err := d.QueryRow(`SELECT per_minute, out_per_day, paused_at, paused_by FROM agent_limits WHERE agent_id = ?`, agent).
Scan(&l.PerMinute, &l.OutPerDay, &paused, &l.PausedBy)
if errors.Is(err, sql.ErrNoRows) {
return l, nil
}
l.Paused = parseTS(paused)
return l, err
}
// SetLimits changes an agent's calls a minute and sends a day (each at
// least 1).
func SetLimits(d *db.DB, agent int64, perMinute, outPerDay int) error {
if perMinute < 1 || outPerDay < 1 {
return errors.New("limits are at least 1")
}
_, err := d.Exec(`INSERT INTO agent_limits (agent_id, per_minute, out_per_day) VALUES (?, ?, ?)
ON CONFLICT (agent_id) DO UPDATE SET per_minute = excluded.per_minute, out_per_day = excluded.out_per_day`, agent, perMinute, outPerDay)
return err
}
// Pause stops all of an agent's calls (by: who), or lets them go on.
func Pause(d *db.DB, agent int64, paused bool, by int64, now time.Time) error {
at := ""
if paused {
at = ts(now)
}
_, err := d.Exec(`INSERT INTO agent_limits (agent_id, per_minute, out_per_day, paused_at, paused_by) VALUES (?, ?, ?, ?, ?)
ON CONFLICT (agent_id) DO UPDATE SET paused_at = excluded.paused_at, paused_by = excluded.paused_by`,
agent, DefaultPerMinute, DefaultOutPerDay, at, by)
return err
}
// Call is one tool call an agent made.
type Call struct {
ID int64
Agent int64
At time.Time
Tool string
Outcome string // ok, error, refused
Detail string
Took time.Duration
}
// Outcomes.
const (
CallOK = "ok"
CallError = "error"
CallRefused = "refused"
)
// RecordCall notes a tool call.
func RecordCall(d *db.DB, c Call) error {
if r := []rune(c.Detail); len(r) > 300 {
c.Detail = string(r[:299]) + "…"
}
_, err := d.Exec(`INSERT INTO agent_calls (agent_id, at, tool, outcome, detail, ms) VALUES (?, ?, ?, ?, ?, ?)`,
c.Agent, ts(c.At), c.Tool, c.Outcome, c.Detail, c.Took.Milliseconds())
return err
}
// CallsSince counts an agent's calls since a time, not counting those
// refused over the rate.
func CallsSince(d *db.DB, agent int64, since time.Time) (int, error) {
var n int
err := d.QueryRow(`SELECT count(*) FROM agent_calls WHERE agent_id = ? AND at >= ? AND outcome <> ?`, agent, ts(since), CallRefused).Scan(&n)
return n, err
}
// RecentCalls are an agent's last calls, newest first.
func RecentCalls(d *db.DB, agent int64, limit int) ([]Call, error) {
rows, err := d.Query(`SELECT id, agent_id, at, tool, outcome, detail, ms FROM agent_calls WHERE agent_id = ? ORDER BY id DESC LIMIT ?`, agent, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Call
for rows.Next() {
var c Call
var at string
var ms int64
if err := rows.Scan(&c.ID, &c.Agent, &at, &c.Tool, &c.Outcome, &c.Detail, &ms); err != nil {
return nil, err
}
c.At, c.Took = parseTS(at), time.Duration(ms)*time.Millisecond
out = append(out, c)
}
return out, rows.Err()
}
// PruneCalls forgets calls older than 30 days.
func PruneCalls(d *db.DB, now time.Time) error {
_, err := d.Exec(`DELETE FROM agent_calls WHERE at < ?`, ts(now.Add(-30*24*time.Hour)))
return err
}
+228
View File
@@ -0,0 +1,228 @@
package users
import (
"crypto/rand"
"database/sql"
"errors"
"math/big"
"strings"
"time"
"supermarket/internal/db"
"supermarket/internal/slug"
)
// Agents are users of kind Agent: no password, no sign-in page, but keys
// that reach /mcp. Each has modules like a member ("read" is View, "read
// and act" is Edit), and maybe the CRM scope.
// CRMScope is the scope of the tools that work the CRM queue through the
// Core (Hermes' bridge). It's kept with the modules.
const CRMScope = "crm"
// KeyPrefix starts every agent key.
const KeyPrefix = "sm_"
// RotationGrace is how long a key replaced by a new one keeps working.
const RotationGrace = 24 * time.Hour
// Key is one of an agent's keys (never the key itself).
type Key struct {
ID int64
User int64
Prefix string // sm_ and its first characters
Created time.Time
Expires time.Time // zero: never
Retires time.Time // zero, or when a rotation ends it
Revoked time.Time
Used time.Time
UsedFrom string
}
// Working says whether the key opens /mcp now.
func (k *Key) Working(now time.Time) bool {
return k.Revoked.IsZero() && (k.Expires.IsZero() || now.Before(k.Expires)) && (k.Retires.IsZero() || now.Before(k.Retires))
}
// ErrBadKey is a key that's unknown, revoked, expired, retired, or whose
// agent is turned off.
var ErrBadKey = errors.New("this key doesn't work")
// CreateAgent adds an agent: a user of kind Agent, active, with a made-up
// address no mail goes to.
func CreateAgent(d *db.DB, name, description string, now time.Time) (*User, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, errors.New("give the agent a name")
}
tag := make([]byte, 4)
_, _ = rand.Read(tag)
base := slug.Make(name)
if base == "" {
base = "agent"
}
u := &User{Email: base + "-" + strings.ToLower(b32.EncodeToString(tag)[:6]) + "@agents.invalid", Name: name, Description: description, Kind: Agent, Status: Active}
return u, Create(d, u, now)
}
// SaveAgent changes an agent's name and description.
func SaveAgent(d *db.DB, id int64, name, description string) error {
name = strings.TrimSpace(name)
if name == "" {
return errors.New("give the agent a name")
}
_, err := d.Exec(`UPDATE users SET name = ?, description = ? WHERE id = ? AND kind = 'agent'`, name, strings.TrimSpace(description), id)
return err
}
const keyAlphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"
// newKey is sm_ and 40 random characters (about 230 bits).
func newKey() (string, error) {
var b strings.Builder
b.WriteString(KeyPrefix)
max := big.NewInt(int64(len(keyAlphabet)))
for i := 0; i < 40; i++ {
n, err := rand.Int(rand.Reader, max)
if err != nil {
return "", err
}
b.WriteByte(keyAlphabet[n.Int64()])
}
return b.String(), nil
}
// NewKey makes a key for an agent, valid until expires (zero: never), and
// returns it: the only time it's seen.
func NewKey(d *db.DB, user int64, expires, now time.Time) (string, *Key, error) {
key, err := newKey()
if err != nil {
return "", nil, err
}
k, err := AddKey(d, user, key, expires, now)
return key, k, err
}
// AddKey keeps a key made elsewhere (the local edition's mcp-token).
func AddKey(d *db.DB, user int64, key string, expires, now time.Time) (*Key, error) {
prefix := key
if len(prefix) > 10 {
prefix = prefix[:10]
}
k := &Key{User: user, Prefix: prefix, Created: now, Expires: expires}
var err error
k.ID, err = d.Insert(`INSERT INTO agent_keys (user_id, hash, prefix, created_at, expires_at) VALUES (?, ?, ?, ?, ?)`,
user, hashToken(key), prefix, ts(now), tsOrEmpty(expires))
return k, err
}
func tsOrEmpty(t time.Time) string {
if t.IsZero() {
return ""
}
return ts(t)
}
// Rotate makes a new key for an agent; the working ones it had keep
// working for RotationGrace, then stop. The new key keeps the old one's
// expiry date (none, if any had none).
func Rotate(d *db.DB, user int64, now time.Time) (string, *Key, error) {
keys, err := Keys(d, user)
if err != nil {
return "", nil, err
}
var expires time.Time
for _, k := range keys {
if k.Working(now) && !k.Expires.IsZero() && k.Expires.After(expires) {
expires = k.Expires
}
}
for _, k := range keys {
if k.Working(now) && k.Expires.IsZero() {
expires = time.Time{}
break
}
}
if _, err := d.Exec(`UPDATE agent_keys SET retires_at = ? WHERE user_id = ? AND revoked_at = '' AND (retires_at = '' OR retires_at > ?)`,
ts(now.Add(RotationGrace)), user, ts(now.Add(RotationGrace))); err != nil {
return "", nil, err
}
return NewKey(d, user, expires, now)
}
// Revoke stops one of an agent's keys at once.
func Revoke(d *db.DB, user, key int64, now time.Time) error {
_, err := d.Exec(`UPDATE agent_keys SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at = ''`, ts(now), key, user)
return err
}
// RevokeAll stops all of an agent's keys at once.
func RevokeAll(d *db.DB, user int64, now time.Time) error {
_, err := d.Exec(`UPDATE agent_keys SET revoked_at = ? WHERE user_id = ? AND revoked_at = ''`, ts(now), user)
return err
}
const keyCols = `id, user_id, prefix, created_at, expires_at, retires_at, revoked_at, used_at, used_from`
func scanKey(row interface{ Scan(...any) error }) (*Key, error) {
var k Key
var created, expires, retires, revoked, used string
if err := row.Scan(&k.ID, &k.User, &k.Prefix, &created, &expires, &retires, &revoked, &used, &k.UsedFrom); err != nil {
return nil, err
}
k.Created, k.Expires, k.Retires, k.Revoked, k.Used = parseTS(created), parseTS(expires), parseTS(retires), parseTS(revoked), parseTS(used)
return &k, nil
}
// Keys are an agent's keys, newest first.
func Keys(d *db.DB, user int64) ([]*Key, error) {
rows, err := d.Query(`SELECT `+keyCols+` FROM agent_keys WHERE user_id = ? ORDER BY id DESC`, user)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Key
for rows.Next() {
k, err := scanKey(rows)
if err != nil {
return nil, err
}
out = append(out, k)
}
return out, rows.Err()
}
// usedEvery is how often a key's use is written down.
const usedEvery = time.Minute
// Authenticate finds the agent a key belongs to, if the key works, and
// notes its use.
func Authenticate(d *db.DB, key, from string, now time.Time) (*User, *Key, error) {
if !strings.HasPrefix(key, KeyPrefix) && len(key) < 32 {
return nil, nil, ErrBadKey
}
k, err := scanKey(d.QueryRow(`SELECT `+keyCols+` FROM agent_keys WHERE hash = ?`, hashToken(key)))
if errors.Is(err, sql.ErrNoRows) {
return nil, nil, ErrBadKey
}
if err != nil {
return nil, nil, err
}
if !k.Working(now) {
return nil, nil, ErrBadKey
}
u, err := ByID(d, k.User)
if errors.Is(err, ErrNotFound) || (err == nil && (u.Kind != Agent || u.Status != Active)) {
return nil, nil, ErrBadKey
}
if err != nil {
return nil, nil, err
}
if now.Sub(k.Used) >= usedEvery || k.UsedFrom != from {
k.Used, k.UsedFrom = now, from
if _, err := d.Exec(`UPDATE agent_keys SET used_at = ?, used_from = ? WHERE id = ?`, ts(now), from, k.ID); err != nil {
return nil, nil, err
}
}
return u, k, nil
}
+144
View File
@@ -0,0 +1,144 @@
package users
import (
"errors"
"strings"
"testing"
"time"
)
func TestAgentKeys(t *testing.T) {
d := openDB(t)
now := time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)
a, err := CreateAgent(d, "Morning writer", "Drafts posts from What to write next.", now)
if err != nil {
t.Fatal(err)
}
if a.Kind != Agent || a.Status != Active || !strings.HasSuffix(a.Email, "@agents.invalid") || !strings.HasPrefix(a.Email, "morning-writer-") {
t.Errorf("agent %+v", a)
}
if _, err := CreateAgent(d, " ", "", now); err == nil {
t.Error("no name accepted")
}
// Agents never sign in with a password.
if CheckPassword(a, "") {
t.Error("password")
}
key, k, err := NewKey(d, a.ID, now.Add(30*24*time.Hour), now)
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(key, "sm_") || len(key) != 43 || k.Prefix != key[:10] {
t.Errorf("key %q, prefix %q", key, k.Prefix)
}
u, got, err := Authenticate(d, key, "203.0.113.7", now)
if err != nil || u.ID != a.ID || got.ID != k.ID {
t.Fatalf("auth: %v", err)
}
keys, _ := Keys(d, a.ID)
if keys[0].UsedFrom != "203.0.113.7" || !keys[0].Used.Equal(now) {
t.Errorf("use not noted: %+v", keys[0])
}
for _, bad := range []string{"", "sm_nope", key + "x", strings.ToUpper(key)} {
if _, _, err := Authenticate(d, bad, "", now); !errors.Is(err, ErrBadKey) {
t.Errorf("%q: %v", bad, err)
}
}
// Expiry.
if _, _, err := Authenticate(d, key, "", now.Add(31*24*time.Hour)); !errors.Is(err, ErrBadKey) {
t.Error("expired key works")
}
// Rotation: the old key works for a day; the new one keeps the expiry.
key2, k2, err := Rotate(d, a.ID, now)
if err != nil {
t.Fatal(err)
}
if !k2.Expires.Equal(now.Add(30 * 24 * time.Hour)) {
t.Errorf("new key's expiry %v", k2.Expires)
}
if _, _, err := Authenticate(d, key, "", now.Add(23*time.Hour)); err != nil {
t.Error("old key stopped within the day")
}
if _, _, err := Authenticate(d, key, "", now.Add(RotationGrace)); !errors.Is(err, ErrBadKey) {
t.Error("old key works after a day")
}
if _, _, err := Authenticate(d, key2, "", now.Add(RotationGrace)); err != nil {
t.Error("new key doesn't work")
}
// Revoking stops it at once; turning the agent off stops every key.
Revoke(d, a.ID, k2.ID, now)
if _, _, err := Authenticate(d, key2, "", now); !errors.Is(err, ErrBadKey) {
t.Error("revoked key works")
}
key3, _, _ := NewKey(d, a.ID, time.Time{}, now)
SetStatus(d, a.ID, Disabled)
if _, _, err := Authenticate(d, key3, "", now); !errors.Is(err, ErrBadKey) {
t.Error("a turned-off agent's key works")
}
SetStatus(d, a.ID, Active)
RevokeAll(d, a.ID, now)
if _, _, err := Authenticate(d, key3, "", now); !errors.Is(err, ErrBadKey) {
t.Error("revoke all")
}
// A person's "key" never authenticates, even if one were stored.
p := &User{Email: "pat@example.com", Status: Active}
Create(d, p, now)
AddKey(d, p.ID, "sm_person_key_0123456789012345678901234", time.Time{}, now)
if _, _, err := Authenticate(d, "sm_person_key_0123456789012345678901234", "", now); !errors.Is(err, ErrBadKey) {
t.Error("a person's key works")
}
// A legacy token (64 hex digits) is a key too.
legacy := strings.Repeat("ab", 32)
AddKey(d, a.ID, legacy, time.Time{}, now)
if _, _, err := Authenticate(d, legacy, "", now); err != nil {
t.Errorf("legacy token: %v", err)
}
if err := Delete(d, a.ID); err != nil {
t.Fatal(err)
}
if ks, _ := Keys(d, a.ID); len(ks) != 0 {
t.Error("keys outlived the agent")
}
}
func TestAgentLimitsAndCalls(t *testing.T) {
d := openDB(t)
now := time.Now()
a, _ := CreateAgent(d, "Bot", "", now)
l, _ := LimitsOf(d, a.ID)
if l.PerMinute != DefaultPerMinute || l.OutPerDay != DefaultOutPerDay || !l.Paused.IsZero() {
t.Errorf("defaults %+v", l)
}
if err := SetLimits(d, a.ID, 0, 5); err == nil {
t.Error("zero accepted")
}
SetLimits(d, a.ID, 10, 5)
Pause(d, a.ID, true, 7, now)
l, _ = LimitsOf(d, a.ID)
if l.PerMinute != 10 || l.OutPerDay != 5 || l.Paused.IsZero() || l.PausedBy != 7 {
t.Errorf("set %+v", l)
}
Pause(d, a.ID, false, 7, now)
if l, _ = LimitsOf(d, a.ID); !l.Paused.IsZero() || l.PerMinute != 10 {
t.Errorf("resumed %+v", l)
}
RecordCall(d, Call{Agent: a.ID, At: now.Add(-2 * time.Minute), Tool: "x", Outcome: CallOK})
RecordCall(d, Call{Agent: a.ID, At: now, Tool: "y", Outcome: CallError, Detail: strings.Repeat("e", 400), Took: 1500 * time.Millisecond})
RecordCall(d, Call{Agent: a.ID, At: now, Tool: "z", Outcome: CallRefused})
if n, _ := CallsSince(d, a.ID, now.Add(-time.Minute)); n != 1 {
t.Errorf("calls in a minute: %d", n)
}
calls, _ := RecentCalls(d, a.ID, 10)
if len(calls) != 3 || calls[1].Tool != "y" || calls[1].Took != 1500*time.Millisecond || len([]rune(calls[1].Detail)) != 300 {
t.Errorf("recent %+v", calls)
}
PruneCalls(d, now.Add(31*24*time.Hour))
if calls, _ = RecentCalls(d, a.ID, 10); len(calls) != 0 {
t.Error("not pruned")
}
}
+102
View File
@@ -0,0 +1,102 @@
package users
import (
"database/sql"
"errors"
"time"
"supermarket/internal/db"
)
// Purpose is what a one-time link is for.
type Purpose string
const (
SetupLink Purpose = "setup" // creates the first owner
ResetLink Purpose = "reset" // chooses a new password
InviteLink Purpose = "invite" // joins the team
CodeLink Purpose = "code" // a sign-in waiting for its two-factor code
)
// How long each kind of link lasts.
var linkTTL = map[Purpose]time.Duration{
SetupLink: 24 * time.Hour,
ResetLink: time.Hour,
InviteLink: 7 * 24 * time.Hour,
CodeLink: 5 * time.Minute,
}
// ErrBadLink is a link that's unknown, used, replaced or out of date.
var ErrBadLink = errors.New("this link has expired or was already used")
// NewLink makes a one-time link's token. It replaces the user's earlier
// link for the same purpose (the setup link has no user: one at a time).
// Only the token's hash is kept.
func NewLink(d *db.DB, p Purpose, user int64, now time.Time) (string, error) {
ttl, ok := linkTTL[p]
if !ok {
return "", errors.New("no such link")
}
token, err := NewToken()
if err != nil {
return "", err
}
tx, err := d.Begin()
if err != nil {
return "", err
}
defer tx.Rollback()
if _, err := tx.Exec(`DELETE FROM links WHERE purpose = ? AND user_id = ?`, string(p), user); err != nil {
return "", err
}
if _, err := tx.Exec(`INSERT INTO links (id, purpose, user_id, created_at, expires_at) VALUES (?, ?, ?, ?, ?)`,
hashToken(token), string(p), user, ts(now), ts(now.Add(ttl))); err != nil {
return "", err
}
return token, tx.Commit()
}
// PeekLink says whose a link is, without using it: to show its page.
func PeekLink(d *db.DB, token string, p Purpose, now time.Time) (int64, error) {
var user int64
err := d.QueryRow(`SELECT user_id FROM links WHERE id = ? AND purpose = ? AND expires_at > ?`, hashToken(token), string(p), ts(now)).Scan(&user)
if errors.Is(err, sql.ErrNoRows) {
return 0, ErrBadLink
}
return user, err
}
// UseLink uses a link up, once: of two people using it together, one
// gets ErrBadLink.
func UseLink(d *db.DB, token string, p Purpose, now time.Time) (int64, error) {
var user int64
err := d.QueryRow(`DELETE FROM links WHERE id = ? AND purpose = ? AND expires_at > ? RETURNING user_id`, hashToken(token), string(p), ts(now)).Scan(&user)
if errors.Is(err, sql.ErrNoRows) {
return 0, ErrBadLink
}
return user, err
}
// DropLinks withdraws a user's links for a purpose (a withdrawn
// invitation; a reset no longer needed).
func DropLinks(d *db.DB, p Purpose, user int64) error {
_, err := d.Exec(`DELETE FROM links WHERE purpose = ? AND user_id = ?`, string(p), user)
return err
}
// LinkExpiry is when a user's link for a purpose runs out; zero if they
// have none that works.
func LinkExpiry(d *db.DB, p Purpose, user int64, now time.Time) (time.Time, error) {
var exp string
err := d.QueryRow(`SELECT expires_at FROM links WHERE purpose = ? AND user_id = ? AND expires_at > ?`, string(p), user, ts(now)).Scan(&exp)
if errors.Is(err, sql.ErrNoRows) {
return time.Time{}, nil
}
return parseTS(exp), err
}
// PruneLinks deletes links that have run out.
func PruneLinks(d *db.DB, now time.Time) error {
_, err := d.Exec(`DELETE FROM links WHERE expires_at <= ?`, ts(now))
return err
}
+194
View File
@@ -0,0 +1,194 @@
package users
import (
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"errors"
"time"
"supermarket/internal/db"
)
// Session lengths: a session ends after a week unused, and after 30 days
// whatever happens.
const (
SessionIdle = 7 * 24 * time.Hour
SessionMax = 30 * 24 * time.Hour
// seenEvery is how often a session's last use is written down: not on
// every request.
seenEvery = time.Minute
)
// Session is a signed-in browser. Its ID is the hash of the cookie's
// value: a copy of the database doesn't let anyone in.
type Session struct {
ID string
User int64
Created time.Time
Seen time.Time
Expires time.Time
IP string
UserAgent string
Team int64 // the team it works in (multi-tenant: switchable)
// A platform admin viewing a team: until when, and why.
ViewUntil time.Time
ViewReason string
Via string // password or core
}
// ErrNoSession is a cookie that leads nowhere: unknown, ended or expired,
// or its user can't sign in any more.
var ErrNoSession = errors.New("not signed in")
func hashToken(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// NewToken is 32 random bytes, for a cookie or a link.
func NewToken() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// StartSession signs a user in: it returns the token for the cookie.
func StartSession(d *db.DB, user int64, ip, userAgent string, now time.Time) (string, *Session, error) {
return StartSessionIn(d, user, Team, ip, userAgent, now)
}
// StartSessionIn signs a user in to work in a team.
func StartSessionIn(d *db.DB, user, team int64, ip, userAgent string, now time.Time) (string, *Session, error) {
token, err := NewToken()
if err != nil {
return "", nil, err
}
if len(userAgent) > 300 {
userAgent = userAgent[:300]
}
s := &Session{ID: hashToken(token), User: user, Created: now, Seen: now, Expires: expiry(now, now), IP: ip, UserAgent: userAgent, Team: team}
_, err = d.Exec(`INSERT INTO sessions (id, user_id, created_at, seen_at, expires_at, ip, user_agent, team_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
s.ID, s.User, ts(s.Created), ts(s.Seen), ts(s.Expires), s.IP, s.UserAgent, s.Team)
if err != nil {
return "", nil, err
}
return token, s, nil
}
// expiry is when a session created at created, last used at seen, ends.
func expiry(created, seen time.Time) time.Time {
idle, max := seen.Add(SessionIdle), created.Add(SessionMax)
if idle.Before(max) {
return idle
}
return max
}
const sessionCols = `id, user_id, created_at, seen_at, expires_at, ip, user_agent, team_id, view_until, view_reason, via`
func scanSession(row interface{ Scan(...any) error }) (*Session, error) {
var s Session
var created, seen, expires, until string
if err := row.Scan(&s.ID, &s.User, &created, &seen, &expires, &s.IP, &s.UserAgent, &s.Team, &until, &s.ViewReason, &s.Via); err != nil {
return nil, err
}
s.Created, s.Seen, s.Expires, s.ViewUntil = parseTS(created), parseTS(seen), parseTS(expires), parseTS(until)
return &s, nil
}
// Lookup finds the session and user a cookie's token belongs to, and
// notes that it was used. Only active users have sessions that work.
func Lookup(d *db.DB, token string, now time.Time) (*Session, *User, error) {
if token == "" {
return nil, nil, ErrNoSession
}
s, err := scanSession(d.QueryRow(`SELECT `+sessionCols+` FROM sessions WHERE id = ?`, hashToken(token)))
if errors.Is(err, sql.ErrNoRows) {
return nil, nil, ErrNoSession
}
if err != nil {
return nil, nil, err
}
if !now.Before(s.Expires) {
_, _ = d.Exec(`DELETE FROM sessions WHERE id = ?`, s.ID)
return nil, nil, ErrNoSession
}
u, err := ByID(d, s.User)
if errors.Is(err, ErrNotFound) {
return nil, nil, ErrNoSession
}
if err != nil {
return nil, nil, err
}
if u.Status != Active {
return nil, nil, ErrNoSession
}
if now.Sub(s.Seen) >= seenEvery {
s.Seen, s.Expires = now, expiry(s.Created, now)
if _, err := d.Exec(`UPDATE sessions SET seen_at = ?, expires_at = ? WHERE id = ?`, ts(s.Seen), ts(s.Expires), s.ID); err != nil {
return nil, nil, err
}
}
return s, u, nil
}
// EndSession signs a cookie's session out.
func EndSession(d *db.DB, token string) error {
_, err := d.Exec(`DELETE FROM sessions WHERE id = ?`, hashToken(token))
return err
}
// EndSessionByID signs one of a user's sessions out, by its ID (from
// Sessions): only theirs.
func EndSessionByID(d *db.DB, user int64, id string) error {
_, err := d.Exec(`DELETE FROM sessions WHERE id = ? AND user_id = ?`, id, user)
return err
}
// EndOtherSessions signs a user out everywhere but the session keep (""
// for everywhere). It returns how many ended.
func EndOtherSessions(d *db.DB, user int64, keep string) (int64, error) {
res, err := d.Exec(`DELETE FROM sessions WHERE user_id = ? AND id <> ?`, user, keep)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Sessions are a user's sessions, the most recently used first.
func Sessions(d *db.DB, user int64, now time.Time) ([]*Session, error) {
rows, err := d.Query(`SELECT `+sessionCols+` FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY seen_at DESC`, user, ts(now))
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Session
for rows.Next() {
s, err := scanSession(rows)
if err != nil {
return nil, err
}
out = append(out, s)
}
return out, rows.Err()
}
// PruneSessions deletes the sessions that have ended.
func PruneSessions(d *db.DB, now time.Time) (int64, error) {
res, err := d.Exec(`DELETE FROM sessions WHERE expires_at <= ?`, ts(now))
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// SetVia records how a session signed in.
func SetVia(d *db.DB, id, via string) error {
_, err := d.Exec(`UPDATE sessions SET via = ? WHERE id = ?`, via, id)
return err
}
+87
View File
@@ -0,0 +1,87 @@
package users
import (
"time"
"supermarket/internal/db"
)
// Limits on signing in.
const (
// LockAfter failed sign-ins in a row lock an account, until its owner
// resets the password or an admin unlocks it.
LockAfter = 10
// ThrottleWindow is how long failures are counted for the limits below.
ThrottleWindow = 15 * time.Minute
// Within the window, an address may fail this often, and an IP this
// often, before sign-ins from them are refused for the rest of it.
MaxFailsPerEmail = 5
MaxFailsPerIP = 20
)
// FailedSignIn counts a wrong password or code against the user, and locks
// the account at LockAfter. It says whether this failure locked it.
func FailedSignIn(d *db.DB, u *User, now time.Time) (lockedNow bool, err error) {
if _, err := d.Exec(`UPDATE users SET failed_signins = failed_signins + 1 WHERE id = ?`, u.ID); err != nil {
return false, err
}
u.FailedSignIns++
if u.FailedSignIns < LockAfter || u.Locked() {
return false, nil
}
res, err := d.Exec(`UPDATE users SET locked_at = ? WHERE id = ? AND locked_at = ''`, ts(now), u.ID)
if err != nil {
return false, err
}
n, _ := res.RowsAffected()
u.LockedAt = now
return n == 1, nil
}
// Unlock clears the failures and the lock: after a sign-in, a password
// reset, or an admin's unlock.
func Unlock(d *db.DB, id int64) error {
_, err := d.Exec(`UPDATE users SET failed_signins = 0, locked_at = '' WHERE id = ?`, id)
return err
}
// Throttle counts events (failed sign-ins, reset emails) by key within a
// window.
// Fails is how many events key has had in the window so far.
func Fails(d *db.DB, key string, window time.Duration, now time.Time) (int, error) {
var n int
var since string
err := d.QueryRow(`SELECT count, since FROM throttle WHERE key = ?`, key).Scan(&n, &since)
if err != nil {
return 0, nil // none yet (or unreadable: the other checks still hold)
}
if !parseTS(since).After(now.Add(-window)) {
return 0, nil
}
return n, nil
}
// Fail counts one event for key, starting a new window if the last one
// has passed.
func Fail(d *db.DB, key string, window time.Duration, now time.Time) error {
old := ts(now.Add(-window))
_, err := d.Exec(`INSERT INTO throttle (key, count, since) VALUES (?, 1, ?)
ON CONFLICT (key) DO UPDATE SET
count = CASE WHEN throttle.since <= ? THEN 1 ELSE throttle.count + 1 END,
since = CASE WHEN throttle.since <= ? THEN excluded.since ELSE throttle.since END`,
key, ts(now), old, old)
return err
}
// ClearFails forgets key's events.
func ClearFails(d *db.DB, key string) error {
_, err := d.Exec(`DELETE FROM throttle WHERE key = ?`, key)
return err
}
// PruneThrottle forgets counts whose window passed a day ago.
func PruneThrottle(d *db.DB, now time.Time) error {
_, err := d.Exec(`DELETE FROM throttle WHERE since < ?`, ts(now.Add(-24*time.Hour)))
return err
}
+223
View File
@@ -0,0 +1,223 @@
package users
import (
"database/sql"
"errors"
"strings"
"time"
"supermarket/internal/db"
)
// Teams (the multi-tenant edition): each is a company, working on one
// website domain, with its data in its own schema (db.Teams). On the local
// and server editions there's one, Team, and no row for it.
// Team statuses.
const (
TeamActive = "active"
TeamSuspended = "suspended"
TeamDeleting = "deleting"
)
// TeamInfo is a team.
type TeamInfo struct {
ID int64
Name string
Domain string
Status string
Created time.Time
DeleteAt time.Time
VerifyToken string // what proves the domain: a TXT record's or a file's
Verified time.Time // zero until the domain is proved
VerifiedBy string // dns, file or search-console
}
// Proved says whether the team proved its domain.
func (t *TeamInfo) Proved() bool { return !t.Verified.IsZero() }
const teamCols = `id, name, domain, status, created_at, delete_at, verify_token, verified_at, verified_by`
func scanTeam(row interface{ Scan(...any) error }) (*TeamInfo, error) {
var t TeamInfo
var created, del, verified string
if err := row.Scan(&t.ID, &t.Name, &t.Domain, &t.Status, &created, &del, &t.VerifyToken, &verified, &t.VerifiedBy); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
t.Created, t.DeleteAt, t.Verified = parseTS(created), parseTS(del), parseTS(verified)
return &t, nil
}
// CreateTeam adds a team (its schema is the caller's to make).
func CreateTeam(d *db.DB, name, domain string, now time.Time) (*TeamInfo, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, errors.New("give the company's name")
}
t := &TeamInfo{Name: name, Domain: strings.ToLower(strings.TrimSpace(domain)), Status: TeamActive, Created: now}
var err error
t.ID, err = d.Insert(`INSERT INTO teams (name, domain, status, created_at) VALUES (?, ?, ?, ?)`, t.Name, t.Domain, t.Status, ts(now))
return t, err
}
// GetTeam finds a team.
func GetTeam(d *db.DB, id int64) (*TeamInfo, error) {
return scanTeam(d.QueryRow(`SELECT `+teamCols+` FROM teams WHERE id = ?`, id))
}
// ListTeams is every team, newest first.
func ListTeams(d *db.DB) ([]TeamInfo, error) {
return queryTeams(d, `SELECT `+teamCols+` FROM teams ORDER BY id DESC`)
}
// TeamsOf are the teams a user belongs to, by name.
func TeamsOf(d *db.DB, user int64) ([]TeamInfo, error) {
return queryTeams(d, `SELECT t.id, t.name, t.domain, t.status, t.created_at, t.delete_at, t.verify_token, t.verified_at, t.verified_by FROM teams t
JOIN memberships m ON m.team_id = t.id WHERE m.user_id = ? ORDER BY t.name COLLATE NOCASE, t.id`, user)
}
func queryTeams(d *db.DB, q string, args ...any) ([]TeamInfo, error) {
rows, err := d.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []TeamInfo
for rows.Next() {
t, err := scanTeam(rows)
if err != nil {
return nil, err
}
out = append(out, *t)
}
return out, rows.Err()
}
// SetTeamStatus suspends, restores or marks a team for deletion.
func SetTeamStatus(d *db.DB, id int64, status string, deleteAt time.Time) error {
_, err := d.Exec(`UPDATE teams SET status = ?, delete_at = ? WHERE id = ?`, status, tsOrEmpty(deleteAt), id)
return err
}
// SetSessionTeam switches a session to another of its user's teams.
func SetSessionTeam(d *db.DB, sessionID string, team int64) error {
_, err := d.Exec(`UPDATE sessions SET team_id = ? WHERE id = ?`, team, sessionID)
return err
}
// AgentTeam is the team an agent works for: agents belong to one.
func AgentTeam(d *db.DB, agent int64) (int64, error) {
var t int64
err := d.QueryRow(`SELECT team_id FROM memberships WHERE user_id = ? ORDER BY team_id LIMIT 1`, agent).Scan(&t)
if errors.Is(err, sql.ErrNoRows) {
return 0, ErrNotFound
}
return t, err
}
// ErrDomainTaken is a domain another team has proved.
var ErrDomainTaken = errors.New("another team has proved this domain is theirs")
// VerifyToken is the team's token for proving its domain, made the first
// time it's asked for.
func VerifyToken(d *db.DB, team int64) (string, error) {
t, err := GetTeam(d, team)
if err != nil {
return "", err
}
if t.VerifyToken != "" {
return t.VerifyToken, nil
}
tok, err := NewToken()
if err != nil {
return "", err
}
tok = "supermarket-verify=" + tok[:32]
_, err = d.Exec(`UPDATE teams SET verify_token = ? WHERE id = ? AND verify_token = ''`, tok, team)
if err != nil {
return "", err
}
t, err = GetTeam(d, team)
if err != nil {
return "", err
}
return t.VerifyToken, nil
}
// DomainHolder is the team that proved a domain, or 0.
func DomainHolder(d *db.DB, domain string) (int64, error) {
var id int64
err := d.QueryRow(`SELECT id FROM teams WHERE domain = ? AND verified_at <> ''`, strings.ToLower(domain)).Scan(&id)
if errors.Is(err, sql.ErrNoRows) {
return 0, nil
}
return id, err
}
// Prove records that a team proved its domain; another team's proof of
// the same domain stands in the way.
func Prove(d *db.DB, team int64, method string, now time.Time) error {
t, err := GetTeam(d, team)
if err != nil {
return err
}
if holder, err := DomainHolder(d, t.Domain); err != nil {
return err
} else if holder != 0 && holder != team {
return ErrDomainTaken
}
_, err = d.Exec(`UPDATE teams SET verified_at = ?, verified_by = ? WHERE id = ?`, ts(now), method, team)
if err != nil && strings.Contains(strings.ToLower(err.Error()), "unique") {
return ErrDomainTaken
}
return err
}
// ReleaseDomain forgets a team's proof (the platform's admin, or the team
// leaving it).
func ReleaseDomain(d *db.DB, team int64) error {
_, err := d.Exec(`UPDATE teams SET verified_at = '', verified_by = '' WHERE id = ?`, team)
return err
}
// ViewAs points a platform admin's session at a team for a while, with
// the reason; team 0, and no time, ends it.
func ViewAs(d *db.DB, sessionID string, team int64, until time.Time, reason string) error {
_, err := d.Exec(`UPDATE sessions SET team_id = ?, view_until = ?, view_reason = ? WHERE id = ?`, team, tsOrEmpty(until), reason, sessionID)
return err
}
// TeamCounts are a team's members and pending invitations.
func TeamCounts(d *db.DB, team int64) (members, invited int, err error) {
err = d.QueryRow(`SELECT count(*), coalesce(sum(CASE WHEN u.status = 'invited' THEN 1 ELSE 0 END), 0) FROM memberships m JOIN users u ON u.id = m.user_id
WHERE m.team_id = ? AND u.kind = 'person'`, team).Scan(&members, &invited)
return members, invited, err
}
// DeleteTeam forgets a team: its memberships, its sessions, and its row
// (its schema is the caller's to drop). People in no other team keep their
// account.
func DeleteTeam(d *db.DB, id int64) error {
tx, err := d.Begin()
if err != nil {
return err
}
defer tx.Rollback()
// Its agents belong to it alone.
if _, err := tx.Exec(`DELETE FROM agent_keys WHERE user_id IN (SELECT user_id FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.team_id = ? AND u.kind = 'agent')`, id); err != nil {
return err
}
if _, err := tx.Exec(`DELETE FROM users WHERE kind = 'agent' AND id IN (SELECT user_id FROM memberships WHERE team_id = ?)`, id); err != nil {
return err
}
for _, q := range []string{`DELETE FROM sessions WHERE team_id = ?`, `DELETE FROM memberships WHERE team_id = ?`, `DELETE FROM teams WHERE id = ?`} {
if _, err := tx.Exec(q, id); err != nil {
return err
}
}
return tx.Commit()
}
+175
View File
@@ -0,0 +1,175 @@
package users
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"crypto/subtle"
"encoding/base32"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"strings"
"time"
"supermarket/internal/db"
)
// Two-factor sign-in with an authenticator app: TOTP (RFC 6238), six
// digits every 30 seconds, as every app does by default. The secret is
// kept in the secrets store (encrypted on the server editions), under
// TOTPSecretName.
// TOTPSecretName is where a user's authenticator secret is kept; while it's
// being set up, TOTPPendingName.
func TOTPSecretName(user int64) string { return fmt.Sprintf("totp:%d", user) }
func TOTPPendingName(user int64) string { return fmt.Sprintf("totp-pending:%d", user) }
const totpPeriod = 30
var b32 = base32.StdEncoding.WithPadding(base32.NoPadding)
// NewTOTPSecret is a new authenticator secret, in base32 as apps take it.
func NewTOTPSecret() (string, error) {
b := make([]byte, 20)
if _, err := rand.Read(b); err != nil {
return "", err
}
return b32.EncodeToString(b), nil
}
// TOTPURL is the otpauth:// address an app reads from the QR code.
func TOTPURL(issuer, account, secret string) string {
v := url.Values{"secret": {secret}, "issuer": {issuer}, "algorithm": {"SHA1"}, "digits": {"6"}, "period": {"30"}}
return "otpauth://totp/" + url.PathEscape(issuer+":"+account) + "?" + v.Encode()
}
// totpAt is the code for a time step.
func totpAt(key []byte, step int64) string {
var msg [8]byte
binary.BigEndian.PutUint64(msg[:], uint64(step))
mac := hmac.New(sha1.New, key)
mac.Write(msg[:])
sum := mac.Sum(nil)
off := sum[len(sum)-1] & 0x0f
n := binary.BigEndian.Uint32(sum[off:off+4]) & 0x7fffffff
return fmt.Sprintf("%06d", n%1000000)
}
// TOTPCode is the code for a time: for tests.
func TOTPCode(secret string, t time.Time) string {
key, _ := b32.DecodeString(strings.ToUpper(secret))
return totpAt(key, t.Unix()/totpPeriod)
}
// CheckTOTP checks a code against the secret, allowing a step either side
// for clocks that differ. A code works only after the step last used
// (after), so one seen over someone's shoulder can't be used again. It
// returns the code's step.
func CheckTOTP(secret, code string, after int64, now time.Time) (int64, bool) {
code = strings.Join(strings.Fields(code), "")
if len(code) != 6 {
return 0, false
}
key, err := b32.DecodeString(strings.ToUpper(secret))
if err != nil || len(key) == 0 {
return 0, false
}
cur := now.Unix() / totpPeriod
for _, step := range []int64{cur - 1, cur, cur + 1} {
if step > after && subtle.ConstantTimeCompare([]byte(totpAt(key, step)), []byte(code)) == 1 {
return step, true
}
}
return 0, false
}
// UseTOTPStep records the step of a code that was used.
func UseTOTPStep(d *db.DB, u *User, step int64) error {
_, err := d.Exec(`UPDATE users SET totp_step = ? WHERE id = ? AND totp_step < ?`, step, u.ID, step)
if err == nil {
u.totpStep = step
}
return err
}
// TOTPStep is the step of the last code used.
func (u *User) TOTPStep() int64 { return u.totpStep }
// NewRecoveryCodes makes ten single-use codes, like 7kq2-m9xw-4tpd, and
// returns them with the hashes to keep.
func NewRecoveryCodes() (codes, hashes []string, err error) {
const alphabet = "abcdefghjkmnpqrstuvwxyz23456789" // no 0/o, 1/l/i
for i := 0; i < 10; i++ {
b := make([]byte, 12)
if _, err := rand.Read(b); err != nil {
return nil, nil, err
}
var sb strings.Builder
for j, c := range b {
if j > 0 && j%4 == 0 {
sb.WriteByte('-')
}
sb.WriteByte(alphabet[int(c)%len(alphabet)])
}
codes = append(codes, sb.String())
hashes = append(hashes, hashCode(sb.String()))
}
return codes, hashes, nil
}
func hashCode(code string) string {
code = strings.ToLower(strings.NewReplacer("-", "", " ", "").Replace(strings.TrimSpace(code)))
sum := sha256.Sum256([]byte(code))
return hex.EncodeToString(sum[:])
}
// SetTwoFactor turns two-factor sign-in on, with new recovery codes'
// hashes, or off (hashes nil). The secret is the caller's to keep or drop.
func SetTwoFactor(d *db.DB, u *User, on bool, hashes []string) error {
if hashes == nil {
hashes = []string{}
}
js, _ := json.Marshal(hashes)
flag := 0
if on {
flag = 1
}
if _, err := d.Exec(`UPDATE users SET two_factor = ?, recovery_codes = ?, totp_step = 0 WHERE id = ?`, flag, string(js), u.ID); err != nil {
return err
}
u.TwoFactor, u.recoveryCodes, u.RecoveryLeft, u.totpStep = on, hashes, len(hashes), 0
return nil
}
// UseRecoveryCode uses up one of the user's recovery codes, if code is one.
func UseRecoveryCode(d *db.DB, u *User, code string) (bool, error) {
h := hashCode(code)
left := make([]string, 0, len(u.recoveryCodes))
found := false
for _, c := range u.recoveryCodes {
if !found && subtle.ConstantTimeCompare([]byte(c), []byte(h)) == 1 {
found = true
continue
}
left = append(left, c)
}
if !found {
return false, nil
}
js, _ := json.Marshal(left)
old, _ := json.Marshal(u.recoveryCodes)
// Only if no one else used a code meanwhile: each works once.
res, err := d.Exec(`UPDATE users SET recovery_codes = ? WHERE id = ? AND recovery_codes = ?`, string(js), u.ID, string(old))
if err != nil {
return false, err
}
if n, _ := res.RowsAffected(); n != 1 {
return false, nil
}
u.recoveryCodes, u.RecoveryLeft = left, len(left)
return true, nil
}
+481
View File
@@ -0,0 +1,481 @@
// Package users holds the people (and, from Phase 11, agents) who sign in
// to the server and multi-tenant editions: their accounts, their role and
// modules in the team, and their sessions. The local edition has none:
// whoever opens it is the owner.
package users
import (
"crypto/rand"
"crypto/subtle"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/mail"
"strings"
"time"
"golang.org/x/crypto/argon2"
"supermarket/internal/db"
)
// Kind is what signs in: a person, or an agent with a key (Phase 11).
type Kind string
const (
Person Kind = "person"
Agent Kind = "agent"
)
// Status is where an account is.
type Status string
const (
Invited Status = "invited" // asked to join; hasn't chosen a password yet
Active Status = "active" // may sign in
Disabled Status = "disabled" // may not sign in; kept for the record
)
// Role is what someone may do in the team.
type Role string
const (
Owner Role = "owner" // everything, and billing (multi-tenant)
Admin Role = "admin" // everything: users, connections, every module
Member Role = "member" // the modules they're given
)
// Access is how much of a module a member has.
type Access string
const (
View Access = "view" // sees its pages
Edit Access = "edit" // and changes things
)
// Team is the one team until the multi-tenant edition (Phase 13).
const Team int64 = 1
// timeFormat sorts as text: fixed width, UTC.
const timeFormat = "2006-01-02T15:04:05.000Z"
func ts(t time.Time) string { return t.UTC().Format(timeFormat) }
func parseTS(s string) time.Time {
t, _ := time.Parse(timeFormat, s)
return t
}
// User is an account.
type User struct {
ID int64
Email string
Name string
Kind Kind
Status Status
Title string
Description string // an agent's: what it's for
TimeZone string
Photo string
Emails []string // the emails they want (the daily SEO email, …)
Created time.Time
SignedIn time.Time // their last sign-in; zero if never
HasPassword bool
FailedSignIns int // failed in a row since the last sign-in
LockedAt time.Time // zero unless locked after too many failures
TwoFactor bool // signs in with an authenticator app's code too
RecoveryLeft int // unused recovery codes
OIDCSubject string // <issuer>|<subject> at the Core, once they've signed in with it
passwordHash string
totpStep int64
recoveryCodes []string
}
// Locked says whether the account is locked after too many failures.
func (u *User) Locked() bool { return !u.LockedAt.IsZero() }
// Membership is a user's place in a team.
type Membership struct {
Team int64
User int64
Role Role
Modules map[string]Access // a member's; admins and owners have them all
// Cap limits every role, admins too: a module missing from it can't be
// reached, one at View only read (the team's plan). nil: no cap.
Cap map[string]Access
}
// Admin says whether the role runs the whole system.
func (m Membership) Admin() bool { return m.Role == Owner || m.Role == Admin }
// Can says whether the member may see a module (write false) or change
// things in it (write true).
func (m Membership) Can(module string, write bool) bool {
if m.Cap != nil {
c, ok := m.Cap[module]
if !ok || (write && c != Edit) {
return false
}
}
if m.Admin() {
return true
}
a, ok := m.Modules[module]
if !ok {
return false
}
return !write || a == Edit
}
// Errors.
var (
ErrNotFound = errors.New("no such user")
ErrExists = errors.New("someone already has that email address")
)
// NormalEmail checks an email address and returns it trimmed, in lower
// case: addresses are compared without case.
func NormalEmail(s string) (string, error) {
s = strings.TrimSpace(s)
a, err := mail.ParseAddress(s)
if err != nil || a.Address != s || !strings.Contains(s, "@") {
return "", fmt.Errorf("%q isn't an email address", s)
}
return strings.ToLower(s), nil
}
const userCols = `id, email, name, kind, status, password_hash, title, description, time_zone, photo, emails, created_at, signed_in_at, failed_signins, locked_at, two_factor, totp_step, recovery_codes, oidc_subject`
func scanUser(row interface{ Scan(...any) error }) (*User, error) {
var u User
var kind, status, emails, created, signedIn, locked, codes string
var twoFactor int
err := row.Scan(&u.ID, &u.Email, &u.Name, &kind, &status, &u.passwordHash, &u.Title, &u.Description, &u.TimeZone, &u.Photo, &emails, &created, &signedIn,
&u.FailedSignIns, &locked, &twoFactor, &u.totpStep, &codes, &u.OIDCSubject)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
u.Kind, u.Status = Kind(kind), Status(status)
_ = json.Unmarshal([]byte(emails), &u.Emails)
u.Created, u.SignedIn = parseTS(created), parseTS(signedIn)
u.HasPassword = u.passwordHash != ""
u.LockedAt, u.TwoFactor = parseTS(locked), twoFactor != 0
_ = json.Unmarshal([]byte(codes), &u.recoveryCodes)
u.RecoveryLeft = len(u.recoveryCodes)
return &u, nil
}
// Create adds a user. Its email is normalized; ID and Created are set.
func Create(d *db.DB, u *User, now time.Time) error {
email, err := NormalEmail(u.Email)
if err != nil {
return err
}
if _, err := ByEmail(d, email); err == nil {
return ErrExists
} else if !errors.Is(err, ErrNotFound) {
return err
}
u.Email = email
if u.Kind == "" {
u.Kind = Person
}
if u.Status == "" {
u.Status = Invited
}
if u.Emails == nil {
u.Emails = []string{}
}
emails, _ := json.Marshal(u.Emails)
u.Created = now
u.ID, err = d.Insert(`INSERT INTO users (email, name, kind, status, password_hash, title, description, time_zone, photo, emails, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
u.Email, strings.TrimSpace(u.Name), string(u.Kind), string(u.Status), u.passwordHash, u.Title, strings.TrimSpace(u.Description), u.TimeZone, u.Photo, string(emails), ts(now))
return err
}
// ByID finds a user.
func ByID(d *db.DB, id int64) (*User, error) {
return scanUser(d.QueryRow(`SELECT `+userCols+` FROM users WHERE id = ?`, id))
}
// ByEmail finds a user by email address, whatever its case.
func ByEmail(d *db.DB, email string) (*User, error) {
return scanUser(d.QueryRow(`SELECT `+userCols+` FROM users WHERE email = ? COLLATE NOCASE`, strings.TrimSpace(email)))
}
// List is every user, people first, then by name.
func List(d *db.DB) ([]*User, error) {
rows, err := d.Query(`SELECT ` + userCols + ` FROM users ORDER BY kind DESC, name COLLATE NOCASE, email`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*User
for rows.Next() {
u, err := scanUser(rows)
if err != nil {
return nil, err
}
out = append(out, u)
}
return out, rows.Err()
}
// Count is how many users there are.
func Count(d *db.DB) (int, error) {
var n int
err := d.QueryRow(`SELECT count(*) FROM users`).Scan(&n)
return n, err
}
// SaveProfile writes the fields a user fills in about themselves.
func SaveProfile(d *db.DB, u *User) error {
if u.Emails == nil {
u.Emails = []string{}
}
emails, _ := json.Marshal(u.Emails)
_, err := d.Exec(`UPDATE users SET name = ?, title = ?, time_zone = ?, photo = ?, emails = ? WHERE id = ?`,
strings.TrimSpace(u.Name), strings.TrimSpace(u.Title), u.TimeZone, u.Photo, string(emails), u.ID)
return err
}
// SetStatus activates, disables or re-invites a user. A disabled user's
// sessions end.
func SetStatus(d *db.DB, id int64, s Status) error {
if _, err := d.Exec(`UPDATE users SET status = ? WHERE id = ?`, string(s), id); err != nil {
return err
}
if s == Disabled {
_, err := d.Exec(`DELETE FROM sessions WHERE user_id = ?`, id)
return err
}
return nil
}
// SignedIn records a sign-in.
func SignedIn(d *db.DB, id int64, now time.Time) error {
_, err := d.Exec(`UPDATE users SET signed_in_at = ? WHERE id = ?`, ts(now), id)
return err
}
// Delete removes a user, their memberships and their sessions.
func Delete(d *db.DB, id int64) error {
tx, err := d.Begin()
if err != nil {
return err
}
defer tx.Rollback()
// Not left to ON DELETE CASCADE: SQLite enforces it only with
// foreign_keys on, and an imported database may not have had them.
for _, q := range []string{`DELETE FROM sessions WHERE user_id = ?`, `DELETE FROM links WHERE user_id = ?`, `DELETE FROM agent_keys WHERE user_id = ?`, `DELETE FROM memberships WHERE user_id = ?`, `DELETE FROM users WHERE id = ?`} {
if _, err := tx.Exec(q, id); err != nil {
return err
}
}
return tx.Commit()
}
// Passwords.
// MinPassword is the shortest password accepted. Length is what makes a
// password strong; there are no rules about kinds of characters.
const MinPassword = 10
// CheckNewPassword says what's wrong with a password someone chose.
func CheckNewPassword(pw, email string) error {
switch {
case len([]rune(pw)) < MinPassword:
return fmt.Errorf("the password needs at least %d characters", MinPassword)
case len(pw) > 1024:
return errors.New("the password is too long")
case strings.EqualFold(strings.TrimSpace(pw), strings.TrimSpace(email)):
return errors.New("the password can't be your email address")
}
return nil
}
// Argon2id's cost: OWASP's suggestion of 19 MiB, two passes.
const (
argonTime = 2
argonMemory = 19 * 1024
argonThreads = 1
argonKeyLen = 32
)
// HashPassword hashes a password with Argon2id, in the PHC string format
// ($argon2id$v=19$m=…,t=…,p=…$salt$hash).
func HashPassword(pw string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
key := argon2.IDKey([]byte(pw), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
b64 := base64.RawStdEncoding
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
}
// VerifyPassword says whether pw matches a hash from HashPassword. It
// reads the cost from the hash, so older hashes still verify.
func VerifyPassword(hash, pw string) bool {
parts := strings.Split(hash, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false
}
var v int
var m, t uint32
var p uint8
if _, err := fmt.Sscanf(parts[2], "v=%d", &v); err != nil || v != argon2.Version {
return false
}
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &m, &t, &p); err != nil || m == 0 || m > 1<<20 || t == 0 || t > 16 || p == 0 {
return false
}
b64 := base64.RawStdEncoding
salt, err1 := b64.DecodeString(parts[4])
want, err2 := b64.DecodeString(parts[5])
if err1 != nil || err2 != nil || len(want) == 0 {
return false
}
got := argon2.IDKey([]byte(pw), salt, t, m, p, uint32(len(want)))
return subtle.ConstantTimeCompare(got, want) == 1
}
// dummyHash is checked against when there's no user, so a sign-in takes
// as long whether or not the address has an account.
var dummyHash, _ = HashPassword("not anyone's password")
// CheckPassword says whether pw is the user's password. A user without
// one never matches.
func CheckPassword(u *User, pw string) bool {
if u == nil || u.passwordHash == "" {
VerifyPassword(dummyHash, pw)
return false
}
return VerifyPassword(u.passwordHash, pw)
}
// SetPassword changes a user's password ("" removes it).
func SetPassword(d *db.DB, u *User, pw string) error {
hash := ""
if pw != "" {
var err error
if hash, err = HashPassword(pw); err != nil {
return err
}
}
if _, err := d.Exec(`UPDATE users SET password_hash = ? WHERE id = ?`, hash, u.ID); err != nil {
return err
}
u.passwordHash, u.HasPassword = hash, hash != ""
return nil
}
// Memberships.
// Join gives a user a role (and a member their modules) in the team, or
// changes it.
func Join(d *db.DB, team, user int64, role Role, modules map[string]Access, now time.Time) error {
switch role {
case Owner, Admin, Member:
default:
return fmt.Errorf("no role %q", role)
}
if role != Member || modules == nil {
modules = map[string]Access{}
}
for m, a := range modules {
if a != View && a != Edit {
return fmt.Errorf("module %s: no access %q", m, a)
}
}
js, _ := json.Marshal(modules)
_, err := d.Exec(`INSERT INTO memberships (team_id, user_id, role, modules, created_at) VALUES (?, ?, ?, ?, ?)
ON CONFLICT (team_id, user_id) DO UPDATE SET role = excluded.role, modules = excluded.modules`,
team, user, string(role), string(js), ts(now))
return err
}
// MembershipOf is a user's place in the team; ErrNotFound if they have none.
func MembershipOf(d *db.DB, team, user int64) (Membership, error) {
m := Membership{Team: team, User: user}
var role, modules string
err := d.QueryRow(`SELECT role, modules FROM memberships WHERE team_id = ? AND user_id = ?`, team, user).Scan(&role, &modules)
if errors.Is(err, sql.ErrNoRows) {
return m, ErrNotFound
}
if err != nil {
return m, err
}
m.Role = Role(role)
m.Modules = map[string]Access{}
_ = json.Unmarshal([]byte(modules), &m.Modules)
return m, nil
}
// HasOwner says whether the team has its owner yet: until then, the
// server edition is waiting to be set up.
func HasOwner(d *db.DB, team int64) (bool, error) {
var n int
err := d.QueryRow(`SELECT count(*) FROM memberships WHERE team_id = ? AND role = 'owner'`, team).Scan(&n)
return n > 0, err
}
// TeamUser is a user with their place in the team.
type TeamUser struct {
*User
Membership
Joined time.Time // when they joined the team
}
// Members are the team's users, people first, then by name.
func Members(d *db.DB, team int64) ([]TeamUser, error) {
cols := strings.ReplaceAll("u."+userCols, ", ", ", u.")
rows, err := d.Query(`SELECT `+cols+`, m.role, m.modules, m.created_at FROM users u JOIN memberships m ON m.user_id = u.id
WHERE m.team_id = ? ORDER BY u.kind DESC, u.name COLLATE NOCASE, u.email`, team)
if err != nil {
return nil, err
}
defer rows.Close()
var out []TeamUser
for rows.Next() {
var role, modules, joined string
u, err := scanUser(rowWith{rows, []any{&role, &modules, &joined}})
if err != nil {
return nil, err
}
m := Membership{Team: team, User: u.ID, Role: Role(role), Modules: map[string]Access{}}
_ = json.Unmarshal([]byte(modules), &m.Modules)
out = append(out, TeamUser{User: u, Membership: m, Joined: parseTS(joined)})
}
return out, rows.Err()
}
// rowWith scans a user's columns followed by some more.
type rowWith struct {
row interface{ Scan(...any) error }
more []any
}
func (r rowWith) Scan(dest ...any) error { return r.row.Scan(append(dest, r.more...)...) }
// ByOIDCSubject finds the user the Core knows by a subject.
func ByOIDCSubject(d *db.DB, subject string) (*User, error) {
if subject == "" {
return nil, ErrNotFound
}
return scanUser(d.QueryRow(`SELECT `+userCols+` FROM users WHERE oidc_subject = ?`, subject))
}
// SetOIDCSubject remembers who a user is at the Core.
func SetOIDCSubject(d *db.DB, id int64, subject string) error {
_, err := d.Exec(`UPDATE users SET oidc_subject = ? WHERE id = ?`, subject, id)
return err
}
+384
View File
@@ -0,0 +1,384 @@
package users
import (
"errors"
"path/filepath"
"strings"
"testing"
"time"
"supermarket/internal/db"
)
func openDB(t *testing.T) *db.DB {
t.Helper()
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
return d
}
func TestPasswords(t *testing.T) {
h, err := HashPassword("correct horse battery")
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(h, "$argon2id$v=19$m=19456,t=2,p=1$") {
t.Errorf("hash %s", h)
}
if !VerifyPassword(h, "correct horse battery") || VerifyPassword(h, "correct horse batterY") {
t.Error("verify")
}
h2, _ := HashPassword("correct horse battery")
if h == h2 {
t.Error("no salt")
}
for _, bad := range []string{"", "x", "$argon2id$v=19$m=0,t=2,p=1$aa$bb", "$argon2i$v=19$m=19456,t=2,p=1$aa$bb", "$argon2id$v=19$m=99999999,t=2,p=1$aa$bb"} {
if VerifyPassword(bad, "x") {
t.Errorf("%q verified", bad)
}
}
if err := CheckNewPassword("short", "a@b.c"); err == nil {
t.Error("short password accepted")
}
if err := CheckNewPassword("Pat@Example.com", "pat@example.com"); err == nil {
t.Error("the email as a password accepted")
}
if err := CheckNewPassword("a long enough one", "pat@example.com"); err != nil {
t.Error(err)
}
}
func TestUsersAndMemberships(t *testing.T) {
d := openDB(t)
now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
if ok, err := HasOwner(d, Team); err != nil || ok {
t.Fatalf("owner on a new database: %v %v", ok, err)
}
u := &User{Email: " Pat@Example.com ", Name: "Pat"}
if err := Create(d, u, now); err != nil {
t.Fatal(err)
}
if u.Email != "pat@example.com" || u.Status != Invited || u.Kind != Person {
t.Errorf("created %+v", u)
}
if err := Create(d, &User{Email: "PAT@example.com"}, now); !errors.Is(err, ErrExists) {
t.Errorf("same address again: %v", err)
}
if err := Create(d, &User{Email: "not an address"}, now); err == nil {
t.Error("bad address accepted")
}
got, err := ByEmail(d, "PAT@EXAMPLE.COM")
if err != nil || got.ID != u.ID || got.HasPassword {
t.Fatalf("by email: %+v %v", got, err)
}
if CheckPassword(got, "") || CheckPassword(nil, "x") {
t.Error("no password matched")
}
if err := SetPassword(d, got, "a long enough one"); err != nil {
t.Fatal(err)
}
got, _ = ByID(d, u.ID)
if !got.HasPassword || !CheckPassword(got, "a long enough one") || CheckPassword(got, "another one!") {
t.Error("password")
}
if err := Join(d, Team, u.ID, Owner, nil, now); err != nil {
t.Fatal(err)
}
if ok, _ := HasOwner(d, Team); !ok {
t.Error("no owner")
}
m, err := MembershipOf(d, Team, u.ID)
if err != nil || !m.Admin() || !m.Can("metrics", true) {
t.Errorf("owner: %+v %v", m, err)
}
jo := &User{Email: "jo@example.com", Name: "Jo"}
if err := Create(d, jo, now); err != nil {
t.Fatal(err)
}
if _, err := MembershipOf(d, Team, jo.ID); !errors.Is(err, ErrNotFound) {
t.Errorf("no membership yet: %v", err)
}
if err := Join(d, Team, jo.ID, Member, map[string]Access{"seo": Edit, "metrics": View}, now); err != nil {
t.Fatal(err)
}
if err := Join(d, Team, jo.ID, Member, map[string]Access{"seo": "all"}, now); err == nil {
t.Error("bad access accepted")
}
m, _ = MembershipOf(d, Team, jo.ID)
for _, c := range []struct {
module string
write bool
want bool
}{{"seo", false, true}, {"seo", true, true}, {"metrics", false, true}, {"metrics", true, false}, {"content", false, false}} {
if got := m.Can(c.module, c.write); got != c.want {
t.Errorf("member Can(%s, %v) = %v", c.module, c.write, got)
}
}
// Changing the role.
if err := Join(d, Team, jo.ID, Admin, map[string]Access{"seo": View}, now); err != nil {
t.Fatal(err)
}
if m, _ = MembershipOf(d, Team, jo.ID); m.Role != Admin || len(m.Modules) != 0 {
t.Errorf("made admin: %+v", m)
}
jo.Title, jo.TimeZone, jo.Emails = "Writer", "Europe/Paris", []string{"seo-daily"}
if err := SaveProfile(d, jo); err != nil {
t.Fatal(err)
}
list, err := List(d)
if err != nil || len(list) != 2 || list[0].Name != "Jo" || list[0].Title != "Writer" || len(list[0].Emails) != 1 {
t.Errorf("list: %+v %v", list, err)
}
if n, _ := Count(d); n != 2 {
t.Errorf("count %d", n)
}
if err := Delete(d, jo.ID); err != nil {
t.Fatal(err)
}
if _, err := MembershipOf(d, Team, jo.ID); !errors.Is(err, ErrNotFound) {
t.Error("membership outlived its user")
}
}
func TestSessions(t *testing.T) {
d := openDB(t)
now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
u := &User{Email: "pat@example.com", Status: Active}
if err := Create(d, u, now); err != nil {
t.Fatal(err)
}
token, s, err := StartSession(d, u.ID, "203.0.113.5", "Firefox", now)
if err != nil {
t.Fatal(err)
}
if s.ID == token || len(token) < 40 {
t.Errorf("token %q, id %q", token, s.ID)
}
if _, _, err := Lookup(d, "nonsense", now); !errors.Is(err, ErrNoSession) {
t.Errorf("unknown token: %v", err)
}
if _, _, err := Lookup(d, "", now); !errors.Is(err, ErrNoSession) {
t.Errorf("empty token: %v", err)
}
got, who, err := Lookup(d, token, now.Add(time.Hour))
if err != nil || who.ID != u.ID || got.IP != "203.0.113.5" {
t.Fatalf("lookup: %+v %+v %v", got, who, err)
}
if !got.Expires.Equal(now.Add(time.Hour + SessionIdle)) {
t.Errorf("expiry not slid: %v", got.Expires)
}
// Used every few days, it still ends after 30 days.
at := now
for i := 0; i < 9; i++ {
at = at.Add(3 * 24 * time.Hour)
if _, _, err := Lookup(d, token, at); err != nil {
t.Fatalf("day %d: %v", i*3, err)
}
}
if _, _, err := Lookup(d, token, now.Add(SessionMax)); !errors.Is(err, ErrNoSession) {
t.Errorf("after 30 days: %v", err)
}
// Idle for a week.
t2, _, _ := StartSession(d, u.ID, "", "", now)
if _, _, err := Lookup(d, t2, now.Add(SessionIdle)); !errors.Is(err, ErrNoSession) {
t.Errorf("idle a week: %v", err)
}
// A disabled user's sessions end.
t5, _, _ := StartSession(d, u.ID, "", "", now)
if err := SetStatus(d, u.ID, Disabled); err != nil {
t.Fatal(err)
}
SetStatus(d, u.ID, Active)
if _, _, err := Lookup(d, t5, now); !errors.Is(err, ErrNoSession) {
t.Errorf("disabled user: %v", err)
}
t3, s3, _ := StartSession(d, u.ID, "", "", now)
t4, _, _ := StartSession(d, u.ID, "", "", now)
if list, _ := Sessions(d, u.ID, now); len(list) != 2 {
t.Errorf("sessions: %d", len(list))
}
if n, err := EndOtherSessions(d, u.ID, s3.ID); err != nil || n != 1 {
t.Errorf("end others: %d %v", n, err)
}
if _, _, err := Lookup(d, t4, now); !errors.Is(err, ErrNoSession) {
t.Error("another session survived")
}
if err := EndSession(d, t3); err != nil {
t.Fatal(err)
}
if _, _, err := Lookup(d, t3, now); !errors.Is(err, ErrNoSession) {
t.Error("signed out, still in")
}
StartSession(d, u.ID, "", "", now)
if n, _ := PruneSessions(d, now.Add(SessionMax)); n != 1 {
t.Errorf("pruned %d", n)
}
}
func TestLinks(t *testing.T) {
d := openDB(t)
now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
a, err := NewLink(d, ResetLink, 7, now)
if err != nil {
t.Fatal(err)
}
if u, err := PeekLink(d, a, ResetLink, now); err != nil || u != 7 {
t.Errorf("peek: %d %v", u, err)
}
if _, err := PeekLink(d, a, InviteLink, now); !errors.Is(err, ErrBadLink) {
t.Error("used for another purpose")
}
if exp, _ := LinkExpiry(d, ResetLink, 7, now); !exp.Equal(now.Add(time.Hour)) {
t.Errorf("expiry %v", exp)
}
if _, err := UseLink(d, a, ResetLink, now.Add(time.Hour)); !errors.Is(err, ErrBadLink) {
t.Error("used after an hour")
}
b, _ := NewLink(d, ResetLink, 7, now)
c, _ := NewLink(d, ResetLink, 7, now) // replaces b
if _, err := UseLink(d, b, ResetLink, now); !errors.Is(err, ErrBadLink) {
t.Error("replaced link worked")
}
if u, err := UseLink(d, c, ResetLink, now); err != nil || u != 7 {
t.Errorf("use: %d %v", u, err)
}
if _, err := UseLink(d, c, ResetLink, now); !errors.Is(err, ErrBadLink) {
t.Error("used twice")
}
i, _ := NewLink(d, InviteLink, 8, now)
if err := DropLinks(d, InviteLink, 8); err != nil {
t.Fatal(err)
}
if _, err := PeekLink(d, i, InviteLink, now); !errors.Is(err, ErrBadLink) {
t.Error("withdrawn link worked")
}
if _, err := NewLink(d, "other", 1, now); err == nil {
t.Error("unknown purpose")
}
}
func TestLockAndThrottle(t *testing.T) {
d := openDB(t)
now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
u := &User{Email: "pat@example.com", Status: Active}
Create(d, u, now)
for i := 1; i <= LockAfter; i++ {
locked, err := FailedSignIn(d, u, now)
if err != nil {
t.Fatal(err)
}
if locked != (i == LockAfter) {
t.Errorf("failure %d: locked %v", i, locked)
}
}
if locked, _ := FailedSignIn(d, u, now); locked {
t.Error("locked twice")
}
got, _ := ByID(d, u.ID)
if !got.Locked() || got.FailedSignIns != LockAfter+1 {
t.Errorf("after: %+v", got)
}
Unlock(d, u.ID)
if got, _ = ByID(d, u.ID); got.Locked() || got.FailedSignIns != 0 {
t.Error("still locked")
}
key := "signin:ip:203.0.113.5"
for i := 0; i < 3; i++ {
if err := Fail(d, key, ThrottleWindow, now.Add(time.Duration(i)*time.Minute)); err != nil {
t.Fatal(err)
}
}
if n, _ := Fails(d, key, ThrottleWindow, now.Add(5*time.Minute)); n != 3 {
t.Errorf("fails %d", n)
}
if n, _ := Fails(d, key, ThrottleWindow, now.Add(ThrottleWindow)); n != 0 {
t.Errorf("after the window: %d", n)
}
Fail(d, key, ThrottleWindow, now.Add(ThrottleWindow)) // a new window
if n, _ := Fails(d, key, ThrottleWindow, now.Add(ThrottleWindow)); n != 1 {
t.Errorf("new window: %d", n)
}
ClearFails(d, key)
if n, _ := Fails(d, key, ThrottleWindow, now.Add(ThrottleWindow)); n != 0 {
t.Errorf("cleared: %d", n)
}
}
func TestTOTP(t *testing.T) {
// RFC 6238's test secret, at 59 seconds: 94287082, of which apps show
// the last six digits.
secret := "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
at := time.Unix(59, 0)
if got := TOTPCode(secret, at); got != "287082" {
t.Errorf("code %s", got)
}
step, ok := CheckTOTP(secret, "287 082", 0, at)
if !ok || step != 1 {
t.Errorf("check: %d %v", step, ok)
}
if _, ok := CheckTOTP(secret, "287082", 1, at); ok {
t.Error("a used code worked again")
}
if _, ok := CheckTOTP(secret, "287082", 0, at.Add(30*time.Second)); !ok {
t.Error("a step late: refused")
}
if _, ok := CheckTOTP(secret, "287082", 0, at.Add(90*time.Second)); ok {
t.Error("three steps late: accepted")
}
if _, ok := CheckTOTP(secret, "000000", 0, at); ok {
t.Error("wrong code")
}
s, _ := NewTOTPSecret()
if len(s) != 32 {
t.Errorf("secret %s", s)
}
if u := TOTPURL("Supermarket (acme.com)", "pat@example.com", s); !strings.HasPrefix(u, "otpauth://totp/Supermarket%20%28acme.com%29:pat@example.com?") {
t.Errorf("url %s", u)
}
}
func TestRecoveryCodes(t *testing.T) {
d := openDB(t)
u := &User{Email: "pat@example.com", Status: Active}
Create(d, u, time.Now())
codes, hashes, err := NewRecoveryCodes()
if err != nil || len(codes) != 10 || len(codes[0]) != 14 {
t.Fatalf("%v %v", codes, err)
}
if err := SetTwoFactor(d, u, true, hashes); err != nil {
t.Fatal(err)
}
u, _ = ByID(d, u.ID)
if !u.TwoFactor || u.RecoveryLeft != 10 {
t.Errorf("%+v", u)
}
if ok, _ := UseRecoveryCode(d, u, strings.ToUpper(codes[3])); !ok {
t.Error("code refused")
}
if ok, _ := UseRecoveryCode(d, u, codes[3]); ok {
t.Error("used twice")
}
// A stale copy of the user can't use a code another request used.
stale, _ := ByID(d, u.ID)
UseRecoveryCode(d, u, codes[4])
if ok, _ := UseRecoveryCode(d, stale, codes[4]); ok {
t.Error("used twice, from a stale copy")
}
u, _ = ByID(d, u.ID)
if u.RecoveryLeft != 8 {
t.Errorf("left %d", u.RecoveryLeft)
}
SetTwoFactor(d, u, false, nil)
if u, _ = ByID(d, u.ID); u.TwoFactor || u.RecoveryLeft != 0 {
t.Errorf("off: %+v", u)
}
}
+8 -3
View File
@@ -6,6 +6,7 @@ import (
"supermarket/internal/config"
"supermarket/internal/db"
"supermarket/internal/jobs"
)
// config is how this Supermarket is run: the local edition's defaults when
@@ -33,12 +34,16 @@ type aboutData struct {
Version string
Schema int
Items []config.Item
Copies []jobs.Instance // copies of the app running now
Locks []jobs.Held // work they have under way
}
// aboutPage shows the edition and how it's run (Settings → About).
func (s *Server) aboutPage(w http.ResponseWriter, r *http.Request) {
c := s.config()
s.render(w, r, "about", page{Title: "About", Nav: "settings/about", Data: aboutData{
Edition: c.Edition, Version: s.Version, Schema: db.Schema(), Items: c.Summary(),
}})
d := aboutData{Edition: c.Edition, Version: s.Version, Schema: db.Schema(), Items: c.Summary()}
d.Copies, _ = s.jobs().Instances()
d.Locks, _ = s.jobs().Locks()
s.render(w, r, "about", page{Title: "About", Nav: "settings/about", Data: d})
}
+292
View File
@@ -0,0 +1,292 @@
package web
import (
"bytes"
"fmt"
"html"
"net/http"
"regexp"
"strings"
"supermarket/internal/users"
)
// Who may reach what. Every route belongs to an area: a module, Settings
// (admins), anything signed in, or public. One table maps addresses to
// areas, by their first segments; the app won't start with a route that
// isn't in it. A GET reads; anything else changes, which a member needs
// edit on the module for.
const (
areaPublic = "public" // no sign-in: the sign-in pages, static files, MCP (its own key)
areaSignedIn = "signed-in" // anyone signed in: the Overview, Search, Your account
areaAdmin = "admin" // admins and the owner: Settings, users, connections
)
// routeAreas maps addresses to areas. An entry matches its path and
// everything under it (/seo matches /seo/check); one starting with = only
// itself. The longest match wins, and an exact one over a prefix.
var routeAreas = map[string]string{
"/static": areaPublic, "=/favicon.ico": areaPublic, "=/healthz": areaPublic, "=/mcp": areaPublic,
"/signin": areaPublic, "=/signout": areaPublic, "=/forgot": areaPublic, "/reset": areaPublic,
"/setup": areaPublic, "/invite": areaPublic, "/signup": areaPublic,
// Stripe's events: signed with the webhook's secret instead.
"=/billing/stripe": areaPublic,
"/teams": areaSignedIn,
// The JSON API: its own keys, like /mcp.
"/api": areaPublic,
"=/": areaSignedIn, "=/search": areaSignedIn, "/settings/account": areaSignedIn,
"/users": areaSignedIn, "=/settings": areaSignedIn,
// Each request is checked against its module (approvals.go).
"/approvals": areaSignedIn,
// Old addresses that only redirect.
"=/profile": areaSignedIn, "=/core": areaSignedIn,
"/settings": areaAdmin,
"/platform": areaPlatform,
// Signing in to a posting account: admins for the company's, anyone
// with Content for their own (oauthStart checks which).
"/auth": areaSignedIn,
// The Core's sign-in comes back here, before anyone is signed in.
"/auth/core": areaPublic,
"/content": "content", "/posts": "content", "/inbox": "content", "/drafts": "content", "/reddit": "content",
"/prospects": "prospects", "/signals": "prospects", "/lead-sources": "prospects", "/funnel": "prospects",
"/outreach": "prospects", "/crm": "prospects",
"/seo": "seo",
"/sites": "sites", "/preview": "sites",
"/metrics": "metrics",
"/market": "market", "/inventory": "market",
}
// areaOf is the area of a path (or a route's pattern, without its method).
func areaOf(path string) (string, bool) {
path = strings.TrimSuffix(path, "{$}")
if len(path) > 1 {
path = strings.TrimSuffix(path, "/")
}
best, area := -1, ""
for prefix, a := range routeAreas {
exact := strings.HasPrefix(prefix, "=")
p := strings.TrimPrefix(prefix, "=")
ok := path == p || (!exact && strings.HasPrefix(path, p+"/"))
score := 2 * len(p) // an exact entry beats a prefix of the same path
if exact {
score++
}
if ok && score > best {
best, area = score, a
}
}
return area, best >= 0
}
// publicPath says whether a path is reached without signing in.
func publicPath(p string) bool {
a, ok := areaOf(p)
return ok && a == areaPublic
}
// can says whether the viewer may read (write false) or change things in
// an area.
func (v *viewer) can(area string, write bool) bool {
switch area {
case areaPublic:
return true
case areaSignedIn:
return v.User != nil || v == localOwner
case areaAdmin:
return v.Member.Admin()
case areaPlatform:
return v.Platform
}
return v.Member.Can(area, write)
}
// canPost says whether the viewer may send a form to a path.
func (v *viewer) canPost(path string) bool {
if i := strings.IndexAny(path, "?#"); i >= 0 {
path = path[:i]
}
a, ok := areaOf(path)
return ok && v.can(a, true)
}
// routes registers handlers, each behind the check for its area.
type routes struct {
s *Server
mux *http.ServeMux
unmapped []string
patterns []string // every route, for the tests that walk them all
}
// HandleFunc registers a handler: a method expression such as
// (*Server).seoPage, run on the Server for the request's team; or a plain
// handler that needs no team.
func (rt *routes) HandleFunc(pattern string, fn any) {
switch f := fn.(type) {
case func(*Server, http.ResponseWriter, *http.Request):
rt.Handle(pattern, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ts, err := rt.s.teamServer(r)
if err != nil {
rt.s.serverError(w, err)
return
}
f(ts, w, r)
}))
case func(http.ResponseWriter, *http.Request):
rt.Handle(pattern, http.HandlerFunc(f))
case http.HandlerFunc:
rt.Handle(pattern, f)
default:
panic(fmt.Sprintf("route %s: a handler of type %T", pattern, fn))
}
}
func (rt *routes) Handle(pattern string, h http.Handler) {
path := pattern
if i := strings.Index(pattern, " "); i >= 0 {
path = pattern[i+1:]
}
area, ok := areaOf(path)
if !ok {
rt.unmapped = append(rt.unmapped, pattern)
return
}
rt.patterns = append(rt.patterns, pattern)
rt.mux.Handle(pattern, rt.s.allow(area, rt.s.guardDomain(pattern, rt.s.audited(pattern, h))))
}
func (rt *routes) err() error {
if len(rt.unmapped) == 0 {
return nil
}
return fmt.Errorf("routes without an area (add them to routeAreas, in access.go): %s", strings.Join(rt.unmapped, ", "))
}
// allow lets a request through if the viewer may reach its area: reading,
// or for anything but GET, changing.
func (s *Server) allow(area string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := viewerOf(r)
if area != areaPublic && v.User == nil && v != localOwner {
s.toSignIn(w, r)
return
}
write := !safeMethod(r.Method)
// A lapsed team changes nothing, but its billing, people's own
// accounts, and switching teams.
if v.ReadOnly && write && !strings.HasPrefix(r.URL.Path, "/settings/billing") &&
!platformPath(r.URL.Path) && !strings.HasPrefix(r.URL.Path, "/teams/") {
http.Error(w, sentence(errLapsed.Error())+".", http.StatusForbidden)
return
}
if !v.can(area, write) {
if write && v.OverSeats {
msg := "The team has more people than its plan has seats, so you can read, not change. The team's owner chooses who keeps editing, under Settings → Billing."
if ts, err := s.teamServer(r); err == nil {
if _, plan := ts.kept(); plan != nil {
msg = fmt.Sprintf("The %s plan has %d people, and the team has more, so you can read, not change. The team's owner chooses who keeps editing, under Settings → Billing, or moves up a plan.", plan.Name, plan.Seats)
}
}
http.Error(w, msg, http.StatusForbidden)
return
}
// A module the team's plan has only to read: say so.
if write && v.Member.Cap != nil && v.Member.Cap[area] == users.View && v.Member.Can(area, false) {
if ts, err := s.teamServer(r); err == nil {
if plan, _ := ts.teamPlan(); plan != nil {
http.Error(w, fmt.Sprintf("The %s plan doesn't include %s: what's there stays, to read. The team's owner can move up a plan under Settings → Billing.",
plan.Name, grantName(area)), http.StatusForbidden)
return
}
}
}
s.forbidden(w, r)
return
}
next.ServeHTTP(w, r)
})
}
// Pages for members who may only view: every form that sends to a module
// they can't change is shown inside a disabled fieldset, so they see what
// it holds but can't submit it (and its buttons are hidden, app.css), and
// htmx buttons that would change something are hidden. The server
// refuses those requests anyway (allow).
var (
formClose = regexp.MustCompile(`(?i)</form\s*>`)
hxChange = regexp.MustCompile(`(?is)<[a-z]+\b[^>]*\bhx-(?:post|put|patch|delete)\s*=\s*"([^"]*)"[^>]*>`)
)
// rewriteForms adds the CSRF token to the forms the viewer may send, and
// disables the others. here is the page's own path, for forms without an
// action.
func rewriteForms(page []byte, token, here string, v *viewer) []byte {
if token == "" && v == nil {
return page
}
var out bytes.Buffer
out.Grow(len(page) + 1024)
rest := page
for {
loc := formTag.FindIndex(rest)
if loc == nil {
out.Write(rest)
break
}
tag := rest[loc[0]:loc[1]]
out.Write(rest[:loc[0]])
rest = rest[loc[1]:]
method, action, _ := formAttrs(tag)
target := action
if target == "" {
target = here
}
if method != "post" || !ownAddress(action) || v == nil || v.canPost(target) {
out.Write(addCSRF(tag, token))
continue
}
// Shown, not sent: the fieldset holds everything up to </form>.
out.Write(tag)
out.WriteString(`<fieldset class="readonly" disabled>`)
end := formClose.FindIndex(rest)
if end == nil {
out.Write(rest)
out.WriteString(`</fieldset>`)
rest = nil
continue
}
out.Write(rest[:end[0]])
out.WriteString(`</fieldset>`)
out.Write(rest[end[0]:end[1]])
rest = rest[end[1]:]
}
if v == nil {
return out.Bytes()
}
return hxChange.ReplaceAllFunc(out.Bytes(), func(tag []byte) []byte {
m := hxChange.FindSubmatch(tag)
if v.canPost(html.UnescapeString(string(m[1]))) {
return tag
}
return append(tag[:len(tag)-1:len(tag)-1], []byte(` hidden disabled>`)...)
})
}
// formAttrs reads a form tag's method (lower case), action and enctype.
func formAttrs(tag []byte) (method, action, enctype string) {
for _, m := range attrRe.FindAllSubmatch(tag, -1) {
switch strings.ToLower(string(m[1])) {
case "method":
method = strings.ToLower(string(m[2]))
case "action":
action = html.UnescapeString(string(m[2]))
case "enctype":
enctype = strings.ToLower(string(m[2]))
}
}
return
}
+227
View File
@@ -0,0 +1,227 @@
package web
import (
"net/http"
"net/url"
"strings"
"testing"
"supermarket/internal/appmail"
"supermarket/internal/audit"
"supermarket/internal/profile"
"supermarket/internal/users"
)
func TestEveryRouteHasAnArea(t *testing.T) {
// The app's own routes: Handler fails if one has no area.
s, _ := newTestServer(t, nil)
if _, err := s.Handler(); err != nil {
t.Fatal(err)
}
// A new route that isn't in the table is caught.
rt := &routes{s: s, mux: http.NewServeMux()}
rt.HandleFunc("GET /brand-new/{id}", func(http.ResponseWriter, *http.Request) {})
rt.HandleFunc("GET /seo/new-page", func(http.ResponseWriter, *http.Request) {})
if err := rt.err(); err == nil || !strings.Contains(err.Error(), "/brand-new/{id}") || strings.Contains(err.Error(), "/seo/new-page") {
t.Errorf("unmapped: %v", err)
}
for path, want := range map[string]string{
"/": areaSignedIn, "/seo": "seo", "/seo/check": "seo", "/seosomething": "", "/settings/account": areaSignedIn,
"/settings/account/two-factor": areaSignedIn, "/settings": areaSignedIn, "/settings/ai": areaAdmin,
"/market/1": "market", "/preview/0/x/index.html": "sites", "/static/app.css": areaPublic, "/mcp": areaPublic,
"/mcp/x": "", "/signin/code": areaPublic, "/{$}": areaSignedIn,
} {
got, ok := areaOf(path)
if got != want || ok != (want != "") {
t.Errorf("areaOf(%s) = %q %v, want %q", path, got, ok, want)
}
}
}
// pages are GET addresses across every area, for the access tests.
var accessPages = []string{"/", "/search?q=x", "/settings/account",
"/market", "/market/new", "/settings/profile", "/settings/ai", "/settings/accounts", "/settings/core", "/settings/users",
"/settings/email", "/settings/tracking", "/settings/search", "/settings/sources", "/settings/backups", "/settings/about",
"/content", "/posts", "/content/scheduled", "/content/published",
"/prospects", "/prospects/new", "/prospects/suppressed", "/outreach", "/crm", "/signals", "/signals/new",
"/seo", "/seo/check", "/seo/report", "/seo/next", "/seo/links", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines",
"/metrics", "/metrics/customers", "/metrics/spend", "/metrics/clv", "/metrics/publish",
"/sites", "/sites/previews", "/sites/pages", "/sites/publishing", "/sites/forms", "/sites/new"}
func TestAccessEnforced(t *testing.T) {
s, h := newServerEdition(t)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}})
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
oc := sessionFor(t, s, owner)
// The owner invites an admin and a member with only SEO.
adminLink := invite(t, s, h, oc, url.Values{"email": {"ada@example.com"}, "name": {"Ada"}, "role": {"admin"}})
memberLink := invite(t, s, h, oc, url.Values{"email": {"sam@example.com"}, "name": {"Sam"}, "role": {"member"}, "module:seo": {"edit"}})
for _, l := range []string{adminLink, memberLink} {
if rec := postForm(h, l, url.Values{"name": {"X"}, "password": {"a long enough one"}, "password2": {"a long enough one"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("join: %d", rec.Code)
}
}
// The member signs in.
rec := signin(h, "203.0.113.20", url.Values{"email": {"sam@example.com"}, "password": {"a long enough one"}})
sc := cookieOf(rec, sessionCookie)
if sc == nil {
t.Fatalf("member sign-in: %d", rec.Code)
}
ada, _ := users.ByEmail(s.DB, "ada@example.com")
ac := sessionFor(t, s, ada)
// The menu shows only SEO.
home := as(h, sc, http.MethodGet, "/", nil).Body.String()
for _, l := range []string{`href="/posts"`, `href="/signals"`, `href="/metrics"`, `href="/sites"`, `href="/market"`, `href="/settings/profile"`} {
if strings.Contains(home, l) {
t.Errorf("member's page links to %s", l)
}
}
if !strings.Contains(home, `href="/seo/check"`) || !strings.Contains(home, `href="/settings/account"`) {
t.Error("member's page lacks SEO or Your account")
}
for _, p := range accessPages {
area, _ := areaOf(strings.SplitN(p, "?", 2)[0])
want := http.StatusForbidden
if area == "seo" || area == areaSignedIn {
want = http.StatusOK
}
if rec := as(h, sc, http.MethodGet, p, nil); rec.Code != want {
t.Errorf("member GET %s: %d, want %d", p, rec.Code, want)
}
// The admin and the owner reach everything.
for who, c := range map[string]*http.Cookie{"admin": ac, "owner": oc} {
if rec := as(h, c, http.MethodGet, p, nil); rec.Code != http.StatusOK {
t.Errorf("%s GET %s: %d", who, p, rec.Code)
}
}
}
// Changes outside SEO, and htmx fragments, are refused too.
for _, p := range []string{"/settings/profile", "/market/save", "/metrics/sync", "/sites/sync", "/signals/new", "/drafts/1/publish", "/settings/users", "/settings/ai/test"} {
if rec := as(h, sc, http.MethodPost, p, url.Values{"name": {"x"}}); rec.Code != http.StatusForbidden {
t.Errorf("member POST %s: %d", p, rec.Code)
}
}
for _, p := range []string{"/settings/core/checks", "/crm/reach", "/settings/ai/models"} {
rec := do(h, http.MethodGet, p, nil, map[string]string{"HX-Request": "true", "Cookie": sessionCookie + "=" + sc.Value})
if rec.Code != http.StatusForbidden {
t.Errorf("member htmx %s: %d", p, rec.Code)
}
}
// Search shows only their modules.
if body := as(h, sc, http.MethodGet, "/search?q=company+profile", nil).Body.String(); strings.Contains(body, `href="/settings/profile"`) {
t.Error("search shows Settings to a member")
}
// What SEO changes, they can.
if rec := as(h, sc, http.MethodPost, "/seo/next/dismiss", url.Values{"page": {"/x"}}); rec.Code == http.StatusForbidden {
t.Errorf("member POST in SEO: %d", rec.Code)
}
// The log shows each step, to admins only.
entries, _ := audit.List(s.DB, audit.Filter{}, 100)
var steps []string
for i := len(entries) - 1; i >= 0; i-- {
e := entries[i]
steps = append(steps, e.UserName+" "+e.Action+" "+e.Target)
}
got := strings.Join(steps, "\n")
for _, want := range []string{"owner invited ada@example.com", "owner invited sam@example.com", "X joined ada@example.com", "X joined sam@example.com", "X signin"} {
if !strings.Contains(got, want) {
t.Errorf("the log lacks %q:\n%s", want, got)
}
}
if rec := as(h, sc, http.MethodGet, "/settings/activity", nil); rec.Code != http.StatusForbidden {
t.Errorf("member reads the log: %d", rec.Code)
}
if body := as(h, oc, http.MethodGet, "/settings/activity", nil).Body.String(); !strings.Contains(body, "invited <strong>sam@example.com</strong>") {
t.Errorf("activity page: %s", body)
}
}
func TestViewOnlyMember(t *testing.T) {
s, h := newServerEdition(t)
addUser(t, s, "owner@example.com", users.Owner, nil)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}})
jo := addUser(t, s, "jo@example.com", users.Member, map[string]users.Access{"seo": users.View, "market": users.Edit})
c := sessionFor(t, s, jo)
rec := as(h, c, http.MethodGet, "/seo/audit", nil)
if rec.Code != http.StatusOK {
t.Fatalf("view: %d", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, `<fieldset class="readonly" disabled>`) {
t.Error("SEO's forms aren't disabled")
}
if strings.Contains(body, `<input type="hidden" name="csrf" value="`+testCSRF) && strings.Contains(body, `action="/seo/audit?site=0" class="card row wrap" data-busy="Starting…"><input`) {
t.Error("a disabled form carries the token")
}
if rec := as(h, c, http.MethodPost, "/seo/audit?site=0", url.Values{}); rec.Code != http.StatusForbidden {
t.Errorf("view member POST: %d", rec.Code)
}
// The search box (GET) and sign-out still work; the Market, which they
// edit, keeps its forms.
if !strings.Contains(body, `action="/signout"><input type="hidden" name="csrf"`) {
t.Error("sign-out form disabled")
}
rec = as(h, c, http.MethodGet, "/market/new", nil)
if strings.Contains(rec.Body.String(), `class="readonly"`) {
t.Error("the Market's forms are disabled for an editor")
}
}
func TestRewriteForms(t *testing.T) {
v := &viewer{Member: users.Membership{Role: users.Member, Modules: map[string]users.Access{"seo": users.View, "market": users.Edit}}, User: &users.User{ID: 2}}
in := `<form method="post" action="/seo/keywords"><textarea>keep me</textarea><button>Find</button></form>` +
`<form method="post" action="/market/save"><button>Save</button></form>` +
`<form method="get" action="/seo"><input name="q"></form>` +
`<form method="post"><button>Here</button></form>` +
`<button hx-post="/seo/changes/suggest">Suggest</button><button hx-get="/seo/audit/status">Status</button>`
out := string(rewriteForms([]byte(in), "T", "/seo/check", v))
want := `<form method="post" action="/seo/keywords"><fieldset class="readonly" disabled><textarea>keep me</textarea><button>Find</button></fieldset></form>` +
`<form method="post" action="/market/save"><input type="hidden" name="csrf" value="T"><button>Save</button></form>` +
`<form method="get" action="/seo"><input name="q"></form>` +
`<form method="post"><fieldset class="readonly" disabled><button>Here</button></fieldset></form>` +
`<button hx-post="/seo/changes/suggest" hidden disabled>Suggest</button><button hx-get="/seo/audit/status">Status</button>`
if out != want {
t.Errorf("got\n%s\nwant\n%s", out, want)
}
}
func TestLocalOwnerReachesEverything(t *testing.T) {
_, h := newTestServer(t, nil)
for _, p := range accessPages {
if p == "/settings/account" || p == "/settings/users" {
continue // there are no accounts on the local edition
}
if rec := do(h, http.MethodGet, p, nil, nil); rec.Code != http.StatusOK {
t.Errorf("local GET %s: %d", p, rec.Code)
}
}
if body := do(h, http.MethodGet, "/seo/keywords", nil, nil).Body.String(); strings.Contains(body, "readonly") {
t.Error("local forms disabled")
}
}
func TestMailTeam(t *testing.T) {
s, _ := newServerEdition(t)
a := addUser(t, s, "a@example.com", users.Member, map[string]users.Access{"seo": users.View})
b := addUser(t, s, "b@example.com", users.Member, map[string]users.Access{"metrics": users.Edit})
c := addUser(t, s, "c@example.com", users.Admin, nil)
d := addUser(t, s, "d@example.com", users.Admin, nil)
for _, u := range []*users.User{a, b, c} {
u.Emails = []string{"seo-check"}
users.SaveProfile(s.DB, u)
}
users.SetStatus(s.DB, c.ID, users.Disabled)
_ = d // didn't ask
if n := s.mailTeam(t.Context(), "seo-check", "Moved", "Text"); n != 1 {
t.Errorf("sent %d", n)
}
m := s.Mail.(interface{ Last(string) *appmail.Message }).Last("a@example.com")
if m == nil || !strings.Contains(m.Body, "/settings/account") {
t.Errorf("mail %+v", m)
}
}
+380
View File
@@ -0,0 +1,380 @@
package web
import (
"encoding/base64"
"html/template"
"net/http"
"net/url"
"strings"
"time"
"rsc.io/qr"
"supermarket/internal/posting"
"supermarket/internal/secrets"
"supermarket/internal/users"
)
// Settings → Your account, on the server edition: each person's profile,
// password, two-factor sign-in, and where they're signed in.
type accountData struct {
U *users.User
Role users.Role
Sessions []sessionRow
Zones []string
Emails []emailKind // the emails they may choose
Photos bool // there's file storage for a photo
// Their own posting accounts, and the networks they can connect.
Posting []*posting.Account
Connectable []grant
Problem string // under the form it's about
Section string // which form: profile, password, two-factor
// Setting up two-factor sign-in.
Secret string
QR template.URL
// Recovery codes, shown once.
Codes []string
}
type sessionRow struct {
*users.Session
This bool
}
// commonZones are offered for the time zone; any IANA name is accepted.
var commonZones = []string{
"UTC", "Europe/London", "Europe/Dublin", "Europe/Lisbon", "Europe/Paris", "Europe/Berlin", "Europe/Madrid", "Europe/Rome",
"Europe/Amsterdam", "Europe/Stockholm", "Europe/Warsaw", "Europe/Athens", "Europe/Helsinki", "Europe/Istanbul",
"America/New_York", "America/Toronto", "America/Chicago", "America/Denver", "America/Phoenix", "America/Los_Angeles",
"America/Anchorage", "Pacific/Honolulu", "America/Mexico_City", "America/Sao_Paulo", "America/Buenos_Aires",
"Africa/Lagos", "Africa/Johannesburg", "Africa/Nairobi", "Asia/Dubai", "Asia/Kolkata", "Asia/Singapore",
"Asia/Shanghai", "Asia/Tokyo", "Asia/Seoul", "Australia/Perth", "Australia/Sydney", "Pacific/Auckland",
}
// me is the signed-in user, or a 404 on the local edition, which has no
// accounts.
func (s *Server) me(w http.ResponseWriter, r *http.Request) *viewer {
v := viewerOf(r)
if v.User == nil {
http.NotFound(w, r)
return nil
}
return v
}
func (s *Server) accountPage(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
s.renderAccount(w, r, v, &accountData{}, http.StatusOK)
}
func (s *Server) renderAccount(w http.ResponseWriter, r *http.Request, v *viewer, d *accountData, code int) {
u, err := users.ByID(s.DB, v.User.ID)
if err != nil {
s.serverError(w, err)
return
}
list, err := users.Sessions(s.DB, u.ID, time.Now())
if err != nil {
s.serverError(w, err)
return
}
d.U, d.Role, d.Zones, d.Emails, d.Photos = u, v.Member.Role, commonZones, emailsFor(v.Member), s.Files != nil
if v.Member.Can("content", true) {
d.Posting, _ = posting.OwnedBy(s.DB, u.ID)
if s.Secrets.Has(secrets.XClientID) {
d.Connectable = append(d.Connectable, grant{"x", "X"})
}
if s.Secrets.Has(secrets.LinkedInClientID) && s.Secrets.Has(secrets.LinkedInClientSecret) {
d.Connectable = append(d.Connectable, grant{"linkedin", "LinkedIn"})
}
}
for _, ss := range list {
d.Sessions = append(d.Sessions, sessionRow{Session: ss, This: ss.ID == v.Session.ID})
}
if code != http.StatusOK {
w.WriteHeader(code)
}
s.render(w, r, "account", page{Title: "Your account", Nav: "settings/account", Data: d})
}
func (s *Server) accountProfile(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
u := *v.User
u.Name = strings.TrimSpace(r.PostFormValue("name"))
u.Title = strings.TrimSpace(r.PostFormValue("title"))
u.TimeZone = strings.TrimSpace(r.PostFormValue("time_zone"))
u.Emails = pickEmails(v.Member, r.PostForm["emails"])
switch {
case u.Name == "":
s.renderAccount(w, r, v, &accountData{Section: "profile", Problem: "Give your name."}, http.StatusUnprocessableEntity)
return
case u.TimeZone != "" && !validZone(u.TimeZone):
s.renderAccount(w, r, v, &accountData{Section: "profile", Problem: "That isn't a time zone: choose one from the list, such as Europe/Paris."}, http.StatusUnprocessableEntity)
return
}
if err := users.SaveProfile(s.DB, &u); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/account", "saved")
}
func validZone(z string) bool {
if z == "Local" || len(z) > 64 {
return false
}
_, err := time.LoadLocation(z)
return err == nil
}
func (s *Server) accountPassword(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
u, err := users.ByID(s.DB, v.User.ID)
if err != nil {
s.serverError(w, err)
return
}
fail := func(msg string) {
s.renderAccount(w, r, v, &accountData{Section: "password", Problem: msg}, http.StatusUnprocessableEntity)
}
if !users.CheckPassword(u, r.PostFormValue("current")) {
s.accountWrongPassword(r, u)
fail("Your current password isn't right.")
return
}
pw := r.PostFormValue("password")
if err := users.CheckNewPassword(pw, u.Email); err != nil {
fail(sentence(err.Error()) + ".")
return
}
if pw != r.PostFormValue("password2") {
fail("The two new passwords aren't the same.")
return
}
if err := users.SetPassword(s.DB, u, pw); err != nil {
s.serverError(w, err)
return
}
n, err := users.EndOtherSessions(s.DB, u.ID, v.Session.ID)
if err != nil {
s.serverError(w, err)
return
}
s.Log.Info("account: password changed", "user", u.Email, "sessions ended", n)
s.audit(r, "password-changed", u.Email, "")
redirect(w, r, "/settings/account", "password-changed")
}
// accountWrongPassword counts a wrong current password like a failed
// sign-in: someone at an open laptop can't guess at it for ever.
func (s *Server) accountWrongPassword(r *http.Request, u *users.User) {
now := time.Now()
s.countFailure("signin:ip:"+clientIP(r), "signin:email:"+u.Email, u, now)
}
func (s *Server) accountEndSession(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
id := r.PathValue("id")
if id == v.Session.ID {
s.signout(w, r)
return
}
if err := users.EndSessionByID(s.DB, v.User.ID, id); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/account#sessions", "session-ended")
}
func (s *Server) accountEndOthers(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
if _, err := users.EndOtherSessions(s.DB, v.User.ID, v.Session.ID); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/account#sessions", "sessions-ended")
}
// Two-factor sign-in.
// twoFactorPage starts setting up an authenticator app: a new secret,
// kept aside until a code from the app confirms it.
func (s *Server) twoFactorPage(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
if v.User.TwoFactor {
http.Redirect(w, r, "/settings/account#two-factor", http.StatusSeeOther)
return
}
secret := s.Secrets.Get(users.TOTPPendingName(v.User.ID))
if secret == "" || r.URL.Query().Get("new") != "" {
var err error
if secret, err = users.NewTOTPSecret(); err != nil {
s.serverError(w, err)
return
}
if err := s.Secrets.Set(map[string]string{users.TOTPPendingName(v.User.ID): secret}); err != nil {
s.serverError(w, err)
return
}
}
s.renderTwoFactor(w, r, v, secret, "", http.StatusOK)
}
func (s *Server) renderTwoFactor(w http.ResponseWriter, r *http.Request, v *viewer, secret, problem string, code int) {
d := &accountData{U: v.User, Secret: spaced(secret), Problem: problem}
if c, err := qr.Encode(users.TOTPURL(s.issuer(), v.User.Email, secret), qr.M); err == nil {
c.Scale = 6
d.QR = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(c.PNG()))
}
if code != http.StatusOK {
w.WriteHeader(code)
}
s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Data: d})
}
// issuer is the name the authenticator app shows: Supermarket and where.
func (s *Server) issuer() string {
if u, err := url.Parse(s.PublicURL); err == nil && u.Hostname() != "" {
return "Supermarket (" + u.Hostname() + ")"
}
return "Supermarket"
}
// spaced writes a secret in groups of four, to type it in.
func spaced(secret string) string {
var b strings.Builder
for i, c := range secret {
if i > 0 && i%4 == 0 {
b.WriteByte(' ')
}
b.WriteRune(c)
}
return b.String()
}
func (s *Server) twoFactorOn(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
u, err := users.ByID(s.DB, v.User.ID)
if err != nil {
s.serverError(w, err)
return
}
secret := s.Secrets.Get(users.TOTPPendingName(u.ID))
if u.TwoFactor || secret == "" {
http.Redirect(w, r, "/settings/account#two-factor", http.StatusSeeOther)
return
}
step, ok := users.CheckTOTP(secret, r.PostFormValue("code"), 0, time.Now())
if !ok {
s.renderTwoFactor(w, r, v, secret, "That code isn't right. Check the app shows Supermarket's code, and that your phone's clock is right, then try the code showing now.", http.StatusUnprocessableEntity)
return
}
codes, hashes, err := users.NewRecoveryCodes()
if err != nil {
s.serverError(w, err)
return
}
if err := s.Secrets.Set(map[string]string{users.TOTPSecretName(u.ID): secret, users.TOTPPendingName(u.ID): ""}); err != nil {
s.serverError(w, err)
return
}
if err := users.SetTwoFactor(s.DB, u, true, hashes); err != nil {
s.serverError(w, err)
return
}
_ = users.UseTOTPStep(s.DB, u, step)
s.Log.Info("account: two-factor sign-in on", "user", u.Email)
s.audit(r, "two-factor-on", u.Email, "")
s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Flash: "Two-factor sign-in is on.", Data: &accountData{U: u, Codes: codes}})
}
func (s *Server) twoFactorOff(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
u, err := users.ByID(s.DB, v.User.ID)
if err != nil {
s.serverError(w, err)
return
}
if !users.CheckPassword(u, r.PostFormValue("current")) {
s.accountWrongPassword(r, u)
s.renderAccount(w, r, v, &accountData{Section: "two-factor", Problem: "Your password isn't right."}, http.StatusUnprocessableEntity)
return
}
if err := turnOffTwoFactor(s, u); err != nil {
s.serverError(w, err)
return
}
s.Log.Info("account: two-factor sign-in off", "user", u.Email)
s.audit(r, "two-factor-off", u.Email, "")
redirect(w, r, "/settings/account#two-factor", "two-factor-off")
}
// turnOffTwoFactor removes a user's authenticator and recovery codes.
func turnOffTwoFactor(s *Server, u *users.User) error {
if err := users.SetTwoFactor(s.DB, u, false, nil); err != nil {
return err
}
return s.Secrets.Set(map[string]string{users.TOTPSecretName(u.ID): "", users.TOTPPendingName(u.ID): ""})
}
func (s *Server) recoveryCodes(w http.ResponseWriter, r *http.Request) {
v := s.me(w, r)
if v == nil {
return
}
u, err := users.ByID(s.DB, v.User.ID)
if err != nil {
s.serverError(w, err)
return
}
if !u.TwoFactor {
http.Redirect(w, r, "/settings/account#two-factor", http.StatusSeeOther)
return
}
if !users.CheckPassword(u, r.PostFormValue("current")) {
s.accountWrongPassword(r, u)
s.renderAccount(w, r, v, &accountData{Section: "two-factor", Problem: "Your password isn't right."}, http.StatusUnprocessableEntity)
return
}
codes, hashes, err := users.NewRecoveryCodes()
if err != nil {
s.serverError(w, err)
return
}
step := u.TOTPStep()
if err := users.SetTwoFactor(s.DB, u, true, hashes); err != nil {
s.serverError(w, err)
return
}
_ = users.UseTOTPStep(s.DB, u, step)
s.Log.Info("account: new recovery codes", "user", u.Email)
s.audit(r, "recovery-codes", u.Email, "")
s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Flash: "New recovery codes: the old ones no longer work.", Data: &accountData{U: u, Codes: codes}})
}
+200
View File
@@ -0,0 +1,200 @@
package web
import (
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/audit"
"supermarket/internal/users"
)
// The audit log: who did what. Sign-ins, accounts and connections are
// recorded where they happen; what's sent, published or deleted, by the
// table below, after the request succeeds.
// audit records something the viewer did.
func (s *Server) audit(r *http.Request, action, target, detail string) {
v := viewerOf(r)
e := audit.Entry{Action: action, Target: target, Detail: detail, IP: clientIP(r)}
if v.User != nil {
e.UserID, e.UserName = v.User.ID, displayName(v.User)
}
s.record(e)
}
// auditFor records something done for a user, without a request: a
// scheduled post going out, an email sent from the queue.
func (s *Server) auditFor(user int64, action, target, detail string) {
e := audit.Entry{Kind: audit.System, Action: action, Target: target, Detail: detail, UserID: user}
if user != 0 {
if u, err := users.ByID(s.DB, user); err == nil {
e.UserName = displayName(u)
}
}
s.record(e)
}
func (s *Server) record(e audit.Entry) {
if err := audit.Record(s.DB, e); err != nil {
s.Log.Error("audit: not recorded", "action", e.Action, "err", err)
}
}
func displayName(u *users.User) string {
if u.Name != "" {
return u.Name
}
return u.Email
}
// auditedRoutes are the changes recorded by their route, when they work:
// the route's pattern, then its {action} ("" for routes without one).
var auditedRoutes = map[string]map[string]string{
"POST /drafts/{id}/{action}": {"schedule": "scheduled", "posted": "marked-posted", "discard": "deleted"},
"POST /outreach/{id}/{action}": {"queue": "queued-email", "send-now": "sent-email", "mark-sent": "marked-sent", "discard": "deleted"},
"POST /prospects/{kind}/{id}/{action}": {"accept": "queued-for-crm", "accept-all": "queued-for-crm", "list": "added-to-list", "delete": "deleted", "suppress": "suppressed"},
"POST /seo/changes/{id}/{action}": {"yes": "opened-pull-request"},
"POST /seo/briefs/{id}/{action}": {"pr": "opened-pull-request", "drop": "deleted"},
"POST /sites/pages/{id}/{action}": {"remove": "deleted", "close": "closed-pull-request"},
"POST /sites/new": {"": "created-site"},
"POST /sites/pages/add": {"": "opened-pull-request"},
"POST /sites/theme/update": {"": "opened-pull-request"},
"POST /sites/previews/delete": {"": "deleted"},
"POST /seo/engines/setup": {"": "opened-pull-request"},
"POST /seo/engines/ping": {"": "sent-to-indexnow"},
"POST /metrics/publish": {"": "published"},
"POST /market/{id}/delete": {"": "deleted"},
"POST /signals/{id}/delete": {"": "deleted"},
"POST /funnel/{id}/delete": {"": "deleted"},
"POST /metrics/spend/{id}/delete": {"": "deleted"},
"POST /settings/backups/{action}": {"restore": "restored-backup", "delete": "deleted"},
"POST /crm/{id}/{action}": {"cancel": "deleted"},
"POST /prospects/suppressed": {"": "changed-suppression"},
"POST /settings/email/send-test": {"": "sent-email"},
"POST /settings/email/listmonk/sync": {"": "synced-mailing-lists"},
"POST /settings/profile": {"": "changed-profile"},
}
// statusWriter notes the response's status.
type statusWriter struct {
http.ResponseWriter
code int
}
func (w *statusWriter) WriteHeader(code int) {
if w.code == 0 {
w.code = code
}
w.ResponseWriter.WriteHeader(code)
}
func (w *statusWriter) Write(b []byte) (int, error) {
if w.code == 0 {
w.code = http.StatusOK
}
return w.ResponseWriter.Write(b)
}
// audited wraps a route in the table: a request that worked (a redirect
// or a page, not an error) is recorded.
func (s *Server) audited(pattern string, next http.Handler) http.Handler {
actions, ok := auditedRoutes[pattern]
if !ok {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
action, ok := actions[r.PathValue("action")]
if !ok {
next.ServeHTTP(w, r)
return
}
sw := &statusWriter{ResponseWriter: w}
next.ServeHTTP(sw, r)
// A failed form re-renders its page with 200 and an error: only
// redirects count as done.
if sw.code == http.StatusSeeOther || sw.code == http.StatusFound {
target := r.URL.Path
if k := r.PathValue("kind"); k != "" {
target = k + " " + r.PathValue("id")
}
s.audit(r, action, target, "")
}
})
}
// Settings → Activity.
type activityData struct {
Entries []audit.Entry
People []users.TeamUser
Filter audit.Filter
More int64 // the ID to page from; 0: no more
}
const activityPage = 100
func (s *Server) activityPage(w http.ResponseWriter, r *http.Request) {
if !s.adminPage(w, r) {
return
}
q := r.URL.Query()
f := audit.Filter{Action: strings.TrimSpace(q.Get("action")), Text: q.Get("q")}
f.UserID, _ = strconv.ParseInt(q.Get("user"), 10, 64)
f.Before, _ = strconv.ParseInt(q.Get("before"), 10, 64)
entries, err := audit.List(s.DB, f, activityPage+1)
if err != nil {
s.serverError(w, err)
return
}
d := activityData{Filter: f}
if len(entries) > activityPage {
entries = entries[:activityPage]
d.More = entries[len(entries)-1].ID
}
d.Entries = entries
d.People, _ = users.Members(s.DB, s.team())
s.render(w, r, "activity", page{Title: "Activity", Nav: "settings/activity", Data: d})
}
// actionLabels say what an action was, in the Activity list.
var actionLabels = map[string]string{
"setup": "set up Supermarket as its owner", "signin": "signed in", "signin-failed": "failed to sign in",
"locked": "was locked out", "signout": "signed out", "reset-asked": "asked to reset the password",
"password-reset": "reset the password", "password-changed": "changed the password",
"two-factor-on": "turned two-factor sign-in on", "two-factor-off": "turned two-factor sign-in off",
"recovery-codes": "made new recovery codes", "joined": "joined",
"invited": "invited", "invitation-resent": "sent an invitation again", "invitation-withdrawn": "withdrew an invitation",
"access-changed": "changed the access of", "disabled": "turned off the account of", "enabled": "turned on the account of",
"unlocked": "unlocked", "two-factor-reset": "reset two-factor sign-in for", "signed-out-user": "signed out everywhere",
"removed-user": "removed", "connected": "connected", "disconnected": "removed the connection to",
"account-signed-out": "signed out the posting account", "posting-grants": "changed who may post to which account",
"published": "published", "scheduled": "scheduled", "marked-posted": "marked as posted", "deleted": "deleted",
"queued-email": "queued an email", "sent-email": "sent an email", "marked-sent": "marked an email as sent",
"queued-for-crm": "queued for the CRM", "added-to-list": "added to a mailing list", "suppressed": "added to the suppression list",
"opened-pull-request": "opened a pull request", "closed-pull-request": "closed a pull request", "created-site": "started a site",
"sent-to-indexnow": "sent pages to IndexNow", "restored-backup": "restored a backup", "changed-suppression": "changed the suppression list",
"synced-mailing-lists": "synced the mailing lists", "changed-profile": "changed the company profile",
"agent-created": "made the agent", "agent-changed": "changed what this agent may do:", "key-rotated": "rotated the key of",
"key-made": "made a new key for", "key-revoked": "revoked a key of",
"asked-approval": "asked for approval to", "did-on-its-own": "did on its own:", "approved": "approved", "refused": "refused",
"allowed-on-its-own": "let an agent act on its own:", "withdrew-on-its-own": "took back what an agent may do on its own:",
"signin-settings": "changed how people sign in:", "billing-checkout": "went to subscribe:", "billing-seat": "added a seat:", "billing-kept": "chose who keeps editing:", "billing": "billing changed:", "trial-ended": "the trial ended:", "lapse-due": "a payment failed:", "lapse-read-only": "made read-only:", "lapse-warned": "warned of deletion:", "team-created": "set up the team", "viewed-as": "looked at the team's data:", "team-suspended": "suspended the team", "team-restored": "restored the team",
"domain-released": "released the domain", "exported": "exported", "downloaded-export": "downloaded the export", "team-deleting": "asked to delete the team", "team-undeleted": "undid the team's deletion", "invitations-resent": "sent the invitations again:", "domain-proved": "proved the domain", "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of",
"wrote-draft": "wrote a draft:", "edited-draft": "edited a draft:", "edited-change": "edited a proposed change to", "market-added": "added to the Market", "market-changed": "changed in the Market",
}
func actionLabel(a string) string {
if l, ok := actionLabels[a]; ok {
return l
}
return strings.ReplaceAll(a, "-", " ")
}
// pruneAudit keeps two years of the log.
func (s *Server) pruneAudit(now time.Time) {
if _, err := audit.Prune(s.DB, 2*365*24*time.Hour, now); err != nil {
s.Log.Warn("audit: pruning", "err", err)
}
}
+53
View File
@@ -0,0 +1,53 @@
package web
import (
"net/http"
"net/url"
"strconv"
"strings"
"testing"
"supermarket/internal/audit"
"supermarket/internal/inventory"
"supermarket/internal/secrets"
"supermarket/internal/users"
)
func TestActivityRecords(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
owner.Name = "Olu"
users.SaveProfile(s.DB, owner)
oc := sessionFor(t, s, owner)
// A failed sign-in, a connection, a deletion.
signin(h, "203.0.113.4", url.Values{"email": {"owner@example.com"}, "password": {"nope nope nope"}})
as(h, oc, http.MethodPost, "/settings/sources", url.Values{secrets.HunterAPIKey: {"hk"}})
e := &inventory.Entry{Name: "Rival", Relationship: "competitor"}
inventory.Save(s.DB, e)
if rec := as(h, oc, http.MethodPost, "/market/"+itoa64(e.ID)+"/delete", url.Values{}); rec.Code != http.StatusSeeOther {
t.Fatalf("delete: %d", rec.Code)
}
entries, _ := audit.List(s.DB, audit.Filter{}, 50)
byAction := map[string][]audit.Entry{}
for _, e := range entries {
byAction[e.Action] = append(byAction[e.Action], e)
}
if f := byAction["signin-failed"]; len(f) != 1 || f[0].IP != "203.0.113.4" || f[0].UserID != owner.ID {
t.Errorf("failed sign-in: %+v", f)
}
if c := byAction["connected"]; len(c) != 1 || c[0].Target != "Hunter.io" || c[0].UserName != "Olu" {
t.Errorf("connection: %+v", c)
}
if d := byAction["deleted"]; len(d) != 1 || !strings.Contains(d[0].Target, "/market/") {
t.Errorf("deletions: %+v", d)
}
// Filters.
body := as(h, oc, http.MethodGet, "/settings/activity?action=signin-failed", nil).Body.String()
if !strings.Contains(body, "failed to sign in") || strings.Contains(body, "Hunter.io") {
t.Errorf("filtered: %s", body)
}
}
func itoa64(n int64) string { return strconv.FormatInt(n, 10) }
+99
View File
@@ -0,0 +1,99 @@
package web
import (
"encoding/json"
"net/http"
"net/url"
"strconv"
"strings"
"testing"
"time"
"supermarket/internal/content"
"supermarket/internal/posting"
"supermarket/internal/users"
)
func TestAgentPauseAndLimits(t *testing.T) {
s, h := newTestServer(t, nil)
agent, key := newAgent(t, s, "Busy", map[string]users.Access{"content": users.Edit})
page := "/settings/agents/" + strconv.FormatInt(agent.ID, 10)
// Its calls are listed on its page, errors too.
mcpCall(t, h, key, "content_drafts", map[string]any{})
mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "myspace", "text": "x"})
body := do(h, http.MethodGet, page, nil, nil).Body.String()
if !strings.Contains(body, "<code>content_drafts</code>") || !strings.Contains(body, "no channel") {
t.Errorf("calls: %s", body)
}
// Pause: every call refused at once, with why.
postForm(h, page+"/pause", url.Values{})
code, _ := mcpTools(h, key)
if code != http.StatusForbidden {
t.Errorf("paused: %d", code)
}
if body := do(h, http.MethodGet, "/settings/agents", nil, nil).Body.String(); !strings.Contains(body, "paused") {
t.Error("not shown as paused")
}
postForm(h, page+"/resume", url.Values{})
if code, _ := mcpTools(h, key); code != http.StatusOK {
t.Errorf("resumed: %d", code)
}
// Calls a minute.
if rec := postForm(h, page+"/limits", url.Values{"per_minute": {"0"}, "out_per_day": {"1"}}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("zero: %d", rec.Code)
}
postForm(h, page+"/limits", url.Values{"per_minute": {"3"}, "out_per_day": {"1"}})
// Two calls so far in this minute; one more is fine, the next isn't.
if _, isErr := mcpCall(t, h, key, "content_drafts", map[string]any{}); isErr {
t.Error("third call refused")
}
if text, isErr := mcpCall(t, h, key, "content_drafts", map[string]any{}); !isErr || !strings.Contains(text, "3 a minute") {
t.Errorf("fourth call: %v %s", isErr, text)
}
calls, _ := users.RecentCalls(s.DB, agent.ID, 1)
if calls[0].Outcome != users.CallRefused {
t.Errorf("not recorded as refused: %+v", calls[0])
}
// A minute later it may call again (the refused call doesn't count).
s.DB.Exec(`UPDATE agent_calls SET at = ?`, time.Now().Add(-2*time.Minute).UTC().Format("2006-01-02T15:04:05.000Z"))
// Things sent out a day: one.
postForm(h, page+"/limits", url.Values{"per_minute": {"100"}, "out_per_day": {"1"}})
company := &posting.Account{Network: posting.X, Name: "@acme", External: "acme"}
posting.Save(s.DB, s.Secrets, company, "t", "", time.Now())
posting.SetGrants(s.DB, map[int64][]int64{company.ID: {agent.ID}})
for i, want := range []string{"Waiting for approval", "may ask to send out 1 things a day"} {
text, _ := mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Post " + strconv.Itoa(i)})
var d draftView
json.Unmarshal([]byte(text), &d)
if text, _ := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID}); !strings.Contains(text, want) {
t.Errorf("ask %d: %s", i, text)
}
}
if body := do(h, http.MethodGet, page, nil, nil).Body.String(); !strings.Contains(body, "Waiting on") || !strings.Contains(body, "asked to send out 1 of its 1") {
t.Errorf("agent page: %s", body)
}
}
// Two agents with the same scopes each have their own server: what they
// write is theirs.
func TestAgentsDontShareServers(t *testing.T) {
s, h := newTestServer(t, nil)
scopes := map[string]users.Access{"content": users.Edit}
a, ka := newAgent(t, s, "A", scopes)
b, kb := newAgent(t, s, "B", scopes)
for _, k := range []string{ka, kb} {
mcpCall(t, h, k, "content_create_draft", map[string]any{"channel": "x", "text": "From " + k[:8]})
}
list, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
by := map[string]int64{}
for _, d := range list {
by[d.Content] = d.WrittenBy
}
if by["From "+ka[:8]] != a.ID || by["From "+kb[:8]] != b.ID {
t.Errorf("written by %v (a %d, b %d)", by, a.ID, b.ID)
}
}
+559
View File
@@ -0,0 +1,559 @@
package web
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"supermarket/internal/approvals"
"supermarket/internal/audit"
"supermarket/internal/fileutil"
"supermarket/internal/mcpserver"
"supermarket/internal/users"
)
// Agents: programs that reach Supermarket over MCP with a key. Each is a
// user of kind agent, given modules to read, or to read and act on, and
// maybe the CRM scope (Hermes' bridge). Admins manage them under Settings
// → Agents, on every edition.
// AgentAuth checks a bearer key for /mcp. Wrong keys count against the
// caller's address, like failed sign-ins.
func (s *Server) AgentAuth(r *http.Request, key string) (*mcpserver.Caller, error) {
now := time.Now()
ip := clientIP(r)
ipKey := "mcp:ip:" + ip
if s.throttled(ipKey, users.MaxFailsPerIP, now) {
return nil, users.ErrBadKey
}
u, _, err := users.Authenticate(s.platform(), key, ip, now)
if err != nil {
if errors.Is(err, users.ErrBadKey) {
_ = users.Fail(s.DB, ipKey, users.ThrottleWindow, now)
s.Log.Info("mcp: a key was refused", "ip", ip)
} else {
s.Log.Error("mcp: checking a key", "err", err)
}
return nil, err
}
team := s.team()
if s.multi() {
if team, err = users.AgentTeam(s.platform(), u.ID); err != nil {
return nil, users.ErrBadKey
}
}
ts, err := s.forTeam(team)
if err != nil {
return nil, err
}
m, err := users.MembershipOf(ts.platform(), team, u.ID)
if err != nil {
return nil, users.ErrBadKey
}
if plan, ro := ts.teamPlan(); plan != nil {
if ro {
return nil, &mcpserver.Refusal{Status: http.StatusForbidden, Reason: sentence(errLapsed.Error()) + "."}
}
m = planned(m, plan, ro)
}
lim, err := users.LimitsOf(ts.DB, u.ID)
if err != nil {
return nil, err
}
if !lim.Paused.IsZero() {
return nil, &mcpserver.Refusal{Status: http.StatusForbidden,
Reason: u.Name + " is paused: an admin can resume it under Settings → Agents."}
}
id := u.ID
c := &mcpserver.Caller{ID: u.ID, Name: u.Name, Can: m.Can, Team: team,
Before: func(ctx context.Context, tool string) error { return ts.beforeCall(id, tool) },
After: func(tool string, res *mcp.CallToolResult, err error, took time.Duration) {
ts.afterCall(id, tool, res, err, took)
}}
if s.multi() {
c.DB = ts.DB
}
return c, nil
}
// beforeCall keeps an agent within its calls a minute, and stops a paused
// agent's call even mid-session.
func (s *Server) beforeCall(agent int64, tool string) error {
now := time.Now()
lim, err := users.LimitsOf(s.DB, agent)
if err != nil {
return err
}
if !lim.Paused.IsZero() {
return errors.New("this agent is paused: an admin can resume it under Settings → Agents")
}
n, err := users.CallsSince(s.DB, agent, now.Add(-time.Minute))
if err != nil {
return err
}
if n >= lim.PerMinute {
_ = users.RecordCall(s.DB, users.Call{Agent: agent, At: now, Tool: tool, Outcome: users.CallRefused,
Detail: fmt.Sprintf("over %d calls a minute", lim.PerMinute)})
return fmt.Errorf("too many calls: this agent may make %d a minute; wait a little", lim.PerMinute)
}
return nil
}
// afterCall records an agent's tool call.
func (s *Server) afterCall(agent int64, tool string, res *mcp.CallToolResult, err error, took time.Duration) {
c := users.Call{Agent: agent, At: time.Now().Add(-took), Tool: tool, Outcome: users.CallOK, Took: took}
switch {
case err != nil:
c.Outcome, c.Detail = users.CallError, err.Error()
case res != nil && res.IsError:
c.Outcome = users.CallError
fallthrough
case res != nil:
if len(res.Content) > 0 {
if t, ok := res.Content[0].(*mcp.TextContent); ok {
c.Detail = strings.Join(strings.Fields(t.Text), " ")
}
}
}
if err := users.RecordCall(s.DB, c); err != nil {
s.Log.Warn("agents: recording a call", "err", err)
}
}
// hermesKey is the setting naming the local edition's built-in Hermes agent.
const hermesKey = "agents:hermes"
// EnsureHermes makes the local edition's built-in Hermes agent, with the
// CRM scope, and makes mcp-token one of its keys: what used to be the one
// token for /mcp is now Hermes' key. Its socket stays as it is.
func (s *Server) EnsureHermes(token string) error {
if token == "" {
return nil
}
now := time.Now()
var id int64
if ok, err := s.DB.GetJSON(hermesKey, &id); err != nil {
return err
} else if ok {
if _, err := users.ByID(s.DB, id); errors.Is(err, users.ErrNotFound) {
ok = false
} else if err != nil {
return err
}
if ok {
// The token file may be new (a restore, a new install).
if _, _, err := users.Authenticate(s.DB, token, "", now); errors.Is(err, users.ErrBadKey) {
_, err = users.AddKey(s.DB, id, token, time.Time{}, now)
return err
}
return nil
}
}
u, err := users.CreateAgent(s.DB, "Hermes", "The Hermes agent on this computer: works the CRM queue through your Core, and reads the Market (Claude Code, set up by install.sh, uses its key too). Its key is mcp-token in the data folder; it also reaches Supermarket through the socket there.", now)
if err != nil {
return err
}
if err := users.Join(s.DB, s.team(), u.ID, users.Member, map[string]users.Access{users.CRMScope: users.Edit, "market": users.View}, now); err != nil {
return err
}
if _, err := users.AddKey(s.DB, u.ID, token, time.Time{}, now); err != nil {
return err
}
s.record(audit.Entry{Kind: audit.System, Action: "agent-created", Target: "Hermes", Detail: "built in, with the key in mcp-token"})
return s.DB.PutJSON(hermesKey, u.ID)
}
// isHermes says whether an agent is the built-in one.
func (s *Server) isHermes(id int64) bool {
var h int64
ok, _ := s.DB.GetJSON(hermesKey, &h)
return ok && h == id && !s.signsIn()
}
// agentGrants are what an agent can be given: the modules, and the CRM.
func agentGrants() []grant {
return append(grants(), grant{users.CRMScope, "CRM through the Core"})
}
// agentRow is an agent in the list.
type agentRow struct {
users.TeamUser
Access string
Keys []*users.Key
Working int // keys that work now
Last *users.Key // the last used
BuiltIn bool
Limits users.Limits
}
func (s *Server) agentRows(now time.Time) ([]agentRow, error) {
list, err := users.Members(s.DB, s.team())
if err != nil {
return nil, err
}
var out []agentRow
for _, m := range list {
if m.Kind != users.Agent {
continue
}
row := agentRow{TeamUser: m, Access: agentAccessText(m.Membership), BuiltIn: s.isHermes(m.ID)}
if row.Limits, err = users.LimitsOf(s.DB, m.ID); err != nil {
return nil, err
}
if row.Keys, err = users.Keys(s.DB, m.ID); err != nil {
return nil, err
}
for _, k := range row.Keys {
if k.Working(now) {
row.Working++
}
if !k.Used.IsZero() && (row.Last == nil || k.Used.After(row.Last.Used)) {
row.Last = k
}
}
out = append(out, row)
}
return out, nil
}
// agentAccessText is an agent's scopes: "SEO (read), Content (read and act)".
func agentAccessText(m users.Membership) string {
var parts []string
for _, g := range agentGrants() {
switch m.Modules[g.ID] {
case users.Edit:
parts = append(parts, g.Name+" (read and act)")
case users.View:
parts = append(parts, g.Name+" (read)")
}
}
if len(parts) == 0 {
return "Nothing yet"
}
return strings.Join(parts, ", ")
}
// agentScopesFromForm reads scope:<id>=read|act|"".
func agentScopesFromForm(r *http.Request) map[string]users.Access {
out := map[string]users.Access{}
for _, g := range agentGrants() {
switch r.PostFormValue("scope:" + g.ID) {
case "read":
out[g.ID] = users.View
case "act":
out[g.ID] = users.Edit
}
}
return out
}
// expiryFromForm reads an optional date (the key stops at its start, in
// the server's time zone).
func expiryFromForm(r *http.Request, now time.Time) (time.Time, error) {
v := strings.TrimSpace(r.PostFormValue("expires"))
if v == "" {
return time.Time{}, nil
}
t, err := time.ParseInLocation("2006-01-02", v, time.Local)
if err != nil {
return time.Time{}, errors.New("the expiry isn't a date")
}
if !t.After(now) {
return time.Time{}, errors.New("the expiry has passed: choose a later date, or none")
}
return t, nil
}
type agentsData struct {
Rows []agentRow
Grants []grant
Form agentForm
MCPURL string
Problem string
}
type agentForm struct {
Name, Description, Expires string
Scopes map[string]users.Access
}
func (s *Server) agentsPage(w http.ResponseWriter, r *http.Request) {
if !viewerOf(r).Member.Admin() {
s.forbidden(w, r)
return
}
s.renderAgents(w, r, agentsData{}, http.StatusOK)
}
func (s *Server) renderAgents(w http.ResponseWriter, r *http.Request, d agentsData, code int) {
rows, err := s.agentRows(time.Now())
if err != nil {
s.serverError(w, err)
return
}
d.Rows, d.Grants, d.MCPURL = rows, agentGrants(), s.mcpURL()
if code != http.StatusOK {
w.WriteHeader(code)
}
s.render(w, r, "agents", page{Title: "Agents", Nav: "settings/agents", Data: d})
}
// mcpURL is where agents reach /mcp.
func (s *Server) mcpURL() string {
if s.signsIn() {
return s.PublicURL + "/mcp"
}
return "http://127.0.0.1:" + publicPort(s.PublicURL) + "/mcp"
}
func (s *Server) agentCreate(w http.ResponseWriter, r *http.Request) {
if !viewerOf(r).Member.Admin() {
s.forbidden(w, r)
return
}
now := time.Now()
f := agentForm{Name: strings.TrimSpace(r.PostFormValue("name")), Description: strings.TrimSpace(r.PostFormValue("description")),
Expires: r.PostFormValue("expires"), Scopes: agentScopesFromForm(r)}
expires, err := expiryFromForm(r, now)
if err == nil {
err = s.limitAgents()
}
switch {
case f.Name == "":
err = errors.New("give the agent a name")
case err == nil && len(f.Scopes) == 0:
err = errors.New("give the agent at least one module to read")
}
if err != nil {
s.renderAgents(w, r, agentsData{Form: f, Problem: sentence(err.Error()) + "."}, http.StatusUnprocessableEntity)
return
}
u, err := users.CreateAgent(s.DB, f.Name, f.Description, now)
if err == nil {
err = users.Join(s.DB, s.team(), u.ID, users.Member, f.Scopes, now)
}
var key string
if err == nil {
key, _, err = users.NewKey(s.DB, u.ID, expires, now)
}
if err != nil {
s.serverError(w, err)
return
}
s.audit(r, "agent-created", u.Name, agentAccessText(users.Membership{Role: users.Member, Modules: f.Scopes}))
s.showKey(w, r, u, key, "new")
}
// showKey shows a key once.
func (s *Server) showKey(w http.ResponseWriter, r *http.Request, u *users.User, key, why string) {
w.Header().Set("Cache-Control", "no-store")
s.render(w, r, "agent-key", page{Title: u.Name, Nav: "settings/agents", Data: map[string]any{
"Agent": u, "Key": key, "Why": why, "MCPURL": s.mcpURL(), "Grace": users.RotationGrace,
"Hermes": s.isHermes(u.ID),
}})
}
type agentData struct {
Row agentRow
Grants []grant
Allowed []approvals.Grant // what it may do on its own
Asked []approvals.Request
Waiting []approvals.Request // what it's waiting on
Calls []users.Call
SentDay int // what it asked to send out in the last 24 hours
Problem string
Now time.Time
}
// agentTarget is the agent named by {id}.
func (s *Server) agentTarget(w http.ResponseWriter, r *http.Request) *users.User {
if !viewerOf(r).Member.Admin() {
s.forbidden(w, r)
return nil
}
id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
u, err := users.ByID(s.DB, id)
if errors.Is(err, users.ErrNotFound) || (err == nil && u.Kind != users.Agent) {
http.NotFound(w, r)
return nil
}
if err != nil {
s.serverError(w, err)
return nil
}
return u
}
func (s *Server) agentPage(w http.ResponseWriter, r *http.Request) {
if u := s.agentTarget(w, r); u != nil {
s.renderAgent(w, r, u, "", http.StatusOK)
}
}
func (s *Server) renderAgent(w http.ResponseWriter, r *http.Request, u *users.User, problem string, code int) {
now := time.Now()
rows, err := s.agentRows(now)
if err != nil {
s.serverError(w, err)
return
}
for _, row := range rows {
if row.ID == u.ID {
if code != http.StatusOK {
w.WriteHeader(code)
}
d := agentData{Row: row, Grants: agentGrants(), Problem: problem, Now: now}
d.Allowed, _ = approvals.Grants(s.DB, u.ID)
d.Asked, _ = approvals.List(s.DB, "", u.ID, 20)
d.Waiting, _ = approvals.List(s.DB, approvals.Waiting, u.ID, 50)
d.Calls, _ = users.RecentCalls(s.DB, u.ID, 50)
d.SentDay, _ = approvals.AskedSince(s.DB, u.ID, now.Add(-24*time.Hour))
s.render(w, r, "agent", page{Title: u.Name, Nav: "settings/agents", Data: d})
return
}
}
http.NotFound(w, r)
}
// agentAction: save, rotate, revoke, disable, enable, remove.
func (s *Server) agentAction(w http.ResponseWriter, r *http.Request) {
u := s.agentTarget(w, r)
if u == nil {
return
}
now := time.Now()
back := "/settings/agents/" + strconv.FormatInt(u.ID, 10)
var err error
switch r.PathValue("action") {
case "save":
scopes := agentScopesFromForm(r)
if len(scopes) == 0 {
s.renderAgent(w, r, u, "Give the agent at least one module to read, or turn it off.", http.StatusUnprocessableEntity)
return
}
if err = users.SaveAgent(s.DB, u.ID, r.PostFormValue("name"), r.PostFormValue("description")); err != nil {
s.renderAgent(w, r, u, sentence(err.Error())+".", http.StatusUnprocessableEntity)
return
}
if err = users.Join(s.DB, s.team(), u.ID, users.Member, scopes, now); err == nil {
s.audit(r, "agent-changed", u.Name, agentAccessText(users.Membership{Role: users.Member, Modules: scopes}))
redirect(w, r, back, "saved")
return
}
case "rotate":
var key string
leaked := r.PostFormValue("leaked") == "on"
if leaked {
// A leaked key: its replacement starts with nothing allowed on
// its own, and the old key stops now.
if err = approvals.WithdrawAll(s.DB, u.ID); err == nil {
err = users.RevokeAll(s.DB, u.ID, now)
}
if err != nil {
break
}
}
if key, _, err = users.Rotate(s.DB, u.ID, now); err == nil {
if leaked {
s.audit(r, "key-revoked", u.Name, "it leaked: every key revoked, and what it may do on its own withdrawn")
}
if s.isHermes(u.ID) {
err = s.newHermesToken(key)
}
if err == nil {
s.audit(r, "key-rotated", u.Name, "the old key works for another day")
s.showKey(w, r, u, key, "rotated")
return
}
}
case "new-key":
var expires time.Time
if expires, err = expiryFromForm(r, now); err != nil {
s.renderAgent(w, r, u, sentence(err.Error())+".", http.StatusUnprocessableEntity)
return
}
var key string
if key, _, err = users.NewKey(s.DB, u.ID, expires, now); err == nil {
s.audit(r, "key-made", u.Name, "")
s.showKey(w, r, u, key, "new")
return
}
case "revoke":
kid, _ := strconv.ParseInt(r.PostFormValue("key"), 10, 64)
if err = users.Revoke(s.DB, u.ID, kid, now); err == nil {
s.audit(r, "key-revoked", u.Name, "")
redirect(w, r, back, "key-revoked")
return
}
case "limits":
pm, _ := strconv.Atoi(r.PostFormValue("per_minute"))
pd, _ := strconv.Atoi(r.PostFormValue("out_per_day"))
if err = users.SetLimits(s.DB, u.ID, pm, pd); err != nil {
s.renderAgent(w, r, u, "Each limit is a whole number, at least 1.", http.StatusUnprocessableEntity)
return
}
s.audit(r, "agent-limits", u.Name, fmt.Sprintf("%d calls a minute, %d sent out a day", pm, pd))
redirect(w, r, back, "saved")
return
case "pause", "resume":
by := int64(0)
if v := viewerOf(r); v.User != nil {
by = v.User.ID
}
paused := r.PathValue("action") == "pause"
if err = users.Pause(s.DB, u.ID, paused, by, now); err == nil {
s.audit(r, ifElse(paused, "agent-paused", "agent-resumed"), u.Name, "")
redirect(w, r, back, ifElse(paused, "agent-paused", "agent-resumed"))
return
}
case "disable":
if err = users.SetStatus(s.DB, u.ID, users.Disabled); err == nil {
s.audit(r, "disabled", u.Name, "an agent: its keys stop working")
redirect(w, r, back, "agent-off")
return
}
case "enable":
if lerr := s.limitAgents(); lerr != nil {
s.renderAgent(w, r, u, sentence(lerr.Error())+".", http.StatusUnprocessableEntity)
return
}
if err = users.SetStatus(s.DB, u.ID, users.Active); err == nil {
s.audit(r, "enabled", u.Name, "an agent")
redirect(w, r, back, "enabled")
return
}
case "remove":
if s.isHermes(u.ID) {
s.renderAgent(w, r, u, "Hermes is built in: turn it off instead.", http.StatusUnprocessableEntity)
return
}
if err = users.Delete(s.DB, u.ID); err == nil {
s.audit(r, "removed-user", u.Name, "an agent")
redirect(w, r, "/settings/agents", "removed")
return
}
default:
http.NotFound(w, r)
return
}
s.serverError(w, err)
}
// newHermesToken writes Hermes' new key to mcp-token, where the local
// edition's tools (Claude Code's setup, supermarket token) read it.
func (s *Server) newHermesToken(key string) error {
if s.DataDir == "" {
return nil
}
if err := fileutil.WriteFileAtomic(s.DataDir+"/mcp-token", []byte(key+"\n"), 0o600); err != nil {
return err
}
s.MCPToken = key
return nil
}
+171
View File
@@ -0,0 +1,171 @@
package web
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"testing"
"time"
"supermarket/internal/users"
)
// mcpTools lists the tools a key is offered, or returns the status.
func mcpTools(h http.Handler, key string) (int, []string) {
raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"})
rec := do(h, http.MethodPost, "/mcp", bytes.NewReader(raw), map[string]string{
"Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Authorization": "Bearer " + key})
if rec.Code != http.StatusOK {
return rec.Code, nil
}
var out struct {
Result struct {
Tools []struct{ Name string } `json:"tools"`
} `json:"result"`
}
json.Unmarshal(rec.Body.Bytes(), &out)
var names []string
for _, t := range out.Result.Tools {
names = append(names, t.Name)
}
return rec.Code, names
}
var keyRe = regexp.MustCompile(`<pre id="key">(sm_[A-Za-z0-9]+)</pre>`)
func TestLocalHermesAgent(t *testing.T) {
s, h := newTestServer(t, nil)
// mcp-token is the built-in Hermes' key: CRM, and reading the Market.
code, tools := mcpTools(h, testToken)
got := strings.Join(tools, " ")
if code != http.StatusOK || !strings.Contains(got, "crm_pending_actions") || !strings.Contains(got, "inventory_list") {
t.Fatalf("hermes: %d %v", code, tools)
}
body := do(h, http.MethodGet, "/settings/agents", nil, nil).Body.String()
if !strings.Contains(body, ">Hermes</a> <span class=\"pill\">built in</span>") || !strings.Contains(body, "CRM through the Core (read and act)") {
t.Errorf("agents page: %s", body)
}
// Starting again doesn't make a second Hermes.
if err := s.EnsureHermes(testToken); err != nil {
t.Fatal(err)
}
if n, _ := users.Count(s.DB); n != 1 {
t.Errorf("%d users", n)
}
// Rotating Hermes' key writes it to mcp-token.
var id int64
s.DB.GetJSON(hermesKey, &id)
rec := postForm(h, "/settings/agents/"+strconv.FormatInt(id, 10)+"/rotate", url.Values{})
m := keyRe.FindStringSubmatch(rec.Body.String())
if m == nil || s.MCPToken != m[1] || rec.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("rotate: %s", rec.Body.String())
}
// Both work for a day.
for _, k := range []string{testToken, m[1]} {
if code, _ := mcpTools(h, k); code != http.StatusOK {
t.Errorf("after rotating, %s…: %d", k[:6], code)
}
}
// Hermes can't be removed, only turned off.
if rec := postForm(h, "/settings/agents/"+strconv.FormatInt(id, 10)+"/remove", url.Values{}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("remove hermes: %d", rec.Code)
}
}
func TestAgents(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
oc := sessionFor(t, s, owner)
member := addUser(t, s, "sam@example.com", users.Member, map[string]users.Access{"seo": users.Edit})
if rec := as(h, sessionFor(t, s, member), http.MethodGet, "/settings/agents", nil); rec.Code != http.StatusForbidden {
t.Errorf("member: %d", rec.Code)
}
// No built-in Hermes on a server, and no key works yet.
if code, _ := mcpTools(h, testToken); code != http.StatusUnauthorized {
t.Errorf("mcp-token on a server: %d", code)
}
if rec := as(h, oc, http.MethodPost, "/settings/agents", url.Values{"name": {"Writer"}}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("no scopes: %d", rec.Code)
}
if rec := as(h, oc, http.MethodPost, "/settings/agents", url.Values{"name": {"Writer"}, "scope:seo": {"read"}, "expires": {"2020-01-01"}}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("expiry passed: %d", rec.Code)
}
rec := as(h, oc, http.MethodPost, "/settings/agents", url.Values{"name": {"Writer"}, "description": {"Drafts"},
"scope:content": {"act"}, "scope:seo": {"read"}, "scope:market": {"read"}, "expires": {time.Now().AddDate(0, 1, 0).Format("2006-01-02")}})
m := keyRe.FindStringSubmatch(rec.Body.String())
if rec.Code != http.StatusOK || m == nil {
t.Fatalf("create: %d %s", rec.Code, rec.Body.String())
}
key := m[1]
if !strings.Contains(rec.Body.String(), "https://") && !strings.Contains(rec.Body.String(), "/mcp") {
t.Error("no address to use it at")
}
code, tools := mcpTools(h, key)
got := strings.Join(tools, " ")
if code != http.StatusOK || !strings.Contains(got, "inventory_list") || strings.Contains(got, "crm_") {
t.Errorf("writer's tools: %d %v", code, tools)
}
agent, _ := users.ByEmail(s.DB, mustAgentEmail(t, s, "Writer"))
page := as(h, oc, http.MethodGet, "/settings/agents/"+strconv.FormatInt(agent.ID, 10), nil).Body.String()
if !strings.Contains(page, key[:10]+"…") || strings.Contains(page, key) || !strings.Contains(page, "from 192.0.2.1") {
t.Errorf("agent page: %s", page)
}
// Agents aren't people: not on Users, no sign-in.
if body := as(h, oc, http.MethodGet, "/settings/users", nil).Body.String(); strings.Contains(body, "Writer") {
t.Error("an agent on the Users page")
}
// Revoking stops the key at once.
keys, _ := users.Keys(s.DB, agent.ID)
as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/revoke", url.Values{"key": {strconv.FormatInt(keys[0].ID, 10)}})
if code, _ := mcpTools(h, key); code != http.StatusUnauthorized {
t.Errorf("revoked: %d", code)
}
// A new key, then the agent turned off: no key works.
rec = as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/new-key", url.Values{})
key2 := keyRe.FindStringSubmatch(rec.Body.String())[1]
if code, _ := mcpTools(h, key2); code != http.StatusOK {
t.Errorf("new key: %d", code)
}
as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/disable", url.Values{})
if code, _ := mcpTools(h, key2); code != http.StatusUnauthorized {
t.Errorf("turned off: %d", code)
}
// Changing its scopes changes its tools.
as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/enable", url.Values{})
as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/save", url.Values{"name": {"Writer"}, "scope:seo": {"read"}})
if _, tools := mcpTools(h, key2); strings.Contains(strings.Join(tools, " "), "inventory_list") {
t.Errorf("market taken away, still offered: %v", tools)
}
// The log.
body := as(h, oc, http.MethodGet, "/settings/activity", nil).Body.String()
for _, want := range []string{"made the agent", "revoked a key of", "changed what this agent may do:"} {
if !strings.Contains(body, want) {
t.Errorf("activity lacks %q", want)
}
}
// Many wrong keys from one address: refused for a while.
for i := 0; i < users.MaxFailsPerIP; i++ {
mcpTools(h, "sm_wrong")
}
if code, _ := mcpTools(h, key2); code != http.StatusUnauthorized {
t.Errorf("after many wrong keys: %d", code)
}
}
func mustAgentEmail(t *testing.T, s *Server, name string) string {
t.Helper()
list, _ := users.Members(s.DB, users.Team)
for _, m := range list {
if m.Kind == users.Agent && m.Name == name {
return m.Email
}
}
t.Fatalf("no agent %s", name)
return ""
}
+712
View File
@@ -0,0 +1,712 @@
package web
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"supermarket/internal/audit"
"supermarket/internal/backlinks"
"supermarket/internal/content"
"supermarket/internal/inventory"
"supermarket/internal/mcpserver"
"supermarket/internal/metrics"
"supermarket/internal/outreach"
"supermarket/internal/prospects"
"supermarket/internal/seo"
"supermarket/internal/signals"
"supermarket/internal/sites"
)
// The modules' tools over MCP. Each calls what the module's pages call,
// so the rules hold for agents as for people. An agent is offered a
// module's reading tools with read, and its other tools with read and act.
// Nothing here sends anything out of Supermarket: publishing, scheduling,
// sending, pushing and mailing-list adds go through Approvals (part 3).
// AgentTools adds the module tools a caller may use.
func (s *Server) AgentTools(srv *mcp.Server, c *mcpserver.Caller) {
if c != nil && s.multi() {
ts, err := s.forTeam(c.Team)
if err != nil {
s.Log.Error("mcp: the agent's team", "team", c.Team, "err", err)
return
}
s = ts
}
may := func(module string, act bool) bool { return c == nil || c.Can(module, act) }
if may("content", false) {
s.contentReadTools(srv)
}
if may("content", true) {
s.contentActTools(srv, c)
}
if may("prospects", false) {
s.prospectsReadTools(srv)
}
if may("prospects", true) {
s.prospectsActTools(srv, c)
}
if may("seo", false) {
s.seoReadTools(srv)
}
if may("seo", true) {
s.seoActTools(srv, c)
}
if may("sites", false) {
s.sitesReadTools(srv)
}
if may("metrics", false) {
s.metricsReadTools(srv)
}
if may("market", false) {
s.marketReadTools(srv)
}
if may("market", true) {
s.marketActTools(srv, c)
}
s.approvalTools(srv, c)
}
// toolJSON is a tool's answer, as JSON text.
func toolJSON(v any) (*mcp.CallToolResult, any, error) {
raw, err := json.MarshalIndent(v, "", " ")
if err != nil {
return nil, nil, err
}
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: string(raw)}}}, nil, nil
}
// auditAgent records what an agent changed.
func (s *Server) auditAgent(c *mcpserver.Caller, action, target, detail string) {
e := audit.Entry{Kind: audit.Agent, Action: action, Target: target, Detail: detail}
if c != nil {
e.UserID, e.UserName = c.ID, c.Name
}
s.record(e)
}
func callerID(c *mcpserver.Caller) int64 {
if c == nil {
return 0
}
return c.ID
}
type none struct{}
type limitArgs struct {
Limit int `json:"limit,omitempty" jsonschema:"at most this many; default 50"`
}
func limitOf(n, def, max int) int {
if n <= 0 {
return def
}
return min(n, max)
}
// --- Content ---
type draftsArgs struct {
Status string `json:"status,omitempty" jsonschema:"waiting (in Posts, for review: the default), scheduled or published"`
Limit int `json:"limit,omitempty" jsonschema:"at most this many; default 50"`
}
type itemsArgs struct {
Entry string `json:"entry" jsonschema:"whose items: a Market entry's name, or own for the company's own products, feeds and pages"`
Limit int `json:"limit,omitempty" jsonschema:"at most this many; default 30"`
}
type draftArgs struct {
Channel string `json:"channel" jsonschema:"x, linkedin or reddit"`
Text string `json:"text" jsonschema:"the post; within the channel's limit (X: 280 characters, counting the source link as 23)"`
Title string `json:"title,omitempty" jsonschema:"Reddit only: the post's title"`
Subreddit string `json:"subreddit,omitempty" jsonschema:"Reddit only: where it goes, without r/"`
SourceURL string `json:"source_url,omitempty" jsonschema:"the link the post is about; added when publishing (on X after the text, on LinkedIn as a card, on Reddit at the end as \"Source: …\")"`
Entry string `json:"entry,omitempty" jsonschema:"the Market entry it's about, or own; empty for none"`
SignalID int64 `json:"signal_id,omitempty" jsonschema:"the buying signal it's written for (signals_list), so its links count for it"`
ItemIDs []string `json:"item_ids,omitempty" jsonschema:"the fetched items it's written from (content_items), marked as used"`
}
type editDraftArgs struct {
ID int64 `json:"id" jsonschema:"the draft's id"`
Text string `json:"text,omitempty" jsonschema:"the new text; empty keeps it"`
Title string `json:"title,omitempty" jsonschema:"Reddit only: the new title; empty keeps it"`
}
type idArgs struct {
ID int64 `json:"id" jsonschema:"its id"`
}
// draftView is a draft as agents see it.
type draftView struct {
ID int64 `json:"id"`
Channel string `json:"channel"`
Status string `json:"status"`
Title string `json:"title,omitempty"`
Subreddit string `json:"subreddit,omitempty"`
Text string `json:"text"`
SourceURL string `json:"source_url,omitempty"`
Entry string `json:"entry,omitempty"`
Length int `json:"length"`
Limit int `json:"limit"`
Problem string `json:"problem,omitempty"`
Error string `json:"error,omitempty"`
PublishAt time.Time `json:"publish_at,omitzero"`
PostURL string `json:"post_url,omitempty"`
PostedAs string `json:"posted_as,omitempty"`
}
func viewDraft(d *content.Draft) draftView {
return draftView{ID: d.ID, Channel: d.Channel, Status: d.Status, Title: d.Title, Subreddit: d.Target, Text: d.Content,
SourceURL: d.SourceURL, Entry: d.InventoryName, Length: d.Length(), Limit: d.Limit(), Problem: d.Problem(),
Error: d.Error, PublishAt: d.PublishAt, PostURL: d.PostURL, PostedAs: d.PostedAs}
}
func (s *Server) contentReadTools(srv *mcp.Server) {
mcp.AddTool(srv, &mcp.Tool{
Name: "content_drafts",
Description: "Posts: drafts waiting for review in Posts, scheduled ones, or published ones, newest first.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a draftsArgs) (*mcp.CallToolResult, any, error) {
statuses := []string{content.StatusDraft, content.StatusFailed}
switch a.Status {
case "", "waiting":
case "scheduled":
statuses = []string{content.StatusScheduled}
case "published":
statuses = []string{content.StatusPublished}
default:
return nil, nil, fmt.Errorf("no status %q: waiting, scheduled or published", a.Status)
}
list, err := content.ListDrafts(s.DB, limitOf(a.Limit, 50, 200), statuses...)
if err != nil {
return nil, nil, err
}
out := []draftView{}
for i := range list {
out = append(out, viewDraft(&list[i]))
}
return toolJSON(out)
})
mcp.AddTool(srv, &mcp.Tool{
Name: "content_items",
Description: "Fetched items to write posts from: a Market entry's recent posts, videos and articles, or (entry: own) the company's own products, feeds and pages. Dismissed ones are left out.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a itemsArgs) (*mcp.CallToolResult, any, error) {
name := strings.TrimSpace(a.Entry)
if strings.EqualFold(name, "own") {
name = content.OwnName
}
if name == "" {
return nil, nil, errors.New("give the entry: a Market entry's name, or own")
}
items, err := content.ListItems(s.DB, name, false, limitOf(a.Limit, 30, 200))
if err != nil {
return nil, nil, err
}
if items == nil {
items = []content.Item{}
}
return toolJSON(items)
})
}
func (s *Server) contentActTools(srv *mcp.Server, c *mcpserver.Caller) {
mcp.AddTool(srv, &mcp.Tool{
Name: "content_create_draft",
Description: "Write a post as a draft, waiting in Posts for review. Write it in the company's voice (profile_get). " +
"It isn't published: a person (or, later, an approval) does that.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a draftArgs) (*mcp.CallToolResult, any, error) {
ch, ok := content.ChannelByID(strings.ToLower(strings.TrimSpace(a.Channel)))
if !ok {
return nil, nil, fmt.Errorf("no channel %q: x, linkedin or reddit", a.Channel)
}
if strings.TrimSpace(a.Text) == "" {
return nil, nil, errors.New("the post is empty")
}
dr := content.Draft{Channel: ch.ID, Content: a.Text, SourceURL: strings.TrimSpace(a.SourceURL), ItemIDs: a.ItemIDs,
Kind: content.KindProduct, WrittenBy: callerID(c)} // about the company, unless an entry is given
if ch.ID == content.ChannelReddit {
dr.Title, dr.Target = strings.TrimSpace(a.Title), strings.TrimPrefix(strings.TrimSpace(a.Subreddit), "r/")
if dr.Title == "" || dr.Target == "" {
return nil, nil, errors.New("a Reddit post needs a title and a subreddit")
}
}
if e := strings.TrimSpace(a.Entry); strings.EqualFold(e, "own") {
dr.InventoryName, dr.Kind = content.OwnName, content.KindProduct
} else if e != "" {
entries, err := inventory.List(s.DB, "")
if err != nil {
return nil, nil, err
}
found := false
for _, en := range entries {
if strings.EqualFold(en.Name, e) {
dr.InventoryName, dr.Kind, found = en.Name, en.Relationship, true
}
}
if !found {
return nil, nil, fmt.Errorf("no Market entry %q", e)
}
}
if a.SignalID != 0 {
if _, err := signals.Get(s.DB, a.SignalID); err != nil {
return nil, nil, fmt.Errorf("no signal %d", a.SignalID)
}
dr.SignalID = a.SignalID
}
batch, err := content.CreateDrafts(s.DB, []content.Draft{dr})
if err != nil {
return nil, nil, err
}
list, err := content.ListDrafts(s.DB, 20, content.StatusDraft)
if err != nil {
return nil, nil, err
}
for i := range list {
if list[i].Batch == batch {
s.auditAgent(c, "wrote-draft", ch.Name, fmt.Sprintf("draft %d", list[i].ID))
return toolJSON(viewDraft(&list[i]))
}
}
return nil, nil, errors.New("the draft was written, but couldn't be read back")
})
mcp.AddTool(srv, &mcp.Tool{
Name: "content_edit_draft",
Description: "Change a draft waiting in Posts: its text, and a Reddit draft's title.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a editDraftArgs) (*mcp.CallToolResult, any, error) {
if strings.TrimSpace(a.Text) != "" {
if err := content.UpdateDraft(s.DB, a.ID, a.Text); err != nil {
return nil, nil, err
}
}
if strings.TrimSpace(a.Title) != "" {
if err := content.UpdateTitle(s.DB, a.ID, a.Title); err != nil {
return nil, nil, err
}
}
d, err := content.GetDraft(s.DB, a.ID)
if err != nil {
return nil, nil, err
}
s.auditAgent(c, "edited-draft", d.ChannelName(), fmt.Sprintf("draft %d", d.ID))
return toolJSON(viewDraft(d))
})
mcp.AddTool(srv, &mcp.Tool{
Name: "content_discard_draft",
Description: "Drop a draft waiting in Posts.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a idArgs) (*mcp.CallToolResult, any, error) {
if err := content.DiscardDraft(s.DB, a.ID); err != nil {
return nil, nil, err
}
s.auditAgent(c, "deleted", fmt.Sprintf("draft %d", a.ID), "")
return toolJSON(map[string]string{"status": "discarded"})
})
}
// --- Prospects ---
type reviewArgs struct {
Status string `json:"status,omitempty" jsonschema:"new (waiting for review: the default), accepted or rejected"`
SignalID int64 `json:"signal_id,omitempty" jsonschema:"only those tagged with this signal"`
Limit int `json:"limit,omitempty" jsonschema:"at most this many; default 50"`
}
type outreachArgs struct {
Tab string `json:"tab,omitempty" jsonschema:"drafts (the default), queued, sent, replied or failed"`
Limit int `json:"limit,omitempty" jsonschema:"at most this many; default 50"`
}
type outreachDraftArgs struct {
ContactID int64 `json:"contact_id" jsonschema:"the person, from prospects_review"`
Channel string `json:"channel,omitempty" jsonschema:"email (the default) or linkedin"`
}
type outreachEditArgs struct {
ID int64 `json:"id" jsonschema:"the outreach draft's id"`
Subject string `json:"subject,omitempty" jsonschema:"the new subject; empty keeps it"`
Body string `json:"body,omitempty" jsonschema:"the new text; empty keeps it"`
}
type suppressArgs struct {
Value string `json:"value" jsonschema:"an email address, or a domain such as example.com"`
Reason string `json:"reason,omitempty" jsonschema:"why, in a few words (they asked us to stop, a competitor…)"`
}
func (s *Server) prospectsReadTools(srv *mcp.Server) {
mcp.AddTool(srv, &mcp.Tool{
Name: "signals_list",
Description: "The buying signals being tested, with each one's funnel over the last 90 days: reached, replied, visited, booked, signed up, paid.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) {
list, err := signals.List(s.DB)
if err != nil {
return nil, nil, err
}
rows, err := signals.Scorecard(s.DB, signals.Filter{Since: time.Now().AddDate(0, 0, -90)})
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]any{"signals": nonNilList(list), "scorecard": nonNilList(rows)})
})
mcp.AddTool(srv, &mcp.Tool{
Name: "prospects_review",
Description: "Companies and people found as prospects, by status: new ones wait for a person to accept (for the CRM) or set aside.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a reviewArgs) (*mcp.CallToolResult, any, error) {
status := a.Status
if status == "" {
status = prospects.StatusNew
}
cs, ps, err := prospects.Review(s.DB, status, a.SignalID, limitOf(a.Limit, 50, 500))
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]any{"companies": nonNilList(cs), "people": nonNilList(ps)})
})
mcp.AddTool(srv, &mcp.Tool{
Name: "outreach_list",
Description: "Outreach messages: drafts, queued to send, sent, replied (with the replies) or failed.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a outreachArgs) (*mcp.CallToolResult, any, error) {
tab := a.Tab
if tab == "" {
tab = "drafts"
}
list, err := outreach.List(s.DB, tab, limitOf(a.Limit, 50, 200))
if err != nil {
return nil, nil, err
}
return toolJSON(nonNilList(list))
})
mcp.AddTool(srv, &mcp.Tool{
Name: "suppression_list",
Description: "Emails and domains never to contact or add: checked before anything is drafted, queued or sent.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) {
list, err := prospects.Suppressions(s.DB)
if err != nil {
return nil, nil, err
}
return toolJSON(nonNilList(list))
})
}
func (s *Server) prospectsActTools(srv *mcp.Server, c *mcpserver.Caller) {
mcp.AddTool(srv, &mcp.Tool{
Name: "outreach_draft",
Description: "Have Supermarket's AI write a first message to a prospect, as on the Outreach page, from the company's profile and the person's signal. " +
"It waits in Outreach → Drafts; sending is a person's.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a outreachDraftArgs) (*mcp.CallToolResult, any, error) {
channel := a.Channel
if channel == "" {
channel = outreach.ChannelEmail
}
if channel != outreach.ChannelEmail && channel != outreach.ChannelLinkedIn {
return nil, nil, fmt.Errorf("no channel %q: email or linkedin", a.Channel)
}
cl, p, err := s.draftClient()
if err != nil {
return nil, nil, err
}
set, _ := s.outreachSettings()
dctx, cancel := context.WithTimeout(ctx, 3*time.Minute)
defer cancel()
m, err := outreach.Draft(dctx, s.DB, cl, p, set, a.ContactID, channel, time.Now())
if err != nil {
return nil, nil, err
}
_ = outreach.SetCreatedBy(s.DB, m.ID, callerID(c))
s.auditAgent(c, "wrote-draft", "outreach to "+m.To, fmt.Sprintf("message %d", m.ID))
return toolJSON(m)
})
mcp.AddTool(srv, &mcp.Tool{
Name: "outreach_edit",
Description: "Change an outreach draft's subject or text.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a outreachEditArgs) (*mcp.CallToolResult, any, error) {
m, err := outreach.Get(s.DB, a.ID)
if err != nil {
return nil, nil, err
}
subject, body := m.Subject, m.Body
if strings.TrimSpace(a.Subject) != "" {
subject = a.Subject
}
if strings.TrimSpace(a.Body) != "" {
body = a.Body
}
if err := outreach.Edit(s.DB, a.ID, subject, body); err != nil {
return nil, nil, err
}
s.auditAgent(c, "edited-draft", "outreach to "+m.To, fmt.Sprintf("message %d", m.ID))
m, err = outreach.Get(s.DB, a.ID)
if err != nil {
return nil, nil, err
}
return toolJSON(m)
})
mcp.AddTool(srv, &mcp.Tool{
Name: "suppress",
Description: "Add an email address or a domain to the suppression list: no one there is drafted, queued, sent to or added to the CRM.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a suppressArgs) (*mcp.CallToolResult, any, error) {
v := strings.ToLower(strings.TrimSpace(a.Value))
kind := "domain"
if strings.Contains(v, "@") {
kind = "email"
}
if v == "" {
return nil, nil, errors.New("give an email address or a domain")
}
if err := prospects.Suppress(s.DB, kind, v, a.Reason, time.Now()); err != nil {
return nil, nil, err
}
s.auditAgent(c, "suppressed", v, a.Reason)
return toolJSON(map[string]string{"status": "suppressed", "kind": kind, "value": v})
})
}
// --- SEO ---
type siteArgs struct {
Site int `json:"site,omitempty" jsonschema:"which website, by its number in seo_sites; 0 for the first"`
}
type changeEditArgs struct {
ID int64 `json:"id" jsonschema:"the proposed change's id, from seo_changes"`
Title string `json:"title" jsonschema:"the page title it proposes"`
Description string `json:"description" jsonschema:"the meta description it proposes"`
}
// seoSiteAt is a website by its number.
func (s *Server) seoSiteAt(i int) (*seoSite, error) {
for _, st := range s.seoSites() {
if st.Index == i {
return &st, nil
}
}
return nil, fmt.Errorf("no website %d: seo_sites lists them", i)
}
func (s *Server) seoReadTools(srv *mcp.Server) {
mcp.AddTool(srv, &mcp.Tool{
Name: "seo_sites",
Description: "The company's websites, by number, with their Search Console property and when it was last synced.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) {
return toolJSON(nonNilList(s.seoSites()))
})
mcp.AddTool(srv, &mcp.Tool{
Name: "seo_morning_check",
Description: "The morning check: this week against last, from Search Console: the pages and searches that really moved, clicks by day, gains and losses.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a siteArgs) (*mcp.CallToolResult, any, error) {
st, err := s.seoSiteAt(a.Site)
if err != nil {
return nil, nil, err
}
if st.Property == "" {
return nil, nil, errors.New("this website has no Search Console property yet")
}
ch, err := seo.MorningCheck(s.DB, s.scope(*st), seo.LoadSettings(s.DB))
if err != nil {
return nil, nil, err
}
if ch == nil {
return toolJSON(map[string]string{"status": "There isn't two weeks of Search Console data yet."})
}
return toolJSON(ch)
})
mcp.AddTool(srv, &mcp.Tool{
Name: "seo_next",
Description: "What to write next: pages, sections and posts worth making, from what converts, what's stalled, signals without pages and apps people mention, " +
"best first, each with why (the numbers behind it).",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a siteArgs) (*mcp.CallToolResult, any, error) {
st, err := s.seoSiteAt(a.Site)
if err != nil {
return nil, nil, err
}
list, more, err := s.nextFor(*st, time.Now())
if err != nil {
return nil, nil, err
}
type item struct {
Key, Kind, Title, Why string
Score float64
}
out := []item{}
for _, sg := range list {
out = append(out, item{sg.Key, sg.Kind, sg.Title, sg.Why, sg.Score})
}
return toolJSON(map[string]any{"suggestions": out, "more": more})
})
mcp.AddTool(srv, &mcp.Tool{
Name: "seo_links",
Description: "Links to the website: the ones known (and whether they still link), and the places worth asking for one.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a siteArgs) (*mcp.CallToolResult, any, error) {
st, err := s.seoSiteAt(a.Site)
if err != nil {
return nil, nil, err
}
links, err := backlinks.Links(s.DB, st.URL)
if err != nil {
return nil, nil, err
}
return toolJSON(nonNilList(links))
})
mcp.AddTool(srv, &mcp.Tool{
Name: "seo_changes",
Description: "Changes to pages' titles and descriptions: proposed ones waiting for a person's yes, and those made, with what they did to clicks.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a siteArgs) (*mcp.CallToolResult, any, error) {
st, err := s.seoSiteAt(a.Site)
if err != nil {
return nil, nil, err
}
list, err := seo.Changes(s.DB, auditKey(*st), 100)
if err != nil {
return nil, nil, err
}
return toolJSON(nonNilList(list))
})
}
func (s *Server) seoActTools(srv *mcp.Server, c *mcpserver.Caller) {
mcp.AddTool(srv, &mcp.Tool{
Name: "seo_edit_change",
Description: "Rewrite a proposed change's title and description, before a person says yes to it. " +
"Saying yes (which opens the pull request) is a person's.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a changeEditArgs) (*mcp.CallToolResult, any, error) {
if err := seo.EditChange(s.DB, a.ID, a.Title, a.Description); err != nil {
return nil, nil, err
}
ch, err := seo.GetChange(s.DB, a.ID)
if err != nil {
return nil, nil, err
}
s.auditAgent(c, "edited-change", ch.Page, "")
return toolJSON(ch)
})
}
// --- Sites ---
func (s *Server) sitesReadTools(srv *mcp.Server) {
mcp.AddTool(srv, &mcp.Tool{
Name: "sites_list",
Description: "The company's websites and the Gitea repository each is built from.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) {
return toolJSON(nonNilList(s.siteRepos()))
})
mcp.AddTool(srv, &mcp.Tool{
Name: "sites_new_pages",
Description: "New pages being made for a website: their kind, signal, sections, and whether they're previewed or in a pull request.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a siteArgs) (*mcp.CallToolResult, any, error) {
for _, st := range s.siteRepos() {
if st.Index == a.Site {
ps, err := sites.Pages(s.DB, st.URL)
if err != nil {
return nil, nil, err
}
return toolJSON(nonNilList(ps))
}
}
return nil, nil, fmt.Errorf("no website %d: sites_list lists them", a.Site)
})
}
// --- Metrics ---
func (s *Server) metricsReadTools(srv *mcp.Server) {
mcp.AddTool(srv, &mcp.Tool{
Name: "metrics_months",
Description: "MRR, customers, new, expansion, contraction, churn and NRR month by month (the last 13), from Stripe.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) {
m, err := metrics.Build(s.DB, time.Now())
if err != nil {
return nil, nil, err
}
months := m.Months
if len(months) > 13 {
months = months[len(months)-13:]
}
return toolJSON(map[string]any{"currency": m.Currency, "months": nonNilList(months)})
})
}
// --- The Market ---
type marketEntry struct {
ID int64 `json:"id"`
inventory.Entry
}
type marketGetArgs struct {
ID int64 `json:"id" jsonschema:"the entry's id, from market_list"`
}
type marketSaveArgs struct {
inventory.Entry
}
func (s *Server) marketReadTools(srv *mcp.Server) {
mcp.AddTool(srv, &mcp.Tool{
Name: "market_list",
Description: "The Market's entries with their ids: partners, competitors and projects watched, with accounts, keywords, talking points and prices.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) {
list, err := inventory.List(s.DB, "")
if err != nil {
return nil, nil, err
}
out := []marketEntry{}
for _, e := range list {
out = append(out, marketEntry{e.ID, e})
}
return toolJSON(out)
})
mcp.AddTool(srv, &mcp.Tool{
Name: "market_get",
Description: "One Market entry, by id.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a marketGetArgs) (*mcp.CallToolResult, any, error) {
e, err := inventory.Get(s.DB, a.ID)
if err != nil {
return nil, nil, err
}
return toolJSON(marketEntry{e.ID, *e})
})
}
func (s *Server) marketActTools(srv *mcp.Server, c *mcpserver.Caller) {
mcp.AddTool(srv, &mcp.Tool{
Name: "market_save",
Description: "Add a Market entry, or change the one with the same name (every field is replaced: read it first with market_get). " +
"relationship is partner, competitor or watch.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a marketSaveArgs) (*mcp.CallToolResult, any, error) {
e := a.Entry
list, err := inventory.List(s.DB, "")
if err != nil {
return nil, nil, err
}
action := "added"
for _, old := range list {
if strings.EqualFold(old.Name, strings.TrimSpace(e.Name)) {
e.ID, action = old.ID, "changed"
}
}
if action == "added" {
if err := s.limitSources(len(list)); err != nil {
return nil, nil, err
}
}
if err := inventory.Save(s.DB, &e); err != nil {
return nil, nil, err
}
s.auditAgent(c, "market-"+action, e.Name, "")
return toolJSON(marketEntry{e.ID, e})
})
}
// nonNilList keeps an empty list a list in JSON ([] rather than null).
func nonNilList[T any](v []T) []T {
if v == nil {
return []T{}
}
return v
}
+164
View File
@@ -0,0 +1,164 @@
package web
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"testing"
"time"
"supermarket/internal/audit"
"supermarket/internal/content"
"supermarket/internal/profile"
"supermarket/internal/users"
)
// mcpCall calls a tool with a key: its text, and whether it was an error.
func mcpCall(t *testing.T, h http.Handler, key, tool string, args map[string]any) (string, bool) {
t.Helper()
raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 2, "method": "tools/call",
"params": map[string]any{"name": tool, "arguments": args}})
rec := do(h, http.MethodPost, "/mcp", bytes.NewReader(raw), map[string]string{
"Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Authorization": "Bearer " + key})
if rec.Code != http.StatusOK {
t.Fatalf("%s: %d %s", tool, rec.Code, rec.Body.String())
}
var out struct {
Result struct {
Content []struct{ Text string } `json:"content"`
IsError bool `json:"isError"`
} `json:"result"`
Error *struct{ Message string } `json:"error"`
}
json.Unmarshal(rec.Body.Bytes(), &out)
if out.Error != nil {
return out.Error.Message, true
}
text := ""
if len(out.Result.Content) > 0 {
text = out.Result.Content[0].Text
}
return text, out.Result.IsError
}
// newAgent makes an agent with scopes and returns its key.
func newAgent(t *testing.T, s *Server, name string, scopes map[string]users.Access) (*users.User, string) {
t.Helper()
u, err := users.CreateAgent(s.DB, name, "", time.Now())
if err != nil {
t.Fatal(err)
}
if err := users.Join(s.DB, users.Team, u.ID, users.Member, scopes, time.Now()); err != nil {
t.Fatal(err)
}
key, _, err := users.NewKey(s.DB, u.ID, time.Time{}, time.Now())
if err != nil {
t.Fatal(err)
}
return u, key
}
func TestAgentModuleTools(t *testing.T) {
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}})
writer, key := newAgent(t, s, "Morning writer", map[string]users.Access{"content": users.Edit, "seo": users.View})
_, tools := mcpTools(h, key)
got := " " + strings.Join(tools, " ") + " "
for _, want := range []string{"profile_get", "content_drafts", "content_items", "content_create_draft", "content_edit_draft",
"seo_sites", "seo_morning_check", "seo_next", "seo_links", "seo_changes"} {
if !strings.Contains(got, " "+want+" ") {
t.Errorf("missing %s: %v", want, tools)
}
}
for _, not := range []string{"seo_edit_change", "crm_pending_actions", "market_save", "market_list", "outreach_list", "metrics_months", "sites_list"} {
if strings.Contains(got, " "+not+" ") {
t.Errorf("offered %s", not)
}
}
// Reading SEO works (no Search Console yet: it says so).
if text, isErr := mcpCall(t, h, key, "seo_morning_check", map[string]any{"site": 0}); !isErr || !strings.Contains(text, "Search Console") {
t.Errorf("morning check: %v %s", isErr, text)
}
if text, isErr := mcpCall(t, h, key, "seo_next", map[string]any{}); isErr || !strings.Contains(text, `"suggestions"`) {
t.Errorf("next: %v %s", isErr, text)
}
// A tool it isn't offered fails.
if _, isErr := mcpCall(t, h, key, "seo_edit_change", map[string]any{"id": 1, "title": "x", "description": "y"}); !isErr {
t.Error("called a tool it doesn't have")
}
// It writes a draft: it waits in Posts, by the agent.
text, isErr := mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Widgets, now faster.", "source_url": "https://acme.example/new"})
if isErr {
t.Fatalf("create: %s", text)
}
var d draftView
json.Unmarshal([]byte(text), &d)
if d.ID == 0 || d.Status != content.StatusDraft || d.Limit != 280 {
t.Errorf("draft %+v", d)
}
saved, _ := content.GetDraft(s.DB, d.ID)
if saved.WrittenBy != writer.ID {
t.Errorf("written by %d", saved.WrittenBy)
}
if body := do(h, http.MethodGet, "/posts", nil, nil).Body.String(); !strings.Contains(body, "by Morning writer") {
t.Error("Posts doesn't say which agent wrote it")
}
if _, isErr := mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "reddit", "text": "x"}); !isErr {
t.Error("a Reddit draft without a title")
}
if _, isErr := mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "myspace", "text": "x"}); !isErr {
t.Error("an unknown channel")
}
text, _ = mcpCall(t, h, key, "content_edit_draft", map[string]any{"id": d.ID, "text": "Widgets, faster than ever."})
if !strings.Contains(text, "faster than ever") {
t.Errorf("edit: %s", text)
}
text, _ = mcpCall(t, h, key, "content_drafts", map[string]any{})
if !strings.Contains(text, "faster than ever") {
t.Errorf("list: %s", text)
}
// What it did is in the log, as an agent.
entries, _ := audit.List(s.DB, audit.Filter{UserID: writer.ID}, 10)
if len(entries) != 2 || entries[0].Kind != audit.Agent || entries[1].Action != "wrote-draft" {
t.Errorf("log: %+v", entries)
}
}
func TestAgentMarketAndProspectsTools(t *testing.T) {
s, h := newTestServer(t, nil)
_, key := newAgent(t, s, "Researcher", map[string]users.Access{"market": users.Edit, "prospects": users.View, "metrics": users.View})
_, tools := mcpTools(h, key)
got := " " + strings.Join(tools, " ") + " "
for _, want := range []string{"market_list", "market_save", "signals_list", "prospects_review", "outreach_list", "suppression_list", "metrics_months"} {
if !strings.Contains(got, " "+want+" ") {
t.Errorf("missing %s", want)
}
}
for _, not := range []string{"outreach_draft", "suppress", "content_create_draft"} {
if strings.Contains(got, " "+not+" ") {
t.Errorf("offered %s", not)
}
}
text, isErr := mcpCall(t, h, key, "market_save", map[string]any{"name": "Rival", "relationship": "competitor", "description": "They sell widgets too."})
if isErr || !strings.Contains(text, `"id":`) {
t.Fatalf("save: %s", text)
}
// The same name again changes it, not a second entry.
mcpCall(t, h, key, "market_save", map[string]any{"name": "rival", "relationship": "competitor", "description": "Cheaper widgets."})
text, _ = mcpCall(t, h, key, "market_list", map[string]any{})
if strings.Count(text, `"name"`) != 1 || !strings.Contains(text, "Cheaper widgets.") {
t.Errorf("list: %s", text)
}
if _, isErr := mcpCall(t, h, key, "market_save", map[string]any{"name": "X", "relationship": "friend"}); !isErr {
t.Error("bad relationship accepted")
}
for _, tool := range []string{"signals_list", "prospects_review", "outreach_list", "suppression_list", "metrics_months"} {
if text, isErr := mcpCall(t, h, key, tool, map[string]any{}); isErr {
t.Errorf("%s: %s", tool, text)
}
}
}
+213
View File
@@ -0,0 +1,213 @@
package web
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"sort"
"strings"
"sync"
"github.com/modelcontextprotocol/go-sdk/mcp"
"supermarket/internal/mcpserver"
)
// The JSON API, for scripts that aren't MCP clients: /api/v1. It's the MCP
// tools as plain HTTP, with the same keys, scopes, limits, logging and
// approvals, because each call is handed to the agent's MCP server:
//
// GET /api/v1/tools what this key may call, with each one's input schema
// POST /api/v1/<tool> call it: the arguments as a JSON object; the answer as JSON
// GET /api/v1/docs every tool, documented (no key needed)
const apiMaxBody = 1 << 20
// apiError writes {"error": msg}.
func apiError(w http.ResponseWriter, code int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(map[string]string{"error": msg})
}
// rpc hands one JSON-RPC call to /mcp, with the request's key, and returns
// the HTTP status and the JSON-RPC response.
func (s *Server) rpc(r *http.Request, method string, params any) (int, *rpcResponse, string) {
body, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
req := httptest.NewRequestWithContext(r.Context(), http.MethodPost, "/mcp", bytes.NewReader(body))
req.RemoteAddr = r.RemoteAddr
for _, h := range []string{"Authorization", "X-Forwarded-For"} {
if v := r.Header.Get(h); v != "" {
req.Header.Set(h, v)
}
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
rec := httptest.NewRecorder()
s.MCP.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
return rec.Code, nil, strings.TrimSpace(rec.Body.String())
}
var out rpcResponse
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
return http.StatusBadGateway, nil, "unreadable answer"
}
return http.StatusOK, &out, ""
}
type rpcResponse struct {
Result json.RawMessage `json:"result"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
// apiTools lists what the key may call.
func (s *Server) apiTools(w http.ResponseWriter, r *http.Request) {
code, res, msg := s.rpc(r, "tools/list", map[string]any{})
if res == nil {
apiError(w, code, msg)
return
}
var list struct {
Tools []struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema any `json:"inputSchema"`
} `json:"tools"`
}
if res.Error != nil {
apiError(w, http.StatusBadRequest, res.Error.Message)
return
}
_ = json.Unmarshal(res.Result, &list)
type tool struct {
Name string `json:"name"`
Description string `json:"description"`
Call string `json:"call"`
Input any `json:"input_schema"`
}
out := []tool{}
for _, t := range list.Tools {
out = append(out, tool{t.Name, t.Description, "POST /api/v1/" + t.Name, t.InputSchema})
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"tools": out})
}
// apiCall calls one tool.
func (s *Server) apiCall(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("tool")
args := map[string]any{}
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, apiMaxBody))
if err != nil {
apiError(w, http.StatusRequestEntityTooLarge, "the body is over 1 MB")
return
}
if len(bytes.TrimSpace(raw)) > 0 {
if err := json.Unmarshal(raw, &args); err != nil {
apiError(w, http.StatusBadRequest, "the body must be a JSON object of the tool's arguments")
return
}
}
code, res, msg := s.rpc(r, "tools/call", map[string]any{"name": name, "arguments": args})
if res == nil {
apiError(w, code, msg)
return
}
if res.Error != nil {
// An unknown tool, or one this key isn't given; or arguments that
// don't fit its schema; or a limit.
status := http.StatusBadRequest
switch {
case strings.Contains(res.Error.Message, "unknown tool"):
status = http.StatusNotFound
case strings.Contains(res.Error.Message, "too many calls"):
status = http.StatusTooManyRequests
case strings.Contains(res.Error.Message, "paused"):
status = http.StatusForbidden
}
apiError(w, status, res.Error.Message)
return
}
var result struct {
Content []struct {
Text string `json:"text"`
} `json:"content"`
IsError bool `json:"isError"`
}
_ = json.Unmarshal(res.Result, &result)
text := ""
if len(result.Content) > 0 {
text = result.Content[0].Text
}
if result.IsError {
apiError(w, http.StatusUnprocessableEntity, text)
return
}
w.Header().Set("Content-Type", "application/json")
if json.Valid([]byte(text)) {
_, _ = w.Write([]byte(text))
return
}
_ = json.NewEncoder(w).Encode(map[string]string{"result": text})
}
// The documentation: every tool, from the tools themselves.
var (
apiDocsOnce sync.Once
apiDocsTools []*mcp.Tool
apiDocsErr error
)
type apiDoc struct {
Name, Description, Scope, Schema string
}
// toolScope says which scope offers a tool, for the docs.
func toolScope(name string) string {
switch {
case name == "profile_get" || name == "approvals_status":
return "every agent"
case strings.HasPrefix(name, "crm_") || name == "bridge_checkin":
return "CRM through the Core"
case name == "inventory_list" || strings.HasPrefix(name, "market_"):
return "Market"
case strings.HasPrefix(name, "content_") || name == "posting_accounts":
return "Content"
case strings.HasPrefix(name, "seo_"):
return "SEO"
case strings.HasPrefix(name, "sites_"):
return "Sites"
case strings.HasPrefix(name, "metrics_"):
return "Metrics"
}
return "Prospects"
}
func (s *Server) apiDocs(w http.ResponseWriter, r *http.Request) {
apiDocsOnce.Do(func() {
apiDocsTools, apiDocsErr = mcpserver.AllTools(r.Context(), s.DB, s.Version, s.AgentTools)
})
if apiDocsErr != nil {
s.serverError(w, apiDocsErr)
return
}
var docs []apiDoc
for _, t := range apiDocsTools {
schema, _ := json.MarshalIndent(t.InputSchema, "", " ")
docs = append(docs, apiDoc{t.Name, t.Description, toolScope(t.Name), string(schema)})
}
sort.SliceStable(docs, func(i, j int) bool {
if docs[i].Scope != docs[j].Scope {
return docs[i].Scope < docs[j].Scope
}
return docs[i].Name < docs[j].Name
})
s.render(w, r, "api-docs", page{Title: "API", Bare: true, Data: map[string]any{
"Docs": docs, "Base": s.PublicURL + "/api/v1", "MCP": s.mcpURL()}})
}
+89
View File
@@ -0,0 +1,89 @@
package web
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"testing"
"time"
"supermarket/internal/users"
)
func apiDo(h http.Handler, method, path, key, body string) (int, map[string]any) {
var rd *bytes.Reader
if body != "" {
rd = bytes.NewReader([]byte(body))
} else {
rd = bytes.NewReader(nil)
}
hdr := map[string]string{"Content-Type": "application/json", csrfHeader: ""}
if key != "" {
hdr["Authorization"] = "Bearer " + key
}
rec := do(h, method, path, rd, hdr)
var out map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
var list []any
if json.Unmarshal(rec.Body.Bytes(), &list) == nil {
out = map[string]any{"list": list}
}
}
return rec.Code, out
}
func TestJSONAPI(t *testing.T) {
s, h := newTestServer(t, nil)
agent, key := newAgent(t, s, "Script", map[string]users.Access{"content": users.Edit, "market": users.View})
// Without a key, or a wrong one: 401. No form token needed.
if code, _ := apiDo(h, http.MethodGet, "/api/v1/tools", "", ""); code != http.StatusUnauthorized {
t.Errorf("no key: %d", code)
}
if code, _ := apiDo(h, http.MethodPost, "/api/v1/content_drafts", "sm_wrong", "{}"); code != http.StatusUnauthorized {
t.Errorf("wrong key: %d", code)
}
code, out := apiDo(h, http.MethodGet, "/api/v1/tools", key, "")
raw, _ := json.Marshal(out)
if code != http.StatusOK || !strings.Contains(string(raw), `"name":"content_create_draft"`) || strings.Contains(string(raw), "seo_next") ||
!strings.Contains(string(raw), `"input_schema"`) {
t.Fatalf("tools: %d %s", code, raw)
}
// A call, its JSON answer.
code, out = apiDo(h, http.MethodPost, "/api/v1/content_create_draft", key, `{"channel": "x", "text": "From a script."}`)
if code != http.StatusOK || out["status"] != "draft" || out["text"] != "From a script." {
t.Fatalf("create: %d %v", code, out)
}
code, out = apiDo(h, http.MethodPost, "/api/v1/content_drafts", key, "")
if code != http.StatusOK || len(out["list"].([]any)) != 1 {
t.Errorf("list: %d %v", code, out)
}
// Errors.
if code, out := apiDo(h, http.MethodPost, "/api/v1/content_create_draft", key, `{"channel": "myspace", "text": "x"}`); code != http.StatusUnprocessableEntity || out["error"] == nil {
t.Errorf("tool says no: %d %v", code, out)
}
if code, _ := apiDo(h, http.MethodPost, "/api/v1/seo_next", key, `{}`); code != http.StatusNotFound {
t.Errorf("not given: %d", code)
}
if code, _ := apiDo(h, http.MethodPost, "/api/v1/content_drafts", key, `[1, 2]`); code != http.StatusBadRequest {
t.Errorf("not an object: %d", code)
}
// The same limits and log as MCP.
if calls, _ := users.RecentCalls(s.DB, agent.ID, 10); len(calls) < 3 || calls[len(calls)-1].Tool != "content_create_draft" {
t.Errorf("calls %+v", calls)
}
users.Pause(s.DB, agent.ID, true, 0, time.Now())
if code, _ := apiDo(h, http.MethodPost, "/api/v1/content_drafts", key, ""); code != http.StatusForbidden {
t.Errorf("paused: %d", code)
}
// The docs: every tool, no key.
rec := do(h, http.MethodGet, "/api/v1/docs", nil, nil)
body := rec.Body.String()
for _, want := range []string{`id="content_publish"`, `id="seo_morning_check"`, `id="crm_pending_actions"`, `id="metrics_months"`, "Authorization: Bearer"} {
if !strings.Contains(body, want) {
t.Errorf("docs lack %s", want)
}
}
}
+694
View File
@@ -0,0 +1,694 @@
package web
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"supermarket/internal/approvals"
"supermarket/internal/content"
"supermarket/internal/mcpserver"
"supermarket/internal/outreach"
"supermarket/internal/posting"
"supermarket/internal/prospects"
"supermarket/internal/seo"
"supermarket/internal/users"
)
// Approvals. Anything an agent asks to send out of Supermarket waits here
// for a person: members with edit on its module, or admins. They can edit
// it first, approve or refuse it, and let the agent take that class of
// action on its own from then on, with a cap per day. Agents read untrusted
// text (signals, replies, search results), so nothing goes out on an
// agent's word alone until a person has said this kind may.
// The classes of action.
const (
classEmailFirst = "email-first" // a first email to a prospect
classEmailReply = "email-reply" // a reply in an existing conversation
)
func classPost(account int64) string { return "post:" + strconv.FormatInt(account, 10) }
func classList(list string) string { return "list:" + list }
func classSEO(site string) string { return "seo-change:" + site }
func classKind(class string) string { k, _, _ := strings.Cut(class, ":"); return k }
func classParam(class string) string { _, p, _ := strings.Cut(class, ":"); return p }
func classModule(class string) string {
switch classKind(class) {
case "post":
return "content"
case "seo-change":
return "seo"
}
return "prospects"
}
// classLabel says what a class lets an agent do.
func (s *Server) classLabel(class string) string {
switch classKind(class) {
case "post":
id, _ := strconv.ParseInt(classParam(class), 10, 64)
if a, err := posting.Get(s.DB, id); err == nil {
return "publish posts to " + a.Label()
}
return "publish posts to an account since signed out"
case classEmailFirst:
return "send a first email to a prospect"
case classEmailReply:
return "send a reply in an existing conversation"
case "list":
return "add people to the mailing list " + classParam(class)
case "seo-change":
return "apply SEO changes to " + classParam(class)
}
return class
}
// agentViewer is an agent as a viewer: for the checks people get too
// (posting to an account).
func (s *Server) agentViewer(id int64) *viewer {
u, err := users.ByID(s.DB, id)
if err != nil || u.Status != users.Active {
return &viewer{}
}
m, err := users.MembershipOf(s.DB, s.team(), id)
if err != nil {
return &viewer{}
}
return &viewer{User: u, Member: m}
}
// ask is how an agent's request to send something out starts: done at
// once if the agent may do this on its own (within its cap), else waiting
// for a person. It returns what to tell the agent.
func (s *Server) ask(ctx context.Context, c *mcpserver.Caller, r *approvals.Request) (string, error) {
r.Agent, r.Module = callerID(c), classModule(r.Class)
if p, err := approvals.Pending(s.DB, r.Class, r.Target); err != nil {
return "", err
} else if p != nil {
return fmt.Sprintf("Already waiting for approval (request %d): nothing more to do; approvals_status says when it's decided.", p.ID), nil
}
now := time.Now()
// The cap per day on what an agent asks to send out, approved or not.
lim, err := users.LimitsOf(s.DB, r.Agent)
if err != nil {
return "", err
}
if n, err := approvals.AskedSince(s.DB, r.Agent, now.Add(-24*time.Hour)); err != nil {
return "", err
} else if n >= lim.OutPerDay {
return "", fmt.Errorf("this agent may ask to send out %d things a day, and has: try again tomorrow, or ask an admin to raise its limit", lim.OutPerDay)
}
ok, err := approvals.Allowed(s.DB, r.Agent, r.Class, now)
if err != nil {
return "", err
}
if !ok {
if err := approvals.Add(s.DB, r, now); err != nil {
return "", err
}
s.auditAgent(c, "asked-approval", r.Summary, fmt.Sprintf("request %d", r.ID))
return fmt.Sprintf("Waiting for approval (request %d): a person approves or refuses it in Supermarket's Approvals. approvals_status says when it's decided.", r.ID), nil
}
// On its own: carried out now, and recorded.
result, runErr := s.carryOut(ctx, r, s.agentViewer(r.Agent))
r.Status, r.Result = approvals.Done, result
if runErr != nil {
r.Status, r.Result = approvals.Failed, runErr.Error()
}
if err := approvals.Add(s.DB, r, now); err != nil {
return "", err
}
s.auditAgent(c, "did-on-its-own", r.Summary, r.Result)
if runErr != nil {
return "", runErr
}
return "Done (allowed on its own): " + result, nil
}
// carryOut does what a request asked, as as (the person approving it, or
// the agent on its own).
func (s *Server) carryOut(ctx context.Context, r *approvals.Request, as *viewer) (string, error) {
now := time.Now()
switch classKind(r.Class) {
case "post":
account, _ := strconv.ParseInt(classParam(r.Class), 10, 64)
a, err := posting.Get(s.DB, account)
if err != nil {
return "", errors.New("that posting account was signed out")
}
if !s.mayPostAs(as, a) {
return "", fmt.Errorf("%s may not post as %s (Settings → Posting accounts)", whoName(as), a.Label())
}
if err := content.SetAccount(s.DB, r.Target, account); err != nil {
return "", err
}
if as.User != nil {
_ = content.SetPostedBy(s.DB, r.Target, as.User.ID)
}
if at := r.Params["at"]; at != "" {
when, err := time.Parse(time.RFC3339, at)
if err != nil {
return "", err
}
if !when.After(now) {
when = now // its time passed while it waited: now
}
if err := content.Schedule(s.DB, r.Target, when); err != nil {
return "", err
}
return "scheduled for " + when.Local().Format("2 Jan 2006 15:04"), nil
}
pctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
d, err := content.Publish(pctx, s.DB, s.publishers(), s.tagger(), r.Target)
if err != nil {
return "", err
}
return "published as " + d.PostedAs + ": " + d.PostURL, nil
case classEmailFirst, classEmailReply:
if err := outreach.Queue(s.DB, r.Target, now); err != nil {
return "", err
}
return "queued: it goes out in turn, within the sending hours", nil
case "list":
lctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
if err := s.addToListID(lctx, r.Target, classParam(r.Class), false); err != nil {
return "", err
}
return "added to the mailing list", nil
case "seo-change":
if !s.domainProved() {
return "", errors.New("the team hasn't proved its domain yet (Settings → Domain)")
}
if s.gitea() == nil {
return "", errors.New("Gitea isn't connected (Settings → Search engines)")
}
ch, err := seo.GetChange(s.DB, r.Target)
if err != nil {
return "", err
}
var site *seoSite
for _, st := range s.seoSites() {
if auditKey(st) == ch.Site {
site = &st
}
}
if site == nil {
return "", errors.New("that change's website isn't in the profile any more")
}
if err := seo.Decide(s.DB, r.Target, true, now); err != nil {
return "", err
}
ap := s.applier(*site)
go func() {
actx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
defer cancel()
if err := ap.Apply(actx, s.DB, r.Target); err != nil {
s.Log.Warn("seo: making the pull request", "change", r.Target, "err", err)
}
}()
return "approved: the pull request is being made", nil
}
return "", fmt.Errorf("no class %q", r.Class)
}
func whoName(v *viewer) string {
if v.User != nil {
return displayName(v.User)
}
return "you"
}
// The Approvals page.
// approvalView is a waiting request, with what's needed to edit it.
type approvalView struct {
approvals.Request
Agent string
ClassLabel string
Draft *content.Draft
Accounts []*posting.Account // for a post: where the viewer may send it
Message *outreach.Message
Change *seo.Change
At time.Time
}
type approvalsData struct {
Waiting []approvalView
Recent []approvalView
Allowed []grantView
}
type grantView struct {
approvals.Grant
Agent string
Mine bool // the viewer may withdraw it
}
// decides says whether a viewer may decide a request in a module.
func decides(v *viewer, module string) bool { return v.can(module, true) }
// waitingFor counts what waits for the viewer: the sidebar's number.
func (s *Server) waitingFor(v *viewer) int {
if v == nil {
return 0
}
list, err := approvals.List(s.DB, approvals.Waiting, 0, 500)
if err != nil {
return 0
}
n := 0
for _, r := range list {
if decides(v, r.Module) {
n++
}
}
return n
}
func (s *Server) agentName(id int64) string {
if u, err := users.ByID(s.DB, id); err == nil {
return u.Name
}
return "an agent since removed"
}
func (s *Server) viewApproval(r approvals.Request, v *viewer) approvalView {
av := approvalView{Request: r, Agent: s.agentName(r.Agent), ClassLabel: s.classLabel(r.Class)}
switch classKind(r.Class) {
case "post":
av.Draft, _ = content.GetDraft(s.DB, r.Target)
if av.Draft != nil {
av.Accounts = s.usableAccounts(v)[av.Draft.Channel]
}
if at := r.Params["at"]; at != "" {
av.At, _ = time.Parse(time.RFC3339, at)
}
case classEmailFirst, classEmailReply:
av.Message, _ = outreach.Get(s.DB, r.Target)
case "seo-change":
av.Change, _ = seo.GetChange(s.DB, r.Target)
}
return av
}
func (s *Server) approvalsPage(w http.ResponseWriter, r *http.Request) {
s.renderApprovals(w, r, "")
}
func (s *Server) renderApprovals(w http.ResponseWriter, r *http.Request, errMsg string) {
v := viewerOf(r)
waiting, err := approvals.List(s.DB, approvals.Waiting, 0, 200)
if err != nil {
s.serverError(w, err)
return
}
recent, err := approvals.List(s.DB, "", 0, 60)
if err != nil {
s.serverError(w, err)
return
}
var d approvalsData
for _, req := range waiting {
if decides(v, req.Module) {
d.Waiting = append(d.Waiting, s.viewApproval(req, v))
}
}
for _, req := range recent {
if req.Status != approvals.Waiting && v.can(req.Module, false) && len(d.Recent) < 30 {
d.Recent = append(d.Recent, approvalView{Request: req, Agent: s.agentName(req.Agent), ClassLabel: s.classLabel(req.Class)})
}
}
grants, err := approvals.Grants(s.DB, 0)
if err != nil {
s.serverError(w, err)
return
}
for _, g := range grants {
if v.can(g.Module, false) {
d.Allowed = append(d.Allowed, grantView{Grant: g, Agent: s.agentName(g.Agent), Mine: decides(v, g.Module)})
}
}
s.render(w, r, "approvals", page{Title: "Approvals", Nav: "approvals", Error: errMsg, Data: d})
}
// approvalAction approves or refuses a request: POST /approvals/{id}/{action}.
func (s *Server) approvalAction(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
v := viewerOf(r)
id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
req, err := approvals.Get(s.DB, id)
if errors.Is(err, approvals.ErrNotFound) {
http.NotFound(w, r)
return
}
if err != nil {
s.serverError(w, err)
return
}
if !decides(v, req.Module) {
s.forbidden(w, r)
return
}
by := int64(0)
if v.User != nil {
by = v.User.ID
}
now := time.Now()
switch r.PathValue("action") {
case "refuse":
if err := approvals.Claim(s.DB, id, by, approvals.Refused, now); err != nil {
s.renderApprovals(w, r, sentence(err.Error())+".")
return
}
s.audit(r, "refused", req.Summary, "asked by "+s.agentName(req.Agent))
redirect(w, r, "/approvals", "refused")
case "approve":
// Edits first, as on the module's own page.
if err := s.editApproval(r, req); err != nil {
s.renderApprovals(w, r, sentence(err.Error())+".")
return
}
if err := approvals.Claim(s.DB, id, by, approvals.Done, now); err != nil {
s.renderApprovals(w, r, sentence(err.Error())+".")
return
}
req, _ = approvals.Get(s.DB, id)
result, runErr := s.carryOut(r.Context(), req, v)
_ = approvals.Finish(s.DB, id, runErr)
if runErr == nil {
_ = approvals.SetResult(s.DB, id, result)
}
s.audit(r, "approved", req.Summary, "asked by "+s.agentName(req.Agent)+": "+result)
if r.PostFormValue("trust") == "on" {
cap, _ := strconv.Atoi(r.PostFormValue("cap"))
g := approvals.Grant{Agent: req.Agent, Class: req.Class, Label: s.classLabel(req.Class), Module: req.Module, DailyCap: max(cap, 0), GrantedBy: by}
if err := approvals.Allow(s.DB, g, now); err != nil {
s.serverError(w, err)
return
}
s.audit(r, "allowed-on-its-own", s.agentName(req.Agent), g.Label+capText(g.DailyCap))
}
if runErr != nil {
s.renderApprovals(w, r, "Approved, but it didn't work: "+runErr.Error())
return
}
redirect(w, r, "/approvals", "approved-request")
default:
http.NotFound(w, r)
}
}
func capText(cap int) string {
if cap <= 0 {
return ", no cap"
}
return fmt.Sprintf(", up to %d a day", cap)
}
// editApproval saves what the person changed before approving: a post's
// text and account, an email's subject and text, a change's wording.
func (s *Server) editApproval(r *http.Request, req *approvals.Request) error {
f := r.PostForm
switch classKind(req.Class) {
case "post":
if text, ok := f["content"]; ok {
if err := content.UpdateDraft(s.DB, req.Target, text[0]); err != nil {
return err
}
}
if title, ok := f["title"]; ok && strings.TrimSpace(title[0]) != "" {
if err := content.UpdateTitle(s.DB, req.Target, title[0]); err != nil {
return err
}
}
if acc := f.Get("account"); acc != "" && acc != classParam(req.Class) {
// Another account: the request becomes that class.
id, _ := strconv.ParseInt(acc, 10, 64)
if _, err := posting.Get(s.DB, id); err != nil {
return errors.New("choose an account")
}
req.Class = classPost(id)
if _, err := s.DB.Exec(`UPDATE approvals SET class = ? WHERE id = ?`, req.Class, req.ID); err != nil {
return err
}
}
case classEmailFirst, classEmailReply:
if body, ok := f["body"]; ok {
if err := outreach.Edit(s.DB, req.Target, f.Get("subject"), body[0]); err != nil {
return err
}
}
case "seo-change":
if t, ok := f["title"]; ok {
if err := seo.EditChange(s.DB, req.Target, t[0], f.Get("description")); err != nil {
return err
}
}
}
return nil
}
// approvalWithdraw takes back what an agent may do on its own.
func (s *Server) approvalWithdraw(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
agent, _ := strconv.ParseInt(r.PostFormValue("agent"), 10, 64)
class := r.PostFormValue("class")
if !decides(viewerOf(r), classModule(class)) {
s.forbidden(w, r)
return
}
if err := approvals.Withdraw(s.DB, agent, class); err != nil {
s.serverError(w, err)
return
}
s.audit(r, "withdrew-on-its-own", s.agentName(agent), s.classLabel(class))
back := "/approvals"
if strings.HasPrefix(r.Referer(), s.PublicURL+"/settings/agents/") {
back = strings.TrimPrefix(r.Referer(), s.PublicURL)
}
redirect(w, r, back, "withdrawn-class")
}
// The tools that ask.
type publishArgs struct {
DraftID int64 `json:"draft_id" jsonschema:"the draft, from content_drafts or content_create_draft"`
AccountID int64 `json:"account_id,omitempty" jsonschema:"the posting account (posting_accounts); empty: the draft's own, or the company's for its channel"`
At string `json:"at,omitempty" jsonschema:"when to publish, as 2026-11-27T09:00 (Supermarket's time zone) or RFC 3339; empty: as soon as it's approved"`
}
type sendArgs struct {
MessageID int64 `json:"message_id" jsonschema:"the outreach draft, from outreach_list or outreach_draft"`
}
type listAddArgs struct {
ContactID int64 `json:"contact_id" jsonschema:"the person, from prospects_review"`
ListID string `json:"list_id" jsonschema:"the Listmonk list's id; only double opt-in lists, which ask the person first"`
}
type changeArgs struct {
ChangeID int64 `json:"change_id" jsonschema:"the proposed change, from seo_changes"`
}
type statusArgs struct {
ID int64 `json:"id,omitempty" jsonschema:"one request; empty for the agent's last 30"`
}
func (s *Server) approvalTools(srv *mcp.Server, c *mcpserver.Caller) {
may := func(module string) bool { return c == nil || c.Can(module, true) }
mcp.AddTool(srv, &mcp.Tool{
Name: "approvals_status",
Description: "Your requests to send things out, and whether a person approved (and what happened), refused, or hasn't decided yet; and what you may do on your own.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a statusArgs) (*mcp.CallToolResult, any, error) {
if a.ID != 0 {
r, err := approvals.Get(s.DB, a.ID)
if err != nil || r.Agent != callerID(c) {
return nil, nil, approvals.ErrNotFound
}
return toolJSON(r)
}
list, err := approvals.List(s.DB, "", callerID(c), 30)
if err != nil {
return nil, nil, err
}
grants, err := approvals.Grants(s.DB, callerID(c))
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]any{"requests": nonNilList(list), "allowed_on_your_own": nonNilList(grants)})
})
if may("content") {
mcp.AddTool(srv, &mcp.Tool{
Name: "posting_accounts",
Description: "The social accounts posts can go out from, with their ids, and whether you may post to each.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, _ none) (*mcp.CallToolResult, any, error) {
av := s.agentViewer(callerID(c))
type acct struct {
ID int64 `json:"id"`
Account string `json:"account"`
Channel string `json:"channel"`
Working bool `json:"working"`
MayPost bool `json:"you_may_post"`
}
out := []acct{}
for _, a := range s.postingAccounts() {
out = append(out, acct{a.ID, a.Label(), posting.Channel(a.Network), s.working(a), s.mayPostAs(av, a)})
}
return toolJSON(out)
})
mcp.AddTool(srv, &mcp.Tool{
Name: "content_publish",
Description: "Ask to publish a draft, now or at a time, from a posting account. It waits for a person's approval unless you may publish " +
"to that account on your own; the answer says which.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a publishArgs) (*mcp.CallToolResult, any, error) {
d, err := content.GetDraft(s.DB, a.DraftID)
if err != nil {
return nil, nil, err
}
if !d.Editable() {
return nil, nil, errors.New("this draft was published, discarded, or is being published")
}
if p := d.Problem(); p != "" {
return nil, nil, errors.New(p + ": fix it first (content_edit_draft)")
}
acct := a.AccountID
if acct == 0 {
ac, err := s.draftAccount(d)
if err != nil {
return nil, nil, err
}
if ac == nil {
return nil, nil, fmt.Errorf("%s has no posting account: one must be connected first", d.ChannelName())
}
acct = ac.ID
}
ac, err := posting.Get(s.DB, acct)
if err != nil || posting.Channel(ac.Network) != d.Channel {
return nil, nil, errors.New("that isn't an account for this draft's channel (posting_accounts)")
}
if !s.mayPostAs(s.agentViewer(callerID(c)), ac) {
return nil, nil, fmt.Errorf("you may not post as %s: an admin can allow it on Settings → Posting accounts", ac.Label())
}
params := map[string]string{}
what := "Publish"
if strings.TrimSpace(a.At) != "" {
at, err := parseAgentTime(a.At)
if err != nil {
return nil, nil, err
}
params["at"] = at.UTC().Format(time.RFC3339)
what = "Schedule, for " + at.Local().Format("2 Jan 15:04") + ","
}
msg, err := s.ask(ctx, c, &approvals.Request{Class: classPost(acct), Target: d.ID, Params: params,
Summary: fmt.Sprintf("%s a post to %s", what, ac.Label())})
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]string{"status": msg})
})
}
if may("prospects") {
mcp.AddTool(srv, &mcp.Tool{
Name: "outreach_send",
Description: "Ask to send an outreach email draft (it's queued, and goes out within the sending hours). It waits for a person's approval " +
"unless you may send that kind on your own (a first email, or a reply in a conversation).",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a sendArgs) (*mcp.CallToolResult, any, error) {
m, err := outreach.Get(s.DB, a.MessageID)
if err != nil {
return nil, nil, err
}
if m.Channel != outreach.ChannelEmail {
return nil, nil, errors.New("LinkedIn messages are sent by hand, by a person")
}
if m.Status != outreach.StatusDraft && m.Status != outreach.StatusFailed {
return nil, nil, fmt.Errorf("this message is %s, not a draft", m.Status)
}
class := classEmailFirst
if prev, err := outreach.ForContacts(s.DB, []int64{m.ContactID}); err == nil {
for _, o := range prev[m.ContactID] {
if o.ID != m.ID && !o.SentAt.IsZero() {
class = classEmailReply
}
}
}
kind := "a first email"
if class == classEmailReply {
kind = "a reply"
}
msg, err := s.ask(ctx, c, &approvals.Request{Class: class, Target: m.ID, Summary: "Send " + kind + " to " + m.To})
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]string{"status": msg})
})
mcp.AddTool(srv, &mcp.Tool{
Name: "mailing_list_add",
Description: "Ask to add a person to a double opt-in mailing list (Listmonk asks them first). It waits for a person's approval unless you may add to that list on your own.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a listAddArgs) (*mcp.CallToolResult, any, error) {
p, err := prospects.GetContact(s.DB, a.ContactID)
if err != nil {
return nil, nil, err
}
if strings.TrimSpace(a.ListID) == "" {
return nil, nil, errors.New("give the list's id")
}
msg, err := s.ask(ctx, c, &approvals.Request{Class: classList(strings.TrimSpace(a.ListID)), Target: p.ID,
Summary: "Add " + p.Name() + " (" + p.Email + ") to mailing list " + a.ListID})
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]string{"status": msg})
})
}
if may("seo") {
mcp.AddTool(srv, &mcp.Tool{
Name: "seo_apply_change",
Description: "Ask to apply a proposed title and description change (a pull request on the site). It waits for a person's approval unless you may apply changes to that site on your own.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, a changeArgs) (*mcp.CallToolResult, any, error) {
ch, err := seo.GetChange(s.DB, a.ChangeID)
if err != nil {
return nil, nil, err
}
msg, err := s.ask(ctx, c, &approvals.Request{Class: classSEO(ch.Site), Target: ch.ID, Summary: "Change the title and description of " + ch.Page})
if err != nil {
return nil, nil, err
}
return toolJSON(map[string]string{"status": msg})
})
}
}
// parseAgentTime reads a time an agent gives: RFC 3339, or local
// 2006-01-02T15:04. It must be ahead, within a year.
func parseAgentTime(v string) (time.Time, error) {
v = strings.TrimSpace(v)
t, err := time.Parse(time.RFC3339, v)
if err != nil {
if t, err = time.ParseInLocation(dateTimeLocal, v, time.Local); err != nil {
return time.Time{}, fmt.Errorf("%q isn't a time: give 2026-11-27T09:00, or RFC 3339", v)
}
}
now := time.Now()
if t.Before(now.Add(-time.Minute)) {
return time.Time{}, errors.New("that time has passed")
}
if t.After(now.AddDate(1, 0, 0)) {
return time.Time{}, errors.New("that's more than a year away")
}
return t, nil
}
+188
View File
@@ -0,0 +1,188 @@
package web
import (
"encoding/json"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"testing"
"time"
"supermarket/internal/approvals"
"supermarket/internal/content"
"supermarket/internal/posting"
"supermarket/internal/profile"
"supermarket/internal/prospects"
"supermarket/internal/users"
)
var requestRe = regexp.MustCompile(`request (\d+)`)
func TestAgentDayThroughApprovals(t *testing.T) {
s, h := newServerEdition(t)
sent := &fakePosts{}
s.testPublisher = func(a *posting.Account) content.Publisher { return fakePub{sent, a} }
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}})
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
oc := sessionFor(t, s, owner)
viewerOnly := addUser(t, s, "vi@example.com", users.Member, map[string]users.Access{"content": users.View})
seoOnly := addUser(t, s, "sam@example.com", users.Member, map[string]users.Access{"seo": users.Edit})
company := &posting.Account{Network: posting.X, Name: "@acme", External: "acme"}
posting.Save(s.DB, s.Secrets, company, "t", "", time.Now())
agent, key := newAgent(t, s, "Morning writer", map[string]users.Access{"content": users.Edit, "seo": users.View})
// A day's work: read the morning check and What to write next…
_, tools := mcpTools(h, key)
got := " " + strings.Join(tools, " ") + " "
for _, not := range []string{"seo_edit_change", "seo_apply_change"} {
if strings.Contains(got, " "+not+" ") {
t.Errorf("an SEO tool that changes things is offered: %s", not)
}
}
mcpCall(t, h, key, "seo_morning_check", map[string]any{})
mcpCall(t, h, key, "seo_next", map[string]any{})
// …write a draft, and schedule it.
text, _ := mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Widgets, faster."})
var d draftView
json.Unmarshal([]byte(text), &d)
// It may not post to the company's account until it's on the grid.
at := time.Now().Add(3 * time.Hour).Format(dateTimeLocal)
if text, isErr := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID, "at": at}); !isErr || !strings.Contains(text, "may not post as X @acme") {
t.Errorf("not on the grid: %v %s", isErr, text)
}
posting.SetGrants(s.DB, map[int64][]int64{company.ID: {agent.ID}})
text, isErr := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID, "at": at})
if isErr || !strings.Contains(text, "Waiting for approval") {
t.Fatalf("publish: %s", text)
}
reqID, _ := strconv.ParseInt(requestRe.FindStringSubmatch(text)[1], 10, 64)
// Asking again doesn't make a second request.
if text, _ := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID, "at": at}); !strings.Contains(text, "Already waiting") {
t.Errorf("asked twice: %s", text)
}
if dr, _ := content.GetDraft(s.DB, d.ID); dr.Status != content.StatusDraft || len(sent.sent) != 0 {
t.Errorf("went out without approval: %+v", dr)
}
// Who sees it: the owner, not a Content viewer, not an SEO member.
if body := as(h, oc, http.MethodGet, "/", nil).Body.String(); !strings.Contains(body, `title="1 waiting for you"`) {
t.Error("no count in the sidebar")
}
page := as(h, oc, http.MethodGet, "/approvals", nil).Body.String()
if !strings.Contains(page, "Morning writer") || !strings.Contains(page, "Widgets, faster.") {
t.Errorf("approvals page: %s", page)
}
for _, u := range []*users.User{viewerOnly, seoOnly} {
c := sessionFor(t, s, u)
if body := as(h, c, http.MethodGet, "/approvals", nil).Body.String(); strings.Contains(body, "Widgets, faster.") {
t.Errorf("%s sees it", u.Email)
}
if rec := as(h, c, http.MethodPost, "/approvals/"+strconv.FormatInt(reqID, 10)+"/approve", url.Values{}); rec.Code != http.StatusForbidden {
t.Errorf("%s approves: %d", u.Email, rec.Code)
}
}
// The owner edits it, approves it, and lets it schedule to @acme on its
// own, once a day.
rec := as(h, oc, http.MethodPost, "/approvals/"+strconv.FormatInt(reqID, 10)+"/approve", url.Values{
"content": {"Widgets, much faster."}, "account": {strconv.FormatInt(company.ID, 10)}, "trust": {"on"}, "cap": {"1"}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("approve: %d %s", rec.Code, rec.Body.String())
}
dr, _ := content.GetDraft(s.DB, d.ID)
if dr.Status != content.StatusScheduled || dr.Content != "Widgets, much faster." || dr.AccountID != company.ID || dr.PostedBy != owner.ID {
t.Errorf("scheduled: %+v", dr)
}
if text, _ := mcpCall(t, h, key, "approvals_status", map[string]any{"id": reqID}); !strings.Contains(text, `"Status": "done"`) {
t.Errorf("status: %s", text)
}
if rec := as(h, oc, http.MethodPost, "/approvals/"+strconv.FormatInt(reqID, 10)+"/approve", url.Values{}); rec.Code == http.StatusSeeOther {
t.Error("approved twice")
}
// Now on its own, once; the next waits again.
text, _ = mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Second."})
json.Unmarshal([]byte(text), &d)
if text, _ := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID}); !strings.Contains(text, "Done (allowed on its own): published as X @acme") {
t.Errorf("on its own: %s", text)
}
if len(sent.sent) != 1 || sent.sent[0] != "X @acme: Second." {
t.Errorf("sent %v", sent.sent)
}
text, _ = mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Third."})
json.Unmarshal([]byte(text), &d)
text, _ = mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID})
if !strings.Contains(text, "Waiting for approval") {
t.Errorf("over the cap: %s", text)
}
third, _ := strconv.ParseInt(requestRe.FindStringSubmatch(text)[1], 10, 64)
// Refused: nothing goes, and the agent can read why.
as(h, oc, http.MethodPost, "/approvals/"+strconv.FormatInt(third, 10)+"/refuse", url.Values{})
if r, _ := approvals.Get(s.DB, third); r.Status != approvals.Refused || len(sent.sent) != 1 {
t.Errorf("refused: %+v", r)
}
// The agent's page lists what it may do on its own; the log has it all.
body := as(h, oc, http.MethodGet, "/settings/agents/"+strconv.FormatInt(agent.ID, 10), nil).Body.String()
if !strings.Contains(body, "publish posts to X @acme") || !strings.Contains(body, "up to 1 a day") {
t.Errorf("agent page: %s", body)
}
act := as(h, oc, http.MethodGet, "/settings/activity", nil).Body.String()
for _, want := range []string{"asked for approval to", "approved", "let an agent act on its own:", "did on its own:", "refused"} {
if !strings.Contains(act, want) {
t.Errorf("activity lacks %q", want)
}
}
// The key leaked: rotated with "it leaked", the old key stops at once and
// nothing is allowed on its own.
rec = as(h, oc, http.MethodPost, "/settings/agents/"+strconv.FormatInt(agent.ID, 10)+"/rotate", url.Values{"leaked": {"on"}})
newKey := keyRe.FindStringSubmatch(rec.Body.String())[1]
if code, _ := mcpTools(h, key); code != http.StatusUnauthorized {
t.Errorf("leaked key still works: %d", code)
}
if gs, _ := approvals.Grants(s.DB, agent.ID); len(gs) != 0 {
t.Errorf("grants kept: %+v", gs)
}
if code, _ := mcpTools(h, newKey); code != http.StatusOK {
t.Errorf("new key: %d", code)
}
// Revoking the key stops it at once.
keys, _ := users.Keys(s.DB, agent.ID)
for _, k := range keys {
users.Revoke(s.DB, agent.ID, k.ID, time.Now())
}
if code, _ := mcpTools(h, newKey); code != http.StatusUnauthorized {
t.Errorf("revoked: %d", code)
}
}
func TestApprovalThatFails(t *testing.T) {
s, h := newTestServer(t, nil)
_, key := newAgent(t, s, "Lister", map[string]users.Access{"prospects": users.Edit})
id, _, err := prospectsAdd(s)
if err != nil {
t.Fatal(err)
}
text, _ := mcpCall(t, h, key, "mailing_list_add", map[string]any{"contact_id": id, "list_id": "3"})
m := requestRe.FindStringSubmatch(text)
if m == nil {
t.Fatalf("add: %s", text)
}
// Listmonk isn't set up: approving says so, and the request is failed.
rec := postForm(h, "/approvals/"+m[1]+"/approve", url.Values{})
if !strings.Contains(rec.Body.String(), "set up Listmonk") {
t.Errorf("approve: %s", rec.Body.String())
}
rid, _ := strconv.ParseInt(m[1], 10, 64)
if r, _ := approvals.Get(s.DB, rid); r.Status != approvals.Failed {
t.Errorf("status %s", r.Status)
}
}
func prospectsAdd(s *Server) (int64, bool, error) {
return prospects.AddContact(s.DB, prospects.Contact{FirstName: "Kim", LastName: "Lee", Email: "kim@example.org", Source: "manual"}, time.Now())
}
+432
View File
@@ -0,0 +1,432 @@
package web
import (
"bytes"
"context"
"crypto/subtle"
"errors"
"html"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"supermarket/internal/config"
"supermarket/internal/users"
)
// The people using the app. On the local edition there is one, the
// owner, who never signs in: only this computer reaches the app. On the
// server edition each request carries a session cookie, and pages are
// shown to whoever it belongs to.
// viewer is who a request comes from.
type viewer struct {
User *users.User // nil on the local edition
Member users.Membership
Session *users.Session // nil on the local edition
Platform bool // runs the multi-tenant platform (SUPERMARKET_PLATFORM_ADMINS)
Viewing bool // a platform admin viewing a team, read-only
ReadOnly bool // the team's subscription has lapsed: nothing may change
// More people than the plan's seats, and not one kept: they read, and
// change nothing.
OverSeats bool
}
// localOwner is the local edition's one user.
var localOwner = &viewer{Member: users.Membership{Team: users.Team, Role: users.Owner}}
type ctxKey int
const (
viewerKey ctxKey = iota
csrfKey
)
// viewerOf is who's asking. Requests that didn't go through the session
// check (tests calling a handler directly) are the local owner's.
func viewerOf(r *http.Request) *viewer {
if v, ok := r.Context().Value(viewerKey).(*viewer); ok {
return v
}
return localOwner
}
// edition is how the app is run; tests without a Config are local.
func (s *Server) edition() config.Edition {
if s.Config == nil {
return config.Local
}
return s.Config.Edition
}
// signsIn says whether people sign in: every edition but local.
func (s *Server) signsIn() bool { return s.edition() != config.Local }
// secureCookies says whether cookies are marked Secure: when people reach
// the app over https.
func (s *Server) secureCookies() bool { return strings.HasPrefix(s.PublicURL, "https://") }
// cookieName gives a cookie the __Host- prefix over https, so nothing on
// another subdomain can set it.
func (s *Server) cookieName(name string) string {
if s.secureCookies() {
return "__Host-" + name
}
return name
}
const (
sessionCookie = "sm_session"
csrfCookie = "sm_csrf"
csrfField = "csrf" // the forms' hidden field
csrfHeader = "X-CSRF-Token" // htmx sends it (app.js)
)
// sessions finds who each request comes from. On the server edition,
// anyone not signed in is sent to sign in.
func (s *Server) sessions(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), viewerKey, localOwner)))
return
}
if !s.multi() && (!publicPath(r.URL.Path) || strings.HasPrefix(r.URL.Path, "/signin")) {
if done, err := s.hasOwner(); err != nil {
s.serverError(w, err)
return
} else if !done {
s.setupUnfinished(w, r)
return
}
}
v, err := s.lookupSession(r)
if err != nil && !errors.Is(err, users.ErrNoSession) {
s.serverError(w, err)
return
}
if v == nil {
if publicPath(r.URL.Path) {
next.ServeHTTP(w, r)
return
}
s.toSignIn(w, r)
return
}
if s.multi() && v.Session != nil && !publicPath(r.URL.Path) && !platformPath(r.URL.Path) {
// A platform admin outside any team: the platform's pages.
if v.Session.Team == 0 {
http.Redirect(w, r, "/platform", http.StatusSeeOther)
return
}
// A team that's suspended or being deleted is closed, but for
// switching teams, one's account, and the platform's admins.
if !v.Viewing && !strings.HasPrefix(r.URL.Path, "/teams/") {
if t, err := users.GetTeam(s.platform(), v.Session.Team); err == nil && t.Status != users.TeamActive {
s.teamClosed(w, r, t)
return
}
}
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), viewerKey, v)))
})
}
// lookupSession is the signed-in viewer, or nil.
func (s *Server) lookupSession(r *http.Request) (*viewer, error) {
c, err := r.Cookie(s.cookieName(sessionCookie))
if err != nil {
return nil, users.ErrNoSession
}
now := time.Now()
sess, u, err := users.Lookup(s.platform(), c.Value, now)
if err != nil {
return nil, err
}
pa := s.isPlatformAdmin(u)
if s.multi() && !sess.ViewUntil.IsZero() {
if pa && now.Before(sess.ViewUntil) {
return &viewer{User: u, Member: readOnly(sess.Team), Session: sess, Platform: true, Viewing: true}, nil
}
// Ran out: back to the platform.
if err := users.ViewAs(s.platform(), sess.ID, 0, time.Time{}, ""); err != nil {
return nil, err
}
sess.Team, sess.ViewUntil, sess.ViewReason = 0, time.Time{}, ""
}
if s.multi() && sess.Team == 0 {
if !pa {
return nil, users.ErrNoSession
}
return &viewer{User: u, Member: users.Membership{Team: 0, Role: users.Member}, Session: sess, Platform: true}, nil
}
m, err := users.MembershipOf(s.platform(), sess.Team, u.ID)
if errors.Is(err, users.ErrNotFound) {
return nil, users.ErrNoSession // no longer in the team
}
if err != nil {
return nil, err
}
v := &viewer{User: u, Member: m, Session: sess, Platform: pa}
if s.billingOn() {
if ts, err := s.forTeam(sess.Team); err == nil {
plan, ro := ts.teamPlan()
v.Member, v.ReadOnly = planned(m, plan, ro), ro
if kept, _ := ts.kept(); kept != nil && !kept[u.ID] {
v.Member, v.OverSeats = viewOnly(v.Member), true
}
}
}
return v, nil
}
// toSignIn sends someone who isn't signed in to the sign-in page, and
// back here afterwards. htmx is told to load the whole page.
func (s *Server) toSignIn(w http.ResponseWriter, r *http.Request) {
target := "/signin"
if r.Method == http.MethodGet && r.URL.Path != "/" {
target += "?next=" + url.QueryEscape(r.URL.RequestURI())
}
if r.Header.Get("HX-Request") != "" {
w.Header().Set("HX-Redirect", target)
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "Sign in first.", http.StatusUnauthorized)
return
}
http.Redirect(w, r, target, http.StatusSeeOther)
}
// startSession signs a user in on this browser.
func (s *Server) startSession(w http.ResponseWriter, r *http.Request, u *users.User) error {
team := s.team()
if s.multi() {
// The team they worked in last, else their first.
list, err := users.TeamsOf(s.platform(), u.ID)
if err != nil {
return err
}
team = 0
for _, t := range list {
if t.Status == users.TeamActive && (team == 0 || t.ID == lastTeam(s, u.ID)) {
team = t.ID
}
}
if team == 0 && !s.isPlatformAdmin(u) {
return errors.New("you aren't in any team that's open")
}
}
return s.startSessionIn(w, r, u, team, "password")
}
// startSessionIn signs a user in to a team, recording how (password, core).
func (s *Server) startSessionIn(w http.ResponseWriter, r *http.Request, u *users.User, team int64, via string) error {
token, sess, err := users.StartSessionIn(s.platform(), u.ID, team, clientIP(r), r.UserAgent(), time.Now())
if err != nil {
return err
}
if via != "password" {
if err := users.SetVia(s.platform(), sess.ID, via); err != nil {
return err
}
}
if err := users.SignedIn(s.platform(), u.ID, time.Now()); err != nil {
return err
}
s.setSessionCookie(w, token)
return nil
}
// lastTeam is the team a person's latest session worked in.
func lastTeam(s *Server, user int64) int64 {
var t int64
_ = s.platform().QueryRow(`SELECT team_id FROM sessions WHERE user_id = ? ORDER BY created_at DESC LIMIT 1`, user).Scan(&t)
return t
}
// setSessionCookie gives the browser its session.
func (s *Server) setSessionCookie(w http.ResponseWriter, token string) {
http.SetCookie(w, &http.Cookie{
Name: s.cookieName(sessionCookie), Value: token, Path: "/",
MaxAge: int(users.SessionMax / time.Second), Secure: s.secureCookies(),
HttpOnly: true, SameSite: http.SameSiteLaxMode,
})
}
// endSession signs this browser out.
func (s *Server) endSession(w http.ResponseWriter, r *http.Request) error {
if c, err := r.Cookie(s.cookieName(sessionCookie)); err == nil {
if err := users.EndSession(s.DB, c.Value); err != nil {
return err
}
}
http.SetCookie(w, &http.Cookie{
Name: s.cookieName(sessionCookie), Value: "", Path: "/", MaxAge: -1,
Secure: s.secureCookies(), HttpOnly: true, SameSite: http.SameSiteLaxMode,
})
return nil
}
// clientIP is where a request came from: the proxy's X-Forwarded-For on
// the server edition (Caddy sets it, replacing what the client sent),
// else the connection's address.
func clientIP(r *http.Request) string {
if f := r.Header.Get("X-Forwarded-For"); f != "" {
parts := strings.Split(f, ",")
if ip := net.ParseIP(strings.TrimSpace(parts[len(parts)-1])); ip != nil {
return ip.String()
}
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}
// CSRF: every form that changes something carries a token that a page on
// another site can't know, as well as the same-origin check (guard). The
// token is a random value in a cookie of its own, repeated in each form
// (the double-submit pattern): the forms get it as a hidden field, added
// as pages are rendered, and htmx sends it as a header.
// csrf makes sure the browser has a token, and checks it on every request
// that changes something.
func (s *Server) csrf(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name := s.cookieName(csrfCookie)
token := ""
if c, err := r.Cookie(name); err == nil && len(c.Value) >= 32 {
token = c.Value
}
if !safeMethod(r.Method) && r.URL.Path != "/mcp" && !strings.HasPrefix(r.URL.Path, "/api/v1/") && r.URL.Path != "/billing/stripe" {
if token == "" || !sameToken(token, sentToken(r)) {
http.Error(w, "This form has expired: reload the page and try again.", http.StatusForbidden)
return
}
}
if token == "" {
var err error
if token, err = users.NewToken(); err != nil {
s.serverError(w, err)
return
}
http.SetCookie(w, &http.Cookie{
Name: name, Value: token, Path: "/", MaxAge: 365 * 24 * 3600,
Secure: s.secureCookies(), HttpOnly: true, SameSite: http.SameSiteLaxMode,
})
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), csrfKey, token)))
})
}
func safeMethod(m string) bool {
return m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions
}
func sameToken(a, b string) bool {
return b != "" && subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
}
// sentToken is the token a request carries: htmx's header, a multipart
// form's address (its body is left for the handler, which limits its
// size), or a form's field.
func sentToken(r *http.Request) string {
if t := r.Header.Get(csrfHeader); t != "" {
return t
}
if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/") {
return r.URL.Query().Get(csrfField)
}
if err := r.ParseForm(); err != nil {
return ""
}
return r.PostForm.Get(csrfField)
}
// csrfToken is the request's token, for the page.
func csrfToken(r *http.Request) string {
t, _ := r.Context().Value(csrfKey).(string)
return t
}
var (
formTag = regexp.MustCompile(`(?is)<form\b[^>]*>`)
attrRe = regexp.MustCompile(`(?is)\b(method|action|enctype)\s*=\s*"([^"]*)"`)
actionArg = regexp.MustCompile(`(?is)\baction\s*=\s*"([^"]*)"`)
)
// addCSRF puts the token into every form on a page that posts to this app:
// a hidden field, and for a file upload (multipart) also its address.
// Forms that post elsewhere never get it.
func addCSRF(page []byte, token string) []byte {
if token == "" {
return page
}
field := []byte(`<input type="hidden" name="` + csrfField + `" value="` + html.EscapeString(token) + `">`)
return formTag.ReplaceAllFunc(page, func(tag []byte) []byte {
method, action, enctype := formAttrs(tag)
if method != "post" || !ownAddress(action) {
return tag
}
if strings.HasPrefix(enctype, "multipart/") {
sep := "?"
if strings.Contains(action, "?") {
sep = "&"
}
a := action + sep + csrfField + "=" + url.QueryEscape(token)
tag = actionArg.ReplaceAll(tag, []byte(`action="`+html.EscapeString(strings.ReplaceAll(a, "$", "$$"))+`"`))
}
out := make([]byte, 0, len(tag)+len(field))
return append(append(out, tag...), field...)
})
}
// ownAddress says whether a form's action is this app: empty, or a path.
func ownAddress(action string) bool {
if action == "" {
return true
}
return strings.HasPrefix(action, "/") && !strings.HasPrefix(action, "//") && !strings.HasPrefix(action, `/\`)
}
// withCSRF renders a template into a buffer and adds the token to its
// forms.
func withCSRF(r *http.Request, exec func(*bytes.Buffer) error) ([]byte, error) {
var buf bytes.Buffer
if err := exec(&buf); err != nil {
return nil, err
}
var v *viewer
if vv := viewerOf(r); !vv.Member.Admin() {
v = vv // forms they can't send are disabled
}
return rewriteForms(buf.Bytes(), csrfToken(r), r.URL.Path, v), nil
}
// teamServer is the Server for the request's team: the viewer's (the
// team their session works in), else this one.
func (s *Server) teamServer(r *http.Request) (*Server, error) {
if !s.multi() {
return s, nil
}
v := viewerOf(r)
if v.Session == nil {
return s, nil
}
return s.forTeam(v.Session.Team)
}
// team is the team this Server works for: 1 on the local and server
// editions.
func (s *Server) team() int64 {
if s.Team == 0 && !s.multi() {
return users.Team
}
return s.Team // 0: the multi-tenant edition's platform, no team's
}
+244
View File
@@ -0,0 +1,244 @@
package web
import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"supermarket/internal/appmail"
"supermarket/internal/config"
"supermarket/internal/storage"
"supermarket/internal/users"
)
// newServerEdition is a test server run as the server edition.
func newServerEdition(t *testing.T) (*Server, http.Handler) {
t.Helper()
s, h := newTestServer(t, nil)
s.Config = &config.Config{Edition: config.Server}
// The server edition has no built-in Hermes.
var hermes int64
if ok, _ := s.DB.GetJSON(hermesKey, &hermes); ok {
users.Delete(s.DB, hermes)
s.DB.Exec(`DELETE FROM settings WHERE key = ?`, hermesKey)
s.DB.Exec(`DELETE FROM audit_log`)
}
s.Mail = &appmail.Outbox{}
files, err := storage.Open(config.Storage{Dir: t.TempDir()})
if err != nil {
t.Fatal(err)
}
s.Files = files
return s, h
}
// addUser makes an active user with a role and a password.
func addUser(t *testing.T, s *Server, email string, role users.Role, modules map[string]users.Access) *users.User {
t.Helper()
u := &users.User{Email: email, Name: strings.Split(email, "@")[0], Status: users.Active}
if err := users.Create(s.DB, u, time.Now()); err != nil {
t.Fatal(err)
}
if err := users.SetPassword(s.DB, u, "a long enough one"); err != nil {
t.Fatal(err)
}
if err := users.Join(s.DB, users.Team, u.ID, role, modules, time.Now()); err != nil {
t.Fatal(err)
}
return u
}
// sessionFor signs a user in and returns their cookie.
func sessionFor(t *testing.T, s *Server, u *users.User) *http.Cookie {
t.Helper()
token, _, err := users.StartSession(s.DB, u.ID, "", "", time.Now())
if err != nil {
t.Fatal(err)
}
return &http.Cookie{Name: sessionCookie, Value: token}
}
// as makes a request with a session cookie.
func as(h http.Handler, c *http.Cookie, method, target string, form url.Values) *httptest.ResponseRecorder {
var req *http.Request
if form != nil {
req = httptest.NewRequest(method, target, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} else {
req = httptest.NewRequest(method, target, nil)
}
req.Host = "localhost:8470"
if c != nil {
req.AddCookie(c)
}
if !safeMethod(method) {
req.AddCookie(&http.Cookie{Name: csrfCookie, Value: testCSRF})
req.Header.Set(csrfHeader, testCSRF)
req.Header.Set("Origin", "http://localhost:8470")
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestCSRF(t *testing.T) {
_, h := newTestServer(t, nil)
form := url.Values{"name": {"Acme"}, "description": {"x"}}
// A page sets the cookie and puts the token in its forms.
rec := do(h, http.MethodGet, "/settings/profile", nil, nil)
var token string
for _, c := range rec.Result().Cookies() {
if c.Name == csrfCookie {
token = c.Value
if !c.HttpOnly || c.SameSite != http.SameSiteLaxMode {
t.Errorf("cookie %+v", c)
}
}
}
if len(token) < 32 {
t.Fatalf("no token cookie: %v", rec.Result().Cookies())
}
body := rec.Body.String()
if !strings.Contains(body, `<input type="hidden" name="csrf" value="`+token+`">`) {
t.Error("the form has no token")
}
if !strings.Contains(body, `<meta name="csrf-token" content="`+token+`">`) {
t.Error("no token for htmx")
}
if strings.Contains(body, `role="search"><input type="hidden" name="csrf"`) {
t.Error("the search form (GET) got the token")
}
post := func(cookie, field, header string) int {
f := url.Values{}
for k, v := range form {
f[k] = v
}
if field != "" {
f.Set(csrfField, field)
}
req := httptest.NewRequest(http.MethodPost, "/settings/profile", strings.NewReader(f.Encode()))
req.Host = "localhost:8470"
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Origin", "http://localhost:8470")
if cookie != "" {
req.AddCookie(&http.Cookie{Name: csrfCookie, Value: cookie})
}
if header != "" {
req.Header.Set(csrfHeader, header)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec.Code
}
for _, c := range []struct {
name string
cookie, field, header string
want int
}{
{"no token at all", "", "", "", http.StatusForbidden},
{"cookie only", token, "", "", http.StatusForbidden},
{"field without a cookie", "", token, "", http.StatusForbidden},
{"wrong field", token, token + "x", "", http.StatusForbidden},
{"field", token, token, "", http.StatusSeeOther},
{"header", token, "", token, http.StatusSeeOther},
} {
if got := post(c.cookie, c.field, c.header); got != c.want {
t.Errorf("%s: %d, want %d", c.name, got, c.want)
}
}
// MCP has its own key.
if rec := do(h, http.MethodPost, "/mcp", strings.NewReader("{}"), map[string]string{csrfHeader: ""}); rec.Code == http.StatusForbidden {
t.Errorf("MCP asked for a form token: %d", rec.Code)
}
}
func TestAddCSRF(t *testing.T) {
in := `<form method="post" action="/a"><form method="get" action="/b"><form action="/c"><form method="POST" action="https://evil.example/x"><form method="post" action="//evil.example/"><form method="post" action="/up?x=1" enctype="multipart/form-data"><form method="post">`
out := string(addCSRF([]byte(in), "T0k"))
want := `<form method="post" action="/a"><input type="hidden" name="csrf" value="T0k"><form method="get" action="/b"><form action="/c"><form method="POST" action="https://evil.example/x"><form method="post" action="//evil.example/"><form method="post" action="/up?x=1&amp;csrf=T0k" enctype="multipart/form-data"><input type="hidden" name="csrf" value="T0k"><form method="post"><input type="hidden" name="csrf" value="T0k">`
if out != want {
t.Errorf("got\n%s\nwant\n%s", out, want)
}
}
func TestServerEditionNeedsSignIn(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
// Not signed in: pages lead to the sign-in page; what's public stays so.
rec := do(h, http.MethodGet, "/seo/check?site=0", nil, nil)
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin?next=%2Fseo%2Fcheck%3Fsite%3D0" {
t.Errorf("page: %d %s", rec.Code, rec.Header().Get("Location"))
}
if rec := do(h, http.MethodGet, "/", nil, nil); rec.Header().Get("Location") != "/signin" {
t.Errorf("home: %s", rec.Header().Get("Location"))
}
if rec := do(h, http.MethodGet, "/seo/audit/status", nil, map[string]string{"HX-Request": "true"}); rec.Code != http.StatusUnauthorized || rec.Header().Get("HX-Redirect") == "" {
t.Errorf("htmx: %d %v", rec.Code, rec.Header())
}
if rec := postForm(h, "/settings/profile", url.Values{"name": {"x"}}); rec.Code != http.StatusUnauthorized {
t.Errorf("post: %d", rec.Code)
}
for _, p := range []string{"/healthz", "/static/app.css", "/favicon.ico"} {
if rec := do(h, http.MethodGet, p, nil, nil); rec.Code != http.StatusOK {
t.Errorf("%s: %d", p, rec.Code)
}
}
// Signed in.
c := sessionFor(t, s, owner)
if rec := as(h, c, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusOK {
t.Errorf("signed in: %d", rec.Code)
}
if rec := as(h, c, http.MethodPost, "/settings/profile", url.Values{"name": {"Acme"}, "description": {"x"}}); rec.Code != http.StatusSeeOther {
t.Errorf("signed-in post: %d %s", rec.Code, rec.Body.String())
}
// A made-up cookie, a disabled user, a user out of the team: not in.
if rec := as(h, &http.Cookie{Name: sessionCookie, Value: "made-up"}, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusSeeOther {
t.Errorf("made-up cookie: %d", rec.Code)
}
users.SetStatus(s.DB, owner.ID, users.Disabled)
if rec := as(h, c, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusSeeOther {
t.Errorf("disabled: %d", rec.Code)
}
users.SetStatus(s.DB, owner.ID, users.Active)
s.DB.Exec(`DELETE FROM memberships WHERE user_id = ?`, owner.ID)
if rec := as(h, c, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusSeeOther {
t.Errorf("out of the team: %d", rec.Code)
}
}
func TestSessionCookiesOverHTTPS(t *testing.T) {
s, _ := newServerEdition(t)
s.PublicURL = "https://sm.example.com"
u := addUser(t, s, "pat@example.com", users.Owner, nil)
req := httptest.NewRequest(http.MethodPost, "/signin", nil)
rec := httptest.NewRecorder()
if err := s.startSession(rec, req, u); err != nil {
t.Fatal(err)
}
c := rec.Result().Cookies()[0]
if c.Name != "__Host-sm_session" || !c.Secure || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.Path != "/" || c.Domain != "" {
t.Errorf("cookie %+v", c)
}
if got, _ := users.ByID(s.DB, u.ID); got.SignedIn.IsZero() {
t.Error("sign-in not recorded")
}
}
func TestClientIP(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = "10.0.0.2:5555"
if got := clientIP(r); got != "10.0.0.2" {
t.Errorf("direct: %s", got)
}
r.Header.Set("X-Forwarded-For", "1.2.3.4, 203.0.113.9")
if got := clientIP(r); got != "203.0.113.9" {
t.Errorf("through the proxy: %s", got)
}
}
+50
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
@@ -59,6 +60,10 @@ func (s *Server) backupsPage(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) renderBackups(w http.ResponseWriter, r *http.Request, errMsg, flash string) {
if s.DB.Dialect != db.SQLite {
s.renderServerBackups(w, r)
return
}
bs, err := backup.List(s.backupDir())
if err != nil {
s.serverError(w, err)
@@ -82,6 +87,10 @@ func (s *Server) renderBackups(w http.ResponseWriter, r *http.Request, errMsg, f
}
func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) {
if s.DB.Dialect != db.SQLite {
http.NotFound(w, r) // the operator backs Postgres up, and restores it
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
@@ -124,6 +133,10 @@ func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) {
// data (not its secrets), so it's served to this machine only, like
// everything else here.
func (s *Server) backupDownload(w http.ResponseWriter, r *http.Request) {
if s.DB.Dialect != db.SQLite {
http.NotFound(w, r)
return
}
b, err := backup.Find(s.backupDir(), r.PathValue("name"))
if err != nil {
http.NotFound(w, r)
@@ -208,3 +221,40 @@ func (s *Server) backupUpload(w http.ResponseWriter, r *http.Request) {
}
s.renderBackups(w, r, "", "Uploaded as "+b.Name+". Restore it from the list when you're ready.")
}
// dump is one of the server's nightly database dumps.
type dump struct {
Name string
Size int64
At time.Time
}
// renderServerBackups lists the nightly dumps of Postgres (compose.server.yaml's
// backup service), newest first, and how the operator restores one.
func (s *Server) renderServerBackups(w http.ResponseWriter, r *http.Request) {
data := map[string]any{"Dir": ""}
if s.Config != nil && s.Config.PGBackups != "" {
data["Dir"] = s.Config.PGBackups
entries, err := os.ReadDir(s.Config.PGBackups)
if err != nil {
data["Err"] = err.Error()
}
var dumps []dump
var total int64
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".dump") {
continue
}
if fi, err := e.Info(); err == nil {
dumps = append(dumps, dump{Name: e.Name(), Size: fi.Size(), At: fi.ModTime()})
total += fi.Size()
}
}
sort.Slice(dumps, func(i, j int) bool { return dumps[i].At.After(dumps[j].At) })
data["Dumps"], data["Total"] = dumps, total
if len(dumps) > 0 && time.Since(dumps[0].At) > 36*time.Hour {
data["Stale"] = dumps[0].At
}
}
s.render(w, r, "backups-server", page{Title: "Backups", Nav: "settings/backups", Data: data})
}

Some files were not shown because too many files have changed in this diff Show More