Settings (SECU-73, SECU-74, SECU-122, SECU-123, SECU-134)
The platform operator uses Settings in the admin app. Team ownership does not grant platform administration. Every Settings route requires a live user session and user.platformRole = 'admin': PlatformAdminGuard (admin/platformAdmin.guard.ts, @PlatformAdminOnly() on the /v1/settings controller) reads it from the database on every request (no user → 401 UNAUTHORIZED, not an administrator → 403 FORBIDDEN). Grant or revoke it for a verified operator with api/scripts/platformAdmin.mjs (cd api && DATABASE_URL=… bun run platform-admin grant|revoke <email>; it needs the dev dependencies, so run it from a checkout, not inside the production image). The CLI is the path for the first administrator and for recovery, and it writes no journal row. An administrator can also grant or revoke it on the admin app's Users page (PUT /v1/admin/users/:userId/platform-role, SECU-118), which writes admin.user.platform_role.grant|revoke to the Audit log and refuses one's own revoke (409 CANNOT_TARGET_SELF) and the last active administrator (409 LAST_PLATFORM_ADMIN). The role is never accepted from registration, a JWT claim, a team role or a Settings request. The same guard covers every /v1/admin/* route (SECU-117). The admin app shows its «No access» screen instead of the menu when the signed-in user (login, GET /v1/auth/me) has another platformRole or any /v1/settings or /v1/admin/* call answers 403 FORBIDDEN; the API still decides.
Contract: specs/008-agentfy-contract (contracts/settings-rest.md, contracts/agentfy-connection.md, data-model.md); the connector/connections group: specs/016-admin-console/contracts/admin-api.md §11; the five product parameter groups (SECU-123): specs/018-product-settings (contracts/setting-field.md, contracts/settings-rest.md, data-model.md); the three billing groups (SECU-134): specs/017-billing.
Boundaries
setup/settingis the generic engine:SettingModule.forRoot([...groups])registers group definitions (tokenSETTING_GROUPS);SettingServicereads, writes, seals and audits. It knows nothing about Agentfy.- Groups are registered in
app.module.tsasSettingModule.forRoot([AGENTFY_SETTING, CONNECTOR_CONNECTIONS_SETTING, CONNECTOR_COPY_SETTING, AUTH_LOGIN_SETTING, AUTH_SESSION_SETTING, MAIL_SENDER_SETTING, MAIL_TRANSPORT_SETTING, JOB_QUEUE_SETTING, BILLING_PAYPAL_SETTING, PAYPAL_SANDBOX_SETTING, PAYPAL_LIVE_SETTING]), each defined in the slice that owns it. Field types arestring,url,enum,secret,boolean,list(an array of strings;falseand[]are values, the default applies only when a value is missing) andnumber(SECU-123). A group may settoggleable: false(no Enable/Disable),envFallback: true(below, «Storage and sources») and anormalise(data)that runs beforevalidateon save and import. - A
numberfield is a whole number stored as a JSON number, in the unit of its env name (unit:count,bytes,ms,seconds), withmin, an optionalmaxand an optionalminOf(env)(a bound from an env-only value; the effective min is the larger of the two). Defaults and bounds come from one constant per name,ENV_NUMBERS(setup/config/envNumbers.ts), whichenvSchemauses too, so the form, a save and the environment agree.displayUnit(MiB,GiB,seconds,minutes,hours,days, …) is only how the admin shows it;restartRequiredmarks a value read once at start (no field has it today). A save takes only a JSON number; anything else, a fraction, an unsafe integer or a value out of bounds → 400SETTING_INVALID{<field>: 'Must be a whole number.'}or'Must be a whole number from <min> to <max>.'(withoutmax:'… of at least <min>.'). Import parses the variable byenvSchema's rule; unset → the field default. setup/agentfy/settingdefinesagent/agentfy(AGENTFY_SETTING: fields,reconnectFields,validate,fromEnv).connector/settingdefinesconnector/connections(CONNECTOR_CONNECTIONS_SETTING): where customer site connections may go. The connector's destination check reads it from the in-memory snapshot on every connection (SettingService.current('connector', 'connections')), neverprocess.env.setup/agentfy/connection.tsturns the group intoIAgentfyConnection. Every consumer (provisioning, server chat,/mcp, grants, the project chat and agent) readscurrentConnection(); nothing else readsprocess.env.AGENTFY_*orMCP_PUBLIC_URL.AGENTFY_CHAT_RECONCILEstays a process test switch, not a setting.admin/setting, the last CleanSlice group, owns the REST routes, the platform administrator check, reconnection and the append-onlysetting_audit.
The agent/agentfy group
Eight fields, in this order. The env name is the source outside production and for Import from environment.
| Field | Type | Env | Notes |
|---|---|---|---|
mode | enum off | fake | organization, default off | AGENTFY_INTEGRATION_MODE | fake is refused in production |
apiUrl | url | AGENTFY_URL | origin only; HTTPS, or loopback HTTP outside production |
organizationId | string | AGENTFY_ORG_ID | A-Z a-z 0-9 . _ : -, 1–128 |
environment | enum test | production, default test | AGENTFY_ORG_ENVIRONMENT | must match the keys |
provisioningKey | secret | AGENTFY_ORG_KEY | orgk_…, required in organization |
serverChatKey | secret | AGENTFY_CHAT_KEY | orgk_…, differs from the provisioning key; optional |
mcpUrl | url | MCP_PUBLIC_URL | this API's public /mcp; required in fake and organization |
modelId | string, default empty | AGENTFY_MODEL_ID | ≤ 128; empty = the first model the organization policy allows |
reconnectFields: mode, apiUrl, organizationId, environment.
What follows from the connection:
- Chat is on by key. There is no chat switch (the SECU-67 switch variable is gone): chat works with an MCP URL and either
fakeororganizationwith aserverChatKey. Without a key the chat routes answer 503AGENTFY_CHAT_NOT_CONFIGURED. /mcpfollowsmcpUrl. It is served whilemcpUrlis non-empty, in any mode (alsooffand a disabled group), read on every request; empty → 404.modelIdis sent asprofile.modelIdwhen an agent is provisioned or its profile is updated in place. Changing it alone does not touch ready agents; they take it with the nextPROFILE_REVISION(docs/agentfy.md).- An invalid environment value fails closed. With the
envsource, a set value the group's rules refuse (the same rules as a save) makes the connectionoffwith no data at all:mcpUrlis empty, so/mcpanswers 404, and no grant is issued. The reason names the fields and their variables only, never the values (Invalid environment settings: mcpUrl (MCP_PUBLIC_URL).). With the modeoffor unset onlyMCP_PUBLIC_URLis checked, so a leftover unrelated variable does not close/mcp. - An incomplete or unreadable set makes the connection
offwith a reason shown in the form (state.reason); it never stops the API.
The connector/connections group (SECU-122)
Where customer site connections (FTP, FTPS, SFTP) may go. Not toggleable and nothing to reconnect.
| Field | Type | Env | Notes |
|---|---|---|---|
allowedHosts | list, default empty | CONNECTOR_ALLOWED_HOSTS (comma-separated) | exact host:port pairs; each is trimmed, lower-cased, an IPv6 address put in brackets ([2001:db8::1]:22), repeats dropped in first-seen order; an item that is not host:port → 400 SETTING_INVALID {allowedHosts: 'Not host:port: …'} |
allowlistEnabled | boolean, default true | — (import sets true) | label «Check the allowed hosts list» |
- The list on (
state.mode: on): only a listedhost:portis connected to. Any other answers the customer 422DESTINATION_NOT_LISTED(Host "<host:port>" is not in the allowed list; contact support; the env name is never mentioned); the app shows «Хост не в списке разрешённых, обратитесь в поддержку», an agent tool getsdestination_not_listed. - The list off (
state.mode: list_off): any publichost:portis allowed. The address check runs whatever the list says: the name is resolved once and every address is classified; loopback (except on the local stand,NODE_ENV=dev), private, link-local, cloud metadata, CGNAT, multicast and reserved addresses are always refused, as is a name that does not resolve, with the formerDESTINATION_NOT_ALLOWED(422). - Sources.
CONNECTOR_ALLOWED_HOSTSis only the import source. Outside production, with no stored row, the group reads it live (source: env); once a row exists the variable is not read. Production reads only the database: with no row the list is empty and checked, so every connection is refused until the operator imports or saves it. Import is offered in production too while the variable is set. A malformed variable still stops the API at start. - Save takes
{version, data: {allowedHosts?: string[], allowlistEnabled?: boolean}}; a value of the wrong type → 400SETTING_INVALID;enabledin the body → 400SETTING_INVALID{enabled}. Reconnect → 400SETTING_INVALID{reconnect}. Test makes no network call: it checks the stored list's format (checks.hosts:ok«N hosts in the list»,failed«Not host:port: …»,skippedwhen the list is off). - Check host.
POST /v1/settings/connector/connections/check-host{host: "name:port"}(or"[v6]:port") normalises the pair (nothost:port→ 400SETTING_INVALID{host}), resolves the name once with the connector's resolver and opens no connection. It answers{host, port, listed, allowlistEnabled, addresses: [{address, family, class}], verdict}, whereclassismetadata|loopback|private|link_local|cgnat|multicast|reservedor null andverdictis the first refusal a real connection would meet, in its order:not_listed(only while the list is on) →unresolved→internal→ elseallowed. It writes no journal row.
Changes take effect within SETTINGS_REFRESH_MS (below), without a restart. In the admin app the group is the Connections section of Settings (Security in the section menu; Agentfy, under Integrations, shows agent/agentfy): the host list as rows with their check-host status, the checkbox with a warning when it is cleared, Save, Import from environment, Test, the Check host panel and Changes; no Disable and no Reconnect. The section menu, the mobile section list at /settings and Agentfy's /settings/agentfy are SECU-143 (specs/016-admin-console/settings-layout.md).
Product parameter groups (SECU-123)
Five groups move product limits and lifetimes from the environment into Settings, one admin Settings section each. Common to all five:
toggleable: false(no Enable/Disable), no reconnect fields (Reconnect → 400SETTING_INVALID{reconnect}),envFallback: true(production without a row reads env, «Storage and sources»).- Every consumer reads the group from the in-memory snapshot on every request or call, so a save takes effect within
SETTINGS_REFRESH_MSwithout a restart. In a stored row, a missing field takes the field default; a stored number that is not a safe integer within its bounds (for example after a bound changed) is ignored for the EnvService value and logged once per field and row version assetting.value_out_of_bounds(group, code and field, no value). - Test makes no network call and writes no values:
checks.valuesisokwhen the current set passes the bounds and the group's rules, elsefailedwith the field labels and the rule broken. Import from environment works as for every group (production included while a variable is set).
connector/copy — section «Копия сайта» (/settings/copy)
| Field | Env | Default | Bounds | Shown in |
|---|---|---|---|---|
maxFiles | MAX_FILES | 100000 | ≥ 1 | count |
maxFileSizeBytes | MAX_FILE_SIZE | 104857600 (100 MiB) | ≥ 1 | MiB |
maxTotalSizeBytes | MAX_TOTAL_SIZE | 10737418240 (10 GiB) | ≥ 1 | GiB |
connectionTimeoutMs | CONNECTION_TIMEOUT_MS | 15000 | ≥ 1 | seconds |
snapshotReconcileAfterSeconds | SNAPSHOT_RECONCILE_AFTER_SECONDS | 3600 | more than AUDIT_TIMEOUT_MS/1000 + 300 (≥ 1201 at the default 900000), ≤ 2592000 (30 days) | minutes |
The connector reads the limits on every connection and the scan reads the file limit on every scan; the reconcile deadline is read per call by checks, the queue sweep (each tick) and the admin Sites and Checks pages. AUDIT_TIMEOUT_MS stays env-only.
auth/login — section «Безопасность входа» (/settings/login)
| Field | Env | Default | Bounds | Shown in |
|---|---|---|---|---|
rateLimitLimit | RATE_LIMIT_LIMIT | 120 | ≥ 1 | count |
rateLimitTtlMs | RATE_LIMIT_TTL_MS | 60000 | ≥ 1 | seconds |
maxFailuresPerIp | AUTH_MAX_FAILURES_PER_IP | 50 | ≥ 1 | count |
maxFailuresPerLogin | AUTH_MAX_FAILURES_PER_LOGIN | 10 | ≥ 1 | count |
loginWindowMs | AUTH_LOGIN_WINDOW_MS | 900000 | ≥ 1 | minutes |
maxVerifyMailsPerHour | AUTH_MAX_VERIFY_MAILS_PER_HOUR | 5 | ≥ 1 | count |
The global rate limit reads it on every request, the failed sign-in counter and the verification letter cap per call (the cap counts the sign-up letter and every «Отправить ещё раз» of POST /v1/auth/verify-email/resend, SECU-180). Too low a request limit also locks out the admin app.
auth/session — section «Сессии» (/settings/sessions)
| Field | Env | Default | Bounds | Shown in |
|---|---|---|---|---|
sessionIdleMs | AUTH_SESSION_IDLE_MS | 259200000 (72 h) | ≥ 1 | hours |
passwordResetTtlMs | AUTH_PASSWORD_RESET_TTL_MS | 3600000 (1 h) | ≥ 1 | minutes |
verifyEmailTtlMs | AUTH_VERIFY_EMAIL_TTL_MS | 86400000 (24 h) | ≥ 1 | hours |
accessTokenTtlSeconds | JWT_ACCESS_TTL | 900 (15m) | ≥ 1 | minutes |
refreshTokenTtlSeconds | JWT_REFRESH_TTL | 2592000 (30d) | ≥ 1 | days |
recentAuthWindowMs | AUTH_RECENT_AUTH_WINDOW_MS | 3600000 (60 min) | ≥ 60000 | minutes |
The two JWT names are durations in env (15m, 30d) and whole seconds in the setting; import and the env value both round up to a whole second. refreshTokenTtlSeconds is the absolute session lifetime: a new value applies to sessions created after it, an open session keeps the end it got at sign-in. The password reset letter states the lifetime in effect. Production on App Platform sets JWT_REFRESH_TTL=14d (.do/app.yaml), so without a row the field shows 14 days from env. AUTH_SESSION_TOUCH_MS stays env-only.
recentAuthWindowMs (SECU-158) is the recent sign-in window: how long after the password was entered an owner or administrator may issue or revoke API keys, save or revoke a connection's secret or folder, and offer an ownership transfer or close the team without entering it again. It is read on every request, so a saved value applies to the next call with no restart. Reading the key list or a connection's folders never needs it. Past the window the API answers 403 REAUTHENTICATION_REQUIRED; the app then shows the password card for that one action and repeats it once the password is confirmed (a new sign-in, there is no separate re-authentication route).
mail/sender — section «Почта» (/settings/mail)
One string field, from (env MAIL_FROM, default empty, required on save): addr@host or Name <addr@host>, at most 320 characters, else 400 SETTING_INVALID {from}. Every letter reads it when sent; an empty sender answers MAIL_NOT_CONFIGURED. AUTH_ACCOUNT_INVITE_TTL_MS stays in env; the transport is the next group (SECU-179).
mail/transport — section «Почта» (/settings/mail, SECU-179)
The transport and its keys (specs/018-product-settings research.md R17–R27), a second card on the same page; the sender stays its own group above, so a stored mail/sender row is untouched. toggleable: false, no reconnect, envFallback: true: without a row the environment is read, in production too; once a row is saved the three env names are never read for it.
| Field | Env | Type | Default | Rule |
|---|---|---|---|---|
transport | MAIL_TRANSPORT | enum resend | smtp | memory | off | resend | memory refused in production |
smtpHost | SMTP_URL | string | empty | required for smtp |
smtpPort | SMTP_URL | number | 587 | 1–65535 |
smtpSecurity | SMTP_URL | enum starttls | tls | none | starttls | tls implicit TLS (465), starttls required STARTTLS (587), none no TLS required (STARTTLS if offered; Mailpit) |
smtpUser | SMTP_URL | string | empty | required when a password is set |
smtpPassword | SMTP_URL | secret | empty | sealed with SETTINGS_KEY, never returned |
resendApiKey | RESEND_API_KEY | secret | empty | required for resend; sealed, never returned |
Import (and the env source) parses SMTP_URL: smtps:// → tls, port 465 by default; smtp:// → none, port 587 (smtp://…?requireTLS=true → starttls; other nodemailer URL options such as ignoreTLS or tls.* are not carried over — before SECU-179 the URL went to nodemailer whole, so check a URL with options before deploying); user and password URL-decoded; an unparseable URL gives empty SMTP fields. The mail gateway reads this group and mail/sender on every letter and rebuilds the provider client only when they change, so a save applies to the next letter without a restart.
- Test (
POST /v1/settings/mail/transport/test, the saved settings, never the form):values,connection(SMTP: connect, TLS and AUTH without sending; Resend: a read-only API call, a sending-only key answeringrestricted_api_keycounts as accepted) andsender. Details carry codes (MAIL_NOT_CONFIGURED,EAUTH,ECONNREFUSED, Resend error names) and fixed words, never a password, key, login or provider message; a not configured transport isconnection: failedwithMAIL_NOT_CONFIGURED. nodemailer'sESOCKETfor a refused connection is reported by its system name (ECONNREFUSED). - Test letter (
POST /v1/settings/mail/transport/test-mail, body{to?}, default the administrator's address): one short letter through the saved settings; 200{ok, at, transport, to, id, code, detail}, a provider refusal isok: falsewith its code; journaled in the operator journal (admin.setting.test), the group's last check is left as it is. Locally the letter is in Mailpit (make ports). envSchemano longer refusesMAIL_TRANSPORT=smtpwithoutSMTP_URLat start (that isMAIL_NOT_CONFIGUREDat send), anddocker/production/start.shonly warns about it;MAIL_TRANSPORT=memoryin production is still refused at start.
job/queue — section «Очередь» (/settings/queue)
| Field | Env | Default | Bounds | Shown in |
|---|---|---|---|---|
retryDelaySeconds | JOB_RETRY_DELAY_SECONDS | 30 | 0–86400 | seconds |
leaseSeconds | JOB_LEASE_SECONDS | 60 | 1–3600 | seconds |
The retry delay is the base of the exponential back-off. Both are read on every claim and retry; a running job keeps the lease length it was claimed with: the claim stores it on the job (job.leaseSeconds), and every heartbeat, from this process or the scan worker channel, extends by it, so shortening the lease never cuts a running scan short. A job claimed before that column existed is extended by the current setting.
Billing groups (SECU-134)
Three groups hold the PayPal connection that pays the monthly invoices (specs/017-billing: data-model.md, research.md R17, R22–R24, R26, R42; one PayPal Order per invoice since SECU-169, the subscription is withdrawn), defined in billing/setting and read by every consumer through currentBillingConnection() (billing/setting/billingConnection.ts), never process.env. Common to all three: toggleable: false (mode is the switch), no envFallback (production reads only the database; without a billing/paypal row billing is off), the env names are import sources only (envSchema checks their format at start). The admin connector is admin/setting/data/billingConnector.gateway.ts; no detail it returns carries a key, a secret or a webhook id.
billing/paypal
| Field | Type | Env | Notes |
|---|---|---|---|
mode | enum off | fake | sandbox | live, default off | BILLING_MODE | fake is refused in production, live outside it |
requireVerifiedMethod | boolean, default false | none | the «verified payment method» gate (SECU-181, below) |
verifiedMethodGraceDays | whole number 0–90, default 14 | none | days of grace for teams created before the switch was turned on |
requireVerifiedMethodSince | ISO time, server-written | none | when the switch was turned on; not a form field |
Until SECU-181 mode was the group's only field; a row saved before it reads the defaults above. SECU-169 removed graceDays (env BILLING_GRACE_DAYS), legacyCutoff and legacyAccessUntil (research.md Q7, H32): there is no grace after a failed payment and no free access for teams created before the launch; access follows the oldest overdue invoice. A stored row that still holds them reads as mode only, without error; the next save drops them, and a save that names them is 400.
fakein production is 400SETTING_INVALID {mode};liveoutside production is refused by the switch check below (the group's ownvalidaterefuses it too, for paths that bypass the admin). A row that holds a refused mode anyway reads asoffwithstate.reasonand is logged once as an error. Missing or unreadable keys do not turn billing off: the mode stays.- Switching to
live(a save or import that changesmodeintolive; staying in or leavingliveis not checked) runs before anything is written: outside production 409BILLING_LIVE_PRODUCTION_ONLY; in production 409BILLING_LIVE_NOT_READYwithdetails.missing, in this order, of whatbilling/paypal_livelacks:live_keys(a stored row with the client id and a readable secret),live_webhook,live_price(a current live price, below),live_test(its last Test did not pass or there is none),live_test_stale(the last passing Test is not newer than the row's last save). - Test makes no network call:
checks.values, then forsandboxandlivethe selected environment'skeys,webhook,priceandtestby the same readiness rules; forfakeonly whether a fake price is set; foroffthe rest is skipped.
The «verified payment method» gate (SECU-181)
specs/017-billing US20, research.md R54, contracts/access-gate.md §5, billing-http.md §15. While requireVerifiedMethod is true, a team without a saved payment method that passed the €1 check (a PayPal authorization of 1.00 EUR, voided at once; below) in the current mode's environment cannot start a check, take a site copy (POST …/projects/:projectId/snapshots, SECU-190), send a chat message or get an agent: 402 PAYMENT_METHOD_REQUIRED (details {graceUntil: null}), MCP securify_scan_run and securify_snapshot_collect the tool error payment_method_required (before a chat proposal card is created; confirming a card is refused the same 402 and the card stays open, SECU-186). An overdue invoice is decided first (402 INVOICE_OVERDUE); the operator's /v1/admin/* routes (the admin check included), background jobs (snapshot.retention and the rest), site create/archive and everything under …/billing (saving and checking the method included) stay open; a manual grant changes nothing. The app disables «Check website» and «Take a copy» while the gate is closed and says «Add a payment method to check the site and make copies» with a link to Billing → Plan.
- Grace. The server writes
requireVerifiedMethodSincewhen the switch goesfalse → true(no row counts asfalse), keeps it while the switch stays on and clears it when it goes off, whatever a save sends for it; turning the switch off and on again starts a new grace. The admin form does not show it. A team created before that moment keeps access untilsince + verifiedMethodGraceDaysdays (the app banner names the date); a team created after it is closed at once. ChangingverifiedMethodGraceDayslater moves the end of the grace for every older team. - Works only while Vault is on in the mode's environment:
billing/paypal_sandboxorbilling/paypal_livevault = true(fakeis always open). With the switch on and that Vault closed the gate does nothing (paymentMethodGate.required: false), and the admin form says so under the switch. Modeoffleaves everything open. So in sandbox or live the switch requiresvault = truefirst (the checklist under SECU-173 below). - A method counts only when it was saved in the mode's environment and is verified: a fake method does not open a sandbox team. A passed check of a closed team opens it (
billing.access_opened, as after paying an invoice). The end of the grace, turning the switch on or off and deleting the method enqueue nothing and stop nothing already running. - The switch is off by default and in the seed. Verified against the fake and stubbed PayPal HTTP only, not a real PayPal sandbox: the sandbox check (v3 test card
4000000000002503, the REST app's Vault with scopereadwrite) is the human's before the switch is turned on in live.
billing/paypal_sandbox and billing/paypal_live
| Field | Type | Env (sandbox / live) | Notes |
|---|---|---|---|
clientId | string, default empty | PAYPAL_SANDBOX_CLIENT_ID / PAYPAL_LIVE_CLIENT_ID | the REST app's client id |
clientSecret | secret | PAYPAL_SANDBOX_CLIENT_SECRET / PAYPAL_LIVE_CLIENT_SECRET | sealed, never shown |
webhookId | string, default empty | PAYPAL_SANDBOX_WEBHOOK_ID / PAYPAL_LIVE_WEBHOOK_ID | the PayPal webhook pointing at RayScan |
vault | boolean, default false | none | opens PayPal Vault for the environment: saving a team's payment method and autopay (SECU-173, below) |
- Every field may be empty (an environment not set up yet); a value is trimmed and must be one token, else 400
SETTING_INVALID.reconnectFields:clientId,clientSecret, so changing the keys needsreconnect: true(409SETTING_RECONNECT_REQUIREDotherwise). Reconnect deletes nothing (removed: 0): it drops the environment's cached OAuth token, so the next PayPal call uses the new keys. - Test is read-only at PayPal (each environment's own base URL,
api-m.sandbox.paypal.com/api-m.paypal.com):auth(an OAuth token for the keys) andwebhook(GETof the webhook id; without an idwebhookfails andauthis a fresh token request alone, so the keys are still proven), plusprice(a current price of the environment, no network).okonly when all three pass. The webhook passes even when some of the six events of an invoice's Order (CHECKOUT.ORDER.APPROVED,PAYMENT.CAPTURE.COMPLETED|PENDING|DENIED|REFUNDED|REVERSED; SECU-169,contracts/paypal-webhook.md§7) are not subscribed; its message counts the missing ones. A refusal shows its code only (PAYPAL_AUTH_FAILED,PAYPAL_WEBHOOK_NOT_FOUND,BILLING_NOT_CONFIGURED,PAYPAL_UNAVAILABLE).paypal_liveoutside production showsstate.mode: offand its Test calls nothing (checks['live.production']failedBILLING_LIVE_PRODUCTION_ONLY).
The price
GET|POST /v1/admin/billing/:environment/prices (admin/billing, platform administrator only, like /v1/settings; :environment is fake|sandbox|live, else 400 VALIDATION_ERROR) read and set the price per site per month in EUR (the platform currency, SECU-178) (billing/plan, BillingPlanService; contract specs/017-billing/contracts/billing-http.md §6.2). GET answers the environment's prices, newest first (amount, PayPal product and plan ids, current, author, createdAt, retiredAt) and writes no journal row. POST {unitAmount: "10.00"} (a string 1.00–9999.99 with two decimals, else 400 VALIDATION_ERROR; bucket billingAdmin, 10 per minute) answers 201 {price, history}:
liveoutside production → 409BILLING_LIVE_PRODUCTION_ONLY;fakeonly in thefakemode outside production, else 409BILLING_FAKE_ONLY;sandbox/livewithout readable keys → 503BILLING_NOT_CONFIGURED; all decided before any network call.- Each new price is a new PayPal plan on the environment's one catalog product (created on the first price, reused after); a price never changes in place. The new row becomes current and the previous one is retired in one transaction; an invoice takes the price current when it is issued, and issued invoices never change.
- Every attempt journals
admin.billing.price_set(allowedin the same transaction, orfailedwith the error code and no row; quiet).
The admin edits these groups in Settings › Billing, one tab and one form per group (SECU-182): Mode /settings/billing (billing/paypal, with which environment is active and whether its keys are set), Sandbox /settings/billing/sandbox, Live /settings/billing/live, Invoices /settings/billing/invoice (billing/invoice), and sets prices at /settings/billing/prices. A refused switch to live lists what is missing and links to the Live tab. The verified-method gate (requireVerifiedMethod, verifiedMethodGraceDays; SECU-181) is part of billing/paypal, so it sits on the Mode tab; while the mode's Vault is off the switch says it is not in effect and links to the Sandbox or Live tab, where Vault is turned on. The team's billing status (GET /v1/teams/:teamId/billing, the app's «Оплата» page) reads the same connection. Since SECU-169 the team owner pays an invoice by a one-off PayPal Order (POST …/billing/invoices/:invoiceId/pay, then …/capture on the return from PayPal; billing-http.md §11), and the platform administrator can mark one paid by hand (POST /v1/admin/invoices/:invoiceId/mark-paid with a comment; the admin form is SECU-172). PayPal's events arrive at POST /v1/billing/paypal/webhook (sandbox or live mode only; off and fake answer 404): each is checked by PayPal's signature verification with the current environment's keys and webhookId and recorded once; only the six Order events above act (subscription events are recorded as ignored). The access gate (specs/017-billing/contracts/access-gate.md): while the team has an overdue invoice, a check start, a chat message and an agent creation answer 402 INVOICE_OVERDUE; mode off leaves everything open, the operator's /v1/admin/* routes and site create/archive are not gated. The PayPal subscription (checkout, cancel, sync, quantity changes, resync) is removed. All of it is verified against the fake and a stubbed PayPal HTTP only, not a real PayPal sandbox. Autopay on the 1st (SECU-173) charges the team's saved payment method through the same payment path (below).
Saved payment method and autopay (SECU-173)
specs/017-billing US19, FR-1760…FR-1769, research.md R51, H40–H43, billing-http.md §14, paypal-gateway.md §11, paypal-webhook.md §8. The team owner saves one payment method on «Оплата › Тариф» — a PayPal account or a card, both through PayPal Vault (/v3/vault/setup-tokens, /v3/vault/payment-tokens); the card is typed only into PayPal's Card Fields. RayScan keeps the PayPal payment token, its type and, for a card, the brand and the last four digits; never the card number, the expiry or payer data. While a usable method is saved, autopay is on; deleting the method turns it off (there is no other switch). Routes GET|POST|DELETE /v1/teams/:teamId/billing/payment-method and POST …/setup (owner saves and deletes, admins read). Issuing a non-free invoice above 0.00 for a team with a usable method enqueues billing.invoice_autopay (one per invoice and UTC day); the charge is a PayPal Order with payment_source.{paypal|card}.vault_id, recorded as an autopay payment through InvoicePaymentService. A charge that did not pay (declined, a dead token, a job that gave up on a PayPal outage) is retried once a day by the hourly tick until the due date (billing/invoice dueDay), except while a payment is pending at PayPal and after DUPLICATE_INVOICE_ID (PayPal already has a paid Order of the invoice: no letter, no more retries). After the first decline or dead token one English letter billing.invoice_autopay_failed_mail gives the reason and «Pay invoice»; a PENDING charge that PayPal later denies counts as a decline. PayPal answering that Vault is not enabled (403) records PAYMENT_METHOD_UNAVAILABLE without a letter. A manual payment stops the retries; an invoice reopened by a full refund or a reversal is never charged automatically again (the team pays it by the link); after the due date the invoice is overdue as before. A temporary PayPal error retries the job, not the attempt.
What to enable before vault = true (the human does it at PayPal, per environment, sandbox first):
- In the PayPal developer dashboard, the REST app of the environment (the one whose
clientId/clientSecretare stored): enable Vault (save payment methods) and, for cards, Advanced Credit and Debit Card Payments (Card Fields). Without them a setup request answers 403/422 and RayScan answers 503PAYMENT_METHOD_UNAVAILABLE. - Subscribe the environment's webhook to
VAULT.PAYMENT-TOKEN.DELETEDas well as the six Order events: a method removed at PayPal is then removed in RayScan. (The admin Settings Test still counts only the Order events.) - Nothing to change in the CSP: since SECU-173 the app host's Content-Security-Policy (
docker/production/nginx.conf; the Hetzner Caddy serves the same image and adds no CSP) allows PayPal's JS SDK —https://*.paypal.comandhttps://*.paypalobjects.cominscript-src,frame-srcandconnect-src, the hosts of PayPal's CSP page, without Venmo,'unsafe-inline'or a nonce — for the card fields only; the website, admin, docs and api. hosts do not. On the sandbox check confirm the card fields load with the browser console free of CSP errors. Saving a PayPal account is a redirect and needs no CSP at all. - Set
vault = trueinbilling/paypal_sandbox, check on the sandbox (save a card and a PayPal account, autopay of an issued invoice, a declined card and the letter, a second Order with the sameinvoice_idafter a decline — if PayPal refuses it, autopay retries need rework (Q32) — the 403/422 answers when Vault is off), and only then set it inbilling/paypal_live.
While vault is false (the default) nothing can be saved (canSave: false, setup 503 PAYMENT_METHOD_UNAVAILABLE) and no invoice is charged. The fake mode always allows it (the fake vault page /billing/fake-paypal-vault). A method saved in another environment (fake, then sandbox) is not used: autopay records PAYMENT_METHOD_UNAVAILABLE and the app asks to save it again. Verified against the fake and stubbed PayPal HTTP only, not a real PayPal sandbox.
The €1 check (SECU-181). Saving a method first authorizes 1.00 EUR on it (an AUTHORIZE Order with the vaulted token) and voids the authorization right after; nothing is captured. A decline answers 422 PAYMENT_METHOD_DECLINED and saves nothing (the previous method stays); a temporary PayPal failure saves the method unverified, unless the team already has a verified method, which then stays (502 PAYPAL_UNAVAILABLE). An unverified method is checked again by POST …/billing/payment-method/verify («Проверить снова» on «Тариф»). A void that fails is retried by the job billing.payment_method_void. The check runs whatever requireVerifiedMethod says; the gate above only decides whether a team without a verified method is closed.
billing/invoice
The seller and the terms of the monthly invoices (SECU-168, specs/017-billing data-model.md, research.md R39), defined in billing/setting/invoiceSetting.ts and read through currentInvoiceSetting(). Unlike the PayPal groups it has no env names at all: outside production a missing row reads the defaults below, and production reads only the database. Not secret, toggleable: false. Its admin connector is the parameter one (admin/setting/data/parameterConnector.gateway.ts: Test checks the fields and rules, no network), and the admin console edits it in Settings › Billing (SECU-172); it is saved through /v1/settings like any other group.
| Field | Type | Default | Validation |
|---|---|---|---|
sellerName | string | empty | — |
sellerAddress | string | empty | — |
sellerCountry | string | empty | when set, ISO 3166 alpha-2; trimmed and stored upper-cased (de → DE) |
sellerTaxId | string | empty | — |
sellerEmail | string | empty | when set, an e-mail address |
vatRate | string | 0 | a percent 0–100 with up to two decimals (20, 7.25) |
dueDay | number | 15 | 1–28: an invoice is due by the end of this day (UTC) of its month of issue, or of the next month when it is issued after that day (SECU-169, H31: the monthly run dates an invoice the moment its issue job runs, so a retry on the 20th is due next month) |
reminderDays | number | 7 | 1–27 and less than dueDay (else 400 SETTING_INVALID on reminderDays): whole days after issue a payment reminder becomes due |
- A refused value is 400
SETTING_INVALIDnaming the field, never its value. - Empty seller fields are allowed so the group can be saved in parts, but invoices are issued only while
sellerName,sellerAddressandsellerCountryare set and the billing mode's environment has a current price: otherwise the month's run isfailedwithINVOICE_SELLER_NOT_SET|BILLING_PRICE_NOT_SETand the scheduler retries it once the setting is fixed, but only within the following month (it looks at the previous month only). Billing modeoffskips the month for good. - Each invoice copies the seller and the VAT rate when it is issued; a later change applies only to the next invoices.
dueAtandremindAtare stored on the invoice. Since SECU-169 an hourly job marks anopeninvoice pastdueAtoverdue, and the overdue gate refuses checks, chat and agent creation (above). Since SECU-170 the hourly tick sends one reminder per unpaid invoice onceremindAthas passed (reminderDaysat the moment of issue; a later change moves no issued invoice), not while billing isoff.
billing/chat_limit (SECU-184)
The team's monthly chat message limit (specs/023-chat-usage-limits), defined in billing/setting/chatLimitSetting.ts and read through chatMessageLimit() on every new chat message (no cache). No env names: a missing row (in production too) reads the default 0, i.e. no limit, never a refusal. Not secret, toggleable: false; parameter connector, edited in admin Settings › Billing › «Цены» (empty field = 0).
| Field | Type | Default | Validation |
|---|---|---|---|
maxMessagesPerMonth | number | 0 | a whole number ≥ 0; 0 means no limit. Counted per team per calendar month UTC; at the limit the chat answers 402 PLAN_LIMIT_REACHED |
agent/topic_filter (SECU-187)
The project chat's off-topic filter (specs/024-chat-topic-filter), defined in agent/projectChat/setting/topicFilterSetting.ts and read through topicFilterConfig() on every new chat message (no cache). No env names: a missing row (in production too) reads the defaults, i.e. off. Not secret, toggleable: false; parameter connector, edited in admin Settings › Agentfy under the Agentfy form.
| Field | Type | Default | Validation |
|---|---|---|---|
enabled | boolean | false | while on, each new message costs one short extra run of the project's agent (usage topic_filter); a failed check lets the message through |
minConfidence | number | 70 | a whole number 50–100: the classifier's percent of confidence «off topic» from which the chat answers 422 CHAT_OFF_TOPIC; below it the message goes to the agent |
snapshot/retention (SECU-188)
How long a site copy's archive and manifest stay in the bucket (specs/001 FR-021), defined in snapshot/setting/retentionSetting.ts and read through snapshotRetentionConfig() at the start of every daily snapshot.retention pass (no cache), so a save applies from the next pass. No env names: a missing row (in production too) reads the defaults, i.e. on, 30 days, keep 1. Not secret, toggleable: false (the switch is the enabled field); parameter connector, edited in admin Settings › «Копия сайта» under the copy limits.
| Field | Type | Default | Validation |
|---|---|---|---|
enabled | boolean | true | off: the pass reads nothing and deletes nothing (logs skipped: disabled) |
retentionDays | number | 30 | a whole number 7–365: a ready copy created more than this many days before the pass is a candidate |
keepLatestPerProject | number | 1 | a whole number 1–10: this many newest ready copies of each site are never deleted, however old |
Storage and sources
Prisma model and quoted PostgreSQL table are exactly Setting, identity (scope, scopeKey, group, code) (here platform / "" / agent / agentfy). Columns: version, data (field values only, secrets sealed), source (database | env), enabled, aadVersion, lastCheck, lastCheckAt, updatedBy, timestamps. setting_audit rows carry the actor (actorId, actorName), the action (save, import, enable, disable, reconnect, rotate, test), the changed field names (never values) and the version. Triggers refuse DELETE and TRUNCATE on Setting and any change to audit rows.
- Production reads only the database. Without a row the Agentfy connection is
off(source: none) and/mcpanswers 404, andconnector/connectionsrefuses every site connection, until the operator saves or imports the group.source: envis refused (400SETTING_INVALID {source}). - Exception:
envFallbackgroups (SECU-123,specs/018-product-settingsresearch.md C1). The five product parameter groups (connector/copy,auth/login,auth/session,mail/sender,job/queue) andmail/transport(SECU-179) without a row read their env names in production too (source: env, version 0), and a field whose variable is unset has itsenvSchemadefault. Once a row exists the environment is not read, as everywhere. Savingsource: envstays refused in production.agent/agentfy,connector/connectionsand the three billing groups keep the database-only rule. - Outside production a group without a row reads its env names live on every call (
source: env, version 0). A row may also selectsource: envexplicitly. - Once a row exists, a missing value, a database failure or an unreadable secret never falls back to the environment. There is no source-selection variable any more.
Each API instance keeps an in-memory copy, refreshed every SETTINGS_REFRESH_MS (default 5000), so a save made elsewhere is seen within seconds and without a restart. A failed refresh keeps the last good copy and is reported in state.refreshFailure.
REST /v1/settings
| Route | Result |
|---|---|
GET /v1/settings | every registered group |
GET /v1/settings/:group/:code | one group |
PUT /v1/settings/:group/:code | save {version, data?, source?, enabled?, reconnect?} |
POST /v1/settings/:group/:code/import | import from env {version, reconnect?} |
POST /v1/settings/:group/:code/test | connection check (connector/connections: list format only; the five product groups: values only; billing: above) |
POST /v1/settings/:group/:code/reconnect | {removed, setting} |
GET /v1/settings/:group/:code/audit | the last 50 audit rows |
POST /v1/settings/rotate | {resealed} |
POST /v1/settings/connector/connections/check-host | {host, port, listed, allowlistEnabled, addresses, verdict} (above) |
Results come in the /v1 envelope {success: true, data}. All POST routes answer 200. Errors use the usual RayScan body {success: false, code, message, details?, requestId} with details.fields or details.version:
| Status | Code | When |
|---|---|---|
| 400 | VALIDATION_ERROR | body does not match the schema |
| 400 | SETTING_INVALID (fields) | validate failed, unknown field, a value of the wrong type, bad secret operation, a number that is not a whole number or out of its bounds, source: env in production, enabled for a group that is not toggleable, reconnect of a group with nothing to reconnect, a check-host host that is not host:port |
| 400 | SETTING_NOTHING_TO_IMPORT | none of the group's env names is set |
| 401 | UNAUTHORIZED | no live session |
| 403 | FORBIDDEN | not a platform administrator |
| 404 | SETTING_NOT_FOUND | unknown group/code |
| 409 | SETTING_VERSION_CONFLICT (version) | stale version |
| 409 | SETTING_RECONNECT_REQUIRED (fields) | a reconnect field changes without reconnect: true |
| 503 | SETTINGS_KEY_MISSING | a secret replacement or rotate without SETTINGS_KEY |
Besides setting_audit, each of the five changing routes (PUT …, import, test, reconnect, rotate) writes one row to the platform journal audit_event once it has finished: admin.setting.save|import|test|reconnect|rotate, actorType user with the administrator's id and session, no team, resource setting / <group>/<code> (none for rotate), outcome allowed, or failed with the error code as reason (the error still reaches the client). The row never holds values or field names. GET routes and check-host write nothing. A refused non-administrator leaves admin.accessdenied not_platform_admin instead. Both are quiet: a journal outage is logged and never changes the answer, so a saved change stays saved. The admin's Audit log page reads them through GET /v1/admin/audit-events (specs/016-admin-console/contracts/admin-api.md §4–§5).
The SECU-73 routes under /api/admin/settings/… and their error codes are gone (specs/008-agentfy-contract/contracts/settings-rest.md lists them).
Saving and importing
A save is one transaction: compare-and-set on version, version + 1, one audit row (setting_audit, unchanged; the admin.setting.* journal row above follows the transaction). Version 0 creates the row. Non-secret values are trimmed; an empty one keeps the stored value, then the field default. Import from environment builds the data from fromEnv (a secret with a value is replaced, without one kept), stores source: database and returns no values. There is no automatic import at startup.
Secrets
Secret operations are keep, replace and clear; a blank replacement is invalid. Responses carry hasValue and unreadable, never ciphertext or plaintext. The sealed form is enc:v1:<key-id>:<nonce>:<tag>:<ciphertext> (AES-256-GCM, random 12-byte nonce, key id from SHA-256). The AAD is ['setting', aadVersion, scope, scopeKey, group, code, field]; rows moved from SECU-73 keep aadVersion 0 (the SECU-73 AAD [scope, scopeKey, group, code, field]) until they are resealed.
SETTINGS_KEY (32 bytes, base64 or hex) lives only outside the database; a malformed key stops the start, a missing one leaves secrets unsealable and unreadable. To change it: deploy the new SETTINGS_KEY with the old key(s) in SETTINGS_KEY_PREVIOUS on every instance. At startup each instance reseals every secret sealed under an older key or with aadVersion < 1 (audit rotate, actor system); POST /v1/settings/rotate does the same on demand (API only, there is no admin button) and returns the number of resealed secrets. Each resealed row gets version + 1. A secret no key opens is left as it is, logged by field name and not counted. Verify every instance reads, then remove the old key. Keep key backups separate from database backups.
Reconnect
Changing mode, apiUrl, organizationId or environment on a stored group changes the connection's scope (fake or organization:<origin>|<orgId>|<env>). A save or import that does so answers 409 SETTING_RECONNECT_REQUIRED unless it carries reconnect: true (the form offers Save and reconnect / Import and reconnect). With it the setting is saved, then reconnect runs: for every organization_workspace whose scope is set and differs from the current one, the projects' agent bindings and MCP grants are revoked, and chat messages, conversations and members of other scopes, provisions, project agents and the workspace are deleted, in foreign-key order. removed counts the deleted rows; state.staleBindings shows how many workspaces wait for it. Reconnect in the form runs it alone. After it, the project's agent is provisioned again in the new organization. This replaces the SECU-73 "disable, wait 15 s, retire agents" flow.
Test connection
This section is agent/agentfy; connector/connections only checks its list's format (above). checks of the result is a record of named items, each {status: ok|failed|skipped, detail}.
Read-only: it creates no agent and runs no model; each probe has a 10 s timeout. The result is stored as lastCheck/lastCheckAt without a version change and audited as test.
| Mode | api | provisioning | chat | mcp | mcpEndToEnd |
|---|---|---|---|---|---|
off | skipped | skipped | skipped | skipped | skipped |
fake | skipped | skipped | skipped | probe | skipped |
organization | probe | probe | probe, or skipped without a key | probe | skipped |
api and provisioning call GET {origin}/v1/orgs/{org}/operations/settings-probe with the provisioning key; chat calls the conversation context probe with the chat key; mcp posts an unauthenticated initialize to mcpUrl and is ok only on 401. mcpEndToEnd is always skipped: the proof is provisioning a project's agent and a tool call with its conversation grant. detail never contains keys.
Migration from SECU-73
The setting_contract migration moves the SECU-73 JSON envelope into columns: values → data, enabled → column, source = 'database', aadVersion = 0; the SECU-73 test result is dropped (lastCheck null). setting_audit.actorId becomes nullable and gains actorName. The first start with SETTINGS_KEY reseals the moved secrets to aadVersion 1.
Rollout: deploy the migrations, set SETTINGS_KEY (and the admin origin in CORS_ORIGIN) in the DigitalOcean console, grant an operator platformRole = 'admin', log in to the admin app, then Import from environment once or enter the connection and Save. Remove the integration env values only after the saved connection is verified.
Local tests use synthetic credentials, isolated PostgreSQL and the fake Agentfy. No production migration, deployment or production connection check has been performed.