Skip to content

feat(server): let internal requests act as a member on allowed routes, checked like a session - #1949

Merged
gkhngyk merged 3 commits into
ansvisor:mainfrom
cihan-gyk:feat/server-internal-acting-user
Nov 1, 2026
Merged

gkhngyk merged 3 commits into
ansvisor:mainfrom
cihan-gyk:feat/server-internal-acting-user

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

The API server can now take a request from the web app on behalf of a member, on seven allow-listed routes. This is for Chat's triggered agent runs: the minute tick and signals have no cookie session, so their writes need another way in. Step 2 of the owner's two-step fix for session-free agent writes (2026-11-01). Server only; nothing calls it yet. The web side that sends these requests is a separate PR. No migration.

How it works (server/src/middleware/acting-user.js)

  • decodeToken first checks whether the request carries Authorization: Bearer <CHAT_ACTING_SECRET>, compared in constant time. If not, the existing token path runs unchanged.
  • With the secret, the request must also pass, in order:
    1. the route is on the allow list;
    2. X-Acting-User is a valid uuid;
    3. Chat is on for the deployment;
    4. the person exists and isn't banned (auth.admin.getUserById);
    5. they belong to an organization (brandAccessOf);
    6. Chat is on for that organization (chatAgenticEnabled);
    7. they can access the brand the request names (assertBrandAccess, service role).
  • When all pass, req.user is that person. The demo brand guard, the plan checks and each route's own brand and role checks (assertRole, MANAGER_ROLES) then run as for a normal session. An analyst still gets the route's 403.
  • Allow list (ACTING_USER_ROUTES), 7 routes:
    • PATCH /content/:id/status
    • POST /prompts/suggestions/:id/dismiss
    • POST /action-center/chat-actions/check
    • POST /action-center/chat-actions
    • POST /audits
    • POST /audits/bulk
    • POST /reports/summary
  • Where each route names its brand (body or the row in the path) comes from the demo brand guard's existing list (DEMO_GUARDED, demoRouteFor, brandsNamedBy). demo-brand.js only exports TooManyIds for this.

Safety

  • The secret is its own: CHAT_ACTING_SECRET, not CHAT_INTERNAL_SECRET. The server sends that one to the web app every minute, so it could leak through a misconfigured PUBLIC_APP_URL; a leak shouldn't also allow writes as members.
  • A secret shorter than 32 characters, or none, keeps the path closed.
  • With the secret on a route that isn't allowed: 401. The secret is never sent to Supabase Auth or written to logs (tested). Logs show the person as actingFor, with one info line per accepted request.
  • X-Acting-User with a normal session token does nothing: the identity comes from the token.
  • Every failure rejects the request (fail-closed): a lookup error is a 500 or 401, never next().
  • Rate limit: each accepted secret + person pair counts in that person's own user:<id> bucket. The secret alone, or a rejected person, gets no bucket.

For the web PR: X-Acting-User must always come from the run's or agent's owner in the database (agent.row.owner_id), never from the model's tool input or a request body.

New env var: CHAT_ACTING_SECRET (server and web, the same value, at least 32 characters). Empty lines with a comment are added to server/.env.example and web/.env.example, plus docs/self-host/env-variables.mdx. Prod needs it set on both (gkhngyk) once the web PR lands.

Left for separate PRs (from the pre-push security review):

  • A percent-encoded id in the path (%34a…) skips the demo brand guard's brand lookup. This already happens on main for normal sessions. The routes' own access checks still stop cross-organization writes. A fix/ PR will decode path params in demo-brand.js.
  • A token that isn't JWT-shaped still goes to auth.getUser.

Related issue

