Skip to content

feat(server): send e-mails only to the people who can see the brand (brand access PR 8) - #1893

Merged
gkhngyk merged 17 commits into
ansvisor:mainfrom
cihan-gyk:feature/brand-access-recipients
Oct 31, 2026
Merged

gkhngyk merged 17 commits into
ansvisor:mainfrom
cihan-gyk:feature/brand-access-recipients

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Brand-level access, PR 8 of ~16: e-mails go only to the people who can see the brand. Stacked on #1888 (PR 7). No migration. Nothing changes while everyone is All brands.

server/src/lib/access.js

  • brandReaders(orgId, brandIds) maps each Account member to the brands they can see, using PR 7's rule (can_access_brand's): Admin, All brands, the demo brand, or a granted brand.
    • It reads profiles, member_brands and brands with the service role, as spec §10 asks (the recipient filter runs on the server).
    • Another Account's brand counts for nobody.
    • It has the same pre-00388 fallback as PR 7: everyone counts as All brands.
  • Pagination: member_brands is read 1,000 rows a page (readAllRpcRows). It isn't read at all when nobody is Selected brands or the Account has no brand.
  • brandOutsiders(orgId, brandId): the members who can't see a brand. It shares memberReach with brandReaders.

Pulse and the AI Traffic digest (resolveRecipients(orgId, settings, brandId))

  • The default list is the members who can see the brand.
  • A hand-set list (by an Admin or Manager) keeps its addresses, except Account members who can't see that brand. Addresses outside the Account, such as a client or a team@ list, stay.
  • Pulse reads its recipients before it claims the day. A failed read writes no claim, so the catch-up sweep sends the day later, webhook included. Before this change, a transient error after the claim dropped that day's webhook.

The automatic audit e-mail

  • People are grouped by the set of brands they can see, and each group gets an e-mail listing only its brands. While everyone is All brands, that's one e-mail as today.
  • Nobody gets an e-mail about brands they can't see.

"Your first results are ready", once per person:

  • A person is claimed only when this run's brand is the first, among the real (non-demo) brands they can see, to have a stamped run. Ties go by brand id.
  • Why per person: 00385 didn't backfill existing members (first_results_emailed_at is null for anyone from before it). Today "the Account's first result" protects them.
  • With everyone All brands, a person's first brand is the Account's first brand, so the behaviour is today's: an existing customer adding a brand e-mails nobody.
  • A Selected-brands person gets it with their own first brand's first results, so nobody is skipped for good.
  • One known case, kept and covered by a test: a member from before 00385, narrowed to a newer brand only, gets it on that brand's first run. A backfill of the old members would close it, in its own PR.

Related issue

None. Brand-level access (spec BRAND-ACCESS), PR 8.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

Run cd server && npx vitest run src/lib/access.test.js src/lib/first-results-email.test.js src/lib/audit src/lib/pulse src/lib/traffic-digest.

access.test:

  • brandReaders for All brands, Admin, Selected brands with a grant, demo only, and another Account's brand;
  • no Account; read errors; the pre-00388 fallback;
  • 1,001 grants read in two pages;
  • brandOutsiders.

Recipients:

  • the default list;
  • a hand-set list drops a narrowed member and keeps an outside address; All brands keeps the list as is;
  • Pulse writes no claim on a failed read.

Automatic audit: one e-mail while everyone is All brands; three groups get three e-mails; someone without an e-mail is skipped.

First results:

  • today's behaviour;
  • an existing customer adding a brand e-mails nobody;
  • a Selected-brands person gets it later, on their own first brand;
  • ties go by brand id;
  • demo-only access;
  • claims released and kept;
  • a failed brandReaders claims nobody.

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/)
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR
  • Help article updated under help/ (or no user-visible change)

Server: npm run format:check (whole tree), npm run lint and the full suite pass (4,712 tests, 3 skipped). Web isn't touched.

Review: the pre-push review found no blocker. Its shoulds are fixed in 060fe48: Pulse dropping a day's webhook on a transient error, hand-set lists keeping narrowed members, and member_brands unpaged. Its smaller items are fixed too: the org filter on claims, deterministic ties, the comment, and tests.

