NyxID
CLAUDE.md37 starsChanged 4 months agoApache-2.0View on GitHub
NyxID is an Auth/SSO platform (similar to Supabase Auth) with a Rust backend, React frontend, and CLI tools: user authentication, OAuth/OIDC, MFA, credential brokering, admin management, and MCP proxy. The nyxid CLI covers all user-facing operations (services, keys, catalog, nodes, approvals, SSH, MCP, notifications) and includes nyxid node for managing on-premise credential nodes. Tech Stack: - Backend: Rust, Axum 0.8, MongoDB 8.0 (mongodb 3.5, bson 2.15) - Frontend: React 19, TypeScript, Vite 7, TanStack Router + Query, Tailwind CSS 4,…
- Installs packages
In this repository18 other files it gives its agents.
- AGENTS.mdAGENTS.md
- aevatar-agent-profile-managementSkill
- aevatar-automationSkill
- aevatar-channels-deliverySkill
- aevatar-codex-exec-node-setupSkill
- aevatar-codex-exec-workflow-sampleSkill
- aevatar-feasibility-advisorSkill
- aevatar-platform-mapSkill
- aevatar-schedulerSkill
- aevatar-service-publisherSkill
- aevatar-team-builderSkill
- aevatar-triageSkill
- aevatar-workflow-authoringSkill
- fallback-to-calling-agentSkill
- firecrawl-via-nyxidSkill
- github-via-nyxidSkill
- nyxid-service-skill-authoringSkill
- nyxidSkill
The file
We split this CLAUDE.md into the rules it gives an agent
6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 18
NEVER use #[serde(skip_serializing)] on model fields -- prevents insert_one(&struct) from storing them
- Very specific: line 19
ALWAYS use #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")] on DateTime<Utc> fields.
- Distinctive: line 70
No hardcoded secrets -- env vars for all sensitive data.
- Very specific: line 73
All key material in Zeroizing wrappers.
- Distinctive: line 94
Add new entries here when introducing additional vendored URN types.
- Very specific: line 312
All API routes under /api/v1:
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Project Overview
NyxID is an Auth/SSO platform (similar to Supabase Auth) with a Rust backend, React frontend, and CLI tools: user authentication, OAuth/OIDC, MFA, credential brokering, admin management, and MCP proxy. The nyxid CLI covers all user-facing operations (services, keys, catalog, nodes, approvals, SSH, MCP, notifications) and includes nyxid node for managing on-premise credential nodes.
Tech Stack:
- Backend: Rust, Axum 0.8, MongoDB 8.0 (
mongodb3.5,bson2.15) - Frontend: React 19, TypeScript, Vite 7, TanStack Router + Query, Tailwind CSS 4, Zod 4, Zustand
- Mobile: React Native 0.83, Expo 55, TypeScript (iOS + Android approval app)
- SDK: TypeScript OAuth 2.0 client (
@nyxids/oauth-core,@nyxids/oauth-react) - Dev tools: Docker Compose (MongoDB + Mailpit), RSA keys for JWT signing
Deep-dive docs live in docs/ -- notably chat/README.md, ENV.md, ORACLE_RELAY.md, AGENT_ISOLATION.md, CHANNEL_BOT_RELAY.md, CHANNEL_EVENT_GATEWAY.md, NODE_PROXY_ARCHITECTURE.md, OPENCLAW_INTEGRATION.md, API_DISCOVERY.md, SSH_NODE_KEY_AUTH.md. Read the relevant doc before working in that subsystem.
Critical Rules
1. MongoDB Model Conventions
- NEVER use
#[serde(skip_serializing)]on model fields -- preventsinsert_one(&struct)from storing them - ALWAYS use
#[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]onDateTime<Utc>fields; forOption<DateTime<Utc>>use thebson_datetime::optionalhelper (models/bson_datetime.rs) - IDs are UUID v4 stored as strings in MongoDB
_id; each model has aCOLLECTION_NAMEconstant
2. Layer Architecture
Strict separation: handlers/ -> services/ -> models/
- models/ -- plain serde structs,
COLLECTION_NAME, no business logic - services/ -- business logic; takes
&mongodb::Databaseand&strfor IDs - handlers/ -- HTTP layer; converts
AuthUser.user_id(Uuid) to string for services; dedicated response structs (never serialize model structs to API responses) - crypto/jwt.rs takes
&Uuid(kept for signing); token_service parses&strtoUuidinternally - unified_key_service -- orchestration layer for the streamlined services architecture; auto-provisions UserEndpoint + UserApiKey + UserService from catalog or custom input in one operation
3. Error Handling
AppError enum (errors/mod.rs, thiserror); handlers return AppResult<T> = Result<T, AppError>. Variants map to HTTP status codes and numeric error codes; backend/src/errors/mod.rs is the authoritative list. Internal/database errors never leak details to clients.
Reserved numeric code blocks (single source of truth -- do not duplicate these tables elsewhere):
- 1011-1019 SSH node-key/auth-mode: 1011
SshNodeKeyMissing, 1012SshHostKeyMismatch, 1013SshNodeExecChannelClosed, 1014SshPrincipalAmbiguous, 1015SshAuthModeUnsupportedForOperation - 8000-8005 node/proxy: 8000
NodeNotFound, 8001NodeOffline, 8002NodeProxyTimeout, 8003NodeRegistrationFailed, 8004NodeCredentialMissing, 8005WsProxyDownstream - 8006-8011 pending-credential protocol: 8006
PendingCredentialDecryptFailed, 8007PendingCredentialVersionUnsupported, 8008PendingCredentialCiphertextTooLarge, 8009PendingCredentialPubkeyAwaiting, 8010PendingCredentialNodeOffline, 8011PendingCredentialQueueFull - 8012
ClientDisconnected(HTTP 499, nginx's "Client Closed Request"): the caller hung up before the response could be written and upstream work was cancelled. Never delivered to anyone — it exists so cancelled work is not counted as a server fault in telemetry and audit. Do not map it to 5xx. - 8013
NodeHttpSignatureUnsupported(HTTP 502): target-selected HTTP requests require a node advertising HTTP signature v2 - 9500-9599 device-code binding: 9500
DeviceCodeNotFound, 9501DeviceCodeExpired, 9502DevicePollSignatureInvalid, 9503DeviceUserCodeInvalid, 9504DeviceCodePending, 9505DeviceCodeAlreadyDelivered, 9506DeviceCodeRateLimited, 9507DeviceCodeLocked, 9508DeviceCodeSlowDown - 10000-10015 channel relay: 10000
ChannelBotNotFound, 10001ChannelBotInactive, 10002ChannelBotLimitReached, 10003ChannelWebhookVerificationFailed, 10004ChannelRelayFailed, 10005ChannelPlatformError, 10006DeviceChannelReplyNotAllowed, 10007ChannelPlatformEditUnsupported, 10008ChannelAgentInitiateNotAllowed, 10009ChannelConversationNotAddressable, 10010ChannelPlatformSendUnsupported, 10011ChannelConversationNotReachable, 10012ChannelMediaUnsupported(415), 10013ChannelMediaTooLarge(413), 10014ChannelMediaFetchFailed(502), 10015ChannelAttachmentNotFound(404) - 11000-11099 oracle relay: 11000
OraclePoolNotFound, 11001OraclePoolSlugTaken, 11002OraclePoolInactive, 11003OracleWorkerTokenInvalid, 11004OracleQueueFull, 11005OracleQuotaExceeded, 11006OracleTaskNotFound, 11007OracleSessionNotFound, 11008OracleSessionClosed, 11009OraclePayloadTooLarge, 11010OracleExtractDisabled, 11011OracleWorkerNotFound, 11012OracleWorkerCapabilityUnsupported, 11013OracleWorkerCommandNotFound, 11014OracleWorkerLabelUnavailable, 11015OracleLoginSnapshotNotFound - 11100
AnonymousIncompatibleService(HTTP 400) - 11200-11207 auth-device login: 11200
AuthDeviceCodeNotFound, 11201AuthDeviceCodeExpired, 11202AuthDeviceCodePending, 11203AuthDeviceCodeSlowDown, 11204AuthDeviceCodeDenied, 11205AuthDeviceCodeAlreadyDelivered, 11206AuthDeviceCodeRateLimited, 11207AuthDeviceUserCodeInvalid - 11300-11305 connect links: 11300
ConnectLinkNotFound, 11301ConnectLinkExpired, 11302ConnectLinkAlreadyCompleted, 11303ConnectLinkCancelled, 11304ConnectLinkRateLimited, 11305ConnectLinkCompletionInProgress - 11500
GrantCascadeConfirmationRequired(HTTP 409) - 11600-11606 triggers: 11600
TriggerNotFound, 11601TriggerSecretInvalid, 11602TriggerRateLimited, 11603TriggerPayloadTooLarge, 11604TriggerDeliveryUnsupported, 11605TriggerDeliveryFailed, 11606TriggerDeliveryRecordNotFound - 11700
RequestBodyTooLarge(HTTP 413): a bounded proxy or forwarding ingress exceeded its configured byte limit - 11900-11909 Agent Key login: 11900
AgentKeyLoginNotFound, 11901AgentKeyLoginExpired, 11902AgentKeyLoginPending, 11903AgentKeyLoginSlowDown, 11904AgentKeyLoginDenied, 11905AgentKeyLoginAlreadyDelivered, 11906AgentKeyLoginRateLimited, 11907AgentKeyLoginUserCodeInvalid, 11908AgentKeyLoginKeyIneligible, 11909AgentKeyCredentialNotFound - 12000-12004 one-time login codes: 12000
LoginCodeInvalid, 12001LoginCodeExpired, 12002LoginCodeCancelled, 12003LoginCodeRedeemed, 12004LoginCodeRateLimited - 12100
AssistantTurnActive(HTTP 409,turn_active): a persisted NyxAgent conversation already has an active turn. - 12101
AssistantAttachmentExpired(HTTP 410,attachment_expired): an assistant upload is no longer available under retention policy. - 12102
AssistantTurnRequired(HTTP 409,assistant_turn_required): a conversation key attempted execution without a live turn. (12101 is already reserved by upload retention.) - 12200
AdminUsageQueryTimeout(HTTP 503): bounded admin usage aggregation timed out; retry with a narrower window or filters. - 12300
WorkspaceDestinationsNotActivated(HTTP 503): incomplete automatic Drive/Workspace editor reconciliation; excluded from proxy-fault telemetry - 12400-12422 machine nodes: 12400
MachineCapabilityDisabled, 12401MachineNotAllowed, 12402MachinePathOutsideRoots, 12403MachineJobNotFound, 12404MachineConfirmationPending, 12405MachineConfirmationDeclined, 12406MachineComputerUnavailable, 12407MachineLimitExceeded, 12408MachineOwnerInControl, 12409MachineNotIsolated, 12410MachineLoginNotFound, 12411MachineLoginOriginMismatch, 12412MachineLoginWrongField, 12413MachineBrowserUnavailable, 12414MachineDriverRestarting, 12415MachineComputerPermissionMissing, 12416MachineComputerToolUnsupported, 12417MachineDisplayUnavailable, 12418MachineTurnStopped, 12419MachineAuthorityUnsupported, 12420MachinePermissionRevoked, 12421MachineAuthorityStale, 12422MachineAuthorityBusy. Nodes also use 12419 forseparated_context_unavailableand 12421 forcontext_quarantine_pending. - 12500-12501 assistant voice: 12500
VoiceQueueFull(HTTP 429), 12501VoiceProviderUnavailable(HTTP 503).
4. Frontend Patterns
- Zod schemas in
schemas/(one per domain); React Hook Form +@hookform/resolvers - Forms use
useAppForm(components/ui/form.tsx), never rawuseForm(lint-enforced viano-restricted-imports): itssetValuedefaults toshouldDirty/shouldTouch/shouldValidate: trueso non-text controls wired viawatch+setValue(Radix Switch/Select/Checkbox, custom editors) correctly enable dirty-gated submit buttons; programmatic writes (prefill, normalization in effects) opt out per call with{ shouldDirty: false, shouldTouch: false } - TanStack Query hooks in
hooks/(one per domain:use-auth.ts,use-services.ts, ...); auth state in Zustand (stores/auth-store.ts) - UI components via Radix UI + shadcn/ui pattern (
components/ui/); noconsole.login production code
5. Security
- No hardcoded secrets -- env vars for all sensitive data; input validation on all endpoints; PKCE for OAuth flows
- AES-256 envelope encryption with pluggable async
KeyProvidertrait (crypto/aes.rs,crypto/key_provider.rs); AWS KMS (crypto/aws_kms_provider.rs, featureaws-kms) and GCP Cloud KMS (crypto/gcp_kms_provider.rs, featuregcp-kms); fallback provider for zero-downtime migration between encryption backends - Assistant Agent Keys are the deliberate exception to hash-only API-key storage:
assistant_agent_credentialsretains one raw key per conversation only under envelope encryption because NyxAgent binds session ownership to the exact key. No API, audit, log, or Debug output may expose ciphertext or raw material; revoke removes the encrypted row; rotation adopts the encrypted successor in the same transaction without returning its raw key. Both clear session bindings. - All key material in
Zeroizingwrappers; all Debug impls redact secrets and key identifiers;MAX_WRAPPED_DEK_SIZE = 1024enforced on encrypt and decrypt paths - Middleware: rate limiting (
mw/rate_limit.rs), security headers (mw/security_headers.rs), JWT auth (mw/auth.rs) - Audit logs are tamper-evident for new rows via HMAC-SHA256 hash chaining (
services/audit_chain_service.rs): newAuditLogrows must setseq,prev_hash,entry_hashthrough the audit service append path; legacy rows withoutseqcount as pre-chain, not backfilled.AUDIT_CHAIN_HMAC_KEYis an optional 64-hex override; otherwise the key is domain-derived fromENCRYPTION_KEYor the JWT private key. v1 does not detect tail truncation without external head anchoring. - Billing transactions are tamper-evident via the append-only
billing_ledgercollection (services/billing/ledger.rs): charged usage settlements (first-apply only, including the wallet-lock crash bridge), provider-confirmed top-up checkouts, paid wallet credits (deduped by Lago invoice id), grant lifecycle movements, and purchased-credit expiry append hash-chained entries with the sameseq/prev_hash/entry_hashconstruction, keyed byBILLING_LEDGER_HMAC_KEYor thebilling-ledgerdomain derivation. Wallet usage locks remain until their v2 posting is durable; provider balance changes and their postings commit transactionally. Checkout notifications remain memo-only best-effort events. Account reconciliation (billing_accounts, additive Integrityaccountsresponse field) checks wallet balance minus pending debits and grant remaining against checkpoints updated atomically with postings. When billing is enabled, a leased, fenced runner checks up to 1,000 accounts per collection in each bounded snapshot, runs batches back-to-back for one pass, then idles until the chain-verification cadence.CHAIN_VERIFY_INTERVAL_SECS=0disables both automatic chain verification and account reconciliation; no account runner is spawned. Grant issuance is unspendable until journaled, grant consumption retains its settlement lock until journal confirmation, grant issuance/terminal markers retry during reconciliation, and purchased-credit expiry retains its wallet operation until every ledger entry is durable. Verify viaGET /api/v1/admin/billing-ledger/verify. Tail truncation is detected: the reconcile sweep anchors the ledger head into the audit chain (billing_ledger_head_anchored) and the server log, and verify cross-checks the newest anchor (tail_truncatedbreak); entries newer than the last anchor (<= one reconcile interval) are the remaining window. Both chains are also re-verified automatically in rolling chunks (services/chain_verify_service.rs,CHAIN_VERIFY_INTERVAL_SECS), with status persisted tochain_verify_status, surfaced on the admin Integrity page (/admin/integrity), and escalated via error-level logs. - Catalog
inferenceis optional admin metadata (protocol/model list/realtime). Compute caller-specific binding andstatus_slug; never store them. Startup defaults respectinference_admin_modified(including explicit null clears) and include admin-createdchrono-llm/chrono-llm-publicand seeded xAI. Provider-linked status usesProviderConfig.slug; other status uses the catalog slug. Seedocs/PLATFORM_KEYS_AND_INFERENCE.mdanddocs/API_DISCOVERY.md. - Catalog
platform_keyuses the existing encrypted master credential and live public/restricted polymorphic-owner grants. Every platform-bound resolver must call the shared ACL before decryption; no anonymous grant, no node routing or user-controlled destination. Gateway-URL providers cannot enable platform keys. Restricted ACLs batch memberships/active owners; catalog, keys (including provisioning/reconciliation), MCP and LLM listings share one request membership snapshot across service/owner checks. Reuse loaded providers or batch them once;available_with_grantsmust perform no database calls. Never cache these grants across requests. Legacy absent configs preserve public internal master-key behavior.UserService.credential_bindingis optional;POST/PUT /keysand hosted/MCP flows useuse_platform_key. Switching to platform retains the user's key. Public audience auto-provisioning is personal-only; restricted audience auto-provisioning creates personal rows for allowlisted people and org rows only for allowlisted orgs reached through activecan_proxy()memberships. Startup removes legacy public-audience org auto rows with their orphan endpoints. Explicit org-owned platform bindings (source != auto_provision) retain the live public execution ACL. Scoped agent auto-connected grants include active auto rows and explicit platform bindings. Platform-key usage is always billed to the acting person, never to an org wallet, viaBillingOwnerResolver::resolve_for_execution. ServiceBilling.byok_pricing/platform_key_pricingare optional credential-class lanes: the existing fields are the primary price; optionalcomponentsadd unique metrics. Either lane present supersedes legacy platform billing; missing lane andNoAuthare free. An unsynced primary substitutes legacy billing (or free) for the entire lane; a synced primary and synced extras charge, while unsynced extras are free and never add fallback. Resale stays independent. Primary Lago codes remainplatform_svc_{slug}_{byok|pk}, components append_{metric}, with durable component cleanup/reconcile. Price removal marks the code'sbilling_rate_cacherowretired_atand never deletes it: historical usage keeps pricing from it,fresh_raterefuses it for new reservations, and a re-synced price replaces the row.GET /billing/usageprices historical rows by grant-settled derivation, then the cached rate, then exact per-row reservation rates (rate × quantity in Decimal128 credits, as exact settlement computes), else null with grant credits still known. Omitted lanes/components preserve them; null/[] clears components. Token/image capture checks every configured component independent of slug/sync; priced token classes subtract caches included in OpenAI/Gemini input, but keep Anthropic's separate cache counts; providerTokenBreakdownremains unchanged. Computed adminallowance_metricslists configured units plus legacy only without lanes or with an unsynced primary; allowances match identical metrics. Default BYOK primary, then platform primary, then legacy. NyxID 0.34.0 prices supportPRICE_FRACTIONAL_DIGITS = 12, optional pico rates plus truncated legacy micros; all money uses checked i128 picocreditCredits, Decimal128 credits in MongoDB and decimal strings in additive API fields. Derive the exact wallet share by subtraction; never ceil or truncate movements. Legacy display fields truncate after exact aggregation. Lago quantities floor cumulatively with durable per-owner/metric/rate residue committed atomically with the claim-fenced final funding split; stale workers reuse both committed outputs. Exact BSON money keys are unit-free and take precedence over legacy integer micros. Canonical Credits use direct BID conversion with BSON-parser-equivalent bytes to bound rollup serialization overhead. Before normalization, rollup reductions fetch mixed documents to distinguish missing from null; after normalization, scalar exact cost mirrors use covering indexes; startup creates each replacement before retiring its obsolete legacy definition to bound transaction cache pressure. Invalid Lago charges disable only their own metrics and surface in Integrity. Webhook/reconcile/expiry use one settled-minus-accrued balance calculation; locked refreshes are durably deferred to a one-second worker. Preserve funding precedence, charge IDs and v1 canonical bytes; v2 entries have balanced postings. First cutover of existing billing data requires draining old writers andBILLING_EXACT_CUTOVER_DRAINED=true; a background task otherwise waits for acknowledgement while billed admission returns BillingProviderUnavailable (503). The server and metering-only traffic remain available. Billing admission and money sweeps wait only forbilling_migrations/exact-v2.completed_at; derived analytics normalization has independentbilling_migrations/exact-v2-rollups.completed_atreadiness and never creates a billing outage. Before the rollup marker, admin usage uses a legacy-tolerant mixed-document reduction; after it, readers use flatquery_{money_field}Decimal128 mirrors and v4 covering indexes, avoiding nested object reconstruction in MongoDB. Folds and normalization write those mirrors atomically with their nested counterparts. Rollup normalization uses bounded MongoDB update pipelines atomic per document with concurrent folds, preserves present exact/null values, converts absent legacy micros, removes legacy mirror keys, and records durable progress/Integrity diagnostics. No hot-path migration runs. Cutover conversion and delta absorption isolate malformed documents, record Integrity diagnostics and continue bounded batches. Old binaries must not be restarted against migrated data. Seedocs/BILLING_EXACT_ACCOUNTING.md. Upgrade ALL replicas before authoring component prices, new-metric allowances, or prices beyond six decimals; old replicas cannot deserialize the new enum units. Seedocs/PLATFORM_KEYS_AND_INFERENCE.md.- Per-service platform prices are authored in NyxID at
ServiceBilling.platform_pricingand synchronized to stable Lagoplatform_svc_{slug}sum metrics and standard charges onLAGO_PLAN_CODE. Plan updates must round-trip the full existing charge array with ids because Lago replaces it. Pending/failed syncs and charge-removal cleanup retry during reconciliation; a service continues using its legacy plan metric until the new price issynced, and services without a NyxID price retain legacy Lago-authored pricing. - Allowance bundles group single-metric rows through an optional
bundle_id; funding is unchanged. Credit benefits live incredit_grants,credit_schedules,credit_schedule_periods,usage_allowances, andusage_allowance_periods. Funding precedence is actual-quantity allowance units, soonest-expiring exact grant credits, then exact wallet credits. Metering-only rows never consume benefits; legacy funding-less wallet rows remain wallet-only. Only the wallet-funded quantity is emitted to Lago or included in drift comparison. Grant expiry is enforced at reservation time and swept for terminal ledgering. Recurring windows are UTC.one_timeapplies only to allowances. Both credit schedules and allowances supportdaily,weekly, andmonthly. Grant issuance journals at most 50 one-shot recipients inline. Deferred rows are unspendable until reconcile confirms their ledger entries. Admin/operator endpoints are under/api/v1/admin/credits. User reads are/api/v1/billing/{grants,allowances}and accept an authorized orgowner_id. Recipients areall_users,selected_users,org_members(target_org_ids), orgroups(target_group_ids); member targets fund personal wallets only, including org viewers and direct group members. Grants snapshot at issuance, schedule periods freeze policy with signup/join cutoffs at claim, and allowances follow live membership; selected lists are mutually exclusive and capped at 500 ids. - A scheduled grant is an ordinary
CreditGrant. Its UUID v5_idis derived from{schedule_id}:{period_start_ms}:{recipient_user_id}and is the disbursement identity. Keepgrant-issued:{grant_id}as the ledger dedupe key. Treat period rows and leases as derived progress, never as money locks. Each period freezes its policy and all-owner signup snapshot when claimed. Catch-up mints only the current window and abandons elapsed incomplete periods. Pausing opens no new period, but an in-flight walk completes. Schedules use the existing billing reconcile interval and add no environment variable. - Purchased Lago credits expire independently 365 days after settlement. Lago v1.50's wallet-wide
expiration_atcannot model rolling purchases, soservices/billing/topup_expiry.rsuses FIFO transaction remainders and Lagovoided_credits.BillingWallet.active_topup_expiryis the crash bridge andpending_topup_expiry_creditsmust be subtracted by every availability expression. The existing billing reconcile interval runs this sweep; there is no separate expiry environment variable. - Anonymous catalog endpoints may be enabled only when the service has
identity_propagation_mode = "none",forward_access_token = false, andinject_delegation_token = false(disabled draft rules may be stored on any service); violating admin writes returnAppError::AnonymousIncompatibleService(400, code 11100). Public execution still force-strips identity propagation, access-token forwarding, delegation-token injection, and downstream auth defaults as defense in depth. - Exact-service approvals bind an execution-authority v2 digest (
services/execution_authority.rs) over resolved execution inputs, includingtoken_exchange_config,service_category, andrequires_user_credential, while retaining the real v1 digest for rolling compatibility. Main-era v1-only rows validate against the live v1 projection; pre-digest rows skip that one gate within their approval expiry. The additive delegated exact-view fields retain the v2 contract: rolling rows keep the pre-additive digest for old replicas and separately bind the full projection for new replicas. DurableServiceEndpointoperations also bind the server-resolved positive generation; instance-spec and legacy unbound rows skip only the generation comparison while every other fence remains. Observe and redeem share one ordered live evaluator (catalog/exact generation -> policy -> read-only execution authority); observe reports transient drift without writes, while redeem claims first and durably records terminal revalidation failures before credential materialization. After those gates, redeem materializes credentials and compares execution authority again before any provider effect.UserApiKey.credential_epochversions credential material: bump it on user-initiated credential replacement only, never on background/lazy OAuth refresh, and always via a pipeline update (vec![doc! { "$set": ... }]) -- the bump is an aggregation expression and a classic update document silently stores it as a literal sub-document. Seedocs/GRANULAR_APPROVALS_DESIGN.md. - Delegated management parity requires the exact
account:readscope,GET, a non-WebSocket request, and a route outside the deny classes inmw/auth.rs; the verifiedAuthUserextractor is authoritative. New secret-delivering, execution-shaped, streaming, upgrade, or authentication/provisioning protocol GET routes MUST be added todelegated_read_denied_pathbefore mounting. Channel media downloads (GET /api/v1/channel-relay/messages/{message_id}/attachments/{index}) are denied; the metadata-onlyGET /api/v1/channel-platformsremains allowed for delegatedaccount:read.
5a. Vendor URN Namespace
NyxID-vendored URN types live under urn:nyxid:params:oauth:<category>:<name> (the params:oauth infix mirrors urn:ietf:params:oauth:* so generic vendor-extension parsers recognize the shape). Registered:
urn:nyxid:params:oauth:token-type:binding-id-- RFC 8693 subject_token_type identifying anOauthBrokerBindinghandle; used at/oauth/tokenwithgrant_type=urn:ietf:params:oauth:grant-type:token-exchange.
Add new entries here when introducing additional vendored URN types.
6. Node Proxy Conventions
NodeWsManager: in-memory connection pool shared viaArcinAppState;DashMapfor lock-free concurrent accessNode.user_idis the polymorphic owner field (person or org user, matchingUserService/UserApiKey). Do not add a separateorg_idto node-related models; ACL viaorg_service::resolve_owner_access(actor, node.user_id).- Registration tokens carry the chosen owner at mint time; admin role is verified at issuance, not redemption -- a revoked admin can still complete registration within the token TTL (default 1h,
NODE_REGISTRATION_TOKEN_TTL_SECS). When removing org admins, also delete their pending registration tokens. - Node auth tokens (
nyx_nauth_...) and registration tokens (nyx_nreg_...) are 32 random bytes; only SHA-256 hashes stored. HMAC signing secrets are generated at registration: SHA-256 hash on server, encrypted locally on the node agent. - WebSocket handler (
handlers/node_ws.rs) authenticates in the first message, not via HTTP middleware - Catalog master credentials (including legacy internal rows) always use server transport; HTTP/WS and MCP ignore owner-node bindings for these rows. This intentionally hardens legacy behavior: nodes inject only node-owned credentials. Explicit platform connections reject node selection.
node_routing_service::resolve_node_routeruns before credential resolution inexecute_proxy(); returnsNodeRoutewithfallback_node_idsfor multi-node failover- Streaming proxy:
proxy_response_start/ chunk frames /proxy_response_end; preferred chunk transport is a WS binary frame with a 36-byte request_id prefix, with legacyproxy_response_chunkJSON fallback for older servers - Node metrics (
node_metrics_service) recorded fire-and-forget after each proxy request; stored as embeddedNodeMetricsdocument on the Node model. Node-routed audit events include"routed_via": "node"and"node_id". NodeStatusis an enum (Online/Offline/Draining) -- not a bare string. WS writer channels are bounded (capacity 256);try_sendtreats full buffers as node offline (H4).- WS auth-frame injection rules live on
DownstreamService.ws_frame_injectionsandUserService.ws_frame_injections; additive, separate from HTTPauth_methodinjection.WsFrameDirectionis the trigger direction: adownstreamrule matches frames from the service and injects the configured response back toward it. Direct and node-routed WS paths emit metadata-onlyws_frame_auth_injectedaudit events; never log injected payloads or credentials. - SSH services use
ssh_auth_mode(cert|node_key|proxy_only); legacycertificate_auth_enabledtrue/false maps tocert/proxy_only. Node-key credentials live only in the node-local encrypted store, keyed by(service_slug, principal), with configuredhost_key_sha256enforced by the russh client. Cert-modessh execand browser terminal also run through russh on the node agent (backend-issued ephemeral private key + OpenSSH user certificate) and verify target host keys against a node-local TOFU storessh_cert_host_keys.tomlin the node config dir; pins are enforced on every session, and a changed key returnsSshHostKeyMismatch(1012) +ssh_host_key_mismatchaudit. Manage pins withnyxid node ssh cert-host-key list|pin|forget(pinpre-seeds/replaces a SHA256 fingerprint;forgetis the legitimate rotation recovery path; the store is live-reloaded, so no daemon restart).ssh proxyis unsupported fornode_key-- usessh execor the browser terminal. - Admin node endpoints (
handlers/admin_nodes.rs) require admin role and have no ownership check nyxid node daemonmanages background service lifecycle (cli/src/node/daemon.rs): launchd LaunchAgent on macOS / systemd user unit on Linux. All node commands support--profilefor multi-instance: service labelsdev.nyxid.node.{profile}(macOS) /nyxid-node-{profile}.service(Linux), config at~/.nyxid-node/profiles/{name}/.- Machine nodes add locally-authoritative
shell/files/computercapabilities (all off by default), mandatory signed requests, bounded jobs/files, cua MCP stdio, job-bound service gateway and human-only live desktops. Only owner-turn assistant chat keys can use them; guests never. Specialists storemachine_node_idsandsaved_login_idsbesidegrants. Owner settings (machine_confirm, single-user saved-login opt-in) are human-only. Browser policies/extension/native host belong to the supervisor;--separate-userssetups use distinct browser and command identities. Saved logins are encrypted, write-only, exact-origin fills, with no secret-bearing Debug, logs, audit or tool results. Setup/control watches queue their event transactionally. No extra machine DB reads on unrelated proxy/MCP/turn paths. Seedocs/MACHINE_NODES.mdfor the binding contract anddocs/NYXID_NODE.mdfor setup and warnings.separatedmode is opt-in behindassistant:machine-contexts, changed only through an owner action card, and never called isolated; seedocs/MACHINE_AGENT_ISOLATION.mdfor residuals. Existing assignments remainshared_legacy; full isolation requires a separate machine container/VM per agent. - Machine exec
servicesis an explicit per-job least-privilege declaration (default none), bound as ID+slug on MachineJob, shown on cards/audit and rechecked at gateway execution. Server cataloginference.wire_protocolandgit_httpmetadata generate the signed SDK/git environment; no node slug mappings. Reuse the shared service visibility resolver and middleware API-key identity constructor. Preserve Content-Encoding with Content-Length through both streaming hops. Non-isolated shell warnings must explicitly mention access to node tokens/signing secrets/stored credentials; recommend the container or--separate-users, never refuse solely for owner-machine risk. Container Chromium uses user-namespace/seccomp sandboxing via the shipped profile; every Linux agent/file child sets NoNewPrivs and denies namespace syscalls through a per-process filter; browser/cua retain sandbox namespace access. Human live view uses X11/XTest or ScreenCaptureKit/separate human cua input, at 30 Hz with JPEG dirty rectangles and zero idle payload; agent actions/observations stay on cua. Controller revisions cancel in-flight agent work without locks across I/O. Run extension freshness/unit tests and machine container e2e in PR CI. Performance measurements and repeatable commands:docs/MACHINE_NODES.md#validation-and-measurements. - Machine automation turns retain live machine/login grants and owner-control fences. Webhook confirmation is additive to
machine_confirm; one exact, one-use owner card satisfies both. Exec, file writes/saves, job cancellation and mutating computer input are destructive; checked login fills and owner-control requests are changing only. Apply the gate in the machine adapter after normalization so direct and universal tool calls agree. Machine gateway streamed uploads bind exact services and never retry another node or pool member; declared pools support buffered SDK/JSON requests with normal failover and live member ACLs. Catalog discovery projects one ID-bounded batch. All human machine routes reuselogin_client_context::require_first_party_human; desktop upgrades also retain the/assistant/nyxagent/*OAuth-client rejection layer.
7. OpenClaw Integration
OpenClaw is a self-hosted AI gateway integrated at three levels (details: docs/OPENCLAW_INTEGRATION.md):
- Provider: seeded as an
api_keyprovider withrequires_gateway_url: true; users supply gateway URL + bearer token.UserProviderToken.gateway_urlstores the per-user instance URL;proxy_service::resolve_gateway_url_override()overrides the service's defaultbase_urlat proxy time. - Node proxy:
nyxid node openclawstores credentials locally, registers the provider connection, and creates the node service binding in one step. Flow: NyxID -> node agent (WS) -> local OpenClaw; the node agent injects the bearer token from its credential store. - Channels:
openclaw_channel_servicehandles inbound webhooks from OpenClaw channels (WhatsApp, Telegram, Discord, ...);openclaw_channel_mappingsmaps channel users to NyxID users, each with its own per-user webhook secret (SHA-256 hash stored, raw secret returned once). No server-level env var needed.
Key files: services/openclaw_channel_service.rs, handlers/openclaw_channel.rs, models/user_provider_token.rs (gateway_url), models/provider_config.rs (requires_gateway_url).
8. Streamlined Services Architecture
Services/connections/providers were unified into 3 user-managed collections plus one orchestration layer; old collections are kept for backward compatibility during migration.
- Collections:
user_endpoints(target URLs, custom or from catalog),user_api_keys(external credentials: API keys, OAuth tokens, bearer tokens),user_services(proxy routing config: endpoint + key + auth method + optional node + identity propagation + custom User-Agent override) unified_key_serviceauto-provisions all 3 records from a singlePOST /api/v1/keysrequest, using catalog defaults or user-provided values- Proxy resolution checks
UserServicefirst (by slug + user_id), then falls back to the legacyDownstreamService+UserProviderTokenpath for unmigrated users - OAuth resource indicators: RFC 8707 resource URIs for user services are deterministic and not stored. The canonical URI is
{BASE_URL}/api/v1/proxy/s/{slug}where{slug}isUserService.slug; catalog and user-services responses expose this asresource_uri. OAuthresourceparameters resolve activeUserServicerows through the same personal/org ACL model used by proxy resolution. Issued JWTs keep the fixed NyxID audience while carrying granted resource URIs in aresourcesclaim plusallowed_service_idsfor enforcement. - Proxy User-Agent: client UA is forwarded as-is by default;
UserService.custom_user_agent/DownstreamService.custom_user_agentoverrides it in all four proxy paths (direct HTTP, node HTTP, direct WS, node WS). Use for downstreams whose WAFs block SDK UA strings (e.g.OpenAI/Python). ApiKeyscope fields (absorbed from the deletedAgentGroupmodel):allowed_service_ids,allowed_node_ids,allow_all_services,allow_auto_connected_services,allow_all_nodes; enforced at proxy time viakey_service- Frontend: unified "AI Services" page at
/keyswith 2 tabs (External Services; NyxID API Keys with scope). Services/Connections/Providers removed from the normal user sidebar (admin-only); old/api-keyspage deleted. - Legacy models kept for migration: DownstreamService (now the read-only catalog), UserServiceConnection, UserProviderToken, UserProviderCredentials, NodeServiceBinding (node routing absorbed into
UserService.node_id) - Lifecycle is exactly two actions, named Disable/Enable (reversible, sets
UserService.is_active) and Delete (hard-deletes credential + endpoint, leaves anis_active: falsetombstone). Do not introduce further synonyms;revokedis a credential status, not a button verb.GET /keysis the one listing that returns disabled services — consumers MUST readis_activerather than assume every row is usable, and MUST NOT renderstatus(the credential's) as the service's state. Every credential-resolving or catalog path keeps the active-onlylist_user_services_with_sources; onlylist_keysuses the_including_disabledvariant, with effective service-allowlist filtering on top for restricted API keys./keys/{id_or_slug}resolves a disabled row by UUID but deliberately not by slug — full rationale and the two known gaps indocs/AI_SERVICES_ARCHITECTURE.md. - AI-service inventory GETs under
/api/v1(/keys,/keys/{id_or_slug},/keys/{id_or_slug}/authorization,/user-services,/endpoints,/endpoints/{id}/authorization,/endpoints/{id}/openapi-endpoints,/api-keys/external,/api-keys/external/{id}/authorization,/mcp/config,/catalog,/catalog/{slug},/catalog/{slug}/endpoints) accept general API keys without provisioning or lazy pending-OAuth reconciliation./mcp/configrequiresproxyorproxy:*scope and matches stateless MCP discovery, including chat acknowledgement semantics. Restricted keys use their effective service allowlist and backing endpoint/credential references; org-owned keys act as the org (credential_source.type: "personal"), personal keys use active Member/Admin memberships and effective role scopes. Inventory writes and NyxID/api-keysmanagement stay human-only for API keys; delegatedaccount:readparity is unchanged.
Platform-admin service account create/update with explicit catalog:skills:read/write scopes atomically sets server-only catalog_scope_authorized=true, sticky purpose=catalog_editor, and protection. These accounts use matching token/live catalog scopes across all existing and future catalog services without catalog roles, activation, or per-resource grants. /keys and /keys/{uuid} need only catalog read scope and return projected catalog metadata with catalog UUIDs and resource_type: "catalog_service"; no private connections. Legacy editors (marker absent/false) retain live global nyxid:catalog:skills:read/write role checks and additional user-services:read for key GETs until explicit admin scope save. Stored General/Curation scope strings never auto-elevate. Skill writes transactionally fence account/token authority and legacy authorizing roles. General and legacy Curation SAs retain their separate connection metadata grant behavior. CatalogEditor Ornn proxy resolves the exact catalog UUID or slug; operation policy is optional only for scope-authorized editors and configured policies remain enforced. Scope-authorized editors may use the guarded internal catalog credential (JWT/Both identity, no provider configuration, platform key, or destination targets); forwarding requires a signed SA identity. Legacy editors and Curation retain mandatory policy and dedicated credentials. See docs/SERVICE_ACCOUNTS.md.
Key files: services/unified_key_service.rs, services/catalog_service.rs (list_catalog_all), handlers/keys.rs, handlers/catalog.rs, models/user_{endpoint,api_key,service}.rs.
CatalogEditor PUT /keys/{catalog_uuid} accepts only recommended_skill_refs with live/token catalog write authority (plus the existing role for legacy editors). It uses the shared skill transaction against one server-observed revision, returns safe metadata without requiring read scope, and never rebases conflicts. Explicit revision/replay clients use /catalog-curation/services/{id}/skills. Human key writes keep their original handler; other SA purposes, API-key, delegated, and relay writes remain denied.
9. Agent Isolation
Per-agent credential binding, rate limiting, and audit attribution: each agent (Claude Code, Codex, OpenClaw, ...) uses its own scoped API key (nyxid_ag_ prefix). Details: docs/AGENT_ISOLATION.md.
- General agent keys can GET
/orgs,/orgs/{key},/orgs/{key}/authorization,/orgs/{org_id}/members,/orgs/{org_id}/members/{member_id}/authorization, and/orgs/{org_id}/role-scopesunder/api/v1, with membership/admin ACLs and no extra scope. Org-owned keys list their own org with Direct read access projected asyour_role: "admin"; all writes, invites (including GET), and primary-org changes remain human-only for API keys. Scheduled-invocation keys remain denied; delegatedaccount:readparity is unchanged. ApiKey.allow_auto_connected_servicesadds active, same-owner auto-provisioned and explicit platform-bound service IDs to restricted keys at auth-context construction; defaults to false. Human/delegated key listing, Agent Key login delivery (login options), and device-code approval/onboarding for the acting person's own account invoke shared provisioning. Public platform services create personal auto rows only; restricted platform services may create org rows only for allowlisted orgs reached through active Member/Admin memberships withcan_proxy()and explicit grants. The 0.19.0 guarantee remains: org-targeted device approval/onboarding resolves existing org services and never provisions rows for the target org as a side effect of targeting. Grant removal or a switch to public reconciles those org auto rows away; startup also removes legacy public org auto rows. Legacy no-auth provisioning remains personal-only during membership traversal. JWT/API-key authentication itself never provisions rows.AuthUsercarriesapi_key_id,api_key_name,rate_limit_per_second,rate_limit_burstwhen auth is via API key;ApiKeyhasrate_limit_per_second,rate_limit_burst,platform;AuditLoghasapi_key_id,api_key_namefor attributionnyxid-assistantkeys belong to one chat, cannot be channel route agents, and cannot be widened by native chat tools. InternalASSISTANT_ACCOUNT_SCOPE(assistant:account) is held by NyxBot thread keys and by specialist thread keys with anaccount_readgrant (read-only tools); it is excluded from public scope assignment and grants no REST management authority.AgentServiceBindingmaps(api_key_id, user_service_id)to an overrideuser_api_key_id; the proxy handler checks bindings before credential injection and falls back to the service defaultPerAgentRateLimiter(mw/rate_limit.rs): per-API-key buckets, 1-second sliding window. Proxy responses includeX-NyxID-Agent-Idwhen the request used an API key.- CLI:
--profileflag onAuthArgs,LoginArgs,BaseUrlArgs, and all node commands (envNYXID_PROFILE); token storage~/.nyxid/profiles/{name}/(default profile uses~/.nyxid/); profile names 1-64 chars, alphanumeric + hyphens + underscores nyxid api-key create --platformandnyxid api-key bindmanage agent identities (consolidated from formerai-setup agentsubcommands)--orgflags accept UUID, slug, or display name, resolved in that order: UUID locally, slug viaGET /orgs/{slug}, display name via oneGET /orgsfetch (errors with candidate rows when ambiguous). Org users have an auto-generatedslug(visible innyxid org list).nyxid service add-sshalso accepts--orgfor org-owned SSH services.- Frontend: API key detail page has platform selector, rate limit editor, and bindings CRUD; the key table shows platform and bindings count
Key files: models/agent_service_binding.rs, services/agent_binding_service.rs, handlers/agent_bindings.rs, services/proxy_service.rs (resolve_agent_credential_override), cli/src/commands/api_key.rs, frontend/src/hooks/use-agent-bindings.ts, frontend/src/schemas/agent-bindings.ts.
10. Catalog Metadata and Endpoint Discovery
Rich metadata on DownstreamService so agents can discover service docs, repos, capabilities, and API endpoints without guessing (issue #148; details: docs/API_DISCOVERY.md).
- Fields:
homepage_url/repository_url/issues_url(validated URLs);capabilities(ServiceCapabilitiesboolean flags:supports_proxy_read,supports_proxy_write,supports_proxy_binary_upload,supports_direct_downstream_auth,supports_authoring_via_nyx,supports_websocket,supports_streaming);auth_notes/known_limitations(max 4096 chars);required_permissions(max 100 entries, 256 chars each) - API: catalog GETs require authentication and accept general API keys without proxy scope; service accounts remain rejected because catalog detail requires a User actor for restricted platform-grant membership lookup; delegated
account:readparity is unchanged. Template metadata/live grants never include instance overrides; instance-backed private access and mounted-spec fallback use effective API-key inventory scope.GET /api/v1/catalog?include_all=trueincludes system services that require no downstream credentials (default filters to connectable);GET /api/v1/catalog/{slug}/endpointsfetches + parses the OpenAPI spec (JSON, or YAML with bounded alias expansion) via hardenedapi_docs_service::fetch_spec_json(DNS pinning, 5MB limit, 60s cache); adminPOST/PUT /servicesaccepts all metadata fields with URL validation and length limits - CLI:
nyxid catalog list --all,nyxid catalog show <slug>,nyxid catalog endpoints <slug>. Frontend: "Service Metadata" sections on the service edit and detail pages. - Legacy:
migrate_legacy_api_spec_url()runs at startup to renameapi_spec_url->openapi_spec_urland remove duplicates; the update handler also includes$unset: { api_spec_url: "" }. - Hosted overlay specs: hand-curated OpenAPI 3.1 overlays with
x-aevatar-toolannotations live inbackend/specs/catalog/and are served publicly at/api/v1/catalog-specs/{spec_key}/openapi.json(services/catalog_spec_registry.rs; several slugs may share one overlay, e.g. github / lark-feishu pairs). Seeded rows getopenapi_spec_urlfrom the registry (insert-time + null-guarded backfill; admin-set URLs never overwritten).services/catalog_spec_sync.rsruns at startup and additively upsertsServiceEndpointrows from the overlays (matched by name; admin-added endpoints never soft-deleted) so/api/v1/mcp/configpublishes concreteservice_id+endpoint_idoperations for catalog-backed user services (issue #1290 / Aevatar v4 workflow admission). - MCP catalog precedence: a valid instance-mounted
openapi_spec_urlon a catalog-backed UserService overrides the template'sServiceEndpointrows (per-instance override wins); a broken/empty instance spec falls back to template rows when they exist, else degrades to the generic proxy tool. No instance spec -> template rows; empty + no spec still drops the service from the operation catalog. - Spec-URL auto-discovery: active HTTP catalog services with an
openapi_spec_urland zeroServiceEndpointrows get discovery run automatically (startup background sweep + on admin create/update with a spec URL) via the hardened fetch path; private/internal spec URLs still need the manualdiscover-endpointsroute, and services with existing rows are never auto-touched. - Overlay drift guard:
.github/workflows/catalog-spec-drift.yml(weekly + manual) runsscripts/check-catalog-spec-drift.pyto verify every overlay operation still exists in the official upstream spec for providers that publish one (OpenAI, X, Discord, ElevenLabs, Twilio); red = update the overlay by hand, never auto-updated.
10a. Catalog Skill Curation
- Dedicated Curation service accounts carry one live embedded grant with exact
DownstreamServiceIDs, persisted write budget, optional Ornn proxy target, and sticky platform protection. Curation Ornn targets require an explicit existingproxy_operation_policyat grant issuance and live resolution; use a dedicated endpoint with exact skill CRU/read rules, since Ornn also has auth-only execution routes. Only platform admins issue/revoke grants or manage protected credentials/roles; ordinary SA request DTOs must reject grant/purpose/protection fields. - The verified SA extractor confines Curation to grant-scoped
/catalog-curationand ordinary HTTP/proxy/{exact_ornn_catalog_id}. No slug routing,_nyxid_via, WS, MCP, LLM, owner connection/node/endpoint inheritance, or self-management. General SA routing stays unchanged. Validate every SA JWT against its persisted token identity/scope/expiry/revocation and current credential generation, including MCP/introspection; generation changes atomically with secret rotation. - Human and machine recommendation writes share
catalog_skill_service: service metadata/skills, revision/history, durable actor/request receipt, and machine budget/fences commit in one MongoDB transaction. Pure no-op has no mutation/receipt/effects; metadata-only mixed changes need a receipt without phantom skill history. Keep external identity/billing/OIDC/discovery effects after commit and repair retries from current committed state. - Preserve the existing names-based catalog digest; refs use a separate versioned skills digest. An instance name override suppresses catalog refs. NyxID owns recommendations, Ornn owns package bytes. Upgrade all auth/proxy/MCP replicas before enabling Curation credentials; disable/revoke before rollback. See
docs/SERVICE_ACCOUNTS.md#catalog-skill-curation.
11. Oracle Relay (browser LLM pools)
Generic async task relay: any NyxID user or agent calls a browser-driven LLM through /api/v1/oracle. A pool owns the shared worker token and quotas. A worker is the supervised CDP daemon or the unchanged userscript. Browser details stay in worker clients. Full design: docs/ORACLE_RELAY.md.
- Models: all documents use UUID-string
_idvalues andCOLLECTION_NAME.OraclePooluses the polymorphicuser_idowner.OracleTaskstores prompt and response bodies, task status, lease, serde-defaultedretry_count/max_retries/attempt_count, optionaldispatch_attempt_id, and terminal TTL.OracleSessionstores multi-turnconv_...metadata.OracleWorkeruses{pool_id}:{label}and has defaulted presence, capability, health, installation, and desired-state fields.OracleWorkerCommandstores leased, bounded command delivery.OracleLoginSnapshotstores only an outer-encrypted copy of an already end-to-end-sealed envelope with a one-hour TTL. - Queue and recovery (
oracle_task_service): MongoDB FIFO claim sorted bycreated_at; no in-memory state.task_timeout_secsdefaults to four hours andackrefreshes the lease. Lease expiry and worker-reported pre-sendbrowser_recovery_exhaustedconsume the same infrastructure retry budget and requeue to the FIFO front while retries remain. Exhaustion fails withinfrastructure_retry_exhausted. Fresh claims increment attempts; idempotent reclaims do not. Capable clients echodispatch_attempt_idon ack/result/pin/transcript so stale attempts cannot settle replacement work.client_refremains submitter-scoped submit idempotency. - Worker identity and commands:
POST /pools/{pool}/workers/allocatereserves a unique label: server-generated by default, or an operator-chosenlabel(validated; an existing unbound legacy row is adopted, a label bound to another installation is refused with 11014). New CDP workers persist a stable installation ID, so two installations cannot share one label. Managers can queuedrain,resume,restart,relaunch_browser,relogin, andupgrade;session_importis internal.DELETE /pools/{pool}/workers/{label}/commands/{id}(worker cancel-command) withdraws a queued or delivered-but-unexecuted command; delivered ones are dropped by the worker on its next heartbeat viacancelled_command_ids.DELETE /pools/{pool}/workers/{label}(worker forget) removes a stale presence row and its commands and releases the label's session affinity; it refuses online or busy workers unlessforce=true. Commands arrive only through capability-gated heartbeats, use delivery leases and bounded redelivery, and carry metadata-only audit records. Legacy userscripts advertise no capabilities and never receive commands or new protocol shapes. - CDP resilience: transient HTTP failures retry forever with capped jittered exponential backoff. CDP disconnects reconnect, repeated CDP and task-level failures relaunch configured Chrome, and tab failures reopen ChatGPT and restore the project URL. Task recovery has a bounded failure count. The mode
0600state file stores task ID, attempt ID, conversation URL, phase, transcript baseline, and failure counters only. Persistsend_attemptedbefore Send. After recovery, extract a completed matching turn, wait for an existing pending turn, or send only from a known pre-send phase. An uncertain post-send transcript must fail withprompt_delivery_uncertain; NEVER resend that prompt. Reasoning-level selection (selectModel) runs under a cooperative deadline with an abort signal, opens the structural composer pill regardless of locale, only treats menus that appeared after the pill click as the picker, never clicks an unrecognized entry, and is followed by a bounded composer-unobstructed guard before typing and before Send; the model family/tier is verified before the effort pill and again before Send.require_model_matchdefaults true on pools/tasks; switcher mismatch or recognized effort evidence that cannot verify fails pre-send asmodel_unavailable(unrecognized Tools/attach controls do not). Families parse generic major/minor versions; compare minors only when both exist. Exact tier-only entries require matching family context; at most one exact-family submenu is opened with a new menu identity baseline. Plain-proandextended/扩展prefer Pro Extended;standard/标准explicitly chooses Standard. Acks runpage_ready->selecting_model(second ack carries metadata-onlyphase_detail) ->ready_to_send->sent. Raw picker labels are logged only withNYXID_ORACLE_LOG_PICKER_LABELS=1. Model family/tier verification (selectModelSwitcher) prefers the header switcher and otherwise accepts a unique compact<version>\n<tier>menu button inside the composer form (also recognized as picker items); the marked switcher trigger is never an effort-pill candidate. - Failure attribution and capacity: bounded
failure_detailisstable_code@phase, never error text; preserve the last underlying cause through infrastructure exhaustion and delivery uncertainty. One metadata-only structural probe accompanies settlement.page_crashedreplaces the tab. After Send, empty output and scoped ChatGPT error UI reload once, recheck the send fence, then wait even without a generation indicator or fail as task errors; persistent pre-send error banners use one reload and one DOM-shape relaunch cycle.usage_limit_reached/model_unavailableuseexcluded_worker_idsand at most 20 capacity reroutes, independent of infrastructure retries; capacity failures settle with the original code when no eligible alternate has recentlast_seen_atfrom heartbeat/ack/claim (busy workers count), or the task is account-pinned. Usage cooldown defaults to 900 seconds (NYXID_ORACLE_USAGE_COOLDOWN_SECS); heartbeats continue without claims. Pool status exposes embedded bundle version and outdated online count; results and capacity reroutes retain canonical switcher/effort observations, with a diagnosticselecting_modelack before strict failure. Presence ignores and unsets legacypage_url. Old workers remain additive-compatible. - Pool-wide login:
nyxid oracle login <pool>performs password, OTP, SSO, and Cloudflare work in local Chrome, captures allowlisted ChatGPT/OpenAI cookies and storage through CDP, and encrypts locally with AES-256-GCM using HKDF-SHA256 from the raw pool worker token. The manager uploads only a 512 KiB-capped sealed envelope and token hash verifier, then stops Chrome and deletes the temporary capture profile. The server validates the verifier, wraps the sealed envelope withEncryptionKeys, TTLs it for one hour, and queuessession_importto capable workers. Workers defer import until task settlement unless a logged-out task cannot continue, decrypt locally, import through CDP, verify the logged-in DOM, and report per-worker results. A device-bound rejection is a clear verification failure. The persisted server state cannot derive the HKDF key, but the live backend sees bearer tokens while authenticating worker requests. - Worker token and bundle:
nyx_owk_...is 32 random bytes; only SHA-256 is stored, and create/rotate shows it once. Install and login use a local token file, environment variable, or hidden prompt and NEVER rotate implicitly. The backend embedsworker.mjs; manager and worker-token endpoints return source, version, SHA-256, and the exactplaywright-coreversion. CLI install and worker upgrade verify SHA-256. Worker upgrade runs npm only when the installedplaywright-corediffers from the manifest pin (bundle-only upgrades need no npm or network), using the install-time absolute npm path (NYXID_NPM_EXECUTABLE) with node's directory on the daemonPATH, and restorespackage.jsonon failure. launchd or systemd restarts the worker after upgrade. - Org worker enrollment:
worker install --pool <pool>automatically enrolls active Member/Admin contributors in org-visible pools using NyxID authentication; owners/admins can also enroll in pools they manage. No shared token is requested. CLI generates and privately persists anyx_owi_installation credential beforePOST /pools/{pool}/workers/enroll; the server stores only its hash. Every worker route checks actor/org activity, membership ID + join timestamp, pool token epoch, label, and installation. Members manage their own contributed workers; admins manage all. Enrollment inventory is capped at 256 separately frommax_workersdispatch concurrency. Rejoining after revocation/rotation requires authenticatedinstall --forceand a fresh credential (11016). New installs use their own browser accounts; shared-login capabilities and envelope access are excluded. Existing/explicit pool-token installs retain saved-login support. - ACL and compatibility:
ensure_can_submituses visibility andorg_service::resolve_owner_access;ensure_can_managegates pool mutation, legacy worker allocation, and login fanout. Worker management also permits eligible contributing owners throughoracle_worker_enrollment_service. Worker commands bind an immutable generation to prevent label-reuse races; enqueue/cancel/forget fence the authorized worker in Mongo transactions. Bundle download requires ordinary authentication; installation proves enrollment or manager access and verifies the worker endpoint's pool ID. Unauthorized task/session reads are not-found-shaped. Startup rewrites exactly the retired pool defaultchatgpt-5.5-protochatgpt-6-proidempotently. All new fields are optional or serde-defaulted. Existing rows, deployed userscripts, and old CDP workers remain valid. - Privacy: prompt, response, transcript, attachment, attachment filename, generated files, generated filenames, session, cookie, storage, raw-token, conversation-URL, and signed-image material must NEVER appear in logs or audit. Prompt, response, and generated artifact bodies live only on the task document and expire after
ORACLE_TASK_RETENTION_DAYS. Worker state contains metadata only. Login snapshot logs and audit contain IDs, sizes, target counts, status, and stable error codes only. Secret-bearing structs need redacted customDebug. - CLI: consumer and pool commands remain. Worker operations add
worker list/show/install/start/stop/status/logs/uninstall, control verbs, andworker upgrade.worker listreports only online workers by default and--alladds offline rows with their last-seen age.worker upgrade --pool <pool>waits for and verifies the installed local worker. Adding--labelqueues an asynchronous remote upgrade.oracle login <pool>performs local capture and pool fanout. Installs live under~/.nyxid-oracle/<pool>/, with named profiles underprofiles/<name>/, and reuse the node daemon's launchd or systemd pattern.
Key files: models/oracle_{pool,task,session,worker,worker_command,login_snapshot}.rs, services/oracle_{pool,task,session,worker,login_snapshot,worker_bundle}_service.rs, handlers/oracle_{pools,tasks,worker,workers,worker_bundle}.rs, cli/src/commands/oracle.rs, cli/src/commands/oracle_worker_daemon.rs, integrations/oracle/cdp-worker/worker.mjs, integrations/oracle/nyxid_oracle.user.js.
12. Auth Device-Code Login
First-party RFC 8628-style login: plain nyxid login and --device display a short user_code; a human chooses account access or a restricted Agent Key in the web UI or mobile app. Explicit --agent-key remains restricted-only.
- Storage and rollout: legacy
auth_device_codesremains account-only./auth/device/v2/{request,poll,poll-web}uses isolatedauth_device_codes_v2andnyx_adc2_poll secrets. Both protocols default to eight-characterXXXX-XXXXhuman codes;AUTH_DEVICE_EIGHT_CHAR_CODES=falserestores2-XXXX-XXXXv2 issuance, and both formats remain readable. Shared preview/decisions search both collections, reject ambiguous matches and use shared code reservations. Capability comes fromsupports_grant_choice, not spelling. Never retry v2 through legacy polling. Both collections store HMACs of codes, sanitized context and encrypted deliveries; raw codes and token plaintext never persist. Terminal TTL usespurge_atonly after cleanup; an indexed expiry sweep retains unfinished revocations. When upgrading replicas without shared readers/reservations, explicitly keep the flag false until they are drained; followdocs/ADR-015-auth-device-login.mdfor rollout and rollback. - Routes:
POST /auth/device/request,/poll, and/previeware public (no auth)./poll-webis also public but is a first-party browser-only delivery surface: it shares the/polllimiter, atomically claims the same delivery, revokes the approve-minted JWT session, and creates a freshnyx_sessioncookie session without returning tokens. Preview is non-mutating and returns untrustedclient_label/client_user_agentplus server-observedclient_ip, Z-suffix timestamps, and status.POST /auth/device/approveand/denyare human-only: JWT session user; API keys, service accounts, delegated tokens, and relay tokens are rejected before handler execution. Approve and deny race atomically onstatus = pending; deny mints no tokens and the next poll returns 11204. All routes are rate-limited per IP; decisions also share a per-user limit. - Grant decisions and delivery: only first-party human sessions/access JWTs without an OAuth client ID can decide grants. Restricted selection uses
/auth/device/approve-agent-key, so an old replica cannot silently issue account access. Issuance and approval commit together. Decrypt before atomically claimingapproved->delivered, retaining retryability on KMS failures. Account browser delivery atomically revokes approval bearer credentials and creates the cookie session. Restricted browser delivery returns a one-time CLI handoff without cookies; handoff redemption and direct polling have one winner. Abandonment revokes only its session/child, preserving reused parent configuration and other consumers. - Rate limiters:
auth_device_{request,poll,approve,approve_per_user,preview}_limiter(/poll-websharespoll) - CLI output: JSON includes
user_code, bareverification_uriandverification_uri_complete; text output and browser opening use the completed link, which carries only the public code and validated preference hints. Poll secrets never appear in output.-c/--clipboardbest-effort copies only the user code before browser opening; failure prints one stderr line and continues. Clipboard conflicts with--passwordand--code, but is allowed with--callbackfor the device-code fallback.--no-wait --output jsonreturns a local request handle and completed login link without copying, opening a browser or polling. Explicit device/Agent Key login on stdin+stderr TTYs promptsOpen in your browser? [Y/n]and opens viacrate::browser::open_browser; failure leaves manual URL entry available. Without a TTY, explicit modes skip the prompt and poll. - CLI dispatch: plain blocking login deliberately defaults to selectable device v2, including desktop: it is the only terminal-originated flow with requester attribution (IP, timezone, origin, screen) and the human's account/restricted Agent Key choice (#1535). This motivated 0.16.0 (
78cb26b), whose commit message omitted the rationale.--callbackselects the legacy local browser callback (full account session, no code entry or requester review), with CannotOpenBrowser -> device-code fallback.NYXID_LOGIN_NO_DEVICE_FALLBACK=1is its legacy alias through the same dispatch path.--callbackconflicts with password/device/Agent Key/code/no-wait flags and rejects--output jsonorlogin resumeat the top of CLI dispatch (no callback JSON/resume contract). Without--callback, explicit device/Agent Key/code/resume/JSON/no-wait modes keep the exchange.--no-wait --output jsonnever waits or opens a browser;login resume <REQUEST_ID> [--once]uses a mode-0600 local handle bound to profile/destination, persists backoff/deadlines and returns distinct stable JSON errors. Poll secrets never appear in output. - Verification page (
/login/device): validates?user_code=and bounded preference hints, retains them in the URL and performs a non-mutating public preview on mount for a valid code. Manual code entry previews only after Continue. Invalid input fails visibly. Preview, scanning and verification never approve the requester. Review echoes the formatted code through final confirmation and asks the approver to match it against the requesting device/terminal and reject a mismatch (RFC 8628 §§3.3.1, 5.4). Account approval and key permission confirmation require first-party human authentication and explicit decisions with >=750 ms throttling. Legacy rows only offer account access./login/codeis a mint page without a code input. Anonymous phone preview leaves browser account cookies/storage untouched. Login-grant routes suppress telemetry even after SPA navigation from an opted-in page. Seedocs/DEVICE_LOGIN_PROTOCOL.mdfor the URL contract. - Approval identity:
/auth/approvalowns request-bound browser verification: begin, status/cancel, password/MFA, inventory and final approval/denial, plusPOST /{id}/appand/app/poll.LoginMethodsshares configured social providers, the NyxID app and enabled email/password between normal and approval login. Only for this request creates no general session; Keep me signed in creates one at verification. Password MFA remains required when configured; social providers own their challenges and app verification uses an existing human session. App rows carry a server-onlylogin_approval_id; ordinary poll routes cannot redeem them. Publish this frontend only after all backend replicas support it. Roll back the frontend and drain outstanding app identity requests before a backend rollback. - Mobile approval:
CameraViewscans only QR codes whose shape ishttps://<frontend>/login/device?user_code=...ornyxid://login/device?user_code=.... The app extracts and normalizes onlyuser_code; every request uses its configured API base URL. Deep links prefill without making a request. Preview and approve/reject remain separate explicit actions, share the >= 750 ms throttle, and never auto-approve. - Web login: the unauthenticated login page can start the browser delivery flow with an explicit click, showing both the QR payload and manual code; it never starts on mount or auto-regenerates codes.
- One-time codes: web/mobile settings mint through
/auth/login-code; public/redeematomically claims and issues either grant. Issuer-only status, cancellation and revocation expose no secrets. Five-minute codes are limited by source and owner and stored only as HMACs. Browser handoff extends the initial 60-second delivery window to approval + 300 seconds; repeated handoffs never extend that fixed deadline. First-party JWTsidchecks live session state during protected access and refresh; issuer revocation cascades to MCP and invalidates refreshed access too. - Local identity lifecycle: login replacement, refresh snapshots and logout use a profile generation under the refresh lock. An in-flight request cannot retry another login's token, including a replacement at the same destination. Bounded logout clears only the matching generation. Explicit credentials do not require profile storage or fall back to another identity.
13. Hosted Connect Links
Single-use hosted credential setup for agents and CLI callers. An authenticated creator requests a catalog service link and gives the returned URL to the same account's human user. App callers can receive lifecycle webhooks; polling remains available. See Third-party Connector Integration for the API and webhook contracts.
connect_linksstores UUID-string IDs and only SHA-256 hashes ofnyx_clk_tokens. Raw tokens appear once in the hosted URL and must never be logged, audited, or persisted in OAuth state.- Links default to 15 minutes, are clamped to 60-3600 seconds, and retain an observable
expiredterminal state through atomic query-time expiry claims. An OAuth or device flow pinned before expiry gets 30 minutes of finalization grace, then expires if it remains pending. - App-bound abandoned links are also claimed by the
CONNECT_LINK_EXPIRY_SWEEP_INTERVAL_SECSbackground sweep soconnect_link.expiredwebhooks do not depend on polling.0disables the sweep. - Preview is public and rate-limited but non-mutating. Completion is human-session-only; API keys, service accounts, delegated tokens, and relay tokens are rejected before the handler. Personal completion requires the exact creating account; org-owned completion uses
org_service::resolve_owner_accesswrite access. Unauthorized access is not-found-shaped. - Normal authorization-code access tokens issued to registered developer apps may create, read, and creator-cancel connect links; their JWT
client_idbinds the link to the active app record. Delegated, relay, and service-account tokens remain rejected on that route group, and no other rejection layer is weakened. App callbacks useoauth_service::validate_clientagainst registered redirect policy, while sessions and agent API keys retain shape-only HTTP(S) validation. The authenticated app ID/name overrides untrusted request-body attribution. - Hosted human decline uses the same raw-token and owner checks as completion but only transitions the link to
cancelled. Every terminal callback is built from the stored URI withstatusandconnect_link_id; existing query parameters are preserved, reserved parameters are replaced, and raw tokens are never added. Provider callback errors store only a normalizedlast_errorcode and timestamp while the link remains retryable. - API-key and OAuth provisioning must reuse
unified_key_service; completion is atomically serialized and single-use. OAuth state carries onlyconnect_link_id, while the browser keeps the raw token in session storage across the redirect. - MCP callers use
nyx__connect_servicefollowed bynyx__wait_for_connection. A pending link must not activate service tools or emittools/list_changed; activation happens only after completed status is observed.
13a. Bot Connection Links
- Tracked bot setup uses separate
channel_connect_linksstorage,/api/v1/channel-connect-linksendpoints, and/connect/bot/{token}. Preserve the existing service Connector link contracts and reusable channel setup URLs. See API reference and implementation and lifecycle. - Owner, platform, and label are fixed at creation. Agent Keys can create/read/cancel; setup routes require a human account with owner write access. Telegram consent remains bound to the account that started it, including for org-owned bots.
- Renewable claims fence setup. Bot insertion and link association are transactional, as are Telegram request insertion and association. Completion reserves one stable terminal event snapshot atomically. Manual
pending_webhookcan count as saved; managed setup must satisfy its readiness checks. Never discard a successful secret-bearing response because terminal recording failed. - Events are
channel_connect.completed,.cancelled, and.expired. App callers use their registered connection webhook; direct callers receive one encrypted-at-rest signing secret once. Bot delivery opts into public HTTPS validation, DNS pinning, redirects disabled, and a separate app quota. Preserve the existing Connector delivery path. The independent bot sweep sharesCONNECT_LINK_EXPIRY_SWEEP_INTERVAL_SECS;0disables both sweeps. - CLI direct webhooks require
--webhook-signing-secret-filewith--webhook-url. Create a new file with mode0600on Unix; reject existing paths and symlinks before creating the link. JSON and terminal output contain the file path and key ID only. Keep the raw secret out of output and logs; the direct HTTP API still returns it once.
14. Connection Webhooks and Triggers
- Developer-app connection webhooks use a server-generated secret encrypted with
EncryptionKeys. Secrets are returned only by configure/rotate responses, alongside a non-secret key ID. Delivery signsX-NyxID-Timestamp + "." + raw_bodywith HMAC-SHA256 and sends the signature, timestamp, event type, delivery ID, and key ID headers. Connect-link terminal events use the link as a durable bounded outbox; connection-expiry events remain best effort. Transition paths never depend on delivery success. - Outbound webhook configuration requires HTTPS and public DNS/IP targets. Apply
webhook_delivery_service::validate_webhook_urlto every new server-fetched webhook URL. - Trigger inbound secrets use the
nyx_trg_prefix and are SHA-256 hashed. HMAC verification additionally retains an encrypted copy because verification requires the raw key. Trigger and delivery types are serde-tagged enums; all secret-bearing structs use redactedDebugimplementations. - Trigger ingress is public; unknown and disabled triggers are not-found-shaped, then per-trigger rate limiting runs before body reads, HMAC decryption, or verification. Webhook-target envelopes are persisted only in
trigger_deliveries, encrypted withEncryptionKeys, and TTL-expired for durable dedup and authenticated replay;TRIGGER_DELIVERY_RETENTION_HOURS=0stores metadata only. Agent and notification payloads are never persisted; their event IDs use fenced, TTL-expiring dedup claims in MongoDB. Agent targets enter through the trusted channel-event service path without broadening the public channel-event auth contract. - Automations extend
Triggerwith defaultedwebhook/schedulesource andassistantdelivery. Schedule verification has no inbound secret or URL and ingress refuses it. Upgrade all replicas before creating automations: old readers fail on new enum variants, including owner lists and ingress; existing retries/replay and delivery TTL never sweep or delete automation rows. - Use covered, leased
trigger_workand UUID-v5 occurrence identities; advance schedules atomically with occurrence insertion and admit assistant runs in the turn transaction. Fence stale workers and never replay started turns. Missed history is one count/bounds summary plus one audit; history is metadata only and bounded, with counter-gated trimming. - Trigger turns preserve normal owner/agent authority and the existing turn pool without changing event streaks. Enforce separate owner budgets and per-trigger overlap. Card decisions wake the same run transactionally; expiry is the fallback, and continuations consume no extra run budget. Busy work uses bounded backoff; exhausted budgets wait for their next window with one notice. Avoid duplicate browser/channel continuations; result delivery uses live ACLs and one claimed outbound attempt.
- Automation management, run history and timezone/budget settings require the shared first-party human guard; legacy trigger API-key rules stay unchanged. Only NyxBot exposes schedule tools. Store webhook prefill on an owner-bound watch, fetch it through authentication and consume it in the insert transaction. URLs contain only the watch ID; secrets stay on the page. Audit never includes instructions or payloads. Reuse trigger errors 11600–11606. See
docs/NYXBOT_SCHEDULES.mdfor limits, APIs and rollout details. - Webhooks default to dedicated threads for every agent and
confirmation_policy = changes. Dedicated/per-run automation threads must never be adopted as home, including after home deletion. Explicithomeordestructivechoices require UI/tool/setup warnings: home retains untrusted text for later full-authority owner/private-channel turns, outside the webhook policy. Classify changing calls through shared HTTP/catalog and native-tool contracts, snapshot policy per run, and never let global skip-destructive bypass it. Schedules retain NyxBot-home/specialist-dedicated defaults and normal owner confirmations. - Cron gaps collapse at the first valid instant, deduplicated against real matches; folds use the earlier instant. Persist instants as UTC BSON dates; parse/format RFC3339 only in DTOs. Every NyxAgent route rejects OAuth-client tokens; first-party web/mobile/CLI tokens have no client ID. Ordinary denials bind the initiating user turn; trigger denials bind their active turn.
15. Agent Key Login
nyxid login --agent-key authorizes a CLI profile with a child login credential bound to an existing or newly created Agent Key. It never creates an account session or falls back to account login. Follow Rule 12's client-context sanitization, request attribution, explicit review, and throttling posture.
- Routes:
POST /auth/agent-key/{request,poll,preview}are public with shared per-IP limits.POST /auth/agent-key/{options,approve,deny}live inapi_v1_human_only; session/access JWTs for people are required, and API-key, service-account, delegated, and relay tokens are rejected. Approver actions have per-IP and per-user limits.GET/DELETE /auth/agent-key/selflive outside the human-only group and require the calling child credential; DELETE can revoke itself even without a write scope.GET /api-keys/{id}/credentialsandDELETE /api-keys/{id}/credentials/{credential_id}inherit key-management auth and personal/org ACLs; API-key callers are rejected by that router, and mutation requires write authority. - Credential model:
api_key_credentialsstores only a SHA-256 hash of eachnyxid_ag_secret, its parent ID, copied owner, sanitized label, request ID, lifecycle metadata, and bounded expiry.validate_api_keyreturns the live parent plusapi_key_credential_id; scopes, restrictions, bindings, rate limits, and audit attribution stay on the parent. Existing-key selection never edits or rotates that key. New-key creation uses the existing scope-authorized validation path, defaults both allow-all flags to false, and discards the primary secret; delivery always uses a child. - Exchange:
agent_key_login_requestsstores domain-separated HMACs of the opaquenyx_akl_device code and user code. Approval atomically commits the pending claim, optional key insertion, child issuance, and encrypted delivery in a MongoDB transaction. Pending requests last 10 minutes; approval opens a 60-second delivery window. Poll atomically claims approved -> delivered once and unsets ciphertext. Deny races only on pending. Failed approval transactions commit no orphaned key or credential. Poll/preview expiry and theAGENT_KEY_LOGIN_SWEEP_INTERVAL_SECSsweep (default 60; 0 disables) revoke undelivered children; terminal TTL never removes an unfinished cleanup marker. New rows set legacykey_was_created=falsewith separatekey_created_by_approvalattribution, so old sweepers cannot delete reused parents. Legacy pending-created parents remain ineligible for new consumers until delivered. - Revocation: logout revokes only the calling child (
logout); the key detail page revokes a child (web_revoke). Parent revoke/rotation deactivates children (parent_revoked/parent_rotated), and parent/child expiry is checked live. Metadata-only approval, denial, delivery, and revocation audits never contain codes or secrets. - Anti-phishing and privacy: share the CLI's
verification_uri_complete, which contains only the public code and validated preferences. The public/login/agent-keypage follows Rule 12's URL contract: validate and retain the code/hints, perform a non-mutating preview for a valid URL code, and require Continue for manually entered codes. Malformed input fails visibly. Phone QR contains a user code, never a credential; scanning/deep linking prefills both web and mobile. Preview, scanning and verification never approve. Review echoes the code through final confirmation and instructs the approver to match the requesting device/terminal and reject a mismatch (RFC 8628 §§3.3.1, 5.4). Approval always requires review, key selection, permission confirmation, and an explicit decision with >=750 ms throttling./login/codeminting is unaffected. The computer's QR path uses anonymous preview polling at >=5 seconds, component state only, and clears temporary state at terminal/unmount without storing account credentials or cookies. - CLI profiles: atomic mode-0600
token,auth_kind=agent_key, safeagent_key.json, and existingbase_urlhandling. Stale account access/refresh/user files are removed. Saved Agent Key credentials never refresh, parse JWT expiry, or prompt for account login.whoami/statususe live self metadata; explicit/env credential precedence stays unchanged.session refreshexits 3; bounded logout clears the matching local login after best-effort server revocation, preserving a newer concurrent login.
File Structure
cli/src/
|-- main.rs # CLI entry point
|-- cli.rs # Clap subcommand definitions
|-- commands/ # Command implementations (one file per command group)
|-- api_client.rs # HTTP client for NyxID API calls
|-- auth.rs # Token storage and retrieval (file-based session)
|-- output.rs # Table/JSON output formatting
backend/src/
|-- config.rs # AppConfig from env vars
|-- db.rs # MongoDB connection + ensure_indexes()
|-- routes.rs # All route definitions
|-- main.rs # Server startup
|-- models/ # MongoDB document structs, one per collection
|-- services/ # Business logic (incl. channel_adapters/{telegram,discord,lark,openclaw})
|-- handlers/ # HTTP handlers
|-- crypto/ # JWT, AES, password hashing, token generation, device-code Ed25519 verification, KeyProvider trait, KMS providers, JWKS
|-- errors/ # AppError enum, ErrorResponse, AppResult
|-- mw/ # Middleware: auth, rate_limit, security_headers
frontend/src/
|-- pages/ # Route pages
|-- components/ # UI components (auth/, dashboard/, layout/, shared/, ui/)
|-- hooks/ # TanStack Query hooks (one per domain)
|-- schemas/ # Zod validation schemas with vitest specs
|-- stores/ # Zustand stores (auth-store)
|-- lib/ # API client, constants, utils
|-- types/ # TypeScript type definitions
|-- router.tsx # TanStack Router config
mobile/src/ # React Native + Expo app (Expo 55, RN 0.83): app/ (shell, navigator,
# deep linking nyxid://challenge/{id}), features/ (auth, challenges,
# approvals, account, legal), components/, lib/ (API client, SecureStore
# session, push registration), theme/
sdk/ # OAuth SDK monorepo (@nyxids/* npm namespace): oauth-core (PKCE OAuth 2.0
# client, NyxIDClient), oauth-react (React context + useNyxID() hook),
# demo-react (private demo app)Key API Routes
All API routes under /api/v1:
/auth-- register, login, logout, refresh, verify-email, forgot/reset-password/auth/device/v2/{request,poll,poll-web}and shared/auth/device/{preview,options,approve,approve-agent-key,deny}-- selectable login; legacy request/poll/poll-web remain account-only (Rule 12)/auth/login-code,/options,/redeem,/{id},/{id}/revoke-- human-issued single-use grants (Rule 12)/auth/agent-key/{request,poll,preview,options,approve,deny,self}-- Agent Key login and calling-credential identity/revocation (Critical Rule 15)/connect-links-- create, poll, creator cancel, public preview, human decline, and human-only completion for hosted service connections (see Critical Rule 13)/channel-connect-links-- tracked bot setup, signed terminal notifications, status and cancellation; human-only manual/managed/Telegram setup (see Critical Rule 13a)/developer/oauth-clients/{client_id}/connection-webhook-- human-only developer-app lifecycle webhook configure/disable;/connection-webhook/rotate-secretreturns a new signing secret and key ID once/triggers-- trigger CRUD plus human-onlyPOST /preview,GET /{id}/runs(cursor-paged metadata) andPOST /{id}/runfor Automations;/{id}/rotate-secret,/{id}/rotate-delivery-secret,/{id}/deliveries, and/{id}/deliveries/{event_id}/redelivercover inbound/outbound secret rotation, delivery history, and retained-envelope replay (JWT or agent API key; delegated, relay, and service-account tokens rejected)/webhooks/triggers/{trigger_id}-- unauthenticated trigger ingress verified by token or raw-body HMAC (see Critical Rule 14)/auth/mfa-- setup, confirm, verify (login), disable (nested under/authinroutes.rs;setupis idempotent against unverified factors per NyxID#506)/users-- get/update current user/api-keys-- CRUD + rotate;ApiKeyscope + agent isolation fields per Critical Rules 8-9/api-keys/{id}/bindings-- agent credential binding CRUD (AgentServiceBinding)/api-keys/{id}/credentialsand/{credential_id}-- list and revoke login credentials bound to a key/services-- CRUD + OIDC credentials + endpoints + requirements/sessions-- list sessions/connections-- connect/disconnect services/providers-- CRUD + OAuth/device-code/API-key flows + token management + per-user credentials;/codex-connectionstatus/import and/codex-connection/verifyrequire first-party human auth and exact reviewed connection versions (seedocs/CODEX_CONNECTION.md)/admin-- user management, audit log, OAuth clients, service accounts/admin/usage-- admin/operator platform-wide usage, default 24 hours and maximum 31 days; actor/owner and service filters, primary-request deduplication, MongoDB ranking and exact/legacy funding costs. Metering requiresBILLING_ENABLED./admin/audit-log-- unchanged substring filters; count and page queries run concurrently. Unfiltered totals are metadata-based viaestimated_document_count(exact except briefly after an unclean shutdown), avoiding a collection-sized count scan. Every non-empty filter keeps an exact count; global-search-only counts use one collection pass instead of seven full index scans, and their pages use the existing sort index. Narrowing predicates retain normal index selection. Event-type filter options are derived display data cached per process/AppState for 30 seconds; audit rows and counts are never cached./assistant/nyxagent/*-- human-only, default-on NyxAgent conversations/history/rename/delete, turn SSE, Stop, acknowledgement decisions (POST /conversations/{id}/acknowledgements/{ack_id}), owner-only tool images (GET /conversations/{id}/attachments/{attachment_id}), agents (GET/POST /agents,GET/PATCH/DELETE /agents/{id},PUT /agents/{id}/grants,POST /agents/{id}/destroy,DELETE /agents/{id}/memory/{note_id}), settings (GET/PUT /settings), channel links (GET/POST /channels,PATCH/DELETE /channels/{id}incl.private_chats) and their chats (GET /channels/{id}/chats,PATCH /channels/{id}/chats/{chat_id}), the owner's live change stream (GET /live, SSE, identifiers only), and cached profile discovery;PATCH /conversations/{id}/access-modeanswers 410. All routes enforce the engine flag and acting-person ownership/nyxbot/*-- NyxBot as the Agent Event Gateway'snyxbotprovider (agent-card,bindings/{binding_id},…/conversations/{conversation_id},…/events/{event_id},responses) authenticated inside each handler by the channel's gateway agent key, plusrelay/{channel_id}for NyxID's signed relay callbacks (direct platforms); outside JWT middleware/admin/assistant/profile-routes-- admin GET/PUT of NyxBot role-to-profile routes (stored and validated; inactive)/assistant/actions-- public static assistant action manifest for Aevatar startup discovery/proxy/{service_id}/{path}and/proxy/s/{slug}/{path}-- authenticated proxy (UUID- and slug-based); HTTP + WebSocket passthrough/proxy/services-- service discovery (paginated list of proxyable services)/llm-- LLM gateway (provider proxy, OpenAI-compatible gateway, status)/delegation/refresh-- refresh delegated access tokens/notifications-- notification settings CRUD, Telegram link/disconnect, device token management/approvals-- approval history, grants, decide, status polling, per-service approval configs (approval_mode:per_requestdefault orgrantopt-in)/webhooks/telegram-- Telegram webhook (unauthenticated, secret-verified)/devices/code/request-- unauthenticated device-code binding start for headless devices; returnsdevice_code,user_code, verification URLs/devices/code/poll-- unauthenticated but Ed25519-signed device poll; returns pending user-code rotations or one-time credentials after approval/devices/code/approve-- authenticated approval (web + CLI); creates the scoped API key, node row, and refresh token.DeviceCodeApprove.default_servicesis an opt-in list of user-service UUIDs/slugs granted proxy access at approval; omit for an empty allowlist./devices/onboard-- authenticated server-side QR provisioning for no-WiFi headless devices; creates the scoped API key + device node stub, embeds WiFi + raw one-time credentials in anyxprov://QR payload, stores only the refresh-token hash, never persists the WiFi password/nodes-- node management (register-token, list, get, delete, rotate-token, bindings CRUD + priority update)/nodes/ws-- WebSocket upgrade for node agents (auth via WS protocol, not middleware)/admin/nodes-- admin node management (list all, get, disconnect, delete -- no ownership check)/integrations/openclaw/channel-- OpenClaw channel webhook (unauthenticated, HMAC-verified);/integrations/openclaw/mappings-- mapping CRUD (authenticated)/keys-- unified key management: auto-provisions UserEndpoint + UserApiKey + UserService from catalog or custom input (CRUD + OAuth flows)/endpoints,/api-keys/external,/user-services-- list/update/delete for the three user collections/catalog-- read-only service catalog (?include_all=truefor full discovery;/{slug}/endpointsfor OpenAPI endpoint discovery via hardened spec fetch)/oracle-- browser LLM relay (Critical Rule 11). Consumer routes cover pools, tasks, attach, status, and sessions. Manager routes add worker allocation/list/show/commands, login-snapshot fanout, and the embedded worker bundle./oracle/worker/{task,heartbeat,ack,result,pin-conv-url,transcript,bundle,login-snapshots/*}authenticates with the pool worker token inside each handler and outside JWT middleware. The Oracle route groups have a 16 MiB body cap and normal global rate limiting. The manager login-snapshot route has a smaller request cap based on its 512 KiB decoded envelope limit./channel-platforms-- authoritative adapter metadata, registration fields, managed onboarding, non-secret credential-configured flags and media capabilities; JWT/session, agent key, service account and delegatedaccount:readaccepted./channel-relay/messages/{message_id}/attachments/{index}-- bounded inbound media download using the assigned live agent key or exact-message reply token without consuming its JTI. Explicitly denied to delegated/service-account/relay tokens. Stores inbound routing metadata only; never media bytes, outbound filenames or captions (ADR-013)./channel-bots-- channel bot registration CRUD + PATCH for platform verification material/admin/platform-credentials[/{provider}]-- admin-only descriptor listing (GET), field updates (PUT/PATCH, null clears), DELETE; generated Verify Token is admin-readable, app secrets never returned/channel-bots/managed-onboarding/{platform}(GET),/channel-bots/managed-onboarding/{platform}/complete(POST),/channel-bots/{id}/reregisterand/channel-bots/{id}/managed-setup/repair(POST) -- human-only router; writes share a per-user rate limit/webhooks/channel/{platform}/platform-- adapter-opted-in public GET handshake / POST signature-verified dispatcher/channel-conversations-- conversation-to-agent routing CRUD (platform conversations -> agent API keys)/channel-relay/reply-- agent async reply to a platform conversation. Only async replies are supported (sync 200+body callback replies removed per ADR-013 / NyxID#221): agents return 202 to the callback and post here. Dual auth: (a) agent API key (Bearer nyxid_ag_..., scoped byconversation.agent_api_key_id); (b) per-callbackreply_tokenfrom the inbound payload -- a single-use RS256 JWT,aud="channel-relay/reply", bound to oneinbound_message_id+conversation_id+api_key_id+platform, TTLJWT_RELAY_REPLY_TTL_SECS, use tracked in MongoDBreply_token_uses. Lets downstream runtimes (e.g. Aevatar) reply without persisting agent keys. Details:docs/CHANNEL_BOT_RELAY.md./channel-relay/send-- target-addressed proactive send, default-off human opt-in (allow_agent_initiated); assigned live API key or human owner session (including first-party CLI access JWT), shared per-conversation rate limit before auth, payload-bound 24h idempotency claims, metadata-only storage. Adapters declare outbound capabilities and classify permanent target refusals; unsupported adapters explicitly refuse dispatch./channel-relay/conversations-- API-key-only discovery of active assigned conversations, addressability, opt-in, capabilities, and last-message timestamp; paginated, metadata only./channel-relay/reply/update-- edit a previously-sent reply by the upstreamplatform_message_id; same dual auth. Lookup is caller-scoped (API key: rows it sent; reply token: its key + conversation + inbound anchor), never by platform ID alone, because Telegram IDs repeat per chat.outbound_message_id(the NyxIDmessage_idfrom/reply//send) pins the row; it is required for API-key edits on adapters withmessage_ids_are_chat_scoped()(Telegram, telegram-new), and ambiguous unpinned matches elsewhere return 409. The per-message edit limiter runs after resolution, keyed on the outbound row. A reply token may edit only if its JTI already exists inreply_token_uses(proves it was used to send first). Native edits: Telegram (including telegram-new), Discord, Slack, Lark, and Feishu. WhatsApp, X, and OpenClaw returnedit_unsupported. API keys can also edit agent-initiated messages; reply tokens remain bound to anchored replies./channel-relay/messages/{conversation_id}-- message history for agents;/channel-relay/resolve-sender-- resolve platform sender to NyxID user/channel-events/{conversation_id}-- HTTP Event Gateway ingress (NyxID#221, ADR-013). Accepts device event envelopes{event_id, source, type, timestamp, payload, metadata}, converts toCallbackPayloadwithplatform="device", forwards through the channel relay pipeline. Per-channel rate limited (default 100/s), idempotent via in-memory LRU dedup (5 min TTL), metadata-only logging tochannel_event_logs(no payload persistence)./webhooks/channel/{telegram,discord,lark,feishu,slack,whatsapp}/{bot_id}-- adapter-driven public POST receivers; WhatsApp also uses GET for Meta subscription verification/ssh/{service_id}/certificate(POST, issue short-lived SSH user cert),/ssh/{service_id}(WS tunnel),/ssh/{service_id}/terminal(WS web terminal),/ssh/{service_id}/exec(POST, remote command execution)/admin/service-accounts-- service account CRUD, secret rotation, token revocation, provider management on behalf of SAs/oauth/token-- also supportsgrant_type=client_credentials(service accounts) and RFC 8693 token exchange (grant_type=urn:ietf:params:oauth:grant-type:token-exchange) for delegated access and social token exchange (subject_token_type=id_tokenfor native mobile Google/GitHub login)
Top-level: /health, /.well-known/openid-configuration, /oauth/*, /mcp, /llms.txt, /llms-full.txt
NyxAgent assistant engine
New browser chats default to assistant:nyxagent-engine (on), then the experimental Direct flag, then Aevatar. NyxID owns nyxa-* transcripts and detached turns; the llm-nyx catalog row owns the target and NyxAgent owns disposable live context. A stable per-conversation assistant key authenticates upstream; failed/Stopped turns clear the context binding, and later turns send a bounded recap. Active fences expire after 2100 seconds and the next send transactionally records turn_lost before reclaiming; settlement retries stop after five minutes. The browser polls selected history while active or awaiting acknowledgement and renders one inline note at the latest context reset. Each chat owns a restricted key, encrypted credential row, and assistant_acknowledgements transcript records. Native nyxid__* account tools dispatch directly through services with owner checks, metadata audit and non-blocking human acknowledgement; refusals are MCP isError results. Ask/Full is retired. Every owner has one persistent NyxBot agent (assistant_agents, kind: nyxbot, Muse/Grok-Bot-style personal chief of staff) with Full access, plus persistent specialist agents created by the owner or NyxBot; conversations are threads of an agent (agent_id; legacy rows are NyxBot threads, upgraded to Full inside begin_turn with stale consent cards expired; access_mode reads full). Each agent has memory notes (nyxid__remember/forget, injected into every thread) and, for specialists, durable grants mirrored onto every thread key (no auto-connected services; NyxID's proxy still lets a live assistant conversation key reach catalog inference model services, because NyxAgent calls its model there with the thread key; allowlists and MCP tools stay the grants). Destructive account tools are NyxBot-only and still show a single-use action card unless the owner sets skip_destructive_confirmation (default false). NyxBot grants a specialist services with nyxid__grant_subagent, which grants what resolves and reports the rest in not_granted with reasons (NyxAgent's own llm-nyx is never a grant). Specialist service/account requests route to NyxBot (decider: orchestrator) at the assigning thread (report_to) or NyxBot's home thread, are decided with nyxid__decide_permission or by the owner, and resume the specialist with an event turn. NyxID starts specialist, event and channel turns itself (owner identity/billing) from an owner pool sized by settings (defaults 8 live / 3 concurrent); events coalesce on pending_events; loop guards are 20 event turns per owner per hour and 3 consecutive event turns per NyxBot thread without a user message. Direct user chats with a specialist never wake NyxBot. Agents may carry an owner-chosen display_name and persona (style only, credential shapes refused). Group chats (assistant_groups/assistant_group_messages) put the owner and 1-8 agents in one transcript: messages go to @mentioned members else the lead (NyxBot when a member), members hand off with @name (bounded by the owner's max_group_handoffs per request, default 6, and max_group_handoffs_per_hour, default 60), each speaking through a hidden member thread (group_id) with its own key; NyxBot threads that post work into a group are woken with the members' replies (group_settled) once it is quiet. The owner never replies "done": connect links and channel-bot setup links a chat hands out are watched (nyxbot_watches, TTL), and they and channel owner verification resume the waiting thread (proxy approvals need nothing: the tool call waits for the decision); each replica's MongoDB change stream (services/assistant_live.rs, identifiers/owner/status projection only) resolves watches the moment a link finishes or a bot becomes active and pushes identifier-only thread/group changes to browsers over GET /assistant/nyxagent/live, with the 15-second sweep as backstop for watches and wake-ups. NyxBot hands out setup/settings pages (nyxid__channel_bot_setup_link, nyxid__settings_link) instead of taking secrets or pointing at Studio; in channel threads and groups links are plain URLs and a reply decides an action card only when it quotes the card's 4-digit code ("yes 4821") or is a plain yes/no with exactly one card raised since the owner's previous message. New requests (owner messages or NyxBot posts from outside) refill the hand-off budget, NyxBot cannot post into a group from inside it, transcript continuations are indented, and names like user/nyxbot are reserved. Agents persist until destroyed (read-only threads, channels disconnected); destroyed specialists can be purged. Role-to-profile routing is admin-settable but inactive. The owner's private chats with an agent on every attached bot continue that agent's own home thread (one transcript and live context with the app; reply_channel sends asynchronous replies to the chat they last wrote from, cleared by app messages; messages record via); a question already being answered or queued is not worked on again (question digest on the active turn; a repeat from another chat gets the answer too via also_deliver), and turns are told what the agent's other threads are working on. Each other person's private chat of a channel bot is its own thread and each group, channel or topic one shared thread (senders named; guests whose platform sends no name read "{Platform} user …1234", and on NyxID's relay Lark/Feishu @_user_N mention keys are replaced by the mentioned names); relay callbacks carry each message's own chat type (not the catching route's), so groups are recognised automatically; per chat the owner sets reply_mode (groups: mention default, or all; the gateway admits every group message only while a chat needs it), members (everyone once the owner has talked to the bot there, else owner), allow_posts (for nyxid__post_to_chat) and an agent override, and per bot private_chats (owner default or everyone). Non-owners talk as guests (guest_turn): NyxBot calls no tools for them (it holds every owner service); a specialist's guest turns use its granted services as far as the owner sets per specialist and service (AssistantAgent::guest_access, on the agent's Grants or via NyxBot's nyxid__set_guest_access): stored beside grants: read (GET/HEAD/OPTIONS, or a POST a catalog contract marks readOnly: stored row or hosted overlay, never a remote spec), use (default: no change or removal of what exists: PUT/PATCH/DELETE by method unless NyxID's per-operation x-nyxid-changes-existing says otherwise (true from any spec wins; false only from a catalog contract), never DELETE nor an x-aevatar-tool.destructive operation; overlay marks come from the compiled overlay so endpoint rows and generations are untouched, a mounted spec's own marks only narrow; Aevatar's markers are not changed) or all (NyxBot must name the services); guest calls never carry method overrides; no name or word matching. Guests never use SSH, nyxid__, connection or Oracle tools, ask for more access, raise approvals or run on the owner's approval grants (audit rows record guest); guests' messages never queue as owner work; the owner's messages are marked (owner) in shared threads; guest turns see none of the owner's memory, roster or app-only messages (messages record their turn origin), start fresh after an owner turn, and cannot confirm cards. Channel bots link to NyxBot or any specialist: the owner's Telegram bots, and personal bots on platforms whose nyxbot:gateway-{platform} feature flag (lark, feishu, discord, slack, whatsapp, x, aurinko; default off, resolved per owner, admin-toggled without a restart) is on, through the Agent Event Gateway (NyxID is its nyxbot provider; the gateway operator must allowlist it; verified personal bots move there automatically once the gateway takes the platform, built beside the working bot and swapped in place, and stay unchanged on NyxID's relay if refused), other platforms through NyxID's relay directly; only owner-verified senders act as the owner (verified by link code, the owner's Telegram notification link, or as the Telegram account that created the bot through NyxID's in-Telegram creation). Bots of organizations the owner administers can be linked too (by id or label; NyxBot's bot/route tools list and manage them with their org): their route and route key are org-owned (no service grants), they always use NyxID's relay, and each inbound message re-checks that the owner still administers the org (else the link fails with org_access_lost). Conversation keys always allow nodes because service consent covers its node route. Platform-source services are granted on a key's allowed_platform_service_ids (chat keys only), and nyx__connect_service mints hosted links for chat keys without an allowlist entry. Execution/mutation requests add assistant MCP audits; read-only discovery does not. An allowed action card resumes the orchestrator with a visible continuation turn, queued until a running turn settles (not after Stop); each turn's instructions also list card decisions made since the previous user message, identifiers only. Chat-key tools/call requests during a live turn are recorded as metadata-only active_turn.activities (bounded) and copied onto the settled reply so the browser can show what the assistant is doing. Verified PNG/JPEG/GIF/WebP tool responses (2xx, <=5 MiB, type and magic bytes agree) become a leading text note plus, for non-chat callers, MCP image content (<=1 MiB inline, NyxAgent caps responses at 2 MiB); chat keys get the note only because NyxAgent stringifies and truncates results at 10,000 characters and cannot pass pixels; for chat keys with a live turn they are also envelope-encrypted into assistant_attachments (<=8 per turn, deleted with the conversation and in user purge), listed as attachments on the turn and reply, and served owner-only at GET /assistant/nyxagent/conversations/{id}/attachments/{attachment_id} with nosniff and a sandbox CSP. ToolResponse.text stays byte-identical for existing consumers and receipt digests. Existing actor history and action routes remain available; the NyxAgent sidebar no longer lists legacy Aevatar/Direct chats. No new NyxID environment variables; the NyxAgent deployment must set NYXAGENT_SERVICE_SLUG=llm-nyx for recursion protection. See docs/chat/08-nyxagent-engine.md for the normative contract and docs/chat/09-nyxbot-orchestrator.md for the NyxBot team and channel design, including the gateway provider registration.
Automation turns share the engine and team pool, with admission fenced inside begin_turn and no trigger lookup on ordinary turns. Schedule tools are NyxBot-only; webhook thread isolation and confirmation rules are in Rule 14 and docs/NYXBOT_SCHEDULES.md.
Channel Bot Notes
Platform Credentials is an adapter-described provider inventory: Stored backing keeps encrypted fields in platform_credentials (Meta); ProviderOAuth { provider_slug } reads/writes the provider config's encrypted client credentials (X shares twitter). Admin API, CLI and forms consume those descriptors. Managed UI components are selected through the meta_embedded_signup / oauth_connection flow registry.
X DMs use managed OAuth user connections (credential_source = "connection", connection_id is an owner-bound UserApiKey), with live refresh through the existing OAuth machinery. The X adapter owns protocol, scopes, rate handling and newest-first pagination; generic ingestion/credential hooks drive a MongoDB-leased poll sweep and the shared inbound pipeline. CHANNEL_POLL_INTERVAL_SECS=30 schedules sweeps; 0 disables them. X polls no faster than 60 seconds, starts at the newest event without replaying history, and fails after five consecutive errors. A backlog exceeding ten pages is truncated with a persistent last_poll_notice, without failing the bot. Reconnect validates the same account and preserves an existing cursor so the next sweep processes the backlog; deletion retains the OAuth connection. Current X pricing uses paid usage credits, shared across NyxID's app. See docs/CHANNEL_BOT_RELAY.md for limits and recovery.
Managed WhatsApp Embedded Signup v4 uses adapter-owned credential/onboarding/dispatcher hooks and SDK launch descriptors, with encrypted platform_credentials configured at Admin > Platform Credentials. Legacy bots default to credential_source = "user"; managed bots use "platform", resolve app-secret fallback on demand, and store their PIN and Verify Token encrypted for setup repair. Coexistence skips number registration and requests contact/history sync without historical chat import; repair preserves successful one-shot requests. Platform and WABA-override callbacks fan out through managed-only lookup and existing per-bot verification/dedup. Deletion best-effort clears unshared WABA overrides while leaving the Meta subscription. No new environment variables. See docs/CHANNEL_BOT_RELAY.md for prerequisites and recovery. The manual setup below describes BYO credentials.
Lark / Feishu developer-console fields serve different purposes -- do not conflate:
- App ID + App Secret: authenticate outbound NyxID calls to Lark/Feishu APIs (tenant access tokens, sending replies)
- Verification Token: required for inbound webhook verification; compared against
header.tokenon v2 events or top-leveltokenon v1 /url_verificationpayloads - Encrypt Key: optional; when configured, NyxID verifies
X-Lark-Signature, decrypts theencryptpayload, then validates the Verification Token on the decrypted JSON
A bot stuck in pending_webhook: patch it with its Verification Token (and optional Encrypt Key) via PATCH /api/v1/channel-bots/{id} or nyxid channel-bot update <ID> --verification-token ... [--encrypt-key ...] [--app-id ...] [--app-secret ...]; the next verified inbound auto-promotes it to active.
WhatsApp uses the Business Platform / Meta Cloud API, not the consumer WhatsApp Business App or Twilio. Access Token authenticates Graph calls; Phone Number ID is platform_bot_id; Meta App Secret verifies raw POST HMACs; optional WABA ID uses the generalized app_id storage column but is exposed as waba_id. The generated one-time Verify Token configures the Meta dashboard GET handshake; token/secret rotation and Verify Bot must preserve its hash. Subscribe the callback to messages and manually subscribe the app to the WABA. Filter app-wide events by Phone Number ID. Registration fields, verification secrets, acknowledgment policy, reply context, and retry deduplication belong to adapter hooks; services/channel_adapters/mod.rs::resolve_adapter is the single registry. WhatsApp alone opts into atomic inbound admission: an existing coordination-store claim is committed with metadata in a MongoDB transaction, scoped to bot/owner/wamid, with an in-transaction legacy-row check and expiry/replacement fencing. X retains lookup dedup and Telegram edits retain their behavior. Provider ACK remains immediate; callback failure, timeout or crash after admission is not automatically retried. Claims are released only before admission; committed markers last 30 days.
WhatsApp send outcome hooks preserve every accepted component ID (split text, media, audio captions; max 64), final-ID API compatibility, expected count and certainty. Default hooks preserve other adapters’ send_bound_reply overrides. A confirmed Graph refusal before any accepted component releases an initiated claim; ambiguous or partial sends retain it for the existing finite 24h retention and persist known IDs without marking the send complete. Signed, phone/WABA-filtered individual receipts store bounded IDs, per-status provider times and numeric codes only, with UUID v4 _id, unique identity key and 30d TTL. Group/participant receipts are rejected. Authorized message pages batch-join exact owner/bot/phone/WABA/recipient/wamid receipts; read implies delivered. Whole-reply status requires all components. Partial/unknown and legacy final-only rows cannot claim whole-reply delivery; group routes never imply all-participant delivery. No raw webhook, error prose, content queue or unmatched receipt API. Conversation IDs are wa_id digits. See docs/CHANNEL_BOT_RELAY.md for setup and delivery limits.
Environment Variables
Full semantics for the long-form entries: docs/ENV.md.
# Required
DATABASE_URL=mongodb://... # MongoDB connection string
ENCRYPTION_KEY= # 64 hex chars (AES-256); required for local, optional for KMS (enables fallback)
ENCRYPTION_KEY_PREVIOUS= # Optional previous key for zero-downtime rotation
KEY_PROVIDER=local # "local" (default), "aws-kms", "gcp-kms" (feature-gated)
# KMS (optional; --features aws-kms / gcp-kms; *_PREVIOUS for rotation)
AWS_KMS_KEY_ARN= / AWS_KMS_KEY_ARN_PREVIOUS=
GCP_KMS_KEY_NAME= / GCP_KMS_KEY_NAME_PREVIOUS=
# Defaults provided
PORT=3001
BASE_URL=http://localhost:3001
FRONTEND_URL=http://localhost:3000
JWT_PRIVATE_KEY_PATH=keys/private.pem
JWT_PUBLIC_KEY_PATH=keys/public.pem
JWT_ISSUER=nyxid
JWT_ACCESS_TTL_SECS=900 # 15 min
JWT_REFRESH_TTL_SECS=604800 # 7 days, ROLLING: every refresh rotates the token and restarts the TTL,
# so an active CLI never needs a browser re-login. Reuse of a rotated
# token more than 120s after rotation (a stale copy in another tool
# or profile) revokes the whole session; the CLI locks + re-reads the
# profile's token files across processes to avoid that.
JWT_RELAY_REPLY_TTL_SECS=1800 # Per-callback reply token TTL
JWT_RELAY_CALLBACK_TTL_SECS=300 # Callback authentication JWT TTL
JWT_RELAY_ACCESS_TTL_SECS=300 # X-NyxID-User-Token relay access token TTL. Relay tokens are
# proxy/LLM-only (rejected elsewhere by reject_relay_tokens),
# inherit the agent key's service/node allowlist, and are
# invalidated when that key is revoked (ensure_relay_agent_key_active).
JWT_ASSISTANT_FORWARD_TTL_SECS=300 # Legacy tombstone for the retired assistant_forward token.
# Live assistant delegation uses the compile-time 300s
# MCP_DELEGATION_TOKEN_TTL_SECS constant; this env has no effect.
SA_TOKEN_TTL_SECS=3600 # Service account tokens
ENVIRONMENT=development
RATE_LIMIT_PER_SECOND=10
RATE_LIMIT_BURST=30
PLATFORM_SERVICE_RATE_LIMIT_PER_SECOND=0 # Sustained per-user rate for platform-credentialed services; 0 (default) disables
PLATFORM_SERVICE_RATE_LIMIT_BURST=10 # Per-user burst capacity for platform-credentialed services
TRUSTED_PROXY_IPS= # Reverse-proxy IPs whose X-Forwarded-For/X-Real-IP are trusted for
# per-IP rate-limit keying. Empty = trust only the TCP peer. Only list
# proxies configured to overwrite client-supplied forwarded headers.
MTLS_CLIENT_CERT_HEADER= # Header carrying a URL-encoded PEM client cert from a trusted
# mTLS-terminating proxy (RFC 8705 cert-bound broker tokens).
# Unset = disabled. The proxy must strip this header from external requests.
BROKER_REQUIRE_SENDER_CONSTRAINT=false # Default-off broker hardening: require DPoP/mTLS-pinned
# broker bindings at create and exchange time. Runtime-overridable
# by platform admins via Admin -> OAuth Clients -> Broker Rollout Policy;
# DB override wins over this env default; other replicas refresh
# from MongoDB on a short background interval. See docs/ENV.md.
BROKER_REQUIRE_ADMIN_CAPABILITY=false # Default-off broker hardening: require platform-admin
# broker_capability_enabled provisioning; DCR scope and
# non-admin developer-app self-grant no longer confer broker mode.
# Runtime-overridable by platform admins; DB override wins over env.
CLI_PAIRING_HMAC_KEY= # Optional 64 hex; keys CliPairing.code_hash against DB-snapshot
# brute force. Unset = derived from ENCRYPTION_KEY or the JWT key
# (stable per-worker, multi-instance safe).
AUDIT_CHAIN_HMAC_KEY= # Optional 64 hex; keys audit-log HMAC chaining; same derivation fallback
BILLING_LEDGER_HMAC_KEY= # Optional 64 hex; keys billing-ledger HMAC chaining; same derivation fallback
CHAIN_VERIFY_INTERVAL_SECS=3600 # Automatic chain verification and billing account reconciliation; 0 disables both
CHANNEL_RELAY_CALLBACK_TIMEOUT_SECS=30
CHANNEL_RELAY_MAX_BOTS_PER_USER=5
CHANNEL_RELAY_MESSAGE_TTL_DAYS=30
CHANNEL_MEDIA_MAX_BYTES=20971520 # Per attachment; only reply/send JSON body caps are raised
CHANNEL_POLL_INTERVAL_SECS=30 # Adapter-driven poll sweep; 0 disables (X minimum interval: 60s)
CHANNEL_RELAY_EDIT_RATE_LIMIT_PER_SECOND=10 # Per-outbound-message edit rate limit
CHANNEL_RELAY_EDIT_RATE_LIMIT_BURST=20
CHANNEL_RELAY_INITIATE_RATE_LIMIT_PER_SECOND=1 # Per-conversation unsolicited message limit
CHANNEL_RELAY_INITIATE_RATE_LIMIT_BURST=5
# Telegram / Approval System (optional)
TELEGRAM_BOT_TOKEN= # From @BotFather
TELEGRAM_WEBHOOK_SECRET= # Random string for webhook verification
TELEGRAM_WEBHOOK_URL= # e.g. https://auth.nyxid.dev/api/v1/webhooks/telegram
TELEGRAM_BOT_USERNAME= # Without @
APPROVAL_EXPIRY_INTERVAL_SECS=5 # Interval between expiry sweeps
CONNECT_LINK_EXPIRY_SWEEP_INTERVAL_SECS=60 # Service-link expiry and bot-link recovery sweeps; 0 disables both
AGENT_KEY_LOGIN_SWEEP_INTERVAL_SECS=60 # Revoke expired undelivered Agent Key credentials; 0 disables
# OAuth token refresh (optional)
OAUTH_REFRESH_SWEEP_INTERVAL_SECS=600 # Proactive refresh sweep for expiring multi-connection OAuth
# tokens; 0 disables (lazy proxy-time refresh still applies).
# Does NOT extend refresh-token lifetime (a Google app in
# "Testing" still expires refresh tokens after 7 days).
OAUTH_REFRESH_SWEEP_WINDOW_SECS=900 # Look-ahead window; keep larger than the proxy-time 5-min buffer
CONNECTION_EXPIRY_NOTIFICATIONS=true # Notify once when OAuth dies; transition audits remain enabled
# Mobile Push (optional)
FCM_SERVICE_ACCOUNT_PATH= # Firebase service account JSON
APNS_KEY_PATH= / APNS_KEY_ID= / APNS_TEAM_ID=
APNS_TOPIC= # iOS bundle ID (e.g. dev.nyxid.app)
APNS_SANDBOX=true # Default true in dev
# Credential Nodes (optional, defaults shown)
NODE_HEARTBEAT_INTERVAL_SECS=30
NODE_HEARTBEAT_TIMEOUT_SECS=90 # Mark offline after N secs without heartbeat
NODE_PROXY_TIMEOUT_SECS=30
NODE_REGISTRATION_TOKEN_TTL_SECS=3600
NODE_MAX_PER_USER=10
NODE_MAX_WS_CONNECTIONS=100
NODE_MAX_STREAM_DURATION_SECS=300
NODE_HMAC_SIGNING_ENABLED=true
PROXY_MAX_BODY_SIZE=104857600 # Authenticated proxy + MCP raw bodies; direct and node-routed
LLM_MAX_BODY_SIZE=10485760 # /api/v1/llm provider + gateway bodies
PUBLIC_PROXY_MAX_BODY_SIZE=1048576 # Anonymous public proxy + public MCP bodies
WS_PASSTHROUGH_MAX_CONNECTIONS=200
# HTTP Event Gateway (NyxID#221, ADR-013)
CHANNEL_EVENT_RATE_LIMIT_PER_SECOND=100
CHANNEL_EVENT_RATE_LIMIT_BURST=200
CHANNEL_EVENT_DEDUP_TTL_SECS=300
TRIGGER_RATE_LIMIT_PER_SECOND=10
TRIGGER_RATE_LIMIT_BURST=20
TRIGGER_PAYLOAD_MAX_BYTES=262144
TRIGGER_DELIVERY_RETENTION_HOURS=72 # 0 keeps metadata only and disables replay
# Registration is gated by the default-on auth:invitation-code feature flag.
AUTO_VERIFY_EMAIL=false # Dev only: skip email verification on registration
# Optional
GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET
GITHUB_CLIENT_ID / GITHUB_CLIENT_SECRET
SMTP_HOST / SMTP_PORT / SMTP_USERNAME / SMTP_PASSWORD / SMTP_FROM_ADDRESSAvailable Commands
# CLI (from project root; end users install prebuilt release binaries, cargo install is for dev)
source "$HOME/.cargo/env" 2>/dev/null # Ensure cargo is available
cargo build -p nyxid-cli # Build CLI binary (includes node subcommand)
cargo test -p nyxid-cli # CLI tests (includes node agent tests)
cargo install --path cli # Install as `nyxid`
nyxid session refresh # Renew the saved session now (rotates the refresh token); exit 3 = must `nyxid login`, 4 = retry later
nyxid login --agent-key --profile agent # Web key selection/creation or phone QR approval; stores no account session
nyxid login --device # Explicit selectable device-code login (also the plain-login default)
nyxid login --callback # Full account session via local callback; legacy env alias: NYXID_LOGIN_NO_DEVICE_FALLBACK=1
nyxid login -c # --clipboard copies only the user code; JSON/no-wait modes skip clipboard/browser
# Backend (from project root)
cargo build [--features aws-kms,gcp-kms] # Feature-gated KMS providers
cargo test [--all-features]
cargo run # Start backend (port 3001)
# Node agent
nyxid node register --token nyx_nreg_... --url ws://localhost:3001/api/v1/nodes/ws
nyxid node start | agent-status | credentials list
nyxid node openclaw connect --url http://localhost:18789 # --credential-env for non-interactive
nyxid node openclaw status | disconnect
nyxid node daemon install|start|stop|restart|status|logs --follow|uninstall # launchd/systemd; supports --profile
nyxid node setup --machine [--computer] [--profile NAME] # pairing or page-issued --token; Linux isolation: sudo + --separate-users
nyxid node machine enable|disable|status # independent shell/files/computer; local authority
nyxid node docker start --machine # desktop image, persistent identity/workspace
nyxid node docker build|start|stop|status|logs [--profile <name>] # Docker alternative to native daemon
# Oracle relay
nyxid oracle ask <pool> <prompt> | result <task_id> | status <pool>
nyxid oracle pool create|list|show|update|rotate-token
nyxid oracle worker install --pool <pool> [--label <label>] [--worker-token-file <path>] [--profile <name>]
nyxid oracle worker list <pool> [--all] | show <pool> <label> # online only unless --all
nyxid oracle worker start|stop|status|logs|uninstall --pool <pool> [--profile <name>]
nyxid oracle worker drain|resume|restart|relaunch-browser|relogin <pool> <label>
nyxid oracle worker forget <pool> <label> [--force] # remove a stale worker row + its commands; releases its session affinity
nyxid oracle worker cancel-command <pool> <label> <command-id> # withdraw a queued/delivered-but-unexecuted command (e.g. a bad upgrade)
nyxid oracle worker upgrade --pool <pool> [--label <label>]
nyxid oracle login <pool> [--worker-token-file <path>]
# Agent isolation
nyxid api-key create --name "coding-agent" --platform claude-code
nyxid api-key list | show <ID_OR_NAME> | rotate <ID_OR_NAME> | delete <ID_OR_NAME>
nyxid api-key bind <ID_OR_NAME> --service <SLUG> --credential <LABEL> # Credential override
# Device-code binding
nyxid device approve XXXX-XXXX-XXXX [--org <ID|SLUG|NAME>] [--label <LABEL>] [--service <SLUG_OR_UUID>]...
nyxid device onboard --label "Kitchen Camera" --ssid "MyNetwork" --password-env WIFI_PASSWORD [--org ...] [--service ...]...
nyxid device factory-key [--count N] [--out FILE] [--ndjson]
# Channel bots
nyxid channel-bot register --platform telegram --label support --token-env TELEGRAM_BOT_TOKEN
nyxid channel-bot register --platform lark --label support --token-env LARK_BOT_TOKEN \
--app-id cli_xxx --app-secret-env LARK_APP_SECRET --verification-token vtoken_xxx
nyxid channel-bot update <BOT_ID> --verification-token ... [--encrypt-key ...]
# env alternatives: NYXID_LARK_VERIFICATION_TOKEN / NYXID_LARK_ENCRYPT_KEY
# Frontend (from frontend/)
npm run dev | build | test | test:watch | lint # dev = port 3000; build = type-check + prod build
# Mobile (from mobile/): npm run start | ios | android
# SDK (from sdk/): npm run build | clean
# Docker (from project root):
docker compose up -d # MongoDB (27018) + Mailpit (8025)Design System
Always read DESIGN.md before making any visual or UI decisions. All font choices, colors, spacing, and aesthetic direction are defined there. Do not deviate without explicit user approval. In QA mode, flag any code that doesn't match DESIGN.md.
Git Workflow
- Conventional commits:
feat:,fix:,refactor:,docs:,test:,chore: - Never commit to main directly
- PRs require review
- All tests must pass before merge
<!-- consensus-rnd:foundational-invariants:start version=1 sha256=180aef50d385eb24f73e772f75753fa61a2adde8407539bbacd586878d7e2166 -->Consensus R&D Foundational Invariants (managed by consensus-rnd)
- FI-001 AI outputs are untrusted by default; before entering the mainline they must pass independent checks, including the applicable mix of consensus, review, or automated verification.
- FI-002 Host facts must be injected by host configuration or host rules; generic skills / engines must not hardcode project, organization, path, branch, or personnel facts. Skill-private runtime directories such as
.refactor-loop/must not become host production configuration or ledger SSOT. - FI-003 Keep the stable core small and auditable; frequently changing behavior belongs in host rules, prompts, scripts, or extension layers, not in core invariants.
- FI-004 Facts that cross processes, turns, or nodes must have an authoritative record; in-process memory, caches, and temporary variables cannot pretend to be sources of truth.
- FI-005 Boundaries take priority over convenience; responsibility, layering, protocols, and state ownership must be clear, and shortcuts through intermediate layers must not bypass the main path.
- FI-006 Changes must be verifiable and evidence-based; failures, gaps, and out-of-bounds commitments must be surfaced explicitly, not hidden behind silent assumptions or disabled tests.
- FI-007 Prefer deletion; remove deprecated paths directly unless host rules explicitly require migration-period compatibility.
<!-- consensus-rnd:foundational-invariants:end -->Aurinko email integration
api-aurinkois an owner-scoped account-token AI Service; its curated overlay supplies fifteen MCP operations. No managed OAuth until Aurinko documents compatible PKCE. Do not use application credentials as a shared mailbox token.- The
aurinkochannel adapter has independent encrypted account-token/signing-secret storage, signed raw-byte POST validation, bound subscriptions, and bounded inline producer retries. Never return 422 to Aurinko. - ADR-013 still applies: persist only email subscription bindings, batch digest/cursor, stable UUID-v4 receipts, and send-attempt barriers. Receipts/sends have no TTL while their bot exists; owner/bot deletion must fence in-flight effects before cleanup. Do not consume a retryable Aurinko reply token before preflight or resend an uncertain POST. Legacy adapter behavior remains unchanged.
- See
docs/AURINKO_INTEGRATION.mdfor lifecycle, callback routing, filtering, reply authority, scopes, and validation limits. Aurinko is included in the catalog overlay drift map.
Assistant workspace navigation places Automations (/assistant/automations) and
Machines (/assistant/machines, Saved logins at ?tab=logins) beside Plugins and
Approvals for both engines. Setup/pairing stay in AssistantShell; the desktop is
standalone under /assistant/machines/{id}/desktop. Studio Nodes shows only a
read-only machine summary linking to assistant settings; Developer → Triggers
retains secrets/replay. /automations redirects with setup and agent intact.
Server-generated browser URLs use services::assistant_links::AssistantPage.
Machine web tasks use nyx__machine_browser; secure browser DevTools and arbitrary script evaluation are disabled. The separate dev browser is for debugging and has no saved-login access. Explicit NyxAgent budget/time errors continue the same session under max_auto_continuations; Stop must fence the turn and cancel node jobs/gateway work. Machine error codes 12413–12418 distinguish browser/driver/display/restart/stop states.
Machine updates: machine_update_service owns durable policy/attempt/watch state;
handlers/machine_update exposes human-only UI and mandatory owner-card tools.
Granted specialists may request, never approve, updates. Keep reconnect watches
bound to their attempt, and exclude jobs/turns/desktops/owner control from idle
updates. Only signed supervisor commands write version-only private update
mailboxes. The companion's Docker socket is host-root authority: fixed official
repositories, digest-bound Publish Images attestations, inspected configuration
preservation and rollback are mandatory. Never log Docker inspect environments
or expose update-volume access to agent/browser users. Test-only local-image
injection must remain behind cfg(test); production has no trust bypass.
Companion self-update uses companion-journal.json, a fenced heartbeat and separate
controller/handoff locks. Keep the predecessor alive until commit; recover
post-commit by finishing cleanup, never rolling back. Successors check the exact
attested image and release. Report companion outcomes separately from machine
progress, and never downgrade the companion.
Machine performance budgets belong in ignored benchmarks or explicit
NYXID_MACHINE_STRICT_BENCHMARK=1 runs on a quiet host. Shared-runner container
CI prints the same measurements but uses sanity ceilings (8 fps minimum,
500 ms input p95) so runner jitter cannot block image publication.
Machine browser compatibility/security: secure and dev Linux browsers use separate Xvfb/Openbox displays and Xauthority cookies; cua remains secure-only. The owner's display switcher routes capture/input and control by display (macOS shares its physical desktop and locks both). Browser refs carry frame IDs; snapshots accept query/offset/scope and return bounded pagination markers. Trusted native input follows extension hit testing; explicit DOM fallback is labelled. Command isolation is an actual uid/filesystem access probe, separate from saved-login browser isolation; missing fields mean unknown. Continuation progress stores rolling MCP argument/result hashes only, never raw values or bounded activity labels. Docker migration/setup commands require the server's cached, attestation-verified updater digest, with no mutable-tag fallback.
Machine 0.41.1 recovery: MV3 startup/install listeners and reconnecting native ports
are required on persisted profiles. A missing/changed managed package must clear
its own Preferences/Secure Preferences install registration before signed policy
reinstallation; deleting Extensions files alone does not repair Chromium. Never
start browsers/cua or bind sockets from machine status: read daemon snapshots.
12416 includes advertised tool names and browser snapshot/screenshot guidance;
machine discovery uses the shared ToolSearch ranker. Container updater TUF
stores live inside its private locked update volume; keep tmpfs flags in both
rendered commands for 0.41.0 compatibility. Failures expose fixed stage/reason
codes and guidance only. Production-image verification tests must exercise real
TUF and attestation code under read-only/cap-drop/no-new-privileges restrictions.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