None. Follow-up to the agent runs review (owner decision 2026-11-01, "İkisi de, sırayla").

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

  1. Set CHAT_ACTING_SECRET (32+ characters) and CHAT_AGENTIC=true on the server.
  2. POST /api/reports/summary with Authorization: Bearer <secret>, X-Acting-User: <a member's id> and a brand of theirs. It runs as that member.
  3. Each of these is rejected:
    • another organization's brand;
    • a brand outside their Selected brands;
    • a route outside the list;
    • a wrong or short secret.
  4. Unit tests (acting-user.test.js) cover:
    • every allowed route and each rejection above;
    • a banned or unknown person, and Chat off;
    • lookup errors, a foreign brand inside a brandId array, and too many ids;
    • logs and the rate limit;
    • an end-to-end run through /api, where a manager passes and an analyst gets the route's 403.

Checklist

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

CI passed on this branch (fd2d63e), run on the fork (https://github.com/cihan-gyk/ansvisor/actions/runs/41332943891): schema is up to date; web format:check, lint, typecheck, all tests and yarn build pass; server lint, format:check and all tests pass.

🤖 Generated with Claude Code

cihan-gyk and others added 3 commits November 1, 2026 19:37
…, checked like a session

A Chat run that an agent's trigger starts has no one's session, so the
web's writes through this API (an opportunity's status, a dismissed
prompt suggestion, Send to Action Center and its duplicate check, Site
Audit, a report's summary) fail today: they send the person's session
token, and there is none.

decodeToken now takes a second identity (middleware/acting-user.js): a
request carrying CHAT_INTERNAL_SECRET as its bearer and
X-Acting-User: <member id> is known as that member. The member must
exist and be able to sign in, belong to an organization with the new
Chat on, and reach the brand the request names (lib/access.js, read as
the service role). req.user is theirs, so the demo brand's check, the
plan's and each route's own brand access and role checks run unchanged.

- Only the seven routes of ACTING_USER_ROUTES take it; each is a
  DEMO_GUARDED route, whose entry says where it names its brand. On any
  other route the secret is refused (401) and never sent to Supabase
  Auth. Without the secret, X-Acting-User is ignored; with
  CHAT_INTERNAL_SECRET unset, the way is closed.
- The member is logged as actingFor; the secret never is.
- Once checked, the request counts in the member's own rate-limit
  bucket, the same as their session's.
- server/.env.example and the self-host env docs describe the new use.

The web side (the tools sending these headers when there is no session)
is a separate change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…at least 32 characters, with Chat checked first

Security review of the acting path:

- A separate CHAT_ACTING_SECRET for the web's requests to this API.
  CHAT_INTERNAL_SECRET stays the server's secret to the web, so a leak
  of either opens one way only. server/.env.example, web/.env.example
  (described empty line, no code yet) and the self-host env docs list it.
- A CHAT_ACTING_SECRET shorter than 32 characters closes the way (401,
  logged) instead of being taken silently; it is still never sent to
  Supabase Auth.
- With the new Chat off on the deployment, the request is refused
  (403 chat_off) before anyone is read: no getUserById, no profile.
- Tests for the new name (CHAT_INTERNAL_SECRET never opens it), the
  length floor, the Chat-off order, a failed read (auth, profile, brand,
  the named row) answering 500 without passing, a list of brands in the
  body with one of another workspace, and more ids than MAX_IDS (400).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Nov 1, 2026

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit fd2d63e.

Approve preview

@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.

LGTM

@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.

LGTM

@gkhngyk
gkhngyk merged commit bcd25b8 into ansvisor:main Nov 1, 2026
7 checks passed
gkhngyk pushed a commit that referenced this pull request Nov 2, 2026
…demo brand guard (#1963)

* fix(server): read a percent-encoded path id as the route does in the demo brand guard

Express hands a route its params decoded, while the demo brand guard read
them raw: /content/%34a0…/brief named no id the guard knew, so a session
could start a write on the demo brand. The guard now decodes path params
the same way, and answers 400 to one that isn't valid percent-encoding, as
Express does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(server): refuse a badly encoded path id on the acting-member path too

The acting-member check (#1949) reads the brand through the demo brand
guard's `brandsNamedBy`, which now throws BadPathParam for a path param that
isn't valid percent-encoding. Answer 400 "Invalid path" there as well,
instead of a 500. Test: an encoded row id is read as the route reads it
(another workspace's brand is refused), and a bad one is a 400.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
gkhngyk pushed a commit that referenced this pull request Nov 2, 2026
…a stray acting header to Supabase Auth (#1974)

Review follow-ups (D-1, D-4) for internal requests acting as a member
(#1949):

- ACTING_USER_ROUTES keeps only the routes the web writes through for a
  run with no session: an opportunity's status, a dismissed prompt
  suggestion, and Send to Action Center with its duplicate check. Site
  Audit's starts (POST /audits, /audits/bulk) and a report's summary
  (POST /reports/summary) leave it: their Chat changes always wait on the
  person's card, whose Approve runs with their session. Least privilege:
  the secret now answers 401 there.
- decodeToken refuses a request carrying X-Acting-User without the
  acting secret (401) before anything reaches Supabase Auth, so a web
  whose CHAT_ACTING_SECRET differs from this server's never sends its
  secret to getUser as a token. It is logged without the secret.
- server/.env.example and the self-host env docs name the routes and the
  refusal.

Tests: the three routes are refused with the secret and nothing is read;
X-Acting-User with a session's token or a wrong secret is refused before
getUser or getUserById; a session without the header still passes. The
default request is now Send to Action Center.

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
gkhngyk added a commit that referenced this pull request Nov 2, 2026
…session is behind it (#1973)

* feat(chat): let a run with no session make a session-free change as its person

An agent run that the minute tick or a signal started (or that another
person's Run now picked up) has no session of its person behind it, so
#1946 turned every change it would make by itself into a card. The draft
rows already have their own writers for such a run (#1959: create_draft
and update_draft runFor, checked as the run's person with the service
role); this wires the engine to them.

- engine.ts: askWithoutSession leaves a sessionFree row's decision as the
  precedence made it, read for the run's person like any call's (role,
  excludeRoles, plan, policy, mode, demo brand, brand scope): Full auto,
  an Admin's Always or the person's tick run it; Ask me first still shows
  the card. Every other row still asks first, with the no-session note.
- write.ts: runLoggedWrite takes withoutSession and runs the row's runFor
  instead of run, with the same idempotency key, Activity log row and
  Undo window. A row without runFor refuses before anything runs.
- The person is always the run's (the tool context the engine builds from
  the run's row), never the model's input. A card's Approve still runs in
  its person's own request, with their session.

Tests: Full auto makes the draft with no card through createContentDraftFor,
logged as the run's person's with Undo (and undone); Ask me first still
asks and the owner's Approve uses their session; a row without runFor
still asks; a Manager made an Analyst mid-run is refused update_draft
(forbidden_role) and an Analyst's run never gets it; the owner's own Run
now still uses their session; runLoggedWrite runs runFor for both draft
rows, once per approval, and refuses a row without it.

Help article updated (help/chat/agents.md: "When a run asks before a change").

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(chat): write through the API server as the run's person when no session is behind it

A run an agent's trigger starts has no session of its person, so its
writes through the API server (an opportunity's status, a dismissed prompt
suggestion, Send to Action Center and its duplicate check, Site Audit)
asked first on a card (#1946). The server takes such writes as a member
since #1949 (CHAT_ACTING_SECRET + X-Acting-User, on seven routes); this is
the web's side.

- lib/chat/actor/api.ts: apiAs sends a request as the run's person: their
  own session's token in their own request, else the acting secret with
  X-Acting-User naming them, never another person's session. The person
  is the run's (the tool context the engine builds from the run's row),
  never the model's input. With CHAT_ACTING_SECRET unset or shorter than
  32 characters the way is closed (actingOpen) and nothing is sent. A 401
  or 403 chat_off on the acting way comes back as a value in the person's
  words (acting_refused, chat_off: chatEngine.acting in en.json), which
  the engine says on the step and to the model.
- lib/chat/actor/api-writes.ts and action-center.ts:
  updateOpportunityStatusFor, dismissSuggestionFor, startSiteAuditsFor,
  createChatActionFor and checkChatActionCoverFor, with what the
  session's action checks first done as the person (isManagerFor,
  assertWritableFor, the chat being theirs for History's place).
- Their requests and the reading of the answers move out of the 'use
  server' modules, unchanged, so both ways share them:
  lib/action-center/chat-send.ts (Send to Action Center) and
  lib/audit/start-answer.ts (Site Audit's start).
- Registry: update_opportunity, dismiss_prompt_suggestion, create_action
  and run_site_audit are sessionFree with runFor and runForOpen: actingOpen;
  create_action has precheckFor, so its duplicate is checked as the run's
  person before any card. defineTool keeps runForOpen and precheckFor to
  session-free rows; runsWithoutSession says whether a row runs now.
- Engine: askWithoutSession and runLoggedWrite use runsWithoutSession, so
  with the way closed these rows ask first as before; precheckOf uses
  precheckFor in a run with no session. Every change still goes through
  the precedence as the run's person (role, excludeRoles, plan, policy,
  mode); run_site_audit keeps its card in every mode, so its runFor isn't
  reached yet.
- build_report stays as it is: its report reads fourteen sections with
  the person's session before the summary, so it still asks first.
- web/.env.example and the self-host env docs say what the web sends and
  that, unset, those changes ask first.

Help article updated (help/chat/agents.md: "When a run asks before a change").

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(chat): decide an agent run's change in the mode it has now

Review follow-ups (D-3, D-6) for the session-free engine:

- An agent run's change is decided in the mode the run has now, read
  fresh at each change (agentModeNow): the mode it started in, or the
  agent's own mode when it was set lower since, and Ask me first once an
  Admin turned Full auto off for agents (chat_settings.agents_full_auto)
  under a run that started in it. What can't be read asks first. So a
  session-free row no longer runs by itself after the owner set the agent
  to Ask me first, or the Admin turned Full auto off, mid-run. A person's
  own chat keeps its mode; reads are not affected.
- Engine tests for the session-free path with an Admin's Never (not
  offered, nothing made) and Ask (its card in Full auto), "Full auto for
  members" off (an Analyst's Full auto asks, an Admin's runs), and the
  agent run's mode now: still Full auto runs, Full auto off for agents or
  the agent set to Ask me first mid-run asks, an unreadable agent asks.

Help article updated (help/chat/agents.md: "When a run asks before a change").

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(chat): act as the run's person with the secret only, and ask when the server takes no one

Review follow-ups (O-1, D-2, D-4, D-5, D-6) for the writes through the
API server for a run with no session:

- apiAs always sends CHAT_ACTING_SECRET with X-Acting-User naming the
  run's person, and never reads a session or a cookie: the engine calls
  runFor only when no session of the person is behind the run. A 401 is
  said once as a warning (a setup to fix), never with the secret.
- precheckOf: in a run with no session only the row's precheckFor
  checks, and only while its way is open; with the way closed nothing is
  checked before the card (a request's session there isn't the person's),
  and the change checks again on approval. An acting refusal in Send to
  Action Center's duplicate check is no longer logged as an error.
- When the server takes no one to act as (acting_refused: the web's and
  the server's secrets differ), the change is no longer a failed step: it
  waits on its card with the no-session note, its step no longer marked
  as made by itself, and the owner's Approve makes it with their session
  on the same approval (runLoggedWrite gives the idempotency key back for
  such a refusal). chat_off still ends the step with its words.
- run_site_audit leaves the session-free rows: its card in every mode
  means its runFor is never reached. startSiteAuditsFor, the shared
  lib/audit/start-answer.ts and the audits.ts change are gone; audits.ts
  and audit-tools.ts are as on main.
- web/.env.example and the self-host env docs say which writes use the
  secret and what a value that differs from the server's does.

Tests: apiAs never reads a session and always names the run's person; the
401 warning; acting_refused turns into the card and the owner's Approve
makes it once, logged as approved; Send to Action Center in the owner's
own request uses precheck and createChatAction, never the run's-person
ones; with the way closed nothing is checked before the card.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Gökhan Geyik <[email protected]>
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