Left for later

  • Daily suggestions (W2-24, feat(chat): pick one daily suggestion per person and brand each morning (W2-24) #1872): once it's on main, its job builds feeds only for the brands a person can see. A small follow-up.
  • Socket events (job-runner.js io.emit): spec §8, its own PR.
  • Assignees and agent notifications: web side, PR 9 and PR 11.
  • Pulse settings page (web/src/app/api/settings/pulse/route.ts): it shows every brand's recipients to every member. That belongs to PR 11.

🤖 Generated with Claude Code

cihan-gyk and others added 13 commits October 31, 2026 01:39
… and access helpers (00388)

BRAND-ACCESS PR 1 of 16: the data and the rule, no behaviour change.
Everyone starts with All brands, and no policy reads it yet.

- profiles.brand_scope ('all' | 'selected', default 'all'), set by the
  server: 00374's guard refuses a person's own change; admins are always
  'all' (a check, and a reset on promotion); leaving the organization
  resets it to 'all'. A move straight into another organization keeps the
  scope the update gives, so it never widens access by itself.
- member_brands (organization, person, brand, granted_by, granted_at),
  one row per person and brand, gone with the brand, the person or the
  organization; a trigger keeps the brand and the person in the row's
  organization. The person reads their own rows, admins the
  organization's; only the server writes. The rows go when the person
  moves, leaves or gets All brands.
- invitations.brand_scope / brand_ids, checked against the organization.
- public.can_access_brand(brand, person default auth.uid()) and
  public.user_brand_ids(): STABLE, SECURITY DEFINER, empty search path,
  for authenticated and service_role only. Admin, All brands, a shared
  brand or the demo brand, in the person's organization; another
  person's id only for the service role.
- A brand added by a Selected-brands person is shared with them (after
  insert trigger).
- web types, and member_brands on the demo coverage's skipped list.
- server/src/lib/brand-access-schema.test.js reads the migration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…and access (00389)

BRAND-ACCESS PR 2 of 16, on top of 00388. Nothing changes while
everyone has All brands: for them each policy passes exactly the rows
it passed before.

- brands select: All-brands people (admins included) still match on the
  row's own organization_id, so a brand being added reads back
  (insert ... returning checks the select policy before the row is
  stored; a lookup by id such as can_access_brand(id) would refuse every
  new brand). Selected-brands people match on user_brand_ids().
- brands update and delete keep their role checks and add
  `id in (select public.user_brand_ids())`. Insert is unchanged.
- The helper runs once per query (an uncorrelated hashed SubPlan); the
  three policies are to authenticated, since anon may not run it.
- Every brand table's policy that reads its brand through brands
  narrows with this. server/src/lib/brand-access-policies.test.js fails
  on a brand table whose client policy neither reads brands nor calls
  the access rule; the 12 tables PR 3 fixes and the 16 server-only ones
  are listed there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…within brand access (00390, 00424)

BRAND-ACCESS PR 3 of 16, on top of 00389. Nothing changes while everyone
has All brands: each rewritten policy is the old one plus the brand
condition, and passes the rows it passed before.

- 00390, the Account's brand tables: prompt_usage_counters,
  content_draft_deliveries and the old Agent's agent_conversations (and
  agent_messages through it) are read only within brand access; the
  organization and person checks stay.
- content_draft_member() asks can_access_brand about the draft's brand,
  so its ten policies (now to authenticated) and three functions follow.
- Plan quotas count the whole Account: org_prompt_location_usage and
  prompt_usage_summary are security definer with a membership or brand
  check; brands the caller can't access come back as one row with no
  brand id. New org_brand_count() for maxBrands, used by createBrand and
  the Brands page (web lib/plan-brand-count.ts, which falls back to the
  old count until the migration is on the database).
- invitations: only admins read them (brand_ids). Settings > Team lists
  the pending ones from the server, without the token or the brands.
- member_brands' check locks the person's profile (for share).
- 00424, Chat's brand tables, after 00400-00422 that create them (in
  00390 a fresh install would fail, and their own policies would win):
  chat_conversations (own, shared, agent run), chat_agent_runs,
  chat_why_analyses, chat_files, chat_activity_log, chat_access_requests,
  ship_events, chat_suggestion_feeds, chat_suggestions. A row with no
  brand stays as it was; an own chat about a hidden brand is hidden, not
  deleted.
- brand-access-policies.test.js: every top-level OR branch ties brand_id
  to brands or the access rule; tables without brand_id reach a brand
  through the row they belong to, or are listed as Account-level with
  why; no policy statement hidden in a $$ body; access-rule policies for
  authenticated only; no policy before its table. Each check was seen to
  fail on deliberately broken temporary migrations, since deleted.
- brand-access-account-tables.test.js: each rewritten policy is its old
  rule plus the brand condition, for authenticated; the functions, the
  invitations policy and the lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…people (00390, 00424)

BRAND-ACCESS PR 3 review fixes. Nothing changes while everyone has All
brands.

- 00390 adds user_has_all_brands(): whether the caller is an admin or has
  All brands (stable, security definer, empty search path; authenticated
  and service_role only).
- 00424: a shared chat, an agent run's chat, an agent run and a filed file
  with no brand may hold any brand's data (a chat with no brand lets each
  tool call pick its own), so only All-brands people read someone else's:
  `brand_id in (select public.user_brand_ids()) or (brand_id is null and
  (select public.user_has_all_brands()))`. The person's own rows with no
  brand stay theirs: their own chat, Chat changes, access requests and old
  Agent chats (with the admins').
- 00390's header notes the one change for All-brands people: someone who
  moved organization no longer reads their old organization's branded
  Agent chats (agent_conversations never checked the organization).
- Coverage test: `brand_id is null` binds only with user_has_all_brands()
  in the same branch, or on the listed own-row policies, each with why; a
  subquery with union, intersect or except, and an `exists` tying brands to
  another table's brand_id, no longer bind. chat_agents (and its versions
  and triggers, PR 9) and integration_connections (PR 14) move to a
  DEFERRED list that must be empty once code writes member_brands or
  brand_scope (PR 12). Each new rule was seen to fail on deliberately broken
  temporary files, since deleted.
- plan-brand-count falls back to the old count only when org_brand_count
  is missing (PGRST202, 42883) and throws on any other error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ion (brand access PR 7)

assertBrandAccess follows the database's can_access_brand (00388): within
the organization, All brands reaches every brand, Selected brands only the
ones granted (member_brands), an Admin and the demo brand always. Another
organization's brand stays 403 not_in_workspace; one not granted is 403
no_brand_access. The caller's organization, role and scope are read once
per /api request (lib/request-scope.js). The opportunity and prompt checks
follow it, the six hand-written copies in prompts, tracking and content
use it, and the Google property lists take ?brandId= (without one they
need All brands). Everyone has All brands today, so nothing changes yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ore 00388, and end the request cache with the response (brand access PR 7)

- The prompt suggestion and Improve routes, the Google integration routes
  and Action Center's catches pass the refusal's code on (not_in_workspace,
  no_brand_access, forbidden): their 403 used to be the bare "Unauthorized"
  the web read as another workspace's brand (BUG-001). Catalog keeps an
  access refusal's own code instead of calling it a role's. The web reads
  no_brand_access as 'workspace' too: switch to one of your brands.
- Before 00388 there is no profiles.brand_scope: on 42703 or PGRST204 the
  profile is read without it, everyone counts as All brands, and that is
  logged once (the code and the migration, no person).
- The request's store closes when its response finishes or its connection
  closes, so a job the request leaves running reads afresh from then on.
- The Google property lists always need All brands until each brand has its
  own connection (PR 14): the list is the whole organization's, and naming
  the demo brand opened it. A sync of every brand needs All brands too.
- A failed brand read is a failure (500), not "Brand not found"; an id that
  isn't a uuid stays 404. A caller without an organization reaches no brand
  (403 not_in_workspace), so /:id/brief's own check for one goes. Grants are
  read within the person's organization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…manager can add one

createBrand chooses the brand's id, inserts without asking for the row
back, then reads it by id. Under 00389 a Selected-brands person sees a new
brand only once the creator grant (00388, after insert) has shared it, and
insert ... returning is checked against the select policy before that, so
Add brand failed for them. 00389's comment now says so.
# Conflicts:
#	web/src/lib/actions/brand.test.ts
…brand access PR 8)

brandReaders(orgId, brandIds) gives the organization's people the brands
each may reach, by PR 7's rule (an Admin, All brands, the demo brand or a
grant) and its 00388 fallback, read from the tables as the service role,
since can_access_brand answers for another person only with that JWT.

- Daily Pulse and the AI Traffic digest: an Admin's typed recipients as
  typed; by default the members who can see the brand.
- The auto-audit e-mail: one per set of brands people see, each listing
  only those; with All brands, the one e-mail as before.
- "Your first results are ready": each person's own first results, when
  this run is the earliest stamped run of the real brands they see, once
  per person. 00385 never stamped the people who had results before it,
  so the earliest run, not the stamp, keeps an existing workspace's
  people from being told a new brand is their first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mbers from set lists, page grants (brand access PR 8)

- Pulse reads its recipients before it claims the day, so a failed read
  leaves the pulse to the catch-up sweep instead of losing its webhook.
- A set recipient list (Pulse, AI Traffic digest) drops the members who
  can't see the brand; addresses that are no member's stay.
- member_brands is read page by page; brandOutsiders names who can't see
  a brand.
- The first-results claim keeps to the organization; ids compare without
  localeCompare.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 31, 2026
- PUT /api/audits/settings: the auto-audit switch and the e-mail after a
  run are the organization's, for every brand, so changing them needs All
  brands. A brand's own exclude patterns still only need that brand. The
  refusal keeps its code.
- GET /api/billing/ai-usage/draft/:draftId: a page's share of the AI
  budget is read only by someone who reaches the page's brand.
- The MCP key's mark-published path: the key's user must reach the draft's
  brand; a brand they weren't given reads as not there.
…rand recipients (brand access PR 8)

brandReaders and brandOutsiders read the organization's profiles in one
request, which PostgREST caps at 1000 rows: past that, people were dropped
without an error, and a Selected-brands person among them was not named an
outsider, so an explicit Pulse list kept their address. The read now pages
(readAllRpcRows), ordered by id, and keeps the pre-00388 fallback.
gkhngyk
gkhngyk previously approved these changes Oct 31, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving, with 1 fix on top: commit e273bd0, which is this PR's head + the fixed #1888 branch (a2f431f, merged in cleanly) + one commit.

Fix

  • brandReaders / brandOutsiders read the organization's profiles in a single request, which PostgREST caps at 1000 rows without an error. Past that, people were dropped: as readers they just got no e-mail, but as outsiders a Selected-brands person beyond row 1000 kept their address on an explicit Pulse / AI Traffic list. The profiles read now pages through readAllRpcRows, ordered by id, and the pre-00388 fallback still works. Test: an organization of 1001 people with the narrowed one last (fails without the fix, since the test mock now drops rows past 1000 like PostgREST does).

Checked, fine

  • memberReach follows can_access_brand exactly: Admin, brand_scope = 'all' (the column is not null and checked, so !== 'selected' is the same thing), the demo brand, or a grant. Brands are read within the organization, so another organization's brand counts for nobody; grants are read within the organization and for those brands, page by page.
  • Senders: Daily Pulse, AI Traffic digest, auto-audit mail and first-results mail are all narrowed by brand. The health report (env list) and cancel feedback (the team's address) are org-wide or internal and correctly left alone. Nothing in web/ sends mail.
  • When the read fails, nobody gets mail. Pulse resolves recipients before the claim, so the catch-up sweep sends it later. The digest gives the week's claim back. Auto-audit and first-results log the error and send nothing. Nothing quietly falls back to mailing everyone.
  • Explicit recipient lists keep non-member addresses and drop only the people who can't see the brand. Frequency and digest switches are checked as before.
  • The PR's own changes are these 11 server files; nothing unrelated.

Follow-ups (not blocking)

  • The address lookup (getUserById) is still one call per recipient, as before. Worth batching once organizations get large.
  • First results now runs one tracking_runs read per real brand, in parallel. Fine at today's brand counts, but an RPC for each brand's first stamp would make it a single query.
  • When an auto-audit mail fails on the recipient read, the run is already marked finished and the mail isn't tried again.

Tests: full server suite 339 files / 4716 passed; eslint src clean; prettier clean on touched files.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merging in order with the other approved PRs. This head merges current main; its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build.

@gkhngyk
gkhngyk merged commit 26093d4 into ansvisor:main Oct 31, 2026
4 of 5 checks passed
@github-actions github-actions Bot removed the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants