# List accounts Source: https://docs.sure.am/api-reference/accounts/list-accounts /openapi.yaml get /api/v1/accounts # Retrieve an account Source: https://docs.sure.am/api-reference/accounts/retrieve-an-account /openapi.yaml get /api/v1/accounts/{id} # Create a new account via SSO Source: https://docs.sure.am/api-reference/auth/create-a-new-account-via-sso /openapi.yaml post /api/v1/auth/sso_create_account Creates a new user and family from a previously issued linking code. Links the SSO identity via OidcIdentity, logs the JIT account creation via SsoAuditLog, and issues mobile OAuth tokens. The linking code must have allow_account_creation enabled. The first user on a fresh instance is assigned the super_admin role; later family creators are assigned an admin-capable role. # Enable AI features for the authenticated user Source: https://docs.sure.am/api-reference/auth/enable-ai-features-for-the-authenticated-user /openapi.yaml patch /api/v1/auth/enable_ai # Exchange mobile SSO authorization code for tokens Source: https://docs.sure.am/api-reference/auth/exchange-mobile-sso-authorization-code-for-tokens /openapi.yaml post /api/v1/auth/sso_exchange Exchanges a one-time authorization code (received via deep link after mobile SSO) for OAuth tokens. The code is single-use and expires after 5 minutes. # Link an existing account via SSO Source: https://docs.sure.am/api-reference/auth/link-an-existing-account-via-sso /openapi.yaml post /api/v1/auth/sso_link Authenticates with email/password and links the SSO identity from a previously issued linking code. Creates an OidcIdentity, logs the link via SsoAuditLog, and issues mobile OAuth tokens. # Log in with email and password Source: https://docs.sure.am/api-reference/auth/log-in-with-email-and-password /openapi.yaml post /api/v1/auth/login # Refresh an access token Source: https://docs.sure.am/api-reference/auth/refresh-an-access-token /openapi.yaml post /api/v1/auth/refresh # Sign up a new user Source: https://docs.sure.am/api-reference/auth/sign-up-a-new-user /openapi.yaml post /api/v1/auth/signup Creates a new user and family. The first user on a fresh instance is assigned the super_admin role; later family creators are assigned an admin role. # Show balance sheet Source: https://docs.sure.am/api-reference/balance-sheet/show-balance-sheet /openapi.yaml get /api/v1/balance_sheet Returns the family balance sheet including net worth, total assets, and total liabilities with amounts converted to the family's primary currency. # List balance history records Source: https://docs.sure.am/api-reference/balances/list-balance-history-records /openapi.yaml get /api/v1/balances # Retrieve a balance history record Source: https://docs.sure.am/api-reference/balances/retrieve-a-balance-history-record /openapi.yaml get /api/v1/balances/{id} # List budget categories Source: https://docs.sure.am/api-reference/budget-categories/list-budget-categories /openapi.yaml get /api/v1/budget_categories # Retrieve a budget category Source: https://docs.sure.am/api-reference/budget-categories/retrieve-a-budget-category /openapi.yaml get /api/v1/budget_categories/{id} # List budgets Source: https://docs.sure.am/api-reference/budgets/list-budgets /openapi.yaml get /api/v1/budgets # Retrieve a budget Source: https://docs.sure.am/api-reference/budgets/retrieve-a-budget /openapi.yaml get /api/v1/budgets/{id} # Show cash flow and optional Sankey graph Source: https://docs.sure.am/api-reference/cash-flow/show-cash-flow-and-optional-sankey-graph /openapi.yaml get /api/v1/cash_flow Server-calculated income, spending, savings, and daily cumulative comparison in family currency. Uses the authenticated user’s finance accounts and Sure reporting rules. Browser sessions do not authenticate this public API. # Create category Source: https://docs.sure.am/api-reference/categories/create-category /openapi.yaml post /api/v1/categories # List categories Source: https://docs.sure.am/api-reference/categories/list-categories /openapi.yaml get /api/v1/categories # Retrieve a category Source: https://docs.sure.am/api-reference/categories/retrieve-a-category /openapi.yaml get /api/v1/categories/{id} # Create a message Source: https://docs.sure.am/api-reference/chat-messages/create-a-message /openapi.yaml post /api/v1/chats/{chat_id}/messages # Retry the last assistant response Source: https://docs.sure.am/api-reference/chat-messages/retry-the-last-assistant-response /openapi.yaml post /api/v1/chats/{chat_id}/messages/retry # Create chat Source: https://docs.sure.am/api-reference/chats/create-chat /openapi.yaml post /api/v1/chats # Delete a chat Source: https://docs.sure.am/api-reference/chats/delete-a-chat /openapi.yaml delete /api/v1/chats/{id} # List chats Source: https://docs.sure.am/api-reference/chats/list-chats /openapi.yaml get /api/v1/chats # Retrieve a chat Source: https://docs.sure.am/api-reference/chats/retrieve-a-chat /openapi.yaml get /api/v1/chats/{id} # Update a chat Source: https://docs.sure.am/api-reference/chats/update-a-chat /openapi.yaml patch /api/v1/chats/{id} # Downloads a completed family export Source: https://docs.sure.am/api-reference/family-exports/downloads-a-completed-family-export /openapi.yaml get /api/v1/family_exports/{id}/download # Lists family exports Source: https://docs.sure.am/api-reference/family-exports/lists-family-exports /openapi.yaml get /api/v1/family_exports # Queues a family export Source: https://docs.sure.am/api-reference/family-exports/queues-a-family-export /openapi.yaml post /api/v1/family_exports # Shows a family export Source: https://docs.sure.am/api-reference/family-exports/shows-a-family-export /openapi.yaml get /api/v1/family_exports/{id} # Retrieve family settings Source: https://docs.sure.am/api-reference/family-settings/retrieve-family-settings /openapi.yaml get /api/v1/family_settings Retrieve a read-only snapshot of non-secret family configuration. # Activate the background publisher Source: https://docs.sure.am/api-reference/financekit/activate-the-background-publisher /openapi.yaml post /api/v1/financekit/connections/{connection_id}/activate # Credential the background publisher Source: https://docs.sure.am/api-reference/financekit/credential-the-background-publisher /openapi.yaml post /api/v1/financekit/connections/{connection_id}/credential # Discover FinanceKit background publisher support Source: https://docs.sure.am/api-reference/financekit/discover-financekit-background-publisher-support /openapi.yaml get /api/v1/financekit/capabilities # Durably accept an ordered FinanceKit publisher batch Source: https://docs.sure.am/api-reference/financekit/durably-accept-an-ordered-financekit-publisher-batch /openapi.yaml post /api/v1/financekit/publishers/{publisher_id}/batches # Enroll a FinanceKit device publisher Source: https://docs.sure.am/api-reference/financekit/enroll-a-financekit-device-publisher /openapi.yaml post /api/v1/financekit/connections # Explicitly create or link a canonical account lineage Source: https://docs.sure.am/api-reference/financekit/explicitly-create-or-link-a-canonical-account-lineage /openapi.yaml put /api/v1/financekit/connections/{connection_id}/account_mappings/{source_id} # List conflicts requiring user review Source: https://docs.sure.am/api-reference/financekit/list-conflicts-requiring-user-review /openapi.yaml get /api/v1/financekit/connections/{connection_id}/conflicts # Read publisher health and paginated mappings Source: https://docs.sure.am/api-reference/financekit/read-publisher-health-and-paginated-mappings /openapi.yaml get /api/v1/financekit/connections/{id} # Read the durable receipt for an accepted batch Source: https://docs.sure.am/api-reference/financekit/read-the-durable-receipt-for-an-accepted-batch /openapi.yaml get /api/v1/financekit/publishers/{publisher_id}/batches/{batch_id} Recover an accepted batch receipt, including its current processing status. # Repair the background publisher Source: https://docs.sure.am/api-reference/financekit/repair-the-background-publisher /openapi.yaml post /api/v1/financekit/connections/{connection_id}/repair # Resolve a FinanceKit import conflict Source: https://docs.sure.am/api-reference/financekit/resolve-a-financekit-import-conflict /openapi.yaml patch /api/v1/financekit/connections/{connection_id}/conflicts/{id} # Revoke a publisher, retaining or discarding imported financial history Source: https://docs.sure.am/api-reference/financekit/revoke-a-publisher-retaining-or-discarding-imported-financial-history /openapi.yaml delete /api/v1/financekit/connections/{id} # List holdings Source: https://docs.sure.am/api-reference/holdings/list-holdings /openapi.yaml get /api/v1/holdings # Retrieve holding Source: https://docs.sure.am/api-reference/holdings/retrieve-holding /openapi.yaml get /api/v1/holdings/{id} # Create import session Source: https://docs.sure.am/api-reference/import-sessions/create-import-session /openapi.yaml post /api/v1/import_sessions Create or idempotently retrieve a multi-file SureImport session keyed by client_session_id. # Publish import session Source: https://docs.sure.am/api-reference/import-sessions/publish-import-session /openapi.yaml post /api/v1/import_sessions/{id}/publish Queue ordered chunk processing for a SureImport session. Later chunks can reference source IDs mapped by earlier chunks. # Retrieve import session Source: https://docs.sure.am/api-reference/import-sessions/retrieve-import-session /openapi.yaml get /api/v1/import_sessions/{id} Retrieve import session status, chunk status, per-entity summary counts, and safe error details. # Upload import session chunk Source: https://docs.sure.am/api-reference/import-sessions/upload-import-session-chunk /openapi.yaml post /api/v1/import_sessions/{id}/chunks Attach an ordered Sure NDJSON chunk to an import session. Chunks are idempotent by sequence and client_chunk_id with content verification. # Create import Source: https://docs.sure.am/api-reference/imports/create-import /openapi.yaml post /api/v1/imports Create a new import from raw CSV content, inline Sure NDJSON content, or an uploaded Sure NDJSON file. CSV content is limited to 10MB. # List import row diagnostics Source: https://docs.sure.am/api-reference/imports/list-import-row-diagnostics /openapi.yaml get /api/v1/imports/{id}/rows List sanitized import rows with validation errors and mapping resolution state. # List imports Source: https://docs.sure.am/api-reference/imports/list-imports /openapi.yaml get /api/v1/imports List all imports for the user's family with pagination and filtering. # Retrieve an import Source: https://docs.sure.am/api-reference/imports/retrieve-an-import /openapi.yaml get /api/v1/imports/{id} Retrieve detailed information about a specific import, including configuration, row statistics, and SureImport readback verification when available. # Validate import content without creating an import Source: https://docs.sure.am/api-reference/imports/validate-import-content-without-creating-an-import /openapi.yaml post /api/v1/imports/preflight Validate CSV or Sure NDJSON import content and return counts, headers, warnings, and validation errors without persisting an import or enqueueing jobs. CSV content is limited to 10MB. # List proactive insights Source: https://docs.sure.am/api-reference/insights/list-proactive-insights /openapi.yaml get /api/v1/insights # Import merchants from CSV Source: https://docs.sure.am/api-reference/merchants/import-merchants-from-csv /openapi.yaml post /api/v1/merchants # List merchants Source: https://docs.sure.am/api-reference/merchants/list-merchants /openapi.yaml get /api/v1/merchants # Retrieve a merchant Source: https://docs.sure.am/api-reference/merchants/retrieve-a-merchant /openapi.yaml get /api/v1/merchants/{id} # Lists provider connection status summaries Source: https://docs.sure.am/api-reference/provider-connections/lists-provider-connection-status-summaries /openapi.yaml get /api/v1/provider_connections List safe provider connection status metadata for the authenticated user's family without exposing credentials, raw provider payloads, or raw sync errors. # Register an APNs device token Source: https://docs.sure.am/api-reference/push-subscriptions/register-an-apns-device-token /openapi.yaml post /api/v1/push_subscriptions Available only in hosted (managed) mode. Requires write scope. # Unregister an APNs device token Source: https://docs.sure.am/api-reference/push-subscriptions/unregister-an-apns-device-token /openapi.yaml delete /api/v1/push_subscriptions/{id} Available only in hosted (managed) mode. Requires write scope. # Create recurring transaction Source: https://docs.sure.am/api-reference/recurring-transactions/create-recurring-transaction /openapi.yaml post /api/v1/recurring_transactions # Delete recurring transaction Source: https://docs.sure.am/api-reference/recurring-transactions/delete-recurring-transaction /openapi.yaml delete /api/v1/recurring_transactions/{id} # List recurring transactions Source: https://docs.sure.am/api-reference/recurring-transactions/list-recurring-transactions /openapi.yaml get /api/v1/recurring_transactions # Retrieve recurring transaction Source: https://docs.sure.am/api-reference/recurring-transactions/retrieve-recurring-transaction /openapi.yaml get /api/v1/recurring_transactions/{id} # Update recurring transaction Source: https://docs.sure.am/api-reference/recurring-transactions/update-recurring-transaction /openapi.yaml patch /api/v1/recurring_transactions/{id} # List rejected transfers Source: https://docs.sure.am/api-reference/rejected-transfers/list-rejected-transfers /openapi.yaml get /api/v1/rejected_transfers # Retrieve a rejected transfer Source: https://docs.sure.am/api-reference/rejected-transfers/retrieve-a-rejected-transfer /openapi.yaml get /api/v1/rejected_transfers/{id} # List rule runs Source: https://docs.sure.am/api-reference/rule-runs/list-rule-runs /openapi.yaml get /api/v1/rule_runs List rule run history for the authenticated user family. # Retrieve a rule run Source: https://docs.sure.am/api-reference/rule-runs/retrieve-a-rule-run /openapi.yaml get /api/v1/rule_runs/{id} Retrieve one rule run from the authenticated user family. # List rules Source: https://docs.sure.am/api-reference/rules/list-rules /openapi.yaml get /api/v1/rules # Retrieve a rule Source: https://docs.sure.am/api-reference/rules/retrieve-a-rule /openapi.yaml get /api/v1/rules/{id} # List securities referenced by family investment data Source: https://docs.sure.am/api-reference/securities/list-securities-referenced-by-family-investment-data /openapi.yaml get /api/v1/securities # Retrieve a security referenced by family investment data Source: https://docs.sure.am/api-reference/securities/retrieve-a-security-referenced-by-family-investment-data /openapi.yaml get /api/v1/securities/{id} # List security price history referenced by family investment data Source: https://docs.sure.am/api-reference/security-prices/list-security-price-history-referenced-by-family-investment-data /openapi.yaml get /api/v1/security_prices # Retrieve a security price referenced by family investment data Source: https://docs.sure.am/api-reference/security-prices/retrieve-a-security-price-referenced-by-family-investment-data /openapi.yaml get /api/v1/security_prices/{id} # Lists sync history Source: https://docs.sure.am/api-reference/syncs/lists-sync-history /openapi.yaml get /api/v1/syncs List sanitized sync status history for the authenticated user's family, accounts, and provider connections. # Shows a sync Source: https://docs.sure.am/api-reference/syncs/shows-a-sync /openapi.yaml get /api/v1/syncs/{id} Return sanitized status metadata for a single family-scoped sync. # Shows the latest sync Source: https://docs.sure.am/api-reference/syncs/shows-the-latest-sync /openapi.yaml get /api/v1/syncs/latest Return the most recently created sanitized sync status for the authenticated user's family, or data: null when no sync exists. # Create tag Source: https://docs.sure.am/api-reference/tags/create-tag /openapi.yaml post /api/v1/tags # Delete a tag Source: https://docs.sure.am/api-reference/tags/delete-a-tag /openapi.yaml delete /api/v1/tags/{id} # List tags Source: https://docs.sure.am/api-reference/tags/list-tags /openapi.yaml get /api/v1/tags # Retrieve a tag Source: https://docs.sure.am/api-reference/tags/retrieve-a-tag /openapi.yaml get /api/v1/tags/{id} # Update a tag Source: https://docs.sure.am/api-reference/tags/update-a-tag /openapi.yaml patch /api/v1/tags/{id} # Create trade Source: https://docs.sure.am/api-reference/trades/create-trade /openapi.yaml post /api/v1/trades # Delete trade Source: https://docs.sure.am/api-reference/trades/delete-trade /openapi.yaml delete /api/v1/trades/{id} # List trades Source: https://docs.sure.am/api-reference/trades/list-trades /openapi.yaml get /api/v1/trades # Retrieve trade Source: https://docs.sure.am/api-reference/trades/retrieve-trade /openapi.yaml get /api/v1/trades/{id} # Update trade Source: https://docs.sure.am/api-reference/trades/update-trade /openapi.yaml patch /api/v1/trades/{id} # Create transaction Source: https://docs.sure.am/api-reference/transactions/create-transaction /openapi.yaml post /api/v1/transactions # Delete a transaction Source: https://docs.sure.am/api-reference/transactions/delete-a-transaction /openapi.yaml delete /api/v1/transactions/{id} # List transactions Source: https://docs.sure.am/api-reference/transactions/list-transactions /openapi.yaml get /api/v1/transactions Returns global ledger history for accessible accounts, including disabled accounts but excluding accounts pending deletion. # Remove a transaction split Source: https://docs.sure.am/api-reference/transactions/remove-a-transaction-split /openapi.yaml delete /api/v1/transactions/{transaction_id}/split Removes the children and restores the parent transaction. # Replace a transaction split Source: https://docs.sure.am/api-reference/transactions/replace-a-transaction-split /openapi.yaml patch /api/v1/transactions/{transaction_id}/split Replaces the children of an existing split. The previous children are destroyed, so anything set on them afterwards is not carried over. # Retrieve a transaction Source: https://docs.sure.am/api-reference/transactions/retrieve-a-transaction /openapi.yaml get /api/v1/transactions/{id} # Retrieve a transaction split Source: https://docs.sure.am/api-reference/transactions/retrieve-a-transaction-split /openapi.yaml get /api/v1/transactions/{transaction_id}/split Returns the child transactions of a split. # Split a transaction Source: https://docs.sure.am/api-reference/transactions/split-a-transaction /openapi.yaml post /api/v1/transactions/{transaction_id}/split Splits a transaction into child transactions. The child amounts must sum exactly to the parent amount, using the same sign convention the transaction endpoints return (positive expenses, negative income). Write operations require read_write scope and owner or full-control account access. The parent becomes excluded from totals. # Update a transaction Source: https://docs.sure.am/api-reference/transactions/update-a-transaction /openapi.yaml patch /api/v1/transactions/{id} # List transfers Source: https://docs.sure.am/api-reference/transfers/list-transfers /openapi.yaml get /api/v1/transfers # Retrieve a transfer Source: https://docs.sure.am/api-reference/transfers/retrieve-a-transfer /openapi.yaml get /api/v1/transfers/{id} # Delete account Source: https://docs.sure.am/api-reference/users/delete-account /openapi.yaml delete /api/v1/users/me Permanently deactivates the current user account and all associated data. This action cannot be undone. # Reset account Source: https://docs.sure.am/api-reference/users/reset-account /openapi.yaml delete /api/v1/users/reset Resets all financial data (accounts, categories, merchants, tags, etc.) for the current user's family while keeping the user account intact. The reset runs asynchronously in the background. The returned job_id is informational only; reset status is family-scoped, not job-scoped. Requires admin role. # Retrieve reset status Source: https://docs.sure.am/api-reference/users/retrieve-reset-status /openapi.yaml get /api/v1/users/reset/status Returns counts of family-owned data targeted by account reset. Use this after DELETE /api/v1/users/reset to decide whether reset materialization has completed. Completion is a counts-based family snapshot and may change if new data is created after reset. # Create valuation Source: https://docs.sure.am/api-reference/valuations/create-valuation /openapi.yaml post /api/v1/valuations # List valuations Source: https://docs.sure.am/api-reference/valuations/list-valuations /openapi.yaml get /api/v1/valuations # Retrieve a valuation Source: https://docs.sure.am/api-reference/valuations/retrieve-a-valuation /openapi.yaml get /api/v1/valuations/{id} # Update a valuation Source: https://docs.sure.am/api-reference/valuations/update-a-valuation /openapi.yaml patch /api/v1/valuations/{id} # Authentication guide Source: https://docs.sure.am/authentication/guide Complete reference for configuring SSO authentication with OIDC, OAuth2, and SAML ## Overview This guide covers all authentication features including OIDC, OAuth2, SAML 2.0, database-backed provider management, JIT provisioning, role mapping, user management, and audit logging. ## Configuration methods ### Database-backed providers (recommended) Manage providers through the admin UI without server restarts: ```bash theme={null} AUTH_PROVIDERS_SOURCE=db ``` Benefits: * Changes take effect immediately * No server restarts required * Web-based configuration at `/admin/sso_providers` * Audit trail for all changes ### YAML-based providers (legacy) Configure providers in `config/auth.yml`. Requires server restart for changes. > [!NOTE] > > We recommend migrating to database-backed providers. See the migration section below. ## OIDC configuration ### Supported providers OIDC works with any compliant provider: * Google Workspace * Microsoft Entra ID (Azure AD) * Okta * Auth0 * Keycloak * Authentik * GitLab ### Basic OIDC setup **1. Create OAuth client in your IdP** Configure the redirect URI shown for the provider in Sure. For a provider with the ID `authentik`, use: ``` https://yourdomain.com/auth/authentik/callback ``` **2. Add provider in admin UI** Navigate to `/admin/sso_providers` and click **Add Provider**: ``` Strategy: openid_connect Issuer URL: https://accounts.google.com Client ID: your-client-id Client Secret: your-client-secret Scopes: openid profile email ``` **3. Configure role mapping** Set default roles and group mappings (optional) **4. Test the integration** Use the test login flow to verify configuration ### Multiple OIDC providers Configure multiple providers simultaneously (e.g., Keycloak + Authentik): ```yaml theme={null} # config/auth.yml providers: - id: "keycloak" strategy: "openid_connect" name: "keycloak" label: "Sign in with Keycloak" issuer: <%= ENV["OIDC_KEYCLOAK_ISSUER"] %> client_id: <%= ENV["OIDC_KEYCLOAK_CLIENT_ID"] %> client_secret: <%= ENV["OIDC_KEYCLOAK_CLIENT_SECRET"] %> - id: "authentik" strategy: "openid_connect" name: "authentik" label: "Sign in with Authentik" issuer: <%= ENV["OIDC_AUTHENTIK_ISSUER"] %> client_id: <%= ENV["OIDC_AUTHENTIK_CLIENT_ID"] %> client_secret: <%= ENV["OIDC_AUTHENTIK_CLIENT_SECRET"] %> ``` Each provider must have a unique `name` field, which determines the callback URL path. For example, a provider named `authentik` uses `https://your-domain.com/auth/authentik/callback`. ## OAuth2 configuration Use OAuth2 for providers without OIDC support (GitHub, GitLab, Discord, Slack). ### GitHub example **1. Create OAuth App** Go to [GitHub Settings](https://github.com/settings/developers) → **OAuth Apps** → **New OAuth App** Callback URL: ``` https://your-domain.com/auth/github/callback ``` **2. Configure in admin UI** ``` Strategy: oauth2 Authorization URL: https://github.com/login/oauth/authorize Token URL: https://github.com/login/oauth/access_token User Info URL: https://api.github.com/user Client ID: [your-client-id] Client Secret: [your-client-secret] Scopes: user:email ``` ### Token endpoint authentication The application supports multiple authentication methods: * `client_secret_post` (default): Send credentials in request body * `client_secret_basic`: Send credentials in Authorization header ## SAML 2.0 configuration ### Service Provider metadata Your application provides SAML metadata at: ``` https://your-domain.com/auth/saml/[provider-id]/metadata ``` ### Okta SAML setup **1. Create SAML application** In Okta admin console: 1. Go to **Applications → Create App Integration** 2. Select **SAML 2.0** **2. Configure SAML settings** ``` Single sign on URL: https://your-domain.com/auth/saml/okta/callback Audience URI (SP Entity ID): https://your-domain.com/auth/saml/okta Name ID format: EmailAddress Application username: Email ``` **3. Configure attribute statements** ``` email: user.email firstName: user.firstName lastName: user.lastName groups: appuser.groups ``` **4. Get IdP metadata** Copy: * Identity Provider Single Sign-On URL * Identity Provider Issuer * X.509 Certificate **5. Configure in admin UI** ``` Strategy: saml SSO URL: [from Okta] Entity ID: [from Okta] Certificate: [paste X.509 certificate] ``` ### Azure AD SAML setup **1. Create enterprise application** 1. Go to **Microsoft Entra ID → Enterprise applications** 2. Click **New application → Create your own application** 3. Select **Integrate any other application (Non-gallery)** **2. Configure SAML** ``` Identifier (Entity ID): https://your-domain.com/auth/saml/azure Reply URL (ACS URL): https://your-domain.com/auth/saml/azure/callback Sign on URL: https://your-domain.com Logout URL: https://your-domain.com/auth/saml/azure/logout ``` **3. Configure attributes** ``` email: user.mail givenname: user.givenname surname: user.surname groups: user.groups ``` **4. Download metadata** Download Certificate (Base64) and copy Login URL and Azure AD Identifier ## Database-backed provider management ### Admin UI features Access at `/admin/sso_providers`: * Add, edit, delete providers without server restarts * Enable/disable providers with a toggle * Test login flows before enabling * View callback URLs with copy button * Encrypted storage of client secrets * Audit trail of all changes ### Security features * Client secrets encrypted at rest using Rails 7.2 ActiveRecord Encryption * Rate limiting: 10 requests/minute per IP on admin endpoints * Discovery endpoint validation for OIDC providers * Issuer validation to prevent impersonation attacks * Super admin role required for provider management ### Seeding providers from YAML Migrate existing YAML configuration to database: ```bash theme={null} # Dry run (preview changes) DRY_RUN=true rails sso_providers:seed # Apply changes rails sso_providers:seed # List all providers rails sso_providers:list ``` ### Migration workflow **1. Backup configuration** ```bash theme={null} cp config/auth.yml config/auth.yml.backup ``` **2. Run migrations** ```bash theme={null} rails db:migrate ``` **3. Seed providers** ```bash theme={null} DRY_RUN=true rails sso_providers:seed rails sso_providers:seed ``` **4. Enable database source** ```bash theme={null} AUTH_PROVIDERS_SOURCE=db ``` **5. Restart application** ```bash theme={null} docker-compose restart app ``` **6. Verify** Check logs for: `[ProviderLoader] Loaded N provider(s) from database` ## Local login control ### Disable local login (SSO-only) ```bash theme={null} AUTH_LOCAL_LOGIN_ENABLED=false ``` Behavior: * Email/password form hidden * `POST /sessions` with local credentials blocked * Password reset routes disabled * `/password/edit` (self-service password change) is blocked — users are redirected away and cannot set a local password while local login is disabled * Users must authenticate via SSO ### Mobile API enforcement The mobile API enforces the same login restrictions as the web interface: * `POST /api/v1/auth/login` returns HTTP 403 when `AUTH_LOCAL_LOGIN_ENABLED=false` and the account is not a super admin using the emergency override. * `POST /api/v1/auth/signup` returns HTTP 403 when the instance is closed to new registrations. * When local login is permitted, login (`POST /api/v1/auth/login`) returns HTTP 401 for a deactivated account. The local-login restriction is checked first and can instead return HTTP 403. Token refresh (`POST /api/v1/auth/refresh`) returns HTTP 401 for a deactivated account. Previously these checks applied only to web sessions; the mobile API now honours them as well. ### Emergency admin override Allow super admins to log in locally during IdP outages: ```bash theme={null} AUTH_LOCAL_LOGIN_ENABLED=false AUTH_LOCAL_ADMIN_OVERRIDE_ENABLED=true ``` Behavior: * Login page shows email/password form with admin-only note * Super admins can log in with local passwords * Super admins can still access `/password/edit` and set a local password * Regular users are blocked from the password change page and redirected away * Override logins are logged ## JIT user provisioning ### Provisioning modes ```bash theme={null} # Create new accounts on first SSO login (default) AUTH_JIT_MODE=create_and_link # Only link to existing users, no account creation AUTH_JIT_MODE=link_only ``` ### Domain restrictions ```bash theme={null} # Allow any verified email domain ALLOWED_OIDC_DOMAINS="" # Restrict to specific domains ALLOWED_OIDC_DOMAINS="example.com,corp.com" ``` When set, JIT account creation is only allowed for emails from listed domains. Applies to all SSO providers. ### Default roles Configure in admin UI under **Role Mapping**: * **Default Role**: Assigned to all JIT-created users (e.g., `member`) * **Group Mappings**: Map IdP groups to application roles When a JIT login creates a new family, the user who creates it is assigned the `admin` role for that family regardless of the default role setting. Super admin accounts retain their elevated defaults. This ensures the first user of a new family always has the access needed to configure it. ## Role mapping ### Group-to-role mapping Map identity provider groups to application roles: ```json theme={null} { "mappings": [ { "group": "Platform-Admins", "role": "super_admin" }, { "group": "Team-Leads", "role": "admin" }, { "group": "Everyone", "role": "member" } ] } ``` Mapping is case-sensitive. When a user belongs to multiple groups, the highest role wins (`super_admin` > `admin` > `member`). ### OIDC group mapping Ensure your OIDC provider includes groups: ``` Scopes: openid profile email groups ``` Configure your IdP to include groups in the ID token or userinfo response. ### SAML attribute mapping Configure group attribute in SAML provider: ```xml theme={null} admin-group developer-group ``` Set the attribute name in provider settings: ``` Group attribute: groups ``` ### Role synchronization Roles are synchronized on every login: 1. Fetch current groups from IdP 2. Apply group-to-role mappings 3. Update user's roles 4. Remove roles no longer mapped Administrators can manually trigger sync at `/admin/users` → **Sync Roles from SSO**. ## User management ### Admin interface Access at `/admin/users`: * View all users with roles, auth methods, last login * Search and filter by role, provider, status * View connected SSO accounts * Manage user roles manually * Suspend/reactivate/delete users * View authentication history ### Connected accounts Users can manage their own connected accounts at `/settings/security` under **Connected Accounts**: * View all connected SSO providers with the last-used timestamp * Connect additional providers by signing in with them * Disconnect a provider using the **Disconnect** button **Safety guard for disconnecting:** Sure prevents a user from disconnecting their last SSO provider when they have no local password set. The disconnect button is hidden in that case, and a warning is shown prompting the user to set a password first. If the user has either a second SSO provider connected or a local password, disconnecting proceeds and the event is recorded in the SSO audit log as an `unlink` event. ### User actions **Deactivate user**: Immediately cut off all access without removing data. All web sessions are destroyed, and all OAuth tokens and API keys are revoked. Subsequent web, mobile, token-refresh, and OIDC attempts cannot establish access; the web OIDC callback redirects to sign-in. ``` /admin/users → Actions popover → Deactivate User ``` **Reactivate user**: Restore access. The user must log in again; existing sessions and tokens are not restored. ``` /admin/users → Actions popover → Reactivate User ``` **Delete user**: Permanently remove (cannot be undone) ``` /admin/users → Actions popover → Delete User → Type email to confirm ``` **Sync roles**: Force role synchronization from IdP ``` /admin/users → Actions popover → Sync Roles from SSO ``` ## Audit logging ### Event types Access logs at `/admin/sso_audit_logs`: **Authentication events:** * `login`: Successful SSO login * `login_failed`: Failed login attempt * `logout`: User logout * `logout_idp`: RP-initiated federated logout * `link`: SSO account linked to user * `unlink`: SSO account unlinked * `jit_account_created`: New account created via JIT provisioning **Query via console:** ```ruby theme={null} SsoAuditLog.by_event("login").recent.limit(50) SsoAuditLog.by_event("login_failed").where("created_at > ?", 24.hours.ago) ``` ### Log retention * Standard: 90 days in database * Extended: 1 year (database + archive) * Compliance: 7 years (archive storage) ### Monitoring Set up alerts for: * Multiple failed login attempts (brute force detection) * Provider configuration changes * Unusual login locations * Role escalations ## Troubleshooting ### Provider not appearing on login page **YAML mode:** * Check required environment variables are set (`OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`) **DB mode:** * Verify provider is enabled in `/admin/sso_providers` * Check `AUTH_PROVIDERS_SOURCE=db` is set * Review application logs for provider loading messages ### Discovery endpoint validation fails When adding an OIDC provider: * Ensure issuer URL is correct and accessible * Check firewall rules allow outbound HTTPS * Verify issuer returns valid JSON with `issuer` field * For self-signed certificates, configure SSL verification ### Callback URL mismatch Each provider requires exact callback URL match: **Format:** `https://yourdomain.com/auth//callback` **Examples:** * Keycloak: `https://yourdomain.com/auth/keycloak/callback` * Authentik: `https://yourdomain.com/auth/authentik/callback` * Google Workspace: `https://yourdomain.com/auth/google/callback` The callback URL is shown in admin UI when editing a provider (with copy button). Use that exact value in your identity provider. Older examples that use `/auth/openid_connect/callback` only apply to a legacy provider whose name is literally `openid_connect`. ### Groups not syncing * Add `groups` scope to OIDC configuration * Verify IdP includes groups in token/assertion * Check group attribute name matches IdP configuration * Review audit logs to see what groups are received * Some IdPs require additional configuration to include groups ### `POST /api/v1/auth/sso_create_account` returns "account already exists" When a mobile SSO account creation attempt conflicts with an existing record (for example, the same email address or identity is already registered), the API returns HTTP 422 with: ```json theme={null} { "errors": ["An account or sign-in identity with these details already exists"] } ``` This is a generic message that does not expose internal database index names or field values. To resolve, have the user sign in with the existing account and link the SSO identity from Settings → Security → Connected Accounts instead. ## Security considerations ### Encryption * Client secrets encrypted at rest using Rails 7.2 ActiveRecord Encryption * In self-hosted mode, encryption keys are derived from `SECRET_KEY_BASE` unless you set dedicated `ACTIVE_RECORD_ENCRYPTION_*` keys * Keep the same `SECRET_KEY_BASE` for the lifetime of an existing instance. Changing it changes the derived encryption keys and can make existing encrypted fields, including user email lookups, unreadable. * For additional security, set custom encryption keys via `ACTIVE_RECORD_ENCRYPTION_*` variables * If you enable custom keys on an existing self-hosted instance, run `bin/rails security:backfill_encryption` once to rewrite older plaintext values * If users suddenly see "invalid username or password" after encryption changes, restore the previous `SECRET_KEY_BASE` or previous `ACTIVE_RECORD_ENCRYPTION_*` values first, then rerun the backfill task if you intentionally moved to dedicated keys. ### MFA password re-authentication Enabling or disabling two-factor authentication requires the user's current password before the change is applied. This prevents anyone who reaches an unlocked browser from stripping or adding a second factor without knowing the password. A wrong password during MFA setup does not discard the setup in progress — the user can correct their password and retry without starting over. Users without a local password cannot access the MFA setup and teardown pages; the Settings page tells them where to manage two-factor authentication in their IdP instead. ### TOTP one-time use Each TOTP code is accepted only once. When a user signs in with a code, Sure records the time step of that code and rejects any subsequent use of the same step—including concurrent requests that arrive at the same time. A code seen over the shoulder, captured by a proxy, or relayed by a phishing page cannot be replayed within its validity window. The time step is claimed atomically with a conditional database update, so two simultaneous requests using the same code can never both succeed. Setting up or disabling two-factor authentication clears the recorded time step. ### Issuer validation * OIDC identities store the issuer claim from ID token * On subsequent logins, issuer is verified against configured provider * Prevents issuer impersonation attacks ### Admin access * SSO provider management requires `super_admin` role * Regular `admin` users (family admins) cannot access `/admin/sso_providers` * All provider changes logged with user ID ### Log filtering Sure filters sensitive values from request logs so they never appear in log output, even when verbose parameter logging is on. The following parameters are always redacted: * Passwords, tokens, keys, and secrets (standard Rails defaults) * One-time codes: MFA TOTP codes, backup codes, OAuth and bank authorization codes, and the desktop SSO exchange code (the `code` parameter, anchored — `currency_code`, `country_code`, and `postal_code` remain readable) * Mobile SSO linking code (`linking_code`) and invitation code (`invite_code`) * SimpleFIN access URL (`access_url`) * Device authorization flow fields (`device_code`, `user_code`, `verification_uri_complete`) * FinanceKit publisher credential and event fields These are configured in `config/initializers/filter_parameter_logging.rb`. ### Rate limiting Sure uses Rack::Attack to throttle credential-checking endpoints in production and staging. Rate limiting is disabled in development and test environments to avoid flakiness. Every endpoint that checks a password, TOTP code, or backup code is throttled by **both** IP address and a credential-identifying discriminator (email address, or the session-bound user ID for MFA step-up). Both throttles must pass — an attacker cannot bypass one by rotating IPs against a single target or by spraying many addresses from one IP. | Endpoint | Throttle keys | Limit | | - | - | - | | `POST /sessions` — web login | IP + email | 10 req/min each | | `POST /mfa/verify` — TOTP and backup codes | IP + session user ID | 10 req/min each | | `POST /password_reset` — password reset | IP + email | 10 req/min each | | `POST /oidc_account/create_link` — SSO identity linking | IP + email | 10 req/min each | | `POST /api/v1/auth/login` — mobile/API login | IP + email | 10 req/min each | | `POST /api/v1/auth/sso_link` — mobile SSO identity linking | IP + email | 10 req/min each | | `PATCH /password` — self-service password change | IP + user ID | 10 req/min each | | `POST /oauth/token` — OAuth token endpoint | IP | 10 req/min | | `POST /register` — OAuth registration | IP | 10 req/min | | `POST /mfa/webauthn_options`, `/mfa/verify_webauthn`, `/sessions/passkey` — WebAuthn MFA | IP | 10 req/min | | `POST /sessions/passkey_options` — passkey challenge (conditional mediation) | IP | 30 req/min | | `POST /settings/webauthn_credentials/options` — passkey registration code check | User ID | 10 req/min | | `POST /settings/webauthn_credentials` — passkey registration code spend | User ID | 10 req/min | | Admin endpoints (`/admin/*`) | IP | 10 req/min | Requests that exceed a limit receive HTTP 429. The throttle also matches format-suffixed paths (e.g. `/sessions.json`) so scripted clients cannot bypass it by appending a file extension. For JSON API requests (`Content-Type: application/json`), the email discriminator is extracted from the request body before Rails parses parameters. The body is rewound after reading so the controller still receives it intact. Non-rewindable input streams (Rack 3 servers that do not support rewind) skip the email throttle and fall back to IP-only throttling for those requests. The password-change throttle uses the signed-in user's ID (resolved from the session cookie) rather than an email address, since the endpoint requires an active session. Requests without a valid session are redirected to sign in and do not spend either budget. During an admin impersonation, the throttle is keyed on the impersonated user's ID — the same user whose password is being checked — so the impersonating admin's sessions do not gain extra guesses. ## Example configurations ### Default hybrid (local + SSO) ```bash theme={null} AUTH_LOCAL_LOGIN_ENABLED=true AUTH_LOCAL_ADMIN_OVERRIDE_ENABLED=false AUTH_JIT_MODE=create_and_link ALLOWED_OIDC_DOMAINS="" ``` Users can sign in with email/password or SSO. JIT account creation allowed for all verified emails. ### Pure SSO-only ```bash theme={null} AUTH_LOCAL_LOGIN_ENABLED=false AUTH_LOCAL_ADMIN_OVERRIDE_ENABLED=false ``` Email/password form hidden. Password reset disabled. SSO required for all users. ### SSO-only with emergency admin override ```bash theme={null} AUTH_LOCAL_LOGIN_ENABLED=false AUTH_LOCAL_ADMIN_OVERRIDE_ENABLED=true ``` Super admins can log in locally during IdP outages. Regular users must use SSO. ### Link-only JIT + restricted domains ```bash theme={null} AUTH_JIT_MODE=link_only ALLOWED_OIDC_DOMAINS="example.com,yourcorp.com" ``` SSO sign-ins can only link to existing users. New account creation disabled. Only specified domains allowed. ## Advanced features ### Request signing (SAML) Generate key pair: ```bash theme={null} openssl req -x509 -newkey rsa:2048 -keyout private.key -out certificate.crt -days 365 -nodes ``` Enable in admin UI: 1. Toggle "Sign requests" to enabled 2. Paste private key content 3. Certificate automatically included in SP metadata ### Custom attribute mapping Map custom IdP attributes to application fields: ```json theme={null} { "custom_mappings": { "employee_id": "externalId", "cost_center": "metadata.costCenter", "manager_email": "metadata.manager" } } ``` ### Conditional role assignment Assign roles based on multiple conditions: ```json theme={null} { "conditions": [ { "attribute": "department", "value": "Engineering", "groups": ["senior-engineers"], "role": "senior-developer" } ] } ``` ### Role hierarchy Define role hierarchies for automatic dependent roles: ```json theme={null} { "hierarchy": { "admin": ["developer", "viewer"], "developer": ["viewer"] } } ``` ## Best practices > **Use OIDC when available** > > OIDC provides standardized user information and better security than OAuth2. > **Enable database-backed providers** > > Manage providers through admin UI for easier updates and no downtime. > **Implement role mapping** > > Use group-to-role mapping to centralize access control in your IdP. > **Monitor audit logs** > > Regularly review authentication events and failed login attempts. > **Rotate secrets regularly** > > Periodically rotate client secrets and update in admin UI. > **Test before enabling** > > Always test provider configuration before enabling for all users. ## Next steps > **[Quickstart](/authentication/quickstart)** > > Get started with SSO in 5 minutes > **[User management](/authentication/user-management)** > > Manage users and connected accounts # Authentication quickstart Source: https://docs.sure.am/authentication/quickstart Get started with SSO authentication in 5 minutes ## Overview Configure single sign-on (SSO) authentication with OIDC, OAuth2, or SAML 2.0 providers. This guide covers the essential steps to get authentication working quickly. ## Choose your provider type > **OIDC** > > **Recommended** > > Google, Okta, Auth0, Azure AD, Keycloak > **OAuth2** > > **Legacy providers** > > GitHub, GitLab, custom OAuth2 > **SAML 2.0** > > **Enterprise** > > Okta, OneLogin, Azure AD ## Quick setup ### Step 1: Enable database-backed providers Set the environment variable: ```bash theme={null} AUTH_PROVIDERS_SOURCE=db ``` Restart your application. ### Step 2: Create OAuth credentials in your IdP **Google** 1. Go to [Google Cloud Console](https://console.cloud.google.com) 2. Navigate to **APIs & Services → Credentials** 3. Click **Create Credentials → OAuth client ID** 4. Select **Web application** 5. Add redirect URI. Use the callback URL shown for the provider in Sure; for this example: ``` https://your-domain.com/auth/google/callback ``` 6. Copy the **Client ID** and **Client Secret** **Okta** 1. Log in to Okta admin console 2. Go to **Applications → Create App Integration** 3. Select **OIDC - OpenID Connect** 4. Choose **Web Application** 5. Add redirect URI. Use the callback URL shown for the provider in Sure; for this example: ``` https://your-domain.com/auth/okta/callback ``` 6. Copy the **Client ID** and **Client Secret** **Azure AD** 1. Go to [Azure Portal](https://portal.azure.com) 2. Navigate to **Microsoft Entra ID → App registrations** 3. Click **New registration** 4. Add redirect URI. Use the callback URL shown for the provider in Sure; for this example: ``` https://your-domain.com/auth/azure/callback ``` 5. Go to **Certificates & secrets** and create a client secret 6. Copy the **Application ID** and **Client Secret** ### Step 3: Configure in admin UI 1. Navigate to `/admin/sso_providers` in your application 2. Click **Add Provider** 3. Fill in the details: ``` Provider name: Google Workspace Provider ID: google Strategy: openid_connect Issuer URL: https://accounts.google.com Client ID: [your-client-id] Client Secret: [your-client-secret] Scopes: openid profile email ``` 4. Click **Save** ### Step 4: Test the integration 1. Log out of your application 2. You should see a "Sign in with Google" button (or your provider name) 3. Click it and complete the authentication flow 4. You should be logged in successfully ## Configuration options ### Local login control Disable local email/password login to enforce SSO-only: ```bash theme={null} AUTH_LOCAL_LOGIN_ENABLED=false ``` Keep an emergency admin override: ```bash theme={null} AUTH_LOCAL_LOGIN_ENABLED=false AUTH_LOCAL_ADMIN_OVERRIDE_ENABLED=true ``` ### JIT user provisioning Control how new users are created: ```bash theme={null} # Allow account creation for any verified email (default) AUTH_JIT_MODE=create_and_link # Only link to existing users, no new account creation AUTH_JIT_MODE=link_only # Restrict to specific email domains ALLOWED_OIDC_DOMAINS=example.com,company.com ``` ### Role mapping Configure default roles for new users in the admin UI under **Role Mapping**: * **Default Role**: `member` (assigned to all new users) * **Group Mappings**: Map IdP groups to application roles Example: ``` IdP Group: admin@company.com → Role: super_admin IdP Group: developers@company.com → Role: admin ``` ## Common configurations ### Pure SSO-only mode ```bash theme={null} AUTH_LOCAL_LOGIN_ENABLED=false AUTH_LOCAL_ADMIN_OVERRIDE_ENABLED=false AUTH_JIT_MODE=create_and_link ``` Users can only log in via SSO. No local passwords. ### Hybrid mode (local + SSO) ```bash theme={null} AUTH_LOCAL_LOGIN_ENABLED=true AUTH_JIT_MODE=create_and_link ``` Users can choose between local login or SSO. ### Enterprise mode (restricted domains) ```bash theme={null} AUTH_LOCAL_LOGIN_ENABLED=false AUTH_JIT_MODE=link_only ALLOWED_OIDC_DOMAINS=company.com ``` Only users with `@company.com` emails can authenticate, and they must be pre-created by an admin. ## Bootstrap first admin The first user to register on a fresh instance is automatically assigned the `super_admin` role. No Rails console step is needed. If you are using SSO with JIT provisioning, the first user whose login creates a new family is also automatically assigned `super_admin`. Subsequent users get the role defined by your provider's default role setting. Once a super admin exists, they can promote other users via the web UI at `/admin/users`. If you need to promote a user to `super_admin` on an existing instance (for example, after a data migration), use the Rails console: ```bash theme={null} bin/rails console ``` ```ruby theme={null} User.find_by(email: "admin@example.com").update!(role: :super_admin) ``` ## Troubleshooting ### Provider not appearing on login page * Verify `AUTH_PROVIDERS_SOURCE=db` is set * Check that the provider is **enabled** in `/admin/sso_providers` * Restart the application after setting environment variables ### Authentication fails * Verify the redirect URI matches exactly in both systems * For database-backed providers, the redirect URI is `https://your-domain.com/auth//callback`; copy the exact value shown in `/admin/sso_providers` * Check that client ID and secret are correct * Ensure the issuer URL is accessible from your server * Review logs at `/admin/sso_audit_logs` ### Email/password login fails after enabling encryption * Do not change `SECRET_KEY_BASE` on an existing instance. Self-hosted Sure derives Active Record encryption keys from it by default, and changing it prevents lookup of encrypted fields such as user email addresses. * If you added dedicated `ACTIVE_RECORD_ENCRYPTION_*` keys after the instance already had data, run the encryption backfill task once. See [Turning on Active Record encryption after first boot](/self-hosting#turning-on-active-record-encryption-after-first-boot). * If the keys were changed accidentally, restore the previous `SECRET_KEY_BASE` or previous `ACTIVE_RECORD_ENCRYPTION_*` values and restart the app. ### User not created automatically * Check `AUTH_JIT_MODE` is set to `create_and_link` * Verify the email domain is allowed (if `ALLOWED_OIDC_DOMAINS` is set) * Ensure the IdP returns a verified email address * Check audit logs for JIT provisioning errors ## Next steps > **[In-depth guide](/authentication/guide)** > > Complete authentication reference with advanced features > **[User management](/authentication/user-management)** > > Manage users, roles, and connected accounts # User management Source: https://docs.sure.am/authentication/user-management Manage users, families, roles, and authentication settings from the admin panel ## Overview Super admins can manage all users on the instance from `/admin/users`. The page groups users by family and lets you change roles, move users between families, set passwords for local-login users, and permanently delete accounts. ## Accessing user management Navigate to the user management page in your admin dashboard: ``` https://your-domain.com/admin/users ``` You must have the `super_admin` role to access this page. ## User list Users are grouped by family and sorted by activity (most active families first). Each user row shows: | Column | Description | | - | - | | Name | Profile picture (or initials if no picture is set), display name, and a role badge (`guest`, `member`, `admin`, or `super_admin`) | | Email | User's email address | | Auth type | A pill indicating local password, SSO, or both. Hover the info icon next to an SSO pill to see the provider name. | | Last login | Timestamp of the user's most recent login | | Sessions | Number of active sessions | | Family | The family/group this user belongs to | ### Filtering * **Filter by role**: Show only users with a specific role (`guest`, `member`, `admin`, `super_admin`) * **Filter by trial status**: Show users with expiring-soon or active trials ## Managing users All per-user actions are in the **actions popover** next to each row. Open it to see the options available for that user. ### Changing a user's role Select the desired role from the popover and save. Available roles are `guest`, `member`, `admin`, and `super_admin`. > [!NOTE] > > You cannot demote the last remaining active super admin. Sure blocks this to prevent losing access to the admin panel. ### Moving a user to a different family Super admins can transfer a user to an existing family or create a new one. To move to an **existing family**, select it from the family dropdown in the popover and save. To create a **new family**, type the new family name in the name field. A new family is created and the user is transferred atomically. > [!WARNING] > > You cannot change a user's family and set their password in the same submission. Submit one change at a time. ### Setting a password for local users For users who authenticate with a local password, super admins can set a new password from the actions popover. The password must meet all registration criteria: * At least 8 characters * At least one uppercase and one lowercase letter * At least one digit * At least one special character (`!@#$%^&*(),.?":{}|<>`) **SSO-only mode:** When `AUTH_LOCAL_LOGIN_ENABLED=false`, the admin panel rejects password changes for users with an existing local password who are not allowed to sign in locally. Super admins with a local password remain eligible when `AUTH_LOCAL_ADMIN_OVERRIDE_ENABLED=true`. The admin panel does not add a local password to an SSO-only account that has none. ### Deleting a family Empty families (no members) can be deleted from the admin user list. Families with active users cannot be deleted. ## Deactivating users Super admins can deactivate a user to immediately cut off all access without permanently removing the account or its data. Deactivation is reversible. **What happens when a user is deactivated:** * All active web sessions are destroyed immediately. * All OAuth access tokens and unexchanged authorization grants are revoked immediately. The mobile app stops working on the next request. * All active API keys are revoked immediately. * Every subsequent login attempt — local password, SSO, MFA completion, mobile REST API, OAuth — is rejected with HTTP 401 and the message "This account has been deactivated. Please contact an administrator." * If a super admin is currently impersonating the user, the impersonation session ends automatically on the next request. * A deactivation that races with an in-progress SSO account-linking flow is handled atomically: the link and any associated audit record are rolled back together, and the one-time linking code is restored so the user can retry from their identity provider once reactivated. The user sees no special deactivation notice. Login attempts return the same 401 response they would see for invalid credentials, directing them to contact an administrator. To deactivate a user, open the actions popover next to their row in `/admin/users` and select **Deactivate User**. To restore access, open the popover and select **Reactivate User**. Existing sessions and tokens are not restored — the user must log in again to get new credentials. > [!NOTE] > > You cannot deactivate a user who is the last active super admin, or who is the last admin in a family that has other members. Promote another user first. ## Deleting users Super admins can permanently delete a user from the instance. **What happens when a user is deleted:** * The user's account and all associated data are permanently removed * Any active sessions are ended immediately * Active OAuth tokens and API keys are revoked * An SSO audit log entry records who deleted the account and when * The action cannot be undone **Safety checks:** * You cannot delete your own account. The **Delete User** action is hidden on your own row. * You cannot delete the last active super admin — promote another user first. To delete a user: **1. Go to /admin/users** Navigate to the admin user list. **2. Open the actions popover** Click the actions menu next to the user you want to delete. **3. Click Delete User** A confirmation dialog opens. **4. Type the user's email to confirm** Enter the user's exact email address and submit. > [!WARNING] > > Deleting a user is permanent. All of their data is removed and cannot be recovered. ## Troubleshooting user issues ### User can't log in 1. Check whether the user is deactivated — a deactivated user gets a 401 on every login path. Reactivate them from the actions popover if the deactivation was unintended. 2. Check the user's auth type pill — if it shows only SSO and their provider is misconfigured, they won't be able to log in. 3. Verify the SSO provider is enabled and configured correctly under `/admin/sso_providers`. 4. If they have a local password, you can reset it from the actions popover. 5. Review audit logs for specific error messages. ### User is locked out after disconnecting their SSO provider Sure blocks users from disconnecting their last SSO provider when they have no local password set, and shows a warning on the security settings page. If a user somehow loses access: 1. Set a local password for them from the admin actions popover (see "Setting a password for local users" above) 2. Once a password is set, they can log in with email and password and reconnect their SSO provider from `/settings/security` ### User has the wrong role Open the actions popover for the user and update their role. Note that super admin role changes are logged for auditing. ### Duplicate accounts 1. Identify the primary account to keep 2. Delete the duplicate account from the actions popover (requires email confirmation) 3. Update the user's email in the identity provider if needed ## Best practices > **Offboarding** > > Delete user accounts promptly when someone leaves. This revokes all sessions, API keys, and OAuth tokens immediately. > **Protect the last super admin** > > Always have at least two super admins on the instance. Sure prevents you from deleting or demoting the last one, but having a backup avoids getting into that state. > **Password resets** > > Use the admin password-set feature when a local user is locked out and cannot receive a reset email. Prefer the self-service reset flow when email is available. ## Next steps > **[Audit logging](/authentication/audit-logging)** > > Monitor user authentication and account changes > **[Admin UI](/authentication/admin-ui)** > > Manage SSO providers and configuration > **[OIDC setup](/authentication/oidc)** > > Configure OIDC authentication providers # LLM Benchmarks Source: https://docs.sure.am/development/llm-benchmarks Benchmark results of popular foundation and open-weights LLMs with Sure ## Foundational/Online models ### Transaction categorization benchmark table Dataset: categorization\_golden\_v1 | Model | Quantisation | json\_mode | batch\_size | easy | medium | hard | edge\_case | accuracy | avg\_latency\_ms | cost\_per\_sample | | - | - | - | - | - | - | - | - | - | - | - | | gpt-5.2 | full | strict | 25 | 100.0% accuracy (33/33) | 97.06% accuracy (33/34) | 84.21% accuracy (16/19) | 100.0% accuracy (14/14) | 96.0 | 9090 | 0.0 | | gpt-5 | full | strict | 25 | 100.0% accuracy (33/33) | 100.0% accuracy (34/34) | 100.0% accuracy (19/19) | 100.0% accuracy (14/14) | 100.0 | 50339 | 0.0 | | gpt-4o | full | strict | 25 | 100.0% accuracy (33/33) | 100.0% accuracy (34/34) | 94.74% accuracy (18/19) | 100.0% accuracy (14/14) | 99.0 | 8302 | 0.0 | ## Open-weight models ### Transaction categorization benchmark table Dataset: categorization\_golden\_v1 | Model | Quantisation | json\_mode | batch\_size | easy | medium | hard | edge\_case | accuracy | avg\_latency\_ms | cost\_per\_sample | notes | | - | - | - | - | - | - | - | - | - | - | - | - | | qwen/qwen3.5-35b-a3b | full | strict | 25 | 100.0% accuracy (33/33) | 100.0% accuracy (34/34) | 100.0% accuracy (19/19) | 100.0% accuracy (14/14) | 100.0 | 54698 | 0.0 | | | qwen3-30b-a3b-instruct-2507 | Q3\_K\_XL | strict | 25 | 100.0% accuracy (33/33) | 100.0% accuracy (34/34) | 94.74% accuracy (18/19) | 100.0% accuracy (14/14) | 99.0 | 25357 | 0.0 | | | gpt-oss-20b | Q3\_K\_XL | none, strict | 25 | 100.0% accuracy (33/33) | 100.0% accuracy (34/34) | 52.63% accuracy (10/19) | 100.0% accuracy (14/14) | 91.0 | 43214 | 0.0 | Needs at least 8k context window due to not supporting strict JSON mode. | | qwen3-14b | Q5\_K\_XL | strict | 25 | 93.94% accuracy (31/33) | 88.24% accuracy (30/34) | 84.21% accuracy (16/19) | 100.0% accuracy (14/14) | 91.0 | 67455 | 0.0 | | | google/gemma-3-12b | 4bit | strict | 25 | 100.0% accuracy (33/33) | 91.18% accuracy (31/34) | 89.47% accuracy (17/19) | 100.0% accuracy (14/14) | 95.0 | 58454 | 0.0 | | # Model Context Protocol (MCP) Source: https://docs.sure.am/development/mcp Connect an MCP-compatible AI assistant to your Sure financial data Sure includes an MCP server that lets compatible AI assistants use the financial data and tools available to your Sure account. > [!WARNING] > > An authorized client can read the user and family financial data exposed by Sure's MCP tools. Depending on the tools available in your Sure version, it may also be able to make changes. For example, `import_bank_statement` can create a transaction import from an uploaded bank-statement PDF. Only connect clients and AI providers you trust, and review tool requests before approving them. ## Connect an AI assistant 1. Sign in to Sure and open **Settings > MCP Server**. 2. Copy the MCP server URL shown on the page. Sure builds this URL from your configured base URL and appends `/mcp`. 3. Open Claude.ai and go to **Settings > Connectors**. 4. Select **Add a connector**. 5. Enter the connector name and paste the MCP server URL from Sure **Settings > MCP Server**, then select **Add**. 6. Select the connector's **Connect** button to complete authorization. Your browser redirects to Sure. Sign in if needed, then authorize access. After authorization, the client can use the Sure tools exposed to it. Other MCP-compatible clients follow the same general process: give the client the URL from **Settings > MCP Server**, then complete Sure's sign-in and authorization flow in your browser. The client handles the MCP and OAuth protocol details; you do not need to register it or create an access token manually. ## Manage connected clients The **Connected clients** section under **Settings > MCP Server** lists clients with active access to your account. Select **Revoke** beside a client to invalidate its token. Revoke clients you no longer use or recognize. ## Available tools and access The current `Assistant.function_classes` registry exposes the following tools. Tool availability and schemas can vary by Sure version, so clients should use `tools/list` as the source of truth for their installation. ### Read | Tool | Description | | - | - | | `get_transactions` | Search transactions with optional filters and pagination; useful for finding transactions and calculating statistics for small groups of results | | `get_recurring_transactions` | Detected and manual recurring transactions (subscriptions, bills, salaries) with expected dates and per-currency totals | | `get_accounts` | List accounts with current and historical balances and account metadata | | `get_holdings` | Search Investment and Crypto account holdings, including portfolio, performance, and cost-basis data; results are paginated | | `get_balance_sheet` | Retrieve balance-sheet and net-worth data with historical information | | `get_income_statement` | Retrieve income and expenses by category for a date range | | `get_budget` | Compare a monthly budget with spending by category, with an optional prior-month trend comparison | | `get_merchants` | List merchants with the IDs that `update_transaction` accepts and the exact names that `get_transactions` filters on | | `get_tags` | List family tags alphabetically | | `get_categories` | List family categories hierarchically, including IDs and parent relationships | | `search_family_files` | Search uploaded family documents and return relevant excerpts and source filenames. This is the vector-store document index, not the Statement Vault — statements archived via `upload_account_statement` are not searchable through it | ### Rules | Tool | Description | | - | - | | `get_rules` | List the family's transaction rules with conditions, actions (account, category, tag, and merchant names resolved), whether each rule is active, its effective date, and its latest run. Pass `rule_id` for a single rule including its current match count. Pass `search` to match by rule name, condition values, action values, or category names. Results are paginated. | | `get_rule_options` | Return the condition types, operators, and action types a rule can use. Call this before `preview_rule` or `create_rule` to build a valid definition. AI-backed actions (`auto_categorize`, `auto_detect_merchants`) are not available through MCP. | | `preview_rule` | Show which transactions a rule matches without changing anything. Pass either `rule_id` for a saved rule or an unsaved definition with `conditions` and `actions`. Returns the match count, a sample of the most recent matching transactions, and the actions in readable form. For a saved rule it can also return the `preview_token` that `apply_rule` requires. A nonzero match count needs at least one visible sample; a rule with zero matches can receive a token for future activation. | | `create_rule` | Save a new transaction rule. Rules are always saved inactive and do not change any transaction until `apply_rule` activates them. Returns the saved rule and a preview, with a `preview_token` when the preview meets the sample requirements described above. | | `update_rule` | Update a rule's name, conditions, actions, effective date, or set it inactive. Supplying conditions, actions, or an effective date deactivates it, even if the supplied value is unchanged; call `apply_rule` after checking the returned preview. Cannot activate a rule; use `apply_rule` for that. Rules with AI-backed actions must be edited in **Settings > Rules**. | | `apply_rule` | Activate a rule and apply it to matching transactions. Requires the `preview_token` from the latest `preview_rule`, `create_rule`, or `update_rule` call for that rule (`get_rules` does not issue one). The token expires after 30 minutes and is invalidated if the rule definition or its match count changes. By default, transactions whose values were set by hand are preserved; pass `override_locked: true` to overwrite them. Runs in the background. | New rules are saved inactive; renaming an existing active rule can leave it active. `apply_rule` is the only tool that activates a rule and applies it to existing transactions. A `preview_token` from an actual preview is required; it expires after 30 minutes and is invalidated if the rule definition or match count changes since the preview was issued. AI-backed actions (`auto_categorize`, `auto_detect_merchants`) are not available through MCP — edit those rules in **Settings > Rules**. ### Create, update, and import | Tool | Description | | - | - | | `import_bank_statement` | Use AI extraction to import transactions from an already-uploaded bank-statement PDF; creates a transaction import and returns its ID and rows for review | | `create_goal` | Create a savings goal linked to at least one eligible depository account, only after confirming key details with the user. The available-accounts list returned on failure includes how much each account has free to earmark and whether it is already claimed in full by another goal. Pass an `earmarks` map (account name → amount) to reserve a specific portion of an account rather than its whole balance — required when an account is already claimed in full. | | `create_tag` | Create a unique family tag | | `update_tag` | Update an existing tag's name or color | | `create_category` | Create a unique category, optionally as a subcategory | | `update_category` | Update an existing category's name, color, or icon | | `create_transaction` | Create a new transaction on a writable account. Negative amount = income (money in), positive = expense (money out). Pass `type` (`income` or `expense`) to derive the sign from a positive magnitude instead. Pass `external_id` (and optionally `source`, defaulting to `"mcp"`) to make the call idempotent: a repeat call with the same account + source + external\_id returns the existing transaction instead of creating a duplicate. | | `delete_transaction` | Permanently delete a transaction and its ledger entry, recalculating the account balance. Pass the transaction `id` returned by `get_transactions` or `create_transaction`. Optionally pass `account_id` as a guard so a mismatched id cannot delete the wrong record. Split child transactions cannot be deleted individually; delete the split parent instead. | | `unmatch_transfer` | Unlink a confirmed or pending transfer between two accounts, keeping both transactions. A confirmed transfer’s legs return to standard kinds; a pending match’s existing kinds are preserved. Pass the `transaction_id` of either side or the `transfer_id`. By default the pairing is rejected so auto-match won't suggest it again; pass `reject: false` to only unlink. Fee transactions attached to the transfer are deleted with it and listed in the result. Pass `dry_run: true` to preview the effect first. | | `update_transfer` | Switch a confirmed transfer from a non-investment, non-crypto account into an investment or crypto account between an investment contribution and a plain transfer. Both accounts must be writable. Contributions count as spending by default, unless the family turns off **Count investing as spending**. Use this when a brokerage or crypto account only converts currency and the round trip should not appear as an expense. Pass `dry_run: true` to preview the change first. | | `update_transaction` | Update an existing transaction's name, notes, category, merchant, or tags after finding it with `get_transactions` | | `update_budget` | Update budget allocations for a month | | `set_opening_balance` | Set a manual account's opening balance and, optionally, the date it applies from. Returns whether the current balance will change as a result. Pass `dry_run: true` to preview the effect without writing. Accounts synced from a provider are refused. | `create_transaction` and `delete_transaction` write to the ledger. `delete_transaction` is permanent and irreversible. `import_bank_statement` is not read-only. It requires a bank-statement PDF already uploaded to Sure and creates an import for review; it does not publish the import automatically. Because MCP access is scoped to the Sure user who authorizes the client, tools can access that user's family data. Review tool calls whenever your client offers that option. `apply_rule` activates a rule and runs it against matching transactions, respecting rule order and attribute locks by default. Deactivating the rule does not undo earlier changes. ### Preview tools These tools appear only when the MCP user has opted into preview features under **Settings > Preferences**. Until then they are absent from `tools/list`, and calling one by name returns an "Unknown tool" error. The Statement Vault tools also require the user to be an admin or member, matching the permissions enforced in the web UI. | Tool | Description | | - | - | | `upload_account_statement` | Store a statement document (PDF/CSV/XLSX) in the Statement Vault; deduplicates by SHA-256 | | `list_account_statements` | List vault documents with their SHA-256, period, linked account, and review status | | `get_account_statement` | One statement's details and its reconciliation checks against the ledger. Present only after the opening and closing balances have been entered in the web UI. Does not return the file; stored documents are served only to a signed-in browser session | | `get_statement_coverage` | Month-by-month statement coverage for an account: `covered`, `missing`, `mismatched`, `ambiguous`, `duplicate`, `not_expected`, each with a reconciliation status | | `record_valuation` | Record an account's value on a date, with a required source citation | | `get_valuations` | List recorded valuations newest first, including the citation stored in each entry's notes; the read pair for `record_valuation` | | `get_insights` | Read the proactive insights feed (spending anomalies, cash-flow warnings, subscription audits, and more) without marking anything read | | `get_bills` | List bills, subscriptions, and other recurring obligations with each one's current payment state; supports filtering by status, payment state, bill type, due date window, and name search | | `get_bill_details` | One bill's full configuration, open occurrences, payment history, price-change history, and cost analytics; pass the exact `bill_id` returned by `get_bills` | | `get_paycheck_plan` | Income plan sliced into pay periods: what is due before the next payday, what stays reserved for later bills, and what is safe to spend; requires at least one declared income schedule | | `get_bill_audit` | Deterministic review of bills: possible duplicates, price changes, trials about to convert, upcoming renewals, long-overdue bills, dormant bills, and undeclared recurring patterns | | `create_bill` | Create a bill, subscription, installment plan, or income schedule; confirm key details with the user before calling | | `update_bill` | Update one bill's configuration; amount changes apply from today forward and status accepts `active` or `paused` | | `record_bill_payment` | Record a partial or full payment against a bill's open occurrence | These tools are designed for agents that maintain a document-backed record of a family's wealth over time. ## Technical details Sure serves MCP over JSON-RPC 2.0 at the URL displayed in **Settings > MCP Server**. The endpoint supports `initialize`, `tools/list`, and `tools/call` over HTTP `POST` requests. MCP-compatible clients use this URL and handle browser-based sign-in and authorization with Sure. Sure authenticates each MCP request with an active OAuth access token that has the `read_write` scope. The token's resource owner determines the Sure user and family available to the tools. Sure creates a fresh transient session for that user for the request so an existing browser or impersonation session is not reused. ### Dynamic client registration redirect URIs Sure registers MCP clients dynamically via `POST /register`. The `redirect_uris` field must contain at least one URI that matches one of the following schemes: * **`https`** — any HTTPS URI with a host (e.g. `https://claude.ai/callback`) * **Loopback HTTP** — `http://localhost`, `http://127.0.0.1`, or `http://[::1]` (any port) * **Native-app private-use scheme** — custom URI schemes used by desktop and mobile OAuth clients, such as `cursor://anysphere.cursor-mcp/oauth/callback`, `vscode://augment.vscode-augment/auth/mcp`, or reverse-domain schemes like `com.example.app:/oauth2redirect/example-provider` A registration request may include a mix of the above (for example, Cursor's default payload includes a `cursor://` scheme, a loopback HTTP URI, and an `https` URI in the same list). Sure validates every URI in the list; if any URI fails validation the entire registration is rejected. The following URI schemes are always rejected: `javascript`, `data`, `file`, `about`, `blob`, `ws`, `wss`, `ftp`, `mailto`, `tel`, `sms`, and `intent`. Plain HTTP to a non-loopback host is also rejected. URIs with a userinfo component or a fragment are rejected regardless of scheme. ### Dynamic client registration client names The `client_name` field in a `POST /register` request is optional; Sure defaults to `"MCP Client"` when it is absent. Two additional restrictions apply: * **Reserved names** — Names that contain the word "Sure" as a whole word, or that start with "SureMobile", are reserved for first-party apps and are rejected with `invalid_client_metadata`. The check is case-insensitive, strips punctuation, invisible characters, and combining marks, and maps look-alike Cyrillic, Greek, and Armenian letters to their Latin equivalents before matching. Names such as "Measure Mobile" or "Surefire" are not affected. * **Bidirectional control characters** — Names that contain any Unicode bidirectional control character (for example U+202E RIGHT-TO-LEFT OVERRIDE) are rejected with `invalid_client_metadata`. These characters can make the consent screen render a different name than the one stored, so Sure rejects them instead of silently stripping them. Both rules return HTTP 400 with `error: "invalid_client_metadata"`. ### Protocol version and transport Sure supports protocol versions `2025-03-26` and `2025-06-18`. The current default is `2025-06-18`, which introduces the Streamable HTTP transport used by clients such as Bifrost v1.6.3 and later. During the `initialize` handshake, the client sends its preferred version in `params.protocolVersion`. Sure selects that version if it is supported, or falls back to `2025-06-18` otherwise. The agreed version is returned in the `initialize` response body and echoed in the `Mcp-Protocol-Version` response header on every subsequent response. The `initialize` response also includes a `sessionId` field. Sure records the session in a server-side cache for 24 hours. Subsequent requests may include this value in the `Mcp-Session-Id` request header; Sure validates the session and echoes the ID in the corresponding response header. Clients that do not send a session ID are still served normally. ### Legacy environment-token fallback Self-hosted deployments can optionally support older clients that cannot complete the browser authorization flow. Set both `MCP_API_TOKEN` to a high-entropy secret and `MCP_USER_EMAIL` to an existing Sure user's email. The client sends the configured token as a bearer token, and the selected user's family data is exposed to the available MCP tools. This is a compatibility fallback: Sure tries OAuth access-token authentication first. Prefer the connection flow in **Settings > MCP Server**, and protect, rotate, and avoid logging any fallback token. ## Optional Pipelock proxy [Pipelock](https://github.com/luckyPipewrench/pipelock) is an optional security proxy that can scan MCP tool calls and responses for secret exfiltration, prompt injection, and tool poisoning before forwarding traffic to Sure. Sure's AI Docker Compose example exposes Pipelock's MCP listener on port `8889` and forwards it to Sure's internal `/mcp` endpoint. The Helm chart can similarly expose a Pipelock MCP ingress. Operators who deploy it should provide users with the proxied MCP address. Pipelock adds scanning; it does not replace Sure's browser sign-in and authorization or require users to configure OAuth manually. Operators can see the [Pipelock section in the Helm guide](/self-hosting-helm#pipelock-ai-agent-security-proxy) for deployment and policy options. Use TLS, restrict direct access to `/mcp` when practical, and ensure clients use the proxied URL so they cannot bypass scanning. # Rails provider generator Source: https://docs.sure.am/development/rails-provider-generator Generate new provider integrations with global or per-family credentials This guide explains how to use the `Provider` generators, which make it easy to add new integrations with either **global** or **per-family** scope credentials. ## Quick start ### Two generators available ```bash theme={null} # Per-Family Provider (each family has separate credentials) rails g provider:family field:type[:secret] ... # Global Provider (all families share site-wide credentials) rails g provider:global field:type[:secret] ... ``` ### Quick examples ```bash theme={null} # Per-family: Each family has their own Lunchflow API key rails g provider:family lunchflow api_key:text:secret base_url:string # Global: All families share the same Plaid credentials rails g provider:global plaid \ client_id:string:secret \ secret:string:secret \ environment:string:default=sandbox ``` ## Global vs per-family: Which to use? ### Use `provider:global` when: * ✅ One set of credentials serves the entire application * ✅ Provider charges per-application (not per-customer) * ✅ You control the API account (self-hosted or managed mode) * ✅ All families can safely share access * ✅ Examples: Plaid, OpenAI, exchange rate services ### Use `provider:family` when: * ✅ Each family/customer needs their own credentials * ✅ Provider charges per-customer * ✅ Users bring their own API keys * ✅ Data isolation required between families * ✅ Examples: Lunch Flow, SimpleFIN, YNAB, personal bank APIs ## Provider:family generator ### Usage ```bash theme={null} rails g provider:family field:type[:secret][:default=value] ... ``` ### Reserved field names The generator rejects field names that are already defined on the items table. Passing a reserved name raises a `Thor::Error` at generation time rather than producing broken migrations or inconsistent models. Reserved names include: `family_id`, `institution_id`, `institution_name`, `institution_domain`, `institution_url`, `institution_color`, `status`, `scheduled_for_deletion`, `pending_account_setup`, `sync_start_date`, `raw_payload`, `raw_institution_payload`. Note that `family` (without `_id`) is **not** reserved — the migration writes `t.references :family`, which creates `family_id`, so a field named `family` is not a collision. ### Example: Adding a MyBank provider ```bash theme={null} rails g provider:family my_bank \ api_key:text:secret \ base_url:string:default=https://api.mybank.com \ refresh_token:text:secret ``` ### What gets generated This single command generates: * ✅ Migration for `my_bank_items` and `my_bank_accounts` tables **with credential fields** * ✅ Models: `MyBankItem`, `MyBankAccount`, and `MyBankItem::Provided` concern * ✅ Adapter class for provider integration * ✅ Simple manual panel view for provider settings * ✅ Controller with CRUD actions and Turbo Stream support * ✅ Routes * ✅ Bank sync wiring: the settings controller's `FAMILY_PANELS` entry and sync maps, and a `provider_summary` case The last item means the provider appears under **Your connections** on the Bank sync page, its connection row shows a sync status, and the Sync button works — all without any manual follow-up steps. The generated item partial renders the provider's logo with `ProviderLogo`. That reads the provider's `Provider::Metadata::REGISTRY` entry, which the generator does not create, so add one in `app/models/provider/metadata.rb`. See the [providers LLM guide](https://github.com/we-promise/sure/blob/main/docs/llm-guides/providers.md#provider-logos) for the fields it reads (`domain`, `logo_text`, `logo_color`, `logo_icon`) and which are used when Brandfetch has no icon or is not configured. The item partial declares `visible_accounts:` as a strict local. Callers must pass the accounts to display explicitly. The rendered account list uses that local; the partial can still query the item's accounts for summary counts. Pass only the accounts you want shown: ```erb theme={null} <%= render "my_bank_items/my_bank_item", my_bank_item: item, visible_accounts: visible_card_accounts(item) %> ``` The generated caller uses `visible_card_accounts(item)` to respect the current user's account visibility. A strict local requires an explicit argument; it does not enforce authorization, so callers must not replace the filtered list with all accounts indiscriminately. ### Key characteristics * **Credentials**: Stored in `my_bank_items` table (encrypted) * **Isolation**: Each family has completely separate credentials * **UI**: Manual form panel at `/settings/providers` * **Configuration**: Per-family, self-service ## Provider:global generator ### Usage ```bash theme={null} rails g provider:global field:type[:secret][:default=value] ... ``` ### Example: Adding a Plaid provider ```bash theme={null} rails g provider:global plaid \ client_id:string:secret \ secret:string:secret \ environment:string:default=sandbox ``` ### What gets generated This single command generates: * ✅ Migration for `plaid_items` and `plaid_accounts` tables **without credential fields** * ✅ Models: `PlaidItem`, `PlaidAccount`, and `PlaidItem::Provided` concern * ✅ Adapter with `Provider::Configurable` * ❌ No controller (credentials managed globally) * ❌ No view (UI auto-generated by `Provider::Configurable`) * ❌ No routes (no CRUD needed) ### Key characteristics * **Credentials**: Stored in `settings` table (global, not encrypted) * **Sharing**: All families use the same credentials * **UI**: Auto-generated at `/settings/providers` (self-hosted mode only) * **Configuration**: ENV variables or admin settings ### Important notes * Credentials are shared by **all families** - use only for trusted services * Only available in **self-hosted mode** (admin-only access) * No per-family credential management needed * Simpler implementation (fewer files generated) ## Comparison table | Aspect | `provider:family` | `provider:global` | | - | - | - | | **Credentials storage** | `provider_items` table (per-family) | `settings` table (global) | | **Credential encryption** | ✅ Yes (ActiveRecord encryption) | ❌ No (plaintext in settings) | | **Family isolation** | ✅ Complete (each family has own credentials) | ❌ None (all families share) | | **Files generated** | 9+ files | 5 files | | **Migration includes credentials** | ✅ Yes | ❌ No | | **Controller** | ✅ Yes (simple CRUD) | ❌ No | | **View** | ✅ Manual form panel | ❌ Auto-generated | | **Routes** | ✅ Yes | ❌ No | | **UI location** | `/settings/providers` (always) | `/settings/providers` (self-hosted only) | | **ENV variable support** | ❌ No (per-family can't use ENV) | ✅ Yes (fallback) | | **Use case** | User brings own API key | Platform provides API access | | **Examples** | Lunch Flow, SimpleFIN, YNAB | Plaid, OpenAI, TwelveData | ## What gets generated (detailed) ### 1. Migration **File:** `db/migrate/xxx_create_my_bank_tables_and_accounts.rb` Creates two complete tables with all necessary fields. The generator writes the Rails version in use when it runs, taken from `Rails::VERSION::MAJOR` and `Rails::VERSION::MINOR` joined by a dot (for example, `8.1`). The version in any generated migration is then fixed — it pins the semantics the migration was written against and is not rewritten by later upgrades. ```ruby theme={null} class CreateMyBankTablesAndAccounts < ActiveRecord::Migration[8.1] def change # Create provider items table (stores per-family connection credentials) create_table :my_bank_items, id: :uuid do |t| t.references :family, null: false, foreign_key: true, type: :uuid t.string :name # Institution metadata t.string :institution_id t.string :institution_name t.string :institution_domain t.string :institution_url t.string :institution_color # Status and lifecycle t.string :status, default: "good" t.boolean :scheduled_for_deletion, default: false t.boolean :pending_account_setup, default: false # Sync settings t.datetime :sync_start_date # Raw data storage t.jsonb :raw_payload t.jsonb :raw_institution_payload # Provider-specific credential fields t.text :api_key t.string :base_url t.text :refresh_token t.timestamps end add_index :my_bank_items, :family_id add_index :my_bank_items, :status # Create provider accounts table (stores individual account data from provider) create_table :my_bank_accounts, id: :uuid do |t| t.references :my_bank_item, null: false, foreign_key: true, type: :uuid # Account identification t.string :name t.string :account_id # Account details t.string :currency t.decimal :current_balance, precision: 19, scale: 4 t.string :account_status t.string :account_type t.string :provider # Metadata and raw data t.jsonb :institution_metadata t.jsonb :raw_payload t.jsonb :raw_transactions_payload t.timestamps end add_index :my_bank_accounts, :account_id add_index :my_bank_accounts, :my_bank_item_id end end ``` ### 2. Models **File:** `app/models/my_bank_item.rb` The item model stores per-family connection credentials: ```ruby theme={null} class MyBankItem < ApplicationRecord include Syncable, Provided, Unlinking, DestroyableLater enum :status, { good: "good", requires_update: "requires_update" }, default: :good # The generator defines this helper directly. def self.encryption_ready? creds_ready = Rails.application.credentials.active_record_encryption.present? env_ready = ENV["ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY"].present? && ENV["ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY"].present? && ENV["ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT"].present? creds_ready || env_ready end # Encryption for secret fields (optional — active with explicit environment keys or Rails credentials) if encryption_ready? encrypts :api_key, :refresh_token, deterministic: true end validates :name, presence: true validates :api_key, presence: true, on: :create validates :refresh_token, presence: true, on: :create belongs_to :family has_one_attached :logo has_many :my_bank_accounts, dependent: :destroy has_many :accounts, through: :my_bank_accounts scope :active, -> { where(scheduled_for_deletion: false) } scope :syncable, -> { active } scope :ordered, -> { order(created_at: :desc) } scope :needs_update, -> { where(status: :requires_update) } def credentials_configured? api_key.present? && refresh_token.present? end def effective_base_url base_url.presence || "https://api.mybank.com" end end ``` **File:** `app/models/my_bank_account.rb` The account model stores individual account data from the provider: ```ruby theme={null} class MyBankAccount < ApplicationRecord include CurrencyNormalizable belongs_to :my_bank_item # Association through account_providers for linking to internal accounts has_one :account_provider, as: :provider, dependent: :destroy has_one :account, through: :account_provider, source: :account validates :name, :currency, presence: true def upsert_my_bank_snapshot!(account_snapshot) update!( current_balance: account_snapshot[:balance], currency: parse_currency(account_snapshot[:currency]) || "USD", name: account_snapshot[:name], account_id: account_snapshot[:id]&.to_s, account_status: account_snapshot[:status], raw_payload: account_snapshot ) end end ``` **File:** `app/models/my_bank_item/provided.rb` The Provided concern connects the item to its provider SDK: ```ruby theme={null} module MyBankItem::Provided extend ActiveSupport::Concern def my_bank_provider return nil unless credentials_configured? Provider::MyBank.new( api_key, base_url: effective_base_url, refresh_token: refresh_token ) end end ``` ### 3. Adapter **File:** `app/models/provider/my_bank_adapter.rb` ```ruby theme={null} class Provider::MyBankAdapter < Provider::Base include Provider::Syncable include Provider::InstitutionMetadata # Register this adapter with the factory Provider::Factory.register("MyBankAccount", self) def provider_name "my_bank" end # Build a My Bank provider instance with family-specific credentials def self.build_provider(family:) return nil unless family.present? # Get family-specific credentials my_bank_item = family.my_bank_items.where.not(api_key: nil).first return nil unless my_bank_item&.credentials_configured? # TODO: Implement provider initialization Provider::MyBank.new( my_bank_item.api_key, base_url: my_bank_item.effective_base_url, refresh_token: my_bank_item.refresh_token ) end def sync_path Rails.application.routes.url_helpers.sync_my_bank_item_path(item) end def item provider_account.my_bank_item end def can_delete_holdings? false end def institution_domain metadata = provider_account.institution_metadata return nil unless metadata.present? metadata["domain"] end def institution_name metadata = provider_account.institution_metadata return nil unless metadata.present? metadata["name"] || item&.institution_name end def institution_url metadata = provider_account.institution_metadata return nil unless metadata.present? metadata["url"] || item&.institution_url end def institution_color item&.institution_color end end ``` ### 4. Controller **File:** `app/controllers/my_bank_items_controller.rb` The generated controller inherits `StreamExtensions` through `ApplicationController` and uses `frame_redirect_to` for missing-credential exits. The account-linking flow actions (`preload_accounts`, `select_accounts`, `select_existing_account`) call `frame_redirect_to` when a required credential check fails. A plain `redirect_to` inside a Turbo frame follows the redirect inside the frame, so the resulting page renders inside the modal and the flash message is never shown. `frame_redirect_to` detects whether the request came from a Turbo frame and, when it did, renders a frame containing a `turbo-stream` redirect action, which causes a full-page visit instead of a frame navigation. ```ruby theme={null} class MyBankItemsController < ApplicationController before_action :set_my_bank_item, only: [:show, :edit, :update, :destroy, :sync, :setup_accounts, :complete_account_setup] def create @my_bank_item = Current.family.my_bank_items.build(my_bank_item_params) @my_bank_item.name ||= "My Bank Connection" if @my_bank_item.save redirect_to settings_providers_path, notice: t(".success"), status: :see_other else render_provider_panel("my_bank", alert: @my_bank_item.errors.full_messages.join(", ")) end end def update if @my_bank_item.update(my_bank_item_params) render_provider_panel("my_bank", notice: t(".success")) else render_provider_panel("my_bank", alert: @my_bank_item.errors.full_messages.join(", ")) end end def destroy @my_bank_item.destroy_later redirect_to settings_providers_path, notice: t(".success", default: "Scheduled My Bank connection for deletion.") end def sync unless @my_bank_item.syncing? @my_bank_item.sync_later end respond_to do |format| format.html { redirect_back_or_to accounts_path } format.json { head :ok } end end # Account-linking flow actions def preload_accounts my_bank_item = Current.family.my_bank_items.first unless my_bank_item&.credentials_configured? frame_redirect_to settings_providers_path, alert: t(".no_credentials_configured") return end my_bank_item.sync_later unless my_bank_item.syncing? redirect_to select_accounts_my_bank_items_path(accountable_type: params[:accountable_type], return_to: params[:return_to]) end def select_accounts my_bank_item = Current.family.my_bank_items.first unless my_bank_item&.credentials_configured? frame_redirect_to settings_providers_path, alert: t(".no_credentials_configured") return end @my_bank_accounts = my_bank_item.my_bank_accounts .left_joins(:account_provider) .where(account_providers: { id: nil }) .order(:name) end def select_existing_account @account = Current.family.accounts.find(params[:account_id]) @my_bank_item = Current.family.my_bank_items.first unless @my_bank_item&.credentials_configured? frame_redirect_to settings_providers_path, alert: t(".no_credentials_configured") return end @my_bank_accounts = @my_bank_item.my_bank_accounts .left_joins(:account_provider) .where(account_providers: { id: nil }) .order(:name) end # ... (link_accounts, link_existing_account, setup_accounts, complete_account_setup) private def set_my_bank_item @my_bank_item = Current.family.my_bank_items.find(params[:id]) end def my_bank_item_params params.require(:my_bank_item).permit(:name, :sync_start_date, :api_key, :base_url, :refresh_token) end end ``` The key difference from a plain `redirect_to` in those credential-check guards is that `frame_redirect_to` uses `turbo_frame_request?` to detect whether the request originated inside a Turbo frame. When it did, it renders a frame that carries a `turbo-stream` redirect action, which exits the frame and performs a full-page visit to the target path with the alert flash intact. For requests outside a frame it falls back to a normal `redirect_to`. ## Customization After generation, you'll typically want to customize three files: ### 1. Customize the adapter Implement the `build_provider` method in `app/models/provider/my_bank_adapter.rb`: ```ruby theme={null} def self.build_provider(family:) return nil unless family.present? # Get the family's credentials my_bank_item = family.my_bank_items.where.not(api_key: nil).first return nil unless my_bank_item&.credentials_configured? # Initialize your provider SDK with the credentials Provider::MyBank.new( my_bank_item.api_key, base_url: my_bank_item.effective_base_url, refresh_token: my_bank_item.refresh_token ) end ``` ### 2. Update the model Add custom validations, helper methods, and business logic in `app/models/my_bank_item.rb`: ```ruby theme={null} class MyBankItem < ApplicationRecord include Syncable, Provided, Unlinking, DestroyableLater belongs_to :family # Validations (the generator adds basic ones, customize as needed) validates :name, presence: true validates :api_key, presence: true, on: :create validates :refresh_token, presence: true, on: :create validates :base_url, format: { with: URI::DEFAULT_PARSER.make_regexp }, allow_blank: true # Add custom business logic def refresh_oauth_token! # Implement OAuth token refresh logic provider = my_bank_provider return false unless provider new_token = provider.refresh_token!(refresh_token) update(refresh_token: new_token) rescue Provider::MyBank::AuthenticationError update(status: :requires_update) false end # Override effective methods for better defaults def effective_base_url base_url.presence || "https://api.mybank.com" end end ``` ### 3. Customize the view Edit the generated panel view `app/views/settings/providers/_my_bank_panel.html.erb` to add custom content. `StyledFormBuilder` (used via `styled_form_with`) accepts these options on every text-type field in addition to standard HTML attributes: | Option | Description | | - | - | | `label:` | Label text shown above the field. Pass `true` to derive it from the field name, or a string for custom text. | | `help_text:` | Hint shown below the field. Linked to the input via `aria-describedby`. | | `label_tooltip:` | Tooltip icon placed beside the label with explanatory text. | | `container_class:` | Extra CSS classes on the wrapper `div`. | | `required:` | Adds a red asterisk to the label and the `required` HTML attribute to the input. | Example — adding a hint to the API key field: ```erb theme={null} <%= form.text_field :api_key, label: t(".api_key_label"), help_text: t(".api_key_hint"), type: :password %> ``` Fields rendered without a label (`label: false` or `inline: true`) receive the hint directly after the input, without a wrapper, so their layout stays unchanged. ## Examples ### Example 1: Simple API key provider ```bash theme={null} rails g provider:family coinbase api_key:text:secret ``` Result: Basic provider with just an API key field. ### Example 2: OAuth provider ```bash theme={null} rails g provider:family stripe \ client_id:string:secret \ client_secret:string:secret \ access_token:text:secret \ refresh_token:text:secret ``` Then customize the adapter to implement OAuth flow. ### Example 3: Complex provider ```bash theme={null} rails g provider:family enterprise_bank \ api_key:text:secret \ environment:string \ base_url:string \ webhook_secret:text:secret \ rate_limit:integer ``` Then add custom validations and logic in the model: ```ruby theme={null} class EnterpriseBankItem < ApplicationRecord # ... (basic setup) validates :environment, inclusion: { in: %w[sandbox production] } validates :rate_limit, numericality: { greater_than: 0 }, allow_nil: true def effective_rate_limit rate_limit || 100 # Default to 100 requests/minute end end ``` ## Reserved field names The generator rejects field names that conflict with columns already defined in the standard items table. Passing a reserved name raises an error at generation time rather than failing silently during `db:migrate`. **Reserved names** (cannot be used as custom fields): | Field | Reason | | - | - | | `institution_id` | Standard institution metadata column | | `institution_name` | Standard institution metadata column | | `institution_domain` | Standard institution metadata column | | `institution_url` | Standard institution metadata column | | `institution_color` | Standard institution metadata column | | `status` | Standard lifecycle column | | `scheduled_for_deletion` | Standard lifecycle column | | `pending_account_setup` | Standard lifecycle column | | `sync_start_date` | Standard sync column | | `raw_payload` | Standard raw data column | | `raw_institution_payload` | Standard raw data column | | `family_id` | Foreign key (created by `t.references :family`) | | `name` | Standard name column | Note that `family` itself is **not** reserved — the migration uses `t.references :family` which creates `family_id`, so a field named `family` does not collide. If you need to customize the behavior of a standard column, do so in the model after generation rather than re-declaring it as a custom field. ## Tips & best practices ### 1. Always run migrations ```bash theme={null} rails db:migrate ``` ### 2. Test in console ```ruby theme={null} # Check if adapter is registered Provider::Factory.adapters # => { ... "MyBankAccount" => Provider::MyBankAdapter, ... } # Test provider building family = Family.first item = family.my_bank_items.create!(name: "Test", api_key: "test_key", refresh_token: "test_refresh") provider = Provider::MyBankAdapter.build_provider(family: family) ``` ### 3. Use proper encryption Sure uses the `Encryptable` concern and `encryption_ready?` to make encryption optional — sensitive fields using this guard are encrypted when all three `ACTIVE_RECORD_ENCRYPTION_*` keys are configured or Active Record encryption is configured through Rails credentials. Auto-derived runtime keys alone do not enable this opt-in guard. Use this pattern in generated models: ```ruby theme={null} # In your model include Encryptable if encryption_ready? encrypts :api_key, :refresh_token, deterministic: true end ``` CI automatically runs tests that call `encryption_ready?` with throwaway keys, so encryption paths are exercised on every pull request without any manual configuration. Guard your own encryption tests the same way to get that coverage for free: ```ruby theme={null} test "stores api_key encrypted" do skip "Encryption not configured" unless MyBankItem.encryption_ready? # ... end ``` ### 4. Implement proper error handling ```ruby theme={null} def self.build_provider(family:) return nil unless family.present? item = family.my_bank_items.where.not(api_key: nil).first return nil unless item&.credentials_configured? begin Provider::MyBank.new(item.api_key) rescue Provider::MyBank::ConfigurationError => e Rails.logger.error("MyBank provider configuration error: #{e.message}") nil end end ``` ### 5. Add integration tests ```ruby theme={null} # test/models/provider/my_bank_adapter_test.rb class Provider::MyBankAdapterTest < ActiveSupport::TestCase test "builds provider with valid credentials" do family = families(:family_one) item = family.my_bank_items.create!( name: "Test Bank", api_key: "test_key" ) provider = Provider::MyBankAdapter.build_provider(family: family) assert_not_nil provider assert_instance_of Provider::MyBank, provider end test "returns nil without credentials" do family = families(:family_one) provider = Provider::MyBankAdapter.build_provider(family: family) assert_nil provider end end ``` ## Reserved field names The `provider:family` generator rejects field names that collide with columns already present on every items table. Passing a reserved name raises an error at generation time rather than failing silently at `db:migrate`. **Reserved names** (cannot be used as custom fields): `institution_id`, `institution_name`, `institution_domain`, `institution_url`, `institution_color`, `status`, `scheduled_for_deletion`, `pending_account_setup`, `sync_start_date`, `raw_payload`, `raw_institution_payload`, `family_id` If you need to store data that overlaps with one of these columns, use the built-in column directly — it already exists on the generated table. ```bash theme={null} # This will raise an error at generation time: rails g provider:family my_bank institution_id:string api_key:text:secret # => Error: 'institution_id' is a reserved field name. Drop it from the command. # Use the built-in column instead: rails g provider:family my_bank api_key:text:secret ``` ## Troubleshooting ### Reserved field name error If the generator raises `Thor::Error: '' is a reserved field name`, remove that field from the command. The items table already defines it, so declaring it again would produce a duplicate migration column and inconsistent model code. See [Reserved field names](#reserved-field-names) for the full list. ### Panel not showing 1. Check that `FAMILY_PANELS` in `settings/providers_controller.rb` includes an entry for the provider: ```ruby theme={null} { key: "my_bank", title: "My Bank", turbo_id: "my_bank", partial: "my_bank_panel" } ``` 2. Check that the instance variable is set in the controller's `show` action: ```ruby theme={null} @my_bank_items = Current.family.my_bank_items.ordered.select(:id) ``` 3. Check that `provider_summary` in `app/helpers/settings_helper.rb` has a `"my_bank"` case. ### Form not submitting 1. Check routes are properly added: `rails routes | grep my_bank` 2. Check the panel root ID matches the `turbo_id` in `FAMILY_PANELS`: the view must have `id="my_bank-providers-panel"` at its root, which `render_provider_panel` replaces via Turbo Stream. ### Encryption not working 1. Check that the model defines `encryption_ready?` (as the generator does) or includes `Encryptable`, and calls the helper before `encrypts`. 2. Configure encryption through Rails credentials or set all three environment variables: `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`, `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY`, and `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT`. Generate values with `openssl rand -hex 32` for each. 3. Restart the app after setting the variables. 4. If data was written before encryption was enabled, check whether the model and its fields are listed in `lib/tasks/security_backfill.rake`; newly generated providers are not discovered automatically. For covered models, `bin/rails security:backfill_encryption` defaults to a dry run. Review its output before applying the backfill with `DRY_RUN=false bin/rails security:backfill_encryption`. See [Turning on Active Record encryption after first boot](/self-hosting#turning-on-active-record-encryption-after-first-boot). ### Reserved field name error The generator rejects field names that collide with columns already defined on the items table. If you see a `Thor::Error` like: ``` Field "institution_id" is reserved and cannot be used as a provider field. The standard column already serves this purpose. Remove it from your command. ``` Drop the named field from your command — the standard column covers it. Reserved names include: `institution_id`, `institution_name`, `institution_domain`, `institution_url`, `institution_color`, `status`, `family_id`, `scheduled_for_deletion`, `pending_account_setup`, `sync_start_date`, `raw_payload`, `raw_institution_payload`. Note that `family` (without `_id`) is **not** reserved — `t.references :family` creates `family_id`, so a field named `family` does not collide. ### `NoMethodError: undefined method 'syncable'` during family sync If a freshly generated provider raises this error and takes down the nightly family sync, the generated item model is missing the `syncable` scope. Add it manually: ```ruby theme={null} # app/models/my_bank_item.rb scope :syncable, -> { active } ``` Providers generated after the fix include this scope automatically. ## Advanced: Creating a provider SDK For complex providers, consider creating a separate SDK class: ```ruby theme={null} # app/models/provider/my_bank.rb class Provider::MyBank class AuthenticationError < StandardError; end class RateLimitError < StandardError; end def initialize(api_key, base_url: "https://api.mybank.com") @api_key = api_key @base_url = base_url @client = HTTP.headers( "Authorization" => "Bearer #{api_key}", "User-Agent" => "MyApp/1.0" ) end def get_accounts response = @client.get("#{@base_url}/accounts") handle_response(response) end def get_transactions(account_id, start_date: nil, end_date: nil) params = { account_id: account_id } params[:start_date] = start_date.iso8601 if start_date params[:end_date] = end_date.iso8601 if end_date response = @client.get("#{@base_url}/transactions", params: params) handle_response(response) end private def handle_response(response) case response.code when 200...300 JSON.parse(response.body, symbolize_names: true) when 401, 403 raise AuthenticationError, "Invalid API key" when 429 raise RateLimitError, "Rate limit exceeded" else raise StandardError, "API error: #{response.code} #{response.body}" end end end ``` ## Summary The per-family `Provider` Rails generator system provides: * ✅ **Fast development** - Generate in seconds, not hours * ✅ **Consistency** - All providers follow the same pattern * ✅ **Maintainability** - Clear structure and conventions * ✅ **Flexibility** - Easy to customize for complex needs * ✅ **Security** - Built-in encryption for sensitive fields * ✅ **Documentation** - Self-documenting with descriptions Use it whenever you need to add a new provider where each family needs their own credentials. # Evaluation framework Source: https://docs.sure.am/evals Test and compare different LLMs for your use case The eval system helps you benchmark different LLMs for transaction categorization, merchant detection, and chat assistant functionality. ## Quick start ### Import a dataset ```bash theme={null} bin/rails 'evals:import_dataset[db/eval_data/categorization_golden_v1.yml]' ``` ### Run an evaluation ```bash theme={null} bin/rails 'evals:run[categorization_golden_v1,openai,gpt-4.1]' ``` ### Compare models ```bash theme={null} MODELS=gpt-4.1,gpt-4o-mini rake evals:compare[categorization_golden_v1] ``` ## Available commands ### Dataset management ```bash theme={null} # List all datasets rake evals:list_datasets # Import dataset from YAML rake evals:import_dataset[path/to/file.yml] # Export manually categorized transactions rake evals:export_manual_categories[family-uuid] ``` ### Running evaluations ```bash theme={null} # Run evaluation rake evals:run[dataset_name,provider,model] # Compare multiple models MODELS=model1,model2 rake evals:compare[dataset_name] # Quick smoke test rake evals:smoke_test # CI regression test rake evals:ci_regression[dataset,provider,model,threshold] ``` ### Viewing results ```bash theme={null} # List recent runs rake evals:list_runs # Show detailed report rake evals:show_run[run_id] # Generate comparison report rake evals:report[run_ids] ``` ### Cascade and analysis ```bash theme={null} # Benchmark the Bayes -> provider cascade # (measures provider accuracy on the transactions Bayes declined to categorize) rake evals:cascade[bayes_run_id,provider_run_id1,provider_run_id2] # or: BAYES= PROVIDERS=, rake evals:cascade # Analyze a candidate provider against a baseline # (shows calibration, disagreement, and a recommendation) rake evals:analyze[baseline_run_id,candidate_run_id] # or: BASELINE= CANDIDATE= rake evals:analyze ``` ## Langfuse integration Track experiments in Langfuse for side-by-side comparison and analysis. ### Setup ```bash theme={null} export LANGFUSE_PUBLIC_KEY="pk-..." export LANGFUSE_SECRET_KEY="sk-..." export LANGFUSE_REGION="eu" # Optional, defaults to eu ``` ### Commands ```bash theme={null} # Check connection bin/rails 'evals:langfuse:check' # Upload dataset bin/rails 'evals:langfuse:upload_dataset[categorization_golden_v1]' # Run experiment bin/rails 'evals:langfuse:run_experiment[categorization_golden_v1,gpt-4.1]' # List datasets in Langfuse bin/rails 'evals:langfuse:list_datasets' ``` ### What gets created When you run a Langfuse experiment, the system creates: * **Dataset** - Named `eval_` with all samples * **Traces** - One per sample showing input/output * **Scores** - Accuracy scores (0.0 or 1.0) for each trace * **Dataset Runs** - Links traces to dataset items for comparison In the Langfuse UI you can: * Compare runs side-by-side * Filter by score, model, or metadata * Track accuracy over time * Analyze per-sample results ## Evaluation types ### Categorization Tests transaction categorization accuracy across difficulty levels. **Metrics:** * Accuracy * Precision, recall, F1 score * Null accuracy (correctly returning null for ambiguous transactions) * Hierarchical accuracy (matching parent categories) * Per-difficulty breakdown **Datasets:** * `categorization_golden_v1` - 100 samples, US merchants * `categorization_golden_v1_light` - 50 samples, quick testing * `categorization_golden_v2` - 200 samples, US and European merchants ### Merchant detection Tests business name and URL detection from transaction descriptions. **Metrics:** * Name accuracy (exact match) * Fuzzy name accuracy (similarity threshold) * URL accuracy * False positive/negative rates * Average fuzzy score **Datasets:** * `merchant_detection_golden_v1` - 90 samples ### Chat assistant Tests function calling and response quality for the AI assistant. **Metrics:** * Function selection accuracy * Parameter accuracy * Response relevance * Exact match rate * Error rate **Datasets:** * `chat_golden_v1` - 50 samples * `chat_golden_v2` - routing and analytical tool scenarios; exercises CHAT classification (no tools), aggregate queries routed to `get_income_statement` / `get_balance_sheet`, and new analytical tool selection ### Naive Bayes categorizer The `naive-bayes` provider evaluates the family-trained Naive Bayes categorizer — the first stage of the auto-categorization cascade that runs before any paid provider sees a transaction. Pass `PROVIDER=bayes` to use the Bayes runner: ```bash theme={null} PROVIDER=bayes SPLIT_ROLE=test rake 'evals:run[categorization_golden_v2,naive-bayes]' ``` The Bayes runner trains the classifier on the dataset's training split and scores it on the held-out test split. A `SPLIT_ROLE` of `test` restricts the run to the test split only; omit it to run on all samples. **Important caveat:** Golden datasets contain roughly one transaction per distinct merchant, chosen for coverage. Real families have the opposite shape — the same handful of merchants repeating hundreds of times — which is exactly the repetition Naive Bayes learns from. Numbers from this runner are a lower bound on production accuracy, not a measurement. ### Cascade reporting The cascade report shows how a paid provider performs on the transactions Bayes declined to categorize. This measures the value each provider adds on top of Bayes — the residual the LLM actually needs to handle. Produce the runs first, all on the same test split: ```bash theme={null} # Step 1: run Bayes on the test split PROVIDER=bayes SPLIT_ROLE=test rake 'evals:run[categorization_golden_v2,naive-bayes]' # Step 2: run your provider(s) on the same test split PROVIDER=jev SPLIT_ROLE=test rake 'evals:run[categorization_golden_v2,~typesafe/jev-latest]' PROVIDER=openai SPLIT_ROLE=test rake 'evals:run[categorization_golden_v2,gpt-4.1]' # Step 3: view the cascade report rake evals:cascade[,,] ``` ### Candidate analysis The analyze command compares a candidate provider against a baseline. It outputs a side-by-side accuracy comparison, a confidence-calibration table for the candidate, a transaction-level disagreement breakdown, and a recommendation verdict. ```bash theme={null} rake evals:analyze[baseline_run_id,candidate_run_id] ``` Both runs must cover the same dataset. The candidate is the provider under evaluation; the baseline is what it would replace. ## Creating custom datasets Export your manually categorized transactions as a golden dataset: ```bash theme={null} # Basic usage rake evals:export_manual_categories[family-uuid] # With options FAMILY_ID=uuid OUTPUT=custom.yml LIMIT=1000 rake evals:export_manual_categories ``` This exports transactions where: * Category was manually set by the user * Category was NOT set by AI, rules, or data enrichment The output matches the standard dataset format and can be imported with `rake evals:import_dataset[path]`. ## JSON mode configuration Control how the LLM outputs structured data. Configure via environment variable or Settings UI. **Modes:** * `auto` - For OpenAI-compatible categorization and merchant detection, tries strict first and retries once with none on HTTP 400, a malformed response, or >50% failed or missing results (recommended) * `strict` - Best for thinking models (qwen-thinking, deepseek-reasoner) * `none` - Best for standard models (llama, mistral, gpt-oss) * `json_object` - Middle ground, broader compatibility ```bash theme={null} # Set via environment LLM_JSON_MODE=none bin/rails 'evals:run[...]' # Or configure in Settings → Self-Hosting → AI Provider ``` ## Example output ``` ================================================================================ Evaluation Complete ================================================================================ Status: completed Duration: 150.1s Run ID: 66c70614-72f4-49cb-8183-46103fb554f2 Metrics: accuracy: 76.0 precision: 78.75 recall: 90.0 f1_score: 84.0 null_accuracy: 100.0 hierarchical_accuracy: 68.0 samples_processed: 100 samples_correct: 76 avg_latency_ms: 1494 total_cost: 0.0 cost_per_sample: 0.0 By Difficulty: easy: 80.0% accuracy (28/35) medium: 70.59% accuracy (24/34) hard: 63.16% accuracy (12/19) edge_case: 100.0% accuracy (12/12) ``` # Recurring transactions Source: https://docs.sure.am/features/recurring-transactions Automatically detect and track recurring transactions like subscriptions, payments, and bills ## Overview The recurring transactions feature automatically identifies patterns in your transaction history to detect recurring charges like subscriptions, regular payments, and bills. Once identified, these transactions are displayed in your transaction list with projected upcoming charges. The Bills surface — which includes the pay-run overview, calendar view, paycheck planner, and AI helpers described below — is a preview feature. Each family member must enable preview features in **Settings → Preferences** before they can access it. The underlying recurring transaction detection and settings pages are available without the preview flag. ## How it works ### Automatic pattern detection Pattern detection analyzes your transaction history to identify recurring patterns based on: * **Merchant matching**: Groups transactions by the same merchant * **Amount consistency**: Looks for transactions with the same amount * **Date clustering**: Detects transactions that occur on similar days each month (within a 5-day window) * **Minimum occurrences**: Requires at least 3 occurrences in the last 3 months * **Recent activity**: Last occurrence must be within the last 45 days The pattern detection uses circular distance calculations to handle month-boundary cases (e.g., transactions on days 28, 29, 30, 31, 1, 2 are recognized as a single recurring pattern). ### Investment and crypto account exclusion Transactions in Investment and Crypto accounts are never considered as bill or income candidates, even when a provider reports them as plain transactions rather than trades. Brokerage and retirement feeds often deliver dividends, reinvestments, and 401k contributions as regular transaction rows on a fixed monthly cadence and in tightly clustered amounts — the exact shape the detector looks for. Without this exclusion, a monthly 401k contribution would be detected as recurring income (because it is an inflow to that account), which inflates cash-flow projections. The Trade entryable type is also excluded separately, so investment activity is filtered regardless of how a provider reports it. Any previously detected series that originated from an Investment or Crypto account are automatically retired (`ended`) on upgrade. Their paid, skipped, and missed occurrences are preserved as historical records, but future occurrences are removed and the detector will not recreate the series. ### When patterns are identified Pattern identification runs automatically after: * CSV imports complete (transactions, trades, accounts, etc.) * Any provider sync completes (Plaid, SimpleFIN, LunchFlow, etc.) * Manual identification via the recurring transactions settings page ### Projected transactions Active recurring transactions appear at the top of your transaction list showing: * Expected upcoming charges for the next month * Merchant name and logo * Projected amount * Expected date based on historical patterns * "Projected" badge to distinguish from actual transactions Projected transactions only appear when no filters are applied to the transaction list. The projected recurring list is cached per user and refreshed automatically when any of the following change: your recurring transactions, account statuses, the merchants attached to your recurring transactions, or your account sharing access. The cache also resets at the start of each new day, since the list shows charges due within the next 10 days. Only recurring transaction IDs are stored in the cache. The full records are loaded fresh on every request using those IDs, and account access is re-verified at that point. This means a series moved to an account you no longer have access to is excluded immediately, even if a cache entry was written just before the change. It also means the cache remains valid across application upgrades that add new columns to recurring transactions — stale cached objects that predate a schema change will not cause errors. ## Account scoping Recurring transactions respect account sharing and permissions: **What you see:** * Recurring transactions are scoped to accounts you have access to * Only recurring patterns from your owned and shared accounts appear in your list * Projected transactions only show for accounts you can view **Pattern detection:** * Pattern identification analyzes only transactions from accounts you have access to * Shared accounts contribute to recurring pattern detection based on your permissions * Each family member may see different recurring transactions based on their account access This ensures that recurring transaction detection respects your account sharing configuration and privacy settings. ## Managing recurring transactions ### Settings page Access recurring transaction management at **Settings → Recurring**. The settings page displays: * **Merchant**: The merchant name and logo * **Amount**: The recurring charge amount * **Expected day**: The day of month when the charge typically occurs * **Next date**: The next expected occurrence date * **Last occurrence**: When the transaction last occurred * **Status**: Active or inactive * **Actions**: Toggle status or delete When detection finds recurring inflows (such as a regular paycheck), those are classified as income suggestions rather than bill suggestions. Income suggestions do not appear in the Bills overview. They appear in a separate strip on **Settings → Recurring** with wording that reflects their nature as income. Confirming an income suggestion adds it as an income series, not a bill. ### Manual actions #### Identify patterns Click **Identify Patterns** to manually trigger pattern detection. This analyzes your transaction history and creates or updates recurring transaction records. Running this multiple times will not create duplicates. #### Clean up stale Click **Clean Up Stale** to mark recurring transactions as inactive if they haven't occurred recently. Staleness is measured in the series' own cycles — two missed cycles of the cadence — so quarterly and annual bills are not incorrectly retired just because they have long gaps between normal occurrences. The minimum floor is 2 months for automatically detected patterns and 6 months for manually marked patterns. Recurring transfers are matched by their transfer pair (an outflow on the source account paired with an inflow on the destination account) rather than by name, so transfers stay active as long as the pair keeps occurring and are retired only when the pair stops. #### Toggle status Use the play/pause icon to manually activate or deactivate a recurring transaction. Inactive transactions won't show projected charges. #### Delete Use the trash icon to permanently remove a recurring transaction record. #### Renaming a bill You can rename a bill from the bill drawer (Edit → name field). Renaming updates its display name without changing its matching identity. For bills matched by transaction name, Sure preserves the original detected name separately. Bills linked to a merchant continue to match by merchant ID. Renaming alone does not cause a bill to be suggested again. #### Mark as recurring You can manually mark any individual transaction as recurring from the transaction detail view. Click **Mark as Recurring** to create a manual recurring transaction. The system automatically calculates amount variance from the past 6 months of similar transactions, allowing it to track recurring charges that vary in amount (like utility bills). Two manual recurring entries for the same payee are allowed as long as their amounts differ (for example, a $3.00 fee and a $19.68 charge from the same merchant). An exact duplicate — same account, payee, currency, and amount — is still blocked. #### Create a bill from a transaction With preview features enabled, **Create a bill** appears alongside **Mark as Recurring** in the detail view for a transaction that is not a split child. It opens the declaration dialog with the merchant name (or transaction name when there is no merchant name), absolute amount, account, currency, and a projected next due date filled in. These fields can be adjusted before saving. An income transaction opens an income declaration instead of a bill. This is the fastest path for declaring a bill you can already see in your transaction history. The dialog requires preview features to be enabled under **Settings → Preferences**. ## Schedules and cadences Recurring transactions support a range of cadences beyond monthly: | Cadence | Description | | - | - | | Monthly | Once per month on a given day (e.g., the 15th) | | Weekly | Once per week on a given weekday | | Biweekly | Every two weeks on a given weekday | | Semimonthly | Twice per month on two fixed days (e.g., the 1st and 15th) | | Quarterly | Every three months on a given day | | Semiannual | Every six months on a given day | | Annual | Once per year on a given month and day | | Custom interval | Every N weeks, months, or years (1–99), for cadences not covered by a named preset | When a recurring transaction uses an interval-based cadence (biweekly, quarterly, semiannual, or a custom interval), an anchor date is required to establish the phase of the schedule. ### Custom intervals The frequency picker includes a **Custom interval** option that lets you set a bill to repeat every N weeks, months, or years, where N is any whole number from 1 to 99. Use this for cadences that named presets do not cover — for example, every 3 weeks, every 2 months, or every 2 years. When you enter a custom interval, the value must be a whole number. Decimal values (e.g. `2.5`) and non-numeric input (e.g. `3abc`) are rejected with a validation error. If the interval you enter matches a named preset — for example, every 3 months is the same schedule as quarterly — the app treats it as that preset. Reapplying the same cadence is a no-op. Custom intervals are not available to the assistant's `create_bill` and `update_bill` tools, which accept only the named preset cadences. ### Recurrence rule validation Each cadence has field requirements that are enforced when you save a recurring transaction. Validation errors are returned in your configured display language (set under **Settings → Preferences → Language**). The rules by frequency: * **Weekly** — requires a weekday. Day of month and week-of-month ordinal are not allowed. * **Monthly** — requires exactly one of: a day of the month (1–31, or -1 for the last day) or a weekday. When a weekday is set, a week-of-month ordinal is also required. * **Yearly** — same as monthly, plus a month of year is required. If you submit a schedule that violates these constraints, the app returns a `validation_failed` error with a localized message describing the specific field and rule that failed. ### Weekend adjustment When a bill falls on a weekend you can choose how the due date adjusts: * **None**: No adjustment; the bill is due on the scheduled date regardless of day of week * **Skip**: The occurrence is skipped entirely on weekends * **Before**: The due date moves to the preceding Friday * **After**: The due date moves to the following Monday ### End conditions A recurring transaction can be set to end in three ways: * **Never**: The series continues indefinitely * **On date**: The series ends on a specific calendar date * **After count**: The series ends after a fixed number of occurrences (up to 600) ## Bill types Each recurring transaction carries a type that describes the nature of the series: | Type | Description | | - | - | | Bill | A recurring expense you owe, such as rent or utilities | | Subscription | A recurring charge for a service, like a streaming plan | | Installment | A fixed-count payment plan, such as loan installments | | Income | A recurring inflow, such as a salary or dividend | | Transfer | A recurring move between your own accounts (set automatically) | | Other | Anything that doesn't fit a specific category | Transfers are typed automatically when the recurring transaction has a destination account. ## Bill fields ### Currency When you create a new bill, the amount field includes a currency picker. It defaults to your family's currency, or to the transaction's currency if you are starting the bill from an existing transaction. Once a bill is saved, its currency is fixed and shown read-only when you edit it. The amount input step follows the selected currency, capped at four decimal places: JPY uses whole units, USD uses two decimal places, and BTC uses four. Bill amounts are stored to four decimal places. Validation rejects meaningful precision beyond that storage limit rather than silently rounding it; the server does not separately impose each currency's display precision. ### Payment URL You can store a payment link on a bill. When set, you can open the link directly from the bill drawer to navigate to the payment portal. ### Autopay Mark a bill as autopay to indicate that the payment is handled automatically. Autopay bills still appear in your bill list but are not flagged as requiring action. On the overview, autopay rows are visually de-emphasized: the name and amount are shown in a secondary color rather than full contrast, making it easy to focus on bills that still need attention. When a new bill series is detected automatically, Sure checks the transaction descriptor for explicit autopay wording — such as AUTOPAY, AUTODRAFT, AUTO-DRAFT, AUTO-DEBIT, AUTO DRAFT, AUTO DEBIT, AUTODEBIT, or AUTOPMT — and sets autopay to on if any of those markers are found. This signal comes directly from the biller or bank and takes precedence over the bill-type default. Subscriptions and installment plans are always set to autopay because they are auto-charged. Bills without autopay wording default to needing action. The autopay flag remains user-editable and detection never reclassifies it after the series is created. ### Notes Free-text notes stored on the recurring transaction for your own reference. ## Status lifecycle A recurring transaction moves through the following statuses: | Status | Meaning | | - | - | | Suggested | Detected by pattern matching; waiting for your confirmation before generating projected occurrences | | Active | Live and generating projected upcoming charges | | Paused | Temporarily suspended by you; resumable | | Inactive | Automatically retired by the system after going stale | | Ended | Reached its end condition, was cancelled, or was dismissed from the suggestion queue. The detector will not recreate an ended series. | The API accepts only `active` and `inactive` on write. The other statuses are owned by the detection pipeline and the UI. ## Bills The Bills surface is a pay-run workspace that lets you see, pay, and plan around your recurring obligations. It is available to family members who have enabled preview features. The Bills page title, navigation tabs, and action buttons (New bill, New income, Review with AI) display in the language you have set in **Settings → Preferences**. Due dates shown in bill rows — in the date rail, the "Next up" strip, and the subline on narrow screens — also follow your locale. Locales that use day-first order (such as French, Polish, and Russian) show dates in that order, and any date that falls in a future year includes the year. ### Header and actions The Bills page header follows the same layout as the Transactions page. An overflow menu appears on the left side of the action area, and the primary action button appears on the right. The overflow menu contains: * The secondary add action (New bill when on the Paycheck view; New income on all other views) * Review with AI (when an LLM provider is configured and AI features are enabled) The primary action button is: * A labeled button on wider screens (New bill, or New income on the Paycheck view) * A round + button on narrow viewports, with the action name as its accessible label The Bills page also has a page heading (“Bills”) at the top of the header, giving screen readers a landmark to navigate to. ### Views The Bills page offers four views, switchable from the view switcher at the top of the page: * **Overview** — your current month at a glance. A banner for detected series awaiting review can appear first. When there are overdue, due-this-month, or upcoming bills, the pulse and AI prompt chips precede the bill list. The list orders sections as **Needs attention**, **This month**, **After this month**, and **Paused**. Payment-match reviews, suggested series, and notices follow the list. Bills are grouped by their effective due date (the later of the original due date and any snoozed date) and, when you have declared income, marked with pay-period boundaries so you can see which paycheck covers which bill. Each boundary band shows the paycheck label and the total due before the next payday. On narrow list widths — such as on a phone, or on a desktop with both sidebars open — the label and total stack vertically so neither wraps. A "Next up" strip shows the next few upcoming occurrences; select **View calendar** to open the Calendar view. The overview shows only payable series (bills, subscriptions, installment payments, and debt repayments) — detected income and transfers do not appear here. Banners, notices, and payment suggestions on the overview are scoped to this same set of payable series. Every row in every section shows a date rail on the left when the bill list is wide enough. On narrow screens (phones, or desktop windows with both sidebars open) the date rail is hidden; the row's subline leads with the same date instead — for example, "Sep 22 · Monthly on the 22nd" or "Today · Amount changed" — so the due date is always visible regardless of screen width. Dates in a future year include the year on a second line inside the rail so they do not wrap mid-date. When you have no overdue, due-this-month, or upcoming bills, the month summary and AI prompt chips are hidden and the page shows an empty state instead. Paused bills do not trigger the pulse or chips, because they owe nothing this month. Detected suggestions that are not yet confirmed do not count as bills for this purpose. The overview also shows a **Needs review** queue for suggested payment matches and a **Possible new bills** strip for suggested series. On wider screens each row in those strips shows the description and review action buttons side by side. On narrow screens (phones, or a desktop with both sidebars open) the buttons drop below the description so the full bill name is readable without truncation. Detected income suggestions are excluded from the overview and reviewed in a separate strip under **Settings → Recurring**. Below the bill list, the overview shows up to three action sections in this order, each with a labeled heading and item count: * **Needs review** — suggested payment matches. Each row shows the suggested transaction and the bill it was matched to, with Link payment and Not this one actions. On narrow layouts, the review action buttons stack below the text. * **Possible new bills** — recurring outflow patterns the detector found but you haven't confirmed yet. This section is collapsible and remembers whether you left it open or closed on each device. On narrow layouts, the Add bill and Not a bill actions stack below the bill name. Renaming a bill you have already confirmed does not by itself cause it to reappear here: detection retains the original transaction-name or merchant-ID matching identity. * **Changes** — notices about upcoming trials converting to paid plans, upcoming renewals, and price changes. Urgent notices appear first. When urgent and routine notices are both present, routine notices collapse under a disclosure; when only routine notices are present, they remain visible. * **All** — the complete list of active bill series, filterable by status, type, and sort order. The filters and the list share one card, the same way the Transactions page groups its filters and list. Each row shows the merchant logo or initials, the bill name over a schedule subline (type and cadence), the amount, and the next due date. For paused or dismissed bills, the status replaces the due date. Income bills display the amount in green. Clicking anywhere on a row opens the bill drawer. On wider screens the list is a scrollable table with four columns (name, next due, amount, actions); on narrower screens it switches to a compact list. * **Calendar** — upcoming bills laid out on a monthly calendar. The month navigation controls sit on the page background. The month totals, the calendar grid (or agenda list on mobile), and the iCal subscription links all sit on a shared card surface. The card heading shows the total bill count for the month. * **Paycheck planner** — upcoming bills apportioned across your next pay periods (see [Paycheck planner](#paycheck-planner) below). Throughout the Overview and Paycheck planner, bills use the later of their original due date and any snoozed date. A bill snoozed to a future month moves out of the current month's totals and into the month it will actually be due. Clicking anywhere on a bill row in the Overview, or on a Next up item, opens the bill in the right-hand drawer. Modifier clicks (Cmd/Ctrl) open the bill in a new tab. Navigating directly to a bill URL (for example, `/bills/:id`) opens the same drawer over the Bills overview. When a current occurrence is available, the bill summary drawer leads with its remaining balance or paid amount. A smaller line shows the amount paid, the expected total, and the due label. If the amount is estimated and the series has a known range, that range appears below the figure at all widths, including on phones. Without a current occurrence, the summary shows the series amount and, when known, the next expected date. A cancellation notice appears above the figure when a cancellation date is recorded but the series is still active. The bill drawer is the complete bill surface. It shows the bill summary at the top, followed by collapsible sections — Overview (12-month chart, per-year totals, price changes), Coming up (upcoming due dates), History (settled cycles and what paid each one), and Notes. Coming up, History, and Notes appear when they have content. The deep sections load lazily when you scroll to them. Edit, Pause/Resume, and Delete are available from a menu in the drawer header, next to the close button. AI configure appears there when you have enabled AI and an LLM provider is available. ### Bill row subline Each bill row shows a single subline with context about that occurrence. The subline follows a fixed order, truncating from the end when space is tight: 1. Due date (narrow screens only, in the same color as the date rail) 2. Autopay (only when the bill is active and set to autopay — paused bills do not show Autopay) 3. Attention reason (see below) 4. Payment N of M (for installment plans) 5. Debt payment (for transfer-type series) 6. Frequency 7. Account **Attention reasons** — when a bill needs action, the subline names the specific reason. Only the overdue reason is shown in red; other reasons (such as "Match needs review" or "Partial") remain uncolored even when the bill is also overdue. For a paused bill, the subline shows "Paused" regardless of whether there is an unpaid occurrence. **Amount changed** — a price-change notice appears only when the bill's amount has shifted by 10% or more within the last 30 days. Smaller changes do not surface in the row. **Estimated amount range** — On wider lists, an estimated, unpaid bill with a known amount range shows that range beneath the amount. On narrow screens this is hidden; open the bill drawer to see the full range. ### Row actions On wider screens, each bill row in the Overview reserves a fixed slot at the trailing edge for an action. A row shows an action only when the bill needs you now. The first matching rule applies: * **No action** — the bill is paused, or the occurrence is already settled. * **Review match** — a payment suggestion is waiting, regardless of due date. * **Add payment** — the occurrence has been partially paid and is still within its payment window. * **No action** — the bill is on autopay and is not yet overdue (autopay will handle it). * **Pay** — the bill has a payment portal URL and the occurrence is within its payment window. * **Find payment** — no payment portal URL is set and the occurrence is within its payment window. * **No action** — the occurrence is outside the payment window. On narrow screens (phones, or a desktop with both sidebars open) rows carry no action. The row's subline describes why the bill needs attention, and tapping anywhere on the row opens the drawer. The occurrence drawer always shows an action, regardless of screen size. ### Occurrence drawer Calendar entries and bill links in pay-period lists open the occurrence drawer — the action surface for resolving that specific billing cycle. Overview rows and Next up items open the bill drawer. Actions such as Review match or Record payment open the occurrence drawer; Pay opens the bill's payment link. The occurrence drawer shows: * **Due label** — a context-aware label describing when the payment is due. The label adapts to the occurrence's state: overdue (with the number of days past due), due today, due in N days, snoozed until a date, or the original due date if the cycle is already settled. For an open occurrence in a non-active series (paused or dismissed), the label leads with the series status — for example, "Paused · Due Sep 10" — rather than showing an overdue count. Paused bills omit Autopay from the bill row and drawer’s schedule subline. * **Payment progress** — the amount paid so far, the expected amount, and a progress ring. The headline reads the current state: the paid amount if fully paid, "Skipped", "Marked missed", or the remaining balance. * **Linked payments** — any transactions already allocated to this occurrence, each with an unlink option. * **Candidate matching** — when the occurrence is still open, the drawer surfaces the most likely matching transaction from your accounts as a card with a single "Link payment" action. Other likely matches appear below it. You can also search all transactions by name. For recurring transfers, the engine matches the outflow leg of a transfer between the series’ source and destination accounts rather than matching by name or merchant. * **Manual payment** — if no matching transaction exists, a disclosure panel lets you record a payment using a styled money field and date picker, without linking a bank transaction. * **Quick actions** — mark paid (settles the remainder without recording a transaction), skip, snooze for one week, and reopen (for already-settled or skipped occurrences). Snoozing moves the bill to its new date across the overview, pay-period groupings, and the "Next up" strip — a bill snoozed into the following month moves out of this month's total entirely. All labels and feedback messages in the occurrence drawer — including the due label states, payment summaries, and action confirmations — are displayed in your configured display language (set under **Settings → Preferences → Language**). ### Recording payments From the bill drawer you can apply a payment to the current occurrence in several ways: * **Link a transaction** — select an existing transaction from your accounts to record as the payment. If the transaction is in a different currency, the app converts at the exchange rate for that transaction's date. * **Manual payment** — enter an amount and date directly, with no transaction linked. * **Partial payment** — enter a custom amount less than the full due amount to record a partial payment. You can add more payments until the occurrence is fully covered. When the app cannot record a payment it shows an error message. Common reasons: * **Over-allocation** — the amount you entered would exceed the total of the linked transaction. * **Transaction used up** — the transaction's full amount is already applied to other payments. Choose a different transaction or enter a partial amount on one that still has remaining balance. * **Already applied** — the transaction is already applied to this bill. This can happen with a double submit or a stale browser tab. * **Missing exchange rate** — the transaction is in a different currency and no exchange rate is available for that date. Enter the amount explicitly to work around this. To remove a payment, use the unlink action in the payment history section of the drawer. **Suggested payments** — the matching engine may automatically suggest a transaction for an open occurrence. You can confirm the suggestion to apply it or dismiss it. Dismissing a suggestion marks that transaction so it will not be suggested for the same bill again. Suggestions appear only for occurrences the overview currently lists; occurrences from ended bills or outside the visible window are not surfaced. Recurring transfers are matched by their account pair: the engine looks for the outflow leg of a transfer from the series' source account into its destination account. This means a mortgage payment or card payment that you have marked as recurring will receive automatic payment suggestions the same way a regular bill does. All payment feedback messages — confirmations and errors — appear in your configured display language. When a transaction is linked to a bill, the **Applied to** section on the transaction detail view shows the bill name and occurrence due date. That date is displayed in your configured language as well. ### Paycheck planner The paycheck planner slices your upcoming bills across the pay periods defined by your declared income. Only manually declared income series (bill type `income`, set to manual) define pay periods; automatically detected inflows do not. Bills are sorted and filed by their effective due date — the later of the original due date and the snoozed date, if any. A bill snoozed past a payday is filed under the pay period it will actually be due in rather than the one that precedes it. For each pay period the planner shows: * The payday date and the income arriving in that period * The safe-to-spend headroom (or shortfall, if obligations exceed income) as the headline figure for that period * A three-column breakdown showing bills due this period, bills reserved for later, and the safe or short amount * An allocation bar tied to the breakdown columns by colored swatches * Bills due inside the period and their share of that paycheck * Bills due in a later period that are too large for their own paycheck and have a reserved slice held back from this period The allocation bar is shown for periods with positive income. Its segments and swatches change depending on whether the period is short: * **Normal period** — the bar has up to three segments: due (high contrast), reserved (muted), and safe (green). Zero-value segments are omitted; each breakdown column has a swatch only when its segment is present. * **Short period** — the bar splits into two segments: covered (muted, the portion income reaches) and short (red, the gap). Only the short column gets a swatch, because only the shortfall has a corresponding segment on the bar. The due and reserved columns still show their figures but without swatches. A leading window covers the time between today and the next payday. It has no income, so shortfalls in that window are measured against your cash on hand (the sum of your visible depository accounts, excluding tax-advantaged accounts). When the balance cannot be determined, the window is shown without any cash-based judgment — neither the shortfall warning nor the covered-with-items note appears. The income schedule summary appears as a card above the pay periods. It shows an eyebrow label ("Income"), the next payday headline, and a Manage control that expands to list each income series with its frequency, next payday, and amount. This section was previously a bare disclosure that sat directly on the page background. To use the paycheck planner, create at least one recurring transaction with bill type `income` and the manual flag set. ### Calendar feed You can subscribe to your bills in any calendar app that supports ICS feeds (Google Calendar, Apple Calendar, Outlook, and others). To get your feed URL, go to **Bills → Settings** (or the bills feed section of your account settings) and copy the calendar link. The feed covers the next 90 days of open, active bill occurrences and updates automatically. Key properties of the calendar feed: * **Sessionless and token-authenticated** — the URL can be shared with a calendar app without logging in each time. * **Per-member scoping** — the feed reflects only the bills you can see based on your account-sharing permissions. * **Revocable** — resetting the feed token invalidates all previously shared URLs immediately. Any calendar app using the old URL will stop receiving updates until it is given the new URL. * **Preview-gated** — the feed endpoint returns 404 if preview features are disabled for your account or if recurring transactions are disabled for your family. ### AI helpers Several in-page AI helpers are available when an LLM provider is configured and you have AI features enabled in your account. **Quick-prompt chips** — shortcut buttons that seed the AI chat sidebar with a pre-written question about your bills. Clicking a chip opens the sidebar and starts a conversation without you typing anything. The Overview shows three chips: * "What's due before my next paycheck?" * "Which subscriptions went up this year?" * "What am I paying monthly for subscriptions?" The Paycheck planner shows two chips: * "What's due before my next paycheck?" * "How much is safe to spend this period?" The Paycheck planner chips only appear when you have at least one declared income schedule. Without declared income there is no pay period or paycheck to ask about, so the chips are hidden. **Smart fill** — when you add a new bill from the Bills page and pick an existing transaction as the starting point, the smart fill button analyzes that transaction's charge history and proposes the bill name, amount, cadence, due day, and autopay status. You review and adjust the proposal before saving. **Smart configure** — in the bill drawer, the smart configure button reads the bill's own charge history and proposes corrections to any fields that the history contradicts (for example, a different due day or amount). Only fields where the history suggests a change come back with a proposal; everything else is left as is. You review the proposal in a dialog and apply only the changes you accept. All helpers require the family's LLM provider to be configured. They are not available on self-hosted installs without a provider set up. ## Assistant and MCP tools for bills When preview features are enabled and an LLM provider is configured, the assistant and any connected MCP client can interact with your bills using a set of dedicated tools. The tools are absent from the tool list until preview features are turned on. All bill tools share a consistent error contract: if a call fails, the response includes an `error` message and a `hint` explaining how to recover or retry. ### Read tools **`get_bills`** — returns your bills, subscriptions, and other recurring obligations, each with its current occurrence's payment state. Accepts optional filters: | Filter | Description | | - | - | | `status` | Series lifecycle: `active` (default), `suggested`, `paused`, `ended`, or `all` | | `payment_state` | Current occurrence state: `overdue`, `due`, `upcoming`, `partial`, or `paid`. Non-active bills never match `overdue` or `due`. Their open occurrence `state` returns the displayed lifecycle status: `"paused"` for paused or inactive series, and `"ended"` for ended series. | | `bill_type` | Kind of obligation (e.g. `bill`, `subscription`, `installment`, `income`) | | `search` | Substring match on the bill or merchant name | | `due_within_days` | Only bills whose next due date falls within this many days (1–365) | The response includes per-currency totals (active monthly equivalent spend, overdue count) computed over the full filtered set, not just the page shown. When the result is empty, `get_bills` checks whether bills exist under other statuses and returns a hint pointing there. For an open occurrence, `current_occurrence.state` is schedule-derived when the series is active (`overdue`, `due`, or `upcoming`). For a non-active series, it returns the displayed lifecycle status instead: `"paused"` for paused or inactive series, and `"ended"` for ended series. Settled occurrences retain `paid`, `skipped`, or `missed` regardless of the series lifecycle status. Use the `status` filter to find bills by lifecycle state. **`get_bill_details`** — returns one bill's full story: configuration, every open occurrence, the last 12 settled occurrences with their payments, upcoming due dates for the next 400 days (first 3), price-change history (24-month window), and cost analytics. Analytics are derived from confirmed payments only, never from estimates. Pass the exact `bill_id` returned by `get_bills`. **`get_bill_audit`** — a deterministic review of your bills that surfaces: * **Possible duplicates** — series with the same name, amount, and due day * **Price changes** — over a configurable lookback window (default 12 months, max 24) * **Upcoming trials** — trials converting within 30 days * **Upcoming renewals** — renewals due within 30 days * **Long overdue** — bills overdue by at least one full billing cycle in the series' own cadence * **Dormant** — paused bills still carrying unpaid occurrences * **Awaiting confirmation** — detected series not yet confirmed by the user * **Undeclared candidates** — recurring outflow patterns not yet declared as bills Each section reports `items`, `count`, and `truncated` (capped at 20 items). The audit returns facts; the assistant narrates and prioritizes them. **`get_paycheck_plan`** — slices upcoming bills across pay periods defined by your declared income schedules. Returns up to 6 pay periods (default 3), each showing income, bills due, bills reserved for a later period, and safe-to-spend headroom. Each bill item includes both `due_on` (the original scheduled date) and `effective_due_on` (the later of the original due date and any snoozed date), so the assistant can show the date the user will actually see. When detected series are excluded because they are still awaiting confirmation, the response notes how many were left out so the assistant can caveat the headroom figure. Only manually declared income series (bill type `income`) define pay periods. Automatically detected bank inflows do not. ### Write tools All write tools confirm their arguments strictly and return a clear error rather than guessing at ambiguous input. **`create_bill`** — creates a bill, subscription, installment plan, or income schedule. Required fields: `name`, `amount` (always a positive magnitude), and `first_due_on` (seeds the due-day anchor). Optional fields include `frequency`, `is_income`, `bill_type`, `account_name`, `category_name`, `autopay`, `payment_url`, and `notes`. The `frequency` field accepts the named preset cadences only (`monthly`, `weekly`, `biweekly`, `semimonthly`, `quarterly`, `semiannual`, `annual`). Custom intervals cannot be set through this tool. Unrecognized frequency values are rejected with the list of valid cadences rather than silently defaulting to monthly. **`update_bill`** — updates one bill's configuration. Pass only the fields being changed. Amount changes apply forward only; occurrences already due keep their original figure. Changing the frequency pins the schedule so automatic detection respects it as the user's intent. `status` accepts `active` or `paused`. **`record_bill_payment`** — records a payment against a bill's open occurrence. Omit `amount` to settle in full; pass `amount` for a partial payment. The tool rejects an amount that exceeds the remaining balance on the occurrence. Linking to a specific bank transaction is not possible here; the app's matching engine owns that flow. ### Prerequisites * Preview features must be enabled in **Settings → Preferences** * An LLM provider must be configured * Recurring transactions must not be disabled for the family (Settings → Recurring transactions) ### Pattern clustering The pattern detector uses circular distance calculations to handle month-boundary patterns: * Days are normalized on a circular scale (1–31) * Clustering accounts for wrap-around (e.g., day 31 to day 1 is distance 1) * Standard deviation threshold of 5 days for clustering * Median calculation on rotated day sequences for accurate expected day ### Amount variance filtering When building or refreshing a manual recurring entry's expected amount range, only historical transactions whose amount is within 2× of the anchor amount (double or half) are included. This prevents unrelated charges from the same merchant — for example, a small fee and a larger monthly due — from being blended into a single projected amount that matches neither real transaction. ### Cleanup logic Recurring transactions are automatically marked inactive when no matching transaction has occurred within two cycles of the series' own cadence, subject to a minimum floor: * **Automatically detected patterns**: minimum 2 months * **Manually marked patterns**: minimum 6 months This means a quarterly bill is not retired after two months of silence — it is allowed two full quarters of inactivity before being considered stale. An annual bill is given two full years. For recurring transfers, matching uses transfer-pair detection (an outflow on the source account paired with an inflow on the destination account, within the usual amount and day-of-month tolerance) so transfers stay active while the pair recurs and are retired only when the pair stops. ### Data storage Each recurring transaction record stores: * Family, account, and merchant associations * Amount and currency * Bill type * Expected day of month (1–31) * Anchor date (required for interval-based cadences) * Last occurrence date * Next expected date * Status * Occurrence count * Payment URL, autopay flag, and notes * End condition (never, on date, or after count) * Weekend adjustment rule ## Self-hosting maintenance ### When detection runs The full pipeline (detect patterns, materialize upcoming occurrences, repair provider-replaced entries, match payments, detect price changes) runs automatically: * After every completed bank sync or import (debounced by 30 seconds) * Nightly at 05:30 UTC for families that never sync You can also trigger it on demand using the **Find recurring transactions** button on an empty Bills page, or **Identify Patterns** under **Settings → Recurring transactions**. ### First run on existing data The user-triggered detection actions backfill the last six months of history: past occurrences are generated and closed as paid where a real transaction anchors them. Past occurrences with no matching transaction are deleted rather than shown as missed, so the backfill reconstructs history without fabricating debt. The backfill is idempotent, so re-running detection never duplicates history. Background syncs never backfill. On an instance upgraded from a build without the Bills subsystem, run either detection action once to reconstruct history. ### Maintenance tasks These tasks are safe to re-run. They only close history a real entry anchors and never touch existing payment records. ```bash theme={null} # Rebuild N months of occurrence history for every family (default 6) bin/rails "recurring:backfill_history[12]" # One-shot classification of auto-detected series still on defaults # (assigns bill/subscription/installment kind, a category, and autopay from descriptor) bin/rails recurring:classify_existing ``` ## Use cases ### Subscription tracking Monitor recurring subscriptions like: * Streaming services (Netflix, Spotify, etc.) * Software subscriptions (Adobe, Microsoft 365, etc.) * Membership fees (gym, clubs, etc.) ### Payment and bill management Track regular payments and bills such as: * Utilities (electricity, water, gas) * Insurance premiums * Rent or mortgage payments ### Income tracking Identify recurring income like: * Salary deposits * Freelance client payments * Investment dividends ## Limitations * Requires at least 3 occurrences in the last 3 months for automatic detection * Last occurrence must be within 45 days for automatic detection * Transactions in Investment and Crypto accounts are excluded from bill and income detection * Amount variance for manual recurring entries is bounded to 2× the anchor amount; charges outside that range are treated as separate recurring entries * Bill amounts are stored to four decimal places; meaningful precision beyond that storage limit is rejected with a validation error * Projected transactions are hidden when filters are applied * Pattern detection is event-driven (runs after syncs or manual triggers), not continuous or real-time * Interval-based cadences (biweekly, quarterly, semiannual, and custom intervals) require an anchor date * Custom interval values must be whole numbers between 1 and 99; decimal or non-numeric input is rejected * Custom intervals are available in the app UI but not through the assistant's `create_bill` or `update_bill` tools * The API writes only `active` and `inactive` status; other statuses are managed by the detection pipeline # Complete guide Source: https://docs.sure.am/guide Learn how to use Sure to manage your finances This guide covers everything you need to know about using Sure, from creating your account to managing investments. > [!NOTE] > > Sure is evolving quickly. If you find something inaccurate, please ask in the [Discord](https://discord.gg/36ZGBsxYEK), open an [issue](https://github.com/we-promise/sure/issues/new/choose), or submit a [PR](https://github.com/we-promise/sure/compare). ## Creating your account Once Sure is installed, navigate to [localhost:3000](http://localhost:3000). On a fresh install you land directly on the **Create account** page — there is no separate sign-up step. ![Landing page on a fresh install](https://github.com/user-attachments/assets/2319dc87-5615-4473-bebc-8360dd983367) Complete the setup screens to configure your login details, personal information, and preferences. When you reach the main dashboard showing "No accounts yet", you're ready to go. ![Blank home screen of Sure, with no accounts yet](https://github.com/user-attachments/assets/f06ba8e2-f188-4bf9-98a7-fdef724e9b5a) ## Using integrations The next sections cover how to manually add accounts and transactions. If you'd prefer to use an integration with a data provider, Sure supports: * [Self-custody wallets](/providers/onchain-wallets) — Bitcoin, EVM, and Solana wallets tracked natively * [Akahu](/providers/akahu) (beta) for New Zealand bank accounts * [Binance](/providers/binance) (beta) * [Coinbase](/providers/coinbase) (beta) * [CoinStats](/providers/coinstats) (beta) * [Enable Banking](/providers/enable-banking) (beta) for European banks * [Lunch Flow](/providers/lunchflow) * [monobank](/providers/monobank) for Ukrainian cards and jars * [Plaid](/providers/plaid) (US and EU) * [Questrade](/providers/questrade) (beta) for Canadian investment accounts * [Redbark](/providers/redbark) for Australian banks * [SimpleFIN](/providers/simplefin) * [SnapTrade](/providers/snaptrade) (beta) for brokerage and investment accounts * [Up](/providers/up-bank) (Australian bank) See **Settings > Bank sync** for the full list of supported providers and their setup options. Only admin users can connect a provider. Even if you use an integration, we recommend reading this guide to understand account types and how they work in Sure. ## Account types Sure supports several account types, grouped into assets (things you own) and debts/liabilities (things you owe): | Assets | Debts/Liabilities | | - | - | | Cash | Credit Card | | Investment | Loan | | Crypto | Other Liability | | Property | | | Vehicle | | | Other Asset | | ### How asset accounts work Cash, checking, and savings accounts increase when you add money and decrease when you spend money. **Example:** * Starting balance: \$500 * Add an expense of $20 → balance is now $480 * Add an income of $100 → balance is now $580 ### How debt accounts work Liability accounts track how much money you owe, so the math works differently than asset accounts. **Key rule:** * **Positive balances** = you owe money * **Negative balances** = the bank owes you (overpayment or refund) **Transaction behavior:** * **Expenses** (purchases) → increase your debt (you owe more) * **Payments or refunds** → decrease your debt (you owe less) **Credit card example:** 1. Balance: \$200 owed 2. Spend $20 → You now owe $220 (balance goes up in red) 3. Pay off $50 → You now owe $170 (balance goes down in green) **Overpayment example:** 1. Balance: -$44 (bank owes you $44) 2. Spend $1 → Bank now owes you $43 (balance shown as -\$43, moving towards zero) > [!TIP] > > This matches standard accounting and what your credit card provider shows online. Think of a liability balance as "amount owed", not "available cash". ### Quick reference | Action | Asset Account (Checking) | Liability Account (Credit Card) | | - | - | - | | Spend \$20 | Balance ↓ \$20 | Balance ↑ \$20 (more debt) | | Receive \$50 | Balance ↑ \$50 | Balance ↓ \$50 (less debt) | | Negative Balance | Overdraft | Bank owes you money | ## Adding accounts This example shows how to add a savings account. > [!TIP] > > If you're adding a credit card, loan, or any other debt, select a **Credit Card** or **Liability** account type instead of **Cash**. This ensures balances update correctly and match what your bank shows. Most bank accounts (checking, savings, money market) are cash accounts: 1. Click **Add account** (on the dashboard) or **New account** (on the Accounts page), then choose **Cash** 2. Choose **Enter account balance** to add the account manually. (If bank sync is configured, admins also see **Link with ...** provider options here.) 3. Fill in the details: * **Account name** * **Balance on date** (the balance as of the opening balance date below — that date defaults to two years ago, so set it to today if you're entering your current balance) * **Opening balance date** * **Subtype** (specify checking, savings, or another type) 4. Click **Create Account** The account selection dialog supports keyboard navigation. Use **J** / **K** or the arrow keys to move between options, **Enter** to select, and **Esc** to close. These labels display in your configured interface language. ![Cash Account creation menu](https://github.com/user-attachments/assets/e564a447-c85e-403e-979b-efe770ea2a61) Once created, you'll return to the home screen. You'll see your new account in the accounts list and an overview in the center under the net worth bar. ![Home screen of Sure, showing one account and no transactions](https://github.com/user-attachments/assets/7766a0cd-6b20-48f0-9ba2-87dfddd77236) ### Expand and collapse account groups Each tab in the accounts sidebar (All, Assets, Debts) has an expand/collapse toggle icon in its header. Clicking the icon expands every account group in that tab when any group is closed, and collapses all groups when every group is already open. The icon updates automatically as you open or close groups manually. The same toggle appears in the Dashboard balance sheet header, where it controls the groups on the dashboard rather than the sidebar. You can configure which groups start expanded by default under **Settings → Appearance → Dashboard**. Groups you mark there open automatically on every page load across the sidebar and the dashboard. ### Account order in the sidebar By default, accounts within each group are sorted alphabetically by name. You can change this under **Settings → Appearance → Default account order** to sort by name (A-Z or Z-A) or by balance (high to low or low to high). Choose **Manual (drag to reorder)** to arrange accounts yourself. A **Sort accounts** button then appears at the top of the sidebar. Click it to enter sort mode, drag rows to reposition them, and click **Done** to exit. You can also move rows with the keyboard: press **Enter** or **Space** to grab a row, use **Up** and **Down** to reposition it, and press **Enter**, **Space**, or **Escape** to release. The order is saved per account type group and also applies to the dashboard balance sheet. ### Account sparklines and trend percentages Each account and account group in the sidebar displays a small 30-day sparkline chart and a percentage trend. The trend percentage shows how the balance has changed over the last 30 days. The sparkline and trend percentage only appear once there is enough balance history. For a brand-new account with no historical data, the sidebar shows a placeholder instead. Once balances accumulate over time, the chart and trend fill in automatically. Sparklines inside collapsed account groups are loaded lazily — Sure only fetches them when the group is expanded and the rows scroll into view. Until then, those rows keep their loading placeholder. This is expected behavior and does not indicate an error. For linked investment and crypto accounts, the sparkline only covers the period supported by your provider connection. Data from before the provider's first import is excluded, so the sparkline reflects your actual account history rather than estimated or zero-filled values from before the connection was established. Group sparklines in the sidebar use the same accounts as the group total they sit next to. That means they include only the accounts that are accessible to you, included in your finances (owned by you or shared with the "include in finances" option), and not excluded from reports. Because the sparkline and the group total count the same accounts, the trend line tracks the balance figure shown for that group. ## Adding transactions To add a transaction: 1. Go to the **Transactions** page (left sidebar) 2. Click **New transaction** (top right; a round **+** button on mobile) 3. Choose the transaction type: * **Expense** → Spending money * **Income** → Receiving money * **Transfer** → Move money between accounts 4. Enter the details, then click **Add transaction** You'll see the transaction in your transaction history and the net worth chart will update accordingly. ![Filled-out expense form](https://github.com/user-attachments/assets/7c1d38d1-edb8-4d12-8b3e-bbef4836cc92) ## Uploading statements You can keep your bank's statements alongside an account and let Sure check balances against them. Open an account and upload PDF, CSV, or XLSX files in **Statements**, or go to **Settings → Statement Vault** to upload first and link later. Sure needs each statement's **period** to show which months are covered and to compare balances. It finds the period in this order: 1. **Inside the PDF** — when the statement includes its period as a date range (e.g. `01 Apr 2026 - 30 Apr 2026`) or as the dates next to the opening and closing balance (e.g. "Saldo iniziale al 01.07.2025"). Sure also reads opening and closing balances from a summary table or next to labels such as "Opening balance" and "Closing balance". Month names and labels are recognized in English, Italian, German, French, Spanish, Dutch, and Portuguese. 2. **Dates in the filename** — for everything else, e.g. `2026-04`, `2026-04-30`, or `Apr 2026`. 3. **Dates inside a CSV** — if the filename did not supply the period, Sure samples up to 250 date values from a recognized date column to fill missing period boundaries. Review the result, since a sample may not cover the whole statement. 4. **Manually** — open the statement and enter the period and balances yourself. If your bank names every file the same way, add the month to the filename before uploading, e.g. `Statement 2026-04.pdf`. ## Managing investment accounts If you're tracking investments in Sure, there are additional features to help you manage your portfolio accurately. ### Cost basis tracking Cost basis tracking helps you understand the original purchase price of your investments, which is essential for calculating returns and tax reporting. #### Cost basis sources Sure tracks cost basis from three sources: | Source | Description | | - | - | | **Manual** | User-entered values that you set directly | | **Calculated** | Computed from your buy trades and transaction history | | **Provider** | Imported from your financial institution (Plaid, SimpleFIN, etc.) | #### Priority hierarchy When multiple sources provide cost basis data, Sure uses this priority: **Manual > Calculated > Provider** This means: * Manual values always take precedence * Calculated values override provider data * Provider data is used when no other source is available #### Lock protection When you manually set a cost basis, Sure automatically locks it to prevent automatic updates from overwriting your value. This ensures your manual entries remain intact during account syncs. #### Setting cost basis manually You can set cost basis in two ways: **From the holdings list:** 1. Navigate to your investment account 2. Find the holding in your portfolio 3. Click the average cost value (a pencil icon appears on hover) 4. The editor shows an invoice-style line: a **Per share** field, your share quantity, and a **Total cost basis** field 5. Enter either the per-share price or the total — the other field updates automatically 6. Click **Save** If you already have a cost basis set, Sure shows a confirmation dialog titled "Overwrite cost basis?" with the current value, and a "Confirm" button in your language. Click **Confirm** to replace it. **From the holding drawer:** 1. Click on a holding to open its detail drawer 2. In the overview section, click the pencil icon next to "Average Cost" 3. Enter the per-share price or the total cost basis 4. Click **Save** After saving, you'll see: * A lock icon indicating the value is protected * A source label showing "(manual)" The editor stores and submits the per-share cost. The total field helps you calculate it but does not get saved directly. The per-share field displays between two and four decimal places as needed; the total displays two. Per-share values, including pasted sub-cent prices such as 0.0049, are preserved at up to four decimal places. A stored cost basis of zero — for example, shares received for free — shows as 0.00 in both fields rather than appearing empty. #### Unlocking cost basis If you want to allow automatic updates to recalculate your cost basis: 1. Open the holding drawer 2. Scroll to the **Settings** section 3. Find "Cost basis locked" 4. Click **Unlock** 5. Confirm the action in the dialog that appears After unlocking: * The lock icon disappears * Future syncs can update the cost basis * Calculated values (from trades) will replace the manual value ![Cost basis lock settings](https://github.com/user-attachments/assets/89d4c64f-7151-4702-b79f-1e22d47a2bee) ### Investment activity labels Activity labels help you classify and understand investment transactions. They appear as badges in your transaction list and can be used to organize and filter your investment activity. #### Available activity types Sure supports these investment activity labels: | Label | Description | | - | - | | **Buy** | Purchase of securities | | **Sell** | Sale of securities | | **Contribution** | Money added to the investment account | | **Withdrawal** | Money removed from the investment account | | **Dividend** | Dividend payments received | | **Interest** | Interest earned | | **Reinvestment** | Dividends or distributions reinvested | | **Sweep In** | Cash swept into the account | | **Sweep Out** | Cash swept out of the account | | **Fee** | Account or transaction fees | | **Exchange** | Currency or security exchanges | | **Transfer** | Transfers between accounts | | **Other** | Miscellaneous transactions | #### Setting activity labels You can set activity labels in two ways: **Manually for individual transactions:** 1. Open a transaction from an investment or crypto account 2. Scroll to the **Settings** section 3. Find "Activity type" 4. Select a label from the dropdown 5. The change saves automatically **Automatically with rules:** Create rules to automatically label transactions based on patterns: 1. Go to **Settings > Rules** 2. Create a new rule 3. Set conditions (e.g., "IF transaction name contains 'DIVIDEND'") 4. Add action: "Set investment activity label" 5. Choose the label (e.g., "Dividend") 6. Save the rule ![Investment activity rule example](https://github.com/user-attachments/assets/6660a3cc-af78-4199-8edc-18c198bbaad3) Example rules: * IF name contains "DIVIDEND" THEN set label to "Dividend" * IF name contains "INTEREST" THEN set label to "Interest" * IF name contains "FEE" THEN set label to "Fee" Rules apply automatically to new transactions and can be run on existing transactions. #### Viewing activity labels Activity labels appear as badges in: * Transaction lists * Transaction detail drawers * Account activity views They help you quickly identify the nature of each investment transaction without reading the full transaction name. ### Investment contributions in cashflow Investment contributions are now automatically visible in your cashflow and transaction history. When you add money to an investment account, Sure automatically: * **Categorizes the transaction**: Contributions are auto-categorized so they appear in your cashflow reports * **Labels the activity**: The transaction receives a "Contribution" activity label * **Tracks the movement**: The money flow is visible in your overall financial picture This ensures that money moved into investment accounts doesn't disappear from your financial tracking - you can see exactly where your money went and how it affects your overall cashflow. **How it works:** 1. When you transfer money to an investment account, the transaction is created 2. Sure automatically applies the "Contribution" activity label 3. The transaction is categorized appropriately for cashflow tracking 4. You can view these contributions in: * Your transaction list * Cashflow reports * Category breakdowns * Investment account activity This feature eliminates the "black hole" effect where investment contributions would seem to vanish from your financial overview. ## Dashboard The **Dashboard** gives you a live snapshot of your financial picture. Several widgets are available, and you can reorder and collapse them to suit your workflow. ### Chart time periods The period picker on net worth and account charts includes presets such as 1 month, 90 days, 1 year, 5 years, and **All**. The **All** period starts one month before the earliest Transaction or Trade entry across your family, giving a small margin before your first real activity. A single old valuation or opening balance no longer stretches the All range back years with a flat, empty line. If your family has only valuations and no Transactions or Trades, the All period uses the family’s oldest entry date when it is before today; a missing, today, or future start falls back to five years ago. ### Balance chart y-axis scaling Account balance charts scale the y-axis to keep real movements visible, whatever the size of your balance. The chart centres the view between the minimum and maximum balances for the period and adds padding around that range. Charts with value labels include extra space above and below the line. A 30-day view of a stable savings or pension account shows the real dips and gains rather than a near-flat line. Genuinely trivial movements — for example, a €50 change on a €100,000 balance — stay visually flat so the scale does not exaggerate noise. Zero is included when the series crosses zero or approaches it relative to its own scale; a small absolute balance alone does not force zero into view. Zooming in with drag-select reloads a narrower date range and applies the same scaling, so zoomed views reveal detail rather than flatten it further. ### Drag to select a date range on charts You can select a custom date range directly on the net worth chart or on any account's balance chart by clicking and dragging across it. Dragging left-to-right over the chart highlights the range and, when you release, navigates the page to that date range. The period picker updates to show the actual start and end dates of your selection. * Drag-select works on the dashboard net worth chart and on individual account balance charts. * The selection snaps to the nearest plotted data points, so the range always matches what the tooltip showed while you were dragging. * Drag-select is a mouse-only interaction. On touch devices, swiping the chart scrolls the page as usual. * After drag-selecting, the period picker shows the selected dates (for example, "Aug 15 – Sep 5") instead of a generic "Custom" label. Choosing a preset period from the picker clears the custom range. ### Customizing the dashboard You can show, hide, and reorder individual dashboard widgets to keep the dashboard focused on what matters to you. To enter Customize mode, click the layout icon in the top-right corner of the dashboard header (hover over it to see the "Customize" tooltip). While in Customize mode: * Each widget shows a hide button (eye icon). Click it to remove the widget from your dashboard. * A "Hidden widgets" card lists every widget you have hidden. Click **Add** next to any hidden widget to bring it back. Widgets with no data to show are not offered in the re-add list. * If you hide every widget, the dashboard shows an empty state with a link back to Customize mode. Click **Done** to leave Customize mode. Your view settings (date range, selected month, and similar filters) carry through so nothing resets when you hide or restore a widget. Hidden widgets also skip their data queries, so a hidden spending trend or money flow chart does not run in the background. Hidden widget preferences are per-user. Other members of your family see their own layout. #### Reordering widgets You can drag widgets into any order. Three input methods are supported: * **Mouse or trackpad**: Hover over a widget to reveal the drag handle (grip icon) in its header. Click and drag the widget to its new position. * **Touch (mobile)**: Press and hold a widget for approximately 800 ms until it lifts, then drag it into place. * **Keyboard**: Tab to a widget, then press **Enter** or **Space** to grab it. Use **Up** and **Down** to move it, then press **Enter**, **Space**, or **Escape** to release. Keys pressed on controls inside a widget (such as a button or input) are not intercepted, so normal interactions still work. The new order is per-user. Mouse and touch moves save when dropped; keyboard moves save when you release the widget. ### Spending trend chart The spending trend chart shows cumulative daily expenses for a selected month plotted against the previous month's curve, so you can see whether you are spending faster or slower than last month at the same point in the month. * Use the month picker to review any of the last 12 months. * The x-axis always spans the selected month's days. If the previous month was longer, its curve's extra days are folded into the final visible point, so the endpoint matches the full-month total shown in the header. * The current month's curve stops at today while the month is in progress. * The header totals and the signed delta compare the same number of elapsed days in both months, so the figure is always apples-to-apples. While the selected month is still in progress, the previous-month label names the day range being compared (for example, "Aug 1–8") rather than implying a full month. Once the selected month is complete, both months are compared in full. * The previous month's chart curve still draws the full month so you can see the complete reference shape. * On mobile, the x-axis shows tick labels for the selected month only and the header shows a compact date range (for example, "Sep 01 - 6, 2026") so the chart stays readable on narrow screens. * The chart uses the same transaction scoping as the Reports page: pending transactions, manually excluded transactions, tax-advantaged account activity, and investment portfolio movements (Transfers, Sweeps, Exchanges) are all excluded, so the totals always agree with what you see in Reports. ## Reports The **Reports** page gives you a breakdown of your income and expenses by category for any date range. ### Navigating periods with the keyboard On the Reports page, press the **Left Arrow** key to go to the previous period and the **Right Arrow** key to go to the next period. Right Arrow does nothing when you are already on the current period. The custom date range mode has no preset period to step through, so neither arrow key navigates when a custom range is active. Each chevron button shows a tooltip with its keyboard shortcut. The shortcuts are also announced to screen readers via `aria-keyshortcuts`. Keys pressed inside text fields on the page are not intercepted, so typing in a date input works normally. ### Drilling into categories Income and expense category rows in the breakdown are clickable. Clicking a category row takes you directly to your transaction list filtered to that category, so you can see exactly which transactions make up the total. Investment-only rows (such as **Other Investments**) are not clickable because those entries are trade records rather than regular transactions and cannot be shown in the transaction list. ## Next steps Now that you have your account set up: * Explore other account types that Sure offers * **Categorize** and **tag** transactions for better searching and reporting * Experiment with **budgets** to track your spending habits * Use **Import** (the Import button on the Transactions page, or **Settings > Imports**) to load historical transactions # API keys Source: https://docs.sure.am/guides/app-features/api-keys Create and manage API keys for programmatic access to your Sure data API keys let scripts, services, and third-party tools access your Sure data without going through the web UI. Each key is tied to your user account and carries a permission scope that controls what the caller can do. ## Creating an API key 1. Go to **Settings → API Keys**. 2. Click **New API Key**. 3. Enter a descriptive name — for example, "Budget export script" or "Portfolio tracker". 4. Select a permission scope (see [Scopes](#scopes) below). 5. Click **Save API Key**. Sure displays the full key value once immediately after creation. Copy it and store it securely. The raw value is not shown again — if you lose it, revoke the key and create a new one. ## Scopes Each API key has exactly one permission scope: | Scope | Label in UI | What it allows | | - | - | - | | `read` | Read Only | View accounts, transactions, balances, and related data | | `read_write` | Read/Write | View data and create or update transactions | Choose the narrowest scope that satisfies your use case. A read-only key cannot write data even if an endpoint would normally accept it. ## Using an API key Include the key in the `X-Api-Key` request header: ```bash theme={null} curl https://your-sure-instance.com/api/v1/transactions \ -H "X-Api-Key: your-key-here" ``` The API also accepts OAuth2 bearer tokens for registered OAuth clients. See the [API reference](/openapi.yaml) for endpoint details. ## Rate limits Rate limits apply to API key requests. Limits reset at the top of each hour. | Tier | Requests per hour | | - | - | | Standard | 100 | | Premium | 1,000 | | Enterprise | 10,000 | All keys start on the standard tier. The current tier is shown on the key's detail page in settings. When a key exceeds its limit, the API returns HTTP `429 Too Many Requests`. The response includes: ```json theme={null} { "error": "rate_limit_exceeded", "message": "Rate limit exceeded. Try again in 300 seconds.", "details": { "limit": 100, "current": 100, "reset_in_seconds": 300 } } ``` Every API response includes rate limit headers: | Header | Description | | - | - | | `X-RateLimit-Limit` | Maximum requests allowed in the current window | | `X-RateLimit-Remaining` | Requests remaining in the current window | | `X-RateLimit-Reset` | Seconds until the window resets | > [!NOTE] > > Rate limiting only applies to hosted instances. Self-hosted deployments have no rate limit applied to API key requests. ## Exporting to Google Sheets The Reports section lets you fetch an updating transaction breakdown into Google Sheets using the `=IMPORTDATA()` formula and your API key. 1. Go to **Reports** and set your desired date range. 2. Click the **Google Sheets** button to open the export instructions modal. 3. If you don't have an API key yet, click **Go to API keys** in the modal to create one with at least `read` scope. 4. Return to Reports and open the modal again. Copy its CSV URL and append `&api_key=YOUR_KEY` using your API key. The modal does not automatically insert a key from Settings. Wrap the completed URL in `IMPORTDATA`, for example: ``` =IMPORTDATA("https://your-sure-instance.com/reports/export_transactions.csv?api_key=YOUR_KEY&...") ``` 5. Paste the formula into any cell in Google Sheets. The export includes a monthly category breakdown for the selected period, with separate sections for income and expenses. The CSV URL contains your API key as a query parameter so Google Sheets can fetch it without a login session. > [!WARNING] > > Anyone with the CSV URL can read your transaction data. Treat the URL like a secret — do not share it or commit it to version control. If the URL is exposed, revoke the API key immediately and create a new one. ## Revoking a key To revoke a key, go to **Settings → API Keys**, find the key, and click **Revoke**. Revocation takes effect immediately. Any request using a revoked key receives an `unauthorized` response. Removing a user from a family also revokes all of their API keys. ## Security considerations * Store API keys as secrets, not in source code or version control. * Use a read-only key whenever write access is not required. * Revoke keys that are no longer in use. * If a key is exposed, revoke it immediately and create a replacement. # AI assistant sidebar Source: https://docs.sure.am/guides/app-features/assistant-sidebar Show, hide, and understand the AI assistant on desktop and mobile in Sure Sure includes an AI assistant on both desktop and mobile. On desktop it appears as a right-hand sidebar; on mobile it is accessible from the bottom navigation bar. ## Hide or show the AI sidebar on desktop On desktop, use the **panel-right** button in the top bar to toggle the right-hand AI sidebar. * Click it once to collapse the AI sidebar * Click it again to reopen the AI sidebar * Sure saves this preference to your account This is useful if you want more room for the main app content or simply do not want to use the assistant yet. ## Accessing the assistant on mobile On mobile, tap **Assistant** in the bottom navigation bar to open the AI chat interface. If AI has not been enabled for your account yet, tapping Assistant shows the consent screen rather than the chat composer. This lets you review and accept the AI terms before starting a conversation. Once you accept, the full chat interface becomes available. ## Chat history in the native mobile app The mobile app loads the full message history when you open a conversation. The chat API paginates messages in batches of 50, oldest first. The app fetches every page in sequence so long conversations render completely, with messages in chronological order and no duplicates. If one of the intermediate pages fails to load — for example due to a network interruption — the app keeps the pages it already fetched instead of discarding the chat. The current screen does not display a partial-history notice. You can reopen the conversation to retry loading the missing messages. ## When the sidebar is hidden by default Sure can also hide the AI sidebar by default for some people: * New `member` and `guest` users start with the AI sidebar hidden when AI is not available * `admin` users still see it by default so they can finish AI setup or troubleshooting If AI becomes available later, you can reopen the sidebar at any time with the same desktop toggle. ## Chat titles When you start a new chat without providing a custom title, Sure generates a default title using your current language and a timestamp. For example, "New chat 2026-08-31 14:30" in English, "Neuer Chat 2026-08-31 14:30" in German, or "Novo chat 2026-08-31 14:30" in Brazilian Portuguese. You can rename any chat at any time using the edit icon next to its title. ## Localized chat interface The full chat interface is localized to match your language setting. This includes the AI greeting, suggested questions, chat navigation labels, consent dialog, and error messages. Brazilian Portuguese (pt-BR) is fully supported. Set your language under Settings → Preferences to switch the chat interface to your preferred language. ## Error messages from the AI provider When the AI provider returns an error, Sure shows a localized message describing the error category, such as a rate limit, temporary service problem, or configuration issue. When chat debug mode is enabled, a technical-details section can also show the stored provider error message. Raw provider details are not shown in the normal chat error message, and may be unavailable for some failures. ## Related settings * For AI provider setup, see [LLM support](/llm-support) * For general app settings, see [Settings](/guides/app-features/settings) # Budgets Source: https://docs.sure.am/guides/app-features/budgets Track your spending with monthly budgets and stay on top of your finances. # Budgets Budgets help you set spending limits for different categories and track how well you're sticking to them throughout the month. ## How Budgets Work When you create a budget, you assign a spending limit to a category. As you spend money in that category, Sure tracks your progress and shows you: * **Amount spent** so far this month * **Amount remaining** in your budget * **Status indicators** showing if you're on track, near your limit, or over budget ### Planning ahead You can create budgets for future months, up to 2 years in advance. This lets you plan your spending ahead of time and set category limits before the month begins. Navigate forward using the month selector to set up upcoming budgets. Month names in the picker are displayed in your account's configured language. ![Screenshot2026 01 21at09 53 09](https://mintcdn.com/sure-917046f5/pSSfgRNCiCb8T1Fu/images/Screenshot2026-01-21at09.53.09.png?fit=max\&auto=format\&n=pSSfgRNCiCb8T1Fu\&q=85\&s=66fa9bb49faa0d53002b4819a48ac4cf) ## Personal budgets > [!NOTE] > > Personal budgets are a preview feature. Enable them in **Settings → Family** to try them out. By default, all family members share a single household budget. When personal budgets are enabled, each family member gets their own independent budget for each period instead of drawing from the shared family-wide budget. ### Enabling personal budgets A family admin can turn on personal budgets in **Settings → Family**. Once enabled, each member's budget is tracked separately and their spending only counts against their own budget, not the household total. ### Household and personal budgets together You can run both a household budget and personal budgets at the same time. The household budget covers shared family expenses, while each member's personal budget covers their individual spending. To opt out of the household budget and use personal budgets only, disable **Household budget** in **Settings → Family**. ### Budget ownership switcher On the budget page and the Plan hub card, a switcher lets you view: * **Household** — the shared family budget * **Mine** — your personal budget * **Shared with me** — personal budgets another member has shared with you ### Sharing a personal budget You can grant another family member access to your personal budget: * **Read-only** — they can view your budget but not edit it * **Read-write** — they can view and edit your budget Manage sharing in **Settings → Preferences → Budget sharing**. Members with read-only access can see your budget but cannot change category limits or amounts. ### Personal budget isolation Each member's personal budget is fully isolated: * Actual spending reflects only the budget owner's own accounts * A new period's budget is seeded from that member's previous period, not another member's * Deleting a family member also removes their personal budgets ## Setting Up Category Budgets Each category can have its own budget. For example, you might set: * Food & Dining: \$500/month * Entertainment: \$200/month * Transportation: \$300/month Sure shows helpful daily suggestions like "\$29.91 suggested per day for 11 remaining days" to help you pace your spending. When editing a subcategory's budget, you'll see "Shared" as the placeholder text. Leave the field empty or set it to \$0 to share the parent category's budget. Hover over the field to see the tooltip: "Leave empty to share parent's budget". ## Budget rollover By default, a category's budget resets to zero at the start of each month. Rollover lets you carry any unspent balance forward so it accumulates over time — useful for irregular expenses like an annual insurance payment, a holiday fund, or car servicing. ### Enabling rollover for a category Open the budget and edit any category. Toggle **Rollover** on to enable it. Once enabled, any surplus left at the end of the month carries into the next month's envelope for that category. The setting persists: you don't have to re-enable it each month. Turning it off for a specific month stops the carry in both directions for that month — the category neither receives a carry from the previous month nor sends one to the next. ### How the carry is calculated ``` carried_in = rollover_enabled ? max(0, budgeted_last_month + carried_in_last_month - spent_last_month) : 0 ``` Only a surplus carries — an overspend never reduces next month's envelope. The carry is shown alongside the monthly allocation on the category card so you can see both figures. ### What rollover affects | Field | Effect | | - | - | | `available_to_spend` | Includes the carried amount. For a parent category, also includes rollover held by ring-fenced subcategories. | | `display_rolled_over_amount` | For a parent category, shows the sum of its own rollover plus any rollover held by ring-fenced subcategories, so the displayed budget, rollover, spending, and availability stay consistent. | | `percent_of_budget_spent` | Counts the carried amount as part of the envelope | | `display_budgeted_spending` | Shows the current month's allocation only, not the carry | The top-of-page budget totals (`budgeted_spending`, `allocated_spending`, `available_to_allocate`) are not affected by the carry. ### Rollover and personal budgets Each budget owner's rollover chain is independent. A household budget's carry is shared across all family members and is not influenced by who views the page. A personal budget's carry follows only that member's own accounts. ### Currency changes If a category's currency changes, the rollover chain stops at the point of the change. The carry will not cross a currency boundary. ## Subcategories and Shared Budgets You can organize your spending further with subcategories. For example, "Food & Dining" might include: * Coffee & Takeout * Groceries * Restaurants ![Screenshot2026 01 21at09 54 22 2](https://mintcdn.com/sure-917046f5/pSSfgRNCiCb8T1Fu/images/Screenshot2026-01-21at09.54.22-2.png?fit=max\&auto=format\&n=pSSfgRNCiCb8T1Fu\&q=85\&s=20ed37a6f4ead16e3560550d1ca994b1) ### Individual budgets Give each subcategory its own limit. This works well when you want strict control over specific types of spending. ### Shared budgets Leave a subcategory's budget empty to share the parent category's budget. This is great when you want flexibility across related expenses. **Example:** Set "Food & Dining" to \$500, but leave the subcategories without individual limits. Now all your food spending draws from the same \$500 pool, whether you're buying groceries or eating out. When a subcategory shares its parent's budget, you'll see a "(shared)" label next to the budget amount, making it clear which subcategories are drawing from the shared pool. ### Mixed approach Combine both methods. Set a fixed budget for some subcategories while others share the remaining amount. **Example:** * Food & Dining: \$500 total * Restaurants: \$100 (fixed limit) * Groceries and Coffee share the remaining \$400 When you set an individual budget for a subcategory, that amount is "ring-fenced" from the parent budget. Only that subcategory can use it, and it won't be available to other subcategories sharing the parent's budget. **How it works:** * **Restaurants** has \$100 remaining (\$100 budget - \$0 spent) * **Groceries** and **Coffee** share \$350 remaining. The shared pool is the parent's allocation (\$500) minus ring-fenced siblings' allocations (\$100) = \$400, minus shared spending (\$50) = \$350. * The parent **Food & Dining** shows the total remaining across all subcategories, including any rollover carried by ring-fenced subcategories ### Parent auto-aggregation When you edit a subcategory's budget, the parent category's budget automatically updates to reflect the change. You don't need to manually adjust the parent — Sure keeps it in sync for you. **How it works:** * When you increase a subcategory's budget, the parent's budget increases by the same amount. * When you decrease a subcategory's budget, the parent's budget decreases accordingly. * If the parent had extra budget beyond the sum of its subcategories (a "reserve"), that reserve is preserved during the update. * The parent's budget never drops below the combined total of its subcategories. **Example:** * Food & Dining starts at \$500 with Restaurants at \$100 and Groceries at \$150 (\$250 reserve in the shared pool) * You increase Groceries from \$150 to \$200 * Food & Dining automatically updates to \$550, preserving the \$250 reserve ## Bills and budget reservations On initialized category cards showing budget details, Sure displays a reservation when qualifying unpaid bill occurrences have a positive remaining amount within the budget period. The card displays a line like **"\$X reserved by bills"**. This figure is read-only information — it does not reduce the available amount shown for the category. It tells you how much of your remaining budget is already spoken for, so you can plan accordingly rather than spending money that is already committed. If a bill is in a foreign currency and no exchange rate is available, Sure cannot convert it to your budget currency and will instead show a warning like **"1 bill is not reserved, no exchange rate available"**. The unconvertible bill is counted and reported rather than silently excluded, so you always know when a reservation could not be calculated. ### What counts as a reservation Sure reserves the remaining unpaid amounts of open occurrences that are: * Part of an active, categorized expense series * From a series with no destination account * Due within the budget period Confirmed payment allocations reduce the reserved amount. Paid, skipped, missed, income, and transfer occurrences are excluded. ## Status Indicators Sure uses color-coded badges to show your budget status at a glance: * **On Track** (green) - You're within budget and pacing well * **Near Limit** (yellow) - Getting close to your limit * **Over Budget** (red) - You've exceeded your budget ## Tax-advantaged accounts and budgets Sure automatically excludes activity from tax-advantaged investment accounts when calculating budget spending. This ensures your budgets accurately reflect your day-to-day spending without being skewed by investment contributions or withdrawals. **Excluded account types:** * 401(k) accounts * IRA accounts (Traditional and Roth) * 403(b) accounts * Other tax-advantaged retirement accounts Transactions from these accounts won't count toward your budget limits, keeping your budget focused on regular income and expenses. ## Creating a budget without category allocations You can save a budget that only sets an overall monthly amount without splitting it across categories. The budget setup wizard no longer requires any category allocation before you can confirm. Any unallocated amount is treated as uncategorized spending and appears in the donut chart on the budget page. You can always add category allocations later by editing the budget. ## Cash on hand panel > [!NOTE] > > This panel is a preview feature. Enable preview features in **Settings → Preferences** to see it. Below the plan on the budget page, a separate **Cash on hand** panel shows what you actually have in cash — a real-money view that complements the forecast above it. The plan answers "what did I plan to spend?" and uses numbers you typed (`budgeted_spending`, `expected_income`). The Cash on hand panel answers "what do I actually have?" and reads live account balances. The panel shows three figures. **Really free** is the panel's primary answer and appears highlighted at the bottom: | Figure | What it means | | - | - | | **Available in cash** | Sum of all your cash account balances (checking, savings, and similar depository accounts), converted to your budget currency | | **Already earmarked for goals** | The portion of those same cash accounts already claimed by active goals | | **Really free** | Available minus earmarked (floored at zero) — shown highlighted as the panel's answer | The earmarked amount only covers cash accounts, not investment accounts. Goals can be backed by brokerage or investment accounts, but those balances are never counted in "available" and are therefore not subtracted from it. In a multi-currency household, each account balance is converted to the budget currency before the figures are summed. A link to the Goals page appears in the panel so you can inspect what is earmarked and why. ## Tips for Effective Budgeting 1. **Start simple** - Begin with just a few major categories before adding detail 2. **Review monthly** - Check your budgets at the end of each month and adjust as needed 3. **Use shared budgets** for categories where you want flexibility between subcategories 4. **Use individual limits** when you need strict control over specific spending # CSV imports Source: https://docs.sure.am/guides/app-features/csv-imports Import your financial data from CSV files into Sure # CSV imports Sure supports importing financial data from CSV files, making it easy to migrate from other financial apps or add bulk data. ## Importing older history A historical export can fill gaps left by a bank connection. File imports use the dates in the file rather than a bank-feed lookback window. See [Transaction history and import limits](/providers/transaction-history) to check your source first. * Export only the missing date range where possible, and check for overlapping transactions already in Sure. * Choose the importer matching the file format, verify the destination account and currency, and review the preview before publishing. * Do not assume that file imports automatically deduplicate transactions already received from a provider. > [!NOTE] > > The general transaction-import account mapping dropdown currently lists manual accounts only. Although the backend supports an account-specific import targeting a linked account, that path has not been browser-verified for this guide. These instructions do not promise that an existing linked account will appear in the dropdown. Do not create a duplicate account or unlink an existing connection merely to bypass this limitation. ## Supported import types You can import the following types of data via CSV: * **Accounts**: Create multiple accounts with opening balances * **Actual Budget transactions**: Import transaction history exported from Actual Budget * **Mint transactions**: Import transaction history exported from Mint * **Merchants**: Create merchant records in bulk * **Transactions**: Import transaction history * **Trades**: Import investment trades * **Categories**: Set up your category structure * **Rules**: Import transaction rules ## Importing accounts Account imports let you quickly set up multiple accounts with their opening balances. ### CSV format Your CSV file should include these columns: | Column | Required | Description | Example | | - | - | - | - | | Account type | Yes | Type of account | Checking, Savings, Credit Card | | Name | Yes | Account name | Main Checking Account | | Balance | Yes | Opening balance | 1000.00 | | Currency | No | Currency code (defaults to family currency) | USD | | Balance Date | No | Date for the opening balance | 01/01/2024 | ### Example CSV ```csv theme={null} Account type,Name,Balance,Currency,Balance Date Checking,Main Checking Account,1000.00,USD,01/01/2024 Savings,Emergency Fund,5000.00,USD,01/15/2024 Credit Card,Rewards Card,-500.00,USD,02/01/2024 ``` ### Balance date column The optional **Balance Date** column lets you specify when the opening balance should be recorded. This is useful when: * Migrating historical data from another app * Setting up accounts with balances from a specific date * Maintaining accurate historical balance tracking If you don't provide a balance date, Sure will use the current date for the opening balance. > [!NOTE] > > The date format should match your import settings. Common formats include MM/DD/YYYY, DD/MM/YYYY, YYYY-MM-DD, and DD/MM/YY. The DD/MM/YY format (two-digit year) is available for CSV imports only. Two-digit years are interpreted as 1969–2068, so verify the parsed preview before confirming the import. ### Supported account types * Checking * Savings * Credit Card * Investment * Loan * Property * Vehicle * Crypto * Other Asset * Other Liability ## Importing transactions Transaction imports let you add historical transaction data to your accounts. ### CSV format Your CSV file should include these columns: | Column | Required | Description | | - | - | - | | Date | Yes | Transaction date | | Amount | Yes | Transaction amount | | Name | Yes | Transaction description | | Account | Yes | Account name | | Category | No | Category name | | Notes | No | Additional notes | ### Example CSV ```csv theme={null} Date,Amount,Name,Account,Category,Notes 01/15/2024,-45.50,Grocery Store,Main Checking,Groceries,Weekly shopping 01/16/2024,-12.00,Coffee Shop,Main Checking,Dining Out,Morning coffee 01/20/2024,2500.00,Paycheck,Main Checking,Income,Bi-weekly salary ``` ## Importing merchants Merchant imports create new merchant records in bulk. Sure creates every row as a family-owned merchant, so the `color` column applies and a hex value is accepted. Provider-detected merchants (created automatically during bank sync or AI enrichment) are managed by Sure and do not support a color. ### CSV format | Column | Required | Description | | - | - | - | | name | Yes | Merchant name | | color | No | Hex color code (e.g. `#e99537`). A random color is assigned if omitted. | | website\_url | No | Merchant website URL | ### Example CSV ```csv theme={null} name,color,website_url Coffee Shop,#e99537,https://coffeeshop.com Pizza Palace,#4da568,https://pizzapalace.com Bookstore,, ``` ### How duplicate names are handled If a merchant with the same name already exists in your family, that row is skipped. The import reports the count of created merchants and the count of skipped rows separately. ## Permissions required to publish or revert Imports are family-scoped, but imports attached to account statements also require permission to view the statement. Publishing an import (writing transactions into accounts) and reverting a published import (deleting those entries) each require **write access** — owner or full\_control — to every pre-existing account the import targets. Accounts created by the import itself are excluded from this account-access check. Statement imports additionally require permission to manage the statement. This covers: * The primary destination account selected during mapping * Any accounts referenced via column mappings * Accounts that already received entries from a previous publish of the same import * For QIF files with embedded account names: any existing Sure accounts whose names match those in the file If your access to an account has been downgraded to read-only since the import was configured, the publish or revert step will fail with a permissions error. Ask the account owner to grant you write access, or have them complete the action themselves. If a revert fails, the import's status changes to **Revert failed**. A **Try again** button appears on the import detail page — click it to retry the revert without needing to navigate back to the imports list. ## Import process The import wizard shows a step indicator at the top of the page. Step labels display in your configured language (set under **Settings → Preferences → Language**). On mobile, the indicator shows a "Step X of Y" progress count instead. ### Template suggestions When you reach the Configure step after uploading a CSV, Sure checks whether you have a previous completed import of the same type for the same account. If one exists, a prompt appears offering to apply that import's column mapping configuration to the current one. The prompt text, button labels, and sample data caption are displayed in your configured language. * Select **Apply template** to copy the column assignments, date format, signage convention, and number format from the previous import. * Select **Manually configure** to dismiss the suggestion and set up the columns yourself. If no previous import is found, the Configure step opens directly in manual mode without showing a suggestion. The steps vary by import type: | Import type | Steps | | - | - | | CSV (transactions, trades, accounts, etc.) | Upload → Configure → Clean → Map → Confirm | | QIF | Upload → Select → Clean → Map → Confirm | | PDF statement | Upload → Configure → Clean → Confirm | | Sure export (NDJSON) | Upload → Confirm | The Map step only appears when your data requires column or account mapping; it is skipped automatically when no mapping is needed. 1. **Navigate to imports**: Go to Settings → Imports or use the import button in the app 2. **Upload**: Drag and drop your file or click to browse 3. **Configure**: Choose the date format, number format, and column assignments 4. **Select** (QIF only): Review the detected date format and choose which categories and tags from your QIF file to import 5. **Clean**: Fix any invalid rows flagged in the table 6. **Map** (when needed): Assign imported accounts, categories, or tags to existing ones in Sure 7. **Confirm**: Review the import summary and publish ## QIF imports QIF (Quicken Interchange Format) files are exported from Quicken and similar personal finance apps. Sure parses the QIF format directly — no column mapping is needed. ### Supported QIF account types | QIF type | Sure account type | | - | - | | Bank | Depository | | Cash | Depository | | CCard | Credit Card | | Invst | Investment | | Oth A | Other Asset | | Oth L | Other Liability | ### Split transactions QIF files can contain split transactions — single entries that are broken into multiple line items with individual categories, amounts, and notes. When your file contains splits, Sure imports each split line as a child entry under the parent transaction, preserving the original breakdown. Split categories are shown separately on the Select step so you can choose which ones to include. If the split amounts do not sum to the parent total, Sure skips the split lines and imports the transaction as a single entry. ### Multi-account QIF files A QIF file exported from Quicken can contain multiple accounts in a single file (identified by `!Account` sections). When Sure detects account metadata in the file: * Each account in the QIF file is matched to an existing Sure account by name, or created automatically if no match is found. * Opening balances declared in the file are applied to the corresponding accounts. * You do not need to assign a single target account before publishing — Sure routes each transaction to the correct account automatically. When the QIF file does not contain account metadata, you must select a target account before publishing, as with a standard single-account import. ### Date format detection Sure automatically detects the date format used in your QIF file by sampling the D-fields and selecting the best match. You can review and change the detected format on the Select step before proceeding. The default fallback is MM/DD/YYYY (US convention). QIF files support several date styles including: * `MM/DD/YYYY` and `MM/DD/YY` (Quicken US) * `DD.MM.YYYY` (European dot-separated) * `DD-MM-YYYY` (dash-separated) * `DD MMM YYYY` (e.g. `26 Jan 2026`, Amex-style) ### Investment transactions QIF `!Type:Invst` sections are imported as investment activity. Trade actions (Buy, Sell, Cover, ShtSell, ReinvDiv) create Trade records. Non-trade actions (Div, IntInc, CGLong, CGShort, XIn, XOut, MiscInc, MiscExp) create Transaction records with appropriate labels. Securities are resolved by matching the QIF security name to the ticker defined in the file's `!Type:Security` sections. ## Importing rules Rule imports let you create or update transaction rules in bulk from a CSV file. ### CSV format | Column | Required | Description | | - | - | - | | name | No | Rule name. If a rule with this name already exists, it is updated in place. Rows without a name always create a new rule. | | resource\_type\* | Yes | Must be `transaction` | | active | No | `true` or `false` (defaults to `false`) | | effective\_date | No | Only apply the rule to transactions on or after this date (YYYY-MM-DD) | | conditions\* | Yes | JSON array of condition objects | | actions\* | Yes | JSON array of action objects | ### Condition types Each entry in the `conditions` array is a JSON object with `condition_type`, `operator`, and `value` fields. | `condition_type` | Description | Value | | - | - | - | | `transaction_name` | Matches on the transaction name | Plain text | | `transaction_amount` | Matches on the amount | Numeric | | `transaction_type` | Matches on transaction type (income, expense, transfer) | Type string | | `transaction_merchant` | Matches on merchant | Merchant name — resolved to an ID automatically | | `transaction_category` | Matches on category | Category name — resolved to an ID automatically | | `transaction_tag` | Matches on tag | Tag name — resolved to an ID automatically | | `transaction_details` | Matches on provider metadata fields | Plain text | | `transaction_notes` | Matches on transaction notes | Plain text | | `transaction_account` | Matches on the account | Account UUID — account names are not resolved | The `operator` field must be supported by the condition type: | Condition types | Supported operators | | - | - | | `transaction_name`, `transaction_notes` | `like`, `not_like`, `starts_with`, `ends_with`, `matches_regex`, `=`, `!=`, `is_null`, `is_not_null` | | `transaction_amount` | `>`, `>=`, `<`, `<=`, `=`, `!=` | | `transaction_merchant`, `transaction_category`, `transaction_tag`, `transaction_account` | `=`, `!=`, `is_null`, `is_not_null` | | `transaction_type` | `=` (with `income`, `expense`, or `transfer`) | | `transaction_details` | `like`, `=`, `is_null` | For text conditions, `like` means contains, `not_like` means does not contain, and `starts_with` and `ends_with` match a prefix or suffix. The `matches_regex` operator runs a case-insensitive PostgreSQL regular expression against the stored field value; patterns are capped at 200 characters and back-references (`\\1` through `\\9`) are not allowed. `is_null` and `is_not_null` do not require a value. `transaction_details` searches string and number values in provider metadata. Both `like` and `=` use contains matching there: `like` is case-insensitive and `=` is case-sensitive. It does not support the extended text operators. When a `transaction_category`, `transaction_merchant`, or `transaction_tag` condition references a name that does not exist yet, Sure creates the category, merchant, or tag automatically. The same name used in multiple rows in the same file reuses the record created for the first row. ### Action types Each entry in the `actions` array is a JSON object with `action_type` and an optional `value` field. | `action_type` | Description | Value | | - | - | - | | `set_transaction_category` | Assign a category | Category name — resolved to an ID automatically | | `set_transaction_merchant` | Assign a merchant | Merchant name — resolved to an ID automatically | | `set_transaction_tags` | Assign one or more tags | Comma-separated tag names — each resolved to an ID automatically | | `set_transaction_name` | Set the transaction name | Plain text | | `auto_categorize` | Auto-categorize using AI | No value needed | ### Example CSV ```csv theme={null} name,resource_type*,active,effective_date,conditions*,actions* Categorize groceries,transaction,true,2024-01-01,"[{""condition_type"":""transaction_name"",""operator"":""like"",""value"":""grocery""}]","[{""action_type"":""set_transaction_category"",""value"":""Groceries""}]" Tag coffee runs,transaction,true,,"[{""condition_type"":""transaction_name"",""operator"":""like"",""value"":""coffee""}]","[{""action_type"":""set_transaction_tags"",""value"":""Coffee,Personal""}]" ``` ## Tips for successful imports 1. **Use templates**: Download CSV templates from the import screen for the correct format 2. **Check encoding**: Ensure your CSV file is UTF-8 encoded 3. **Validate dates**: Make sure dates match your selected format 4. **Test with small files**: Try importing a few rows first to verify the format 5. **Clean your data**: Remove any extra columns or formatting before importing ## Troubleshooting ### File upload fails on iPhone or iPad On iOS (Safari and Chrome for iOS), tapping the file picker to upload a Sure export (NDJSON) or a bank statement (PDF) could fail silently or return an error page. The upload appeared to start but never reached the server. The affected Sure upload forms used native form submission. They now submit through Turbo using `requestSubmit()`, allowing Turbo to send the selected file in its fetch request. If you are on an older version and see a "We didn't receive your file. Please try uploading it again." alert on iOS, upgrade to the latest release and retry the upload. ### Import fails with date errors Check that your date format matches the setting you selected during import. The Balance Date column in account imports must use the same format as other date fields. Sure supports the following date formats for CSV imports: | Format | Example | | - | - | | MM/DD/YYYY | 01/15/2024 | | DD/MM/YYYY | 15/01/2024 | | YYYY-MM-DD | 2024-01-15 | | DD/MM/YY | 15/01/24 | > [!NOTE] > > The `DD/MM/YY` format is available for CSV imports only. Because two-digit years are ambiguous (Sure interprets them as 1969–2068), this format is not available as a global date preference. Always verify the parsed preview against your CSV data before confirming the import. ### Accounts not found When importing transactions, ensure the account names in your CSV exactly match existing account names in Sure. ### Duplicate transactions Sure will import all rows from your CSV. Review your data before importing to avoid duplicates. ### Rule import with tag conditions produces broken rules If you imported a rules CSV with `transaction_tag` conditions on an older version of Sure (before the fix in [#3419](https://github.com/we-promise/sure/pull/3419)), the tag name was stored as-is instead of being resolved to the tag's ID. Rules with this problem match no transactions for the tag condition. To fix affected rules, delete and re-import them, or edit each rule manually in **Settings → Rules** to remove and re-add the tag condition. ### Sure NDJSON import fails with a null rule name Rules exported from Sure may have a `null` name field, which is valid. If a full `all.ndjson` export fails preflight with an error about a missing rule name, ensure you are using a current version of Sure — older versions incorrectly required the name field to be present. ### Sure NDJSON import fails with a missing reference on rejected transfers If your export contains rejected transfers whose original transactions were later deleted, Sure will skip those orphaned rows and report them as warnings rather than blocking the import. Check the preflight warnings in the import response for details on any skipped records. Preflight missing-reference error and warning messages are displayed in your configured interface language (set under **Settings → Preferences → Language**). ### Sure NDJSON import fails with a duplicate category or tag name Category and tag names must be unique within a family. If your NDJSON file contains two or more Category (or Tag) records with the same name, preflight will reject the import with a `duplicate_taxonomy_name` error. Remove or rename the duplicate entries in your export file before retrying. If the duplicate names already exist in your Sure database from before this constraint was enforced, Sure automatically merges them during the upgrade migration. The oldest record (by creation date) is kept, and all references — transactions, rules, budget lines, and import mappings — are updated to point to the surviving record. ### Sure NDJSON import on a fresh family shows warnings about existing categories, tags, or merchants When you import a Sure export into a fresh family, Sure seeds that family with a default set of categories during onboarding. If your export contains categories, tags, or merchants whose names match those defaults, Sure treats the collision as a warning rather than an error: the existing record is reused and updated with the imported data instead of creating a duplicate. The import proceeds normally. The confirm screen lists how many records were reused so you can verify the outcome. No action is needed. If you see these warnings and the import finishes without errors, your data imported correctly. ### Sure NDJSON import shows a warning about merchant details differing Provider-assigned merchants (including legacy AI-created provider records) are shared across all families on a Sure instance. When an imported `ProviderMerchant` record already exists on the instance with different details — for example, a different website URL or name — Sure keeps the existing record as-is and surfaces the differences on the confirm screen as a warning. This is expected behavior. The import still proceeds; affected transactions reference the existing shared merchant. No action is required unless you want to update the merchant's details, which you can do manually from **Settings → Merchants** after the import completes. If the import file contains a `ProviderMerchant` that does not exist on the instance at all, Sure creates a family-owned merchant (a `FamilyMerchant`) for the importing family instead of registering a new shared provider merchant. The transactions in the import are linked to that family-owned merchant, and the import proceeds normally. ### Sure NDJSON import reports missing merchants as warnings instead of errors Exports taken before provider-merchant support was added (before version containing [#3113](https://github.com/we-promise/sure/pull/3113)) did not include `ProviderMerchant` rows. When you import such a file, Sure cannot resolve the merchant references. The import now treats unresolvable `merchant_id` values as warnings rather than blocking errors — the affected transactions and recurring transactions import without a merchant assigned. The confirm screen shows the count of affected records. If you import from a newer export and still see this warning, it may mean some merchant records were not exported. Re-export from the source instance and retry the import. ### Unnamed recurring transactions are skipped when their merchant is missing A recurring transaction series requires either a name or a merchant to import. If a series has neither — because its merchant could not be resolved and it has no name — Sure skips it and reports the count on the confirm screen. Named series without a merchant import normally. Automatically detected recurring transactions that are skipped are rebuilt after the import completes when Sure syncs the family's accounts. ## Limits * **Account imports**: Maximum 50 accounts per import * **Transactions**: Maximum 10,000 rows per import * **Actual Budget imports**: Maximum 10,000 rows per import * **Mint imports**: Maximum 10,000 rows per import * **Trade imports**: Maximum 10,000 rows per import * **Category imports**: Maximum 10,000 rows per import * **Rule imports**: Maximum 10,000 rows per import * **Merchant imports**: Maximum 10,000 rows per import * **CSV file size**: Maximum 10 MB per import > [!NOTE] > > If a CSV import fails during upload or publish, check both the row count and the file size. An import can be under the row limit and still fail if the CSV file is larger than 10 MB. ## Getting help If you encounter issues with CSV imports: * Check the [troubleshooting guide](/guides/knowledge-base/troubleshooting) * Ask in the [Discord](https://discord.gg/36ZGBsxYEK) * Open an [issue](https://github.com/we-promise/sure/issues/new/choose) # Family Sharing Source: https://docs.sure.am/guides/app-features/family-sharing Share accounts and collaborate on finances with family members # Family Sharing Family sharing allows you to share specific accounts with other members of your family, enabling collaborative financial management while maintaining privacy and control over your data. ## How Family Sharing Works Each Sure family can have multiple members with different permission levels. You can selectively share accounts with specific family members, giving them View only, Can annotate, or Full control access. ### Permission Levels When sharing an account you assign one of three permission levels to each family member. | Permission | Description | Can view | Can categorize, tag, and add notes | Can edit and delete transactions | | - | - | - | - | - | | **Full control** | Can view, edit, and manage transactions | ✅ | ✅ | ✅ | | **Can annotate** | Can categorize, tag, and add notes | ✅ | ✅ | ❌ | | **View only** | Read-only access | ✅ | ❌ | ❌ | The account owner always retains full control and cannot be removed through the sharing settings. In bulk edit and the categorize flow, **Full control** (`full_control`) allows changes to all supported fields. **Can annotate** (`read_write`) allows category, merchant, tags, and notes, while **View only** (`read_only`) accounts are skipped. Can annotate does not permit name, date, or amount changes. ## Sharing an Account To share an account with family members: 1. Navigate to the account you want to share 2. Click the **Share** button or access sharing settings 3. Select the family members you want to share with 4. Choose their permission level (View only, Can annotate, or Full control) 5. Click **Save** The account will now appear in the selected family members' account lists with the appropriate access level. ## What Gets Shared When you share an account, the following information is accessible to family members: * **Account balance** and balance history * **Transactions** and transaction details * **Holdings** (for investment accounts) * **Trades** (for investment accounts) * **Account settings** and preferences ## Privacy and Scoping Family sharing respects privacy boundaries: * **Scoped views**: Each family member only sees accounts shared with them * **Reports**: Financial reports are scoped to only include accounts the user has access to * **Budgets**: The household budget includes shared accounts. Personal budgets (when enabled) are scoped to each member's own accounts independently. * **Totals**: Net worth and other totals reflect only accessible accounts * **Sparklines**: Sidebar group sparklines count the same accounts as the group total: accounts accessible to the current user, included in their finances, and not excluded from reports. Each member sees a sparkline that matches the balance figure shown for that group. * **Providers**: Third-party provider connections are scoped per family. When a sync completes, the browser refreshes through its own authenticated request, so account visibility is checked for that member. Automatic refresh can be deferred while a form or dialog is in use; provider-card HTML is not broadcast to the whole family. * **Provider cards**: Connection cards on the accounts page show a member only accounts they own or that have been shared with them. If a connection has three accounts and a member has access to only one, that card displays only the one shared account. Admins see all accounts on every connection. * **Provider sync summary**: When a member can see only some accounts on a connection, the sync summary shows counts rather than account names and details for the other accounts on that connection. * **Manual accounts after provider setup**: When provider setup or linking refreshes the Accounts page, its manual-account list includes only accounts the current user owns or that have been shared with them. This also applies to admins. * **Merchants**: Merchant data is shared across the family for consistency * **Personal budgets**: When personal budgets are enabled, each member's actual spending is scoped to their own accounts only * **Insights**: The shared insights feed only shows insights about accounts every active family member can access. Access is checked again when the feed is read, so revoking a required share hides the related insight on the next read. * **Sync updates**: After an account sync, page refreshes use each browser’s own authenticated request. Automatic refresh can wait while the user is interacting with a form or dialog. Account names and balances are not pushed to family members who do not have access to that account. ## Managing Shared Accounts ### Viewing Shared Accounts Shared accounts appear in your account list with an indicator showing they're shared. You can filter your account list to show: * Only your accounts * Only shared accounts * All accounts ### Editing Shared Accounts If you have **Full control** permission on a shared account, you can: * Add, edit, and delete transactions * Update account settings * Record trades (for investment accounts) * Categorize, tag, and add notes to transactions If you have **Can annotate** permission, you can categorize, tag, and add notes to transactions but cannot add or delete transactions or change their financial fields. If you have **View only** permission, you can see the account data but cannot make any changes. ### Imports and account write access Publishing or reverting an import writes to (or removes entries from) its target accounts. Sure requires **write access** — owner or full\_control — to every pre-existing account the import targets, including accounts referenced via column mappings and any accounts that already received entries from a previous publish of the same import. Accounts created by the import itself are excluded from this check. Statement imports also require permission to view and manage the associated statement. A family member with read-only access to an account cannot publish or revert an import that targets it, even if they created the import. If a member's access to an account is downgraded after an import is configured, someone with write access to every pre-existing target account must complete the publish or revert. > [!NOTE] > > When recording a deposit or withdrawal on an investment account, Sure books the transaction on a second account (the transfer account). You must have Full control on that transfer account as well. Accounts shared with you as View only or Can annotate do not appear in the transfer account picker. ### Removing Access Account owners can remove sharing access at any time: 1. Open the shared account 2. Go to sharing settings 3. Remove the family member or change their permission level 4. Click **Save** The account will immediately disappear from that family member's view. ## Family Roles ### Admin Role Family admins have additional privileges: * Manage family members * Configure family-wide settings * Manage all third-party provider connections * Access all family accounts (if shared) ### Member Role Members can connect and manage their own Plaid bank connections. This is the only provider integration a non-admin can manage — all other providers require admin access. A member can re-authenticate, sync, and delete the Plaid connections they created, but cannot modify connections created by other members or by an admin. If a member is demoted to guest, an admin must manage their connections. ### Guest Role Guests have read-only access to family configuration. They can view categories, tags, merchants, and rules, but cannot create, edit, or delete them. They also cannot create or manage any provider connections. The option to connect a provider is not shown to guests; the server also refuses connection creation for that role. These restrictions are enforced consistently across every access path: * **Web UI**: Write controls for categories, tags, merchants, and rules are hidden or disabled. The rule toggle is shown but disabled. The "create a rule?" prompt after categorizing a transaction is not shown. * **API**: Guest API credentials receive a `403 Forbidden` response on any write endpoint for categories, tags, merchants, and family-configuration import types (category, merchant, rule, and Sure imports). Read endpoints remain available. * **Imports**: Guests cannot create, publish, revert, or delete category, merchant, rule, or Sure imports. Guests also cannot publish any import — including transaction, Mint, QIF, or PDF imports — if publishing would create new categories or tags. Mapping an unmapped value to an existing category or tag, or leaving it empty, still works. For guests, reverting or deleting non-family-configuration imports requires write access to all affected accounts, including accounts created by the import; linked-statement permissions also apply. * **Import wizard**: Guests can edit pending or failed imports that are not category, merchant, rule, or Sure imports, subject to linked-statement access requirements. * **Assistant and MCP**: The `create_tag`, `update_tag`, `create_category`, and `update_category` tools are not available in a guest's tool registry for either the chat assistant or MCP. ## Use Cases ### Couples Managing Joint Finances Share checking, savings, and credit card accounts with your partner. Both can track spending, categorize transactions, and monitor budgets together. ### Parents Teaching Financial Literacy Share specific accounts with children in view-only mode, allowing them to learn about budgeting and money management without making changes. ### Household Budget Collaboration Share household expense accounts with all family members who contribute to bills, enabling transparent tracking of shared expenses. ### Investment Portfolio Oversight Share investment accounts with a financial advisor or trusted family member for oversight while maintaining control over trading decisions. ## Security Considerations * **Encryption**: All shared data is encrypted at rest and in transit * **Access control**: Permissions are enforced at the database level * **Audit trail**: All changes to shared accounts are logged * **Revocable access**: Sharing can be revoked instantly by the account owner * **File attachment access**: Sure checks access before serving protected financial attachments; public logos and avatars are exempt. Export files require the requester to be an admin of the owning family. Import files (PDF and NDJSON) and family document attachments require membership in the same family; statement-linked imports also require visibility of the linked statement. Direct attachment requests that fail these checks return a 404. ## Best Practices 1. **Start with view-only**: Give new family members **View only** access first, then upgrade to **Can annotate** or **Full control** as needed 2. **Regular reviews**: Periodically review who has access to your accounts 3. **Clear communication**: Discuss financial goals and boundaries with family members 4. **Use categories consistently**: Establish category conventions for shared accounts 5. **Respect privacy**: Only share accounts that genuinely need collaboration ## Limitations * Sharing is limited to members within the same family * Most provider credentials are managed at the family level by admins. Plaid connections can also be created and managed by members for their own bank accounts. * Some account types may have restrictions on sharing * Recurring transactions are scoped to the family, not individual users # Goals Source: https://docs.sure.am/guides/app-features/goals Set savings goals and emergency fund reserves, track progress, and record pledges in Sure # Goals Goals let you earmark money in your accounts toward specific targets — a vacation fund, a new car, or an emergency reserve. Sure reads the live balance of the linked accounts to show you progress, projected completion, and how much you need to save each month. > [!NOTE] > > Goals require preview features to be enabled. Go to **Settings → Preferences** and turn on **Enable preview features** to access Goals. ## Goal types Every goal is one of two kinds: **One-off goals** are saved toward once and then closed. You set a target amount, an optional deadline, and Sure tracks how close you are. When the target is reached you can mark it complete. A vacation fund, a car down-payment, or a home repair budget are all one-off goals. **Maintained goals** are target balances to hold, not milestones to cross. An emergency fund is a maintained goal: reaching the target is good, but the goal keeps running so you know when the balance drops below the target balance. Maintained goals cannot be completed — they can only be paused or archived. ## Progress basis For goals backed by **depository accounts** (checking, savings), Sure uses the account balance to measure progress. For goals backed by **investment accounts**, Sure defaults to the **contributions basis**: the net amount deposited into the account, excluding market gains. This prevents a market decline from making a goal look behind even when you have kept up with savings. ## Creating a goal 1. Open **Goals** from the main navigation. 2. Click **New goal**. 3. Choose a kind (**One-off** or **Maintained**). 4. Enter a name, target amount, currency, and optional deadline (one-off only). 5. Pick one or more accounts to link. Accounts must be depository or investment type. Accounts in different currencies can all be linked to the same goal; a hint below the account list confirms which currency the totals will use. 6. Optionally add a color, icon, and notes. If you skip the color, Sure assigns a default color automatically. The progress ring on the goal card and the goal's avatar both use the same color, so they always match. 7. Save. ### Emergency fund targets When creating a maintained goal you can set the target balance as a **fixed amount** or as **N months of expenses**. With the months-of-expenses mode, Sure derives the target balance from your family's median monthly spend at the moment you save the goal, then recalculates it automatically on the first of each month so the target balance stays meaningful as your spending changes. In months mode the target balance field is replaced by a derived display. If your family has no spending history yet, the form shows "Worked out when you save" and keeps the field editable so you can enter an initial amount manually. Once a history exists, the form shows the calculated figure instead of a text input. ## Goals overview strip When goals exist, the top of the Goals page shows three summary tiles. The pace tiles summarize active goals; the contribution tile measures flows through the family’s goal-linked accounts. **Contributed last 30d** shows the net amount deposited into goal-linked depository accounts during the current contribution window. A negative figure means more left those accounts than came in. Below the amount, a comparison line shows how this pace compares with the prior 30 days: * An up arrow with a percentage means your pace increased compared with the previous window. * A down arrow means your pace slowed. * "vs. prior 30d" with no arrow means the pace is flat. * "First 30d of activity" appears when the prior window’s net contribution is zero, including when both windows are zero; it does not necessarily mean there was no earlier activity. The contribution figure uses goal-linked depository accounts in the family’s primary currency. Investment accounts, other currencies, pending transactions, and excluded entries do not count. The current window includes today and the preceding 30 days; the comparison uses the 30 days before that window. **Needs this month** shows the total monthly amount required across all goals that are behind pace. Zero means no goals are currently behind their target rate. **Goals on track** shows how many active, deadline-bearing goals are saving at or above their required monthly pace, out of the total being tracked. Maintained goals, goals without a deadline, paused goals, and goals already reached are not counted in either the numerator or denominator. ## Tracking progress Each goal card shows: * **Progress amount** — the total counting money still held in the linked accounts plus any amount already spent on the goal. This is the same figure the progress ring is drawn from, so the ring and the number always agree. * Progress percentage * Monthly saving rate needed to reach a deadline (one-off goals with a target date) * Current pace (rolling 90-day average net inflow into the linked accounts, divided by three months) * Status pill When you have recorded spending from a goal, a secondary line reads **"Including X already used"** beneath the progress amount. This tells you how much of the total has been consumed, so you do not need to subtract it yourself. Goals backed by a reserve (maintained goals) never show this line because reserves do not support spending. ### Status values | Status | Meaning | | - | - | | On track | You are saving at or above the required monthly rate | | Behind | Your pace is below what you need to hit the deadline | | Reached | The balance meets or exceeds the target (one-off) | | No target date | Open-ended goal, no deadline | | Funded | The reserve is at or above its target balance (maintained) | | Depleted | The reserve has fallen below its target balance (maintained) | Paused goals show a **Paused** badge instead of a status, because the pace clock is intentionally stopped. ## Pledges A pledge is a recorded intent to add money toward a goal. Use it when you want to track a specific deposit you plan to make. **To add a pledge:** 1. Open the goal's page. 2. Click **I'm saving toward this**. 3. Choose an account, enter the amount, and confirm. Sure watches incoming transactions and account-balance updates for the pledge window. When a matching deposit arrives — within \$0.50 or 1% of the pledge amount and within the pledge window — Sure marks the pledge as matched and links it to the transaction. Pledges expire after seven days if no matching transaction arrives. You can extend a pledge's window or renew it. ## Recording spending from a goal When you use money saved toward a goal — for example, you pay for the trip your vacation fund covered — record the spend so the goal's progress stays accurate. 1. Open the goal's page. 2. Click **I used some of this money**. When the goal has been reached, this button appears directly on the goal card alongside the close action. You can also find it in the overflow menu at any time while the goal is active. 3. Enter the amount spent. The dialog shows your goal's current balance beneath the amount field so you know the maximum you can record. If the goal is linked to more than one account, choose the account the money came from. Sure records the spend and adjusts the goal's earmark on the linked account so the money is freed up for other goals or regular spending. * For goals with a **fixed earmark** (a specific amount allocated to the goal), the earmark is reduced by the amount spent. * For goals linked to a **whole account** (no fixed amount set), the whole-account link is converted to a fixed earmark equal to what the goal still needs to reach its target, capped by what the account currently backs. This prevents the consumed amount from being counted twice when the account balance catches up after the transaction syncs. If the amount you enter exceeds what the account currently backs for this goal, the spend is refused. ## Goal states A goal moves through the following states: | State | Meaning | | - | - | | Active | Running normally | | Paused | Saving stopped intentionally; the earmark is preserved | | Completed | Target was reached and the goal was closed (one-off only); the earmark is released back to the account | | Archived | Kept as a record; the earmark is released back to the account | You can reverse some state transitions. Open the goal's detail page and use the menu to: * **Reopen** a completed goal — moves it back to active and reinstates its earmark. * **Unarchive** an archived goal — moves it back to active and reinstates its earmark. Deleting a goal removes it and its pledges entirely. It does not affect your account balances or transactions. ## Multi-currency goals A goal can link accounts in different currencies. The goal itself has a single currency, and all progress figures — balance, target, pace, remaining amount — are shown in that currency. Each account's earmark stays in the account's native currency; totals are converted to goal currency at the time they are displayed. **Exchange rate rules:** * Backing (current balance), pace, and market value all use today's rate. Pace is an estimate, and converting per entry date would require a rate lookup for every transaction on every page load. * Recording a spend linked to a transaction or matching a pledge uses the entry’s date. A manual spend without a linked transaction uses today’s rate. * If a rate is unavailable, Sure never substitutes a 1:1 conversion. Instead, accounts whose balances cannot be converted are left out of the total and a warning is shown. **Missing rate warnings:** When one or more linked accounts cannot be converted because no exchange rate is available, Sure alerts you. On the goal card a small warning marker appears beneath the progress amount with the text "Some balances aren't counted (no exchange rate yet)". On the goal detail page a warning alert appears above the progress ring, naming which currencies are missing and what currency the goal uses. The alert includes a link to exchange rate provider settings for self-hosted administrators. Recording a spend from an account whose currency cannot be converted is refused until a rate becomes available. **Goal currency is locked** once at least one account is linked. To change the currency, you would need to remove the linked accounts first. **The spend dialog** shows a hint when the goal has linked accounts in more than one currency: "Enter the amount in \[goal currency]. For an account in another currency, it's converted at today's rate before it comes off that account's earmark." **The funding breakdown** on the goal detail page shows each linked account's contribution and trailing inflows. For an account whose currency cannot be converted, the inflow figures show "—" instead of zero. ## Linked accounts and earmarks A goal earmarks the balance of its linked accounts. You can link an account to a goal in two ways: * **Whole account** — the goal claims the entire account balance. Leave the amount field blank to use this mode. The field shows the placeholder **"Blank: whole balance"** to make clear that an empty field is a deliberate choice. Only one active goal at a time can hold a whole-account link on any given account. Trying to add a second whole-account link to the same account is refused. * **Fixed earmark** — you allocate a specific amount of the account balance to the goal. Multiple goals can each hold a fixed earmark on the same account, provided the total does not exceed the balance. When you leave the amount field blank, the hint beneath the account row tells you what the goal will claim: * If no other goal has earmarked any portion of that account, the hint reads **"This goal will use this account's whole balance."** * If other goals already hold earmarks on the same account, the hint reads **"This account will fund whatever is left after the other earmarks."** When another goal already holds a whole-account link on an account, that account shows as unavailable. You must enter a specific amount to add it to a second goal. To split a balance between goals, allocate a specific portion to each goal using the earmark controls in the goal form. ## Background jobs * **SweepExpiredGoalPledgesJob** — runs every 15 minutes and marks pledges that have passed their window as expired. * **RefreshMaintainedGoalTargetsJob** — runs at 3:00 AM on the first of each month and recalculates the target amount for any maintained goal using the months-of-expenses mode. # Insights Source: https://docs.sure.am/guides/app-features/insights Proactive financial observations delivered to your family nightly ## Overview Insights are short, actionable observations about your finances that Sure generates nightly. Each insight spots a pattern or event in your data — a spending anomaly, a milestone crossed, a budget running over — and fills a plain-language summary from a template so you understand what changed and why. Insights appear in the dashboard feed. ## Insight types | Type | What it flags | | - | - | | `spending_anomaly` | A category's projected month-end spend deviates 25 %+ from the three-month average baseline (above or below). Projection uses the full calendar month length, not just elapsed days, so an on-pace category is never flagged as a shortfall. Only fires after 7 days into the month. | | `cash_flow_warning` | Projected cash balance may drop below a safe threshold within the next 30 days | | `net_worth_milestone` | Net worth has crossed a round-number milestone within the last 30 days | | `subscription_audit` | A recurring transaction has not appeared since its expected due date, by at least one full billing cycle | | `savings_rate_change` | Savings rate has shifted materially compared to recent months | | `idle_cash` | A cash account has a large balance that has been untouched for 60+ days | | `budget_at_risk` | Budget categories are near or over their monthly limit | | `budget_on_track` | All budget categories are on track (shown after the month is at least half over) | | `maintained_goal_depleted` | A reserve goal has fallen below its target balance | ## Priority Each insight carries one of three priority levels: * **High** — requires prompt attention (e.g. significantly over budget) * **Medium** — worth reviewing soon * **Low** — a gentle nudge (e.g. idle cash) The dashboard feed and API response order insights by priority first, then by recency. ## Statuses | Status | Meaning | | - | - | | `active` | New — not yet seen | | `read` | Viewed but not dismissed | | `acknowledged` | Dismissed by the user | | `expired` | The underlying condition cleared; no longer shown in the feed | `active` and `read` insights appear in the feed. Acknowledged insights can be unacknowledged — this restores them to `read` without treating them as new. ## Accessing insights On desktop, the Insights button appears in the left navigation sidebar. On mobile, the button appears on the left side of the top navigation bar, next to the account sidebar toggle. It shows an unread badge with a count of active insights you haven't viewed yet. The badge updates live: it decrements when you dismiss an insight, increments when you undo a dismissal, and updates when newly generated insights arrive — without requiring a page navigation. Tapping or clicking the button opens the full insights feed and marks all active insights as `read`. The Insights button is only shown when preview features are enabled for your account. ## Family feed and account privacy The insights feed is shared across the whole family. An insight that names a specific account — such as an idle cash nudge — appears in the feed only while every active family member can access that account. If account sharing is revoked, a member joins the family, or the account is hidden or deleted, the insight is hidden on the next feed read if the visibility condition no longer holds. Restoring access can make it visible again if it is still active or read, rather than dismissed or expired. The idle cash generator only considers accounts every active member can see. A private account is excluded when another active family member lacks access. In a family with only one active member, an account owned by that member can qualify without a share. ## Dashboard feed The dashboard shows the three highest-priority, unacknowledged insights. Clicking an insight marks it `read`. Dismissing it marks it `acknowledged`. ## Dig in with AI Each insight card has a **Dig in with AI** button that opens the assistant sidebar with a pre-filled message summarising the insight — its title, body, period, and key figures. You can edit the message before sending it. The button is shown when: * The family's assistant is enabled * An LLM provider is configured (or an external assistant is set up) Clicking the button prefills the chat input; it does not send the message automatically. ### Customizing the dig-in prompt Family admins can replace the default first message from **Settings → AI Prompts** under the **Insight Dig In** section. The override supports four placeholders: | Placeholder | Value | | - | - | | `%{title}` | Insight title | | `%{body}` | Insight body text | | `%{period}` | Display period (e.g. "Oct 1 – Oct 31") | | `%{facts}` | Key figures as a bulleted list | Any other `%{...}` sequences are left as typed. Clearing the field restores the default message. ## Language Insight bodies are filled from i18n templates in your family's locale. The template is interpolated with the generator's pre-computed figures, so no LLM call is made when creating or refreshing an insight. If no locale is set, Sure defaults to English. ## API access You can read your family's insights via the API: * `GET /api/v1/insights` — list all visible insights Push notification device tokens are managed separately: * `POST /api/v1/push_subscriptions` — register a device token * `DELETE /api/v1/push_subscriptions/{id}` — unregister a device token ### Push subscription registration The registration endpoint accepts an optional `device_key` — a 64-character lowercase hex string that identifies a specific app installation. Include it when your app generates a stable per-install identifier (for example, a UUID stored in the keychain, hex-encoded). When a token arrives with a `device_key`, Sure compares a SHA-256 digest of that key against the value stored for the existing subscription. If the digests match, the subscription transfers to the new user. If they do not match, registration is rejected with a `validation_error` to prevent one user from claiming another user's device. Call `DELETE /api/v1/push_subscriptions/{id}` before the user signs out so the old subscription is cleaned up before a new one is created. ### Delivery behavior Push notifications for high-priority insights are delivered only on the hosted version of Sure. The server retries on transient APNs errors (HTTP 429 and 5xx responses) with exponential back-off up to five attempts. A 410 response from APNs means the token is permanently unregistered; Sure removes the subscription only if the token has not been re-registered since the APNs invalidation timestamp, so a prompt re-registration from the device is never incorrectly removed. Subscriptions inactive for more than 90 days are excluded from all deliveries. # Passkeys and security keys Source: https://docs.sure.am/guides/app-features/passkeys Use passkeys, Touch ID, Windows Hello, or hardware security keys to sign in or verify MFA Passkeys and security keys let you sign in with your device, password manager, or hardware key. They can also be used as the second factor after signing in with email and password. When passkey login is enabled, people with a registered passkey can skip email/password and sign in directly with **Sign in with a passkey**. Sure requires user verification for that flow, so the passkey acts as possession plus biometric or device PIN verification. If passkey login is disabled, registered passkeys still work as an MFA method. In that mode, people sign in with their account credentials first, then use the passkey or security key to complete two-factor verification. ## Before you start You need: * Two-factor authentication enabled on your Sure account * A browser that supports WebAuthn passkeys or security keys * A passkey-capable device, password manager, Touch ID, Windows Hello, or hardware security key > [!NOTE] > > Self-hosted admins should configure the WebAuthn relying party settings before users register passkeys. See [Self-hosting configuration](#self-hosting-configuration). ## Add a passkey or security key 1. Go to **Settings → Security**. 2. Enable **2FA** if it is not already enabled. 3. Find **Passkeys and security keys**. 4. Enter a recognizable key name, such as "MacBook Touch ID" or "YubiKey". 5. Enter your current authenticator code or an unused backup code. 6. Select **Add passkey or security key**. 7. Follow your browser, operating system, password manager, or hardware key prompt. Sure checks the code before asking your browser to create the passkey. This prevents a stolen session cookie from registering a new passkey. If the code is wrong or has already been used, Sure rejects the request before the browser prompt runs, so no authenticator slot is used up. A backup code is consumed only when the passkey is successfully saved. Cancelling the browser prompt does not spend it. After registration succeeds, the key appears in the **Passkeys and security keys** list with its creation date. ## Sign in with a passkey If passkey login is enabled: 1. Go to the Sure sign-in page. 2. Select **Sign in with a passkey**. 3. Complete the browser prompt with the same passkey, device, or hardware key you registered. To use a passkey as a second factor: 1. Sign in with your Sure account as usual. 2. When Sure asks for two-factor verification, select **Use passkey or security key**. 3. Complete the browser prompt with the same passkey, device, or hardware key you registered. If you also have authenticator-app 2FA configured, you can still use a one-time code when a passkey is unavailable. ## Remove a passkey 1. Go to **Settings → Security**. 2. In **Passkeys and security keys**, find the key you no longer want to use. 3. Select **Remove** and confirm. Removing a key only removes it from Sure. If the passkey is stored in your browser, operating system, password manager, or hardware key, manage that copy in the tool where it was created. ## Self-hosting configuration For self-hosted deployments, set stable WebAuthn relying party values before people register passkeys: ```txt theme={null} WEBAUTHN_RP_ID=example.com WEBAUTHN_ALLOWED_ORIGINS=https://sure.example.com ``` `WEBAUTHN_RP_ID` is usually the registrable domain, such as `example.com`, not a full URL and not a hostname with a port. `WEBAUTHN_ALLOWED_ORIGINS` is a comma-separated list of full origins where people access Sure, including scheme and host: ```txt theme={null} WEBAUTHN_ALLOWED_ORIGINS=https://sure.example.com,https://app.example.com ``` For local development, use: ```txt theme={null} WEBAUTHN_RP_ID=localhost WEBAUTHN_ALLOWED_ORIGINS=http://localhost:3000 ``` > [!WARNING] > > Changing `WEBAUTHN_RP_ID` after people register credentials can make existing passkeys and security keys unavailable. Keep it stable across reverse proxy, domain, and hostname changes. Passwordless passkey login is enabled by default: ```txt theme={null} AUTH_PASSKEY_LOGIN_ENABLED=true ``` Set it to `false` if you only want passkeys and security keys to work as an MFA method after email/password sign-in. ### Upgrading an instance that already has passkeys Passwordless sign-in is on by default, and it applies to passkeys that were registered before this feature existed. A passkey a user added purely as a second factor can, after the upgrade, sign that user in on its own. This applies to a credential only if the authenticator that holds it made it discoverable. Registration asks with `residentKey: "preferred"`, which an authenticator is free to decline, and nothing in the database records what it decided — so Sure cannot tell you in advance which existing credentials are affected. Password managers and platform authenticators (Proton Pass, iCloud Keychain, 1Password, Bitwarden, Windows Hello) store discoverable credentials by default, so theirs generally are. A credential stored non-discoverably — such as one on a hardware key with no free resident-key slot — stays second-factor only. Nothing needs to be re-registered either way. The opt-out is instance-wide. There is no per-user or per-credential setting: to keep passkeys as a second factor for everyone, set `AUTH_PASSKEY_LOGIN_ENABLED=false` before upgrading. A single user can only opt out by removing the credential. This is not a reduction in security. The passwordless ceremony requires user verification, so the passkey alone is still two factors. It is a change in what an already-registered credential can do. ### Browser autofill When the browser supports conditional mediation, saved passkeys are offered from the email field's autofill menu before any button is clicked. Browsers without that support fall back to the **Sign in with a passkey** button, which works the same way. # Settings Source: https://docs.sure.am/guides/app-features/settings Configure Sure to match your preferences and needs # Settings Sure provides various settings to customize your experience and control how the app behaves. ## Security settings ### High-resolution logos Sure can fetch high-resolution logos for merchants, financial institutions, and cryptocurrencies using the Brandfetch service. This feature enhances the visual appearance of your transactions, accounts, and holdings. **To enable high-resolution logos:** 1. Navigate to Settings → Security 2. Scroll to the "Brandfetch Settings" section 3. Toggle "Use high-resolution logos" to enable 4. The setting saves automatically When enabled, Sure will: * Show each bank sync provider's own brand icon on Bank Sync cards, drawers, and Accounts connection cards * Fetch higher quality logos for merchants and institutions * Display dedicated logos for cryptocurrency assets (e.g., BTC, ETH) via Brandfetch's crypto logo service * Use Brandfetch as a fallback for stock tickers when logos aren't available * Display clearer, more professional-looking icons throughout the app > [!NOTE] > > High-resolution logos may increase data usage slightly as larger image files are downloaded. ### Brandfetch integration The Brandfetch integration provides: * **Provider logos**: Each bank sync provider's own icon on Bank Sync cards and Accounts connection cards, falling back to a generic icon or initials when unavailable * **High-quality logos**: Professional brand assets for better visual recognition * **Cryptocurrency logos**: Dedicated logo resolution for crypto assets using per-coin identifiers * **Fallback support**: Automatic logo lookup for stock tickers and merchants * **Consistent branding**: Standardized logo appearance across all transactions and holdings This feature works automatically once enabled. Self-hosted users must also set the `BRAND_FETCH_CLIENT_ID` environment variable. See [self-hosting configuration](/self-hosting#brand-logo-variables) for details. ## API keys Generate API keys for programmatic access to your Sure data from **Settings → API Keys**. Each key carries a permission scope — Read Only or Read/Write — and is authenticated using the `X-Api-Key` request header. See [API keys](/guides/app-features/api-keys) for details on creating keys, scopes, and rate limits. ## Passkeys and security keys Add passkeys, Touch ID, Windows Hello, or hardware security keys from **Settings → Security** after enabling 2FA. These credentials can be used to sign in without email/password when passkey login is enabled, or as the second factor after email/password sign-in. See [Passkeys and security keys](/guides/app-features/passkeys) for setup steps and self-hosting configuration notes. ## Bank sync settings Configure third-party bank, brokerage, crypto, and data sync integrations from Settings → Bank sync. See the [providers documentation](/providers/overview) for detailed setup instructions. ### Syncing from the Accounts page The **Accounts** page has a sync control in the header that lets you trigger and manage a family-wide sync without leaving the page. * When no sync is running, a refresh icon button is shown. Click it to start a sync of all connected accounts. * When a sync is in progress, the refresh icon becomes a spinning indicator and is disabled. A **Cancel sync** button also appears next to it. * Clicking **Cancel sync** requests cancellation and shows a confirmation notice. Work already running may finish before the sync stops. Sure triggers a family-wide sync automatically on login when `auto_sync_on_login` is enabled and the family has not synced yet today. When this auto-sync is in progress as you navigate to the Accounts page, the sync controls reflect the in-progress state immediately. ## AI settings Configure AI features like chat and transaction rules from Settings → Self-Hosting. See the [LLM support documentation](/llm-support) for more details. ## Preferences ### Count investing as spending By default, investment contributions from a non-investment, non-crypto account into an investment or crypto account count as spending in budgets, reports, the savings rate, and the cash flow Sankey. Transfers between investment or crypto accounts remain funds movements. Existing account and transaction exclusions still apply, including accounts excluded from reports and tax-advantaged accounts. If your household treats contributions to an ISA, pension, or brokerage as saving rather than spending, you can turn this off. Go to **Settings → Preferences** and toggle **Count investing as spending** to off (requires admin role). When the setting is off: * Investment contributions no longer appear in spending totals or budget actuals. * The cash flow Sankey draws a separate **Invested** outflow node next to Surplus or Deficit. * The AI assistant's income statement reports an `invested` total alongside income and expenses. * Budget drilldowns and report breakdowns exclude those transactions. * Loan payments are unaffected and remain counted as expenses. The preference is part of the income statement cache key, so a new report request uses the updated setting. ## Preview features Some newer areas of the app are gated behind preview features while they are still rolling out. ### Goals section The Goals section is gated behind preview features. To access it, enable **Preview features** in your preferences. 1. Navigate to Settings → Preferences 2. Turn on **Enable preview features** 3. Refresh the app if the Goals section does not appear immediately Once enabled, Goals appears in the main navigation. See [Goals](/guides/app-features/goals) for full details. #### Reserve target: months of expenses When creating or editing a maintained goal (such as an emergency fund), you can set the target balance as a number of months of your household's spending rather than a fixed amount. **To use a months-based target:** 1. Create or open a maintained goal. 2. Under **Target balance**, choose **Months of expenses** instead of **Fixed amount**. 3. Enter the number of months (for example, 3 or 6). 4. Sure calculates the target balance from your family's median monthly spending and saves it immediately. Sure recalculates and updates the target balance on the 1st of each month so it stays current as your spending changes. If your family has no spending history yet, the form keeps a manual entry field so you can set an initial target balance directly. Once spending history is available, the form shows the calculated figure instead of a text input. Changing the number of months or switching back to a fixed amount updates the target balance right away. #### Funding accounts and earmarks When you create or edit a goal, each eligible depository account shows how much of its balance is still available to earmark. * Leave the amount field blank to dedicate that account's whole balance to the goal. The field shows the placeholder **"Blank: whole balance"** so it is clear that an empty field is a deliberate choice, not an unfilled value. * Enter a specific amount to reserve only that portion, leaving the rest available for other goals. The hint beneath each account row tells you what the goal will claim when the amount is left blank: * If no other goal has earmarked any portion of that account, the hint reads **"This goal will use this account's whole balance."** * If other goals already hold earmarks on the same account, the hint reads **"This account will fund whatever is left after the other earmarks."** If your goals on the same account add up to more than its balance, Sure shows a message explaining that they will progress pro rata — it is not an error. A goal in progress legitimately claims more than its account currently holds. When another goal already holds a whole-account link on an account, that account shows as unavailable. You must enter a specific amount to add it to a second goal. #### Linking accounts to a goal When you link an account to a goal, you can either dedicate the account's entire balance to that goal or earmark a fixed amount. An account's full balance can only be dedicated to one active goal at a time. If another active goal already claims an account in full, Sure asks you to enter a specific amount instead of claiming the whole balance. This prevents the same money from being counted toward two goals simultaneously. If you archive a goal that claimed an account in full, that account becomes available for another goal to claim in full. Restoring the archived goal while the account is already claimed in full by another goal will fail with a message identifying the conflicting goal. To restore it, either update the conflicting goal to use a fixed amount, or restore the archived goal and set a fixed amount on that account link. #### Completing a goal When a goal reaches its target, a celebration panel appears on the goal's page. For one-off goals (goals with a fixed target you save toward once), the panel offers a **Close** action. Closing a goal does two things: * **Releases the earmark** — the money the goal was reserving on your linked accounts is freed. Other goals sharing those accounts can now claim that balance. * **Freezes the reached amount** — the figure is stamped at the moment you close the goal, so spending from those accounts afterward does not walk the goal's history back. Until you explicitly close a reached goal, it continues to reserve its earmark and compete with sibling goals on the same accounts. Maintained goals (reserves you hold indefinitely, such as an emergency fund) are never asked to close. A maintained goal at 100% is in its normal state and keeps its reservation. A closed goal can be reopened from the kebab menu, which thaws the frozen amount and returns the goal to active status. #### Archiving a goal Archiving moves a goal off the active list. An archived goal releases its earmark — any accounts it claimed in full become available to other goals. If you later unarchive a goal, Sure checks whether another goal has since claimed one of its whole-account links. If so, the restore fails with a message identifying the conflicting goal and account, so you can resolve the overlap manually. #### Deleting a goal You can delete a goal directly from the goal's page using the **Delete** option in the kebab menu — no need to archive it first. The confirmation dialog describes exactly what will be removed (linked accounts and pledges). Deleting a goal does not affect your transactions or account balances. ### New Sankey cash flow chart A redesigned Sankey cash flow chart is available as a preview feature on the dashboard. It uses a shared API with the mobile Swift client, making the web and mobile charts consistent. To access it, enable **Preview features** in your preferences (Settings → Preferences → Enable preview features). When preview features are enabled, the new chart appears below the existing cashflow visualization on the dashboard under the label **New Sankey chart**. You can expand it into a full-screen dialog using the expand button in the chart header. The preview panel includes a feedback prompt so you can compare the new chart against the original and report any differences. If Sure detects that the two charts produce different financial totals, the "Something looks wrong" button highlights automatically. Submitting feedback opens a short form — describe the issue without including account numbers or balances, as responses are sent to PostHog. **Label display:** The chart labels nodes in order of size — larger categories claim their labels first when space is limited. A small node positioned above a large one no longer causes the larger category's label to be hidden. If two nodes are the same size, the one higher in the chart takes priority. On narrow screens, a label that would extend across into a neighboring column's bar is hidden so it does not cover other categories. Hidden labels remain visible on hover. **Sort flows:** A "Sort flows" control lets you change the vertical ordering of nodes in each column of the chart. Three options are available: * **Auto** — uses d3-sankey's default layout, which minimises crossing lines between nodes. * **Smallest first** — orders nodes from smallest amount at the top to largest at the bottom. * **Largest first** — orders nodes from largest amount at the top to smallest at the bottom. Your choice is saved in the browser and applies to both the inline chart and the expanded full-screen view, keeping them in step. **Show flows by category or account:** A "Show flows by: Category / Account" toggle appears in the Sankey chart header. The default category view routes money through a single Cash Flow node. The account view routes income categories through each individual account to expense categories. An account that takes in more than it spends feeds Surplus; an account that spends more than it takes in (for example, a credit card paid off by a transfer) is fed from Deficit. Transfers between accounts do not appear as flows. The choice is saved as a preference and the chart updates without a page reload. ### AI sidebar on desktop If you do not want to use the AI assistant yet, you can hide the desktop AI sidebar with the **panel-right** button in the top bar. * The toggle collapses and reopens the right-hand sidebar * Sure remembers your preference for future visits * Some new users may also see the sidebar hidden by default when AI is not available See [AI assistant sidebar](/guides/app-features/assistant-sidebar) for the full behavior. ## Appearance settings ### Dashboard layout You can customize how your dashboard is displayed: **Hide and show widgets**: Enter Customize mode by clicking the layout icon in the dashboard header. In Customize mode, each widget shows a hide button. Clicking it removes the widget from your dashboard. A panel at the bottom of the page lists all hidden widgets so you can add them back at any time. Click **Done** to exit Customize mode. Hidden widgets and their date ranges, account filters, and other settings are preserved while hidden. If you hide all widgets, the dashboard shows an empty state with a link back to Customize mode. **Reorder widgets**: Drag widgets into any order. Hover over a widget to reveal the drag handle (grip icon) in its header, then drag to reposition. On touch devices, press and hold a widget for about 800 ms before dragging. With a keyboard, press **Enter** or **Space** to grab a focused widget, use **Up** and **Down** to move it, and press **Enter**, **Space**, or **Escape** to release. The new order is per-user and saves on drop or keyboard release. **2-column layout**: On wide screens, display dashboard cards in a 2-column grid for better space utilization. This setting is available in Settings → Appearance. When enabled: * Dashboard cards arrange in two columns on desktop screens * Provides a more compact view of your financial overview * Automatically adjusts to single column on mobile devices **Start expanded by default**: Choose which account groups open automatically when the dashboard and account sidebar load. Available in Settings → Appearance → Dashboard. You can select any combination of the nine account group types: Cash, Investments, Crypto, Property, Vehicles, Credit Cards, Loans, Other Asset, and Other Liability. Groups you check here start open on every page load. You can still collapse them manually at any time — the preference only controls the initial state, not any changes you make during the session. ### Account order Control how accounts are sorted within each group in the sidebar and the dashboard balance sheet. Go to **Settings → Appearance** and choose a **Default account order**: * **Name (A-Z)** — alphabetical ascending (default) * **Name (Z-A)** — alphabetical descending * **Balance (Low to High)** — smallest balance first * **Balance (High to Low)** — largest balance first * **Manual (drag to reorder)** — arrange accounts yourself When you select **Manual**, a **Sort accounts** button appears at the top of the accounts sidebar. Click it to enter sort mode. In sort mode you can: * **Mouse**: drag any account row to a new position within its group * **Touch**: drag rows on touch devices * **Keyboard**: press **Enter** or **Space** to grab a focused row, use **Up** and **Down** to move it, then press **Enter**, **Space**, or **Escape** to release The order is saved per account type group and per user. Accounts you add later appear after your arranged ones, sorted alphabetically. The manual order also applies to the dashboard balance sheet. If you navigate away while holding a row with the keyboard, Sure saves the move before continuing so the new page reflects your change. ### Drag to select a date range on charts You can select a custom date range directly on the net worth chart or on any account's balance chart by clicking and dragging across it. Releasing the mouse navigates the page to that range. The period picker updates to show the selected dates (for example, "Aug 15 – Sep 5") instead of a generic "Custom" label. Choosing a preset from the picker clears the custom range. Drag-select is mouse-only; on touch devices, swiping the chart scrolls normally. ### Spending widget The dashboard includes a **Spending** widget that shows your cumulative daily spending for the selected month plotted against the previous month's full curve. This lets you see at a glance whether your current month's spending is tracking ahead of or behind last month. The widget displays: * Your current month's running total (in green) with a marker at today's date * The previous month's spending curve (in gray) labeled with the actual month name (for example, "August 2026"). The x-axis spans the selected month's days; if the previous month was longer, its extra days are folded into the final visible point so the endpoint still equals the full previous-month total * The total spent so far this month and the signed delta versus the previous month, both calculated over the same number of elapsed days so the comparison is always apples-to-apples. While the selected month is still in progress, the previous-month label names the day range being compared (for example, "Aug 1–8"). Once the selected month is complete, both months are compared in full. * Gridlines with compact currency labels and a shared tooltip * On narrow viewports, a compact date range (for example, "Sep 01 - 6, 2026") instead of the full date range, and x-axis tick labels for the selected month only so the chart stays uncluttered **Selecting a month:** Use the month picker in the widget header to review any of the past 12 months. The widget's selected month is independent of the dashboard's global time period at the top of the page. **Filtering by category:** A filter beside the month picker lists complete category groups with spending in the selected or previous month, plus groups containing a selected category. Uncategorized appears when it has spending or is selected. Selecting a parent includes its subcategories. Selecting every displayed option becomes unfiltered when every option belongs to a group with spending; a selected category with no spending keeps the filter active across months. Both chart lines and header totals use the selection. The button count reflects selected categories, counting children instead of also counting their parent. The selection is stored in the URL and carried through month changes and Customize mode. The widget is hidden when there is no spending data for the selected month. ### Theme selection Sure supports multiple theme options to match your preference: **Available themes:** * **Light** - Light color scheme for bright environments * **Dark** - Dark color scheme for low-light environments * **System** - Automatically matches your device's system theme **To change your theme:** 1. Navigate to Settings 2. Find the "Theme" or "Appearance" section 3. Select your preferred theme (Light, Dark, or System) 4. The theme applies immediately The theme setting is saved to your account and syncs across all your devices. > [!TIP] > > The "System" option automatically switches between light and dark themes based on your device's settings, providing the best experience throughout the day. ## Mobile app settings ### Localization The mobile app supports English and Swedish (Svenska). It uses the locale configured on your device to select the display language automatically. ### AI chat improvements The mobile app includes an enhanced AI chat experience: * **Typing indicator**: An animated indicator shows when the AI is generating a response * **Smooth animations**: The typing indicator uses a classic three-dot bounce animation * **Auto-scroll**: The chat automatically scrolls to show new messages as they arrive * **Improved flow**: Chat creation is now lazy-loaded on first message send, eliminating loading delays ## Debug log The debug event log at **Settings → Debug** records diagnostic events from background jobs and provider syncs. ### Expandable table view The log table has an **expand** button in the card header (the same pattern used by the dashboard cashflow chart). Clicking it opens the full table in a wide dialog, giving all seven columns — level, category, message, source, context IDs, and metadata — enough room to be read without truncation. The expanded view is also useful on smaller screens where the inline table is cramped. ## Data exports Sure allows you to export your financial data for backup or analysis purposes. When you create an export, the page automatically refreshes to show the latest status. Only family admins can create and download exports. The web export feature redirects non-admins, while the API returns 403. Direct export-attachment requests without admin access to the owning family return 404. ### Export status tracking The export list page automatically polls for updates when exports are in progress: * **Processing exports**: The page checks for updates every 3 seconds * **Completed exports**: Auto-refresh stops once all exports are complete * **Download ready**: Download buttons appear when exports finish processing This ensures you always see the current status without manually refreshing the page. ## Localization Sure supports multiple display languages. You can change the interface language from **Settings → Preferences**. ### Country selector The **Country** field in Settings → Preferences uses a searchable dropdown. Type a country name to filter the list instead of scrolling through the full list. Supported languages: English, French, German, Spanish, Italian, Turkish, Norwegian Bokmål, Catalan, Romanian, Russian, Polish, Portuguese (Brazil), Portuguese (Portugal), Chinese (Simplified), Chinese (Traditional), Dutch, Hungarian, Vietnamese, and Ukrainian. Navigation labels update to match your selected language. For example, the System health link in the Advanced section of the settings navigation appears as **Systemstatus** when the interface language is set to German. Super-admin-only navigation items follow the same localization as the rest of the interface. The **Settings → Background Jobs** console is fully localized in German and Russian. This includes the worker status stats panel (Workers, Busy, Enqueued, Retries, Scheduled, Dead), the in-flight operations table columns, per-operation status labels (Running, Queued, Recent, Stuck), action buttons, and all confirmation and error messages. In German, the page title appears as **Hintergrundjobs** and the worker status section heading as **Worker-Status**. In Russian, the page title appears as **Фоновые задачи** and the worker status section heading as **Состояние обработчиков**. The AI chat interface is fully localized in Brazilian Portuguese (pt-BR). This includes the AI greeting, suggested questions, chat navigation labels (all chats, start new chat, edit title, delete), the AI consent dialog, and error messages. Several account page UI strings that previously failed to resolve in non-English locales now display correctly. The balance tooltip and "no balance data" message on account activity date rows, the selection toggle label in the activity feed, and the period picker's accessibility label all use the correct language when a non-English locale is set. Previously these strings rendered as raw translation-missing text or fell back silently to English. ### MXN number formatting in Spanish When the interface language is set to Spanish, Mexican peso (MXN) amounts now display with US-style separators — a dot (`.`) as the decimal separator and a comma (`,`) as the thousands separator — matching how MXN values are natively formatted. Previously, the Spanish locale's European-style separators were applied to MXN, producing incorrect formats such as `1.234,56` instead of `1,234.56`. All other currencies continue to use the locale-aware separators for their respective locales. ### Date formatting across all locales Dates that span multiple years — such as those shown in bills, the period picker, and transaction date pickers — now display in the correct format for your locale. Previously, only 7 of the 118 supported locales defined their own short-with-year date format. The other 111 fell back to the English format (`Jan 05, 2027`), so a German user, for example, would see `Jan 05, 2027` instead of `05. Jan 2027`. All 118 locales now have an explicit short-with-year format derived from their own long date format. ## Release highlights When a new version of Sure is deployed, a "What's new" dialog appears the first time you interact with the app after the update. It shows the release notes for the deployed version so you can see what changed without leaving the app. The dialog appears once per release, per account. Each release — including hotfix releases — is tracked separately, so a hotfix update triggers its own dialog even if you have already seen the base release. Dismissing it (by clicking **Done**, the close icon, the overlay, or pressing Escape) marks that release as seen and it will not reappear. Navigating away without dismissing does not mark it seen — the next page will offer it again. The dialog is fetched lazily on your first click or keypress after the page loads, so it never interrupts the initial render. If a drawer or modal is already open when you first interact, the dialog waits until the page is clear before appearing. ## Account preferences Manage your personal account settings, including: * Email and password * Display preferences * Notification settings * Connected SSO accounts Access these from Settings → Account or Settings → Security. # Statement Vault Source: https://docs.sure.am/guides/app-features/statement-vault Store account statements and understand how Sure suggests matching accounts for uploaded PDFs # Statement Vault The Statement Vault stores original account statement files for a family. It accepts PDF, CSV, and XLSX uploads, keeps the original file, and uses the file hash to avoid storing the same document twice. You can upload statements from Settings -> Statement Vault. If you choose an account during upload, Sure links the statement to that account immediately. If you leave the account blank, the statement stays in the unmatched inbox and Sure may suggest a matching account for review. > [!NOTE] > > An account suggestion is not the same thing as an account link. Sure only links an unmatched statement after a person confirms the suggestion or selects an account manually. ## How PDF account suggestions work When an unmatched PDF is uploaded, Sure reads metadata from the filename and compares it with visible accounts in the same family. For PDFs, Sure currently uses filename-based detection: * Statement period, from dates or month names in the filename * Account last four digits, from patterns like `ending 1234`, `last 4 1234`, `acct 1234`, or `xx1234` * Institution and account name hints, from meaningful remaining filename text after generic words and dates are removed Sure then scores each visible account: * Institution hint matches the account name, institution name, or institution domain: `+0.45` * Account name hint matches the account name: `+0.25` * Last-four hint matches the account name or institution name: `+0.25` * Statement currency matches the account currency: `+0.05` Accounts below `0.35` confidence are ignored. The highest scoring account becomes the suggested account shown in the unmatched inbox. ## Example A file named `Chase_Bank_2024-01_account_6789.pdf` can produce: * A January 2024 statement period * `Chase Bank` as an institution/account hint * `6789` as the account last-four hint If a visible account has matching Chase metadata and the same currency, Sure will show that account as a suggestion with a confidence score. ## Reviewing suggestions From Settings -> Statement Vault, the inbox shows statements that are unmatched or rejected: * The original filename * Detected statement period, when available * Suggested account and confidence score, when Sure finds one * A **Rejected** badge for statements whose suggestion was previously rejected * Actions to link or reject the suggestion Selecting the link action files the statement against that account. Rejecting the suggestion clears it and marks the statement as rejected. Rejected statements stay in the inbox so you can find and delete them — they are not re-suggested by routine metadata edits and their file hash still counts against duplicate detection until the statement is deleted. ## PDF imports and AI extraction PDF transaction imports use the Statement Vault as their storage layer, but account matching and AI extraction are separate steps. When you upload a PDF through the import flow, Sure first stores it as an unmatched statement, then creates a PDF import and queues AI processing. The AI processing classifies the document and may extract transactions for bank or credit card statements. That AI extraction does not currently improve the account suggestion; the suggestion comes from the statement metadata matching described above. After transactions are extracted, the import still needs an account before it can be published. You can target any account — including provider-synced accounts — because Sure reconciles extracted transactions against what the account already holds before presenting them for review. ### Reconciliation When you assign an account to a PDF import, Sure matches each extracted transaction against the account's existing entries by amount and date (with a small date window to account for posting-date differences). Transactions that are already on file are marked reconciled and excluded from the import; only genuinely new transactions are offered for review. The import summary shows: * **Extracted** — total transactions found in the statement * **Already recorded** — transactions matched to existing entries * **Imported** — transactions added by this import * **Awaiting review** — transactions not yet published A statement whose transactions are all already on file completes with zero rows to import. This is expected when the account has already synced the same period from a provider. Reconciliation is reversible. If you reassign an import to a different account, Sure releases the previous account's reconciliations and re-evaluates the rows against the new account. Reverting a published import also releases any reconciliations it created. ## Duplicate detection and reconciliation When you assign an account to a PDF import, Sure automatically compares each extracted transaction against what that account already holds. Transactions that already exist — whether imported earlier or synced from a provider — are marked as reconciled and excluded from the review step. Only genuinely new transactions are offered for import. This means: * A statement whose transactions are all already on file will complete with zero rows to review. The import summary shows how many transactions were found in the statement, how many were already recorded, and how many were imported. * Provider-synced accounts can now be used as import targets. The duplicate check prevents re-importing transactions that sync already brought in. * Matching uses amount and date (with a small date window to account for posting-date differences). Transaction names are not matched because statement descriptions and provider names for the same transaction rarely agree. If you reassign a PDF import to a different account, Sure releases the previous account's reconciliation marks and re-evaluates the statement against the new account. ### Import summary After AI processing completes or after you publish, you can view a summary of the import that breaks down: * **Transactions found**: Total transactions extracted from the statement * **Already recorded**: Transactions matched to existing entries * **Imported**: New transactions added by this import * **Awaiting review**: Transactions not yet published ## Tips for better matches * Keep the institution name in the filename. * Include the statement month or date range. * Include a masked account suffix when available, such as `account_6789`. * Avoid generic filenames like `statement.pdf`; they usually do not contain enough information to suggest an account confidently. # Transactions Source: https://docs.sure.am/guides/app-features/transactions Review, categorize, and clean up transactions in Sure # Transactions Transactions are the day-to-day entries that drive Sure's budgets, reports, and account history. Use the Transactions screen to review imported activity, add manual entries, categorize spending, and keep related labels such as merchants and tags tidy. ## Review transactions Open **Transactions** from the main navigation to see recent activity across your accounts. From this screen you can: * Search and filter by account, date, type, status, amount, category, tag, merchant, or attachments. The merchant filter includes a **No merchant** option to show only transactions without an assigned merchant; the tag filter includes an **Untagged** option to show only transactions with no tags; the attachments filter lets you show only transactions that have files attached or only those with no attachments. * View a summary of the count and total amounts for your current filter * Click anywhere on a transaction row to open its detail drawer * Add a new manual transaction * Import transaction data from a CSV file * Review upcoming recurring transactions * Convert eligible investment cash activity into a security trade ### Tags in the transaction list Tags are shown directly on each transaction row so you can see at a glance which tags a transaction carries. On wider screens, a dedicated **Tags** column appears. A single tag renders as a colored pill. Multiple tags collapse into a compact badge showing the first two letters of each tag; hovering the badge reveals all tag names. On narrower screens and on mobile, tag pills appear inline after the transaction title. To change the tags on a transaction without opening its detail drawer, click any tag pill (or the add-tag icon) on the row. A searchable picker opens where you can toggle tags on or off. Each click applies the change immediately without closing the picker. Transfer rows display tags as read-only in the list; edit tags for a transfer from its detail drawer, which keeps both legs in sync. Tags can only be added or removed by users who have annotate permission on the account. Pending transactions are visible in your transaction list but are excluded from account balance calculations. Balances reflect only settled (posted) transactions. Once a pending transaction posts, it is included in balance and report totals. If Sure detects that a pending transaction might duplicate a posted one, you can merge the duplicate or keep both transactions. When you merge a pending duplicate into its posted counterpart, Sure carries over the data you added while the transaction was pending: * **Attachments** (receipts, invoices): attachment files from the pending transaction move to the posted transaction. If the posted transaction already references the same stored attachment blob, the duplicate attachment row is dropped rather than duplicated. A merge is refused if it would push the posted transaction above 10 attachments total; the pending transaction and its attachments remain untouched in that case. * **Tags**: any tags on the pending transaction that the posted transaction does not already have are added to the posted transaction. * **Notes**: if only the pending transaction has notes, those notes are copied to the posted transaction. If the posted transaction already has notes, the pending notes are appended after a blank line, unless the same complete paragraphs already appear consecutively in the posted notes. A partial text match does not count as a duplicate. ## Add a manual transaction To add a transaction that was not imported from a provider, select **Add transaction** from the Transactions screen. Fill in the date, amount, account, and any other details, then save. If you submit the form more than once — for example by double-clicking the save button, using the browser back button, or restoring a cached tab — Sure detects the repeated submission and opens the existing transaction instead of creating a second one. ## Edit transaction details Click anywhere on a transaction row to open it and update the fields that affect reporting and review: * **Name**: The display name for the transaction * **Date**: The transaction date * **Amount**: The transaction amount and direction. When you change the currency selector, the amount field's symbol, decimal step, and precision update immediately to match the selected currency. You can paste formatted amounts — such as `20,000`, `1.234,56`, or `$1,234.56` copied from a bank statement or spreadsheet — directly into any money field. Sure parses the value and inserts the plain number. When the pasted amount is ambiguous (for example, `1,234` could be one-thousand-two-hundred-thirty-four or one point two-three-four), Sure uses the decimal separator of the selected currency to decide: pasting `1,234` into a euro field yields 1.234, while the same paste into a US dollar field yields 1234. Amounts in parentheses are treated as negative. Text that does not match a recognizable amount is left to the browser. * **Account**: The account the transaction belongs to. When adding a new transaction, the account selector includes a search box so you can find the right account quickly. * **Category**: The income or expense category used for budgets and reports. Subcategories appear indented under their parent in every category selector across the app, so the hierarchy is always visible when you assign or change a category. The "Uncategorized" option is displayed as a badge in the category selector, consistent with how other categories appear, making it easy to identify at a glance. * **Merchant**: The merchant or payee associated with the transaction * **Tags**: Extra labels for flexible filtering. When you filter by one or more tags, the summary count and totals reflect each matching transaction once, even if it carries multiple matching tags. You can also filter by **Untagged** to find transactions that have no tags assigned. * **Notes**: Private context for the transaction You can also mark a transaction as excluded. Excluded transactions are removed from budgeting calculations and reports, which is useful for activity you do not want counted in normal spending analysis. Excluded transactions remain visible in the account activity list so you can review or re-include them at any time. ### How syncs interact with your edits When you edit a transaction through the app, Sure automatically marks it as user-modified so later provider syncs do not overwrite it. Edits through the API or AI assistant also lock the fields that changed, including date, amount, name, category, and merchant. These field locks protect the edited values while other unlocked fields can still be enriched. An API update with `user_modified: true` additionally protects the whole entry from provider sync updates. These protections last until they are explicitly removed. Re-enabling sync clears the entry's user-modified and import-lock flags and its field locks. Saving changes to **Name**, **Notes**, **Category**, **Merchant**, or **Tags** does not trigger a background account sync. Reports and budgets update immediately through the entries cache. Saving changes to **Amount**, **Date**, or **Account** does trigger an account sync to recalculate balances from the affected date forward. ### Create a merchant inline If the merchant you need does not exist yet, you can create it directly from the merchant selector in the transaction detail or new-transaction form. Type a name in the merchant field and select the option to create it. Sure saves the new merchant and immediately assigns it to the transaction. There is no need to navigate to **Settings → Merchants** first. ## Categorize transactions Categories help Sure group income and expenses consistently. You can assign a category from the transaction detail view or directly from the transaction list. When there are uncategorized transactions, use the categorize flow to work through them in batches. You can assign a category to each transaction and optionally create a categorization rule so future matching transactions use the same category. After you change a transaction's category, a prompt may appear offering to create a matching rule. Use the **X** button to close only that prompt without affecting future ones. Select **Hide for today** to pause all rule suggestions for 24 hours — a note below the buttons states this so the effect is clear. Check **Don't show this again** to permanently disable rule prompts for your account. Use subcategories when you want more detail within a broader category. For example, a parent category such as **Food & Dining** can contain subcategories such as **Groceries**, **Restaurants**, and **Coffee**. The category picker groups subcategories under their parent and indents them with a hierarchy indicator, so the full structure is visible in the transaction form, bulk edit, rule builder, search filters, and import mapping. Budgets can use subcategories individually or share the parent budget. ### Category filter sidebar When you filter transactions by category in the sidebar, parent and subcategory checkboxes are linked: * Checking a parent category automatically checks all of its subcategories. * Unchecking any single subcategory automatically unchecks its parent. * If some but not all subcategories are checked, the parent shows an indeterminate (partial) state. This keeps the filter consistent with what the backend submits: selecting a parent category includes every subcategory with no way to exclude one individually, so the checkboxes always reflect exactly what gets applied to your transaction list. If you arrive at the transaction list from a link that filters by a parent category, all subcategories are pre-checked to match the active filter. ### What counts as uncategorized The Uncategorized filter, the uncategorized badge count, and the Quick Categorize wizard all use the same definition: a transaction is uncategorized when it has no category assigned and its kind is not a pure inter-account transfer leg (specifically, `funds_movement` and `cc_payment` are excluded because those legs have nothing to categorize). All other transaction kinds — including `loan_payment`, `investment_contribution`, and `one_time` — appear in the uncategorized list if they have no category. The dashboard's uncategorized aggregate uses the same set, so the count shown on the dashboard always matches what you see in the Transactions list. Loan payment and investment contribution transfers are categorizable. For a matched transfer, assign the category, merchant, and tags on its outflow transaction. The inflow shows the outflow category read-only. An unmatched imported transfer leg remains editable. ### Filter by AI categorization status The search popover on the Transactions page includes an **AI** filter group with two independent checkboxes: * **AI** — shows transactions whose category was set by automatic categorization (Bayes or LLM) and still matches that original assignment. * **AI history** — shows transactions where automatic categorization ran but the category no longer matches: a rule, manual edit, import, or a clear has since changed it. Checking both options together returns any transaction that was ever automatically categorized, regardless of whether the category was later changed. Leaving both unchecked applies no AI-status filter. These filters let you audit how auto-categorization has behaved across your transaction history — for example, to find transactions where the AI assignment was overridden, or to confirm which transactions still carry their original AI-assigned category. ### Filter by attachment The search popover on the Transactions page includes an **Attachment** filter group with two independent checkboxes: * **With attachment** — shows only transactions that have at least one file attached. * **Without attachment** — shows only transactions that have no files attached. Checking both options together is the same as leaving both unchecked: no attachment filter is applied. For split transactions, Sure checks the parent transaction for attachments. A split child counts as attached when its parent has a file, so the filter behaves consistently whether you view splits individually or grouped. ### Filter by uncategorized on an account page The Filter popover on each account's activity list includes an **Uncategorized only** option under a **Category** section. Checking it narrows the activity list to transactions that meet the same uncategorized definition used by the Transactions page filter, the uncategorized badge, and Quick Categorize. The filter combines with the status filters (Confirmed, Pending) and the search field, so you can work through what still needs a category within a single account without switching to the global Transactions page. ### Categorize flow The categorize flow (accessible when uncategorized transactions exist) displays a category picker that groups subcategories under their parent, consistent with the rest of the app. Both the parent label and its subcategories are visible together, making it straightforward to pick the right level of detail without navigating a flat list. The categorize flow only surfaces transactions on accounts you have permission to annotate — owner, full-control share, or read-write share. Transactions on read-only or unshared accounts are excluded from both the count displayed on the Transactions page and from the flow itself. If a bulk categorization would skip every selected entry because none belong to accounts you can annotate, no rule is created. This ensures the wizard accurately reflects what you can change. ### Create a category inline If the category you need does not exist yet, you can create it directly from the transaction form or detail panel without leaving the transaction. Type a new name in the category selector and choose **Create "\[name]"** from the dropdown. The new category is saved and immediately assigned to the transaction. To create a subcategory instead, select **Add as a subcategory…** below the create row. The picker switches to a list of your top-level categories. Select a parent to create the new category under it. The new subcategory inherits its parent's color and is immediately assigned to the transaction. ### Create a category from the quick picker The quick category picker that opens from a transaction row in the list now also supports inline creation. When you type a name that does not match any existing category, the picker shows a **Create "\[name]"** row. Click the row or press Enter to create the category and assign it to the transaction in one step. The row refreshes in place and the rule suggestion prompt appears as normal. To create a subcategory instead, click **Add as a subcategory…** below the create row. The picker swaps to a list of your top-level categories. Select a parent to create the new category under it and immediately assign it. If category creation fails, an error message appears in the picker so you can correct the name and try again. In the category selector used by transaction forms, focus also returns to the search field, where Escape closes the selector. The transaction row’s quick picker shows the error but does not perform that focus reset. These options are only shown when you have permission to annotate the transaction's account. ## Bulk edit transactions Select multiple transactions to reveal the selection bar at the bottom of the screen. The bar shows how many transactions are selected and gives you quick actions. Choose **Edit** to apply the same details to all selected rows. Bulk editing can update: * Name * Date * Category * Merchant * Tags * Notes Before saving, review the selected transactions so you do not apply a cleanup change to unrelated activity. If your selection includes split transactions, Sure applies the bulk edit to the individual split entries rather than the parent transaction. The parent itself is not updated directly. ### Bulk edit and account permissions Bulk edit respects the account share permissions of the user making the change: * **Owner or full control share**: all fields (name, date, category, merchant, tags, notes) can be updated. * **Read-write share**: only annotation fields (category, merchant, tags, notes) can be updated. Name and date changes are ignored for these transactions. * **Read-only share or no access**: the transaction is skipped entirely and not updated. This means a bulk edit applied to a mixed selection may update different fields on different transactions depending on the account each transaction belongs to. The final notice shows how many transactions were actually updated. ## Group split transactions When a transaction is split into multiple entries, Sure can display the child entries grouped under their parent row with an indented layout. This applies to both the Transactions page and the Activity tab on individual account pages. To enable or disable this behavior, go to **Settings → Appearance** and toggle **Group split transactions**. When the toggle is on, split children appear indented under their parent in both views. When the toggle is off, split children appear as individual rows in the same position they would occupy by date. ### Duplicate a transaction When exactly one non-investment transaction is selected, a **Duplicate** action appears in the selection bar. Selecting it opens a pre-filled new transaction form with the same details as the original, so you can adjust and save a copy without re-entering all the fields. ## Manage categories, merchants, and tags The Transactions screen includes shortcuts for: * **Edit categories** * **Edit merchants** * **Edit tags** * **Edit imports** Use these management screens when the labels themselves need cleanup, not just one transaction assignment. ## Editing provider-assigned merchants Bank providers can assign shared merchant records used across families. New merchants created by AI detection are family-owned; older AI-created provider records may still exist. You can personalize a shared provider merchant for your family. When you edit a provider-assigned merchant and change its **name** or **website**, Sure converts that merchant to a family-owned merchant for your family only. Your family's transactions point to the new family-owned record; other families on the instance continue to use the original shared merchant without seeing your changes. If you submit a blank website during the edit, Sure clears the website on your family's copy. Leaving the form unchanged keeps the shared merchant as-is. ## Lock category creation Admins can prevent new categories from being created by locking the category structure. To toggle the lock, open **Edit categories** and select **Lock category creation** or **Unlock category creation** from the menu. The option is only visible to admins. When category creation is locked: * The **New category** button is hidden for all users. * Attempts to create a category through the web UI or API return an error. * Existing categories can still be edited, merged, and deleted. * Bank syncs and imports can still add categories automatically. * The category selector in transaction forms reflects the locked state. An AI assistant attempt to create a category receives a `categories_locked` error. An info banner appears on the Categories page while the lock is active so all users know why they cannot add new categories. ## Delete a category To delete a category, open **Edit categories**, select the category, and choose **Delete**. Sure removes the category and clears it from every transaction that had it assigned. Transactions eligible for the Uncategorized filter then appear there, and the count badge follows the same filtering rules after the category is cleared. If you delete a parent category, its subcategories are not deleted automatically — they become top-level categories. Delete each subcategory separately if you want to remove the entire group. ## Merge categories Use **Edit categories** and then **Merge categories** when two or more categories represent the same kind of activity. When you merge categories, Sure asks you to choose: * **Target category**: The category to keep * **Source categories**: The categories to merge into the target Both the target dropdown and the source checkbox list use hierarchy-aware ordering: parent categories appear in alphabetical order, and each parent's subcategories appear immediately after it in the same alphabetical order. This keeps related categories grouped together so you can quickly find the right target or source without scanning a flat, alphabetically mixed list. Sure moves matching transactions from each source category to the target category. It also moves budget lines to the target category. If a budget already has lines for both the source and target categories, Sure combines their budgeted amounts into the target line. After the move, Sure deletes the source categories. ### Merge guardrails Sure prevents merges that would make the category hierarchy confusing or invalid: * You cannot choose the same category as both the target and a source * You cannot merge a parent category into one of its own subcategories * You cannot merge a category that has subcategories into another subcategory If a source category has subcategories and the target is a parent category, Sure reparents those subcategories under the target. ## Transaction rules Rules let you automatically apply categories, merchants, tags, and other attributes to transactions that match a set of conditions. You can create and manage rules from **Settings → Rules**. ### Condition types If a rule was created on an older version of Sure and includes a condition type that no longer exists, that condition shows an "Unsupported" label in the rule editor. The condition matches no transactions while in that state. You can delete the unsupported condition and replace it with a supported one to restore the rule's behavior. ### Validation for rule types Sure validates recognized resource and action types before saving. The supported resource type is `transaction`; action types must be registered transaction actions. The web rule form returns a 422 response when validation fails. Other callers receive errors through their own API or import interface; direct database writes can bypass model validation. This validation does not repair previously stored invalid types. If a legacy rule prevents the Rules page from loading, a maintainer must repair the stored rule through an administrative path that does not depend on that page before it can be edited normally. AI actions such as auto-categorize and auto-detect merchants remain valid on existing rules even when the AI provider is not configured. Their execution still depends on the available categorization and LLM providers; absence of a configured LLM does not make the action type invalid. Rules support the following condition types: * **Transaction name** – match on the transaction name or description * **Amount** – match on the transaction amount * **Transaction type** – match on whether the transaction is income, expense, or transfer * **Merchant** – match on the merchant associated with the transaction * **Category** – match transactions that already have a specific category assigned, or that have no category * **Tag** – match transactions that already have a specific tag applied, or that have no tags * **Transaction details** – search within provider-specific metadata such as SimpleFIN payee, description, or memo fields * **Notes** – match on the notes you have added to a transaction * **Account** – match on the account the transaction belongs to Each condition type supports a set of operators based on how the field stores its data: * **Text fields** (Transaction name, Notes): Contains, Does not contain, Starts with, Ends with, Matches regex, Equal to, Not equal to, Is empty, Is not empty * **Number fields** (Amount): Greater than, Greater than or equal to, Less than, Less than or equal to, Equal to, Not equal to * **Select fields** (Merchant, Category, Account): Equal to, Not equal to, Is empty, Is not empty * **Tag**: Equal to, Not equal to, Is empty, Is not empty * **Transaction type**: its own fixed set of type-matching operators * **Transaction details**: Contains, Equal to, Is empty (JSONB metadata supports contains and equality semantics only) The **Not equal to** operator also matches transactions where the field has no value set, so "category not equal to Food" includes uncategorized transactions. **Does not contain** likewise matches transactions where the text field is absent. The **Is empty** and **Is not empty** operators do not require a value. The condition form hides the value input automatically when you select one of these operators. **Starts with** and **Ends with** perform case-insensitive prefix and suffix matches after trimming leading and trailing whitespace and collapsing repeated whitespace in the field and search value. **Matches regex** runs your pattern as a case-insensitive PostgreSQL regular expression (`~*`) against the stored field value. The field and pattern are not whitespace-normalized; regular-expression metacharacters retain their PostgreSQL regex meanings. Patterns are capped at 200 characters. Back-references (`\1` through `\9`) are not allowed and are rejected at save. A pattern that PostgreSQL cannot compile is also rejected at save so the rule never enters a broken state. A pattern that takes too long to run causes that rule's run to be recorded as failed without blocking other rules; you can identify timed-out patterns in the debug log under **Settings → Debug** (category `rule_notification` or `rule_run`). The tag condition supports all four select operators: **Equal to**, **Not equal to**, **Is empty**, and **Is not empty**. **Not equal to** matches transactions that do not carry the specified tag, including those with no tags at all. **Is not empty** matches any transaction that has at least one tag. When you combine multiple tag conditions with AND, each condition is evaluated independently, so a transaction with both tags will match correctly. ### Rule actions Rules can set: * Category * Merchant * Tags (you can select multiple tags in a single action; the rule merges them with any tags already on the transaction rather than replacing them) * Notes * Name * **Send email notification** – sends a digest email listing new matching transactions each time the rule runs #### Email notification action When a rule has a send email notification action, Sure records the set of transactions that already matched at the time the rule was created or activated. Later digests include matching transactions not already recorded as delivered; the initial matching set is not re-sent. If you edit the rule and change its match criteria — adding or removing a condition, changing a condition's type, operator, or value, or updating the rule's effective date — Sure re-records that baseline using the new conditions. Transactions that match the new criteria when the edit is saved are recorded as already delivered and are not included in the next digest. This prevents older transactions from appearing in the email as if they were new after a rule is widened. Editing any other part of the rule (name, action values, stop-processing toggle) does not reset the baseline. ### Rule order Rules run from top to bottom in the order shown on **Settings → Rules**. You can drag any rule by its handle to change its position in the list. The order matters when two rules target the same field on the same transaction: the higher rule wins and the lower rule leaves that field alone. Tags are an exception — every matching rule adds its tags rather than the first one winning. ### Stop processing Each rule has a **Stop processing further rules** toggle. When a transaction matches a rule with this toggle enabled, no rules below it run against that transaction. Use this to prevent lower rules from overriding a deliberate assignment. When a rule with stop processing is enabled, a **Stop** badge appears next to it in the list as a visual reminder. ### Applying rules Rules run automatically during account syncs. You can also apply rules manually from **Settings → Rules** using **Re-apply** on an individual rule or **Apply All** to run all rules against your existing transactions. **Apply All** runs every rule in the family — including inactive ones — so their transaction changes (category, merchant, tags, and so on) take effect. Inactive rules skip the email notification action only: matches seen while a rule is off are not recorded and no digest email is sent. When you switch a rule back on, those unrecorded matches are picked up on the next run. When you re-apply a single rule, Sure first runs all active rules above it in order before applying the selected rule. This means the result matches what the rule would produce during a full run — for example, a rename applied by a higher rule is visible to a categorization rule below it. ## Transaction splits API The API exposes a nested resource for managing transaction splits programmatically: | Endpoint | Scope | Description | | - | - | - | | `GET /api/v1/transactions/:transaction_id/split` | `read` | Return the child transactions of a split. Returns 404 when the transaction has not been split. | | `POST /api/v1/transactions/:transaction_id/split` | `read_write` | Split a transaction for the first time. Children must sum exactly to the parent amount. | | `PATCH /api/v1/transactions/:transaction_id/split` | `read_write` | Replace all children of an existing split. The previous children are deleted and the new ones are created. | | `DELETE /api/v1/transactions/:transaction_id/split` | `read_write` | Unsplit a transaction. The children are deleted and the parent is restored. | A split-child transaction ID resolves to its parent, so you can address either transaction to reach the split resource. Amounts use the same sign convention as the transaction endpoints: positive for expenses, negative for income. This differs from the web split editor, which handles sign conversion internally. Read requests need read scope and access to the account. Split writes need `read_write` scope and owner or full-control permission on the account. Use `amount_decimal` from the split response for exact amounts; inputs are rounded to four decimal places before checking their sum. See the [OpenAPI spec](https://docs.sure.am/openapi.yaml) for full request and response schemas. ## Bill allocations When a transaction has been applied to one or more bill occurrences, an **Applied to** section appears at the bottom of the transaction detail view. Each entry shows the bill name (linked to the bill's detail page), the amount applied, and the due date of the occurrence. Due dates in this section are displayed in your configured language. To change the language, go to **Settings → Preferences → Language**. ## Related pages * [Budgets](/guides/app-features/budgets) * [CSV imports](/guides/app-features/csv-imports) * [Recurring transactions](/features/recurring-transactions) # All Account Types Sure Offers Source: https://docs.sure.am/guides/key-concepts/account-types A complete reference of all account types available in Sure, including assets, liabilities, and their subtypes organized by region. # All Account Types Sure Offers Sure supports a comprehensive range of account types to track your complete financial picture. This page provides a complete reference of all available account types and their subtypes. ## Overview: Assets vs. Liabilities | Classification | Types | Description | | - | - | - | | **Assets** | Cash, Investment, Crypto, Property, Vehicle, Other Asset | Things you own | | **Liabilities** | Credit Card, Loan, Other Liability | Things you owe | ## Asset Accounts ### Cash (Depository) Liquid funds in bank accounts. | Subtype | Short Name | Description | | - | - | - | | checking | Checking | Everyday spending account | | savings | Savings | Interest-bearing savings | | hsa | HSA | Health Savings Account | | cd | CD | Certificate of Deposit | | money\_market | MM | Money Market account | ### Investment Investment accounts hold securities and have tax treatment based on account type. #### United States | Subtype | Short Name | Full Name | Tax Treatment | | - | - | - | - | | brokerage | Brokerage | Brokerage | Taxable | | 401k | 401(k) | 401(k) | Tax-Deferred | | roth\_401k | Roth 401(k) | Roth 401(k) | Tax-Exempt | | 403b | 403(b) | 403(b) | Tax-Deferred | | 457b | 457(b) | 457(b) | Tax-Deferred | | tsp | TSP | Thrift Savings Plan | Tax-Deferred | | ira | IRA | Traditional IRA | Tax-Deferred | | roth\_ira | Roth IRA | Roth IRA | Tax-Exempt | | sep\_ira | SEP IRA | SEP IRA | Tax-Deferred | | simple\_ira | SIMPLE IRA | SIMPLE IRA | Tax-Deferred | | 529\_plan | 529 Plan | 529 Education Savings Plan | Tax-Advantaged | | hsa | HSA | Health Savings Account | Tax-Advantaged | | ugma | UGMA | UGMA Custodial Account | Taxable | | utma | UTMA | UTMA Custodial Account | Taxable | #### United Kingdom | Subtype | Short Name | Full Name | Tax Treatment | | - | - | - | - | | isa | ISA | Individual Savings Account | Tax-Exempt | | lisa | LISA | Lifetime ISA | Tax-Exempt | | sipp | SIPP | Self-Invested Personal Pension | Tax-Deferred | | workplace\_pension\_uk | Pension | Workplace Pension | Tax-Deferred | #### Canada | Subtype | Short Name | Full Name | Tax Treatment | | - | - | - | - | | rrsp | RRSP | Registered Retirement Savings Plan | Tax-Deferred | | tfsa | TFSA | Tax-Free Savings Account | Tax-Exempt | | resp | RESP | Registered Education Savings Plan | Tax-Advantaged | | lira | LIRA | Locked-In Retirement Account | Tax-Deferred | | rrif | RRIF | Registered Retirement Income Fund | Tax-Deferred | #### Australia | Subtype | Short Name | Full Name | Tax Treatment | | - | - | - | - | | super | Super | Superannuation | Tax-Deferred | | smsf | SMSF | Self-Managed Super Fund | Tax-Deferred | #### Europe | Subtype | Short Name | Full Name | Tax Treatment | | - | - | - | - | | pea | PEA | Plan d'Epargne en Actions | Tax-Advantaged | | pillar\_3a | Pillar 3a | Private Pension (Pillar 3a) | Tax-Deferred | | riester | Riester | Riester-Rente | Tax-Deferred | #### Generic (Available Everywhere) | Subtype | Short Name | Full Name | Tax Treatment | | - | - | - | - | | pension | Pension | Pension | Tax-Deferred | | retirement | Retirement | Retirement Account | Tax-Deferred | | mutual\_fund | Mutual Fund | Mutual Fund | Taxable | | angel | Angel | Angel Investment | Taxable | | trust | Trust | Trust | Taxable | | other | Other | Other Investment | Taxable | ### Crypto Cryptocurrency holdings. | Subtype | Short Name | Full Name | Manual Trades | | - | - | - | - | | wallet | Wallet | Crypto Wallet | No | | exchange | Exchange | Crypto Exchange | Yes | > [!NOTE] > > Only exchange accounts support manual trade entry. Wallet accounts are sync-only. ### Property Real estate assets. | Subtype | Short Name | Full Name | | - | - | - | | single\_family\_home | Single Family Home | Single Family Home | | multi\_family\_home | Multi-Family Home | Multi-Family Home | | condominium | Condo | Condominium | | townhouse | Townhouse | Townhouse | | investment\_property | Investment Property | Investment Property | | second\_home | Second Home | Second Home | **Additional fields:** * Address * Area (square feet or square meters) * Year built ### Vehicle Cars, trucks, and other vehicles. **Additional fields:** * Make * Model * Year * Mileage (miles or kilometers) ### Other Asset Anything of value that doesn't fit other categories: * Collectibles (art, antiques, coins) * Jewelry and watches * Equipment * Other valuables ## Liability Accounts ### Credit Card Track credit card balances and spending. **Additional fields:** | Field | Description | | - | - | | APR | Annual Percentage Rate | | Available Credit | Remaining credit limit | | Minimum Payment | Minimum amount due | | Annual Fee | Yearly card fee | | Expiration Date | Card expiration date | ### Loan Track mortgages, auto loans, student loans, and other installment debt. | Subtype | Short Name | Full Name | | - | - | - | | mortgage | Mortgage | Mortgage | | student | Student | Student Loan | | auto | Auto | Auto Loan | | other | Other | Other Loan | **Additional fields:** | Field | Description | | - | - | | Interest Rate | Annual interest rate | | Rate Type | Fixed, variable, or adjustable | | Term (months) | Loan duration | | Start date | Date the loan was drawn down (optional) | | Interest basis | How each period is measured against a year: **30/360** (default, a flat twelfth), **Actual/365**, or **Actual/actual** | | Monthly Payment | Calculated from loan details (fixed-rate only) | > [!TIP] > > Sure generates an amortization schedule for any loan that has an interest rate, a term, and an original balance — including variable-rate and adjustable-rate loans. Open the loan account and select the **Schedule** tab to view the full payment breakdown. For variable-rate loans you can also record rate changes; Sure re-amortises the schedule at each change. See [Amortization schedule](/guides/key-concepts/debt-accounts#amortization-schedule) for details. ### Other Liability Debts that don't fit the above categories: * Personal loans from friends/family * Medical bills * IOUs * Tax obligations ## Tax Treatment Explained Investment accounts have different tax implications: | Treatment | Description | When Taxes Apply | | - | - | - | | **Taxable** | Normal taxation | Gains taxed when realized | | **Tax-Deferred** | Taxes postponed | Taxes paid on withdrawal | | **Tax-Exempt** | No taxes on gains | Qualified withdrawals are tax-free | | **Tax-Advantaged** | Special benefits | Varies by account type and use | > [!IMPORTANT] > > Tax treatment in Sure is for informational and organizational purposes. Consult a tax professional for tax advice specific to your situation. ## Choosing the Right Account Type | Your Situation | Recommended Account Type | | - | - | | Bank checking/savings | Cash (Depository) | | Brokerage account | Investment | | 401(k), IRA, pension | Investment (select appropriate subtype) | | Bitcoin, Ethereum holdings | Crypto | | Your home | Property | | Your car | Vehicle | | Credit card | Credit Card | | Mortgage | Loan (mortgage) | | Student loans | Loan (student) | | Car loan | Loan (auto) | | Money you owe someone | Other Liability | | Collectibles, jewelry | Other Asset | ## Account Sharing and Permissions Sure supports sharing accounts with other family members, allowing collaborative financial management while maintaining appropriate access controls. ### How Account Sharing Works Accounts can be shared with other members of your family with different permission levels: **Permission Levels:** | Permission | Can View | Can Edit | Can Delete | | - | - | - | - | | **View Only** | ✅ Yes | ❌ No | ❌ No | | **Edit** | ✅ Yes | ✅ Yes | ❌ No | | **Full Access** | ✅ Yes | ✅ Yes | ✅ Yes | ### Sharing an Account To share an account with family members: 1. Navigate to the account you want to share 2. Open the account settings or details page 3. Find the "Sharing" or "Permissions" section 4. Click **Share Account** or **Manage Access** 5. Select the family member you want to share with 6. Choose their permission level 7. Click **Save** or **Share** ### Managing Shared Accounts **As an account owner:** * You maintain full control over accounts you create * You can modify or revoke sharing permissions at any time * You can see who has access to each account **As a shared user:** * Shared accounts appear in your account list * Your available actions depend on your permission level * You can see who owns the account ### Account Scoping Account sharing affects how data appears throughout Sure: **Dashboard and reports:** * Your dashboard shows all accounts you own plus accounts shared with you * Net worth calculations include all accessible accounts * Reports and budgets can be filtered by account ownership **Transactions and activity:** * You can view transactions for any account you have access to * Edit permissions allow you to categorize, tag, and modify transactions * Full access allows you to delete transactions and manage account settings **Provider connections:** * Only account owners and users with full access can manage provider connections * Synced data is visible to all users with access to the account ### Family-Level Features Some features operate at the family level and are accessible to all family members: * **Recurring transactions**: Scoped to accounts you have access to * **Merchants**: Shared across the family for consistent categorization * **Categories and tags**: Available to all family members * **Rules**: Can be created by any family member and apply to their accessible accounts > [!IMPORTANT] > > Account sharing is designed for trusted family members. Users with edit or full access permissions can modify financial data, so only share accounts with people you trust. ### Privacy and Security **What's shared:** * Account balances and transaction history * Holdings and investment details (for investment accounts) * Account metadata (name, type, institution) **What's not shared:** * Your login credentials * Provider API keys (unless explicitly configured) * Personal settings and preferences **Admin controls:** * Family admins can manage provider connections for the entire family * Most third-party provider integrations require admin access. Members can connect and manage their own Plaid bank connections; all other providers are admin-only. * Account owners always retain control over their own accounts ## Related Pages * [How Asset Accounts Work](/guides/key-concepts/account-types#asset-accounts) * [How Debt Accounts Work](./debt-accounts.mdx) * [Managing Investment Accounts](./investment-accounts.mdx) * [Transfers Between Accounts](./transfers.mdx) # Sure clients Source: https://docs.sure.am/guides/key-concepts/clients Choose the right client for accessing Sure — web, desktop, mobile, MCP, or API. Sure is centered on a Rails server. Every client connects to that server and uses the same accounts, users, authentication rules, and financial data. A client can be a browser, a native app, a mobile app, an automation script, or an LLM agent using Sure's MCP endpoint. ## Client overview | Client | Best for | Status | Entry point | | - | - | - | - | | Web app | Full everyday use, administration, and self-hosted access from any modern browser | Primary client | Run the Rails app and visit the server URL | | macOS desktop app | People who want Sure in a native Mac window with system app chrome and deep-link handling | Native shell around the web app | See the desktop README in the repository | | Mobile app | Basic mobile access on iOS and Android, currently focused on login and account balances | Flutter companion app | See the mobile README in the repository | | LLM agents and assistants | Claude Desktop, GPT agents, local agents, or custom tools that need structured access to Sure data | MCP endpoint for external AI clients | See [MCP server](/development/mcp) | | Custom API clients | Scripts, services, importer experiments, dashboards, or other integrations | HTTP API | See the [API reference](/api-reference) | ## Web app The web app is the complete Sure experience. It is the right default when a person wants to use Sure directly, manage settings, connect providers, review transactions, or work with features that may not yet be available in native clients. For self-hosting, start with the [Docker hosting guide](/self-hosting). For local development, run the Rails app and visit the local server URL: ```sh theme={null} bin/dev ``` Then open `http://localhost:3000` in your browser. The web app also serves as the surface rendered by the macOS desktop app. ## macOS desktop app The macOS desktop app is a Tauri 2 shell that renders the full Sure web app in a native Mac window. On first launch, it asks for the Sure server URL, checks the server health endpoint, and then loads the normal sign-in flow. Use it when someone wants a desktop app experience without a separate desktop data model. It uses the same server, authentication, MFA, and permissions as the browser. The app supports servers hosted under a sub-path. If your self-hosted instance is mounted behind a reverse proxy at a path prefix — for example `https://home.example.com/sure` — enter that full URL when adding the server. The app probes the health endpoint starting at the address you entered and walks up to the origin to find the actual mount point. You can also paste a deep link (such as a session URL copied from your browser) and the app will resolve the correct base automatically. **Downloads.** Files your Sure server sends as downloads — CSV exports, statement PDFs, transaction attachments, and the import sample CSV — are saved to your macOS Downloads folder. When a download finishes, Sure shows a confirmation toast in the app window. A native macOS notification is also sent when the window is not in front, and replaces the toast when the window is hidden or the server is too old to provide it. Enable Sure notifications in System Settings to receive them. Repeated downloads of the same filename get a numbered suffix. **Printable reports.** Report pages (URLs ending in `/reports/print`) open in a separate Sure window that carries your session over. Once the page has loaded, the app opens the native macOS print dialog automatically. The print dialog appears once per report window. **External links.** Links that target a new window follow the same rules as the web app. Pages hosted on a saved server open in a new Sure window. Other `http` and `https` links open in your default browser. Links with non-web schemes or embedded credentials are ignored. ## Mobile app The mobile app is a Flutter companion app for iOS and Android. It connects to a Sure server through the API and currently focuses on core mobile flows such as authentication and viewing account balances. The app is available in English and Swedish, selected automatically based on the device locale. Use it when someone needs phone access and the feature set they need is available in the mobile client. For the full application surface, use the web app. ## LLM agents and MCP clients LLM agents are clients too. Sure exposes a Model Context Protocol endpoint for external assistants and agent runtimes that need structured access to financial data. Use MCP when a person wants an assistant such as Claude Desktop, a GPT agent, or a custom local agent to query Sure directly instead of copying data into a chat window. MCP access is configured server-side with a bearer token and a specific Sure user email. Because this gives the assistant read access to that user's family data, treat the MCP token like a production secret and only connect assistants and providers the user trusts. See [MCP server](/development/mcp) for setup and protocol details. ## Custom API clients Custom clients can call Sure's HTTP API directly. This is the right path for scripts, services, import experiments, dashboards, and integrations that do not need an MCP-compatible agent interface. API requests can authenticate with a user-generated `X-Api-Key` header, or with OAuth2 bearer tokens from Sure's Doorkeeper authorization server for registered app clients. See the [API reference](/api-reference) for available endpoints. ## Choosing a client * Start with the **web app** when a person needs the complete Sure experience. * Use the **macOS desktop app** when they want the web app wrapped in a native Mac application. * Use the **mobile app** for iOS or Android access to supported mobile flows. * Use **MCP** for LLM agents and assistant runtimes. * Use the **HTTP API** for custom software integrations. All clients connect to a Sure server the user controls or trusts. Native, mobile, API, and MCP clients do not replace the server — they are different ways to access it. # How Debt Accounts Work Source: https://docs.sure.am/guides/key-concepts/debt-accounts Understand how liability accounts track what you owe, why debt math seems backwards, and how different debt types work in Sure. # How Debt Accounts Work Debt accounts (also called liability accounts) track money you owe to others. This includes credit cards, loans, and any other obligations. ## Why Debt Math Seems "Backwards" If you're used to thinking about asset accounts, debt accounts can feel counterintuitive at first. Here's the key difference: | Balance Type | What It Means | | - | - | | **Positive balance** | You owe money | | **Negative balance** | The lender owes you money (overpayment, refund) | And transactions work in the opposite direction from assets: | Action | Asset Account | Debt Account | | - | - | - | | Spend money | Balance decreases | Balance increases (more debt) | | Receive money | Balance increases | Balance decreases (less debt) | > [!TIP] > > Think of a debt balance as "Amount Owed" rather than "money I have." A higher number means you owe more, not that you have more. ## Credit Card Example Let's walk through a typical credit card scenario: | Action | Balance Change | New Balance | What It Means | | - | - | - | - | | Starting balance | — | \$500 | You owe \$500 | | Buy groceries (+\$80) | +\$80 | \$580 | You now owe \$580 | | Gas purchase (+\$45) | +\$45 | \$625 | You now owe \$625 | | Make payment (-\$300) | -\$300 | \$325 | You now owe \$325 | Notice how spending **increases** the balance (you owe more) and payments **decrease** it (you owe less). ### Overpayment Scenario What happens if you pay more than you owe? | Action | Balance Change | New Balance | What It Means | | - | - | - | - | | Starting balance | — | \$100 | You owe \$100 | | Make payment (-\$150) | -\$150 | -\$50 | Card company owes you \$50 | | Buy coffee (+\$5) | +\$5 | -\$45 | Card company owes you \$45 | A negative balance on a credit card means you've overpaid—the credit card company owes *you* money. This might happen from: * Overpayment * Refunds for returned purchases * Statement credits or rewards ## Types of Debt Accounts Sure supports three types of liability accounts: ### Credit Card Track your credit card balances and spending. Credit card accounts can include: | Field | Description | | - | - | | APR | Annual percentage rate (interest rate) | | Available Credit | Remaining credit you can use | | Minimum Payment | Minimum amount due | | Annual Fee | Yearly card fee | | Expiration Date | Card expiration date | ### Loan Track mortgages, auto loans, student loans, and other installment debt. | Subtype | Description | | - | - | | Mortgage | Home loan | | Student | Student loan debt | | Auto | Car loan | | Other | Personal loans, etc. | Loan accounts support additional fields: | Field | Description | | - | - | | Interest Rate | Annual interest rate | | Rate Type | Fixed, variable, or adjustable | | Term | Loan duration (months) | | Start date | Date the loan was drawn down (optional). When you enter an original principal, a start date within the supported range overrides the form's opening balance date. A date on or before the cutoff 30 years ago keeps the form's opening balance date instead; the start date still drives the amortization schedule. | | Down payment | What you paid upfront. Not part of the amortization, but used to calculate your leverage ratio on the overview. | | Insurance rate | Annual insurance premium rate, charged monthly alongside the repayment. | | Insurance type | How the premium is calculated: **Level term** charges the rate on the original balance each month (constant premium); **Decreasing** charges it on the outstanding balance (falls as you repay). | | Interest basis | How each monthly period is measured against a year. **30/360** charges a flat one-twelfth each month and is the default. **Actual/365** charges by the actual number of days in the month divided by 365 — standard for UK and Australian mortgages. **Actual/actual** charges by actual days divided by the number of days in the calendar year, splitting periods that cross a year boundary. | | Monthly Payment | Calculated from loan details (fixed-rate only) | > [!NOTE] > > Sure calculates a monthly payment automatically for fixed-rate loans. For variable-rate and adjustable-rate loans, use the Schedule tab to see the current payment amount. ### Other Liability For debts that don't fit the above categories: * Personal loans from friends/family * Medical bills * IOUs * Tax obligations ## How Debt Affects Net Worth Liabilities **reduce** your net worth: ``` Net Worth = Total Assets - Total Liabilities ``` When you pay down debt, your net worth increases (even though your cash decreases). This is because the debt reduction outweighs the cash spent—you're converting a liquid asset (cash) into reduced liability (less debt). ### Example: Paying Off a Credit Card | Account | Before Payment | After \$500 Payment | | - | - | - | | Checking (Asset) | \$2,000 | \$1,500 | | Credit Card (Liability) | \$500 | \$0 | | **Net Worth** | **\$1,500** | **\$1,500** | Your net worth stays the same because you traded $500 of cash for $500 of debt reduction. But now you have no credit card debt! ## Adding Debt Accounts To add a debt account: 1. Click **+ Add Account** on your dashboard 2. Select the liability type (Credit Card, Loan, or Other Liability) 3. Enter your account details: * Account name * Current balance (the amount you currently owe) * For loans: original balance (the principal when the loan started), interest rate, term, and rate type 4. Click **Create Account** > [!IMPORTANT] > > Make sure to select a liability account type (Credit Card, Loan, or Other Liability) when adding debt. If you accidentally create a Cash account for your credit card, the balance calculations will be incorrect. ### Loans with a different opening and current balance When you add a loan, you can enter both the original principal (opening balance) and your current remaining balance. These two figures are often different — for example, a mortgage you took out years ago has a much lower remaining balance today than when it started. When you enter an original principal, Sure dates its opening anchor on the loan's start date if that date is strictly newer than the cutoff 30 years ago; otherwise it uses the form's opening balance date. If this opening anchor is before today and the current remaining balance differs, Sure also records today's balance so the first sync preserves both. If the opening anchor is today, its opening balance takes precedence and a separate current-balance anchor is not created. Dating a supported opening anchor on the start date lets the chart begin at origination. ## Understanding Loan Payments When you make a loan payment, the payment typically covers: 1. **Interest** - Cost of borrowing 2. **Principal** - Reducing the amount you owe Sure tracks your loan balance, which represents the remaining principal. As you make payments, the balance decreases until the loan is paid off. > [!TIP] > > To track loan payments accurately, create a [transfer](./transfers.mdx) from your checking account to your loan account. This properly reflects the payment in both accounts. ## Loan overview The **Overview** tab on a loan account shows a grid of summary cards and a repayment progress section. ### Summary cards | Card | Description | | - | - | | Original Loan Amount | The original principal (what was borrowed) | | Remaining Loan Amount | Your current outstanding balance | | Interest Rate | The rate in force today — for variable-rate loans this reflects the most recent recorded rate change | | Monthly Payment | The contracted payment for fixed-rate loans; for variable-rate loans, the payment currently in force based on the latest re-amortization | | Term | Total loan duration in years (or months for loans shorter than one year) | | Original Payoff Date | The date the final scheduled payment falls due under the original contract | | Type | Fixed, variable, or adjustable | | Total Cost | Total principal plus interest over the life of the loan. When an insurance rate is recorded the card is labeled **Total Cost incl. Insurance** and includes the premium total. | | Insurance | Only shown when an insurance rate is recorded. Displays the total premium if a schedule is available, or the annual rate if not. | | Leverage | Only shown when a down payment is recorded. Displays the loan-to-deposit ratio and a band (Conservative, Moderate, or High). | ### Repayment progress Below the summary cards, the overview shows how far into repayment you are: * **Repaid ring** — A donut chart showing the percentage of the original loan amount already repaid, based on your current balance. * **Payment breakdown** — The current scheduled installment split into principal, interest, and insurance (if applicable), each shown as an amount and a share of the total payment. ## Amortization schedule Sure generates a full amortization schedule for any loan that has an interest rate, a term, and an original balance — including variable-rate and adjustable-rate loans. The schedule uses a constant-payment (French) method: interest is charged on the outstanding principal each month, and the remainder of each payment reduces principal. This matches the table your lender uses. The interest charged each period is calculated using the loan's **Interest basis** setting. The default, 30/360, charges a flat one-twelfth of the annual rate each month. Actual/365 and actual/actual charge by the actual number of days in the period, which lets the schedule match lenders who accrue on those conventions — common for UK and Australian mortgages. To view the schedule, open a loan account and select the **Schedule** tab. The tab shows summary figures at the top: | Figure | Description | | - | - | | Opening payment | The level amount at the start of the loan | | Total interest | All interest charged over the life of the loan | | Total cost | Principal plus total interest | | Payoff date | The date of the final scheduled payment | For fixed-rate loans, the opening payment is also the contracted monthly payment for the life of the loan. For variable-rate and adjustable-rate loans, Sure re-amortises the schedule at each recorded rate change, so the payment amount can change after a rate change takes effect. The summary labels this as the opening payment rather than "the" monthly payment when the schedule re-amortises. Below the summary is a full payment table with one row per period: | Column | Description | | - | - | | # | Payment number | | Date | Scheduled payment date | | Payment | Total amount due that period | | Principal | Portion applied to the outstanding balance | | Interest | Portion charged as interest | | Remaining balance | Outstanding principal after the payment | Rows for payments whose scheduled date has already passed are shaded to distinguish elapsed periods from upcoming ones. The monthly payment shown on the loan overview is read directly from the schedule, so it is cent-accurate. For example, a $500,000 mortgage at 3.5% over 360 months shows $2,245.22 rather than a rounded figure. ### Variable-rate loans For variable-rate and adjustable-rate loans, you can record rate changes directly on the loan. Each change requires an effective date and the new annual rate. Sure re-amortises the schedule from the point of each change: the payment for periods after the effective date is resized to pay off the remaining balance over the remaining term at the new rate. The interest charged in a period always uses the rate that was in force when the period opened, so a change effective on a payment date takes effect from that payment forward — it does not retroactively change the interest already accrued in the current month. A variable-rate loan with no recorded rate changes runs at its base rate, just as a fixed-rate loan does. > [!NOTE] > > The monthly payment field on the loan overview is only shown for fixed-rate loans. For variable-rate loans, use the Schedule tab to see the current payment in force. ## Loan balance chart Loan accounts include a balance chart that shows three series together: | Series | What it shows | | - | - | | Actual (solid) | Your recorded balance from origination to today | | Scheduled (dashed) | The original contract balance from origination to the contracted payoff date | | Projected (dashed) | Where today's recorded balance is heading if you keep paying the contracted amount | The gap between the actual and scheduled lines shows whether you are ahead of or behind the original contract. The projected line starts at today's balance and ends when the loan is paid off at the contracted repayment. The chart offers a period picker with the same windows available on other account charts (month, 90 days, year, 5 years, 10 years, and all time). Each window is clamped so it never opens before the loan's origination date. Under **All**, the domain extends far enough to show every series, including the full projected payoff. The forward-looking series (scheduled and projected) are only drawn under the **All** window, since they extend past today. The summary cards beside the chart show the projection figures regardless of which period is selected. ### Tooltip Hovering over or keyboard-stepping through the chart shows a tooltip for the nearest scheduled date in the selected window. If the window contains no scheduled points, the tooltip instead stops at the dates plotted by the available series. For each scheduled payment point, the tooltip shows the remaining balance and the breakdown of that payment into principal and interest, using the same labels as the Schedule tab. The opening point (the original loan amount) carries no breakdown because it is not a payment. The actual and projected series show only the balance. ## Payoff projection The **Schedule** tab shows a payoff projection alongside the amortization table. The projection starts from your current recorded balance and applies the contracted repayment each period to show where the loan is actually heading — not where the original contract said it would be. The Schedule tab summary shows: | Figure | Description | | - | - | | Opening payment | The level amount at the start of the loan | | Total interest | All interest charged over the life of the loan | | Total cost | Principal plus total interest | | Forecasted payoff date | The date the loan will actually be paid off based on today's balance and the contracted repayment | The forecasted payoff date reflects any extra payments you have already made: if your current balance is lower than the contract expected, the projection finishes sooner and saves interest. If your balance has grown past what the contract expected, the projection may not converge — in that case the tab shows a notice instead of a date. The projection runs only to the original contracted maturity date. It does not extend the term or invent a new repayment size. This means: * A borrower who is ahead of schedule finishes earlier and saves interest. * A borrower whose balance has grown may reach the end of the contracted term still owing a balance. The tab shows that remaining balance rather than a payoff date. > [!NOTE] > > The projection is not shown when the loan has no amortization schedule (for example, if the interest rate, term, or original balance is missing), or when the current balance is zero. # Managing Investment Accounts Source: https://docs.sure.am/guides/key-concepts/investment-accounts Learn how to track holdings, trades, cost basis, and investment activity in Sure's investment and crypto accounts. # Managing Investment Accounts Investment accounts in Sure go beyond simple balance tracking. They help you understand your portfolio through holdings, trades, cost basis tracking, and investment activity labels. ## Understanding Holdings A **holding** represents your position in a specific security. For example, if you own 50 shares of Apple stock, that's one holding. Each holding tracks: * **Security** - What you own (stock, ETF, mutual fund, crypto) * **Quantity** - How many shares or units you hold * **Price** - Current market price per share * **Amount** - Total current value (quantity x price) * **Cost Basis** - What you originally paid The holdings list shows a rounded share count for readability. When you open the detail drawer for a holding, the **Shares** field displays the exact quantity with up to 8 decimal places, so you can see the precise position size for fractional shares or crypto holdings. ### Cross-account holdings roll-up The Investments panel on the dashboard and in reports aggregates your holdings by security across all investment accounts. If you hold the same security in multiple accounts — for example, Apple shares split between a brokerage and an IRA — Sure sums those positions into a single row rather than listing each account separately. Portfolio weight shown in the top holdings table and in the allocation view is calculated as a percentage of your total portfolio value (including cash). Both views share the same denominator, so the same security always shows the same weight in both places. ### Provider-synced holdings When a provider (such as SimpleFIN, SnapTrade, or CoinStats) imports your holdings, it delivers a snapshot of your positions on a specific day. Sure tracks which day each snapshot came from and only shows holdings from the **most recent provider import day** in investment views. Holdings from earlier snapshots are excluded so that stale positions do not appear alongside your current portfolio. If a provider reports prices for individual securities on different dates within the same import batch, Sure preserves those per-security price dates while still treating the entire batch as a single import day. This means your portfolio view reflects the most up-to-date information from each sync, without mixing in older snapshots. For accounts that have no provider connection, Sure shows the most recent holding per security in the account's currency from your manually entered or calculated data. Holdings recorded in a different currency than the account's base currency are excluded from the current portfolio view. #### How locks carry forward across syncs When a provider creates a new daily snapshot row for a holding you have previously locked — either a security remap lock or a cost basis lock — Sure copies those locks onto the new row automatically. This applies to all providers, including those that do not supply a per-holding unique identifier (such as Plaid, Indexa Capital, and SnapTrade securities). Without this carry-forward, a new sync would silently drop your manual corrections and replace them with the provider's values. ### Chart history and inception dates For linked investment and crypto accounts, the balance chart only displays data from the point where Sure has reliable provider history. The chart start date is determined by the earliest date your provider supplied activity or holdings data — data from before that point is excluded so the chart never shows misleading zero or estimated values. **Opening point alignment** When the chart includes the inception date (the first supported history date), Sure aligns the opening point so the chart starts at the balance before the first activity rather than after it. Without this, a first deposit of $5,000 on the opening day would appear as the starting value and the "vs. beginning" comparison would show $0 in gains instead of reflecting actual growth. There are two cases: * **Periodic sampling landed on the inception date** (for example, a daily "All" chart): the first point's closing balance already includes the day's activity. Sure resets that point to the pre-activity balance — zero, or the opening anchor balance when that anchor is dated at inception. This only applies when the inception date comes from the first provider activity date; if it comes from provider holdings data (for example, when only pending transactions exist), the first point is genuine history and is left as-is. * **Periodic sampling missed the inception date** (for example, a monthly chart that skips the exact opening day): Sure prepends an anchor point on the inception date with the correct opening balance before the first sampled point. For balance and cash views, the opening point uses the recorded opening anchor balance only when the anchor's date matches inception; otherwise it uses zero. For gains and holdings views, the opening balance is always zero. The same scoping applies to the 30-day sparkline shown in the sidebar for investment and crypto account groups. ## Recording Trades Investment accounts support manual trade entry to track your buy and sell activity. ### Trade Types When recording a trade, you can specify: * **Buy**: Purchase of securities * **Sell**: Sale of securities * **Dividend**: Dividend income (recorded as a trade with qty: 0 and price: 0) * **Interest**: Interest income (recorded as a trade with qty: 0 and price: 0) ### Recording Dividends and Interest Dividends and interest are recorded as trades to maintain data integrity: **Dividends:** * Require a security selection (the security that paid the dividend) * Recorded with qty: 0 and price: 0 * Amount represents the dividend payment received **Interest:** * Security selection is optional * If no security is selected, Sure creates a synthetic cash security for the account * Recorded with qty: 0 and price: 0 * Amount represents the interest earned This approach ensures all investment income is properly tracked while maintaining the requirement that trades reference a security. > [!NOTE] > > Some providers — including Trading 212, Interactive Brokers, Questrade, SnapTrade, Indexa Capital, and Kraken (fiat staking and earn) — deliver dividend and interest income as labeled transactions rather than as qty:0 trades. Sure counts both forms when calculating the dividend and interest totals shown on your investment summary. ### Transaction Fees Trades support an optional **fee** field to track transaction costs: * Fees are included in the total amount calculation: `qty × price + fee` * Fees default to 0 if not specified * Useful for tracking brokerage commissions, exchange fees, or other trading costs For example: * Buy 10 shares at $100/share with a $5 fee = \$1,005 total cost * Sell 10 shares at $110/share with a $5 fee = \$1,095 proceeds (fee deducted before the gain is measured) To add a fee to a trade: 1. Open the trade form (create or edit) 2. Enter the fee amount in the fee field 3. The total amount updates automatically to include the fee For acquisitions, the fee is folded into the per-share cost basis: a $5 fee on 10 shares adds $0.50 to the cost of each newly acquired share before that lot is combined with any existing position. Disposal fees do not affect the cost basis of shares you still hold. Fees are included in cost basis and gains calculations: * A purchase fee raises the cost of the lot, reducing unrealized gain while you hold the position. * A disposal fee is deducted from the sale proceeds before the realized gain is measured. ## Securities types Sure supports various security types: | Type | Examples | | - | - | | Stocks | Individual company shares (AAPL, GOOGL) | | ETFs | Exchange-traded funds (SPY, VTI) | | Mutual Funds | Pooled investment funds | | Crypto | Bitcoin, Ethereum, other cryptocurrencies | | Bonds | Fixed-income securities | ### Asset classification Each security can be classified by asset class, sub-class, sector, industry, and region. This classification data will power allocation breakdowns — letting you see how your portfolio is distributed across equities, fixed income, real estate, and other categories. **Asset classes** | Value | Description | | - | - | | `equity` | Stocks and equity-like instruments | | `fixed_income` | Bonds and other debt instruments | | `real_estate` | Real estate investment trusts and direct property | | `commodity` | Physical goods such as gold, oil, or agricultural products | | `alternative_investment` | Hedge funds, private equity, and other alternatives | | `liquidity` | Cash, money-market funds, and near-cash holdings | **Asset sub-classes** `bond`, `cash`, `collectible`, `commodity`, `cryptocurrency`, `etf`, `loan`, `mutual_fund`, `precious_metal`, `private_equity`, `real_estate`, `stock` **Sector and industry** hold the vocabulary your data provider supplies. Because different providers use different taxonomies, these fields accept any string rather than a fixed list. **Region** is derived from the security's country code against a list Sure owns, so it uses a closed vocabulary. No provider writes this field directly. **Classification source** records who set the classification: | Value | Meaning | | - | - | | `provider` | Set by a connected data provider | | `manual` | Set by you | | `ai` | Set by Sure's AI enrichment | | `default` | Applied as a fallback | **Classification locked** is a boolean flag. When `true`, no automated source — provider, AI, or default — can overwrite the classification. Sure sets this automatically when you change a security's classification manually. ## Stock splits A stock split changes a security's share count without a trade. A 2-for-1 split turns 10 shares into 20; a 1-for-10 reverse split turns 100 into 10. The money invested does not change, so the cost per share moves by the inverse of the ratio. ### How splits are applied Sure applies a split at the open of its ex-date, before that day's trades. If you hold a security on the ex-date, your share count is scaled up (or down for a reverse split) and the per-share cost is adjusted by the inverse ratio so that your total cost basis does not change. Splits are applied from your account's start date through today. A split with a future ex-date takes effect when that date arrives — it is not applied early. ### Splits on provider-synced accounts When a provider snapshot is older than the ex-date, Sure carries the snapshot forward through any splits that occurred between the snapshot date and today before applying it to your portfolio. This ensures your current holdings reflect the correct post-split share count even when a sync is delayed or the provider's data is stale. ### Precision Quantities after a split are rounded to 18 decimal places, matching the precision of the stored share count column. A scale-then-unscale round trip can land one unit in the last decimal place away from the original — this is the floor the storage format imposes and affects only negligibly small fractions of a share. ## Cost Basis Tracking Cost basis is the original purchase price of your investments. It's essential for: * Calculating gains and losses * Understanding investment performance * Tax reporting ### Cost Basis Sources Sure tracks cost basis from three sources, in order of priority: | Priority | Source | Description | | - | - | - | | 1 (Highest) | **Manual** | Values you enter directly | | 2 | **Calculated** | Computed from your trade history using weighted-average cost | | 3 (Lowest) | **Provider** | Imported from your financial institution | This hierarchy ensures your manual entries always take precedence, calculated values override provider data, and provider data is used when nothing else is available. ### How calculated cost basis works Sure uses the **weighted-average cost** method to compute your cost basis from trades: * **Buys** update the running average: the new share cost is folded into the existing position at the average weighted by quantity. Any acquisition fee is included in the per-share cost — a $5 fee on 10 shares adds $0.50 to the cost of each newly acquired share before that lot is combined with any existing position. * **Sells** relieve the position at the current average cost, leaving the per-share average unchanged for the shares that remain. A disposal fee does not affect the basis of the remaining shares. * **Full liquidation** resets the tracker completely. If you sell your entire position and buy again later, the new lot starts from a clean basis — the old (realized) lots do not carry over and corrupt the new position's cost basis. * **Outbound transfers** (shares moved to another account you own) are treated the same as sells: they relieve the running average so the transferred shares no longer affect the basis of any shares remaining in the account. Price and fee conversions for foreign-currency trades use a rate carried by the trade when available, otherwise the rate for the trade's date. If the required conversion rate is unavailable, the calculated basis is unknown rather than using today's rate or treating the currencies as equal. This means `avg_cost` on a holding — shown in the holdings list, the holding drawer, and the API — reflects only the cost of the shares you currently hold, not an average across every purchase the account ever made for that security. ### Transfers and cost basis When securities are transferred **into** an account, Sure cannot determine what those units originally cost. Because the purchase happened elsewhere — at a price nothing in this account recorded — any calculated cost basis for that position would be fabricated rather than real. Sure marks the position's cost basis as unknown so you are not shown a misleading figure. When securities are transferred **out** of an account, Sure does not touch the cost basis of the shares that remain. Those remaining shares came from real purchases this account recorded, and their cost basis is correct. You can set it manually if you need to record it explicitly. Once you sell all of the transferred shares and the position reaches zero, Sure releases the unknown mark. Any shares you buy after that point are treated as a fresh purchase with a known cost basis, so gains and losses calculate correctly from that repurchase forward. > [!NOTE] > > Only a calculated cost basis is cleared on an inbound transfer. If you have set a manual cost basis, or your institution provided one, Sure keeps that value — it represents an explicit assertion about what the position cost, which the app respects. ### Setting cost basis manually You can set cost basis from the holdings list or the holding drawer. **From the holdings list:** 1. Navigate to your investment account. 2. Find the holding in your portfolio. 3. Click the pencil icon next to the average cost. 4. The editor shows two input fields with the quantity between them: **Per share** × quantity = **Total cost basis**. Enter a value in either the per-share field or the total field — Sure fills in the other automatically. The quantity is shown as plain text between them. 5. Click **Save**. If a cost basis is already set, Sure shows an "Overwrite cost basis?" confirmation — click **Confirm** to replace it. **From the holding drawer:** 1. Click on a holding to open its detail drawer. 2. In the Overview section, click the pencil icon next to "Average Cost". 3. Edit the per-share or total value. 4. Click **Save**. Sure asks for confirmation if you are overwriting an existing cost basis. The total field helps calculate the per-share cost but is not saved directly. The editor stores a per-share cost with up to four decimal places, so sub-cent prices (such as 0.0049 per share) are preserved exactly. Pasting a value into either field keeps sub-cent precision without rounding to two decimal places. A stored cost basis of zero is shown as 0.00 in the editor so you can review it. If Sure does not know the cost basis (for example, for shares received from an inbound transfer), both fields are left empty — the per-share field is required, and submitting an empty value does not change the holding. > [!TIP] > > Enter either the per-share cost or the total — Sure calculates the other in real time. ### Lock Protection When you manually set a cost basis, Sure automatically **locks** it to prevent automatic updates from overwriting your value. You'll see a lock icon indicating the value is protected. This ensures your manual entries remain intact during account syncs. When a provider sync creates a new daily holding row, Sure carries the lock forward onto that row, including for providers that do not supply a per-holding unique identifier (Plaid, Indexa Capital, and SnapTrade securities). ### Unlocking Cost Basis If you want Sure to recalculate cost basis from your trades: 1. Open the holding drawer 2. Scroll to the **Settings** section 3. Find "Cost basis locked" 4. Click **Unlock** 5. Confirm the action in the dialog that appears After unlocking: * The lock icon disappears * Future syncs can update the cost basis * Calculated values (from trades) will replace the manual value ### Resetting a remapped security If you have remapped a holding to a different security and want to restore the provider's original security: 1. Open the holding drawer 2. Scroll to the **Settings** section 3. Find the remapped security notice 4. Click **Reset to provider** 5. Confirm the action in the dialog that appears After resetting, the holding returns to the security your provider originally sent. The security lock is removed and future syncs will use the provider's value. ## Recording Trades Investment accounts support recording various types of trades to track your portfolio activity. ### Trade Types | Type | Description | Security Required | | - | - | - | | **Buy** | Purchase of securities | Yes | | **Sell** | Sale of securities | Yes | | **Dividend** | Dividend payments received | Yes | | **Interest** | Interest earned on cash or securities | No (optional) | | **Deposit** | Cash added to the investment account from another account | No | | **Withdrawal** | Cash removed from the investment account to another account | No | ### Deposits and withdrawals A deposit or withdrawal moves cash between your investment account and a second account (the transfer account). Because the trade books an entry on both sides, Sure requires write access on the transfer account — the same requirement that applies when creating a transfer directly. The transfer account picker only shows accounts you can write to. If an account is shared with you as view-only, it does not appear in the list. When using the API, passing a `transfer_account_id` that belongs to a read-only or inaccessible account returns a `404 Not Found` response. ### Recording Dividends and Interest Dividends and interest are recorded as trades with zero quantity and zero price, allowing them to be associated with specific securities while maintaining data integrity. **Dividends:** * Require a security selection (the stock/fund paying the dividend) * Recorded as a trade with qty: 0 and price: 0 * Amount represents the dividend payment received **Interest:** * Security selection is optional * When no security is selected, Sure creates a synthetic cash security for the account * Recorded as a trade with qty: 0 and price: 0 * Amount represents the interest earned To record a dividend or interest payment: 1. Navigate to your investment account 2. Click **+ New Trade** 3. Select **Dividend** or **Interest** from the type dropdown 4. For dividends: Select the security that paid the dividend 5. For interest: Optionally select a security, or leave blank for cash interest 6. Enter the amount received 7. Set the date 8. Click **Save** > [!NOTE] > > Dividends require a security selection, while interest can be recorded without one. When no security is selected for interest, Sure automatically creates a per-account synthetic cash security (kind: `cash`, offline: `true`) to maintain data integrity. Some providers — including Trading 212, Interactive Brokers, Questrade, SnapTrade, Indexa Capital, and Kraken (fiat staking and earn) — import dividend and interest income as labeled transactions rather than as qty:0 trades. Sure counts both forms when calculating the totals shown on your investment summary. Income-labeled outflows such as margin-interest charges or dividend reversals reduce the total rather than adding to it. ### Trade Fees All trades support an optional fee field to track transaction costs: * Fees are included in the total amount calculation: `total = (qty × price) + fee` * Fees default to 0 if not specified * A purchase fee is added to the lot cost, so it reduces your unrealized gain while you hold the position * A disposal fee is deducted from the sale proceeds before the realized gain is measured ## Investment Activity Labels Activity labels help you classify investment transactions. They appear as badges in your transaction list and help you understand your investment activity at a glance. The quick-edit activity badge, its label picker, and the transaction detail select use the translated activity label, falling back to the stored label when no translation exists. The trade detail header uses its own translations: when it has wording for the recorded activity, it displays that translated name. When the label is absent or has no header wording, it falls back to "Buy" for a positive entry amount and "Sell" otherwise. ## Recording Dividends and Interest Dividends and interest are recorded as **trades** with zero quantity and zero price. This approach maintains data integrity while properly tracking investment income: * **Dividends** require a security to be selected (the stock or fund paying the dividend) * **Interest** can optionally specify a security, or will use a synthetic cash security for the account * Both appear in your holdings and trade history * Both are properly labeled with their respective activity types * The zero-quantity, zero-price approach preserves the trade model's required security association When creating a dividend or interest transaction: 1. Select **Dividend** or **Interest** from the trade type dropdown 2. For dividends: Choose the security paying the dividend (required) 3. For interest: Optionally select a security, or leave blank to use the account's cash position 4. Enter the amount received 5. The trade is created with qty: 0 and price: 0, maintaining the security association Some providers import dividend and interest income as labeled transactions rather than as qty:0 trades. Sure counts both forms in your investment totals, so the figures on your investment summary are accurate regardless of how your provider delivers the data. ## Trade Fees All trades support an optional **fee** field to track transaction costs like brokerage commissions, exchange fees, or other trading expenses. ### How fees work * Fees are included in the total transaction amount: `Total = (Quantity × Price) + Fee` * Fees default to 0 if not specified * A purchase fee is added to the lot cost. This raises your cost basis per share, so unrealized gain is lower while you hold the position. * A disposal fee is deducted from the sale proceeds before the realized gain is calculated. ### Adding fees to trades When creating or editing a trade: 1. Enter the quantity and price as usual 2. Add the fee amount in the **Fee** field 3. The total amount updates automatically to include the fee 4. Save the trade Example: Buying 10 shares at $50 with a $5 commission: * Quantity: 10 * Price: \$50 * Fee: \$5 * \*\*Total cost: $505** (10 × $50 + $5), giving a cost basis of $50.50 per share Fees affect: * Cost basis and unrealized gain (purchase fees) * Realized gain and the investment sales report (disposal fees) * Tax reporting and record keeping ### Available Activity Labels | Label | Description | | - | - | | **Buy** | Purchase of securities | | **Sell** | Sale of securities | | **Contribution** | Money added to the investment account | | **Withdrawal** | Money removed from the investment account | | **Dividend** | Dividend payments received (recorded as trades with qty: 0) | | **Interest** | Interest earned (recorded as trades with qty: 0) | | **Reinvestment** | Dividends or distributions reinvested | | **Sweep In** | Cash swept into the account | | **Sweep Out** | Cash swept out of the account | | **Fee** | Account or transaction fees | | **Exchange** | Currency or security exchanges; security exchanges appear in the sales report | | **Transfer** | Asset moved to another account you own; excluded from sales report | | **Other** | Miscellaneous transactions | > [!NOTE] > > Dividends and interest are recorded as trades with zero quantity and zero price. Dividends require a security selection, while interest can optionally use a synthetic cash security if no specific security is selected. ### Setting Labels Manually 1. Open a transaction from an investment or crypto account 2. Scroll to the **Settings** section 3. Find "Activity type" 4. Select a label from the dropdown 5. The change saves automatically ### Setting Labels with Rules Create rules to automatically label transactions based on patterns: 1. Go to **Settings > Rules** 2. Create a new rule 3. Set conditions (e.g., "IF transaction name contains 'DIVIDEND'") 4. Add action: "Set investment activity label" 5. Choose the label (e.g., "Dividend") 6. Save the rule Example rules: * IF name contains "DIVIDEND" THEN set label to "Dividend" * IF name contains "INTEREST" THEN set label to "Interest" * IF name contains "FEE" THEN set label to "Fee" > [!NOTE] > > Transfer, Sweep In, and Sweep Out are excluded from budget calculations and from the investment sales report, since they represent assets moving between accounts you own rather than actual sales. Exchange is excluded from budget calculations, but security exchanges remain in the investment sales report because they can represent a taxable disposition. ## Tax Treatment Categories Investment accounts have different tax implications based on their type: | Category | Description | Examples | | - | - | - | | **Taxable** | Gains taxed when realized | Brokerage, Cash Management Account (CMA), UGMA/UTMA | | **Tax-Deferred** | Taxes deferred until withdrawal | 401(k), Traditional IRA, 403(b) | | **Tax-Exempt** | Qualified gains are tax-free | Roth IRA, Roth 401(k), ISA | | **Tax-Advantaged** | Special tax benefits with conditions | 529 Plan, HSA | Sure automatically assigns tax treatment based on account subtype, but you can adjust it manually if needed. ## How investment cash flows are classified Eligible trades and transactions in investment or crypto accounts are assigned one of five flow classes. Sure uses these classes to compute portfolio returns, allocation breakdowns, and income figures consistently. | Class | What it covers | | - | - | | **External inflow** | Money or assets arriving from outside the scope being measured (a deposit, a contribution) | | **External outflow** | Money or assets leaving the scope (a withdrawal) | | **Income** | A dividend or interest payment | | **Fee** | An account fee or commission | | **Internal** | A buy, sell, reinvestment, sweep, exchange, or a transfer whose other leg sits inside the same scope | Classification considers the entry type, activity label, transaction kind, attached transfer fees, and whether a transfer counterpart falls inside the scope being measured. A transfer between two of your brokerage accounts is **internal** when you are looking at your whole portfolio, but **external** (an outflow from one account and an inflow to the other) when you are looking at either account on its own. Activity labels map to flow classes as follows: | Label | Flow class | | - | - | | Dividend | Income | | Interest | Income | | Fee | Fee | | Buy | Internal | | Sell | Internal | | Reinvestment | Internal | | Sweep In | Internal | | Sweep Out | Internal | | Exchange | Internal | | Contribution | External by direction; a linked cash transaction is internal when its counterpart is in scope | | Withdrawal | External by direction; a linked cash transaction is internal when its counterpart is in scope | | Transfer | Internal if the other leg is in scope; external by direction otherwise | Excluded entries, pending transactions, and valuation entries do not count in any class. Contribution and Withdrawal labels on trades use quantity direction; the linked-counterpart exception in the table applies to cash transactions. Attached transfer-fee transactions are classified as fees before their activity label is considered. Setting the correct activity label on an entry is the primary way you control how it affects your portfolio return figures. An unlabeled deposit transaction with no in-scope transfer counterpart is classified as an external inflow and excluded from the investment return; a dividend labelled as a contribution would be counted as a cash flow in rather than as income. Use the activity label selector in the entry detail view to correct misclassified entries. ## Portfolio returns: time-weighted vs. money-weighted Sure tracks two different return figures for your investments, because no single number answers every question about performance. **Time-weighted return (TWR)** measures what the investments themselves did. It strips out the effect of your cash flow timing — when you added money or withdrew it — so you can compare your portfolio against a benchmark on equal terms. **Money-weighted return (MWR)** measures what you, the investor, got. It is the internal rate of return (IRR) of your actual cash flows: money you put in is negative, money you took out or the terminal value of the portfolio is positive. Two investors holding the same fund over the same year, one of whom bought most of their position the week before a large fall, did not have the same year — MWR captures that difference. ### How Sure calculates the money-weighted return Sure solves for the rate that makes the present value of your cash flows equal to zero. The solver uses Newton-Raphson with a bisection fallback: * Newton converges in a handful of iterations for most portfolios. * Every loss and other ill-conditioned series is handed off to bisection, which is slower but cannot diverge. * The result is expressed as an annualised rate unless the period is short enough that annualising would produce an unreliable extrapolation, in which case the period rate is used instead. The returned rate is a `BigDecimal` rounded to the same precision Sure uses for all monetary figures. ### When a money-weighted return is not available Three situations produce no rate rather than an approximate one: | Situation | Reason | | - | - | | All cash flows go the same direction | No rate exists — money only went in, or only went out | | All flows fall on the same date | No time passes, so no annual rate can be defined | | The solver does not converge | The series has no rate the algorithm can reach within its tolerance | In each case Sure shows nothing rather than a fallback guess. ### Series with more than one valid rate A cash flow series that changes sign more than once can have two rates that both satisfy the equation — for example, a portfolio with a withdrawal between two deposits. Sure returns the rate the solver reaches from its starting point (10%), which matches the behaviour of Excel's XIRR function. The `ambiguous?` flag on the calculation is a conservative signal: `false` guarantees the figure is the only rate that fits; `true` means it may be one of several. Over-hedging a unique figure is a smaller error than presenting one of several as definitive. > [!NOTE] > > The money-weighted return display in the UI is coming in a follow-up release. The calculation engine described here is already in place. ## Understanding Gains and Losses Sure helps you track two types of gains: ### Unrealized Gains/Losses Paper gains or losses on holdings you still own: ``` Unrealized Gain = Current Value - Cost Basis ``` Cost basis includes any purchase fee: if you bought 10 shares at $100 with a $5 fee, your cost basis is $1,005 — not $1,000. If those shares are now worth $1,200, your unrealized gain is $195. ### Realized Gains/Losses Actual gains or losses from securities you've sold. These are what matter for taxes. Fees are included in the calculation on both sides: the purchase fee is part of your cost basis, and the sale fee is subtracted from your proceeds. For example, if you bought 10 shares at $100 with a $5 purchase fee and sold them at $110 with a $3 sale fee, your realized gain is `(10 × $110 − $3) − (10 × $100 + $5) = $1,097 − $1,005 = $92`. The **Trend** indicator on each holding shows your unrealized gain or loss, calculated from your cost basis. If cost basis is unknown (no trades and no manual entry), the trend won't display. Trades labeled **Transfer**, **Sweep In**, or **Sweep Out** are not counted as sales in the investment report. These labels mean the asset moved to another account you own, so no gain or loss is realized. The investment report excludes them and `realized_gain_loss` returns nothing for them. Trades labeled **Exchange** are included in the report. For cash this label means a currency exchange, which is internal. For a security it covers a security-for-security exchange, which can dispose of an appreciated asset. Because the two cases are not distinguishable by label alone, and because a missing realized gain is harder to spot than an extra line, exchange trades on securities remain visible so you can review them. ### Multi-currency gains and cost basis When a security is priced in a different currency from the one your account uses, Sure converts amounts into the account currency before calculating gains. There is no fallback to a nearby date and no default rate of 1.0 — if the rate for a given day is missing, Sure treats the figure as unknown rather than showing an incorrect one. **Realized gains:** Sure converts sale proceeds at the exchange rate for the disposal date. If that rate is missing, no realized gain figure is shown for that trade. **Cost basis and unrealized gains:** If a purchase was made in a foreign currency and neither a usable trade-level rate nor a rate for that purchase date is available, Sure marks the cost basis as unknown. The calculated basis remains unknown until the needed conversion is available and the holding is recalculated, or a usable provider or manual cost basis supplies it. Exchange rates that are zero or negative are treated the same as missing. A bad rate in the database does not silently produce a wrong figure. If a gain or cost basis figure is absent for a foreign-currency position, check that an exchange rate exists for the security's currency against your account's currency on the relevant date. You can add missing rates at **Settings → Exchange rates**. Some data providers (such as IBKR via Flex reports) supply a trade-level exchange rate alongside each transaction. When this rate is present, Sure uses it for cost basis calculations and falls back to the exchange-rate table only if no trade-level rate was provided. ### Automatic exchange rate import for foreign-currency securities When an account holds securities priced in a currency other than the account currency — for example, a USD-priced crypto asset in a EUR account — Sure automatically imports exchange rates for those price currencies during each sync. Rates are fetched starting from the first date the account needs a price for each security, based on your own trades and holdings rather than the security's global price history. Security prices are imported before exchange rates so the relevant currencies are known at the start of each sync. Only price currencies that have a price on or after the first required date are included, so currencies from older listings used by other accounts do not trigger unnecessary rate imports. This means the portfolio cache can always convert each security price into your account currency without falling back to live per-day provider requests. Syncs that previously repeated hundreds of exchange rate lookups because rates were missing from the database complete in normal time after upgrading. ## Crypto-Specific Features Crypto accounts work similarly to investment accounts but have unique characteristics: | Subtype | Description | Manual Trades | Transaction-to-trade conversion | | - | - | - | - | | Wallet | Self-custody or provider-synced | No | No | | Exchange | Centralized exchanges (Binance, Coinbase, etc.) | Yes | Yes | * **Exchange accounts** support manual trade entry, letting you record buys and sells * **Wallet accounts** are sync-only, holdings are updated through provider connections Crypto is taxable by default, though it can be held in tax-advantaged accounts (for example, a self-directed IRA). ### Converting a transaction to a trade (crypto exchange accounts) When a provider syncs your crypto exchange account as plain transactions rather than trades, you can convert an eligible, non-excluded transaction into a trade directly from the activity feed. To convert a transaction: 1. Open your crypto exchange account and go to the **Activity** tab. 2. Click the activity label badge on the transaction you want to convert. 3. Select **Buy** or **Sell** from the label picker. Sure opens a conversion form pre-populated with the transaction's amount and date. 4. Enter either a **quantity** or a **price per unit** — Sure calculates the missing value from the transaction amount automatically. 5. Select the security (cryptocurrency) from the list, or choose **Enter custom ticker** to type one in. 6. Confirm the details and submit the form. Sure creates a new trade entry and marks the original transaction as excluded. The original transaction's name and date are preserved in a note on the trade. If the price you enter (or the price implied by the quantity you enter) differs from the security's current market price by more than 50%, Sure shows a warning. This is not an error — it means you may have selected the wrong security or entered an unusual value. Review the ticker and amount before saving. > [!NOTE] > > This conversion is not available for wallet-type crypto accounts. Only exchange accounts (`subtype: "exchange"`) support trades and transaction conversion. Excluded transactions cannot be converted, including originals excluded by an earlier conversion. Re-including the original removes that exclusion, so avoid converting it again and creating a duplicate trade. ## Adding Investment Accounts 1. Click **+ Add Account** on your dashboard 2. Select **Investment** or **Crypto** 3. Choose the appropriate subtype (see [Account Types](./account-types.mdx) for all options) 4. Enter your account details: * Account name * Current balance * Tax treatment (if different from default) 5. Click **Create Account** After creating the account, you can add holdings manually or connect a provider to sync them automatically. # Transfers Between Accounts Source: https://docs.sure.am/guides/key-concepts/transfers Learn how transfers work in Sure, including transfer types, automatic matching, and how transfers affect your budgets and net worth. # Transfers Between Accounts A transfer moves money between your own accounts. Unlike income or expenses, transfers don't change your net worth—they simply move funds from one place to another. ## How Transfers Work Every transfer consists of two linked transactions: 1. **Outflow** - Money leaving one account (negative amount) 2. **Inflow** - Money entering another account (positive amount) These two transactions are linked together as a single transfer. ### Example: Moving Money to Savings When you transfer \$500 from checking to savings: | Account | Transaction | Amount | | - | - | - | | Checking | Outflow | -\$500 | | Savings | Inflow | +\$500 | | **Net Effect** | | **\$0** | Your total net worth stays the same—the money simply moved from one account to another. ## Transfer Types Sure recognizes different types of transfers based on the destination account: | Transfer Type | When It's Used | Budget Impact | | - | - | - | | **Funds Movement** | Between asset accounts, including investment/crypto accounts | Excluded | | **CC Payment** | Payment to a credit card | Excluded | | **Loan Payment** | Payment to a loan account | Treated as expense | | **Investment Contribution** | From a non-investment, non-crypto account to an investment or crypto account | Treated as expense by default (can be overridden) | ### Funds Movement General transfers between asset accounts: * Checking to savings * Savings to money market * Between investment accounts These are excluded from budgets because they don't represent spending or income. ### Credit card payment When you pay your credit card bill, Sure creates a `cc_payment` transfer: * Outflow from your checking account * Inflow to your credit card (reducing your debt) This is excluded from budgets because the spending already happened when you used the credit card. When syncing transactions from a provider, Sure automatically classifies transactions to credit card accounts as credit card payment transfers. ### Loan payment Payments to loan accounts (mortgage, auto, student loans) are treated as `loan_payment` transfers. > [!NOTE] > > Loan payments are treated as expenses in budgets since they represent an ongoing financial obligation, even though they also reduce your debt. For a matched loan payment, assign a category, merchant, and tags on the outflow transaction; the inflow shows the outflow category read-only. When syncing transactions from a provider, Sure automatically classifies transactions to loan accounts as loan payment transfers. ### Investment Contribution Transfers from a non-investment, non-crypto account to an investment or crypto account: * Contributing to your 401(k) * Adding funds to a brokerage account * Moving money to a crypto exchange By default, investment contributions from a non-investment, non-crypto account are tracked as expenses in budgets. An admin can turn off **Count investing as spending** in **Settings → Preferences** to exclude investment contributions from spending across the family. Existing account and transaction exclusions still apply. Transfers between investment or crypto accounts remain funds movements and are excluded. For a matched contribution, assign a category, merchant, and tags on the outflow transaction; the inflow shows the outflow category read-only. #### Counting a transfer as a plain transfer instead If you use a brokerage or crypto account purely to convert currency — moving money in and straight back out — the contribution would normally count as spending when **Count investing as spending** is enabled. You can override this on a confirmed transfer from a non-investment, non-crypto account to an investment or crypto account, provided you have write access to both accounts. Open the transfer's outflow transaction and look for the **Investment contribution** toggle in the Details section, next to the category field. Turning the toggle off reclassifies the outflow as a funds movement, removes the auto-assigned Investment Contributions category, and excludes it from budget spending. The choice is saved and persists through provider syncs; unlinking the transfer resets it. The same change can also be made by the AI assistant or an MCP agent using the `update_transfer` tool. ## Creating Transfers Manually To create a transfer: 1. Go to the **Transactions** page 2. Click **+ New Transaction** 3. Select **Transfer** 4. Choose: * **From account** - Where money is coming from * **To account** - Where money is going * **Amount** - How much to transfer * **Date** - When the transfer occurred 5. Click **Add transaction** Sure automatically creates both the outflow and inflow transactions and links them together. The **From** and **To** selectors support search — type part of an account name to filter the list. Only active accounts appear. Disabled accounts are not available when creating a transfer. ## Automatic Transfer Matching When you sync accounts with a provider (Plaid, SimpleFIN, etc.), Sure attempts to automatically match transfers between accounts. ### How Matching Works Sure looks for transaction pairs that: * Are from different accounts in the same family * Have opposite amounts (one positive, one negative) * Occurred within a date window ### Date Windows | Transaction Status | Window | | - | - | | Pending transactions | 4 days | | Confirmed transactions | 30 days | ### Suggested matches When Sure finds a potential transfer match, it creates a **pending** transfer suggestion. You can: 1. **Confirm** - Accept the match and link the transactions as a transfer 2. **Reject** - Dismiss the match (transactions remain separate and keep their existing kinds and categories) To review suggested transfers: 1. Open a transaction that may be part of a transfer 2. Look for transfer match suggestions 3. Confirm or reject as appropriate **What changes at confirmation:** * Sure assigns the appropriate transfer kind (funds movement, CC payment, investment contribution, etc.) to both legs at the moment you confirm — not when the suggestion first appears. * If the outflow has no category, the destination is an investment or crypto account, and the source is neither an investment nor a crypto account, Sure assigns the Investment Contributions category automatically. * Any notes on the transfer are preserved when you confirm from the transaction list. **What stays the same while a match is pending:** * The suggestion itself leaves both transactions’ existing kinds, categories, and reporting treatment unchanged. * The pending suggestion does not remove category editing; existing permission and transaction-kind restrictions still apply. * The pending suggestion itself does not add a Transfer badge. * The pending suggestion does not itself exclude either transaction from budgets or income-statement totals. **When you reject a match:** * If a transaction already had a kind (for example, one you set manually), that kind is preserved — rejection does not reset it. ## Cross-Currency Transfers When transferring between accounts with different currencies: * Sure validates that amounts have opposite signs * The exact amounts don't need to match (due to exchange rates) * Both transactions are linked as a transfer Example: Transferring from a USD checking account to a EUR savings account: | Account | Currency | Amount | | - | - | - | | US Checking | USD | -\$1,000 | | Euro Savings | EUR | +€920 | The transfer is valid because one amount is negative and one is positive, even though the numbers differ due to the exchange rate. ### How exchange rates are looked up Sure syncs exchange rates from each account's currency to your family currency. For a transfer between two non-family currencies — for example, RUB to THB in a USD family — there is no direct RUB→THB rate stored. Sure derives the cross rate through the family currency instead: (RUB→USD) / (THB→USD). This means automatic matching works for transfers between any two currencies as long as both have a rate against the family currency, not just transfers that involve the family currency directly. When a direct rate exists, Sure uses it. The derived rate is only used when no direct pair rate is available or when the direct rate is zero. Exact same-currency matches (where amounts are equal and no FX math is involved) are always ranked ahead of FX-tolerance guesses, so a coincidental cross-currency candidate cannot claim a transaction that has a real exact-amount counterpart. ### Automatic matching and manual accounts During a sync, Sure uses a tolerance band around the exchange rate to find cross-currency transfer pairs automatically. This automatic path only considers accounts that have a live provider connection (Plaid, SimpleFIN, or another connected provider). Manual accounts — those with no institution behind them — are excluded from automatic cross-currency matching because a coincidental pair of round-number transactions in different currencies could fall inside the tolerance band and be silently linked as a transfer. There is one exception: if those two accounts already have a confirmed transfer in the same direction, including when one or both accounts are manual, Sure treats that as a known route and will auto-match future transfers along it. The prior confirmed route need not itself have used different currencies. Future cross-currency candidates must still meet the normal matching checks and are created as pending suggestions; an unconfirmed suggestion cannot establish a route. Manual accounts still participate in same-currency matching, where amounts must be exactly equal and no FX approximation is involved. If you have a real cross-currency transfer that involves a manual account, you can still confirm it yourself. Open either transaction, choose **Match as transfer**, and select the counterpart from the dialog. The manual match dialog uses a wider tolerance (up to 10%) and shows manual account candidates so you can find and confirm the match by hand. ### Write access requirement for auto-matching For a transfer pair to be created automatically, at least one family member must have write access to both accounts involved. Ownerless accounts have the exception described below. Write access means being the account owner or having a full-control share on the account. An account whose owner has been removed from the family (owner nullified) does not block auto-matching on its own. A member who can write to the other side is sufficient, since they can still reject the match. Two accounts that nobody in the family can write to are skipped entirely. The automatic matcher checks the two endpoint accounts. Rejecting or unlinking a transfer uses a separate permission check: you need write access to at least one endpoint and to every account holding an attached fee transaction, because unlinking removes those fee transactions. ## Categorizing Transfers For transfers where a category is meaningful (investment contributions and loan payments), Sure assigns the category to the outflow leg — the transaction in the spending account that budgets and reports count. The inflow leg of the same transfer displays the outflow's category as a read-only field. Editing the category on the inflow side has no effect; changes must be made on the outflow leg. This ownership is based on the Transfer record itself, not the leg's transaction kind. If a provider sync updates a leg's kind, the category assignment does not change. ## Transfer Summary Totals When viewing your transaction list filtered by transfers, Sure displays **Inflow** and **Outflow** totals instead of the standard Income and Expenses labels. ### How It Works **Transfer-only filter:** * When filtering exclusively by "Transfer" type, the summary bar shows: * **Inflow**: Total positive transfer amounts (money coming in) * **Outflow**: Total negative transfer amounts (money going out) **Mixed filters:** * When filtering by transfers along with other transaction types (income, expenses), the summary bar shows standard Income/Expenses labels * Transfer amounts are excluded from these totals since they don't represent actual income or spending This helps you understand your cash movement patterns when reviewing transfers in isolation. > [!NOTE] > > When filtering by both transfers and other transaction types, transfer amounts are excluded from income and expense totals to avoid confusion. ### Currency display in transfer-only days When a day's entries are all transfers, every entry is excluded from the total, leaving a zero balance. Sure displays that zero in the original currency of the day's entry group rather than defaulting to your family currency. For example, a group of GBP entries containing only transfers shows £0.00, even when the family currency is USD. This keeps currency symbols consistent across your transaction list regardless of how many transfers a day contains. ## How Transfers Affect Budgets Transfers are generally **excluded** from budget calculations because they don't represent actual spending or income: | Transfer Type | Budget Treatment | | - | - | | Funds Movement | Excluded | | CC Payment | Excluded | | Investment Contribution | Treated as expense by default (can be overridden — see [Counting a transfer as a plain transfer instead](#counting-a-transfer-as-a-plain-transfer-instead)) | | Loan Payment | Treated as expense | > [!NOTE] > > Loan payments are treated as expenses in budgets. Investment contributions count as spending by default, subject to **Count investing as spending** and existing account and transaction exclusions. For matched transfers, assign a category, merchant, and tags on the outflow transaction. A pending auto-match does not itself change budget or income-statement treatment. Confirmation assigns the transfer kinds; reporting then follows those kinds and any existing exclusions. Transactions that already had excluded kinds or were manually excluded remain subject to those rules while a suggestion is pending. ## Understanding Net Worth Impact Transfers are **zero-sum** for net worth: * Moving \$500 from checking to savings: Net worth unchanged * Paying \$500 to credit card: Net worth unchanged (reduced cash = reduced debt) * Contributing \$500 to 401(k): Net worth unchanged (reduced cash = increased investments) The only time a transfer affects net worth is if there are fees involved (which would be a separate expense transaction). ## Common Transfer Scenarios ### Paying Off a Credit Card 1. Money leaves your checking account (-\$500) 2. Credit card balance decreases (-\$500 debt) 3. Net worth: unchanged ### Making a Mortgage Payment 1. Money leaves your checking account (-\$2,000) 2. Loan balance decreases (-$1,700 principal, $300 goes to interest) 3. Note: The interest portion is technically an expense > [!IMPORTANT] > > Mortgage payments include both principal (reducing debt) and interest (an expense). Sure tracks the full payment as a loan transfer, but the interest portion represents a true cost. ### Contributing to Retirement 1. Money leaves your checking account (-\$500) 2. Investment account balance increases (+\$500) 3. Net worth: unchanged (cash converted to investments) ### Transferring Between Banks 1. Money leaves Bank A checking (-\$1,000) 2. Money arrives at Bank B checking (+\$1,000) 3. Net worth: unchanged ## Troubleshooting Transfers ### Duplicate Transactions If you see both a transfer and separate expense/income transactions: * Check if the transactions should be linked as a transfer * Confirm or reject the transfer suggestion * Delete duplicate transactions if needed ### Duplicate transfer from double-submit If you submit the transfer form twice in quick succession (double-click, browser retry, or two simultaneous requests), Sure creates only one transfer. A per-form idempotency key is generated when the form loads and sent with each submission. The first request to reach the database wins; any subsequent request with the same key returns the already-created transfer instead of inserting a duplicate. If a transfer is rejected or deleted after creation, the idempotency key is cleared from its entries so a later retry creates a fresh transfer rather than returning an error. ### Transfer matching stops mid-sync When two account syncs run at the same time, each transfer candidate is matched in its own isolated savepoint. A conflict on one pair no longer affects the others, so all remaining candidates continue to be processed. ### Unmatched Transfers If Sure didn't automatically match a transfer: * The amounts may not match exactly (due to fees or timing) * The dates may be too far apart * You can manually create a transfer to link them ### Wrong Transfer Type If a transfer is categorized incorrectly: * Check that both accounts are the correct type * The transfer type is determined by the destination account # How Asset Accounts Work Source: https://docs.sure.am/guides/key-concepts/untitled-page Learn how asset accounts track things you own, how transactions affect balances, and the different types of asset accounts available in Sure. # How Asset Accounts Work Assets are things you own that have monetary value. In Sure, asset accounts track your wealth—from the cash in your checking account to the value of your home. ## Understanding Asset Balances Asset account balances work intuitively: * **Income increases your balance** (money coming in) * **Expenses decrease your balance** (money going out) ### Example: Checking Account Let's walk through a simple example: | Action | Balance Change | New Balance | | - | - | - | | Starting balance | — | \$1,000 | | Paycheck deposit (+\$2,500) | +\$2,500 | \$3,500 | | Rent payment (-\$1,200) | -\$1,200 | \$2,300 | | Grocery shopping (-\$150) | -\$150 | \$2,150 | This matches what you see in your bank account—straightforward and predictable. ## Types of Asset Accounts Sure supports six types of asset accounts: ### Cash (Depository) Liquid funds you can access immediately. Includes: | Subtype | Description | | - | - | | Checking | Everyday spending account | | Savings | Interest-bearing savings | | HSA | Health Savings Account | | CD | Certificate of Deposit | | Money Market | Money market account | ### Investment Accounts that hold securities like stocks, bonds, and mutual funds. Investment accounts have additional features for tracking holdings, trades, and cost basis. See [Managing Investment Accounts](./investment-accounts.mdx) for details. ### Crypto Cryptocurrency holdings, either in: | Subtype | Description | | - | - | | Wallet | Self-custody or provider-synced wallets | | Exchange | Centralized exchanges with trade history | > [!NOTE] > > Only exchange accounts support manual trade entry. Wallet accounts are sync-only. ### Property Real estate you own: | Subtype | Description | | - | - | | Single Family Home | Primary residence | | Multi-Family Home | Duplex, triplex, etc. | | Condominium | Condo unit | | Townhouse | Townhouse property | | Investment Property | Rental or investment real estate | | Second Home | Vacation home | Property accounts can track additional details like address, area (square footage), and year built. When adding a property, you can look up the estimated market value automatically using a valuation provider (RentCast, Realie, or Chimnie). The provider returns the property details and an estimated value which you review before the account is created. Sure then refreshes the value on a monthly schedule. If you added a property manually without a provider, you can link one later from the property's Overview tab, when you have write access, the full address is in the provider’s supported country, and the account currency matches. This later-linking option supports configured RentCast or Realie connections; Chimnie requires its identifier during property creation. See [property valuations](/providers/property-valuations) for setup and configuration details. ### Vehicle Cars, trucks, motorcycles, and other vehicles you own. Vehicle accounts can track make, model, year, and mileage. ### Other Asset Anything else of value that doesn't fit the categories above: * Collectibles (art, antiques, coins) * Jewelry and watches * Equipment * Other valuables ## Liquid vs. Illiquid Assets Sure distinguishes between liquid and illiquid assets: **Liquid assets** can be quickly converted to cash without significant loss of value: * Cash accounts (checking, savings) * Most investments (stocks, bonds, ETFs) **Illiquid assets** take time to sell or may lose value if sold quickly: * Property * Vehicles * Some investments (private equity, real estate funds) * Other assets (collectibles, jewelry) This distinction helps you understand not just your total net worth, but how much of it you could access quickly if needed. ## How Assets Affect Net Worth Your net worth is calculated as: ``` Net Worth = Total Assets - Total Liabilities ``` Every asset account contributes positively to your net worth. When asset values increase (your investments grow, your home appreciates), your net worth increases. When you spend from asset accounts, that balance decreases—but the money likely went toward something (an expense, a purchase, or a debt payment). > [!TIP] > > For a complete picture of your finances, make sure to add both your assets and your [debt accounts](./debt-accounts.mdx). Sure calculates your true net worth by subtracting what you owe from what you own. ## Adding Asset Accounts To add an asset account: 1. Click **+ Add Account** on your dashboard 2. Select the asset type (Cash, Investment, Crypto, Property, Vehicle, or Other Asset) 3. Enter your account details: * Account name * Current balance * Subtype (if applicable) 4. Click **Create Account** Your new asset account will appear in your accounts list and contribute to your net worth calculation immediately. # FAQ Source: https://docs.sure.am/guides/knowledge-base/faq ## Transaction history and imports > **How far back can Sure import transactions?** > > Available history depends on your bank, connection provider, and Sure's integration settings. Sure does not always request everything available: some integrations use a fixed initial date range or a record limit, and later syncs may only fetch recent changes. > > See [Transaction history and import limits](/providers/transaction-history) for the source-by-source comparison, defaults, and options for older history. Historical exports can help fill gaps; review overlapping dates to avoid duplicates. ## Balances and Pending Transactions > **Why doesn't my account balance include pending transactions?** > > Sure excludes pending transactions from account balance calculations. Account balances reflect only settled (posted) transactions. > > This prevents balances from being temporarily inflated or deflated by transactions that may still change amount, be cancelled, or be replaced by a posted version from your provider. > > Pending transactions remain visible in your transaction list. Once a transaction posts, it is counted in your balance and in reports. > > Providers that report pending status include SimpleFIN, Plaid, Lunchflow, Enable Banking, Akahu, Up, Mercury, and Redbark. > **Why does my balance look different from what my bank shows?** > > Banks commonly display an "available balance" that deducts pending transactions. Sure shows a settled balance — one that reflects only posted activity. > > If the difference matches the sum of your pending transactions, that is expected behavior. Your balance in Sure will update once those transactions post. ## Transfers and Currencies > **Can I have a transfer between accounts with different currencies (exchange rate)?** > > Yes, you can make transfers between accounts with different currencies. Sure automatically applies the exchange rate for the transfer date: > > * The outgoing transaction uses the source account's currency and amount. > * The incoming transaction is converted to the destination account's currency using the rate for that date. > * If no exchange rate is available, the transfer falls back to a 1:1 rate. The amount may be incorrect until rates are synced. > * Foreign exchange metadata is recorded for auditing purposes. > > For best results, make sure an exchange rate provider is configured in **Settings → Self-Hosting** and rates are current. > **What happens when an account has transactions in a currency with no exchange rate?** > > If an exchange rate is missing for a specific currency pair and date, Sure skips that transaction when calculating balances rather than marking the entire account as errored. The skipped entry is logged in **Settings → Debug** under the `sync` category so you can identify which rate is absent. > > Once rates are available — after configuring or re-enabling an exchange rate provider and triggering a sync — the previously skipped entries are included in the next balance calculation. > > Holdings without a rate are still counted at a 1:1 rate to prevent phantom cash from appearing, and the occurrence is logged alongside the entry warning. # Troubleshooting Source: https://docs.sure.am/guides/knowledge-base/troubleshooting ## Sparklines not visible in the account sidebar Account trend sparklines — the small charts next to account groups and individual account rows in the sidebar — did not render in some versions. The charts appeared blank even though the sparkline data had loaded correctly. > **What caused this issue?** > > The chart controller that draws sparklines included a dimension guard that skipped rendering when the drawable width or height, after subtracting chart margins, was less than 50 pixels. Sidebar sparkline containers are 32×12 pixels (account group totals) and 32×20 pixels (individual account rows), so they fell below the threshold and were never drawn. > **How was it fixed?** > > The dimension guard skips rendering when the drawable width or height is zero or negative after chart margins are subtracted. Small containers with positive drawable dimensions, including sidebar sparklines, render normally. A ResizeObserver redraws when layout changes give the chart usable dimensions. > > Charts whose drawable width and height were already at least 50 pixels are unaffected by this guard change. > > Upgrade to a build containing [Sure PR #4361](https://github.com/we-promise/sure/pull/4361). As of October 21, 2026, the fix is on `main` but is not in the latest stable release, `v0.7.5-hotfix.2`. No configuration change is required. ## AI-detected merchants were created as shared records When merchant detection identified a new merchant from a transaction's description, Sure previously created a globally-shared `ProviderMerchant` record (source: `ai`). Because those records are visible to every family on the deployment, a transaction description crafted to steer the LLM's output could create or match a shared merchant with an attacker-chosen name, website, or logo — affecting all other families. > **What was affected?** > > The `Family::AutoMerchantDetector` class, which runs as part of the background merchant detection job. When no existing merchant could be matched for a transaction, it fell back to creating a `ProviderMerchant` (source: `ai`) scoped globally rather than to the family. > > Reusing an already-existing shared merchant by website or name was not affected — that path does not write new data into shared records. > **How was it fixed?** > > When AI detection cannot find a shared merchant to reuse, it now creates a `FamilyMerchant` scoped to the requesting family instead of a global `ProviderMerchant`. AI-sourced merchants from before this fix are also limited to the family that already has them on its transactions — they are no longer matched by name or URL across families. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Account name and balance visible to family members without access after a sync In earlier versions, when an account finished syncing, Sure broadcast a rendered account row — including the account name and balance — on the family's shared Turbo stream. Every signed-in family member subscribed to that stream, including members who did not have access to the account. The row reached their browser after every sync even though the accounts page did not show it to them. > **What was affected?** > > Any account that could sync independently — linked accounts (connected via a provider) and manual accounts that were synced — could expose their name and balance to all currently signed-in family members, regardless of whether those members had view or edit access to the account. > **How was it fixed?** > > The broadcast that replaced the account row in the family stream is removed. Instead, when a sync completes, Sure sends a lightweight sync toast to each browser. The browser refreshes through its own authenticated request, so only members with access see the account data. Refresh can be deferred during interaction with forms or dialogs, and a manual refresh may be needed. > > The fix also covers linked accounts that sync on their own with no follow-up provider event, which would previously have left the accounts page stale for members who do have access. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Settings link causes a 500 error when many accounts are filtered Opening the **Settings** link from a transactions list filtered by a large number of accounts could result in a 500 error (`CookieOverflow`). The transactions list passes the current page's full URL — including all selected account IDs — as a `?return_to=` query parameter so Sure can return you to the same filtered view after you leave settings. With enough accounts selected, that URL exceeds the 4 KB limit of the cookie-backed session. > **What causes this issue?** > > Sure stores the `?return_to=` value in the session so it can redirect back to the page you came from after completing an action in settings. The session is stored entirely in an encrypted browser cookie. When the `return_to` URL contains dozens of account IDs as query parameters, the resulting cookie size exceeds 4 KB and Rails raises a `CookieOverflow` error, producing a 500 response. > **How was it fixed?** > > When the `return_to` value exceeds 1 KB, Sure now stores only the path without its query string. If even the bare path is over 1 KB, the `return_to` value is discarded entirely and the previous stored value is also cleared so a stale redirect target is never used. When the shortened path fits, Sure retains it as the return destination without the filters. Only when the path is discarded does Sure fall back to the default destination. > > Upgrade to the latest release to get this fix. No configuration change is required. ## "All" chart period starts later than expected When you select the **All** period on a net worth or account chart, the chart now starts one month before the earliest Transaction or Trade entry across your family — not your earliest entry of any kind. In earlier versions, Sure used the oldest entry of any type to anchor the All period. A single valuation or opening balance dated years in the past stretched every All-range chart back to that date, leaving a long flat line with no activity before any real spending or trading began. > **What changed?** > > The All period now anchors to one month before the first Transaction or Trade entry across your family. Valuations and opening balances no longer affect how far back the All range extends. > > If your family has only valuations and no Transactions or Trades, the All period uses the family’s oldest entry date when it is before today; a missing, today, or future start falls back to five years ago. > **Why does my chart look different after upgrading?** > > If you had a valuation or opening balance dated further back than your first real transaction, the All chart will now start later. The data is unchanged — only the visible range has shifted to focus on the period where you have actual activity. > > Budgets and the AI balance sheet are not affected. They still use the oldest entry date as before. ## Mixed-currency arithmetic produces wrong totals silently Earlier versions of Sure allowed arithmetic operations (`+`, `-`, `/`, `<=>`) between `Money` objects in different currencies. The result kept the left operand's currency and discarded the right operand's — so `200 USD - 180 EUR` returned `20 USD` with no error or log line. This affected syncs, transfer matching, insight generators, and some report pages for families that hold accounts in more than one currency. > **What was affected?** > > Any calculation that combined two `Money` values from different currencies without an explicit `exchange_to` conversion first. Common surfaces include: > > * Balance and net worth totals across multi-currency accounts > * Transfer matching when accounts are in different currencies > * Insight generators and assistant read functions > * Report and API responses for families mixing currencies such as EUR, GBP, and USD > **How was it fixed?** > > `Money` arithmetic now checks that both operands share the same currency before proceeding. > > In development and test, a mismatch raises `Money::CurrencyMismatchError` immediately so the call site is easy to find. > > In production, the mismatch is reported through `Rails.error` and logged at `warn` level (deduplicated by operation, currency pair, and call site within a bounded per-process cache) and the operation keeps its previous result so no page starts failing while the root cause is fixed. Equality comparisons between different currencies return false without raising. > > Versions containing currency-mismatch detection enable it without an additional configuration change. > **I see a currency mismatch warning in my logs — what do I do?** > > A log line like `[Money] Can't apply + to USD and EUR amounts; convert one with exchange_to first` means Sure found a call site that combines amounts in two different currencies without converting first. > > The log includes the call site location. In most cases the fix is to call `exchange_to` on one of the amounts before the operation, passing the target currency and the relevant date. > > If you are self-hosting a customized version of Sure, search for the call site identified in the log and add the conversion. On an unmodified install, upgrade to the latest release — the known call sites are being fixed progressively. ## Confirmation dialogs could run script from bank-provided names In earlier versions, confirmation dialogs (such as those shown when deleting a provider merchant, resetting holdings, or replacing a SimpleFIN account) interpolated user-supplied names directly into the dialog body via `innerHTML`. Names sourced from bank feeds, brokerage providers, or other family members could contain HTML that the browser executed as script. Because provider merchant rows are shared across families, a crafted merchant name could reach any user who opened a confirmation involving that merchant. > **What was affected?** > > Confirmation dialogs that showed a record name in the body text, including: > > * Provider merchant deletion confirmations (the merchant name came from bank feeds and was shared across families) > * SimpleFIN account replacement prompts (account name from the bank) > * SnapTrade brokerage and holdings reset confirmations (brokerage name and ticker symbols from the provider) > * Any other confirmation built through `CustomConfirm` or the raw `turbo_confirm` hash that included a record name > **How was it fixed?** > > The confirmation dialog now sets its body using `textContent` instead of `innerHTML`. Record names are rendered as plain text regardless of how the confirmation was constructed, so HTML in a name is never parsed or executed. > > Upgrade to the latest release to get this fix. No configuration change is required. ## MXN amounts show wrong number separators in Spanish When the interface language is set to Spanish, Mexican peso (MXN) amounts were formatted using European-style separators — a comma as the decimal separator and a dot as the thousands separator. This produced values like `1.234,56 MXN` instead of the correct `1,234.56 MXN`. > **What caused this issue?** > > Sure formats currency amounts using the active locale's separator rules. Spanish uses European-style separators for most currencies, but MXN natively uses US-style separators (dot as decimal, comma as thousands). The formatter did not have a currency-specific override for MXN under the Spanish locale, so it applied the locale's default separators instead. > **How was it fixed?** > > The number formatter now checks the currency code before applying locale-derived separators. When the currency is MXN and the active locale is Spanish, Sure retains MXN’s dot decimal separator and comma thousands separator. Other locales keep their existing formatting rules. All other currencies continue to follow the locale's own separator conventions. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Category avatar preview does not update when picking a color When editing or creating a category, changing the color using the color picker previously did not update the avatar preview — the icon and background appeared to stay at the original color until the form was saved. > **What causes this issue?** > > The category avatar uses a `--avatar-color` CSS variable to compute both the background (a light tint) and the icon color (the full color). Earlier versions of the color picker updated the avatar's inline `style.color` and `style.backgroundColor` directly instead of setting the variable. Overriding the resolved values bypassed the theme-aware `color-mix` logic, so the preview stayed stuck at the last saved color. > **How was it fixed?** > > The color picker now updates the `--avatar-color` CSS variable on the avatar element when you select a new color. The avatar's CSS reads from the variable, so both the background tint and the icon color update immediately as you pick. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Account balance or net worth drops to zero unexpectedly If an account balance or your net worth chart falls to zero for a day — without any transactions that explain it — a provider may have returned a zero or invalid exchange rate for that currency pair on that date. Storing a zero rate converts every balance in that currency to zero. > **What causes this issue?** > > Exchange rate providers occasionally return a zero rate for a single-day lookup. Earlier versions of Sure stored whatever value the provider returned. Any conversion that used that rate multiplied the balance by zero, wiping the reported value for that day. The bulk importer was already protected, but single-rate lookups were not. > **How was it fixed?** > > Sure now validates every rate — whether from a single lookup or a series — before storing it. A finite, positive number is required. Rates that are zero, negative, `NaN`, or infinite are rejected: > > * A single-rate lookup that returns an unusable value is treated as a failed response; that response supplies no replacement rate. Any fallback depends on the caller. > * Rates in a bulk series that are unusable are dropped. The importer can fill subsequent gaps from a usable prior rate. Without an earlier anchor it begins at the earliest usable provider date; if no usable rates are returned, it does not fill the series. > * A database check constraint rejects zero, negative, and non-finite values for any write that bypasses model validations, such as bulk upserts. > * Any provider rate rejected by this validation is recorded in **Settings → Debug** under the `exchange_rates` category so you can see which provider returned the bad value and on which date. > > A rate of exactly `1` is valid and is stored normally (used for pegged currencies). > > Existing invalid rates in the database are removed when you upgrade. The next sync refetches those dates from the provider. > > Versions containing this validation need no configuration change to enable it. > **How do I confirm the cause?** > > Go to **Settings → Debug** and filter by the `exchange_rates` category. Entries naming the concrete exchange-rate provider class, with level `warn`, show the provider name, the currency pair, and the invalid rate that was rejected. ## Account shows an error when a foreign-currency transaction has no exchange rate If an account holds transactions in a currency that has no exchange rate available for a given date, earlier versions would abort the entire balance calculation for that account, marking it as errored even though all transactions had imported correctly. > **What causes this issue?** > > Balance calculation converts each entry into the account's base currency. When no exchange rate exists for the currency pair on a specific date, Sure previously raised an error that escaped the calculation loop. A single unconvertible entry was enough to produce no balances at all and leave the account in an error state. > **How was it fixed?** > > Sure now skips the unconvertible entry rather than aborting. The entry is excluded from the balance total, the missing rate pair is written to **Settings → Debug** under the `sync` category, and the rest of the account's transactions are still used to calculate balances normally. > > Holdings with a missing rate are handled differently: they are still counted toward the total at a 1:1 rate (to avoid phantom cash appearing in the cash balance), and the occurrence is also logged. > > To see which rate was absent, go to **Settings → Debug** and filter by the `sync` category. Look for entries from `Balance::SyncCache` with level `warn`. > > Upgrade to the latest release to get this fix. No configuration change is required. > **How do I resolve the missing exchange rate?** > > Go to **Settings → Self-Hosting** and confirm an exchange rate provider is configured. Twelve Data is the default. After configuring or re-enabling a provider, trigger a manual sync on the affected account. Once rates are fetched, the previously skipped entries will be included in the next balance calculation. ## Dragging a section on the reports page activates mid-scroll on mobile On mobile, a brief pause while scrolling the reports page could accidentally activate drag mode on a reorderable section, visibly shifting the section and interrupting the scroll. > **What causes this issue?** > > The reports page lets you reorder sections by deliberately holding a section and dragging. The previous hold delay was 150ms with no movement threshold, so a normal scroll gesture — a short pause followed by a swipe — was enough to trigger drag mode mid-scroll. Once drag mode activated, the section moved with the finger instead of the page scrolling. > **How was it fixed?** > > The hold delay is raised to 800ms and a 10-pixel movement threshold is added. If the touch moves more than 10px before the hold delay expires, the pending drag is cancelled and native scrolling continues uninterrupted. A `touchcancel` event (for example, from an interrupting system gesture) now also discards the pending reorder instead of committing it. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Every click on the reports page navigates to a transaction drill-down in Safari In Safari, clicking anywhere on the reports page — including the period picker or other controls — could unexpectedly navigate to a category's transactions drill-down instead of performing the intended action. On iOS Safari, the same layout also caused scrolling to freeze for the entire page. > **What causes this issue?** > > The earlier category-row implementation used an absolutely positioned stretched-link overlay. The fix addresses Safari reports of that overlay intercepting clicks outside the intended cells and iOS scrolling freezing. The current source also documents WebKit table-layout scroll-height problems with positioned overlays. > **How was it fixed?** > > The stretched-link overlay is replaced with normal-flow `` elements wrapping the icon, name, and entry count in the category cell, and separate `` elements to the same destination in the amount and percentage cells. The clickable cells no longer rely on a positioned overlay anchored to a table row. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Debugging rule failures When an async rule run fails (for example, during a family sync or after a provider webhook), the error is written to the debug log. To view it: 1. Go to **Settings → Debug** 2. Filter by the `rules` category Each entry includes the error message and the rule that failed. This is useful for diagnosing why auto-categorization stopped working after a provider or model change. ## When Rules Are Triggered Rules run automatically during family syncs or can be triggered manually. Understanding when rules execute helps troubleshoot categorization issues. > **Manual trigger (user-initiated)** > > Rules can be manually triggered in the following ways: > > * Clicking "Re-apply" on an individual rule in `/settings/rules` > * Clicking "Apply All" in `/settings/rules` > * Running the rake task: `bin/rails rules:apply_all[family_id]` > **During family sync (only active rules)** > > Rules with `active: true` run automatically when a family sync occurs (`Family::Syncer.perform_sync`): > > **Scheduled syncs:** > > * `SyncAllJob` - runs daily at 2:22 AM for all families > * `SyncHourlyJob` - runs every hour (for items that opt-in to hourly syncing) > > **Triggered syncs:** > > * Provider webhooks (Plaid, etc.) - triggers sync which eventually propagates to family > * Manual sync button on accounts page > * After CSV imports complete (`Import` model calls `family.sync_later`) > **When rules do NOT run** > > Rules are **not** triggered in these scenarios: > > * **Manual transaction creation** - Only triggers an Account sync (not Family sync) > * **Manual transaction editing (balance-affecting fields)** - Changing the amount, date, or account triggers an Account sync (not Family sync). Editing only descriptive fields — name, notes, category, merchant, or tags — does not trigger any account sync. Reports and budgets still pick up the change through the entries cache version bumped by the save. > * **Inactive rules (automatic syncs)** - Rules with `active: false` never run during automatic family syncs > > **Apply All** is an exception: it runs all rules, active and inactive, so their transaction changes (category, merchant, tags, and so on) apply. Inactive rules skip the email notification action only. Matches seen while a rule is off stay unrecorded; they are handled when the rule is switched back on. > **How do I see why a rule run failed?** > > Failures during async rule runs (including auto-categorize provider failures) are written to the debug log. To view them: > > 1. Go to **Settings** → **Debug** > 2. Look for entries with category **`rules`** > > Each failed run includes the error message and the rule that triggered it. ## Rule run failures not visible in the UI When rules run asynchronously (during a sync or via a background job), failures are not surfaced in the main UI. If auto-categorization or merchant detection appears to stop working silently, check the debug log. > **Where are async rule failures logged?** > > Failures from background rule runs — including auto-categorize provider errors — are written to the debug log. To view them: > > 1. Go to **Settings → Debug** > 2. Filter by the relevant category (e.g., `rules` or `auto_categorization`) > > A request that was enqueued but has no matching start entry in the log means the job never reached a worker. ## Category Rule Popup Behavior When you select a category for a transaction, a prompt appears to create an automatic categorization rule. This prompt has two controls: * **X (close)** — removes this individual prompt only. It makes no server call and does not affect future prompts. * **Hide for today** — hides all rule suggestion prompts for 24 hours. A note below the buttons reads "Hide for today pauses these suggestions for 24 hours." so the behavior is always visible. There is also a **Don't show this again** checkbox that permanently disables rule prompts for your account. The prompt is gated by several conditions: > **When does the prompt appear?** > > The prompt only shows when **all** of these conditions are met: > > 1. You have not disabled rule prompts (`rule_prompts_disabled` is false) > 2. You have not clicked **Hide for today** in the last **24 hours** > 3. The transaction category actually changed > 4. No active transaction rule that sets this category already matches this specific transaction > 5. The transaction has a category assigned > **Why isn't the prompt showing?** > > Check these common reasons: > > * **Recently snoozed**: You clicked **Hide for today** — wait 24 hours for prompts to resume > * **A matching rule already exists**: An active rule whose conditions match this transaction already sets this category. A rule that sets the same category but whose conditions do not match this transaction does not suppress the prompt. > * **Prompts disabled**: Check if `rule_prompts_disabled` is enabled for your account (set via **Don't show this again**) > * **Prompt appeared behind an open drawer**: In older versions, the prompt could be rendered while the transaction drawer was still open. The browser renders native dialogs in a top layer above all other content, so the prompt sat behind the drawer unseen. A page refresh then removed it before the drawer closed. This is fixed in the current release — the prompt now waits until the drawer closes before appearing. ## Sure Doesn’t Work Over HTTPS If Sure behaves incorrectly or fails when accessed over HTTPS, it’s usually due to missing SSL-related configuration between Nginx and Rails. > **What causes this issue?** > > Sure relies on correct protocol headers to determine whether a request is secure.\ > When HTTPS is terminated at Nginx but not properly forwarded to the app, Rails may treat requests as HTTP. > **How do I fix it?** > > Apply the following configuration changes: > > 1. **Nginx** > > Ensure HTTPS is forwarded to the upstream app: > > ```nginx theme={null} > proxy_set_header X-Forwarded-Proto https; > ``` > > 2. **docker-compose.yml** > > In the `x-rails-env: &rails_env` section, set: > > ```yaml theme={null} > RAILS_ASSUME_SSL: "true" > ``` > > This tells Rails to treat all requests as HTTPS. ## Some pages break over HTTPS Sure uses WebSockets for certain pages. If some pages fail to render correctly or break entirely, this is often caused by missing SSL or upgrade headers in your reverse proxy configuration. > **What are the symptoms?** > > You may see pages partially load, fail completely, or errors similar to: > > ```text theme={null} > Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: close, HTTP_UPGRADE: ) > ``` > > This indicates that the WebSocket upgrade request is not being forwarded correctly. > **How do I fix it?** > > Ensure your Nginx configuration includes the required WebSocket headers: > > ```nginx theme={null} > proxy_set_header Upgrade $http_upgrade; > proxy_set_header Connection "upgrade"; > ``` > > These headers allow Nginx to properly handle WebSocket upgrade requests over HTTPS. ## Money In / Out links return 500 errors behind a forward-auth proxy Self-hosted setups using a forward-auth proxy (Authelia, Authentik, Traefik forward-auth, etc.) may see 500 errors when clicking the **Income** or **Expense** drill-down links on the dashboard's Money In / Out widget. The links work fine when accessed directly. > **What causes this issue?** > > The drill-down links previously included every accessible account ID as explicit query parameters. With many accounts, the resulting URL could exceed several thousand characters. Forward-auth proxies forward the full URL to the auth service in a request header; if that header exceeds the proxy's read-buffer or header-size limit, the request fails with a 500 before it reaches Sure. > **How was it fixed?** > > Sure now omits the `account_ids` parameter when the widget's selected accounts exactly match the user's full set of accessible accounts — the same default the transactions page uses when no filter is applied. The result is identical, but the URL stays short. > > When a family has accounts excluded from reports or tax-advantaged accounts (so the eligible set differs from the accessible set), the IDs remain explicit to preserve the correct scope. > > Upgrade to the latest release to get this fix. No configuration change is required. > **Workaround for older versions** > > If you cannot upgrade immediately, increase the header buffer size in your proxy. For Nginx acting as a forward-auth proxy: > > ```nginx theme={null} > proxy_buffer_size 16k; > proxy_buffers 4 16k; > ``` > > For Traefik, set `forwardAuth.tls.insecureSkipVerify` is unrelated — instead configure your auth service to accept larger headers. ## Holdings list is slow with many securities When an investment account holds a large number of securities, opening the holdings list in the web app could be noticeably slow in earlier versions. > **What caused this issue?** > > The holdings list loaded each holding's associated security in a separate database query — one query per row. With many holdings, this produced a large burst of queries, causing the page to load slowly. > **How was it fixed?** > > The holdings controller now fetches all securities for the current account's holdings in a single query before rendering the list. This replaces the per-row security lookups with eager loading, reducing the number of database queries needed to render the list. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Rule prompt disappears after changing category from the transaction drawer In older versions, changing a transaction's category from the transaction detail drawer did not show the "create a rule?" prompt. The prompt was delivered while the drawer was still open, which placed it behind the drawer in the browser's rendering stack where it could not be seen or clicked. A sync completing shortly after then refreshed the page and removed it entirely. > **What caused this issue?** > > The transaction drawer uses a native browser `` element, which the browser places in a special top layer above all other page content. The rule prompt was streamed into the notification tray at the same time as the drawer was open. Because the notification tray sits below the top layer, the prompt was invisible and unclickable. When the next sync completed and morphed the page, the prompt was removed before the drawer ever closed. > **How was it fixed?** > > The notification tray now defers streams targeting the prompt area and page-refresh streams while a dialog is open. Other streams continue normally. Once the last dialog closes, deferred prompts render first. A deferred refresh is skipped while a prompt is visible, preventing these background refreshes from erasing an unread prompt. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Account disappears after a failed delete If you delete an account and it vanishes from every list and the balance sheet but is never actually removed, one possible cause is that the background deletion job was not queued successfully. A job that fails during destruction is a separate case, described below. > **What causes this issue?** > > Deleting an account marks it `pending_deletion` and queues a background job to remove it. In earlier versions, the status was committed to the database before the job was pushed to the queue. If the job push failed at that point — because the queue (Redis) was temporarily unreachable or the push was rejected — the account was left marked `pending_deletion` with no job coming to finish the deletion. Because `pending_deletion` accounts are excluded from every visible list, the account appeared to vanish. There was no AASM event to leave `pending_deletion`, so you could not retry from the UI. > **How was it fixed?** > > Sure now restores the account's previous status when the job push fails, so the account reappears in your list instead of staying hidden. The deletion attempt also runs under a row lock to prevent a double-submit from capturing a stale status. If the push was rejected, a failure alert is shown and you can try again once the queue is healthy. > > Upgrade to the latest release to get this fix. No configuration change is required. > **What should I do if an account is already stuck?** > > If an account is already stuck in `pending_deletion` on an older version, verify that your worker container and Redis are healthy: > > ```bash theme={null} > docker compose ps worker > docker compose logs worker --tail 50 > ``` > > Once the worker is running and Redis is reachable, a server administrator can reset the account's status directly in the database, then attempt the deletion again from the UI. ## Account reappears as disabled after a failed deletion When you delete an account, Sure marks it as pending deletion and then runs a background job to remove it. If the background job encounters an error during destruction, the account was previously left in the pending deletion state — hidden from every account list, ineligible for any further action, and impossible to re-delete. The only way out was a direct database fix. > **What causes this issue?** > > The deletion request marks the account `pending_deletion` before queuing the background job that attempts destruction. If the destroy raises an error mid-run — for example, a database constraint violation or a provider API failure — the job's own error handler reset a `scheduled_for_deletion` flag that belongs to provider items, not to accounts. The account was left stuck in `pending_deletion` with no job queued to retry it. > **How was it fixed?** > > `Account#destroy` now catches destruction errors and fires a `restore_after_failed_deletion` event, which transitions the account from `pending_deletion` back to `disabled`. The account reappears in your account list and can be deleted again once the underlying problem is resolved. > > For accounts that were already disabled before deletion was attempted, the original `disabled_at` timestamp is preserved so the net worth chart cutoff is not moved forward to the failure date. > > Upgrade to the latest release to get this fix. No configuration change is required. > **What should I do if an account is already stuck?** > > If an account is already stuck in pending deletion on an older version, it requires a direct database update to restore it. Set the account's `status` column back to `disabled` so it becomes visible and can be re-deleted from the UI. After upgrading, an exception raised during destruction restores the account to disabled so you can retry. ## Dashboard loads slowly with many accounts When a user has access to many accounts (through family sharing or account groups), earlier versions issued a separate database query to load accessible accounts on each access during a single request. This caused the dashboard to slow down noticeably as the account count grew. > **What caused this issue?** > > `Current.accessible_accounts` was computed fresh on every call within a request cycle. Controllers and views that accessed `Current.accessible_accounts` multiple times — common on the dashboard, which renders several widgets — each triggered a new database query. With a large number of shared accounts, this produced many redundant queries per page load. > **How was it fixed?** > > `Current.accessible_accounts` is now memoized for the duration of each request. The query runs once and the result is reused across every controller and view that accesses it. The memoized value is cleared automatically when the request context resets. > > `Current.finance_accounts` received the same fix. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Transactions disappear from income, spending, or budgets after a provider sync If one or more transactions vanish from your income, spending, or budget totals after a sync — without being deleted — one possible cause in older versions is a provider removing a transaction that was part of a confirmed transfer. > **What causes this issue?** > > A confirmed transfer links two transactions and assigns transfer-specific kinds such as `cc_payment` or `funds_movement`. A pending match leaves the existing kinds unchanged. When a provider removes a pending transaction that is one leg of a transfer, the transfer itself is destroyed. In older versions, deleting a transfer through that cascade path skipped the step that resets the surviving transaction's kind back to a standard value. The surviving transaction kept its transfer kind — `cc_payment` or `funds_movement` — with no transfer behind it, which caused it to be silently excluded from income, spending, and budget calculations. > > One possible trigger involves pending transactions from provider feeds: a provider may post a pending charge, the transfer is confirmed in Sure, and then the provider cancels or replaces the pending entry before it settles. > **How was it fixed?** > > The kind reset now runs as a `before_destroy` callback on the transfer, so every deletion path — including cascades triggered by deleting a transaction or its entry — resets the surviving leg's kind to the appropriate standard value. Pending transfers keep their existing behaviour and are not affected. > > Upgrade to the latest release to get this fix. No configuration change is required. > **What should I do if transactions are already missing?** > > The callback prevents this problem when a transfer is deleted; it does not repair transactions orphaned before the upgrade. A manual sync is not a general repair for those records. Ask your server administrator to investigate the affected transactions and correct their kinds only after confirming they are no longer transfers. > > To find potentially affected transactions, look for transactions with no linked transfer that have a kind of `cc_payment` or `funds_movement` on accounts where those kinds are unexpected. ## Deleting an account with many transfers is slow When you delete an account, Sure removes all transfers linked to its transactions. In older versions, this process issued a separate database query for each transfer's associated transaction records, causing it to slow significantly when an account had hundreds of transfers. > **How was it fixed?** > > Sure now loads all transfer transaction associations in a single query before starting the deletion loop. Deleting an account with a large transfer history completes in roughly constant time regardless of the number of transfers involved. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Provider connection stuck on "Deletion in progress" If a provider connection shows "Deletion in progress" indefinitely and never disappears, the background deletion job may not have been queued successfully. > **What causes this issue?** > > When you delete a provider connection, Sure marks it as scheduled for deletion and enqueues a background job to remove it. If the job queue (Redis) was unreachable at that moment — or if an enqueue callback rejected the job — the flag stayed set with no job queued. The connection dropped out of the active list and could never be synced again, but it was never actually deleted. > **How was it fixed?** > > Sure now restores the deletion flag when the enqueue fails, so the connection returns to its normal state rather than staying stuck. If the job queue is temporarily unavailable, you can retry the deletion once the queue is healthy again. > > Upgrade to the latest release to get this fix. No configuration change is required. > **What should I do if a connection is already stuck?** > > If a connection is already stuck on an older version, triggering a fresh deletion from **Settings → Providers** will re-enqueue the job once the queue is reachable. If the connection does not respond to deletion, verify that your worker container and Redis are healthy: > > ```bash theme={null} > docker compose ps worker > docker compose logs worker --tail 50 > ``` > > Once the worker is running and Redis is reachable, attempt the deletion again. ## Cash flow and income reports show stale data after deleting an account After you delete an account, cash flow charts, income statements, and category spending totals could continue to include that account's transactions until an unrelated change triggered a cache refresh. > **What causes this issue?** > > The shared income statement freshness key already included the most recent account update timestamp, along with entry changes, exchange rates, and family currency. However, an account timestamp alone can return to an earlier value after an account is marked for deletion and then destroyed, allowing an older cached result to be reused. The family and category statistics caches also used only the entry version rather than the shared freshness key. > **How was it fixed?** > > On `main`, the shared freshness key uses an account version containing both the account count and the full-precision latest update timestamp. The count changes when an account is destroyed, preventing the key from reverting to its pre-deletion value. Family and category statistics now use the shared freshness key too, so a new report request refreshes those results when account status or family currency changes. > > This fix was merged in [Sure PR #4235](https://github.com/we-promise/sure/pull/4235). As of October 20, 2026, it is on `main` but is not included in the latest stable release, `v0.7.5-hotfix.2`. Use a build containing that fix, or wait for a stable release that includes it. No configuration change is required. ## Reports show stale data after merging or deleting a category When you merge categories or delete a category, dashboards and income statements could continue to display the deleted category until an unrelated transaction change occurred. > **What causes this issue?** > > Category merges and category deletions reassign transactions in bulk using `update_all`, which skips Active Record callbacks. The cache key for family reports is driven by the `updated_at` timestamp of the most recently changed entry. Because `update_all` bypassed callbacks, the entry timestamps were never updated, so the report cache key did not change and the old category data remained visible. > **How was it fixed?** > > Sure now routes all bulk category reassignments through `Transaction.reassign_category!`, which updates the affected transactions and then touches the corresponding entries inside a single database transaction. Touching the entries bumps their `updated_at` values, which invalidates the report cache key immediately. > > The entry touch is batched in groups of 5,000 to avoid building an unbounded `UPDATE` statement on large merges. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Budget page shows a 500 error when expected income is not set If the budget page crashes with a server error after the AI assistant sets a spending budget without also setting an expected income, the page can fail when rendering the income-side calculations. > **What causes this issue?** > > The budget model's `initialized?` check only looks at `budgeted_spending`, so a budget with spending set but a nil `expected_income` passes that check and the page attempts to render. Earlier versions of `expected_income_money`, `actual_income_percent`, `remaining_expected_income`, and `surplus_percent` did not guard against a nil value, causing a division-by-zero or nil error during render. > > This could happen when the AI assistant's `update_budget` tool was asked to set only a spending amount — it did not automatically fill in `expected_income`. > **How was it fixed?** > > The income-side budget methods now treat a nil `expected_income` as zero, matching how the spending side already behaved. `surplus_percent` no longer divides by zero. > > In addition, when `update_budget` sets `budgeted_spending` without an `expected_income` and the budget’s existing income is nil, it fills in `expected_income = 0`. An existing income amount is preserved. This matches what the budget form saves when you leave the income field empty. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Budget totals do not update after deleting transactions If a budget still shows spending from a transaction that was already deleted, the most likely cause is a stale aggregate cache. Sure hard-deletes the transaction entry, so the deleted transaction is gone; the stale value can come from cached budget or income totals that were not invalidated by deleting an older entry. > **What causes this issue?** > > Budget totals are derived from entry aggregation queries. Older versions of Sure used the most recent entry update timestamp as part of the cache key, which meant deleting an older transaction could leave the cache key unchanged. > **How was it fixed?** > > The entry aggregate cache version now includes both: > > * The current entry count > * The newest entry `updated_at` timestamp > > Because the count changes when an entry is deleted, budget and income aggregate caches are invalidated even when the deleted transaction was not the most recently updated entry. > **How can maintainers validate it?** > > Confirm the installed version includes the cache invalidation fix for `Family#entries_cache_version`, then re-check the affected budget after the next request or cache refresh. The regression test is: > > ```bash theme={null} > bin/rails test test/models/family_test.rb > ``` ## Chat fails immediately on a fresh family with a strict OpenAI-compatible provider Some strict OpenAI-compatible providers (not OpenAI itself) reject chat requests with a schema validation error when a family has no accounts, categories, merchants, tags, or tickers yet. ## Rule runs fail silently If auto-categorization or merchant detection rules appear to do nothing, the background job may have failed without surfacing an error in the UI. > **How do I see rule run failures?** > > Async rule run failures are now logged to the debug log. Go to **Settings → Debug** and look for entries from the `rule_run` category. Each failed run includes the error class, message, and the rule that triggered it. > > You can also check worker logs directly: > > ```bash theme={null} > docker compose logs worker > ``` > **What causes rule runs to fail?** > > Common causes include: > > * **LLM provider errors** — The AI provider returned an error or timed out. Check your `OPENAI_ACCESS_TOKEN` and provider connectivity. > * **Auto-categorize provider failures** — The provider returned an unexpected response format. These are now propagated and logged rather than silently swallowed. > * **Worker not running** — Rules run in the background via Sidekiq. Verify the `worker` container is healthy. ## App crashes for a family with an invalid timezone If a family's timezone setting contains an unrecognized IANA zone name (for example, after a tzdata rename like `Europe/Kiev` → `Europe/Kyiv`), Sure now falls back to the application default timezone instead of crashing. ## Chat fails immediately on a new account with a strict OpenAI-compatible provider Some strict OpenAI-compatible providers (not OpenAI itself) reject chat requests with a schema validation error when a family has no tags, merchants, or categories yet. This happens because the assistant's tool schemas include `enum` fields built from family data — an empty family produces `enum: []`, which is invalid JSON Schema. > **What causes this?** > > Sure builds tool schemas for the assistant using family data (account names, categories, merchants, tags, tickers). A family with none of this data produces `enum: []` for those fields, which is invalid JSON Schema. OpenAI tolerates it, but strict providers reject the entire request before the model runs. > `Family#timezone` is a free-text field. If the stored value becomes stale — due to a tzdata rename, a database restore from an older backup, or a direct database edit — the app previously raised an `ArgumentError` on every request for that family, including the login page. > **How is it handled now?** > > Sure validates the timezone value against `ActiveSupport::TimeZone` before using it. If the value is unrecognized, the app falls back to the default timezone and logs a warning to **Settings → Debug** under the `timezone` category. The log is debounced to once per day per family so it does not flood the debug log. > > To fix the root cause, update the family's timezone to a valid IANA zone name from **Settings → Profile**. > Sure builds tool schemas dynamically from your family's data (account names, categories, merchants, tags, tickers). When none of that data exists yet, the schema contains `enum: []`, which is invalid JSON Schema. OpenAI tolerates it, but strict OpenAI-compatible providers reject the entire request before the model runs. > **How was it fixed?** > > Empty enum arrays are now pruned from tool schemas before the request is sent, falling back to a plain `string` type. This fix applies to both chat tool definitions and the `/mcp` endpoint's `tools/list`. > > If you are on an older version and cannot upgrade, add at least one account, category, or tag to the family — this populates the enum and avoids the empty-array case. ## Chat shows "assistant not available" before the model finishes Self-hosted users running a local model (Ollama, LM Studio, etc.) may see the chat fail with "assistant not available" even though the model is still generating a reply and tokens are being billed. > **What causes this?** > > Sure uses a whole-turn watchdog (`AI_RESPONSE_TIMEOUT`, default 90 seconds) that starts when the message is queued. Custom OpenAI-compatible providers use a synchronous code path — nothing renders until the full reply is generated — so the watchdog fires before the model finishes. > > Tool-using turns make this worse: each tool call adds another full model round. The total time the watchdog must cover is: > > ```text theme={null} > (1 + ASSISTANT_MAX_TOOL_CALL_ITERATIONS) × OPENAI_REQUEST_TIMEOUT > + tool execution time + queue wait > ``` > > With the defaults (`ASSISTANT_MAX_TOOL_CALL_ITERATIONS=8`, `OPENAI_REQUEST_TIMEOUT=60`), a worst-case turn can take up to 540 seconds of model time — far beyond the 90-second default. > **How do I fix it?** > > The most effective approach is to lower `ASSISTANT_MAX_TOOL_CALL_ITERATIONS` (reducing the worst-case bound) and then size `AI_RESPONSE_TIMEOUT` using the formula above. > > For a local Ollama setup: > > ```bash theme={null} > OPENAI_REQUEST_TIMEOUT=300 > ASSISTANT_MAX_TOOL_CALL_ITERATIONS=2 > AI_RESPONSE_TIMEOUT=1200 > ``` > > You can also set **Chat Response Timeout** from **Settings → Self-Hosting → AI Provider** in the UI. The environment variable takes precedence. > > See [Chat response timeout](/llm-support#chat-response-timeout) for full sizing guidance. ## Account creation form clears all fields when a loan is saved When you clicked **Create Account** on a loan (or any account with nested fields such as an interest rate), the form could come back completely blank if the save failed after account-level validation passed. The failure happened inside the opening balance entry or during attribute locking, so the rescued exception held an Entry record rather than the account the form rendered. Sure rebuilt a blank account instead of the one you submitted, discarding every field you had typed — including the account name and the loan rate. > **What was affected?** > > Any manual account creation that failed after the account model itself was valid. This was most likely to surface when: > > * A loan with nested fields (interest rate, term, etc.) was submitted with values that caused the opening balance entry to raise an error. > * The attribute lock step failed during `create_and_sync`. > > On failure, the form came back empty, forcing users to re-enter every field. > **How was it fixed?** > > Sure now rebuilds the account from the submitted parameters on a failed save, applying the same default for nested accountable attributes that `create_and_sync` uses. The form comes back filled in with everything you typed so you can correct the specific error and resubmit without losing your work. > > Upgrade to the latest release to get this fix. No configuration change is required. ## "Record payment" button does nothing in the manual payment form If you clicked **Record payment** in the manual payment panel of the bill occurrence drawer, the button previously did nothing. Only pressing Enter while focused inside the amount or date field submitted the form. The button now submits the form correctly when clicked. > **What caused this issue?** > > The `DS::Button` component defaults to `type="button"` to avoid accidentally stealing Enter-key form submission from other buttons on the page. The **Record payment** button was not overriding that default, so clicking it fired no action. Only pressing Enter in one of the form fields triggered the submission. > **How was it fixed?** > > The **Record payment** button is now rendered with `type="submit"`, which makes it behave as a standard form submit button. > > Upgrade to a version containing this fix. No configuration change is required. ## "Add transaction" button does nothing when no account is selected If you click **Add transaction** on the new transaction form without selecting an account, the button previously appeared to do nothing (the request returned a 404 error). The form now re-renders with a validation error so you can see what is missing and correct it. ## Split transactions not grouped in account activity When the **Group split transactions** preference was enabled, split child entries were collapsed under their parent on the Transactions page but still appeared as flat, ungrouped rows on the Activity tab of individual account pages. Split transaction grouping now applies consistently to both the Transactions page and the account activity feed. When the preference is on, split children appear indented under their parent row in both views. ## Excluded transactions disappear from account activity Transactions marked as excluded were previously hidden from the account activity feed entirely. This made it impossible to re-include them because there was no row to click. Excluded transactions now appear greyed-out in the account activity list so you can still open them and toggle exclusion off if needed. ## Rule rejected with an invalid field error If saving a rule or importing rules fails with an "invalid" validation error on a name, condition value, or action value, the field likely contains a null byte (`\0`) or a malformed UTF-8 sequence. PostgreSQL rejects strings with null bytes, and Sure now catches them before they reach the database. > **What triggers this error?** > > The error appears when: > > * A rule name, condition value, or action value was copied from a source that embedded a null byte (for example, certain export tools or scripted database edits). > * A CSV or NDJSON import file contains rule rows with binary garbage or truncated multibyte characters in any text field. > * A condition type, action type, or resource type field in a submitted form contains a malformed encoding — in that case the form returns an error as plain text rather than re-rendering. > **How do I fix it?** > > * **Manually created rules**: Open the rule in **Settings → Rules**, clear and retype the affected field, then save. > * **Imported rules**: Open the import file in a text editor, find the row flagged in the error, remove or replace any non-printable characters in the name, condition value, or action value column, and re-run the import. > * **CSV files**: Ensure the file is saved as UTF-8 without BOM and without embedded null bytes. Most spreadsheet apps can re-export a clean UTF-8 file. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Rule category, merchant, or tag names missing in exports When you export your data (via **Settings → Exports**), rule conditions and actions that reference a category, merchant, or tag should appear with the human-readable name rather than the raw UUID. In older versions, two bugs could cause the name to be missing or stale in the exported `rules.csv` and `all.ndjson` files: * **Uppercase UUID stored in the rule** — Rule operand values are stored as UUIDs. If a UUID was stored in uppercase (for example, after a direct database edit or migration), the export lookup was case-sensitive and would miss the match, leaving the raw UUID in place of the name. * **Stale in-memory association** — If a category, merchant, or tag was created or modified during the same request that triggered the export (for example, as part of an import or rule-apply job), the exporter could read a stale in-memory association and produce an outdated name or omit the `value_ref` entirely. Both bugs are fixed in the current release. UUID lookups are now case-normalized before the cache lookup, and operand records are reloaded from the database at the start of each export rather than using a cached association. **To resolve:** Upgrade to the latest release and re-run the export. No data migration or configuration change is required. If you previously imported an export that contained raw UUIDs instead of names in rule operand fields, update those rule conditions and actions manually after upgrading. ## Rule creation from modal fails with "must have at least one action" When creating a rule from the rule creation modal, saving the form could fail with a validation error saying the rule must have at least one action — even though you had added one. The re-rendered form also lost any dynamically added action or condition rows. > **What caused this issue?** > > The rule form uses dynamically generated keys to identify newly added action and condition rows before they are persisted. A previous change introduced string keys of the form `new_1`, `new_2` for these rows. Rails strong parameters only treat integer-keyed hashes as nested attributes — it checks that the key matches `/\A-?\d+\z/` — so string keys were silently dropped before the record was saved. The result was a rule with no actions, which failed validation. > **How was it fixed?** > > The key generator now produces numeric-only keys by combining the current timestamp with a per-session sequence counter (`Date.now() * 1000 + seq`). This avoids collisions with the numeric indexes Rails assigns to already-persisted rows on edit forms, and ensures all dynamically added rows pass Rails' nested-attribute check. > > Upgrade to the latest release to get this fix. No configuration change is required. ## Import fails on rules with no name or deleted rejected transfers Importing an `all.ndjson` export could fail with two unrelated errors: * **Rule with `"name": null`** — The import preflight incorrectly required a name for every rule, but the rule model allows a null name. The preflight now requires the rule's `id` instead, matching what the importer actually uses. * **RejectedTransfer referencing a deleted transaction** — A rejected transfer whose original transaction was later deleted caused the import to abort with a hard error. These orphaned rows are now skipped with a warning instead of blocking the entire import. If a previous import attempt failed for either of these reasons, retry the import after upgrading. ## Sure import fails with unresolved merchant references from an older export Exports produced before provider-merchant support was added did not include `ProviderMerchant` rows in the `all.ndjson` file. Importing such a file into a current version of Sure would previously fail preflight with a blocking error for every transaction whose `merchant_id` pointed at a provider-assigned merchant. > **What changed?** > > An unresolvable `merchant_id` on a transaction or recurring transaction is now a preflight warning rather than a blocking error. Sure imports the row without a merchant assigned. The confirm screen shows the number of affected records under a "merchant references not found" notice. > > Unnamed recurring transaction series that have neither a name nor a resolvable merchant are skipped entirely (and reported separately). Named series without a merchant import normally. > **How do I get the merchants into the new instance?** > > Re-export from the source instance using a current version of Sure. The exporter now includes all `ProviderMerchant` records referenced by the family's transactions and recurring transactions. Importing that newer export resolves the merchant references without warnings. > > If the source instance is no longer available, the missing merchants are rebuilt automatically the next time Sure syncs the family's connected accounts. ## Editing a provider merchant's website had no effect in older versions In versions before the fix in [#3824](https://github.com/we-promise/sure/pull/3824), submitting a website-only edit on a provider-assigned merchant (one created automatically by bank sync or AI enrichment) updated the shared merchant record for every family on the instance. If you had a same-name family merchant already, the edit form reported success but silently kept the old URL because the existing family merchant was not updated. > **What changed?** > > Changing the name or website of a provider-assigned merchant now converts it to a family-owned merchant scoped to your family only. Other families on the instance are unaffected. If your family already has a merchant with the same name, Sure reuses that record and applies the submitted website (including a blank value to clear it). A submitted color is also applied to the reused merchant. > > Saving the edit form without making any changes still keeps the shared provider merchant as-is. > **What if I see the old website after upgrading?** > > Open **Settings → Merchants**, find the merchant, and submit the edit form with the correct website. The current version will apply your change to a family-owned copy of the merchant. ## Sure import fails because categories or tags already exist on the destination family When a fresh family is created, Sure seeds it with a default set of categories. Importing a Sure export from another instance into that family previously failed preflight if any exported Category, Tag, or Merchant names matched the existing defaults. > **What changed?** > > Name collisions on family-owned taxonomy records (Category, Tag, and family Merchant) are now preflight warnings rather than blocking errors. Sure reuses the existing record and updates it with the imported data. The confirm screen lists how many records were reused. > **Will my data be correct after the import?** > > Yes. Transactions and rules that referenced the imported category or tag are remapped to the surviving (reused) record. The imported data updates that record's fields. No manual cleanup is needed. ## Balance anchor dated away from provider holdings When Sure syncs an investment or crypto account, it compares the date of the balance anchor (the recorded current balance) with the date of the newest holding that the provider reported. If the two dates differ, Sure writes a warning to the debug log so you can investigate possible date-related cash artifacts in balance calculations. > **What causes this warning?** > > Some providers date their holdings to the day the data was produced (for example, the previous trading day's close), while the balance anchor is set to the day of the sync. A gap between the anchor date and the holdings date can cause the reverse balance calculator to interpret differences in valuation as cash. > > Interactive Brokers and Plaid are known examples of providers that can produce this gap. > > Manual accounts, accounts without a current balance anchor, and accounts whose holdings carry no provider attribution are not checked and will never produce this warning. > **Where do I see the warning?** > > Go to **Settings → Debug** and filter by the `provider_sync` category. Look for `warn`-level entries with a message like: > > ``` > Balance anchor dated 1 day(s) after the newest provider holding > ``` > > Each entry includes the provider, the account, both dates, and the gap in days as structured metadata. A steady gap does not add a new entry on each sync — only a change in the gap (including the gap closing) is recorded. > > When the gap closes, Sure logs an `info`-level entry: > > ``` > Balance anchor and newest provider holding are dated alike again > ``` > **What should I do about it?** > > This warning is informational for self-hosted operators. The warning itself does not change account data. Investigate it if the account balance or cash history looks wrong. > > If you see cash appearing and disappearing in an investment account's balance chart on a one-day cycle, check **Settings → Debug** for a `provider_sync` warning on that account. The gap days value confirms a date mismatch, which may help explain the anomaly; it does not by itself prove the cause. > > The warning does not indicate a sync failure. The sync completes normally; only the debug entry is written. ## Auto mode does not retry with a simpler format after a malformed response In older builds, `LLM_JSON_MODE=auto` only fell back to `none` mode when the provider rejected the request outright (HTTP 400) or returned more than 50% null results. A response that came back with HTTP 200 but contained unparseable or wrongly-shaped JSON escaped the fallback entirely, so `auto` behaved the same as `strict` for those models. > **What caused this?** > > The auto-mode fallback caught `Faraday::BadRequestError` (HTTP 400) and the null-result threshold. JSON parse failures and shape mismatches raised a different error class that was not caught inside the auto-mode wrapper, so they propagated out and prevented the `none`-mode retry. > > For merchant detection specifically, the retry heuristic only counted a missing `business_name` as a failure. A result that had a name but no URL was treated as successful and suppressed the retry, even though Sure ignores detections without both fields. > **How was it fixed?** > > A dedicated `ResponseFormatError` is now raised for JSON parse failures and shape mismatches in the generic extractors. The auto-mode wrappers for both categorization and merchant detection catch this error and retry once with `none` mode, the same as they already did for the >50% failure heuristic. > > The merchant-detection heuristic was also corrected: an item missing either `business_name` or `business_url` now counts as a failure for the retry threshold. > > Upgrade to a build containing [Sure PR #3602](https://github.com/we-promise/sure/pull/3602). No configuration change is required. If you were using `LLM_JSON_MODE=strict` as a workaround, switch to `auto`. ## Reading auto-categorization debug logs When auto-categorization runs, Sure writes structured entries to the debug log under the `auto_categorization` category. Go to **Settings → Debug** and filter by `auto_categorization` to see them. > **What entries will I see?** > > Each run can produce the following entries: > > * **AI categorization cache used** (info) — logged when some transactions in the batch already have an AI-set category that matches their current category. Those transactions are skipped to avoid redundant API calls. The entry includes the IDs of the cached transactions. > * **AI categorization blocked by enrichment protection** (info) — logged when some transactions have a locked `category_id` attribute that was not set by AI. Those transactions are protected from being overwritten. The entry includes the IDs of the blocked transactions. > * **AI categorization failed: no categories available** (error) — logged when the family has no categories configured. Auto-categorization cannot run without categories to map against. > * **AI categorization completed** (info) — logged at the end of a successful run. The entry includes the requested transaction IDs, which transactions were categorized, which were cached or blocked, and the total number of modified transactions. > **Why are some transactions not being categorized?** > > Check the debug log for `auto_categorization` entries. Transactions may be skipped because: > > * They already have an AI-assigned category that matches the current value (cache hit — shown in the **cache used** entry). > * Their `category_id` attribute is locked by a non-AI source (shown in the **blocked** entry). > * The family has no categories set up (shown in the **no categories available** error entry). ## Why is Sure not running auto-categorization and merchant detection on the same transactions again? Sure caches AI-generated results to avoid redundant API calls and costs. Once a transaction has been processed by AI rules, it won't be re-processed unless you explicitly reset the AI cache. > **Why does Sure cache AI results?** > > When AI rules process transactions, Sure stores: > > * **Enrichment records** - Which attributes were set by AI (category, merchant, etc.) > * **Attribute locks** - Prevents rules from re-processing already-handled transactions > > This caching ensures: > > * Transactions aren't sent to the LLM repeatedly > * API costs are minimized > * Processing is faster on subsequent rule runs > **How do I force Sure to re-process transactions?** > > To have AI rules re-process transactions, you need to reset the AI cache: > > 1. Go to **Settings** → **Rules** > 2. Click the menu button (three dots) > 3. Select **Reset AI cache** > 4. Confirm the action > > After resetting, the next time rules run (either manually or during a sync), AI will re-process all transactions. > > **Note:** This will incur API costs if using a cloud provider. > > The reset runs in the background. You can track its progress and see how many AI cache entries were removed in **Settings → Debug**, filtered by the `ai_cache_reset` category. Each run logs when it starts, how many entries were removed per scope, and any records that could not be cleared. > **When should I reset the AI cache?** > > Common scenarios for resetting the cache: > > * **Switching LLM models** - Different models may produce better categorizations > * **After system updates** - New versions may have improved prompts > * **Fixing miscategorizations** - When AI made systematic errors > * **Testing** - During development or evaluation of AI features > > The AI cache is automatically cleared when you change the OpenAI model setting. > **How do I verify the reset actually ran?** > > The reset runs as a background job. You can confirm it completed — and see a breakdown of how many AI cache entries were removed — in the debug log: > > 1. Go to **Settings** → **Debug** > 2. Filter by category **`ai_cache_reset`** > > You will see: > > * An **info** entry when the reset is enqueued from the rules page > * An **info** entry when the job starts on a worker > * A **completion** entry with the number of enrichments deleted, broken down by scope > * **warn** entries for any individual records that could not be cleared > * An **error** entry if the job could not be enqueued at all > > If you see the enqueue entry but no start entry, the job never reached a worker — check that your worker container is running. ## Drawer close button missing on mobile, or two Customize buttons visible on the dashboard On mobile, certain drawers (transactions, trades, transfers, holdings, and valuations) showed no close button because the responsive close button was configured to appear only at large screen widths. On the dashboard, the desktop Customize button appeared alongside the mobile button because `hidden` was not overriding the component's `inline-flex` display. > **What caused these issues?** > > The design system's button component (`DS::Buttonish`) applied `inline-flex` through its icon-only container classes. Because `inline-flex` wins over `hidden` in the generated CSS, a button marked `hidden lg:inline-flex` for responsive hiding remained visible at every width rather than hiding on smaller screens. > > For drawer close buttons, `DS::Dialog#close_button` was configured as `hidden lg:flex` under the responsive option. The close button was therefore unavailable on phones. > **How was it fixed?** > > The button component now lets a `hidden` class override only the display utility. Alignment and gap classes are preserved so buttons continue to lay out correctly once they become visible. Icon-only sizes no longer add `inline-flex` back through their container classes. > > `DS::Dialog#close_button` now shows at every width so drawers always have a close control on mobile. > > Upgrade to a build containing [Sure PR #4342](https://github.com/we-promise/sure/pull/4342). As of October 21, 2026, the fix is on `main` but is not in the latest stable release, `v0.7.5-hotfix.2`. No configuration change is required. # Introduction Source: https://docs.sure.am/index Sure is a personal finance app for everyone - track your accounts, transactions, and build wealth with complete control over your data # Sure: The personal finance app for everyone Sure is a fully-featured personal finance and wealth management app that you can self-host for free. Track your accounts, manage transactions, monitor investments, and take control of your financial future — all with complete ownership of your data. > **[Quickstart](/quickstart)** > > Get started with Sure in minutes > **[Self-hosting](/self-hosting)** > > Deploy Sure with Docker on your infrastructure > **[Complete guide](/guide)** > > Learn about all features and capabilities > **[GitHub](https://github.com/we-promise/sure)** > > View source code and contribute ## About Sure Sure is a community-maintained fork of the Maybe Finance project, which was open-sourced after the original team spent nearly \$1 million building a comprehensive personal finance platform. The app includes: * **Account management** - Track cash, credit cards, investments, and loans * **Transaction tracking** - Record expenses, income, and transfers * **Investment monitoring** - Monitor your portfolio and net worth * **Budget planning** - Set and track financial goals * **Reports** - Break down income and expenses by category for any date range * **AI assistant** - Ask questions about your finances in a built-in chat sidebar * **Data ownership** - Self-host with complete control over your data ## Get involved > **[Discord](https://discord.gg/36ZGBsxYEK)** > > Join our community > **[Website](https://sure.am)** > > Visit our website > **[Issues](https://github.com/we-promise/sure/issues)** > > Report bugs or request features ## License Sure is distributed under the [AGPLv3 license](https://github.com/we-promise/sure/blob/main/LICENSE). You're free to fork, modify, and self-host the application. This project is a community fork of Maybe Finance and is **not affiliated with or endorsed by** Maybe Finance Inc. "Maybe" is a trademark of Maybe Finance Inc. # LLM support Source: https://docs.sure.am/llm-support Configure AI features with local or cloud models > [!NOTE] > > LLM usage is optional and must be explicitly configured. You can maintain full control by running local models on your own systems through Ollama, LM Studio, or similar tools. No data is sent to external services unless you configure a cloud provider. ## Architecture: two AI pipelines Sure has two separate AI systems that operate independently. Understanding this matters because they have different configuration requirements. **Chat assistant (conversational)** — the interactive chat where users ask questions about their finances. It routes through one of two backends: * **Builtin** (default): uses the LLM provider selected by `LLM_PROVIDER` (OpenAI-compatible or native Anthropic). Calls Sure's function tools directly. * **External**: delegates the entire conversation to a remote AI agent. The agent calls back to Sure via MCP to access financial data. Set `ASSISTANT_TYPE=external` as a global override, or configure it per family in Settings. * **MCP only**: disables the in-app assistant entirely — no chat sidebar, no chat API, no bills AI shortcuts, no Dig in with AI on insight cards. The `/mcp` endpoint stays active so external agents can still connect. Background auto-categorization also continues. Use this when you bring your own agent over MCP and want to remove the built-in chat UI. Set `ASSISTANT_TYPE=mcp_only` as a global override, or choose "None in app (connect your own agent via MCP)" in Settings → Self-Hosting. **Auto-categorization (background)** — a two-step pipeline that classifies uncategorized transactions on every sync: 1. **Naive Bayes pass** — trains a multinomial Bayes model on the family's existing categorized transactions and classifies new ones locally. No provider or API key is needed. Only transactions that clear a 70% confidence threshold are categorized; the rest fall through to step 2. The Bayes pass requires at least 20 categorized transactions across at least 2 categories before it activates. If Bayes categorizes every transaction in a batch, the LLM step is skipped entirely. 2. **LLM pass** — sends the remaining uncategorized transactions to the provider selected by `LLM_PROVIDER`. This step is skipped when Bayes covers the full batch. **Merchant detection (background)** — uses the preferred configured LLM provider (OpenAI-compatible or native Anthropic). Selecting Jev for categorization does not route merchant detection to Jev. | Setting | Chat assistant | Auto-categorization | Merchant detection | | - | - | - | - | | `ASSISTANT_TYPE=builtin` (default) | Uses the LLM provider | Bayes first, then LLM provider or Jev | Uses the LLM provider | | `ASSISTANT_TYPE=external` | Uses external agent | Bayes first, then LLM provider or Jev | Uses the LLM provider | | `ASSISTANT_TYPE=mcp_only` | Disabled (in-app chat off) | Bayes first, then LLM provider or Jev | Uses the configured LLM provider | If you use an external agent for chat, auto-categorization and merchant detection still use the configured LLM provider. Set `OPENAI_ACCESS_TOKEN` (for the OpenAI-compatible provider) or `ANTHROPIC_ACCESS_TOKEN` / `ANTHROPIC_API_KEY` (for the native Anthropic provider), or configure [Jev](/providers/jev) as the categorization provider. Families with at least 20 categorized transactions across 2 or more categories will see Bayes reduce or eliminate LLM calls for categorization. ## Where AI jobs run (Sidekiq lanes) AI work runs in the Sidekiq `worker` in its own capsule ("lane"), so a slow model can't hold up syncs, balance recalculation, and scheduled jobs. Both lanes are defined in `config/sidekiq.yml`: | Lane | Queues | Threads | Jobs | | - | - | - | - | | default | `scheduled`, `high_priority`, `medium_priority`, `low_priority`, `default` | `RAILS_MAX_THREADS - RAILS_AI_MAX_THREADS` (3 - 1 = 2 by default) | syncs, balances, rules, imports, scheduled jobs | | ai | `ai_high_priority`, then `ai_low_priority` (strict order) | `RAILS_AI_MAX_THREADS` (default `1`) | chat (`ai_high_priority`); auto-categorization, merchant detection and enhancement, PDF processing (`ai_low_priority`) | Key behaviors: * **`RAILS_MAX_THREADS`** is the worker's total thread count and also sizes its database pool. It must be greater than `RAILS_AI_MAX_THREADS` (at least `2` by default). A lane with 0 threads stops the worker from starting. Puma reads the same variable, so if you lower it for the web service to save memory, set the worker's value separately. * **Strict order:** a waiting chat runs next, but it doesn't interrupt the AI job already running. Auto-categorization, merchant-detection, and merchant-enhancement work is batched using `LLM_MAX_ITEMS_PER_CALL` (default `25`). An OpenAI-compatible provider can split a batch into several calls when it does not fit the context window. PDF import and chat jobs can make several calls. With one AI thread, a PDF import or other `ai_low_priority` job waits behind earlier ones, and continuous chat use pauses background AI work. * **Busy notice:** when a chat would wait behind another AI job (a chat has waited over 30 seconds, or, with one AI thread, a background AI job has waited over 30 seconds), its "Thinking" bubble says the system is busy until the chat's job starts. `AI_RESPONSE_TIMEOUT` includes that wait. * **One AI thread suits a model that serves one request at a time,** such as a local model on CPU. A chat turn's calls run back to back, keeping the model's prompt cache warm. If your provider serves requests in parallel (hosted APIs or a local server with several slots), raise `RAILS_AI_MAX_THREADS` and `RAILS_MAX_THREADS` by the same amount so the default lane keeps its threads. * **Load `config/sidekiq.yml` to use the configured AI capsule.** `bundle exec sidekiq` discovers this file by default. A `-q` option overrides the default capsule’s queues but does not remove the AI capsule from a loaded configuration. If a custom worker command loads a different configuration without the AI capsule, ensure that some worker polls `ai_high_priority` and `ai_low_priority`. Otherwise System health and the site-wide banner report "No worker is processing the AI queues", and the chat page warns that responses may not be delivered. Use `-C config/sidekiq.yml` to select Sure’s configuration explicitly. * **System health:** AI backlog doesn't count towards "queue backed up" (a large merchant-detection run can queue for hours), but "Oldest job age" still includes it. Check the queue table or `/sidekiq` to see which queue is waiting. * **Large batches:** Sure doesn't limit `LLM_MAX_ITEMS_PER_CALL`. OpenAI-compatible providers split a batch that doesn't fit the context window. With the native Anthropic provider, raise `ANTHROPIC_MAX_TOKENS` (default `4096`) along with `LLM_MAX_ITEMS_PER_CALL`, or replies are cut off. * **Upgrading:** AI jobs moved from `high_priority` (chat), `medium_priority`, and `scheduled` to the AI queues. Jobs already queued under the old names still run once, in the default lane. ## Quickstart The fastest way to enable AI features is to use OpenAI: 1. Get an API key from [OpenAI](https://platform.openai.com/api-keys). 2. Set the environment variable: `OPENAI_ACCESS_TOKEN=sk-proj-...your-key-here...` 3. Restart Sure (both `web` and `worker` services). The AI assistant becomes available once you enable it in the UI. Sure uses `gpt-4.1` as the default model. ## Supported providers Sure supports two first-class LLM providers: * **OpenAI** (or any OpenAI-compatible endpoint, including Ollama, LM Studio, OpenRouter, Groq, Together AI, etc.) * **Anthropic** (native Claude support, including custom Anthropic-compatible endpoints such as Amazon Bedrock or Google Vertex) Set the active provider with the `LLM_PROVIDER` environment variable (or the `LLM Provider` setting in the UI). It defaults to `openai`. The matching access token must be configured for the selected provider. When set, `LLM_PROVIDER` takes precedence over any provider choice saved in the UI. | `LLM_PROVIDER` | Required credential | | - | - | | `openai` *(default)* | `OPENAI_ACCESS_TOKEN` | | `anthropic` | `ANTHROPIC_ACCESS_TOKEN` (or `ANTHROPIC_API_KEY`) | Chat routing honors `LLM_PROVIDER` first: the provider selected by that setting is tried before any fallback. If the selected provider does not support the model in use, the other configured provider is tried as a fallback. This means setting `LLM_PROVIDER=anthropic` reliably routes chat to Anthropic even when a custom OpenAI-compatible endpoint (`OPENAI_URI_BASE`) is also configured. ## Configuration via settings Configure AI settings through the web interface: 1. Go to **Settings** → **Self-Hosting** 2. Scroll to the **AI Provider** section The form contains the following fields, grouped by function: **Provider & credentials** * **LLM Provider** — `openai` or `anthropic` * **Access Token** — API key for the selected provider * **URI Base** — Custom endpoint URL (OpenAI-compatible providers only; leave blank for OpenAI) * **Model** — Model name (required for custom endpoints) **Behavior** * **JSON Mode** — Output mode for structured responses: `auto`, `strict`, `json_object`, or `none` * **Chat Response Timeout** — Whole-turn watchdog in seconds (see [Chat response timeout](#chat-response-timeout)) **Token budget** * **Context Window** — Total tokens the model accepts * **Max Response Tokens** — Tokens reserved for the model's reply * **Max Items Per Batch** — Upper bound for auto-categorize and merchant detection batches 3. Choose your **LLM Provider** (`openai` or `anthropic`) 4. Configure the matching credentials and options: **OpenAI / OpenAI-compatible provider fields:** | Field | Description | | - | - | | **Access Token** | API key for the provider (maps to `OPENAI_ACCESS_TOKEN`) | | **URI Base** | Custom endpoint URL — leave blank for OpenAI (maps to `OPENAI_URI_BASE`) | | **Model** | Model name — required for custom endpoints (maps to `OPENAI_MODEL`) | | **JSON Mode** | JSON output mode for OpenAI-compatible categorization and merchant-detection calls, plus text-based PDF and bank-statement extraction: Auto, Strict, JSON Object, or None (maps to `LLM_JSON_MODE`) | | **Context Window** | Total tokens the model accepts (maps to `LLM_CONTEXT_WINDOW`, default `2048`) | | **Max Response Tokens** | Tokens reserved for the model's reply (maps to `LLM_MAX_RESPONSE_TOKENS`, default `512`) | | **Max Items Per Batch** | Upper bound for auto-categorize / merchant detection batches (maps to `LLM_MAX_ITEMS_PER_CALL`, default `25`) | | **Chat Response Timeout** | Whole-turn watchdog in seconds (maps to `AI_RESPONSE_TIMEOUT`, default `90`) | **Anthropic provider fields:** | Field | Description | | - | - | | **Access Token** | API key for Anthropic (maps to `ANTHROPIC_ACCESS_TOKEN`) | | **Base URL** | Custom endpoint URL for Bedrock / Vertex proxies (maps to `ANTHROPIC_BASE_URL`) | | **Model** | Model name — required when Base URL is set (maps to `ANTHROPIC_MODEL`, default `claude-sonnet-4-6`) | Environment variables take precedence over UI settings when set to a non-blank value. A blank environment variable (e.g. `OPENAI_MODEL=`) is treated as unset and the UI setting is used instead. If an environment variable is set to a non-blank value, the corresponding field is disabled in the UI. ## Choosing a provider Sure ships with two first-class LLM providers: * **OpenAI (and OpenAI-compatible)** — default. Works with OpenAI directly, Ollama, LM Studio, OpenRouter, Groq, and any other OpenAI-compatible endpoint. * **Anthropic** — native Claude support via the Messages API, including auto-categorization, merchant detection, and provider-merchant enhancement. Select the active provider with the `LLM_PROVIDER` environment variable: | Variable | Description | Default | | - | - | - | | `LLM_PROVIDER` | Active provider. Set to `openai` or `anthropic`. When set, this value takes precedence over any provider choice saved in the UI. | `openai` | > [!NOTE] > > Chat tries the provider selected by `LLM_PROVIDER` first when it supports the chat model, then tries the other configured provider. A custom OpenAI-compatible endpoint does not automatically override a compatible Anthropic selection. Check the chat model and provider credentials if a request uses the fallback provider. ## OpenAI compatible API Sure supports any OpenAI-compatible API endpoint, giving you flexibility to use: * **OpenAI** - Direct access to GPT models * **Ollama** - Run models locally on your hardware * **LM Studio** - Local model hosting with a GUI * **Google Gemini** - Use Gemini models directly with a Gemini API key * **OpenRouter** - Access to multiple providers (Anthropic, Google, etc.) * **Other providers** - Groq, Together AI, Anyscale, Replicate, and more > [!NOTE] > > Sure normalizes tool-call payloads to the strict OpenAI wire format before sending them. Tool result messages omit the deprecated `name` field that some endpoints reject, and function arguments are always serialized as a JSON-encoded string rather than a raw object. Blank or missing arguments are sent as `{}`. These adjustments fix `400` errors on endpoints such as GLM/Z.ai that enforce the schema strictly. ### OpenAI ```bash theme={null} OPENAI_ACCESS_TOKEN=sk-proj-... # No other configuration needed ``` Recommended models: * `gpt-4.1` - Default, best balance of speed and quality * `gpt-5` - Highest quality * `gpt-6-sol` - GPT-6 Sol, vision and PDF capable * `gpt-6.1-sol` - GPT-6.1 Sol, vision and PDF capable * `gpt-4o-mini` - Cheaper, good quality > [!NOTE] > > `gpt-6-sol` and `gpt-6.1-sol` are vision-capable and use the `max_completion_tokens` request parameter for PDF processing, matching the behavior of `o1` and `o3`. ### Ollama (local) ```bash theme={null} # Dummy token (Ollama doesn't need authentication) OPENAI_ACCESS_TOKEN=ollama-local # Ollama API endpoint OPENAI_URI_BASE=http://localhost:11434/v1 # Model you pulled OPENAI_MODEL=llama3.1:13b ``` Install and run Ollama: ```bash theme={null} # macOS brew install ollama # Linux curl -fsSL https://ollama.com/install.sh | sh # Start Ollama ollama serve # Pull a model ollama pull llama3.1:13b ``` ### LM Studio (local) 1. Download from [lmstudio.ai](https://lmstudio.ai/) 2. Download a model through the UI 3. Start the local server 4. Configure Sure: ```bash theme={null} OPENAI_ACCESS_TOKEN=lmstudio-local OPENAI_URI_BASE=http://localhost:1234/v1 OPENAI_MODEL=your-model-name ``` > [!NOTE] > > LM Studio and some other OpenAI-compatible runtimes reject `response_format: { type: "json_object" }` with an error like `'response_format.type' must be 'json_schema' or 'text'`. If bank statement imports or other structured AI calls fail with this message, set `LLM_JSON_MODE=none` to omit the `response_format` parameter entirely. ### Google Gemini You can connect to Gemini directly via Google AI Studio's OpenAI-compatible endpoint, or via OpenRouter. Sure also recognizes `gemini-4-argon` in its usage-cost estimates. **Recommended Gemini models:** * `gemini-3.8-flash` - Best all-around choice; fast, strong reasoning, and reliable tool calling for chat and finance tools * `gemini-3.5-flash-lite` - Ultra-low cost and fast; ideal for background categorization and merchant detection * `gemini-3.1-pro-preview` - Best for complex financial analysis, portfolio queries, and multi-year trends * `gemini-2.5-flash` - Previous-generation option for users with existing access * `gemini-2.5-pro` - Previous-generation reasoning model for users with existing access Google limits direct Gemini 2.5 API access to users who actively used those models previously. For new projects, use `gemini-3.5-flash-lite` or `gemini-3.8-flash`; see [Google's model availability guidance](https://ai.google.dev/gemini-api/docs/models). #### Direct via Google AI Studio [Google AI Studio](https://aistudio.google.com/) provides direct API access to Gemini models with a free tier and an OpenAI-compatible endpoint: ```bash theme={null} OPENAI_ACCESS_TOKEN=your-google-ai-studio-api-key OPENAI_URI_BASE=https://generativelanguage.googleapis.com/v1beta/openai OPENAI_MODEL=gemini-3.8-flash ``` #### Via OpenRouter Access multiple providers through a single API: ```bash theme={null} OPENAI_ACCESS_TOKEN=your-openrouter-api-key OPENAI_URI_BASE=https://openrouter.ai/api/v1 OPENAI_MODEL=google/gemini-3.8-flash ``` Recommended models via OpenRouter: * `google/gemini-3.8-flash` - Fast and capable * `anthropic/claude-sonnet-4.5` - Excellent reasoning * `anthropic/claude-haiku-4.5` - Fast and cost-effective > [!NOTE] > > Cost estimates on the LLM usage screen work for OpenRouter models. Sure strips the `provider/` prefix from model names (for example, `google/gemini-3.8-flash` is priced as `gemini-3.8-flash`) before looking up the rate. Models not in Sure's pricing table show no estimated cost. ## Anthropic Sure can talk to Anthropic's Messages API directly, with full chat (text + streaming + tool use) parity with the OpenAI provider. ```bash theme={null} LLM_PROVIDER=anthropic ANTHROPIC_ACCESS_TOKEN=sk-ant-... # Optional — defaults to claude-sonnet-4-6 ANTHROPIC_MODEL=claude-sonnet-4-6 ``` Recommended models: * `claude-sonnet-4-6` - Default, best balance of speed and quality * `claude-haiku-4-5` - Fast and cost-effective Set `LLM_CONTEXT_WINDOW` to your model’s context size; the setting also applies to native Anthropic chat, even though its UI field is in the OpenAI panel. Values below 4096 collapse account and category rosters to counts. Larger values allow lists, but families with more than 25 visible accessible accounts or more than 60 categories still receive counts and use tools to retrieve the full lists. ### Custom Anthropic-compatible endpoints Set `ANTHROPIC_BASE_URL` to route requests through Amazon Bedrock, Google Vertex, or any other Anthropic-compatible proxy. `ANTHROPIC_MODEL` is required when a custom base URL is set, because proxy providers use their own model-ID conventions (for example, Bedrock IDs like `anthropic.claude-sonnet-4-5-20250929-v1:0`). ```bash theme={null} LLM_PROVIDER=anthropic ANTHROPIC_ACCESS_TOKEN=your-proxy-token ANTHROPIC_BASE_URL=https://your-proxy.example.com ANTHROPIC_MODEL=anthropic.claude-sonnet-4-5-20250929-v1:0 ``` ### Anthropic environment variables | Variable | Description | Default | | - | - | - | | `ANTHROPIC_ACCESS_TOKEN` *(or `ANTHROPIC_API_KEY`)* | API key for Anthropic (or a compatible proxy) | — | | `ANTHROPIC_MODEL` | Model name. Required when `ANTHROPIC_BASE_URL` is set | `claude-sonnet-4-6` | | `ANTHROPIC_BASE_URL` | Custom endpoint URL (Bedrock, Vertex, or other proxy). Leave blank for `api.anthropic.com` | — | | `ANTHROPIC_REQUEST_TIMEOUT` | HTTP timeout in seconds | `600` | | `ANTHROPIC_MAX_TOKENS` | Maximum tokens returned by the model on each chat turn | `4096` | ### Batch operations Auto-categorization, merchant detection, and provider-merchant enhancement are implemented on Anthropic via a single output tool whose `input_schema` mirrors the desired result. The `tool_choice` strategy depends on the model: * **Claude 3.x, 4.x, and Haiku 5.5** — uses `tool_choice: { type: "tool", disable_parallel_tool_use: true }` to force the model to call the tool. * **Claude 5 families (Opus 5.5, Sonnet 5.5, Fable 5.1, Mythos 5.1) and any model not in the forced list** — uses `tool_choice: { type: "auto", disable_parallel_tool_use: true }` and appends a fixed system prompt instruction telling the model to call the tool. This avoids forcing a tool choice on models outside Sure’s allowlist. Both strategies request structured tool output without the OpenAI-compatible JSON-mode fallback. A model can still omit the tool call or return an invalid result; Sure raises an error when the expected tool output is missing or malformed. Batch size is controlled by `LLM_MAX_ITEMS_PER_CALL` (default `25`), the same variable used by the OpenAI-compatible provider. Raise `ANTHROPIC_MAX_TOKENS` alongside it — the Messages API requires a reply-token limit and a large batch can exceed the default `4096` — or replies will be cut off. ## Token budget Sure applies a token budget to every outbound LLM call — chat history, auto-categorization, merchant detection, and PDF processing. The defaults are conservative (2048-token context window) so small-context local models like Ollama work out of the box. If you use a cloud provider or a larger-context local model, raise these values. ### Configure via settings UI 1. Go to **Settings** → **Self-Hosting** 2. Scroll to the **AI Provider** section 3. Under **Token Budget**, configure: * **Context Window** — total tokens the model accepts (default: `2048`) * **Max Response Tokens** — tokens reserved for the model's reply (default: `512`) * **Max Items Per Batch** — upper bound for auto-categorize and merchant detection batches (default: `25`) ### Configure via environment variables Environment variables take precedence over the settings UI. | Variable | Description | Default | | - | - | - | | `LLM_CONTEXT_WINDOW` | Total tokens the model will accept | `2048` | | `LLM_MAX_RESPONSE_TOKENS` | Tokens reserved for the model's reply. When set, this value is sent to the provider as `max_tokens` (Chat Completions) or `max_output_tokens` (Responses API). Leave unset to use the provider's default uncapped behavior. | `512` | | `LLM_MAX_HISTORY_TOKENS` | Maximum tokens for conversation history. Derived automatically if unset (`context_window - max_response_tokens - system_prompt_reserve`) | Derived | | `LLM_SYSTEM_PROMPT_RESERVE` | Tokens reserved for the system prompt | `256` | | `LLM_MAX_ITEMS_PER_CALL` | Upper bound on auto-categorize / merchant detection batch size | `25` | > [!NOTE] > > `LLM_MAX_ITEMS_PER_CALL` applies to all providers (both OpenAI-compatible and Anthropic). OpenAI-compatible providers split a batch that doesn't fit the context window; with the native Anthropic provider, raise `ANTHROPIC_MAX_TOKENS` alongside `LLM_MAX_ITEMS_PER_CALL` or replies may be cut off. ### Recommended values | Setup | Context window | Max response tokens | Max items per batch | | - | - | - | - | | Ollama / small local models | `2048` (default) | `512` (default) | `25` (default) | | Cloud OpenAI (gpt-4.1, gpt-5) | `16384` or higher | `4096` | `50` | | Cloud OpenAI (gpt-6-sol, gpt-6.1-sol) | `131072` or higher | `8192` | `50` | | Large-context local models | `8192` | `2048` | `50` | ## Responses API routing Sure automatically routes chat requests to the OpenAI Responses API when using the official OpenAI endpoint, and falls back to the Chat Completions API for custom providers. You can override this behavior with the `OPENAI_SUPPORTS_RESPONSES_ENDPOINT` environment variable. | Variable | Description | Default | | - | - | - | | `OPENAI_SUPPORTS_RESPONSES_ENDPOINT` | Set to `true` to force the Responses API on a custom provider, or `false` to force the Chat Completions API on all providers | Auto-detected | ## AI cache management Sure caches AI-generated results (like auto-categorization and merchant detection) to avoid redundant API calls and costs. ### What is the AI cache? When AI rules process transactions, Sure stores: * **Enrichment records** - Which attributes were set by AI (category, merchant, etc.) * **Attribute locks** - Prevents rules from re-processing already-handled transactions This caching means: * Transactions won't be sent to the LLM repeatedly * Your API costs are minimized * Processing is faster on subsequent rule runs ### When to reset the AI cache You might want to reset the cache when: * **Switching LLM models** - Different models may produce better categorizations * **Improving prompts** - After system updates with better prompts * **Fixing miscategorizations** - When AI made systematic errors * **Testing** - During development or evaluation of AI features > [!WARNING] > > Resetting the AI cache will cause all transactions to be re-processed by AI rules on the next run. This **will incur API costs** if using a cloud provider. ### How to reset the AI cache **Via UI (recommended):** 1. Go to **Settings** → **Rules** 2. Click the menu button (three dots) 3. Select **Reset AI cache** 4. Confirm the action The cache is cleared asynchronously in the background. You can monitor the reset's progress and any errors in **Settings → Debug** by filtering for the `ai_cache_reset` category. Each run logs when the job is enqueued, when it starts, how many AI cache entries were removed (broken down by scope), and any records that could not be cleared. **Automatic reset:** The AI cache is automatically cleared for all users when the OpenAI model setting is changed. This ensures that the new model processes transactions fresh. ### What happens when cache is reset * **AI-locked attributes are unlocked** - Transactions can be re-enriched * **AI enrichment records are deleted** - The history of AI changes is cleared * **User edits are preserved** - If you manually changed a category after AI set it, your change is kept ## Observability with Langfuse Sure can send traces of every LLM interaction to [Langfuse](https://langfuse.com) for debugging and usage analytics. Langfuse is open-source and can be self-hosted or used as a cloud service. Tracing uses the OpenTelemetry (OTel) protocol. Sure exports spans to Langfuse's OTLP endpoint using ingestion version 4. ### Setup 1. Create a Langfuse project (cloud or self-hosted). 2. Copy the public key and secret key from the project's settings. 3. Set the environment variables: ```bash theme={null} LANGFUSE_PUBLIC_KEY=your_public_key LANGFUSE_SECRET_KEY=your_secret_key # Optional: only needed when self-hosting Langfuse or using a non-default domain LANGFUSE_HOST=https://your-langfuse-domain.com ``` In Docker deployments, add these variables to `compose.yml` and the `.env` file. Sure reads them on boot and enables tracing automatically. When the keys are absent, Sure runs normally without Langfuse. ### What gets traced | Trace name | Description | | - | - | | `openai.chat_response` / `anthropic.chat_response` | Conversational AI assistant turns | | `openai.auto_categorize` / `anthropic.auto_categorize` | Background transaction categorization | | `openai.auto_detect_merchants` / `anthropic.auto_detect_merchants` | Background merchant detection | | `openai.process_pdf` / `anthropic.process_pdf` | PDF bank statement processing | The prefix identifies the provider. Traces and their child generations record inputs, outputs, the model, and token usage where available. Chat provider calls create separate traces grouped by session; tool executions do not currently have their own trace spans. ### Viewing traces After starting Sure with the variables set, open your Langfuse dashboard to see traces and their nested generations. Traces appear with their full name (for example, `openai.chat_response`); a chat turn that makes multiple provider calls can produce multiple traces. ## Evaluation system Test and compare different LLMs for your specific use case. The eval system helps you benchmark models for transaction categorization, merchant detection, and chat assistant functionality. See the [evaluation framework](/evals) documentation for details on: * Running evaluations * Comparing models * Creating custom datasets * Langfuse integration for tracking experiments ## Vector store (document search) Sure's AI assistant can search documents uploaded to a family's vault. Documents are indexed in a vector store, and the assistant retrieves relevant passages when answering questions. ### Supported backends | Backend | Status | Best for | Requirements | | - | - | - | - | | **OpenAI** (default) | Ready | Cloud deployments, zero setup | `OPENAI_ACCESS_TOKEN` | | **Pgvector** | Ready | Self-hosted, full data privacy | PostgreSQL with `pgvector` extension + embedding model | | **Qdrant** | Scaffolded — not yet functional | Self-hosted, dedicated vector DB | Running Qdrant instance | ### OpenAI (default) No extra configuration is needed. If you have `OPENAI_ACCESS_TOKEN` set for the AI assistant, document search works automatically. ### Pgvector (self-hosted) Use PostgreSQL's pgvector extension for fully local document search. All data stays on your infrastructure. **Requirements:** * Use the `pgvector/pgvector:pg16-trixie` Docker image instead of `postgres:16` * An embedding model served via an OpenAI-compatible `/v1/embeddings` endpoint (for example, Ollama with `mxbai-embed-large`) * Run migrations with `VECTOR_STORE_PROVIDER=pgvector` set to create the `vector_store_chunks` table ```bash theme={null} VECTOR_STORE_PROVIDER=pgvector EMBEDDING_MODEL=mxbai-embed-large # Default: mxbai-embed-large EMBEDDING_DIMENSIONS=1024 # Must match your embedding model (default: 1024) EMBEDDING_URI_BASE=http://ollama:11434/v1 # Falls back to OPENAI_URI_BASE if not set EMBEDDING_ACCESS_TOKEN= # Optional; falls back to OPENAI_ACCESS_TOKEN ``` The LLM and embedding endpoints are independent. A common fully local setup uses an OpenAI-compatible chat model via `OPENAI_URI_BASE`, pgvector for storage, and a separate embedding model via `EMBEDDING_URI_BASE`. Sure enables the `vector` extension automatically when it first provisions the chunks table, provided the database user has permission. If the AI status page reports the extension is available but not enabled, connect as the PostgreSQL superuser and run: ```sql theme={null} CREATE EXTENSION vector; ``` If you use Ollama, pull the embedding model before starting Sure: ```bash theme={null} docker compose exec ollama ollama pull mxbai-embed-large ``` > [!WARNING] > > Do not change `EMBEDDING_MODEL` for an existing pgvector index without rebuilding it. Vectors from different models are not comparable even when they have the same dimensions. Remove existing documents from Sure, drop the chunks table, update the embedding settings, restart Sure, and re-upload the source documents. ### Verifying the configuration Super-admins can open **System health → AI** at `/admin/system_health?tab=ai` to run live checks. The tab verifies: * The configured LLM model is accessible * The vector store responds correctly * The embedding endpoint returns vectors with the expected dimensions These checks run from the `web` process. To verify that worker processes can also reach the configured provider, click **Verify worker configuration** on the same tab. See [AI status tab](/self-hosting#ai-status-tab) and [Verifying worker configuration](/self-hosting#verifying-worker-configuration) in the self-hosting guide for details on the checks, worker-specific caveats, and how to tune probe timeouts. ## Additional environment variables These optional variables fine-tune provider selection and the behavior of the OpenAI-compatible provider. See [Anthropic environment variables](#anthropic-environment-variables) for the Anthropic-specific options. | Variable | Description | Default | | - | - | - | | `LLM_PROVIDER` | Active LLM provider: `openai` or `anthropic`. Takes precedence over any provider choice saved in the UI. | `openai` | | `OPENAI_ACCESS_TOKEN` | API key for the provider | — | | `OPENAI_URI_BASE` | Custom endpoint URL (leave blank for OpenAI) | — | | `OPENAI_MODEL` | Model name (required for custom endpoints). A blank value is treated as unset and falls through to the UI setting, then `gpt-4.1` | `gpt-4.1` | | `OPENAI_REQUEST_TIMEOUT` | HTTP timeout in seconds for each individual HTTP call to the model | `60` | | `AI_RESPONSE_TIMEOUT` | Whole-turn watchdog timeout in seconds. See [Chat response timeout](#chat-response-timeout) for sizing guidance | `90` | | `ASSISTANT_MAX_TOOL_CALL_ITERATIONS` | Maximum number of tool-call rounds per chat turn | `8` | | `OPENAI_SUPPORTS_PDF_PROCESSING` | Set to `false` for endpoints without vision support | `true` | | `OPENAI_SUPPORTS_RESPONSES_ENDPOINT` | Override Responses API vs Chat Completions routing | Auto-detected | | `LLM_JSON_MODE` | JSON output mode for OpenAI-compatible categorization and merchant-detection calls, plus text-based PDF and bank-statement extraction: `auto`, `strict`, `json_object`, or `none`. For OpenAI-compatible categorization and merchant detection, `auto` tries strict JSON first and retries once with `none` if strict is rejected with HTTP 400, the response is malformed, or more than 50% of requested results fail or are missing. Text-based PDF and bank-statement extraction do not use this retry wrapper. | — | Native OpenAI Responses calls and PDF vision processing do not use `LLM_JSON_MODE`. For text extraction without a JSON schema, `strict` falls back to `json_object`. See [Token budget](#token-budget) for `LLM_CONTEXT_WINDOW`, `LLM_MAX_RESPONSE_TOKENS`, and related variables. ## Chat response timeout Sure uses two separate timeouts for AI chat turns: * **`OPENAI_REQUEST_TIMEOUT`** — bounds each individual HTTP call to the model. The default is `60` seconds. * **`AI_RESPONSE_TIMEOUT`** — a whole-turn watchdog that starts when the message is queued and covers everything: queue wait, every model call, and all tool executions in between. The default is `90` seconds, which is sized for typical cloud latency. ### Why the default 90 seconds is often too short for local models Custom OpenAI-compatible providers (Ollama, LM Studio, etc.) route through a synchronous code path, so nothing renders until the full reply is generated. On top of that, a tool-using turn runs multiple model calls in sequence. The total time the watchdog must cover is: ```text theme={null} (1 + ASSISTANT_MAX_TOOL_CALL_ITERATIONS) × OPENAI_REQUEST_TIMEOUT + tool execution time + queue wait ``` With the defaults (`ASSISTANT_MAX_TOOL_CALL_ITERATIONS=8`, `OPENAI_REQUEST_TIMEOUT=60`), a worst-case turn takes up to 540 seconds of model time — far beyond the 90-second watchdog. The chat will report "assistant not available" even though the model is still generating a reply. ### Recommended approach The cheapest lever is lowering `ASSISTANT_MAX_TOOL_CALL_ITERATIONS` rather than setting a very large timeout. Fewer iterations means a shorter worst-case bound, and long tool chains fail with a clear limit error instead of a silent timeout. For a local Ollama setup with slow generation: ```bash theme={null} OPENAI_REQUEST_TIMEOUT=300 ASSISTANT_MAX_TOOL_CALL_ITERATIONS=3 # (1 + 3) × 300 = 1200s model time + ~300s headroom = 1500 AI_RESPONSE_TIMEOUT=1500 ``` In `compose.yml`, pass `ASSISTANT_MAX_TOOL_CALL_ITERATIONS` alongside the other AI variables so the setting actually reaches the `web` and `worker` containers: ```yaml theme={null} x-rails-env: &rails_env OPENAI_REQUEST_TIMEOUT: "300" ASSISTANT_MAX_TOOL_CALL_ITERATIONS: "" # leave empty to use the app default (8) AI_RESPONSE_TIMEOUT: "1200" ``` Leave the value empty to let the app's own default govern, or set it explicitly to cap tool-call rounds. For cloud providers (OpenAI, Anthropic) the defaults are usually fine. If you see timeouts, raise `AI_RESPONSE_TIMEOUT` using the formula above. > [!NOTE] > > `AI_RESPONSE_TIMEOUT` must be sized as a sum, not just set above `OPENAI_REQUEST_TIMEOUT`. The watchdog covers the entire turn — queue wait, every model call, and all tool executions — so the bound is: > > ```text theme={null} > (1 + ASSISTANT_MAX_TOOL_CALL_ITERATIONS) × OPENAI_REQUEST_TIMEOUT > + tool execution time + queue wait > ``` > > Setting `AI_RESPONSE_TIMEOUT` equal to or below `OPENAI_REQUEST_TIMEOUT` means any tool-using turn will always time out. The 90-second default is sized for typical cloud latency; use the formula above once per-call latency approaches the timeout. ### Configure via settings UI `AI_RESPONSE_TIMEOUT` is also configurable from the web interface: 1. Go to **Settings** → **Self-Hosting** 2. Scroll to the **AI Provider** section 3. Set **Chat Response Timeout** to your desired value in seconds The environment variable takes precedence over the UI setting. The minimum accepted value is 30 seconds. ## Docker compose example ### Basic Ollama setup ```yaml theme={null} services: sure: environment: - OPENAI_ACCESS_TOKEN=ollama-local - OPENAI_URI_BASE=http://ollama:11434/v1 - OPENAI_MODEL=llama3.1:13b # Optional: raise token budget for larger-context models # - LLM_CONTEXT_WINDOW=8192 # - LLM_MAX_RESPONSE_TOKENS=2048 # - LLM_MAX_ITEMS_PER_CALL=50 depends_on: - ollama ollama: image: ollama/ollama:latest ports: - "11434:11434" volumes: - ollama_data:/root/.ollama # Uncomment if you have an NVIDIA GPU # deploy: # resources: # reservations: # devices: # - driver: nvidia # count: 1 # capabilities: [gpu] volumes: ollama_data: ``` ### Advanced AI setup with OpenClaw For advanced AI features including code execution and tool use, you can use the `local-ai` profile with OpenClaw: ```yaml theme={null} services: sure: profiles: - local-ai environment: - OPENAI_ACCESS_TOKEN=ollama-local - OPENAI_URI_BASE=http://openclaw:8080/v1 - OPENAI_MODEL=llama3.1:13b depends_on: - openclaw - ollama openclaw: image: openclaw/openclaw:latest profiles: - local-ai ports: - "8080:8080" environment: - OLLAMA_HOST=http://ollama:11434 depends_on: - ollama ollama: image: ollama/ollama:latest profiles: - local-ai ports: - "11434:11434" volumes: - ollama_data:/root/.ollama volumes: ollama_data: ``` To use the local AI setup: ```bash theme={null} # Start with local AI profile docker compose --profile local-ai up # Or include it with other profiles docker compose --profile local-ai --profile external-assistant up ``` The `local-ai` profile includes: * **Ollama** - Local LLM inference * **OpenClaw** - Gateway providing enhanced AI capabilities and tool use * Automatic routing between Sure and the AI stack ## Custom AI prompts Family admins can override the built-in prompts from **Settings → AI Prompts** — no fork or redeploy required. Overrides are stored per family, so one family's edits never affect another on the same deployment. Six prompts are editable: | Prompt | What it controls | | - | - | | Chat system prompt | The static instructions the assistant follows in every conversation | | Categorizer (OpenAI) | Instructions for the background transaction categorization job | | Categorizer (Anthropic) | Same, when using an Anthropic provider | | Merchant detector (OpenAI) | Instructions for the background merchant detection job | | Merchant detector (Anthropic) | Same, when using an Anthropic provider | | Insight Dig In | The first message pre-filled in the assistant when a user clicks **Dig in with AI** on an insight card | Each field opens with the current default text for your deployment, or the saved override if one exists. Clearing a field resets it to the default. The **Reset to default** button asks for confirmation before restoring the original text. A live character counter and status label sit below each field. The limit is 20,000 characters per prompt. **When using a custom OpenAI-compatible endpoint** (`OPENAI_URI_BASE` set), the categorizer and merchant detector fields show the terse variant those models receive. A single override replaces both the terse and detailed variants, so editing the field on a custom endpoint affects local models only. ### How the chat prompt works The builtin assistant's system prompt has two parts: a static half (`STATIC_INSTRUCTIONS`) that is byte-identical on every request so providers can cache it, and a volatile `## Session context` block that holds the current date, currency, account roster, and categories. Only the static half is editable here. What you can adjust: tone and personality, response format, domain-specific rules and constraints. Overriding the chat prompt gives up prefix caching for that family. The static half is normally byte-stable across all families sharing an API key; a family that overrides it gets its own prefix, which is not shared with others. The first request after each save also pays the full uncached price. ### Output format warnings for categorizer and merchant prompts The categorizer and merchant parsers expect a specific JSON structure (`{"categorizations": [...]}` or `{"merchants": [...]}`). Sure also asks for those keys in a per-request message that your override cannot replace, so rewording the example is generally safe. Parsing breaks when an override contradicts the output format — for example, asking for reasoning before the answer, using a different wrapper key, or requesting YAML instead of JSON. Smaller local models tend to follow the system prompt over the per-request instruction. For that reason, the editor warns when a custom OpenAI override removes the example JSON block, even though the request-level fallback usually covers it. ## External AI assistant Instead of using the built-in LLM, you can delegate chat to an external AI agent. The agent receives the conversation, can call back to Sure's financial data via MCP, and streams a response back. This is useful when: * You have a custom AI agent with domain knowledge, memory, or personality. * You want to use a non-OpenAI-compatible model (the agent handles translation). * You want to keep LLM credentials and logic entirely outside Sure. > [!NOTE] > > The external assistant handles chat only. Auto-categorization and merchant detection still use the configured LLM provider (`OPENAI_ACCESS_TOKEN` for OpenAI-compatible providers, or Jev if you have selected it as the categorization provider). ### How it works 1. A user sends a message in the Sure chat UI. 2. Sure forwards the conversation to your agent's API endpoint (OpenAI chat completions format). 3. Your agent processes it using whatever LLM, tools, or context it needs. 4. Your agent can call Sure's `/mcp` endpoint for financial data and actions (accounts, transactions, balance sheet, budgets, file search, statement import, goals). 5. Your agent streams the response back to Sure via Server-Sent Events (SSE). The agent's API must be OpenAI chat completions compatible: accept `POST` with a `messages` array and return SSE with `delta.content` chunks. ### Configuration **Settings UI:** 1. Go to **Settings → Self-Hosting**. 2. Set **Assistant type** to "External (remote agent)". 3. Enter the **Endpoint URL** and **API Token** from your agent provider. 4. Sure loads the available agents from the endpoint's `/v1/models` response and shows them in the **Agent** dropdown. Select the agent that should handle conversations. **Environment variables:** ```bash theme={null} ASSISTANT_TYPE=external # Global override (or set per-family in UI) EXTERNAL_ASSISTANT_URL=https://your-agent/v1/chat/completions EXTERNAL_ASSISTANT_TOKEN=your-api-token EXTERNAL_ASSISTANT_MODEL=openclaw/main # Agent identifier from /v1/models; defaults to openclaw/main EXTERNAL_ASSISTANT_SESSION_KEY=agent:main:main # Optional, for session persistence EXTERNAL_ASSISTANT_ALLOWED_EMAILS=user@example.com # Optional, comma-separated allowlist ``` When environment variables are set, the corresponding UI fields are disabled and the env values take precedence. Set `ASSISTANT_TYPE=external` to route all users to the external agent globally. Without it, routing falls back to each family's `assistant_type` setting in the UI (default: `builtin`). > [!NOTE] > > `EXTERNAL_ASSISTANT_AGENT_ID` is a legacy variable kept for backwards compatibility. Use `EXTERNAL_ASSISTANT_MODEL` for new installs. ### MCP callback endpoint Sure exposes a Model Context Protocol (MCP) endpoint at `/mcp` so your external agent can call back and query financial data. **Authentication:** Bearer token via `Authorization` header. Sure supports both OAuth bearer tokens (via its discovery and registration endpoints) and static bearer tokens configured with `MCP_API_TOKEN` and `MCP_USER_EMAIL`. **Static-token environment variables:** ```bash theme={null} MCP_API_TOKEN=your-secret-token # Bearer token the agent sends to authenticate MCP_USER_EMAIL=user@example.com # Email of the Sure user the agent acts as ``` See [MCP server for external AI assistants](/self-hosting-mcp) for the full list of available tools and protocol details. ### Access control Use `EXTERNAL_ASSISTANT_ALLOWED_EMAILS` to restrict which users can access the external assistant. When set, only users whose email is in the comma-separated list see the AI chat. When blank, all users have access. ### Docker Compose example ```yaml theme={null} x-rails-env: &rails_env ASSISTANT_TYPE: external EXTERNAL_ASSISTANT_URL: https://your-agent/v1/chat/completions EXTERNAL_ASSISTANT_TOKEN: your-api-token MCP_API_TOKEN: your-mcp-token MCP_USER_EMAIL: user@example.com ``` You can also configure the assistant via the Settings UI after startup; the MCP environment variables are still required for agent callbacks. # Akahu Source: https://docs.sure.am/providers/akahu Connect New Zealand bank accounts to Sure via Akahu Akahu is a New Zealand open banking platform. Sure connects to it using your personal app token and user token, syncing bank and investment account balances and transactions automatically. > [!NOTE] > > Akahu support is in beta. Functionality is working but may have rough edges. Report issues in the [Discord](https://discord.gg/36ZGBsxYEK). See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works 1. Create an Akahu account and register a personal app to get your app token and user token 2. Paste both tokens into Sure 3. Sure discovers your Akahu accounts and begins syncing balances and transactions 4. Choose how each discovered account should appear in Sure (Cash, Credit Card, Investment, or Loan) ## Prerequisites * An [Akahu](https://akahu.nz/) account connected to your New Zealand bank accounts * A personal app token and user token from the Akahu developer portal ## Setting up Akahu ### Get your tokens 1. Sign in to the [Akahu developer portal](https://developers.akahu.nz/) 2. Create a personal app — give it a name and description 3. Copy your **app token** (used to identify your application) 4. Follow the Akahu authorization flow to get your **user token** (grants access to your accounts) ### Connect Akahu in Sure 1. In Sure, go to **Settings > Bank sync** 2. Find the **Akahu** panel and enter your app token and user token 3. Click **Save** — Sure initiates a first sync to discover your accounts 4. Go to the **Accounts** tab and run account setup to choose how each Akahu account should appear ### Link discovered accounts After the first sync, Sure shows all accounts returned by Akahu but not yet linked. For each one: 1. Choose an account type: **Cash**, **Credit Card**, **Investment**, or **Loan** — or skip accounts you do not want to track 2. Click **Create accounts** to create the selected accounts and begin syncing them You can also link a discovered Akahu account to an existing Sure account if you already track that account manually. ## Supported account types Akahu can return bank accounts, savings accounts, investment accounts, and credit cards. You choose how each one maps to a Sure account type during setup. ## Syncing Sure syncs Akahu accounts on demand. Trigger a sync from the account card or provider panel at any time. Transactions include date, amount, and description, plus optional reference, particulars, and code fields when your bank provides them. ## Troubleshooting **"Configure Akahu in provider settings first" error**: If you see this alert when trying to add an Akahu account, the selected connection is missing an app token or user token. Go to **Settings > Providers > Akahu**, enter both tokens, and save before adding accounts. **Connection shows "requires update"**: Your user token may have expired or been revoked. Re-enter the token in **Settings > Bank sync > Akahu**. **Accounts not appearing after setup**: Trigger a manual sync from the Akahu provider panel. If accounts still do not appear, confirm your tokens are valid and that the accounts are visible in the Akahu portal. **Transactions missing**: Akahu transactions are fetched using cursor-based pagination. A first sync retrieves recent history. Older history may not be available depending on your bank's data retention. For Akahu API documentation, see [developers.akahu.nz](https://developers.akahu.nz/). # Apple Wallet Source: https://docs.sure.am/providers/apple-wallet Connect Apple Card and Apple Cash accounts via FinanceKit on iOS Apple Wallet integration uses Apple's FinanceKit framework to import Apple Card, Apple Cash, and family Apple Cash accounts directly from your iPhone. No Apple credentials reach the Sure server: the iOS app obtains authorization from Apple and uploads only the accounts you selected. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## Requirements Apple Wallet sync requires no server-side configuration. There is no feature flag and no family allowlist — any deployment running this code serves the FinanceKit endpoints automatically. The enrolling user must be a family administrator. No Apple entitlement, private key, or FinanceKit framework is needed on the server. ## How it works 1. The iOS app prompts the user to authorize access to Wallet accounts via FinanceKit. 2. The app creates a publisher enrollment and maps the selected Apple accounts to Sure accounts. 3. The app uploads encrypted batches of transactions and balances to Sure's server. 4. Sure's background worker applies each batch in sequence, creating or updating accounts and transactions. Sure records the following for each Apple Wallet connection: * **Apple Card** — credit card account with purchases, payments, and pending activity. * **Apple Cash** — depository (cash) account with top-ups and purchases. * **Family member Apple Cash** (e.g. Nancy's Apple Cash) — a separate depository account per family member. ## Viewing your connection Once connected, Apple Wallet appears under **Settings → Bank Sync** alongside other providers. The panel shows: * **Status** — `Sync active` when the connection is healthy, or `Repair required — open the Sure iOS app` when the connection needs attention. * **Last accepted by Sure** — when Sure last durably stored an upload from the device. * **Last imported into your family** — when the background worker last applied a batch to your ledger. * **Linked accounts** — the accounts connected through this publisher, each with a link to the account page. All connected accounts also appear in the main **Accounts** list. ## Unlinking You can unlink a Wallet connection from the web UI. Because a single publisher credential covers all selected Wallet accounts, unlinking one disconnects the entire Wallet connection and makes its accounts manual. Unlinking: * Revokes the publisher credential and queued uploads * Preserves existing accounts, balances, transactions, and source identities * Does not delete any financial data To reconnect, open the iOS app and start a new enrollment. Sure reuses existing accounts and imported transactions without requiring the old connection or stream state. ## Transaction dates `posted_at` is optional, including for booked Apple Card transactions. When supplied, it must be a valid timestamp no later than the capture timestamp. Sure assigns ledger dates using this order of precedence: `posted_at`, then the required `transacted_at`, both converted into the mapped account's ledger timezone. ## Debugging uploads Super admins can view upload events at `/settings/debug?provider_key=financekit`. Filter further by family, log level, or source. Events share `connection_id`, `publisher_id`, `generation`, `stream_id`, and `next_sequence`. | Event | Meaning | | - | - | | `upload_accepted` | Sure stored the upload. Acceptance does not mean import is complete. A sequence ahead of `next_sequence` is waiting for its predecessor; a multi-chunk capture waits for all chunks. | | `upload_rejected` | A typed protocol error and HTTP status were recorded. Identical accepted retries reuse their receipt without re-logging. | | `capture_imported` | Records the resulting sync ID and counts, including records requiring conflict review. | | `import_retry` | Includes attempt count, retry deadline, error code, and exception class. | | `import_failed` | Repair is required. | | `import_blocked` | Failure occurred before a batch could be selected. | | `downstream_completed` | Account updates and rules were scheduled. | | `downstream_failed` | Includes the affected account or provider link when available; the inbox sweep retries this stage. | Diagnostics omit exception messages, financial payloads, credentials, transaction descriptions, merchant names, and amounts. Requests rejected before reaching the batch inbox (such as invalid credentials or wrong content type) do not create these events. ## Demo and sample data The standard demo account includes a synthetic Apple Wallet connection with: * **Apple Card** (CreditCard) — a year of purchases, payments, and pending activity * **Apple Cash** (Depository, cash) — top-ups, purchases, and 1% Daily Cash rewards from Apple Card activity * **Nancy's Apple Cash** — gifts from the parent account plus small purchases Wallet demo data is included in every environment by both the full generator and the sample-data reset flow. It does not enable FinanceKit feature flags or change user permissions. To add just the Wallet accounts to an existing demo family without replacing other data: ```sh theme={null} FAMILY_ID= bin/rails demo_data:financekit ``` Alternatively use `DEMO_EMAIL=` (defaults to the configured demo email). `SEED=42` controls generated amounts and merchants. Reruns preserve the existing enrollment and transactions and upgrade older synthetic data with merchant-specific categories and paired transfers. ## Capacity limits | Limit | Value | | - | - | | Selected accounts per publisher | 20 | | Events per batch | 500 | | Payload size per batch | 1 MiB | | Queued batches per publisher | 100 | | Chunks per capture | 100 | Payload bytes are retained for seven days after apply, permanent failure, or revocation for response-loss recovery. Financial data and source identity records follow Sure's normal family retention and deletion behavior. A family financial-data reset removes FinanceKit connections, lineages, observations, identities, conflicts, and batch receipts for that family. ## Self-hosting deployment checklist Before accepting Apple Wallet connections on a new instance: 1. Deploy the migration, application, worker, and scheduler. 2. Confirm the high-priority job queue and recurring `FinancekitInboxJob` scheduler are healthy. 3. Enroll and activate a synthetic publisher over HTTPS using a disposable test family. 4. Upload sequences 2 then 1 and confirm the inbox applies them in order. 5. Retry identical bytes and confirm the receipt is stable with no ledger duplicates. 6. Rotate the credential and confirm the prior credential cannot upload or call normal APIs. 7. Replace the publisher and confirm canonical accounts, source identities, and tombstones are reused. 8. Induce a bad predecessor and confirm the connection enters `repair_required`; repair must create a new generation and stream. 9. Confirm health reports device contact, acceptance, import, and downstream completion separately. 10. Confirm applied, permanently failed, and revoked payload bytes are removed after seven days. # Binance Source: https://docs.sure.am/providers/binance Connect your Binance account to track cryptocurrency holdings, balances, and trades Binance integration allows you to sync your cryptocurrency accounts, track holdings across spot, margin, and earn products, and monitor trades directly in Sure using the Binance API. > [!NOTE] > > This integration is currently in beta. Please report any issues you encounter. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works When you connect your Binance account, Sure syncs: * Spot wallet balances * Cross-margin account balances (net assets) * Simple Earn positions (flexible and locked) * Spot trade history * Holdings with daily valuations All three account types (spot, margin, and earn) are combined into a single cryptocurrency account in Sure, with a unified USD-denominated balance. ## Prerequisites To use the Binance integration, you need: * An active Binance account * Binance API credentials (API key and API secret) * API key permissions for reading account data and trade history ## Getting your API credentials 1. Log in to your [Binance account](https://www.binance.com) 2. Navigate to **Account** > **API Management** 3. Create a new API key with the following permissions: * Enable reading (view account information, balances, and trade history) 4. Save your API key and API secret securely > [!WARNING] > > Your API secret is only shown once during creation. Store it securely — you'll need both the API key and secret to connect Sure. > [!WARNING] > > Do not enable withdrawal or trading permissions on your API key. Sure only requires read access. > [!TIP] > > For security, restrict your API key to read-only access. Sure does not execute trades or withdrawals on your behalf. ## Connecting Binance to Sure You can connect Binance from the **Add Account** dialog or from **Settings** > **Providers**. **From Add Account:** 1. Open the **Add Account** dialog and select **Crypto** > **Binance**. 2. Sure opens account setup for your Binance connection directly. This direct route requires one eligible connection or an explicitly selected connection. With multiple connections and no selection, Sure sends you to **Settings** > **Providers** to choose one; if none are configured, add one there first. **From Settings > Providers:** 1. Navigate to **Settings** > **Providers** in Sure. 2. Click **Connect** on the **Binance** card. 3. Enter your API credentials: * **Name**: A label for this connection (e.g., "My Binance") * **API Key**: Your Binance API key * **API Secret**: Your Binance API secret 4. Optionally set a **Sync start date** to limit how far back trade history is fetched. The date must be in the past. 5. Click **Connect**. ## Account setup The first sync discovers Binance accounts and marks unlinked accounts as needing setup. Open setup from **Add Account** or **Import accounts** on the connection card: 1. Review the discovered Binance accounts. 2. Select the accounts you want to import. 3. Click **Save** to complete the setup. After saving, Sure syncs the newly imported accounts and returns you to where you started. > [!NOTE] > > If you open **Add Account** > **Crypto** > **Binance** and no credentials are configured, or the selected connection is unavailable, Sure redirects you to **Settings** > **Providers** with an alert so you can add or fix the connection first. > [!NOTE] > > Spot, margin, and earn balances are combined into a single account. They are not tracked separately. ## Supported features ### Account types The Binance integration syncs data from: * **Spot wallet** — free and locked balances for all assets * **Cross-margin** — net asset balances (assets minus borrowed amounts) * **Simple Earn** — flexible and locked staking/savings positions ### Holdings tracking Sure creates a daily holding record for each asset, including: * Current quantity per asset and source (spot, margin, earn) * Price data from Binance market data * Valuations converted to your family's preferred currency When Binance reports that an asset is no longer in your wallet, Sure removes it from today's holdings so your portfolio stays accurate. Assets are removed based on what the latest sync reports, not on individual price lookups — a temporary pricing outage does not cause a holding to disappear. If one of the Binance sources (spot, margin, or earn) is temporarily unavailable during a sync, Sure carries forward the last known positions for that source rather than treating the silence as an empty wallet. The held positions are refreshed as soon as that source responds again. ### Trade syncing Sure syncs your spot trade history, including: * Buy and sell trades * Trade price and quantity * Commission and fees * Support for multiple quote currencies (USDT, BUSD, FDUSD, BTC, ETH, BNB) Trades are synced incrementally — only new trades are fetched on subsequent syncs. ### Currency handling * The account is created in your family's currency. Spot and futures trade entries are stored in USD after quote-currency conversion; P2P entries retain their fiat currency. * Stablecoins (USDT, BUSD, FDUSD, TUSD, USDC, DAI) are treated as 1:1 with USD. * The initial current balance is the provider balance converted into your family's currency, or zero if a conversion rate is unavailable. A subsequent sync updates the converted balance when rate data is available. ### Opening balance New Binance exchange accounts have a zero historical opening anchor, separate from the current balance imported from the provider. After importing entries, Sure moves that zero anchor to the day before the earliest entry only if it is not already earlier. Existing nonzero opening anchors are preserved. ## Security ### Credential encryption Your Binance API credentials are encrypted using ActiveRecord Encryption: * **API Key**: Uses deterministic encryption for querying * **API Secret**: Uses standard encryption for maximum security ### Read-only access Sure only requires read permissions on your Binance API key. No withdrawal or trading permissions are needed. ### API timeouts All Binance API requests include a 30-second timeout to prevent hanging connections. ## Syncing ### Manual sync To manually sync your Binance account, an admin can use either of these options: * On the **Accounts** page, find your Binance connection card and click the refresh icon in the header row. * Go to **Settings** > **Providers**, find your Binance connection, and click **Sync**. ### Automatic sync Sure automatically syncs your Binance account on a regular schedule along with your other connected accounts. ## Limitations * Only spot, cross-margin, and Simple Earn accounts are supported — futures, options, and other Binance products are not included * Margin balances reflect net assets (assets minus borrowed), not gross positions * Margin and Earn transaction history is not currently synced (only current balances) * Historical trade data depends on Binance API availability and retention * Real-time price updates depend on Binance market data availability ## Troubleshooting ### Credentials need updating If the Binance connection card shows "Credentials need updating", Sure could not read a configured API key and secret. This warning alone does not establish that the provider revoked a key. Click **Update credentials** in the connection card header to go to **Settings** > **Providers**, then enter your new API key and secret. ### Connection errors If you encounter connection errors: 1. Verify your API credentials are correct 2. Check that your API key has the required read permissions 3. Ensure your API key hasn't been revoked or expired ### Missing balances If balances are missing: 1. Manually trigger a sync 2. Check that the asset has a non-zero balance on Binance 3. Verify the account type (spot, margin, earn) is supported 4. Verify the account is linked in Sure If a source such as margin or Earn is temporarily unavailable, Sure preserves the last known positions for that source and logs the issue to **Settings** > **Debug** against the connection. Check there for details on any sync warnings. ### Missing trades If trades are missing: 1. Check that your API key has trade history read permissions 2. Verify the trade exists in your Binance account 3. Ensure the sync start date is set to a past date that falls before the trade date ### Stale holdings after selling If a sold asset continues to appear in your portfolio, manually trigger a sync. Sure removes holdings that Binance no longer reports as part of the wallet during each sync. ### Stale rate warnings If you see stale rate warnings on certain holdings, this means Sure couldn't find a recent exchange rate for that asset. This can happen with low-liquidity tokens. ### Account linking issues If you have trouble linking accounts: 1. Ensure you've completed the account setup after connecting 2. When linking to an existing account, verify it's a manual crypto account 3. Try unlinking and relinking the account ## Getting help If you encounter issues with the Binance integration: * Check the [troubleshooting guide](/guides/knowledge-base/troubleshooting) * Ask in the [Discord](https://discord.gg/36ZGBsxYEK) * Open an [issue](https://github.com/we-promise/sure/issues/new/choose) # Brex Source: https://docs.sure.am/providers/brex Connect Brex business cash and card accounts to Sure Brex is a business financial platform offering corporate cards, cash management accounts, and expense tracking. Sure connects to Brex using a read-only API token you generate from the Brex developer settings. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works Sure uses the Brex API to pull account balances and transaction history directly into your family's accounts. Each Brex company you want to connect requires its own named connection and API token. ## Setting up Brex ### Step 1: Generate a Brex API token 1. Log in to [brex.com](https://brex.com) with the account you want to connect. 2. Go to the Brex developer or API token settings for the company. 3. Create a new API token with the following read-only scopes: * `accounts.cash.readonly` * `accounts.card.readonly` * `transactions.cash.readonly` * `transactions.card.readonly` 4. Copy the generated token. ### Step 2: Add the connection in Sure 1. Go to **Settings → Providers**. 2. Find the **Brex** section. 3. Enter a connection name (for example, "Business checking") and paste the token. 4. Leave the **Base URL** field blank for production. The field is available for Brex-approved staging environments only and does not accept customer tokens. 5. Click **Add Brex connection**. Sure begins syncing your accounts automatically after saving the connection. ### Step 3: Set up accounts After the first sync, Brex accounts appear in the setup queue. Go to the connection panel and click **Set up accounts** to assign each account an account type (checking, savings, credit card, and so on) and a transaction history start date before they appear in your account list. You can sync up to three years of transaction history. ## Multiple companies Use a separate named connection for each Brex company or API token you want to sync. Each connection is independent and syncs only the accounts accessible to its token. ## Encryption Brex API tokens are stored using ActiveRecord Encryption when encryption keys are configured in your deployment. Without encryption keys, tokens are stored in plaintext. Configure `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`, `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY`, and `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT` before adding tokens in a production environment. ## Account types Brex exposes two kinds of accounts: | Kind | Description | | - | - | | Cash | Brex cash management accounts | | Card | Brex corporate card accounts | During account setup you choose the Sure account type (checking, savings, credit card, and so on) that matches each imported account. ## Transaction classification Sure automatically classifies certain Brex card transactions when importing: * **Credit card payments**: A card account transaction with type `COLLECTION` and a negative amount is classified as a credit card payment transfer (`cc_payment`). This covers the payment from your bank to your Brex card. * **Refunds and credits**: A `COLLECTION` transaction with a positive amount (money returned to the card) is imported as a regular transaction, not a credit card payment. This means refunds and statement credits appear in your transaction list rather than being treated as payments, so they show up correctly in budgets and reports. ## Troubleshooting ### Invalid API token Check that you copied the full token and that the token has not been revoked. Generate a new token from the Brex developer settings if needed. ### Insufficient permissions The token must include all four required scopes: `accounts.cash.readonly`, `accounts.card.readonly`, `transactions.cash.readonly`, and `transactions.card.readonly`. Regenerate the token with the correct scopes. ### Expired credentials Brex tokens can expire or be revoked. When Brex rejects the token with a 401 or 403, Sure marks the connection as requiring an update and the sync fails — the connection card shows a **Reconnect** prompt instead of a green "Connected" status. This also applies when the token can list your accounts but is refused access to their transactions. Generate a new token and update the connection in **Settings → Providers → Brex**. ### No accounts found after syncing If the connection syncs successfully but no accounts appear, click **Set up accounts** in the connection panel to review unlinked accounts and assign types. # Coinbase Source: https://docs.sure.am/providers/coinbase Connect your Coinbase account to track cryptocurrency holdings and transactions Coinbase integration allows you to sync your cryptocurrency accounts, track holdings, and monitor transactions directly in Sure using the Coinbase Developer Platform (CDP) API. > [!NOTE] > > This integration is currently in beta. Please report any issues you encounter. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works When you connect your Coinbase account, Sure syncs: * Account balances across multiple cryptocurrencies * Trading history and transactions * Holdings with real-time valuations * Native currency support (USD, EUR, GBP, etc.) The integration supports both cryptocurrency balances and fiat currency accounts linked to your Coinbase profile. ## Prerequisites To use the Coinbase integration, you need: * An active Coinbase account * Coinbase CDP API credentials (API key and API secret) ## Getting your API credentials 1. Log in to your [Coinbase Developer Platform](https://portal.cdp.coinbase.com/) account 2. Navigate to Settings → API 3. Create a new API key with the following permissions: * View account information * View transaction history * View balances 4. Save your API key and API secret securely > [!WARNING] > > Your API secret is only shown once. Store it securely - you'll need both the API key and secret to connect Sure. ## Connecting Coinbase to Sure 1. Navigate to **Settings** > **Bank sync** in Sure 2. Click **Connect** on the **Coinbase** card 3. Enter your API credentials: * **API Key**: Your Coinbase API key * **API Secret**: Your Coinbase API secret 4. Click **Connect** ## Account linking After connecting, Sure discovers your Coinbase wallets through the initial sync. You can link them in two ways: * **From Add Account**: Open the Add Account dialog, choose **Crypto** > **Coinbase**, and Sure opens wallet setup directly when there is exactly one active connection with configured credentials, or when a specific connection was selected. After you finish, Sure returns you to where you started. * **From Settings**: Navigate to **Settings** > **Providers**, find your Coinbase connection, and open the wallet setup from there. In the wallet setup screen: 1. Review the list of unlinked Coinbase wallets 2. Select the wallets you want to import 3. Click **Import selected** to create Sure accounts for each wallet If more than one eligible Coinbase connection exists and none was explicitly selected, Sure returns to Provider Settings with an alert asking you to choose a connection. An unavailable selected connection or missing credentials also returns you there with an alert. ## Supported features ### Account types The Coinbase integration supports: * Cryptocurrency wallets (BTC, ETH, etc.) * Fiat wallets (USD, EUR, GBP, etc.) * Trading accounts ### Transaction syncing Sure automatically syncs: * Trades (buy/sell) * Deposits and withdrawals * Transfers between accounts * Fees ### Holdings tracking For cryptocurrency accounts, Sure tracks: * Current balances in native currency * Holdings by asset type * Real-time valuations * Fractional quantities with up to 18 decimal places of precision ### Native currency support The integration handles multiple currencies: * Cryptocurrency balances (BTC, ETH, etc.) * Fiat currencies (USD, EUR, GBP, etc.) * Automatic currency conversion for reporting ## Security ### Credential encryption Your Coinbase API credentials are encrypted using ActiveRecord Encryption: * **API Key**: Uses deterministic encryption for querying * **API Secret**: Uses standard encryption for maximum security ### API timeouts All Coinbase API requests include timeouts to prevent hanging connections and ensure responsive syncing. ## Syncing ### Manual sync To manually sync your Coinbase accounts, an admin can use either of these options: * On the **Accounts** page, find your Coinbase connection card and click the refresh icon in the header row. * Go to **Settings** > **Providers**, find your Coinbase connection, and click **Sync**. ### Automatic sync Sure automatically syncs your Coinbase accounts on a regular schedule along with your other connected accounts. ## Troubleshooting ### Credentials need updating If the Coinbase connection card shows "Credentials need updating", Sure could not read a configured API key and secret. This warning alone does not establish that the provider revoked a key. Click **Update credentials** in the connection card header to go to **Settings** > **Providers**, then enter your new API key and secret. ### Connection errors If you encounter connection errors: 1. Verify your API credentials are correct 2. Check that your API key has the required permissions 3. Ensure your API key hasn't expired ### Missing transactions If transactions are missing: 1. Manually trigger a sync 2. Check the date range of the sync 3. Verify the transaction exists in your Coinbase account ### Account linking issues If you have trouble linking wallets: 1. Ensure you've selected wallets to import during setup 2. If Sure shows a "connection unavailable" alert from Add Account, the connection may have been removed or its credentials are no longer configured — go to **Settings** > **Providers** to check 3. Try syncing the connection first so Sure can discover new wallets before opening setup 4. Check that the wallet is active in your Coinbase account ## Limitations * Historical data is limited to what's available via the Coinbase API * Some account types may not support full transaction history * Real-time price updates depend on Coinbase API availability * Cost basis is not available from the Coinbase API and is not tracked ## Getting help If you encounter issues with the Coinbase integration: * Check the [troubleshooting guide](/guides/knowledge-base/troubleshooting) * Ask in the [Discord](https://discord.gg/36ZGBsxYEK) * Open an [issue](https://github.com/we-promise/sure/issues/new/choose) # CoinSpot Source: https://docs.sure.am/providers/coinspot Connect your CoinSpot account to track cryptocurrency holdings, balances, and trades CoinSpot is an Australian cryptocurrency exchange. Sure connects to CoinSpot using a read-only API key and imports your combined crypto holdings, order history, on-chain transfers, and AUD deposits and withdrawals. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## What is imported Sure imports one combined Crypto exchange account per CoinSpot connection, containing: * Current crypto holdings and balances (all assets) * AUD total balance * Completed buy and sell order history * On-chain send and receive transactions * AUD deposits and withdrawals ## Setting up CoinSpot ### Step 1: Create a CoinSpot API key 1. Log in to [CoinSpot](https://www.coinspot.com.au) and go to [API settings](https://www.coinspot.com.au/my/api). 2. Create a new read-only API key with access to balances and order history. > [!WARNING] > > Do not grant send, withdrawal, trading, or transfer permissions. Sure only imports balances, AUD values, transfers, deposits, withdrawals, and completed order history. Granting write permissions is unnecessary and a security risk. 3. Copy the **API Key** and **API Secret** shown after creation. ### Step 2: Add the connection in Sure 1. Go to **Settings → Providers**. 2. Find the **CoinSpot** section. 3. Enter a connection name, paste your **API Key** and **API Secret**, and click **Add CoinSpot connection**. 4. Sure begins syncing your CoinSpot exchange account automatically. ### Step 3: Import the account After the first sync, your CoinSpot exchange account appears in the setup queue. Click **Import Account** in the provider panel to add it to your account list. ## Multiple connections If you have multiple CoinSpot accounts, add a separate named connection for each one. Each connection imports one combined Crypto exchange account. ## Account currency When Sure creates your CoinSpot exchange account, it uses your family's currency. CoinSpot order amounts and prices are converted from AUD into the account currency during import. ## Opening balance New CoinSpot exchange accounts have a zero historical opening anchor, separate from the current balance imported from the provider. After importing entries, Sure moves that zero anchor to the day before the earliest entry only if it is not already earlier. Existing nonzero opening anchors are preserved. ## Sync history If no sync start date is set, Sure imports up to 365 days of order, transfer, deposit, and withdrawal history on the first sync. Order history is fetched in 30-day windows to work within CoinSpot's API limits. To import a different range, set a sync start date before adding the connection. ## Security Your CoinSpot API credentials are encrypted at rest using ActiveRecord Encryption when encryption keys are configured in your deployment. Configure `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`, `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY`, and `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT` before adding credentials in a production environment. Without those keys, credentials are stored in plaintext. ## Troubleshooting ### Credentials need updating If the connection shows a reconnect prompt, your API key may have been revoked or the credentials may have changed. Generate a new read-only API key from CoinSpot and update the connection in **Settings → Providers → CoinSpot**. ### No accounts found After adding a connection, wait for the first sync to complete. If no accounts appear, verify that your API key has read access to balances and order history. ### Balance shown as approximate When the exact exchange rate for a given date is unavailable, Sure shows the balance as approximate. The balance updates to the exact figure on the next sync when rate data becomes available. ### Missing order history If older orders are missing, check that your sync start date is set to a date that covers the period you want. CoinSpot's order history is fetched starting from that date. ### Add Account redirects to Provider Settings When you choose **CoinSpot** in **Add Account** and no active CoinSpot connection has configured credentials, Sure redirects you to **Settings → Providers** with an alert explaining that a connection is required. Add a CoinSpot connection there first, then return to add the account. ### Connection appears under Available instead of Your connections After a successful setup, the CoinSpot panel should move to the "Your connections" section of **Settings → Providers** and show a status pill, sync button, and last-synced line. If it stays in Available, the connection was not saved. Re-enter your API key and secret and save again. # CoinStats Source: https://docs.sure.am/providers/coinstats Sync cryptocurrency wallets, DeFi positions, and exchange accounts using CoinStats CoinStats is a third-party provider that allows you to sync cryptocurrency wallet balances, DeFi positions, exchange portfolios, and transactions into Sure. This integration uses the CoinStats OpenAPI to fetch data from multiple blockchain networks and centralized exchanges. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works When you connect a crypto wallet through CoinStats, Sure syncs: * **Wallet balances** across multiple tokens * **DeFi positions** including staking, liquidity pools, and yield farming positions associated with linked wallets * **Exchange portfolios** from centralized exchanges * **Transaction history** from wallets and exchanges * **Real-time price data** for all holdings The integration supports multiple blockchain networks including Ethereum, Bitcoin, and many others available through CoinStats. ## Setting up CoinStats **1. Get an API key** Obtain a CoinStats API key from [CoinStats](https://coinstats.app/). **2. Add a connection** In Sure, open **Settings** > **Bank sync**, select **CoinStats**, and enter your API key. **3. Link your assets** Choose one of the connection methods below to start syncing. ## Connecting a wallet Link a wallet by providing its address and selecting the blockchain network. 1. Select **Link wallet** from the CoinStats connection page 2. Choose the blockchain (e.g. Ethereum, Bitcoin, Polygon) 3. Enter your wallet address 4. Sure fetches token balances and creates an account for each token found Once linked, Sure automatically syncs wallet balances on a recurring schedule. ### DeFi position discovery When you link a wallet, Sure also queries the CoinStats DeFi API to discover staking, liquidity pool, and yield farming positions associated with that address. Each DeFi position is tracked as a separate crypto wallet account. DeFi accounts are named using the pattern **TOKEN (Protocol Action)**, for example: * `ETH (Aave Staking)` * `USDC (Uniswap Rewards)` If a DeFi position is fully unstaked or no longer returned by the API, its balance is automatically set to zero. > [!NOTE] > > DeFi discovery runs during every wallet sync. New positions are added automatically and inactive positions are zeroed out. ## Connecting an exchange CoinStats supports syncing portfolios from centralized cryptocurrency exchanges: 1. Connect your CoinStats account to Sure 2. Link your exchange accounts within CoinStats 3. Sure will automatically sync: * Holdings from all connected exchanges * Transaction history * Real-time balance updates 4. Charts for linked investment accounts are normalized to provide accurate portfolio views The credential fields vary by exchange. Sure dynamically renders the required fields based on the exchange you select. Sensitive fields like secrets and passphrases use masked input. ## Currency storage approach All CoinStats accounts are stored in **USD** and will remain in USD. This design decision ensures data consistency and prevents exchange rate drift. ### Why USD storage? There are two possible approaches for storing cryptocurrency values: **Option 1: Store in USD (current implementation)** * CoinStats data is stored in USD * Values are converted to your family currency when displayed * Works the same way as multi-currency accounts already do in Sure * If you update exchange rates, values automatically update correctly without requiring a sync * Original USD values are always preserved **Option 2: Store in family currency** * Convert cryptocurrency values to family currency during sync * **Problem**: If currency provider is not set up or conversion fails, data is saved with a 1:1 exchange rate * Once saved incorrectly, you lose the original value and cannot fix it later * Creates data integrity issues ### Benefits of USD storage 1. **No forex drift**: Values are converted only once, preventing cumulative exchange rate errors 2. **Data integrity**: Original values are always preserved 3. **Automatic updates**: When you fix or update exchange rates, all cryptocurrency values update correctly without requiring a sync 4. **Consistency**: Works the same way as other multi-currency accounts in Sure 5. **Reliability**: No dependency on currency provider being available during sync > [!NOTE] > > DeFi positions follow a slightly different path: USD balances from the API are converted to your family currency during sync for consistent portfolio reporting. If the exchange rate is unavailable, the value falls back to USD. This is why USD storage is the preferred approach and will remain the standard for CoinStats integration. ## Supported features | Feature | Wallets | DeFi | Exchanges | | - | - | - | - | | Balance syncing | Yes | Yes | Yes | | Transaction history | Yes | No | Yes | | Multiple tokens/positions | Yes | Yes | Yes | | Automatic periodic sync | Yes | Yes | Yes | | Multiple blockchains | Yes | Yes | N/A | * **Normalized charts**: Investment charts are automatically normalized and linked across all CoinStats accounts ## Limitations * CoinStats integration is currently in beta * Requires a valid CoinStats API key * Subject to CoinStats API rate limits * All values are stored in USD (see currency storage approach above) * DeFi position discovery depends on CoinStats DeFi API coverage for each blockchain and protocol # Enable Banking Source: https://docs.sure.am/providers/enable-banking Connect European bank accounts using PSD2 open banking Enable Banking is a free third-party provider that allows you to connect European bank accounts to Sure using PSD2 open banking standards. It supports thousands of banks across the EU. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works Enable Banking uses the PSD2 open banking framework to securely access your bank data: 1. Select your bank from the list of supported institutions 2. Authorize Sure to access your account through your bank's authentication flow 3. Sure syncs your account balances and transactions 4. Data is refreshed periodically to keep your information current All authentication happens directly with your bank. Enable Banking and Sure never see your banking credentials. The authorization flow is tied to your browser session. Sure generates a unique, random state value for each authorization attempt and stores it in your session. When your bank redirects back to Sure, the callback is matched against that stored state before proceeding. This means the authorization must complete in the same browser where you started it. ## Supported regions Enable Banking supports banks across the European Union and EEA countries. You can query available banks by country code (e.g., "GB", "DE", "FR"). ## Setting up Enable Banking > [!WARNING] > > The most common setup issue is `REDIRECT_URI_NOT_ALLOWED`. Before connecting a bank, register Sure's callback URL in your Enable Banking application settings. Copy the exact callback URL shown in **Settings > Bank sync > Enable Banking** in Sure. > > In production this is usually `https://your-domain.example/enable_banking_items/callback`, but in development it may use a different URL. Use the exact value shown by Sure. To connect your European bank accounts: 1. Obtain an Enable Banking application ID and client certificate from [Enable Banking](https://enablebanking.com/) 2. Register Sure's callback URL in your Enable Banking application settings 3. In Enable Banking, link your bank account to the application 4. In Sure, configure your Enable Banking credentials 5. Select your country and bank from the available options 6. Complete the authorization flow with your bank 7. Sure creates a session and begins syncing your accounts If you want to connect another bank, or connect the same bank with a different login, use **Add Connection** after your first Enable Banking connection is working. Sure stores each Enable Banking connection separately, so you can sync, reconnect, or remove them independently. Make sure to link the bank account first in the Enable Banking portal, and then create the bank connection in Sure. ### Updating credentials When you update an existing Enable Banking connection, the **Application ID** and **Client Certificate** fields are empty. Leave either field blank to keep the stored value. Enter a new value only when you need to replace a credential. For existing provider configurations, both credential fields are disabled while any Enable Banking connection in your family has a stored session. This applies across configurations, rather than depending only on the status of the connection being edited. Remove the connections with stored sessions before changing credentials. ### Using one provider config across different countries You do **not** need to create a separate Enable Banking provider configuration for each country. Use one shared Enable Banking configuration with your application ID and client certificate, then use **Add Connection** for each additional bank you want to link. When adding each bank connection: 1. Start from **Settings > Bank sync > Enable Banking** 2. Choose the country in **Country Code** list 3. Save the configuration with selected country 4. Click **Add Connection** 5. Select the bank in that country 6. Complete authorization Example: you can keep one Enable Banking provider config in Sure, then add one connection for a Spanish bank and another connection for a German bank using the same credentials. ## Features ### Account access * **Account details**: View account information including IBAN and account type * **Balance information**: Balance data fetched from your bank using a priority order that prefers reconciled booked figures * **Transaction history**: Import historical transactions with date range filtering * **Multiple accounts**: Connect multiple accounts from different banks * **Duplicate detection**: Automatic deduplication of transactions with different entry reference IDs ### Session management Enable Banking uses sessions to maintain access to your accounts: * Session validity depends on your bank's maximum consent period, up to 180 days * You can revoke access at any time by deleting the session * Sessions automatically refresh to keep data current Sure requests the longest consent window your bank advertises (capped at 180 days by default), so reauthorization happens as infrequently as possible. If your bank rejects the requested duration, Sure automatically retries with progressively shorter windows (90, 45, and 30 days) until the bank accepts one. Set the `ENABLE_BANKING_CONSENT_DAYS` environment variable to a whole number of days to override the 180-day ceiling. Only integer values are accepted; non-integer strings are ignored and the default is used. ### Transaction period retries Some banks reject a sync request when the requested date range is outside the window they allow. Sure automatically retries with a shorter window when this happens. N26 reports this condition with `{"code": "PERIOD_INVALID", ...}` rather than the more common `WRONG_TRANSACTIONS_PERIOD` error shape. Sure recognizes both forms and applies the same retry ladder, so N26 syncs recover automatically instead of failing outright. ### Transaction syncing When syncing transactions, Sure imports both booked and pending transactions: * **Booked transactions**: Confirmed transactions from your bank * **Pending transactions**: Transactions that have not yet settled (visible for 1–3 days before they become booked) * When a pending transaction settles, the pending entry is automatically replaced by the booked version * You can filter synced transactions by date range * Large transaction sets are paginated automatically ### Pending transactions By default, Sure imports both booked and pending (uncleared) transactions from Enable Banking. Pending transactions are automatically reconciled once they post as booked. You can disable pending transaction imports in your sync settings by toggling "Include pending transactions" off. When disabled, only booked transactions are imported, and any previously stored pending transactions are removed during the next sync. > [!NOTE] > > Disable this option if your bank provides unreliable pending transaction data. ### Card authorization holds Some banks (ASPSPs) return unfinalized card authorization holds with a `BOOK` status while omitting the `transaction_id`, `entry_reference`, and creditor information. The remittance field contains a masked card descriptor instead of a merchant name (for example `474836xxxxxx6879 003015315475`), and the credit/debit indicator may be set to `CRDT` even though the hold is an outgoing expense. Sure detects these holds by checking for a masked card descriptor in the remittance field when the transaction lacks identifying fields. Detected holds are: * Named **Card Authorization Hold** * Imported as pending expenses (no merchant is created) * Corrected to a positive outgoing amount when the bank erroneously reports them as credit When pending transactions are disabled, unidentified card holds are filtered out and not imported. ### Balance selection When Enable Banking returns multiple balance types for an account, Sure picks the most reliable figure using a fixed priority order that prefers reconciled booked balances over available or expected ones: 1. **CLBD / closingBooked** — closing booked balance 2. **ITBD / interimBooked** — interim booked balance 3. **OPBD / openingBooked** — opening booked balance (start of current period) 4. **PRCD / previouslyClosedBooked** — previously closed booked balance (end of last period) 5. **XPCD / expected** — expected balance 6. **CLAV / closingAvailable** — closing available balance 7. **ITAV / interimAvailable** — interim available balance Available balances are last because some banks include an arranged overdraft facility in the available figure, which would overstate actual cash. OPBD and PRCD are period-boundary snapshots rather than live figures, so they may be up to a day old. To guard against this, Sure checks the optional `reference_date` field on each balance. If the same response contains a newer XPCD, CLAV, or ITAV balance with a strictly later `reference_date`, the fresher balance wins instead of the period-boundary one. When `reference_date` is absent on either side, the priority order applies unchanged. If none of the recognised types are present, Sure falls back to the first balance the API returns. #### Duplicate same-type balances Some banks report the same balance type more than once with different amounts — for example, two CLBD entries where one includes an arranged overdraft. When this happens, Sure resolves the conflict in stages, using the strongest available evidence first: 1. **Credit limit gap** (depository accounts) — if the difference between the two amounts equals the account's known credit limit, the lower amount is the real balance and the higher one includes the overdraft facility. 2. **Last committed transaction** — each candidate balance may reference a `last_committed_transaction` field pointing to a specific booking. If every candidate points to a distinct booking with an unambiguous date, the uniquely most recent booking wins. Tied or ambiguous dates do not decide the result. 3. **Previous verified anchor** (depository accounts) — Sure computes the expected balance by subtracting booked transaction flows from the last verified anchor. A unique candidate that matches this expectation wins. If multiple candidates match, a uniquely newest `last_change_date_time` can choose one, but that timestamp-based pick is not marked verified. If the anchor date is ambiguous (some transactions may or may not be included), Sure checks both possibilities and only uses the result when both agree. 4. **Lowest balance** (depository accounts) — an included overdraft facility only ever raises the reported figure, so the lower amount is more likely to be real. 5. **First in response order** (other account types) — no evidence is available; Sure uses the first entry the bank returned. Sure logs each resolved tiebreak to **Settings > Debug** under the `provider_sync_warning` category. To avoid log spam, it only records a new entry when the candidates or the outcome change between syncs. **Balance verification:** a balance chosen by one of the evidence-backed stages (credit limit gap, last committed transaction, or previous verified anchor) is marked as verified. This verified flag is then used by the anchor stage on subsequent syncs — Sure only trusts a previous anchor to inform the next tiebreak when that anchor itself was written from a verified pick. This prevents a wrong balance from confirming itself across syncs. If any booked transaction lacks a usable date, Sure skips the anchor stage entirely because it cannot tell whether that transaction falls before or after the anchor. #### Credit cards with "Balance is available credit" When a credit card account has the **Balance is available credit** setting enabled, Sure uses a different priority order that prefers available balance types first: 1. **CLAV / closingAvailable** — closing available balance 2. **ITAV / interimAvailable** — interim available balance 3. Then the same booked order as above (CLBD, ITBD, OPBD, PRCD, XPCD) This is needed because some banks (for example mBank PL) report the credit limit as the booked balance (ITBD) and the actual available credit as ITAV. Without this adjustment, Sure would treat the credit limit as available credit, producing zero calculated debt. XPCD (expected) stays after the booked types in this order because it is a projected booked balance, not an available credit figure. This available-first priority only applies when the provider account is linked to a credit card account in Sure. If the account is later relinked to a different account type, Sure falls back to the standard booked-first order even if the "Balance is available credit" flag is still set. ### Multi-currency accounts Some wallets and payment services (such as PayPal) report multiple balances under the same balance type — one per currency — in a single response. Without special handling, the last entry would win, causing the account to display the wrong currency and an empty balance. When Sure detects a multi-currency response, it keeps only the balances in the account's reported currency: * Sure reads the currency from the raw account snapshot, not the stored column, to avoid using a value that a previous faulty sync may have set incorrectly. * If the snapshot currency is not present in the response (for example, PayPal reports `XXX` for its wallet), Sure falls back to the first recognized currency returned. * Balances in other currencies are not discarded silently. If any non-selected currency carries a non-zero amount, Sure logs the details to **Settings > Debug** under the `provider_sync` category so support can investigate if needed. Single-currency accounts are not affected by this logic. ### Account type mapping Sure automatically maps your bank's account types to the appropriate Sure account type: * **Checking accounts** (CACC, TRAN, SALA, and others) map to depository accounts * **Savings accounts** (SVGS, MOMA) map to depository savings accounts * **Credit cards** (CARD, CRCD) map to credit card accounts * **Loans and mortgages** (LOAN, MORT) map to loan accounts ### Automatic transfer detection When syncing transactions from Enable Banking, Sure automatically detects certain transfer types based on the destination account: * **Loan payments**: Transactions to loan accounts are automatically classified as loan payment transfers * **Credit card payments**: Transactions to credit card accounts are automatically classified as credit card payment transfers See [transfers](/guides/key-concepts/transfers) for more details on how transfer types affect budgets. ### Transaction name cleanup For banks that return remittance information as a multi-line array (common with Austrian and German banks such as BankDirekt/Raiffeisen), Sure automatically selects the most descriptive line as the transaction name. Technical terminal descriptor lines — such as `POS 45,13 AT D6 31.07. 10:27` — are skipped in favour of the actual merchant name. Sure strips payment wallet prefixes (Apple Pay, Google Pay, Samsung Pay) from remittance lines before reading the payee name. Some banks prepend the wallet used to make a payment — for example, `Apple Pay: Coffee Shop Name` — onto the transaction descriptor. Stripping the wallet prefix ensures the real merchant name is used for matching and display, so a purchase from Apple's own store does not cause all subsequent wallet-paid transactions to be labelled as Apple purchases. Sure also strips known small-merchant payment-processor prefixes (SumUp, Square, iZettle, PayPal) from the selected line, and matches the transaction against your family's known merchants for a cleaner display name. ### Duplicate transaction handling Enable Banking includes robust content-based deduplication to prevent API-level duplicate transactions: * The API sometimes returns the same logical transaction multiple times with different `entry_reference` IDs * Sure uses a composite key based on transaction content, including `transaction_id` when present, plus date, amount, currency, creditor and debtor information, remittance information, status, and credit/debit indicator * When multiple transactions have identical content, only the first occurrence is kept * The `credit_debit_indicator` helps distinguish between payments and refunds of the same amount on the same day This keeps your transaction history clean and accurate even when the API returns duplicate data. ### ID-less transaction handling Some banks (ASPSPs) omit both `transaction_id` and `entry_reference` from their responses, which are both optional under PSD2. For these transactions, Sure generates a deterministic ID based on date, amount, currency, direction, creditor, debtor, and remittance information. When the bank later assigns a real identifier to one of these transactions — for example, once a statement closes — Sure re-keys the stored row to the new identifier rather than importing a second entry. This preserves any category, merchant, or transfer link already attached to the original row. This re-keying only applies to booked (settled) transactions on both sides. Pending transactions are excluded from the re-keying pool and from the candidate set that receives claims, so Enable Banking's own pending-to-booked reconciliation handles the settlement transition independently without the two mechanisms conflicting. Transactions that already carry a provider ID are not affected by this logic. ## Supported account types Enable Banking supports both personal and business accounts: * **Personal accounts**: Standard consumer bank accounts (default) * **Business accounts**: Business banking accounts When connecting a bank, Sure validates the selected account type against the types your bank supports. If your bank only supports one type, it is selected automatically. ## API reference For technical details about the Enable Banking API, see the [official documentation](https://enablebanking.com/docs/api/reference/). ## Troubleshooting ### Authorization callback fails with "Connection not found" Sure could not resolve a pending authorization for your current browser session and family. The returned state may not match a pending attempt, or the associated connection may no longer be available. It can happen if you: * Opened the bank's authorization page in a different browser or profile than the one where you started the flow * Completed the bank's authorization after your Sure session expired * Navigated away from Sure and your session was cleared Start the authorization again from **Settings > Bank sync > Enable Banking** and complete the bank's approval without switching browsers or letting your session time out. ### N26 and PERIOD\_INVALID errors N26 (and some other ASPSPs via Enable Banking) rejects out-of-range transaction date windows with a `PERIOD_INVALID` error rather than the more common `WRONG_TRANSACTIONS_PERIOD` shape. Sure recognizes both error shapes and automatically retries the sync with a shorter date window, so you should not need to take any action if a sync fails with this error. ### Bank rejects the session mid-sync Some banks reject an Enable Banking session with a 401 or 404 during a sync even though the session has not yet expired by its recorded expiry date. When this happens, Sure marks the connection as requiring re-authorization and finishes the sync cleanly — the connection card shows a **Reconnect** prompt instead of a green "Connected" status. Click **Reconnect** and complete the bank authorization flow again to restore syncing. ### Syncs keep failing without a reconnect prompt Enable Banking sometimes rejects individual account balance or transaction requests with a 401 “Invalid credentials or expired JWT” while the session-level check still reports the session as valid. Because only a session-level failure flips the connection to `requires_update`, the connection card stays green and no reconnect prompt appears automatically. Syncs can fail for the affected accounts without requesting reauthorization; these failures can still appear as sync errors. To reconnect manually, an admin can open the action menu on the connection card and choose **Reconnect**. This option is always available as long as the connection is not already showing a reconnect prompt. Clicking it routes through the same reauthorization flow as a normal reconnect, so you do not need to disconnect and re-add the bank. ### FORMAT\_ERROR: PSU IP Address field not valid (self-hosted) Some banks (such as HypoVereinsbank) reject syncs with a `FORMAT_ERROR: PSU IP Address field not valid` response when the `Psu-Ip-Address` header contains a non-public IP address. This can happen on self-hosted instances accessed over a LAN, VPN, or tunnel (for example Tailscale). The browser's address is stored at the time of connection. If that address is private, loopback, link-local, CGNAT (`100.64.0.0/10`), or another IANA special-purpose range that is not globally reachable, Sure omits the `Psu-Ip-Address` header rather than forwarding an invalid address to the bank. After upgrading to a build that includes [Sure PR #4304](https://github.com/we-promise/sure/pull/4304), no additional configuration is needed: the next sync omits a stored non-public IP automatically. This fix is on `main` but is not in the latest stable release, `v0.7.5-hotfix.2`, as of October 21, 2026. If the bank session needs reauthorization, an admin can use **Reconnect** from the connection card menu. ## Limitations * Only supports banks in EU/EEA countries * Requires PSD2-compliant banks * Session validity depends on your bank's consent limits (up to 180 days) * Banks that use decoupled authentication (separate device approval) are not supported * Subject to Enable Banking API rate limits * Some banks may have additional authentication requirements # FinanceKit Source: https://docs.sure.am/providers/financekit Sync Apple Wallet data directly from iOS devices FinanceKit is an Apple framework that lets users share their Apple Wallet accounts — bank accounts, credit cards, and transaction history — directly with Sure from their iPhone. The iOS app reads Wallet data on-device with the user's consent and uploads it to Sure over HTTPS. No Apple credentials, private keys, or FinanceKit framework components are required on the server. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works The iOS client uses Apple's FinanceKit framework to read Wallet data. It enrolls a publisher connection with Sure, maps each selected source account to a Sure account, and uploads ordered batches of events. Sure's server-side worker applies each batch and updates your ledger. Both foreground "Sync now" (triggered manually from the app) and optional background delivery use the same enrollment, upload, receipt, and conflict-resolution protocol. Whether Wallet sync is offered to a user is the iOS client's decision, made through StoreKit. The server does not gate access by family ID or a feature flag — any family administrator can enroll a publisher. ## Protocol overview ### Enrollment and activation The iOS client enrolls a publisher connection by calling `POST /api/v1/financekit/connections` with a consent record and a client-generated enrollment ID. Sure returns a `FinancekitPublisherConfiguration` that includes the upload URL, protocol version, account limits, and a publisher credential. Before uploads begin, the client maps each selected source account to a Sure account using `PUT /api/v1/financekit/connections/{connection_id}/account_mappings/{source_id}`, then activates the connection with `POST /api/v1/financekit/connections/{connection_id}/activate`. ### Uploading batches The client uploads ordered batches to `POST /api/v1/financekit/publishers/{publisher_id}/batches`. Each batch is an immutable, sequenced payload of up to 500 events authenticated with the publisher credential (a bearer token separate from the user's API key). Each batch carries: * A `sequence` number starting at 1 * A `predecessor_digest` (SHA-256 of the previous batch payload) for all sequences after the first * A `capture_id` and `chunk_index` / `chunk_count` to support multi-chunk captures * `capture_mode` (`snapshot` or `delta`) and a `snapshot_complete` flag * Up to 500 events: account upserts, balance upserts, transaction upserts, transaction tombstones, or account unavailability notices Sure acknowledges each batch immediately with a `FinancekitBatchReceipt`. The client can retrieve a receipt at any time using `GET /api/v1/financekit/publishers/{publisher_id}/batches/{batch_id}` to recover from response loss. ### Capacity limits Protocol 2 enforces per-publisher limits: * 20 selected accounts per publisher * 500 events per batch * 1 MiB of JSON per batch payload * 100 accepted or processing batches in the inbox at one time * 100 chunks per capture (allowing large histories across consecutive captures) ### Batch receipt status | Status | Meaning | | - | - | | `accepted` | Durably stored, awaiting processing | | `processing` | Worker has started applying the batch | | `applied` | Ledger updated successfully | | `failed` | Permanent processing failure; see `error_code` | | `revoked` | Batch invalidated by a credential rotation or repair | ### Credential rotation and repair A publisher credential can be rotated with `POST /api/v1/financekit/connections/{connection_id}/credential`. After rotation, the previous credential can no longer upload batches or call the batch receipt endpoint. If a connection enters `repair_required` — for example, due to an unresolvable conflict or a predecessor digest mismatch — the client must call `POST /api/v1/financekit/connections/{connection_id}/repair` to open a new generation and stream before uploads resume. ## Conflicts A conflict arises when Sure cannot automatically reconcile a publisher event with existing ledger data. Open conflicts are listed on `GET /api/v1/financekit/connections/{connection_id}/conflicts` and resolved with `PATCH /api/v1/financekit/connections/{connection_id}/conflicts/{id}`. Two resolutions are available: * `keep_sure` — closes the conflict without modifying the publisher stream. The conflicting source identity is settled permanently so the same record does not re-enter the conflict branch on future captures. * `retry_after_repair` — closes the conflict, moves the connection to `repair_required`, revokes queued work and credentials, and requires a repair call before uploads resume. A balance observation that disagrees with a stored value raises a conflict and allows ingestion to continue. The stored observation and canonical balance stay unchanged; the connection keeps applying subsequent batches while the conflict is open. ## Disconnecting a publisher Deleting a connection revokes the publisher credential and removes the AccountProvider links. What happens to the imported financial data depends on the `disposition` parameter passed to `DELETE /api/v1/financekit/connections/{connection_id}`. | Disposition | Behavior | Response | | - | - | - | | `retain` (default) | Keeps every account, balance, and transaction | `204 No Content` | | `discard` | Removes imported accounts, entries, identities, and lineage data in the background | `202 Accepted` | When `discard` is accepted, the connection payload includes `purge_requested_at`. Poll `GET /api/v1/financekit/connections/{connection_id}` and check `purge_completed_at` to confirm the removal has finished. Which dispositions a build supports is advertised in the `connection_dispositions` array returned by `GET /api/v1/financekit/capabilities`. Client code should feature-detect against that list rather than hardcoding the available values. > [!NOTE] > > A discard is irreversible. Imported entries the family reconciled, excluded, split, or edited are removed along with the rest. ## Data retention Exact payload bytes are retained for seven days after a batch is applied, permanently failed, or revoked. This supports response-loss recovery and operational investigation. Canonical financial data follows Sure's normal family retention behavior. A family financial-data reset removes all FinanceKit connections, lineages, observations, identities, conflicts, and batch receipts for that family. ## API reference The FinanceKit endpoints are documented in the [API reference](/api-reference). | Endpoint | Description | | - | - | | `GET /api/v1/financekit/capabilities` | Discover supported protocol versions, limits, and connection dispositions | | `POST /api/v1/financekit/connections` | Enroll a new publisher | | `GET /api/v1/financekit/connections/{id}` | Read connection status and paginated account mappings | | `PUT /api/v1/financekit/connections/{connection_id}/account_mappings/{source_id}` | Map a source account | | `POST /api/v1/financekit/connections/{connection_id}/activate` | Activate the publisher | | `POST /api/v1/financekit/connections/{connection_id}/credential` | Rotate the publisher credential | | `POST /api/v1/financekit/connections/{connection_id}/repair` | Open a new generation after repair\_required | | `DELETE /api/v1/financekit/connections/{connection_id}` | Disconnect a publisher, retaining or discarding imported history | | `POST /api/v1/financekit/publishers/{publisher_id}/batches` | Upload a batch | | `GET /api/v1/financekit/publishers/{publisher_id}/batches/{batch_id}` | Read a batch receipt | | `GET /api/v1/financekit/connections/{connection_id}/conflicts` | List open conflicts | | `PATCH /api/v1/financekit/connections/{connection_id}/conflicts/{id}` | Resolve a conflict | # Fio banka Source: https://docs.sure.am/providers/fio Connect your Fio banka (Czechia) account to Sure [Fio banka](https://www.fio.cz/) is a Czech bank. Sure connects to it directly using your own API token, syncing balances and transaction history. No third-party aggregator sits in between, and no consent expires every 90 days. > [!NOTE] > > One token grants access to one account. If you track three Fio accounts in Sure, generate three tokens and add three connections. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## Setting up Fio banka ### Step 1: Get your token 1. Sign in to [Fio internet banking](https://ib.fio.cz). 2. Open **Nastavení** (top right), then the **API** tab. 3. Create a token with the **Sledování účtu** (account monitoring) permission. This is read-only — Sure never initiates payments, and a token without payment rights cannot be used to move money. 4. Authorize the request with SMS or push confirmation. Jointly held accounts require all signatories to sign. 5. Wait five minutes before using the token. Fio rejects a brand-new token until then. Every token must have an expiry, up to 180 days. Choose automatic renewal if you don't want to repeat this process twice a year: Fio extends the token by 180 days on each internet or smart banking login. ### Step 2: Add Fio to Sure 1. In Sure, go to **Settings > Providers** and find the **Fio banka** panel. 2. Enter a connection name, paste your token, and save. 3. Sure runs the first sync to discover the account. After it completes, link the account to an existing Sure account or create a new one. Fio reports no account type, so the account is offered as a checking account. Choose a loan account instead if the token belongs to a mortgage, loan, or overdraft — Fio reports those balances as negative, and Sure stores a liability as a positive balance. ## Syncing One property of the Fio API shapes everything: a token may be used once per 30 seconds. Every sync therefore makes exactly one request. * Each sync fetches movements booked between the day the last sync covered and today. * The window starts a week before that day rather than right after it. Fio books a movement under its banking date, which can trail the day it becomes visible. * Re-reading is safe: every movement has a permanent ID, so a movement already imported updates its entry rather than creating a duplicate. A reversal gets its own ID and arrives as its own entry. If you trigger a manual sync within 30 seconds of a scheduled one, Fio refuses the request. Nothing is fetched, the connection stays healthy, and the next sync continues from where the last one stopped. Fio has no concept of a pending or held transaction, so no transactions are marked pending and nothing needs to be reconciled later. ## Transaction history older than 90 days Fio serves 90 days of history by default. To import older movements, unlock the full account history in internet banking under **Nastavení > API**: click the padlock on the token and authorize. This opens a 10-minute window. Set the connection's sync start date to how far back you want to go before unlocking. If the start date reaches past 90 days and history is still locked, Fio refuses the request — the connection reports this and all future syncs stay within the 90 days Fio does serve, so recent movements keep arriving. To collect the rest: unlock the history in internet banking, then press **Sync** on the connection. This tells Sure the unlock happened, and the next sync reaches for the full range again. ## Configuration The following environment variables are available for self-hosted deployments: | Variable | Default | Purpose | | - | - | - | | `FIO_INITIAL_HISTORY_DAYS` | `90` | History a new connection reaches for when no start date is set. Values above 90 require an unlock | | `FIO_SYNC_LOOKBACK_DAYS` | `7` | Days before the last covered day that every sync re-reads | | `FIO_DEBUG_RAW` | unset | Log raw API payloads. Development only — the dump contains counterparty names and payment messages | ## Troubleshooting **"Configure Fio banka in provider settings first" error**: If you see this alert when trying to add a Fio account, the selected connection has no configured API token. Go to **Settings > Providers > Fio banka**, enter your token, and save before adding accounts. **Connection requires a new token**: Fio returns an error for unknown, expired, or deactivated tokens. Check the token's validity under **Nastavení > API** and paste a new one into the provider panel. **The statement is too large**: Fio caps one request at 50,000 movements. Set a later sync start date on the connection. **Older transactions are missing**: Either the account history was never unlocked (see above), or the connection's sync start date bounds how far back it goes. **Sync errors**: Provider sync failures are captured in Sure's debug log. Super admins can view them at **Settings > Debug**, filtered by the `fio` provider key. The token is never logged. # Indexa Capital Source: https://docs.sure.am/providers/indexa-capital Connect Indexa Capital automated investment portfolios to Sure Indexa Capital is a Spanish robo-advisor that manages automated investment portfolios. Sure connects to Indexa Capital to import your portfolio holdings, balances, and transaction history. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## Setting up Indexa Capital Sure supports two authentication methods for Indexa Capital: an API token or username and password credentials. ### Option 1: API token (recommended) 1. Log in to your Indexa Capital dashboard. 2. Navigate to the API or developer settings to generate a read-only API token. 3. In Sure, go to **Settings → Providers** and find the **Indexa Capital** section. 4. Paste your API token into the **API Token** field and save. ### Option 2: Username and password 1. In Sure, go to **Settings → Providers** and find the **Indexa Capital** section. 2. Enter your Indexa Capital **Username** (email), **Document ID**, and **Password**. 3. Save the configuration. After saving, Sure begins syncing your Indexa Capital accounts. Go to the **Accounts** tab to set up any newly discovered accounts. ## Setting up accounts After the first sync, your Indexa Capital accounts appear in the setup queue. Click **Set up accounts** to assign each account an account type and a transaction history start date before it appears in your account list. ## Troubleshooting ### Provider not configured If you see a "provider not configured" error, check that your credentials are saved in **Settings → Providers → Indexa Capital** and that at least one authentication method is filled in correctly. ### No accounts found after syncing Run a manual sync from **Settings → Providers** after saving your credentials. If accounts still do not appear, verify your credentials are correct in the Indexa Capital dashboard. # Interactive Brokers Source: https://docs.sure.am/providers/interactive-brokers Connect Interactive Brokers investment accounts to Sure using Flex Web Service reports Interactive Brokers (IBKR) is a brokerage platform supporting stocks, options, futures, currencies, bonds, and funds. Sure connects to IBKR using its Flex Web Service, which lets you export account data through a configured Flex Query. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## What is imported Sure imports the following data from an IBKR Flex report: * Holdings with current prices and quantities * Cost basis per position * Trades (with commissions folded into the trade fee), dividends, and cash deposits or withdrawals Historical activity is limited to the date range configured in your Flex Query. Sure imports full current holdings plus up to the last 365 days of activity. ## Setting up Interactive Brokers ### Step 1: Create an Activity Flex Query in IBKR 1. In your IBKR Client Portal, navigate to **Performance & Reports → Flex Queries**. 2. Click the **+** icon in the **Activity Flex Query** section to create a new query. 3. Name the query (for example, "Sure Sync"). 4. Enable the following sections and fields: **Account Information:** Account ID, Currency **Cash Report:** * Options: None * Fields: Currency, Ending Cash **Cash Transactions:** * Options: Dividends, Deposits & Withdrawals, Detail * Fields: Amount, Conid, Currency, FX Rate To Base, Report Date, Transaction ID, Type **Change In Position Value Summary:** Currency, End Of Period Value **Net Asset Value (NAV) in Base:** * Options: None * Fields: Currency, Report Date, Total **Open Positions:** * Options: Summary * Fields: Asset Class, Conid, Cost Basis Price, Currency, FX Rate To Base, Mark Price, Quantity, Report Date, Security ID, Security ID Type, Side, Symbol **Trades:** * Options: Execution * Fields: Asset Class, Buy/Sell, Conid, Currency, FX Rate To Base, IB Commission, IB Commission Currency, Quantity, Symbol, Trade Date, Trade ID, TradePrice, Transaction ID 5. Set the following query configuration options: | Option | Value | | - | - | | Models | Optional | | Format | XML | | Period | Last 365 Calendar Days | | Date Format | yyyy-MM-dd | | Time Format | HH:mm:ss | | Date/Time Separator | ; (semi-colon) | | Profit and Loss | Default | | All other options | No | 6. Save the query and note your **Query ID**. ### Step 2: Generate a Flex Web Service token After saving the query, use the gear icon in the **Flex Web Service Configuration** section of the Flex Queries page to generate an access token. Copy this token. ### Step 3: Add the connection in Sure 1. Go to **Settings → Providers**. 2. Find the **Interactive Brokers** section. 3. Paste your **Query ID** and **Token** into the form fields and save. 4. Sure begins syncing and discovering your IBKR accounts. ### Step 4: Set up accounts After the first sync, discovered IBKR accounts appear in the setup queue. Click **Set up accounts** in the provider panel to select which brokerage accounts to link and confirm the linkage. You can also link a discovered IBKR account to an existing manual investment account if you already have one in Sure. ## How balances work Sure anchors your IBKR account balance on the date of the Flex report, not the date of the sync. The NAV (Net Asset Value) comes from the equity summary in your Flex report and is recorded as of that report's date. Holdings imported alongside it are also written on that same date. If IBKR delivers a statement with a date older than the most recent balance already on record, Sure records that statement as a historical reconciliation entry on its own date and leaves the newer balance in place. This preserves balance history without walking the account's reported value backwards. A balance write failure is logged to **Settings → Debug** against the connection so you can identify and diagnose it. ## How commissions work When Sure imports a trade from IBKR, it records the commission as the trade's fee rather than as a separate transaction. The fee flows into the trade's cost basis and realized gain calculations, and its amount is included in the cash the trade moved. A commission stays as a separate transaction in these cases: * The commission was charged in a different currency than the trade. * IBKR did not report which currency the commission was in. If a commission was imported as a separate transaction before this change, Sure removes the old transaction and moves it onto the trade as a fee during the next sync. **User edits are preserved.** If you edited a trade's fee directly, Sure keeps the fee you set and does not overwrite it on subsequent syncs. Likewise, a separate commission transaction that you have edited, locked, or attached a receipt to is treated as yours and left in place. ## Limitations * Historical activity is limited to the report window of your Flex Query. Sure imports up to 365 days of activity based on the query's configured period. * Only investment (brokerage) accounts are supported. Cash accounts and other account types are not imported from IBKR. ## Troubleshooting ### No accounts discovered after syncing If Sure reports no accounts discovered, check that your Flex Query includes the **Account Information** section with Account ID and Currency enabled. Run a manual sync from **Settings → Providers** after updating the query. ### Provider not configured If you see a "not configured" error when trying to add an IBKR account, Sure could not find an active IBKR connection. This alert is about the connection record, not a check that the credentials are valid. Go to **Settings → Providers → Interactive Brokers**, enter both values, and save before adding accounts. ### Credentials need attention If the connection shows a "Credentials need attention" status, your Query ID or Token may have expired or been revoked. Generate a new token from the Flex Web Service Configuration section in IBKR and update the connection in Sure. ### Only manual investment accounts can be linked When linking a discovered IBKR account to an existing account, the existing account must be a manual investment account without an existing provider link. Convert the account to manual first if needed. ### Balance shows unexpected cash or looks incorrect after sync If your account balance or cash position looks wrong after a sync, the most likely cause is a mismatch between the NAV date in your Flex report and the date Sure recorded it on. This was a known issue that has been fixed: Sure now anchors the balance on the Flex report's own date rather than the sync date. Run a manual sync from **Settings → Providers** to pull a fresh report and recalculate the balance. ### Portfolio value or cash appears incorrect on historical dates IBKR reports each position in the security's own currency, while Sure's internal calculations use the account's base currency. A previous version of Sure's duplicate-removal step only matched calculated and provider rows when they shared the same currency, so on historical snapshot dates (not the most recent one) both rows survived. The same position was counted twice, and cash was correspondingly understated. This has been fixed: Sure now drops calculated holdings whenever a provider snapshot exists for the same security and date, regardless of currency. Run a manual sync from **Settings → Bank sync** to trigger a recalculation. If the balance still looks wrong after syncing, check **Settings → Debug** for any errors logged against the IBKR connection. # Jev (TypeSafe) Source: https://docs.sure.am/providers/jev Use Jev for transaction categorization with calibrated confidence scores Jev is a classification provider made by [TypeSafe](https://typesafe.ai/). It answers typed questions about a transaction and returns a calibrated probability for each answer, rather than generating free text. This makes it well-suited to transaction categorization, where you want a specific category name and a measure of how certain the model is. Because Jev only classifies, it cannot handle chat, PDF processing, or merchant detection. It is configured independently of `LLM_PROVIDER` and never replaces your LLM for those features. ## How it differs from the LLM path | | LLM provider | Jev | | - | - | - | | Categorizes transactions | Yes | Yes | | Chat and AI assistant | Yes | No | | PDF import | Yes | No | | Merchant detection | Yes | No | | Returns confidence score | No | Yes | | Confidence threshold gating | No | Yes | | Pricing model | Per token | Per transaction state | The LLM path sends a batch of transactions in one request. Jev sends one request per transaction, run concurrently. At roughly 400–550 ms per transaction, throughput depends on concurrency rather than batch size. ## Prerequisites * A TypeSafe account with a Jev API key * Preview features enabled for the families that will use Jev (the provider selector is hidden until preview is on) ## Setup ### 1. Get a Jev API key Sign in at [typesafe.ai](https://typesafe.ai/) and create an API key. Jev requires an explicit key — it does not fall back to any other key you have configured (for example, an OpenRouter key). ### 2. Configure the environment variables Add these to your `.env` file: ```txt theme={null} JEV_API_KEY=your-jev-api-key ``` That is the minimum required. The endpoint and model default to TypeSafe's production API: ```txt theme={null} JEV_ENDPOINT=https://api.typesafe.ai/v1/systemone # default JEV_MODEL=jev-latest # default ``` ### 3. Select Jev as the categorization provider Each family chooses their own provider. Once `JEV_API_KEY` is set and preview features are enabled: 1. Go to **Settings > Self-Hosting > Categorization provider**. 2. Select **Jev (TypeSafe)**. 3. Save. To switch every family on the instance at once, set the environment variable override: ```txt theme={null} CATEGORIZATION_PROVIDER=jev ``` This takes precedence over each family's individual choice. ## Confidence threshold Jev returns a confidence score between 0 and 1 for each answer. Sure uses this to decide whether to apply the category or leave the transaction uncategorized for a later retry. The default threshold is **0.7**. Measured against a 200-sample golden set, this threshold: * Categorizes 91.5% of transactions * Reduces the error rate on applied answers from 4.5% to 1.6% Answers below the threshold are not applied and not locked, so a later run retries them. Raising the threshold withholds more answers without meaningfully reducing errors. You can adjust the threshold per family in **Settings > Self-Hosting** or set an instance-wide override: ```txt theme={null} CATEGORIZATION_CONFIDENCE_THRESHOLD=0.7 # range: 0.0–1.0 ``` The LLM path does not report confidence scores and is never gated by this threshold. ## Shadow mode Shadow mode runs the unselected provider alongside the active one. It applies only the selected provider's answers but records where the two providers disagreed. This lets you compare providers on real traffic without switching over. Shadow mode is off by default because it doubles categorization spend. Turn it on by setting a sampling rate: ```txt theme={null} CATEGORIZATION_SHADOW_RATE=0.1 # 10% of runs also query the other provider ``` The rate is sampled per categorization run, not per transaction (because LLM providers categorize a whole batch in one request). A value of `1.0` shadows every run. Results appear in **Settings > Self-Hosting** under the categorization panel. ## Using a gateway Jev's API is compatible with OpenRouter's Decisions API. To route through OpenRouter, set both variables: ```txt theme={null} JEV_ENDPOINT=https://openrouter.ai/api/alpha/decisions JEV_MODEL=~typesafe/jev-latest ``` Routing through a gateway means your families' transaction descriptions transit that gateway as well as TypeSafe. The data-sharing disclosure in **Settings > Self-Hosting** names the host your current configuration actually sends to, and notes when a gateway is involved. > [!WARNING] > > `JEV_ENDPOINT` must use HTTPS. HTTP endpoints (other than loopback addresses like `localhost` or `127.0.0.1`) are rejected to prevent the API key and transaction descriptions being transmitted in cleartext. If the endpoint is rejected, Sure falls back to the LLM provider and writes a diagnostic entry to the debug log rather than stopping categorization entirely. ## Environment variable reference | Variable | Default | Description | | - | - | - | | `JEV_API_KEY` | — | Required. TypeSafe API key. No fallback to other keys. | | `JEV_ENDPOINT` | `https://api.typesafe.ai/v1/systemone` | Jev API endpoint. Must use HTTPS (loopback exempt). | | `JEV_MODEL` | `jev-latest` | Model name passed to the endpoint. | | `CATEGORIZATION_PROVIDER` | — | `llm` or `jev`. Overrides every family's choice when set. | | `CATEGORIZATION_CONFIDENCE_THRESHOLD` | `0.7` | Minimum confidence to apply an answer. Clamped to 0.0–1.0. | | `CATEGORIZATION_SHADOW_RATE` | `0.0` | Fraction of runs that also query the other provider. Clamped to 0.0–1.0. | | `JEV_REQUEST_TIMEOUT` | `30` | Per-request HTTP timeout in seconds. Raise for slow endpoints. | | `JEV_CONCURRENCY` | `8` | Maximum number of concurrent requests per categorization run. | `JEV_REQUEST_TIMEOUT` and `JEV_CONCURRENCY` are environment-only controls. Jev credentials, endpoint, and model can be configured in **Settings > Self-Hosting** when preview features are enabled; those are instance settings. Categorization provider, confidence threshold, and shadow rate have family preferences. Their corresponding environment variables take precedence when set. On initial display, the endpoint field shows the effective URL with userinfo, query string, and fragment removed. `JEV_ENDPOINT` takes precedence and disables this field when set. After a validation error, the form can redisplay the value you submitted. The field auto-submits on blur. When a submitted value matches the redacted form of the stored endpoint, Sure preserves the original stored URL. A different valid URL replaces the stored value; a blank clears it. # Kraken Source: https://docs.sure.am/providers/kraken Connect Kraken crypto exchange accounts to Sure Kraken is a cryptocurrency exchange. Sure connects to Kraken using a read-only API key and imports your combined crypto holdings and spot trade history. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## What is imported Sure imports one combined Crypto exchange account per Kraken connection, containing: * Current crypto holdings and balances — staked and bonded wallet balances (such as ETH.B or DOT28.S) are combined with their spot balance into a single holding per asset, valued at their balance-weighted average price * Spot trade fills (buy/sell history) * Deposits and withdrawals — each imported as two entries: the principal and a separate fee entry, so the transfer can be matched to your receiving account * Staking rewards and Earn income * Dust sweeps ("convert small balances") as paired Sweep In / Sweep Out entries * Standalone fiat fees Crypto ledger entries (deposits, withdrawals, staking rewards, and so on) are recorded as trades that carry a unit quantity and the price on the day they moved, not as cash transactions. This keeps your crypto position history accurate and separate from your cash balance. Fiat balances held at the exchange (EUR, USD, and other supported currencies) are treated as cash, not as holdings. This prevents them from being valued twice alongside the cash your ledger already tracks. Staked and bonded asset variants — for example, ETH2.S or DOT28.S — are treated as the same position as their underlying asset. A staked ETH balance and a spot ETH balance appear together as one holding. For spot trades, Sure reads the filled quantity and cash movement from the Kraken ledger rather than from TradesHistory. The ledger nets each side of a trade against its fee — including fees charged in the base asset, which TradesHistory does not expose — so the recorded quantity and cash reflect what actually moved. Quantity and cash are resolved independently: if one ledger side is unavailable, that value falls back to TradesHistory. When the missing ledger side arrives, Sure can correct that value on an unprotected trade. ## Setting up Kraken ### Step 1: Create a Kraken API key 1. Go to [Kraken API settings](https://pro.kraken.com/app/settings/api). 2. Create a new API key with the following permissions only: * **Query Funds** * **Query Closed Orders & Trades** * **Query Ledger Entries** > [!WARNING] > > Do not grant trading, cancellation, withdrawal, export, or transfer permissions. Sure only needs read access. Granting write permissions is unnecessary and a security risk. 3. Copy the **API Key** and **Private Key** shown after creation. ### Step 2: Add the connection in Sure 1. Go to **Settings → Providers**. 2. Find the **Kraken** section. 3. Enter a connection name, paste your **API Key** and **Private Key**, and save. 4. Sure begins syncing your Kraken exchange account automatically. ### Step 3: Import the account After the first sync, your Kraken exchange account appears in the setup queue. Click **Import Account** in the provider panel to add it to your account list. ## Multiple connections If you have multiple Kraken accounts, add a separate named connection for each one. Each connection imports one combined crypto account. ## Account currency When Sure creates your Kraken exchange account, it uses your family's currency, not Kraken's reporting currency (USD). All balances and holdings are displayed in your family's currency. Kraken trade entries retain their quote currency and are converted for display. ## Opening balance New Kraken exchange accounts have a zero historical opening anchor, separate from the current balance imported from the provider. After importing entries, Sure moves that zero anchor to the day before the earliest entry only if it is not already earlier. Existing nonzero opening anchors are preserved. ## Configuration The following environment variables are available for self-hosted deployments: | Variable | Default | Purpose | | - | - | - | | `KRAKEN_MIN_REQUEST_INTERVAL` | `1.0` | Seconds enforced between consecutive requests to Kraken's public and standard private endpoints | | `KRAKEN_HISTORY_MIN_REQUEST_INTERVAL` | `8.0` | Seconds enforced between consecutive requests to account-history endpoints (`Ledgers`, `TradesHistory`), paced separately from other calls | Sure uses separate pacing for repeated history requests during a paginated backfill. Kraken currently charges 2 counter points for ledger/trade history calls, with decay rates that depend on the account tier; see [Kraken's REST rate limits](https://docs.kraken.com/exchange/guides/rest/ratelimits). Sure's default history interval remains `8.0` seconds. Pacing is maintained per provider instance, so concurrent syncs or other applications using the same API key can still reach the limit. Consider that shared usage and your tier before reducing either interval. If either variable is set to an invalid value (non-numeric, zero, negative, or infinite), Sure raises a configuration error on the first request using that interval rather than silently disabling the throttle. ## Troubleshooting ### Credentials need updating If the connection shows a reconnect prompt, your API key may have been revoked or the credentials may have expired. Generate a new API key from Kraken and update the connection in **Settings → Providers → Kraken**. ### No accounts found After adding a connection, wait for the first sync to complete. If no accounts appear after syncing, verify that your API key has the **Query Funds** permission enabled. ### Balance shown as approximate When the exact exchange rate for a given date is unavailable, Sure shows the balance as approximate. The balance updates to the exact figure on the next sync when rate data becomes available. ### Historical account value looks wrong after a buy or sell If your Kraken account was connected before October 2026, trade entries may have been recorded with their cash flow direction inverted: a buy was recorded as money arriving and a sell as money leaving, rather than the reverse. This caused the historical balance series to show incorrect values, sometimes by a large amount on accounts with significant trading activity. The upgrade migration corrects eligible existing trade entries automatically. The balance series then rebuilds on the account's next sync; no re-import is needed. Entries marked as manually modified are left unchanged. ### Setup screen shows USD balance instead of your currency The setup screen converts Kraken's reported balance into your family's currency before display. If no exchange rate is available for the conversion, the screen shows zero rather than an unconverted figure. The initial current account balance uses the same conversion. The zero historical opening anchor is separate from this current balance. ### Crypto holdings history looks wrong for older accounts If your Kraken account was connected before October 2026, crypto ledger entries may have been recorded as cash transactions rather than unit-carrying trades. Sure corrects these automatically on the next sync — no re-import or manual action is needed. Entries you have manually edited or matched into a transfer are left as-is. ### Balance history looks wrong for accounts older than two years Older accounts may have an opening anchor dated after their earliest imported entry. After an import, Sure moves a zero opening anchor earlier when needed. It preserves nonzero opening anchors, so syncing does not automatically reset an existing nonzero opening balance. ### The same asset appears as multiple holdings If you see separate holdings for what should be one position — for example, BTC split across different entries — older snapshots may use different security records for the same asset. Current imports resolve each asset to a canonical security and combine spot, staked, and bonded variants in the new snapshot. This does not guarantee that all older duplicate holding records are removed. ### Fiat balance appears as a holding If a currency like EUR or USD appears in your holdings list, the balance was imported before Sure began excluding fiat from the holdings snapshot. Current imports skip fiat holdings. This does not guarantee removal of fiat holding records already stored by an older import. ### Trade quantities or cash amounts look slightly off Kraken can charge a trade's fee in either the base asset (for example, BTC on a BTC/USD buy) or the quote currency. When the fee comes out of the base asset, TradesHistory reports the gross quantity with no indication that units were taken as a fee. Sure now reads trade quantity and cash from the Kraken ledger, which nets fees correctly on both sides. Trades imported before the "Query Ledger Entries" API permission was active — or before the ledger backfill reached them — held the uncorrected gross figures. Sure corrects those trades automatically on the next sync once the ledger rows are available. Trades you have manually edited or locked are left unchanged. # Lunch Flow Source: https://docs.sure.am/providers/lunchflow Connect bank accounts worldwide with global coverage Lunch Flow is a paid third-party provider that offers global bank account connectivity. It's the recommended option for users who need to connect accounts from multiple countries or regions outside the EU and US. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works Lunch Flow provides a unified API to access bank accounts across different countries and financial institutions: 1. Obtain a Lunch Flow API key 2. Configure the API key in Sure 3. Sure syncs your accounts, balances, and transactions 4. Data is refreshed automatically to keep information current ## Global coverage Lunch Flow supports financial institutions worldwide, making it ideal for: * Users with accounts in multiple countries * Regions not covered by Enable Banking or SimpleFIN * International banking needs ## Setting up Lunch Flow To connect your bank accounts: 1. Sign up for a Lunch Flow account at [lunchflow.app](https://lunchflow.app/) 2. Generate an API key from your Lunch Flow dashboard 3. In Sure, add your Lunch Flow API key 4. Sure will automatically discover and sync your connected accounts ## Account setup After importing Lunch Flow accounts, Sure asks you to assign a type to each one before it appears in your accounts list. When selecting accounts, Sure displays each account's name, institution, currency, status, and — where available — the last four characters of the IBAN. The full IBAN is never shown. ### Account types Choose from the following types during setup: * **Checking or savings account** — checking, savings, HSA, certificate of deposit, money market * **Credit card** * **Investment account** — brokerage, pension, retirement, 401(k), Roth 401(k), 403(b), TSP, 529 Plan, HSA, mutual fund, traditional IRA, Roth IRA, angel, and registered plans for Canadian and European accounts * **Loan or mortgage** — mortgage, student loan, auto loan, home equity, line of credit, business loan, other * **Other asset** * **Skip** — excludes the account from import ### Historical data range The setup form accepts a historical start date, but the transaction importer at the [verified Sure commit](/providers/transaction-history) does not use the saved connection start date. A newly created provider account normally requests about seven days of transactions. Later syncs use a recent overlap rather than automatically recovering older history. This is a Sure integration limitation, not a statement about how much history Lunch Flow or your bank can provide. Selecting an earlier setup date does not currently guarantee that range will be fetched. ## Features ### Account management * **Account listing**: View all connected accounts with balances * **Balance tracking**: Real-time balance information in native currencies * **Transaction history**: Import transactions with date range filtering * **Investment holdings**: Track investment account holdings and values (where supported) ### Transaction syncing Sync transactions with flexible filtering: * Filter by date range (start and end dates) * Automatic pagination for large transaction sets * Transaction details include merchant, description, amount, and currency * **Pending transactions**: Optionally include pending transactions that haven't yet posted to your account ### Investment accounts For investment accounts, Lunch Flow provides: * Holdings information (securities, quantities, values) * Total portfolio value * Currency-specific valuations Note: Not all account types support holdings. The API will indicate when holdings are not available for a specific account. ### Balance reported as available credit Some banks report a credit card's remaining available credit instead of the amount owed. For example, a card with a £5,000 limit and £16.17 outstanding might return +£4,983.83 rather than -£16.17. Without correction, Sure interprets this as a large credit balance and overstates your net worth by roughly the full card limit. To fix this, open the credit card's edit dialog and enable **Balance is available credit**. For Lunch Flow cards, this control appears when the card is linked to Lunch Flow. Enable Banking cards have a corresponding control. When the toggle is on, Sure derives the debt from the card's **Available credit** field (which holds the limit, since Lunch Flow does not report one) using the formula: limit minus the reported amount. If no limit is set, Sure keeps the last known balance and logs a warning rather than recording the available credit figure as debt. Overpayments remain a negative (credit) balance, matching the default Lunch Flow behaviour. If you change the card limit while the toggle is on, Sure queues a sync automatically to update the balance when that sync runs. ### Holdings history Holdings are stored by date: a sync on a new day creates that day’s row, while another sync on the same day updates it instead of overwriting the previous day’s record. Sure accumulates a daily history of your positions so you can see how your portfolio has changed over time. ### User corrections carried forward When you remap a holding to a different security or lock a cost basis, Sure preserves that correction when a new day's sync creates the next holding row. Sure uses the latest earlier row for the same account, provider, provider security, and currency, carrying its active security and cost-basis locks forward. If you have since undone a correction, the undone state is not revived — only the latest version is carried forward. ### Sync status The Lunch Flow connection card shows the current sync state: * **Synced N accounts** — all linked accounts are active * **N synced, M need setup** — some imported accounts haven't been assigned a type yet; go to "Set Up New Accounts" to complete setup * **Never synced** — no sync has run yet * **Error** — the last sync encountered a problem; the error tooltip shows details ## API structure Lunch Flow uses a straightforward REST API: * **GET /accounts**: List all connected accounts * **GET /accounts//balance**: Get current balance for an account * **GET /accounts//transactions**: Fetch transaction history * **GET /accounts//holdings**: Get investment holdings (if supported) ## API reference For detailed API documentation, see the [Lunch Flow documentation](https://docs.lunchflow.app/introduction). ## Pricing Lunch Flow is a paid service. Check [lunchflow.app](https://lunchflow.app/) for current pricing information. ## Configuration ### Pending transactions You can configure Lunch Flow to include pending transactions in your syncs. Pending transactions are those that have been authorized but haven't yet posted to your account. To enable pending transactions, set the following environment variable: ```bash theme={null} LUNCHFLOW_INCLUDE_PENDING=1 ``` When enabled, transactions marked as pending by Lunch Flow will be imported and displayed with a "Pending" badge in the UI. When a pending transaction posts, Sure automatically refreshes the stored snapshot so the entry transitions from pending to posted. The "Pending" badge is removed and the transaction reflects the final posted details. ### Card authorization holds Some banks return unfinalized card authorization holds with blank transaction IDs, masked card numbers instead of merchant names (for example `474836xxxxxx6879 003015315475`), and sometimes with inverted credit/debit signs. When `LUNCHFLOW_INCLUDE_PENDING=1` is set, Sure detects these holds automatically and imports them as pending expenses named **Card Authorization Hold**. No merchant is created for them. If the bank reports the hold amount as a credit (inflow), Sure corrects the sign so it appears as an outgoing expense, matching the settled transaction when it arrives. When pending transactions are disabled (`LUNCHFLOW_INCLUDE_PENDING` is not set or is `0`), unidentified card holds are filtered out and not imported. ### Debug mode For troubleshooting, you can enable debug logging to see the raw API responses: ```bash theme={null} LUNCHFLOW_DEBUG_RAW=1 ``` ## Limitations * Requires a paid Lunch Flow subscription * Subject to Lunch Flow API rate limits * Holdings data not available for all account types * Coverage varies by country and institution ## Troubleshooting ### Connection fails with a validation error If you submit the Lunchflow connection form with a missing or blank API key, Sure redirects back to the Accounts page and displays an alert describing the validation error (for example, "Api key can't be blank"). Correct the API key and try again. ### Rejected credentials When Lunch Flow rejects the API key with a 401 or 403, Sure marks the connection as requiring an update and the sync fails. The connection card shows a **Reconnect** prompt instead of a green "Connected" status. Update the API key in **Settings -> Providers** to restore syncing. ### Sync marked unhealthy after a fetch failure When the Lunch Flow API rejects fetches — for example due to rate limiting or a transient network error — Sure marks the sync as unhealthy and surfaces a warning in the UI. The warning message indicates how many accounts or transaction fetches failed, and is shown in your configured language. Once the Lunch Flow API becomes available again, trigger a manual sync from the Accounts page to clear the error and import the missing data. ### Balances during rate limits If the Lunch Flow balance endpoint returns an error (for example a 429 rate-limit response), Sure keeps the existing balance on your account rather than resetting it to zero. The account balance stays unchanged until a successful balance fetch updates it on the next sync. ### Pending transactions stuck with a "Pending" badge Lunch Flow assigns stable IDs to most transactions. When a transaction moves from pending to posted under the same ID, Sure detects that the stored snapshot has changed and refreshes it automatically on the next sync, clearing the pending status. Some pending transactions from Lunch Flow have no ID. Sure deduplicates these by content hash within a single sync response, so two genuinely identical purchases in the same response are each preserved rather than collapsed into one. If a pending transaction with no ID is still showing after it has posted, trigger a manual sync to force a fresh fetch. # Mansa API Source: https://docs.sure.am/providers/mansa Connect NGX (Nigerian Exchange) securities with the Mansa API provider Mansa API is a market data provider for African stock exchanges. Sure's integration covers the Nigerian Exchange (NGX), which is not available through Sure's other securities providers. ## Overview * **Coverage**: NGX (Nigerian Exchange) securities * **Free tier**: 100 requests per day, no credit card required * **API key**: Required — get one at [mansaapi.com](https://mansaapi.com) * **Historical data**: Current quote only (free tier). Historical OHLCV requires a paid Mansa Pro plan. ## Setting up Mansa API 1. Register at [mansaapi.com](https://mansaapi.com) and obtain an API key. 2. In Sure, go to **Settings > Self-Hosting** and enable **Mansa API** under securities providers. 3. Enter your API key in the settings form. ### Environment variable You can also set the API key as an environment variable: ```bash theme={null} MANSA_API_KEY=your-key-here ``` When `MANSA_API_KEY` is set in the environment, the key field in the UI is disabled. The environment variable takes precedence. ## How it works ### Searching for securities When you add an NGX-listed stock to a trade or holding, Sure queries the Mansa API search endpoint scoped to the Nigerian Exchange. Results that cannot be mapped to a verified ISO MIC code are dropped rather than stored with a non-standard exchange code. Sure's trade form does not pass an exchange filter when you search — the integration defaults to NGX. If a specific exchange is passed and it is not NGX (MIC: `XNSA`), the search returns no results rather than silently fetching from an unverified exchange. ### Prices The free tier exposes the current quote only. Sure uses this in two ways: * **Today's price**: Fetched directly from the live quote endpoint. * **Date range including today**: Sure returns today's quote as a single data point. This is enough for a current holding valuation sync. A date range entirely in the past cannot be fulfilled on the free tier. Sure reports a clear error in that case rather than returning nothing silently. ### Rate limits The free tier allows 100 requests per day. Sure tracks usage in its cache and blocks requests once the daily limit is reached to avoid API errors mid-sync. You can override the default limit with an environment variable if your plan allows more requests: ```bash theme={null} MANSA_MAX_REQUESTS_PER_DAY=500 ``` ## Limitations * **NGX only**: Only the Nigerian Exchange is verified and supported. Other African exchanges covered by Mansa's API are not enabled. * **No historical prices**: The free tier has no historical OHLCV endpoint. Holdings sync with today's price only. * **100 requests/day**: A large portfolio with many NGX securities may approach the free-tier limit during a full sync. ## Troubleshooting ### Security not found If a search returns no results for a ticker you expect to find: * Confirm the ticker is listed on the NGX. Mansa does not return results for other exchanges. * Check whether your daily request limit has been reached under **Settings > Self-Hosting > Mansa API**. ### Historical price errors If you see an error about historical prices not being available, your portfolio sync is requesting prices for past dates. The free tier only supports the current quote. To resolve this, either upgrade to a Mansa Pro plan or accept that NGX holdings will only show today's value rather than full price history. ### Rate limit reached If syncs fail with a rate limit error, you have exhausted the 100 requests/day free tier. Options: * Wait until the daily limit resets (midnight UTC). * Upgrade your Mansa plan and set `MANSA_MAX_REQUESTS_PER_DAY` to match your new limit. * Reduce the number of NGX securities in your portfolio to stay within the free tier. # Market data providers Source: https://docs.sure.am/providers/market-data Configure securities pricing providers for stock, ETF, and mutual fund data Sure uses market data providers to fetch security prices, search for securities, and display portfolio holdings. You can enable multiple providers simultaneously, and each security can be assigned to a specific provider. ## Available providers | Provider | API key required | Free tier | Coverage | | - | - | - | - | | **Yahoo Finance** | No | Unlimited | Global stocks, ETFs, crypto | | **Twelve Data** | Yes | 800 requests/day | Global stocks, ETFs, forex | | **Tiingo** | Yes | 500 requests/hour | US and international equities | | **EODHD** | Yes | 20 requests/day | 70+ global exchanges | | **Alpha Vantage** | Yes | 25 requests/day | Global stocks, ETFs | | **MFAPI** | No | Unlimited | Indian mutual funds | | **MOEX** | No | Unlimited | Russian stocks, funds, and bonds (MOEX), including RUB forex | | **T-Invest (T-Bank)** | Yes (read-only token) | N/A | Russian stocks, funds, and bonds; brand logos for all securities | | **Mansa API** | Yes | 100 requests/day | NGX (Nigerian Exchange) securities | ## Configuring providers You can enable and configure market data providers from **Settings > Self-Hosting** in the Sure UI. Select the providers you want to use and enter API keys where required. ### Environment variables You can also configure providers through environment variables. Add these to your `.env` file or Docker Compose configuration: ```bash theme={null} # Exchange rate provider (default: twelve_data) EXCHANGE_RATE_PROVIDER=twelve_data # Securities providers (comma-separated list) SECURITIES_PROVIDERS=yahoo_finance,twelve_data # API keys TWELVE_DATA_API_KEY=your-key-here TIINGO_API_KEY=your-key-here EODHD_API_KEY=your-key-here ALPHA_VANTAGE_API_KEY=your-key-here ``` > [!NOTE] > > When you set `SECURITIES_PROVIDERS` as an environment variable, it takes precedence over the UI setting. To manage providers from the UI only, leave the environment variable unset. ### Multiple providers You can enable multiple securities providers at the same time. When searching for securities, Sure queries the active provider and assigns each security to the provider that found it. This lets you use different providers for different asset types — for example, Yahoo Finance for US stocks and MFAPI for Indian mutual funds. If you disable a provider that has securities assigned to it, those securities are marked offline until the provider is re-enabled. ## Provider details ### Yahoo Finance Yahoo Finance is the default provider and requires no API key. It offers broad global coverage for stocks, ETFs, indices, and cryptocurrencies. * **Rate limits**: No strict API key limits, but subject to Yahoo's usage policies * **Coverage**: Global stocks, ETFs, mutual funds, indices, crypto * **API key**: Not required #### How price fetching works Sure fetches chart and price data from Yahoo Finance without sending authentication cookies or a crumb token. Yahoo rate-limits authenticated chart requests far more aggressively than anonymous ones, so skipping authentication reduces 429 rate-limit errors on price syncs. If Yahoo returns a 401 for a specific symbol (either a hard HTTP 401 or a 200 response with an `Unauthorized` error code), Sure automatically retries that request once with a fresh cookie and crumb. If the retry also fails with a 401, Sure raises an authentication error and stops retrying. Cookie and crumb authentication is still used for security detail lookups (the `quoteSummary` endpoint), which require it. #### European and other non-US exchanges Sure automatically appends Yahoo Finance's required exchange suffix when fetching prices for securities listed on European and other international exchanges. The following venues are supported: | Exchange | MIC | Yahoo suffix | Currency | | - | - | - | - | | Xetra | XETR | `.DE` | EUR | | Frankfurt floor | XFRA | `.F` | EUR | | Munich | XMUN | `.MU` | EUR | | Stuttgart | XSTU | `.SG` | EUR | | London Stock Exchange | XLON | `.L` | GBP | | Euronext Paris | XPAR | `.PA` | EUR | | Euronext Amsterdam | XAMS | `.AS` | EUR | | Euronext Brussels | XBRU | `.BR` | EUR | | Euronext Lisbon | XLIS | `.LS` | EUR | | Bolsa de Madrid | XMAD | `.MC` | EUR | | Borsa Italiana | XMIL | `.MI` | EUR | | SIX Swiss Exchange | XSWX | `.SW` | CHF | | Nasdaq Stockholm | XSTO | `.ST` | SEK | | Nasdaq Copenhagen | XCSE | `.CO` | DKK | | Nasdaq Helsinki | XHEL | `.HE` | EUR | | Oslo Børs | XOSL | `.OL` | NOK | | Vienna Stock Exchange | XWBO | `.VI` | EUR | | NSE India | XNSE | `.NS` | INR | | BSE India | XBOM | `.BO` | INR | | Colombia | XBOG | `.CL` | COP | | Indonesia | XIDX | `.JK` | IDR | London-listed securities are quoted in pence (GBp) by Yahoo Finance. Sure converts pence prices to GBP automatically. If a security's exchange is not in the table above, its ticker is sent to Yahoo Finance without a suffix. You can still find and add such securities by searching with the full suffixed symbol as shown on Yahoo Finance's quote page URL. #### Searching for securities with exchange suffixes Yahoo Finance's search index has gaps for some instruments — notably non-US managed funds such as Australian APIR-coded funds (e.g. `VAN0111AU.AX`). When the search index returns no results for a query that looks like a fully qualified symbol (contains a `.` exchange suffix, such as `.AX` for ASX or `.L` for LSE), Sure retries the query directly against the Yahoo Finance chart endpoint and synthesizes a result from the returned metadata. This means you can add these instruments by pasting the full symbol exactly as shown on Yahoo Finance's own quote page URL — for example, `VAN0111AU.AX` rather than just `VAN0111AU`. A bare ticker without an exchange suffix does not trigger the fallback, since bare tickers already resolve through Yahoo's normal search index. > [!NOTE] > > If you experience connection issues with Yahoo Finance, some IPv6 networks may have trouble reaching Yahoo's servers. Try setting `YAHOO_FINANCE_IPV6=false` in your environment variables to force IPv4 connections. ### Twelve Data Twelve Data provides real-time and historical market data for global equities and forex. It also serves as the default exchange rate provider. * **Provider free tier**: 800 API requests per day * **Sure throttle default**: 7 API credits per minute; this is Sure's pacing setting, not the provider's advertised plan limit * **Coverage**: Global stocks, ETFs, forex, crypto * **API key**: Required — get one at [twelvedata.com](https://twelvedata.com) Sure paces requests to stay within Twelve Data's per-minute limit using a two-layer throttle: a per-instance minimum interval between calls, and a global per-minute credit counter stored in the cache. The per-minute counter requires Redis in production — with `null_store`, usage is not retained between requests, so the per-minute limit is not enforced. You can tune the throttle with these environment variables: | Variable | Default | Description | | - | - | - | | `TWELVE_DATA_MAX_REQUESTS_PER_MINUTE` | `7` | Maximum API credits consumed per minute | | `TWELVE_DATA_MIN_REQUEST_INTERVAL` | `1.0` | Minimum seconds between consecutive requests | ### Tiingo Tiingo provides end-of-day and intraday price data for US and international equities. * **Rate limits**: 500 requests per hour (free tier) * **Coverage**: US stocks, international equities, ETFs, mutual funds * **API key**: Required — get one at [tiingo.com](https://www.tiingo.com) ### EODHD EODHD (End of Day Historical Data) provides end-of-day prices across 70+ global exchanges. * **Rate limits**: 20 API requests per day (free tier) * **Coverage**: 70+ exchanges worldwide, stocks, ETFs, mutual funds, bonds * **API key**: Required — get one at [eodhd.com](https://eodhd.com) #### Warsaw Exchange (GPW) securities Securities listed on the Warsaw Stock Exchange (XWAR/GPW) are priced in PLN. If you added Polish securities before this fix was released, their historical prices may have been stored as USD. Sure automatically corrects mis-tagged Warsaw prices on upgrade: USD prices are relabeled to PLN, duplicates are removed, and any affected accounts are queued for a sync so holdings revalue at the correct exchange rate. ### Alpha Vantage Alpha Vantage provides free stock, ETF, and technical data for global markets. * **Rate limits**: 25 API requests per day (free tier), with a minimum 1-second interval between requests * **Coverage**: Global stocks, ETFs, technical indicators * **API key**: Required — get one at [alphavantage.co](https://www.alphavantage.co) * **History**: Free tier returns approximately 100 trading days of historical data ### MFAPI MFAPI is a free, open-source API for Indian mutual fund NAV (Net Asset Value) data. It requires no API key. * **Rate limits**: No strict limits * **Coverage**: Indian mutual funds only (BSE-listed schemes) * **API key**: Not required ### MOEX MOEX (Moscow Exchange) is a free provider for Russian-listed securities via the ISS public API. It requires no API key. * **Rate limits**: No strict limits * **Coverage**: Russian stocks, ETFs, BPIFs (mutual funds), and bonds on the Moscow Exchange; also provides RUB exchange rates * **API key**: Not required ### T-Invest (T-Bank) T-Invest is T-Bank's (formerly Tinkoff) invest API. It serves two purposes in Sure: 1. **Securities pricing** — when enabled as a provider, it prices Russian stocks, funds, and bonds listed on MOEX and SPB Exchange. 2. **Brand logos** — when a read-only token is configured, Sure uses T-Invest's CDN to fetch instrument brand logos for all securities, regardless of which provider handles pricing. This means MOEX-priced holdings still get real logos if a T-Invest token is present. Because of the brand logo role, the T-Invest settings block in **Settings > Self-Hosting** remains visible whenever a token is already configured, even if T-Invest is not checked as a price provider. * **Rate limits**: Generous per-minute limits (hundreds of requests per minute) * **Coverage**: Russian stocks, funds (incl. БПИФs), and bonds on MOEX and SPB Exchange; brand logos for any security * **API key**: Required — create a read-only token in T-Bank investments under Settings > API tokens (requires an open T-Bank brokerage account) ### Mansa API Mansa API provides current quote data for securities listed on the Nigerian Exchange (NGX). It is the only Sure provider with verified NGX coverage. * **Rate limits**: 100 API requests per day (free tier) * **Coverage**: NGX (Nigerian Exchange) only * **API key**: Required — get one at [mansaapi.com](https://mansaapi.com) * **History**: The free tier returns today's quote only. Historical OHLCV data requires a paid Mansa Pro plan. > [!NOTE] > > Because the free tier has no historical endpoint, NGX holdings sync with today's price rather than building full price history. A date range that doesn't include today will return an error rather than empty data. See the [Mansa API provider page](/providers/mansa) for full setup instructions. ## Price sync scope Sure only fetches prices for the date range each account actually needs for a given security. The range starts with the earliest trade or positive holding for that security. For provider-synced holdings, it can extend back to the account start date. Its end depends on whether you still hold the position: * **Open positions** — prices are fetched through today. * **Closed positions** — prices are fetched through the later of the last quantity-changing trade and the last positive holding date. Once you sell or transfer out your full position, Sure stops requesting new prices for that security in that account. If you reopen a position (by buying again, or by editing a trade that affects the net quantity), Sure detects the change and resumes fetching prices through today. This scoping applies to both account-level syncs and the daily market data import. The daily importer merges the required windows across accounts before importing each security’s prices. Account-level syncs use their own account’s window. The daily importer also checks security details for all online securities, even when their positions are closed. Details already present are normally reused rather than fetched again. ## Price freshness When Sure cannot fetch a real price for a given date (for example, on weekends or market holidays when providers return no data), it carries the last known price forward to fill the gap. These gap-filled prices are marked as **provisional**. Provisional prices are automatically replaced the next time a sync runs and the provider returns a real value for that date. Sure re-checks provisional prices within a 7-day rolling window, so a Friday price carried forward over a weekend is corrected as soon as Monday's data is available. Prices older than 7 days that were gap-filled are kept as-is and are not re-fetched. Prices you edit manually are never marked provisional and are not overwritten by syncs. # Mercury Source: https://docs.sure.am/providers/mercury Connect Mercury business bank accounts to Sure Mercury is a business banking platform for startups and small businesses. Sure connects to Mercury using a read-only API token you generate from your Mercury account settings. > [!NOTE] > > Mercury requires IP whitelisting. Before connecting, add your server's IP address to the allowed list in your Mercury dashboard. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works Sure uses the Mercury API to pull account balances and transaction history directly into your family's accounts. Each Mercury login or API token you want to sync requires its own named connection. ## Setting up Mercury ### Step 1: Generate a Mercury API token 1. Log in to [mercury.com](https://mercury.com) with the account you want to connect. 2. Go to **Settings → Developer → API Tokens**. 3. Create a new API token with **Read Only** access. 4. Copy the full token, including the `secret-token:` prefix. ### Step 2: Add the connection in Sure 1. Go to **Settings → Providers**. 2. Find the **Mercury** section. 3. Enter a connection name and paste the full token (including the `secret-token:` prefix). 4. Leave the **Base URL** field blank for production. For sandbox testing, enter `https://api-sandbox.mercury.com/api/v1`. 5. Click **Add Mercury connection**. Sure begins syncing your accounts automatically after saving the connection. ### Step 3: Set up accounts After the first sync, Mercury accounts appear in the setup queue. Click **Set up accounts** in the connection panel to assign each account an account type (checking, savings, and so on) and a transaction history start date before they appear in your account list. You can sync up to three years of transaction history. ## Multiple accounts Use a separate named connection for each Mercury login or API token you want to sync. Each connection is independent and syncs only the accounts accessible to its token. ## Encryption Mercury API tokens are stored using ActiveRecord Encryption when encryption keys are configured in your deployment. Without encryption keys, tokens are stored in plaintext. Configure `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`, `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY`, and `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT` before adding tokens in a production environment. ## Troubleshooting ### Invalid API token Make sure you copied the full token, including the `secret-token:` prefix. Verify that the token has not been revoked in your Mercury account. Generate a new token if needed. ### Insufficient permissions The token must have **Read Only** access. Tokens created with write access or no access will not work. Generate a new token with the correct permissions. ### Expired credentials Mercury tokens can be revoked from the developer settings. When Mercury rejects the token with a 401 or 403, Sure marks the connection as requiring an update and the sync fails — the connection card shows a **Reconnect** prompt instead of a green "Connected" status. Generate a new token and update the connection in **Settings → Providers → Mercury**. ### Connection fails with a network error Mercury requires that your server's IP address is whitelisted in the Mercury dashboard. Add your IP under the API token settings and retry the connection. ### Sandbox testing For sandbox testing, set the **Base URL** to `https://api-sandbox.mercury.com/api/v1`. Sandbox tokens are separate from production tokens and do not work against the production endpoint. # Monobank Source: https://docs.sure.am/providers/monobank Connect your Monobank (Ukraine) account to Sure Monobank is a Ukrainian neobank. Sure connects to it directly using Monobank's personal API, syncing your cards, jars, balances, and transactions automatically. You bring your own token — no third-party aggregator sits in between. > [!NOTE] > > This integration uses Monobank's **personal** API. Its documentation states that a service which stores other people's data on its own servers must use the corporate (service provider) API instead, and that programs used by clients personally — where the data never passes through the developer's nodes — do not. A self-hosted Sure instance is the latter. If you run Sure as a hosted service for other people, read [Monobank's API terms](https://api.monobank.ua/docs/index.html) first. > [!NOTE] > > The personal API is not available to clients under 16. Data for a child's accounts is available from the parent's account. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works 1. Generate a personal token at [api.monobank.ua](https://api.monobank.ua/) 2. Paste the token into Sure 3. Sure discovers your cards and jars and begins syncing balances and transactions 4. MCC codes on transactions are mapped to your Sure categories automatically on import ## Setting up Monobank 1. Go to [api.monobank.ua](https://api.monobank.ua/) and sign in by scanning the QR code with the Monobank app 2. Generate a personal token and copy it. It is shown only once 3. In Sure, go to **Settings > Providers**, find the **Monobank** panel, and paste the token 4. Link each discovered card or jar to an existing Sure account or create a new one. Skip anything you don't want to track Cards become checking accounts; jars become savings accounts. A card's balance reflects your own funds — Monobank includes the credit limit inside the reported balance, and Sure subtracts it. ## Features ### Account syncing * **Cards and jars**: All Monobank cards and jars with current balances * **Transaction history**: Transactions are imported with date, amount, description, and category * **Deduplication**: Transactions are matched by their Monobank ID, so re-syncing never creates duplicates ### Pending transactions Held (unsettled) authorisations are imported and marked **Pending**. When a hold settles, Monobank may issue the settled record under a different ID. Sure matches it to the pending entry by amount and date, and the settled record inherits the pending entry's category and notes. A hold that disappears from the statement (cancelled rather than settled) has its pending entry removed — unless: * The statement request did not actually reach the hold's date. It stays visible while the funds are still blocked. Pre-authorisations for hotels, car hire, and fuel routinely outlive the few days a sync re-reads by default. * You have taken over the entry yourself (excluded, edited, or split). It only loses its pending badge, so your edits, splits, and transfers survive. To import only settled transactions, set `MONOBANK_INCLUDE_PENDING=0` in your environment. ### Category mapping Monobank does not categorise transactions directly; it reports the merchant's MCC code. Sure maps codes with a clear equivalent (groceries, restaurants, fuel, pharmacies, and others) onto your existing Sure categories, matching by the category name in your own language. Codes without a clear equivalent — cash withdrawals, transfers, gambling — are left uncategorised for your own rules to handle. Category mapping only applies to your existing Sure categories. If you have already set or locked a category on a transaction in Sure, a re-sync will not overwrite it. To turn off automatic category mapping, open the account in Sure, go to its settings, and disable the **Automatic category mapping** toggle. When disabled, imported transactions carry no auto-assigned category and are left for your rules or the AI categorizer to handle. The raw transaction data and MCC code are still imported; only the auto-category assignment is skipped. ### Syncing cadence Monobank's rate limit shapes how syncing works. Each personal endpoint accepts one request per minute, and a single statement request may cover at most 31 days. So: * Every sync fetches your account list once, then reads statements account by account * A sync spends a fixed budget of statement requests (4 by default). Accounts that don't fit are picked up by the next sync, least-recently-synced first * History older than one statement window is backfilled over successive syncs, walking backwards 31 days at a time * Each sync also re-reads the last few days, and any older hold that is still unsettled, so pending transactions stay accurate Because of the throttle, a sync sleeps between requests. With four accounts, expect it to take a few minutes. ## Configuration The following environment variables are available for self-hosted deployments: | Variable | Default | Purpose | | - | - | - | | `MONOBANK_INCLUDE_PENDING` | `1` | Import held transactions and badge them as pending | | `MONOBANK_MAX_STATEMENT_REQUESTS_PER_SYNC` | `4` | Statement requests one sync may spend. Each costs about a minute | | `MONOBANK_PENDING_LOOKBACK_DAYS` | `3` | Minimum period every sync re-reads. A hold older than this extends the window on its own | | `MONOBANK_INITIAL_HISTORY_DAYS` | `31` | History a new connection reaches for when no start date is set | | `MONOBANK_MIN_REQUEST_INTERVAL` | `60` | Seconds enforced between requests to the same endpoint | | `MONOBANK_DEBUG_RAW` | unset | Log raw API payloads. Development only — the dump contains personal data | ## Foreign currency operations When a transaction is made in a currency other than the account's own currency — for example, paying in EUR from a UAH card — Monobank includes the operation currency code (`currencyCode`) and the operation amount (`operationAmount`) alongside the account-currency `amount`. Sure records the account-currency `amount` as the transaction amount and stores the foreign-currency detail as `fx_from` (the operation currency) and `fx_amount` (the operation amount in that currency), following the same convention used by the Up Bank integration. Both `fx_from` and `fx_amount` are set only when the operation currency is recognized and differs from the account currency. An operation in the account's own currency, or one whose currency code Sure does not recognize, leaves both unset. The raw `operationAmount` is always recorded in `operation_amount` for reference when it differs from `amount`. If the `operationAmount` cannot be parsed, `fx_amount` is left unset and the incident is captured as a `provider_sync_error` in the debug log (visible at **Settings > Debug**, filtered by the `monobank` provider key). ## Limitations * Ukrainian accounts only * Personal tokens are scoped to a single Monobank account holder * Data is read-only; Sure never writes anything back to Monobank (the token can also register a statement webhook, but Sure does not use that capability) ## Troubleshooting **"Configure Monobank in provider settings first" error**: If you see this alert when trying to add a Monobank account, the selected connection has no configured personal token. Go to **Settings > Providers > Monobank**, paste your token, and save before adding accounts. **Connection requires update**: The token was revoked or is invalid. Generate a new one at [api.monobank.ua](https://api.monobank.ua/) and update it in the provider panel. **A sync says accounts were skipped**: Either the statement request budget ran out for this run, or Monobank throttled the request. One request per minute per endpoint means a manual sync started right after a scheduled one collides. These are normal and leave the connection healthy. The next sync continues where this one stopped. Raise `MONOBANK_MAX_STATEMENT_REQUESTS_PER_SYNC` if you would rather trade a longer sync for fewer runs. **Older transactions are missing**: History arrives in 31-day steps, one step per sync. Set a start date on the connection to bound how far back it goes, then let it run. **Sync errors**: Provider sync failures and notes are captured in Sure's debug log. Super admins can find them at **Settings > Debug**, filtered by the `monobank` provider key. This includes cases where a foreign-currency operation amount could not be parsed — the transaction still imports with the correct account-currency amount, but the FX detail (`fx_from`/`fx_amount`) is omitted. For more detail, see the [Monobank personal API documentation](https://api.monobank.ua/docs/). # On-chain wallets Source: https://docs.sure.am/providers/onchain-wallets Track self-custody Bitcoin, EVM, Solana, Polkadot, and Cosmos Hub wallets by public address — no keys required. Sure can track wallets you hold the keys to — Bitcoin, six EVM networks, Solana, Polkadot, and Cosmos Hub — from their **public addresses only**. Nothing is signed, no key or seed phrase is ever entered, and no API key is required for any chain. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. > [!NOTE] > > Cosmos Hub (ATOM) tracks balance only — spendable plus staked plus unbonding. Sure’s Cosmos integration does not request transaction history, so no transfers are imported. ## What gets tracked One Sure account is created per **asset**, per **address**, per **network**. A wallet holding ETH, USDC, and USDT on Ethereum becomes three accounts, all Crypto accounts with the "wallet" subtype. For each asset Sure records: * The **quantity** held, read from the chain * A **holding** valued at the current price, or at zero when no price is available * The **transfers** in and out, recorded as investment trades labeled "Transfer" when the price for that day is known. Each entry is named "Received" or "Sent" (or the equivalent in your family’s language) followed by the quantity and asset symbol. Transfer trades carry a cash amount of zero — the value lives in quantity and price for cost basis purposes, but no cash leg is recorded (a self-custody wallet has no cash side). When that day’s price is not known, the transfer still appears as an excluded, zero-amount entry — and it is upgraded to a trade on the first sync after the price becomes available. Balances are read-only and always derived from the chain. Editing them by hand is pointless: the next sync overwrites them. Every sync also revalues every linked asset at the latest stored price, so a wallet that has not moved on chain still reflects current market prices after each sync. Because a transfer is not an acquisition, Sure cannot know what the asset cost you before it arrived. A holding with any transfer in its history will show no cost basis and no gain/loss trend. To see those figures, set a manual cost basis on the holding. ## Prices need two settings, not one On-chain data sources report **quantities, not values**. Prices come from Sure's market data providers, and the only provider that can quote bare crypto symbols is **Binance public** (keyless). If no crypto-capable market data provider is enabled, every on-chain wallet is tracked by quantity and **valued at zero**. This is by far the most common support report for this feature, and it is a settings issue rather than a sync failure. The settings panel and the linking modal both warn you before you link anything, and on a self-hosted instance an admin can fix it from the warning itself with **Enable crypto prices** — that adds `binance_public` to the enabled providers and leaves the others alone. Otherwise, enable it under **Settings → Self hosting → Market data providers**, or set `SECURITIES_PROVIDERS` to a comma-separated list including `binance_public`. ### Exchange rates for non-USD families The crypto provider quotes in USD, so valuing a wallet in any other family currency needs one conversion — and Sure's default exchange rate provider (`twelve_data`) requires an API key. With no key and a non-USD family, there is no FX at all and every on-chain wallet is valued at zero for that second, separate reason. Set `EXCHANGE_RATE_PROVIDER` (or **Settings → Self hosting**) to a provider you can actually use; `frankfurter` needs no API key. The linking UI warns about this gap specifically, naming your currency, and a USD family never sees the warning because it needs no conversion. When an asset ends up valued at zero for either reason, it is recorded in **Settings → Debug logs** under the `onchain_wallet` provider, with the reasons listed. ### ETH as a currency ETH (Ethereum) is a supported currency denomination in Sure, alongside standard fiat currencies. You can denominate an account directly in ETH — balances display with the Ξ symbol and up to 8 decimal places. Wei is the currency’s minor unit (1 ETH = 10^18 Wei), but Sure stores account balances and transaction amounts as decimal ETH, not integer Wei. Those fields currently store four decimal places; the eight-place display setting does not imply eight-place storage. This is separate from tracking ETH as an investment holding. An account denominated in ETH records its cash balance and transactions in ETH, whereas an on-chain wallet account tracked by the provider holds ETH as a security with a quantity and a market value. ## Data sources | Network | Source | Key required | Override | | - | - | - | - | | Bitcoin | [mempool.space](https://mempool.space) REST API | No | `MEMPOOL_SPACE_URL` | | Ethereum | Blockscout (`eth.blockscout.com`) | No | `BLOCKSCOUT_ETHEREUM_URL` | | Base | Blockscout (`base.blockscout.com`) | No | `BLOCKSCOUT_BASE_URL` | | Arbitrum | Blockscout (`arbitrum.blockscout.com`) | No | `BLOCKSCOUT_ARBITRUM_URL` | | Optimism | Blockscout (`optimism.blockscout.com`) | No | `BLOCKSCOUT_OPTIMISM_URL` | | Polygon | Blockscout (`polygon.blockscout.com`) | No | `BLOCKSCOUT_POLYGON_URL` | | Gnosis | Blockscout (`gnosis.blockscout.com`) | No | `BLOCKSCOUT_GNOSIS_URL` | | Solana | Public JSON-RPC (`api.mainnet-beta.solana.com`) | No | `SOLANA_RPC_URL` | | Solana token names | Jupiter token search (`lite-api.jup.ag`) | No | `SOLANA_TOKEN_LIST_URL` | | Polkadot | Parity Asset Hub Sidecar (`polkadot-asset-hub-public-sidecar.parity-chains.parity.io`) | No | `POLKADOT_SIDECAR_URL` | | Cosmos Hub | Public Cosmos SDK REST (`cosmos-rest.publicnode.com`) | No | `COSMOS_REST_URL` | Every override expects the base URL of a compatible instance, without a trailing slash — useful if you run your own indexer or node, or if a public endpoint rate limits you. ### Optional Etherscan key Ethereum, and only Ethereum, can be read through Etherscan instead of Blockscout. A key buys nothing except a higher rate limit. Add it under **Settings → Providers → On-chain wallets → Advanced**; it is stored encrypted, per family. A key only moves **transfer history** onto Etherscan. Balances and network detection always come from the keyless indexer. Leave the field empty unless you are being rate limited. ### Limiting transfer history by date Under **Settings → Providers → On-chain wallets → Advanced**, the **Ignore transfers before** field accepts a date. Transfers recorded before that date are skipped during every sync. Leave the field empty to import everything the explorer reports. This setting is useful when a wallet has a very long history that you do not need, or when you want to start fresh from a known date without deleting existing accounts. ## Linking a wallet Go to **Settings → Providers → On-chain wallets → Add wallet**. **1. Paste the public address** Leave the network on "Detect automatically" unless you know which one you want. **2. Confirm the network** If the address format belongs to several networks — every `0x` address is valid on all six EVM networks, and Bitcoin's Base58 shape overlaps Solana's — Sure probes each and asks you to choose, marking the ones where it found activity. **3. Choose assets to track** The native coin and assets the data source treats as notable are pre-ticked. "Notable" means a priced holding worth more than a dollar on EVM networks, or a place on Solana's verified token list. You can still track anything listed; unpriceable assets show a quantity and a value of zero. Nothing is imported that you did not tick. > [!WARNING] > > Never enter a seed phrase or private key. Sure only needs the public wallet address. ## Managing a wallet Go to **Settings → Providers → On-chain wallets → Manage wallets**. | Action | Description | | - | - | | **Review tokens** | Reopens the asset selection with the address unchanged. Use this to start tracking a token that arrived later, or stop tracking one you no longer want. | | **Stop tracking** (per asset) | Drops one asset. | | **Disconnect wallet** | Drops every asset at one address. | Disconnecting never deletes an account. The provider link is removed, holdings are detached, and what you can see stays as a manual account that no longer updates. Delete the account itself if you want it gone. Deleting an account directly — rather than disconnecting or using **Stop tracking** — is safe. The next time you add that address, Sure detects that the internal tracking record left behind is no longer linked to any account and clears it automatically before creating the new one. An address can only be tracked once per network. To change which assets are tracked, use **Review tokens** rather than adding the address again. To correct an address, remove it and add the new one — the history follows the address you remove, not the one you add. ## Rate limits and request cost All the default endpoints are free and shared, so they throttle. Per sync, per address, the cost is roughly: | Network | Requests per sync | | - | - | | Bitcoin | 1 + up to 10 history pages | | EVM | 1 summary + up to 10 pages of transfers + up to 10 pages of token transfers | | Solana | \~2 + up to 25 transaction reads | | Polkadot | 1 (balance only) | History is capped by default at 10 pages per source and at 25 transactions for Solana. Wallets with more history than that keep their **current balance correct** — balances come from an address summary, never from history — but their oldest transfers are not imported. Raise both caps with `ONCHAIN_HISTORY_MAX_PAGES` (default 10, maximum 200). The Solana budget scales with it proportionally. **History is best effort; balances are not.** If a source refuses or times out on the paginated history, the balances are still recorded and the history is marked incomplete. When a cap is hit, the affected address says so in **Manage wallets**, and the event is recorded in **Settings → Debug logs**. ### Token cap per address Real addresses are airdrop dumping grounds: a well-known Ethereum address holds close to 8,000 ERC-20 tokens. One read surfaces at most **200 tokens** per address, settable with `ONCHAIN_MAX_TOKENS_PER_ADDRESS` (maximum 5,000). The native coin is never affected, and anything already tracked keeps syncing regardless. On EVM networks the tokens kept are ranked by the market cap the indexer reports, so real assets survive the cap and airdrops fall off the end. ## Limitations **Only tokens the crypto price provider quotes get a value, and it quotes by symbol.** Valuation goes through a `CRYPTO:` ticker, and a symbol is not a token's identity — its contract is. In practice the provider covers major assets and little else: measured on a real Ethereum address, of its ten largest token positions it quoted two. The other eight — including holdings worth roughly $406,000, $141,000 and \$74,000 — showed a value of zero while their quantities were tracked correctly. **A zero next to a token you know is worth something almost always means the provider does not list that token, not that the balance is wrong.** Check the quantity, which is read straight from the chain. Native coins (BTC, ETH, SOL, POL, XDAI) and large-cap tokens are the well-covered case. **DeFi positions are not seen at all.** Staked ETH, liquidity-pool tokens, lending positions, and Solana stake accounts are invisible. A wallet holding most of its value in a staking or lending protocol will report a fraction of it. **Cosmos Hub records balance only, not transfers.** The balance includes spendable, delegated (staked), and unbonding ATOM. Sure’s Cosmos integration reads balance and staking endpoints without importing transfer history. **Bitcoin is one address at a time.** Extended keys (`xpub`, `ypub`, `zpub`) are not supported and are rejected as addresses. Most Bitcoin wallets are HD wallets where one extended key derives thousands of addresses — tracking a single address of such a wallet reports only that address's balance. **Solana token names depend on a token list.** RPC returns mints, not names, so names come from Jupiter's token search — and only for mints it reports as *verified*. Unverified or unknown mints keep a label built from their mint address and are tracked by quantity only. Names are cached for 24 hours per mint. **Polkadot tracks balance only.** Sure’s Polkadot integration reads the current DOT balance and does not import transfer history. The balance is free plus reserved, so staked DOT counts. Token assets on Polkadot Asset Hub (other than DOT itself) are not tracked. **Polkadot addresses use the SS58 format with the Polkadot network prefix.** A valid address starts with `1` and is 47–48 characters long. Extended public keys (derived from a mnemonic) are not supported — enter the public address of the specific account you want to track. **Fees are not itemised.** Network fees are included in the net effect of each transfer rather than recorded separately. **Bridged assets are normalised.** USDC.e, USDbC, USDT0, WETH, and similar 1:1-redeemable forms are tracked as their canonical asset. **NFTs are not tracked.** They are filtered out by token standard. ## Troubleshooting **Every wallet shows a value of zero.** Either no crypto-capable market data provider is enabled, or your family currency is not USD and no exchange rate provider is configured. Both are covered above, and the linking UI says which one applies. **One token shows zero while the others in the same wallet are fine.** The price provider does not quote that token. Pricing is by symbol and covers major assets, so long-tail tokens are tracked by quantity and valued at zero. **A Bitcoin balance is much lower than my wallet app shows.** You are tracking one address of an HD wallet. See "Limitations" above. **Sync says the explorer could not be reached.** The public endpoint is down, throttling you, or too slow to answer. Retry later, or point the relevant `*_URL` override at your own instance. **Solana shows balances but no transfers.** The free endpoint throttles the history methods; balances are kept and the history is marked incomplete. Set `SOLANA_RPC_URL` to your own node or a paid endpoint to get the transfers. **On a self-hosted instance, "Track selected assets" or the Review tokens submit button did nothing.** This happened when the crypto price-provider warning was rendered inside the asset-selection form. The warning's "Enable crypto prices" button is itself a form, and browsers do not allow nested forms — the inner form's closing tag ended the outer form early, leaving the checkboxes and submit button outside any form. The fix moves the warning above the form. If you are on an older build, enable a crypto price provider first under **Settings → Self-Hosting → Market data providers** before using **Track selected assets** or **Review tokens**. **Adding an address fails with "already tracked" even though no account exists for it.** The address has a leftover internal record from a previously deleted account. Adding the address again clears that record automatically. If you are on a self-hosted instance that has not yet received the fix, you can work around it by using **Review tokens** on any existing wallet that still has that address, then unticking all assets; the orphan record is removed when you save. **A token I received is not showing up.** New assets are never imported automatically. Use **Review tokens** and tick it. **A Solana token shows as `SPL:abcd…wxyz`.** The token list does not vouch for that mint, so Sure will not name or price it. Tick it anyway to track the quantity. **Transfers appear with a value of 0 and are excluded from totals.** No price was available for that date yet. Once market data covers the range, the next sync upgrades those entries to trades automatically. If they stay at zero, the date is outside what your market data provider can serve. Note that transfer trades always carry a cash amount of zero by design — the value lives in quantity and price, not in a cash figure. **Manage wallets says the history is incomplete.** The address has more transfers than one sync reads. Balances are unaffected. Raise `ONCHAIN_HISTORY_MAX_PAGES` if you need the full history and can afford the extra requests. **Balances are correct but nothing updates.** Every sync revalues all linked assets at the latest available price, even if the wallet did not move on chain. If the value still does not update, check **Settings → Providers** for the last sync time, and **Settings → Debug logs** filtered to the `onchain_wallet` provider for recorded failures. # Overview Source: https://docs.sure.am/providers/overview Choose the right providers for banking, crypto, and market data Sure supports multiple third-party providers for syncing financial accounts and fetching market data. Each provider has different coverage areas, pricing, and features. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## Market data providers Sure uses market data providers to fetch stock, ETF, and mutual fund prices for your investment accounts. You can enable multiple providers at once and configure them from **Settings > Self-Hosting**. Available providers include Yahoo Finance, Twelve Data, Tiingo, EODHD, Alpha Vantage, MFAPI (Indian mutual funds), and Mansa API (NGX — Nigerian Exchange). See the [market data providers](/providers/market-data) page for setup instructions and details on each provider. ## Choosing a provider ### Global coverage **Lunch Flow** is recommended for users who need worldwide bank coverage. It's a paid service that supports institutions across multiple countries and regions. * **Best for**: Users with accounts in multiple countries * **Pricing**: Paid service * **Documentation**: [Lunch Flow](/providers/lunchflow) ### Wise users **Wise** connects your Wise multi-currency account directly using a personal API token, syncing balances, Jars, and transfers. * **Best for**: Users who hold multiple currencies in a Wise account * **Pricing**: Free (requires a Wise personal API token) * **Documentation**: [Wise](/providers/wise) ### European users **Trade Republic** connects your Trade Republic investment account directly using a secure web login. It syncs your portfolio (stocks, ETFs, bonds, crypto, private market instruments) and cash account (deposits, withdrawals, card payments, interest, dividends). * **Best for**: Trade Republic customers in Europe who want to track their investment and cash accounts * **Pricing**: Free (requires a Trade Republic account) * **Documentation**: [Trade Republic](/providers/trade-republic) **Monobank** connects your Monobank (Ukraine) cards and jars directly using Monobank's personal API, syncing balances and transactions. MCC codes are mapped to your Sure categories on import. * **Best for**: Monobank customers in Ukraine * **Pricing**: Free (requires a Monobank personal token) * **Documentation**: [Monobank](/providers/monobank) **Trading 212** connects your Trading 212 investment portfolio using a read-only API key. It syncs your positions, order history, dividends, and cash transactions. * **Best for**: Trading 212 customers who want to track their investment portfolio and cash movements * **Pricing**: Free (requires a Trading 212 API key) * **Documentation**: [Trading 212](/providers/trading212) **Fio banka** connects your Fio banka (Czechia) account directly using a read-only API token, syncing balances and transaction history. No third-party aggregator is involved. * **Best for**: Fio banka customers in Czechia * **Pricing**: Free (requires a Fio banka API token) * **Documentation**: [Fio banka](/providers/fio) **Enable Banking** is recommended for EU users. It provides free access to European banks through PSD2 open banking standards. * **Best for**: Users with European bank accounts * **Pricing**: Free * **Documentation**: [Enable Banking](/providers/enable-banking) ### United States and Canada users **SnapTrade** (beta) is a strong option for brokerage connectivity in the US and Canada. It is focused on investment and crypto accounts and works well when you want holdings plus brokerage activity from supported brokers. * **Best for**: People who want to sync brokerage and investment accounts through a beta integration * **Pricing**: SnapTrade account required; free tier available with connection limits * **Note**: Focused on investment and crypto accounts, not everyday banking * **Documentation**: [SnapTrade](/providers/snaptrade) **Questrade** (beta) connects Canadian investment accounts directly using a personal API refresh token, syncing holdings, balances, and trading activity. * **Best for**: Questrade customers in Canada who want to sync their investment accounts * **Pricing**: Free (requires a Questrade account with IQ API access) * **Documentation**: [Questrade](/providers/questrade) **Sophtron** (alpha) connects bank, credit card, investment, loan, and other financial accounts in the US and Canada. It supports a wide range of institution types through Sophtron's aggregation API. * **Best for**: US and Canadian users who want broad institution coverage * **Pricing**: Check [sophtron.com](https://www.sophtron.com/) for details * **Note**: Currently in alpha * **Documentation**: [Sophtron](/providers/sophtron) **SimpleFIN** is a cost-effective option for US users. It offers a simpler, more affordable alternative to Plaid. * **Best for**: US users looking for a budget-friendly option * **Pricing**: Paid (cheaper than alternatives) * **Documentation**: [SimpleFIN](/providers/simplefin) **Plaid** is another US-focused option, but requires more technical setup and may violate their terms of service for personal use. * **Best for**: Technical users comfortable with complex setup * **Pricing**: Pay-as-you-go * **Note**: Using Plaid for personal use might be against their TOS * **Documentation**: [Plaid](/providers/plaid) ### New Zealand users **Akahu** (beta) connects New Zealand bank and investment accounts through the Akahu open banking platform using a personal app token and user token. * **Best for**: Users with New Zealand bank accounts * **Pricing**: Requires an Akahu account * **Documentation**: [Akahu](/providers/akahu) ### Australian users **Up bank** syncs Australian Up bank accounts with a personal access token. Sure maps Up's category slugs to your existing Sure categories automatically on import, so transactions arrive pre-categorised. * **Best for**: Up bank customers in Australia * **Pricing**: Free (requires an Up personal access token) * **Documentation**: [Up bank](/providers/up-bank) **Redbark** connects Australian bank accounts through the Consumer Data Right (CDR) open banking framework, with read-only consented access. * **Best for**: Users with Australian bank accounts * **Pricing**: Paid service (API access requires a Redbark Developer or Professional plan) * **Documentation**: [Redbark](/providers/redbark) ## Account visibility for family members Provider connection cards on the accounts page show each family member only accounts they own or that have been shared with them. If an admin connects a provider with multiple accounts and shares only some of them with a member, that member's card lists only their accessible accounts. Admins see all accounts on every connection regardless of sharing. When a member can see only some accounts on a connection, the sync summary for that card shows counts rather than account names and per-account details. This prevents account names and balances from other members from being revealed through the sync panel. This scoping applies to all providers, including SimpleFIN, Sophtron, SnapTrade, Plaid, Enable Banking, Binance, Kraken, CoinSpot, Trade Republic, Trading 212, and all others. See [Family Sharing](/guides/app-features/family-sharing) for more on how account sharing works. ## Categorization providers Sure categorizes transactions using your configured LLM provider by default. Self-hosted instances with preview features enabled can optionally switch to Jev. **Jev (TypeSafe)** is a classification provider that answers typed questions about a transaction with calibrated confidence scores rather than generating text. It is a good fit when you want fine-grained control over how certain a model must be before a category is applied. * **Best for**: Self-hosted instances that want a dedicated classification model with confidence-based gating * **Pricing**: Per-transaction (TypeSafe billing) * **Documentation**: [Jev (TypeSafe)](/providers/jev) ## Cryptocurrency providers ### On-chain wallets (self-custody) **On-chain wallets** lets you track Bitcoin, EVM networks (Ethereum, Base, Arbitrum, Optimism, Polygon, Gnosis), and Solana wallets directly from their public addresses — no API key, no third-party account required. * **Best for**: Tracking self-custody wallets across Bitcoin, Ethereum, and Solana without sharing private keys * **Pricing**: Free (uses public blockchain explorers by default) * **Documentation**: [On-chain wallets](/providers/onchain-wallets) ### Binance **Binance** integration connects directly to your Binance account to sync spot, margin, and earn balances along with trading history. * **Best for**: Binance users who want to track crypto holdings and trades through direct exchange integration * **Pricing**: Free (requires Binance API credentials) * **Documentation**: [Binance](/providers/binance) ### Coinbase **Coinbase** integration connects directly to your Coinbase account using the Coinbase Developer Platform (CDP) API to sync cryptocurrency and fiat holdings. * **Best for**: Coinbase users who want direct integration with their exchange account * **Pricing**: Free (requires Coinbase API credentials) * **Documentation**: [Coinbase](/providers/coinbase) ### CoinSpot **CoinSpot** connects directly to your CoinSpot account using a read-only API key. It imports your crypto holdings, completed order history, on-chain send and receive transactions, and AUD deposits and withdrawals. * **Best for**: CoinSpot customers in Australia who want to track their crypto exchange account * **Pricing**: Free (requires a CoinSpot read-only API key) * **Documentation**: [CoinSpot](/providers/coinspot) ### CoinStats **CoinStats** allows you to sync cryptocurrency wallets, DeFi positions, and centralized exchange accounts from multiple blockchain networks. * **Best for**: Tracking crypto holdings across wallets, DeFi protocols, and exchanges * **Pricing**: Free (requires CoinStats API key) * **Documentation**: [CoinStats](/providers/coinstats) # Plaid Source: https://docs.sure.am/providers/plaid Connect US bank accounts with advanced technical setup > [!WARNING] > > Using Plaid for personal use might be against their terms of service. This integration is intended for technically savvy users who understand the implications and requirements. > [!WARNING] > > Plaid integration currently only works for Western users. Plaid Production support is not available to European users. > [!NOTE] > > For Plaid integration, your Sure instance needs to be accessible from the internet behind a domain with working SSL. See additional context in [maybe-finance/maybe#2419](https://github.com/maybe-finance/maybe/pull/2419). Plaid is a US-focused banking provider that offers comprehensive account connectivity. However, it requires significant technical setup and may not be suitable for personal use according to their terms of service. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## Prerequisites Before setting up Plaid: * Your Sure instance must be publicly accessible via HTTPS * You need a valid domain with working SSL certificate * You must be comfortable with technical configuration * You should review Plaid's terms of service for personal use ## Creating a Plaid account 1. Go to [dashboard.plaid.com](https://dashboard.plaid.com) and register for a new account 2. Complete the registration process 3. Request production access based on your bank type (see below) ## Requesting production access The process differs depending on whether your bank requires OAuth authentication. ### For banks without OAuth 1. On the Home page, find "Learn how to build with Plaid" and click **Unlock real data** 2. Enter your real name and phone number 3. In the description box, write: > This is for personal use only on a self-hosted version of the Sure Finance software. I am only using it to manage my finances, sync my bank accounts, track my spending, and create a budget. 4. Leave "Additional products" **unchecked** 5. Click **Request Access** 6. Wait for approval (may take more than 24 hours) ### For banks with OAuth > [!NOTE] > > Per Plaid Support as of July 2025, certain banks have extended OAuth approval timelines: > > * **Chase Bank**: 3-4 months > * **Schwab**: Up to 2 months 1. In the left sidebar, click **Get production access** 2. Enter your real address 3. For business profile, write: > This is for personal use only on a self-hosted version of the Sure Finance software. I am only using it to manage my finances, sync my bank accounts, track my spending, and create a budget. 4. Leave company website **blank** 5. Enter your real name, phone number, email, and date of birth 6. Click **Next** 7. Indicate: * 0 employees * Your country of data access * You do not sell data * No security breach in past 12 months 8. Click **Next** 9. Select industry: **Budgeting and financial management tools** 10. Click **Next** 11. Enter any name for your application 12. Upload a logo (1024x1024px, under 4MB) 13. Leave brand color as **#22CCEE** 14. Set Website URL to: `https://github.com/we-promise/sure` 15. In "Reason for data access", enter: > This is for personal use only on a self-hosted version of the Sure Finance software. I am only using it to manage my finances, sync my bank accounts, track my spending, and create a budget. 16. Enter your real email as support email 17. Click **Next** 18. Enter your country for "Where do you want to launch?" 19. For products: * **Payments**: Check only **Auth** and **Balance** * **Credit Underwriting**: Leave all unchecked * **Fraud & Compliance**: Leave all unchecked * **Financial Management**: Check **all products** 20. Click **Next** 21. For use cases: * **Payments**: Select **Consumer bill pay** * **Financial Management**: Select **Personal budgeting and financial advice** for all products 22. Click **Next** 23. Select **Pay As You Go** plan 24. Click **Next** 25. Enter billing details and check agreement boxes 26. Click **Next** 27. Click **Start Security Practices Questionnaire** 28. For each question: * Select **Other - please see comments** * Write in notes: > This is for personal use only on a self-hosted version of the Sure Finance software. I am only using it to manage my finances, sync my bank accounts, track my spending, and create a budget. 29. Continue through all sections, repeating step 28 30. Click **Submit** 31. Wait for approval (may take more than 24 hours) ## Configuring Sure After your Plaid account is approved: 1. Go to [dashboard.plaid.com/developers/api](https://dashboard.plaid.com/developers/api) or click **Developers > API** 2. Click **Configure** next to Allowed redirect URIs 3. Click **Add new URI** 4. Enter your domain with `/accounts` appended (e.g., `https://budget.yourdomain.com/accounts`) 5. Click **Save changes** 6. Go to [dashboard.plaid.com/developers/keys](https://dashboard.plaid.com/developers/keys) or click **Developers > Keys** 7. Copy your `client_id` and Production `secret` key ### Complete Plaid Link customization After production access is approved, finish the Plaid Link configuration before testing bank connections: 1. In the Plaid Dashboard, go to **Link > Link Customization** 2. Add **Track and manage your finances** as a use case 3. Publish the changes If this step is missing, Plaid may let you select and validate a bank but then show an empty Link popup afterward. This can look like a Sure application issue, but it usually means Plaid still has a configuration or validation step left to complete. ### Docker Compose configuration In your `docker-compose.yml` file, add these environment variables: ```yaml theme={null} PLAID_CLIENT_ID: ${PLAID_CLIENT_ID} PLAID_SECRET: ${PLAID_SECRET} PLAID_ENV: ${PLAID_ENV} ``` ### Environment variables In your `.env` file, add: ```bash theme={null} PLAID_CLIENT_ID=ENTER_CLIENT_ID_FROM_PLAID_HERE PLAID_SECRET=ENTER_SECRET_KEY_FROM_PLAID_HERE PLAID_ENV=production # Use 'production' for Full/Limited Production Access, or 'sandbox' for Sandbox Access ``` ### Restart Sure After updating your configuration, restart your Sure instance. You should now see the **Link account** option in the Sure UI. ## Member-owned connections By default, only family admins can connect and manage provider integrations. Plaid is an exception: because a Plaid Link session authenticates only the person completing the flow, a family member can safely connect their own bank without exposing any other member's credentials. ### Who can connect Plaid | Role | Can connect Plaid | Can manage their own connection | Can manage all connections | | - | - | - | - | | Admin | Yes | Yes | Yes | | Member | Yes | Yes (connections they created) | No | | Guest | No | No | No | A member who connects a bank can re-authenticate it, sync it, and delete it. They cannot edit or delete connections created by other members or by an admin. An admin always has full visibility and management over every Plaid connection in the family, regardless of who created it. ### What members see on a shared connection When a member owns a Plaid connection, the connection card shows only the accounts they have access to. Accounts that were shared and later had sharing revoked are no longer shown on that member's card, even if they remain on the underlying connection. Admins see all accounts on every connection. ### Moving between families When a member accepts an invitation to join a different family, their Plaid connections move with them if all of the accounts on that connection belong to the member. Connections that include accounts belonging to other family members stay behind, with ownership released and the connection reverting to admin-managed. If a member is demoted to guest, they lose the ability to manage their Plaid connections. The connections are not deleted, but only an admin can manage them until the member's role is restored. ## Duplicate institution warning When you complete a Plaid Link flow for an institution you already have connected, Sure detects the overlap before creating a second connection and shows a warning dialog. This prevents duplicate connections, which consume a Plaid Item slot that cannot be recovered on the Trial plan even if the duplicate is later removed. Sure compares the accounts Link reported with your existing connections by account name and last-four mask, then offers different actions depending on what it finds. ### All accounts already connected If every account in the new Link session matches an existing connection, Sure shows a "Close" button only. Adding the connection would only duplicate accounts already in your family. The dialog points you to alternatives where applicable: * For a US connection you can manage and own (or a legacy connection with no owner), use **Add accounts** to add more accounts without creating a second connection. Plaid does not support this account-selection flow for UK/EU institutions. * Go through Link again with a different bank login if you intended to connect a different account at the same institution. ### Some accounts are new If the new session includes both connected and new accounts, Sure offers an update action for eligible US connections you can manage and own (or legacy connections with no owner). Updating adds the new accounts through the existing connection. If the overlap is only with other members' connections, the dialog leads with **Confirm this connection** instead. A **Confirm this connection** option is also available for cases where the overlap is explained by a different login sharing an account (such as a joint account). ### No accounts match If none of the reported accounts match an existing connection, Sure treats this as a different login and leads with **Confirm this connection**. You can still close without adding if you changed your mind. ### Nothing to compare When Sure cannot reliably compare accounts — for example, when an account has no last-four mask — it leads with Close. Confirm remains available; update actions appear only for eligible US connections you can manage and own, or legacy connections with no owner. ### Expired token The held public token expires after 30 minutes. If you leave the warning dialog open past that point and then try to confirm, Sure redirects to Accounts with an alert asking you to go through Link again. ### Admin and member behavior Admins can see the family's connections in the warning. When every reported account is already connected only through other members, the warning names whose connection holds the accounts and offers Close rather than confirmation. If some accounts are new, confirmation remains available. Matches narrow the listed connections to those holding matching accounts; when there are no matches or comparison is unavailable, the dialog lists the institution's existing connections. Members see only their own connections in the warning. *** ## Managing accounts ### Adding accounts to an existing connection If you have an existing US Plaid connection and want to add more accounts from the same institution, you do not need to create a new connection. 1. Go to **Settings > Providers** and find your Plaid connection 2. Click **Add accounts** next to the connection 3. The Plaid Link flow opens with account selection enabled 4. Select the additional accounts you want to add 5. Complete the flow — Sure will sync the new accounts automatically The **Add accounts** button is only available for US Plaid connections. ### Linking an unlinked Plaid account to an existing Sure account If you have a Plaid account that is not yet linked to any Sure account, you can connect it to an existing account rather than creating a new one. 1. Go to **Settings > Providers** and find the account you want to link 2. Open the account menu and choose the option to link to a Plaid account 3. A dialog lists all unlinked Plaid accounts available in your family 4. Select the Plaid account and click **Link account** If no accounts appear in the list, all of your Plaid accounts are already linked. Connect a new Plaid account first. ## How Sure selects Plaid products When you initiate a Plaid Link flow, Sure requests a specific set of Plaid products based on the type of account you are linking. Plaid filters out any institution that does not support every product in the requested set, so the product selection directly controls which institutions appear in the Link UI. | Account type | Primary product | Additional consented products | | - | - | - | | Investment | `investments` | `transactions` | | Credit card / Loan | `liabilities` | `transactions`, `investments` | | Depository (and others) | `transactions` | `investments` | Because `liabilities` is only requested when linking a liability account (credit card or loan), investment-only institutions such as E\*TRADE that do not offer Plaid's liabilities product are now visible when you link an investment account. Previously, requesting `liabilities` for every account type caused those institutions to be silently hidden in the Link flow. Sure fetches liability details (minimum payment, next payment due date, APR) for all Plaid accounts with type `credit`, regardless of subtype. This covers both standard credit cards (`credit/credit card`) and PayPal Credit accounts (`credit/paypal`). For loan accounts, liabilities are fetched only for `mortgage` and `student` subtypes. Plaid reports an item's products across three lists: `available_products`, `billed_products`, and `consented_products`. Sure treats all three as supported. Products granted through `additional_consented_products` during the Link flow appear in `consented_products` until they are first billed — if Sure only checked the first two lists, those products would appear unsupported and their data would not be fetched. ## Transaction names Plaid returns both a cleaned merchant name and the bank's original description. Sure combines them into a single transaction name — for example, `Target - TARGET 00023 SAN MATEO CA` — so distinct transactions from the same merchant stay distinguishable. If Plaid resolves no merchant, the bank's description is used on its own. Merchant records, logos, and reports are still built from the merchant name alone, so grouping and reporting are unaffected by the combined display name. ### Rules and combined names Rules using **contains** (`like`) automatically reach both parts of the combined name, so a rule matching "Target" still catches all Target transactions. Rules using **is** (`=`) or **is not** (`!=`) continue to match on the merchant name alone, so an existing `= "Target"` rule keeps working without any changes. This applies only to Plaid transactions — manually entered transactions are not affected. ## Transaction details The transaction detail drawer shows Plaid-specific metadata under **Additional details** when Plaid reports it. This can include: * **Original description** — the bank's own description before Plaid cleaned it * **Payment channel** — how the transaction was made (in-store, online, etc.) * **Transaction code** — Plaid's payment type code * **Payment meta** — reference numbers and other payment metadata * **Counterparties** — merchant or financial institution details These fields are updated on every sync to reflect what Plaid currently reports. ## Features * **US bank coverage**: Comprehensive support for US financial institutions * **Real-time data**: Access to account balances and transactions * **OAuth support**: Secure authentication for supported banks * **Multiple accounts**: Connect accounts from different institutions * **Investment-only institutions**: Brokerages that do not offer liabilities (such as E\*TRADE) can be linked as investment accounts * **Full credit liability support**: Liability data (minimum payment, due date, APR) is fetched for all Plaid `credit` account types, including PayPal Credit (`credit/paypal`) in addition to standard credit cards (`credit/credit card`) ## Pricing Plaid uses a pay-as-you-go pricing model. Check [plaid.com/pricing](https://plaid.com/pricing/) for current rates. ## Limitations * **US-focused**: Primarily supports US institutions, not available for European users * **Complex setup**: Requires significant technical configuration * **TOS concerns**: Personal use may violate Plaid's terms of service * **Public accessibility**: Requires publicly accessible HTTPS endpoint * **Long approval times**: OAuth-enabled banks can take months to approve * **Technical expertise**: Not recommended for non-technical users ## Alternatives Consider these alternatives to Plaid: * **SimpleFIN**: Simpler setup, more affordable, US-focused * **Enable Banking**: Free, EU-focused, easier setup * **Lunch Flow**: Global coverage, paid service ## Transaction refresh behavior Sure requests a fresh transaction pull from Plaid before reading new data in several situations, not only during manual syncs. The refresh is asynchronous: Sure sends a refresh request to Plaid, then polls for an updated transaction cursor, then triggers a follow-up sync once the cursor advances. ### When automatic refreshes run A transaction refresh is requested automatically in the following cases: * **Scheduled sync** — the nightly background job that syncs all families * **Provider-wide sync** — triggered when you sync all accounts from Settings or the accounts page * **Login sync** — when auto-sync on login is enabled and Sure detects a family has not synced today In all three cases, Sure fires the refresh request alongside the normal sync. Because Plaid processes the refresh asynchronously, the baseline sync may run first with existing data. A follow-up sync is queued automatically once Plaid finishes refreshing and the cursor advances, so the latest transactions are imported even if the first sync completes before Plaid is ready. ### Manual sync behavior Manual syncs also request a transaction refresh before fetching data. After sending the refresh request, Sure polls Plaid for the updated cursor and syncs once new data arrives. If no new transactions appear within the polling window (roughly 3 minutes), Sure falls back to a normal sync with whatever data Plaid currently has. ### Coalescing and the cache store requirement To prevent duplicate refresh requests, Sure uses a shared cache to coalesce calls: if a refresh has already been requested for a given Plaid item within the last 5 minutes, subsequent requests are dropped and the in-progress refresh continues normally. The coalescing logic requires a shared cache store. Sure skips the Plaid refresh request (and logs a warning) if the cache store is the default file-based or in-memory store. To enable refresh on a self-hosted instance, configure one of the following: * **Redis** — set `REDIS_URL` to a Redis connection string * **Memcache** — configure `MEMCACHE_SERVERS` * **SolidCache** — enabled by default in the Docker Compose setup Without a shared cache, syncs still work but do not trigger a fresh pull from Plaid before fetching transactions. ## Reconnect status When Plaid requires you to re-authenticate (for example, after a password change), Sure marks the connection with a "requires update" warning. Clicking the **Update** button in **Settings > Providers** opens the Plaid Link re-authentication flow. After you complete re-authentication, the warning is not cleared immediately. Sure clears the "requires update" status only after the next full import succeeds. This means the warning may persist briefly after you reconnect — it disappears once the subsequent sync completes without a login error. If the login issue is still present, the status remains until authentication succeeds and a full import runs cleanly. ## Troubleshooting If you run into Plaid errors that are not visible in Sure, check the Plaid Dashboard logs under **Developers > Logs**. These logs can show whether the issue is coming from Plaid Link configuration, product approval, institution support, or another Plaid-side validation error. ### Investment account shows unexpected cash balance after a sync If a Plaid investment account shows a cash balance that grows or fluctuates each day even though you have not made any cash changes, one possible cause is a balance snapshot anchored on a different date from its holdings. Plaid can report an institution price date for each holding, which may be from an earlier trading session. When that total was anchored on today's date instead, repricing the holdings for today left a gap that appeared as phantom cash. Sure now anchors the balance snapshot on the newest valid holding price date that is not in the future. Future dates are discarded individually; if no eligible date remains, Sure uses today. This reduces date-mismatch artifacts without assuming every holding has the same price date. Trigger a manual sync from the account page to pick up the corrected snapshot. ### Credit card or loan shows no transactions after linking If you linked a credit card or loan account through Plaid and Sure imported balances and liabilities but no transactions, the connection was affected by a bug that is now fixed. Plaid places the `transactions` product in `consented_products` for liability accounts until the first billing call — Sure previously only checked `available_products` and `billed_products`, so `transactions` appeared unsupported and the fetch was skipped. To resolve this, trigger a manual sync from the account page. Sure will now recognize `transactions` as a supported product and import your transaction history. ### Retracted transactions not removed When Plaid removes a transaction (for example, a pending transaction that never settled, or a duplicate Plaid later corrects), Sure deletes the matching entry from your account during the next sync. Entries imported before the `ProviderImportAdapter` was introduced were stored with a `plaid_id` field, and Sure used that field to find and delete retracted transactions. Entries imported after the adapter was introduced are stored with an `external_id` and a source identifier instead, leaving `plaid_id` empty. Because of this, retractions that targeted the newer entries were never matched and the transactions stayed in the account. This is now fixed. Sure looks up retracted transactions by `external_id` and source first, then falls back to `plaid_id` for older entries that predate the adapter. If you have transactions that should have been removed by a Plaid retraction, trigger a manual sync from the account page — Sure will process any pending removals during that sync. ### Investment holdings not showing for accounts with no investment transactions If a Plaid investment account has holdings but you have never made any trades or investment transactions through that institution, the holdings may not have appeared even though the sync completed without errors. The account-scoped investments data previously only passed securities to the holdings processor when the account had both holdings and investment transactions. Accounts with holdings but no transaction history had their securities list dropped, so each holding could not resolve its security and was silently skipped. This is fixed in builds containing [Sure PR #4256](https://github.com/we-promise/sure/pull/4256): securities are included whenever the account has either holdings or investment transactions. As of October 21, 2026, the fix is on `main` but is not in the latest stable release, `v0.7.5-hotfix.2`. After upgrading to a build containing the fix, trigger a manual sync from the account page to import the missing holdings. ### Investment holdings not syncing with encryption enabled If your Sure instance has Active Record encryption configured and Plaid investment account syncs are failing with a `NoMethodError`, you were affected by a bug that is now fixed. The `raw_holdings_payload` column was previously named `raw_investments_payload`. An invalid `previous:` fallback option on the encryption declaration caused `ActiveRecord::Encryption::Context#attribute=` to raise `NoMethodError` when Sure tried to decrypt holdings data using the previous scheme. The column rename preserves the stored ciphertext, and Active Record Encryption does not bind ciphertext to the attribute name, so no fallback scheme was needed. Update to the latest Sure version and trigger a manual sync from the account page. Holdings will decrypt and sync correctly after the update. ### Link modal closes with no error message If the Plaid Link modal closes immediately when you try to open it — before any bank selection screen appears — and Sure shows no error message, a link-token creation error may be the cause. This can happen when your Plaid credentials are misconfigured, a required product is not enabled for your account, or your institution is not available in your region. Sure now shows the error as a page-level alert instead of silently closing the modal. If you see a message such as "Your account is not enabled for the following products" or a similar Plaid configuration error, follow the instructions in that message to resolve the issue in your [Plaid Dashboard](https://dashboard.plaid.com). If the alert is a generic connection error with no specific guidance, verify that your `PLAID_CLIENT_ID`, `PLAID_SECRET`, and `PLAID_ENV` values are correct and that your Sure instance is reachable over HTTPS. Check **Developers > Logs** in the Plaid Dashboard for more detail on what failed. ### Link popup closes after selecting a bank If the Plaid popup closes immediately after you select a bank, and Sure shows no useful app logs, the problem may be on Plaid's side rather than in your Sure configuration. Things to verify first: * Your instance is publicly reachable over HTTPS * Your allowed redirect URI is set correctly in Plaid, for example `https://budget.yourdomain.com/accounts` * `PLAID_ENV=production` when using Limited or Full Production access * Your `PLAID_CLIENT_ID` and `PLAID_SECRET` are the Production credentials, not Sandbox keys If all of that looks correct and the flow still closes with no obvious error, Plaid may need to review or reprocess your onboarding / client registration. This has happened in the wild with Sure. In one confirmed Chase case, the integration started working without app changes after Plaid support escalated the issue to their Chase team and reprocessed the user's client registration. When contacting Plaid support, include: * Your Plaid environment and access tier (for example, Limited Production) * The institution you are trying to connect (especially if it is Chase or another OAuth-heavy institution) * Confirmation that /link/token/create succeeds (can be verified in the Activity section of your Plaid Dashboard) * Confirmation that your redirect URI is configured correctly * A note that the Link popup closes without completing the connection * A request for them to verify or reprocess your client registration / onboarding ## Support For Plaid-specific issues, consult the [Plaid documentation](https://plaid.com/docs/) or contact Plaid support. # Property valuations Source: https://docs.sure.am/providers/property-valuations Automatically look up and refresh property values using RentCast, Realie, or Chimnie Sure can look up a property's estimated market value when you add a property account and refresh that estimate automatically on a recurring schedule. Three providers are supported: **RentCast** and **Realie** for US properties, and **Chimnie** for UK residential properties. ## How it works When you add a new property account using a valuation provider: 1. You enter the property name and address 2. Sure sends the address (or UPRN for Chimnie) to the provider 3. The provider returns the property record and an estimated value 4. You review the result before anything is created 5. Confirming creates the property account with the estimated value as the opening balance After setup, Sure queues automatic valuation refreshes on the first of each month. Each property keeps its selected provider. RentCast and Realie also require at least a day between automatic refreshes; Chimnie requires a month. Properties are processed stalest-first, subject to provider configuration, address and currency checks, and the remaining monthly request budget. ## Enabling a provider Add the API key for the provider you want to use. You can do this in two ways: * **Settings UI** — go to **Settings → Self-Hosting** and enter the key in the provider's field * **Environment variable** — set `RENTCAST_API_KEY`, `REALIE_API_KEY`, or `CHIMNIE_API_KEY` in your environment Once a key is present, the provider appears as an option when you add a new property account. ## Providers ### RentCast [RentCast](https://rentcast.io) is a US property data API. The free tier allows 50 requests per month. | Setting | Value | | - | - | | Free tier cap | 50 requests/month | | Coverage | United States | | Valuation currency | USD | | Minimum automatic refresh interval | One day (the default job runs monthly) | | API key variable | `RENTCAST_API_KEY` | | Monthly cap override | `RENTCAST_MAX_REQUESTS_PER_MONTH` | ### Realie [Realie](https://realie.ai) is a US property data and AVM API. The free tier allows 25 requests per month. | Setting | Value | | - | - | | Free tier cap | 25 requests/month | | Coverage | United States | | Valuation currency | USD | | Minimum automatic refresh interval | One day (the default job runs monthly) | | API key variable | `REALIE_API_KEY` | | Monthly cap override | `REALIE_MAX_REQUESTS_PER_MONTH` | #### Realie API versions (v2 and v3) Realie introduced a v3 response shape on 2026-08-19. The response shape is an account-level setting that all API keys on the account inherit: * **v2 flat record** — the original shape, still active for accounts created before the v3 release unless you opt in. * **v3 nested parcel record** — the default for accounts created after 2026-08-19. Older accounts can switch to v3 from the Realie dashboard. The switch is one-way. Sure handles both shapes automatically. No configuration change is needed when your Realie account is on v3 or when you opt in later. ### Chimnie [Chimnie](https://chimnie.com) is a UK property valuation API. UPRN-based valuations are free and include an estimated value, value range, and confidence level. Sure caps requests at 1,000 per month by default. > [!NOTE] > > Create an account and API key at [dashboard.chimnie.com](https://dashboard.chimnie.com). Check Chimnie’s current sign-up requirements if registration is rejected. | Setting | Value | | - | - | | Default cap | 1,000 requests/month | | Coverage | United Kingdom (residential properties) | | Valuation currency | GBP | | Minimum automatic refresh interval | One month | | API key variable | `CHIMNIE_API_KEY` | | Monthly cap override | `CHIMNIE_MAX_REQUESTS_PER_MONTH` | Chimnie looks up properties by their **UPRN** (Unique Property Reference Number), not by address. You need the UPRN when adding a property through Chimnie. **Finding your UPRN**: every UK address has a UPRN of up to 12 digits. You can find it at [findmyaddress.co.uk](https://www.findmyaddress.co.uk) (GeoPlace) or by asking your local council. Chimnie includes attribution in the property preview: valuation data from Chimnie contains OS data © Crown copyright and database right, Royal Mail data © Royal Mail copyright and database right, and HM Land Registry data © Crown copyright and database right, licensed under the Open Government Licence v3.0. ## Monthly request budget Each provider tracks requests in a durable database counter that resets at the start of each calendar month. This counter covers both user-initiated lookups (adding a property) and automatic refreshes. The refresh job checks the counter before spending a request and stops when the budget is exhausted. For Chimnie, Sure retries HTTP 429 responses with exponential backoff, for up to three retries. Each provider instance spaces requests at least 1.1 seconds apart. Every attempt counts against the monthly cap, and requests stop when that cap is reached. The free tier caps are conservative. If you have a paid plan with a higher limit, set the override variable to match: ```txt theme={null} # Example: raise the RentCast cap to 500 for a paid plan RENTCAST_MAX_REQUESTS_PER_MONTH=500 # Example: raise the Realie cap to 200 for a paid plan REALIE_MAX_REQUESTS_PER_MONTH=200 # Example: raise the Chimnie cap above the default 1,000 CHIMNIE_MAX_REQUESTS_PER_MONTH=2000 ``` ## Linking a valuation provider to an existing property If you added a property manually (without using a valuation provider at creation time), you can link a provider later from the property's Overview tab. A property is eligible to link when all of these are true: * No provider is already linked * The property has a complete address in the provider’s supported country. For RentCast and Realie, provide a US street address, city, state, ZIP code, and country * The property's account currency matches the provider's valuation currency (USD for RentCast and Realie; GBP for Chimnie) * The provider does not require an external identifier (Chimnie requires a UPRN, so it can only be linked at creation time, not after) * The provider's API key is configured When you click the link button, Sure runs the first valuation immediately. The link is kept only if that valuation succeeds. If the address is not found or the monthly budget is exhausted, the link is reverted and the property stays unlinked so you can try a different provider. To link a provider: 1. Open the property account and go to the **Overview** tab 2. If the property is eligible, an **Update value automatically with \[provider name]** button appears for each configured, eligible provider. You need write access to link it 3. Click the button for the provider you want to use 4. Sure runs the first valuation and confirms whether the link succeeded After linking, the Overview tab shows the last valuation date and a **Refresh valuation** button. The property is included in future automatic monthly refreshes. ## Adding a property using a valuation provider ### US properties (RentCast or Realie) 1. Go to **Accounts → Add Account → Property** 2. Select **Add via RentCast** or **Add via Realie** (these options appear only when the provider's API key is configured) 3. Enter the property name and its full US address 4. Click **Look up property** 5. Review what the provider found — the property type, estimated value, and other details are shown before anything is saved. If the address matched an area estimate rather than a specific record, a notice says so 6. Click **Add property** to confirm, or **Back** to correct the address ### UK properties (Chimnie) 1. Go to **Accounts → Add Account → Property** 2. Select **Add via Chimnie** (this option appears only when the `CHIMNIE_API_KEY` is configured) 3. Enter the property name, its UK address (address line 1 and postcode are required; county is optional), and its UPRN 4. Click **Look up property** 5. Review what Chimnie found — the estimated value, value range, and confidence level are shown before anything is saved 6. Click **Add property** to confirm, or **Back** to correct the details Nothing is created until you confirm. If the lookup fails (UPRN not found, rate limit reached, provider error), an error message explains the reason. ## Automatic refresh The default background job runs monthly, on the first day of the month at 01:30 in the scheduler’s configured timezone. It considers active property accounts with a linked valuation provider. A provider’s minimum interval also applies: one day for RentCast and Realie, and one month for Chimnie. Properties are processed in order of their last refresh date, oldest first. A property is skipped if: * It was already refreshed within the provider's refresh interval * Its address fields required by the provider are missing * The provider only supports a specific country and the property's address does not match * Its currency does not match the provider's valuation currency * The provider's monthly request budget is exhausted * The provider's API key has been removed since the property was added Address, provider-configuration, and currency failures are recorded in **Settings → Debug logs** under the provider key. Routine interval and exhausted-budget skips may not create a log entry. A **Refresh valuation** button on the property account bypasses the normal interval and queues a fresh valuation, still subject to the provider budget and validation checks. The button is disabled if the provider is no longer configured. ## Troubleshooting **The valuation option is not showing when I add a property**: the provider's API key is not configured. Add the relevant key (`RENTCAST_API_KEY`, `REALIE_API_KEY`, or `CHIMNIE_API_KEY`) to your environment, or enter it in **Settings → Self-Hosting**. **Chimnie sign-up was rejected**: check Chimnie’s current registration requirements or contact its support team. **The UPRN lookup returned no result**: the UPRN may be for a non-residential property, a newly built property not yet in Chimnie's database, or an invalid number. Double-check the UPRN on [findmyaddress.co.uk](https://www.findmyaddress.co.uk). **The provider returned an area estimate instead of a property record**: the address was not matched to a specific record. The confirmation screen says so explicitly. Review the address for typos before confirming — if the address is correct but the provider has no record for it, you can still add the property and manage its value manually. **The value stopped updating**: the provider's monthly budget is likely exhausted. Check **Settings → Debug logs** filtered to the provider key, or check your provider dashboard. The budget resets at the start of the next calendar month, or you can raise the cap with the override variable if you are on a paid plan. **The property account's currency does not match the provider**: RentCast and Realie return values in USD; Chimnie returns values in GBP. If your property account was created or later changed to a different currency, the refresh job skips it to avoid writing the wrong currency. Change the account currency to match or manage the value manually. **No link button appears on the Overview tab for an existing property**: check that the provider's API key is configured, the address includes every required field and a supported country, and the account currency matches the provider’s valuation currency. Chimnie cannot be linked after creation because it requires a UPRN that can only be supplied when the property is first added. **The link failed with an alert**: the first valuation did not succeed, so the link was not saved. The address may not be in the provider's database or the monthly budget may be exhausted. Correct the address or wait for the budget to reset, then try again. # Questrade Source: https://docs.sure.am/providers/questrade Connect your Questrade investment accounts to Sure Questrade is a Canadian online brokerage. Sure connects to it directly using a personal API refresh token, syncing your investment account balances, holdings, and trading activity. > [!NOTE] > > Questrade support is in beta. Functionality is working but may have rough edges. Report issues in the [Discord](https://discord.gg/36ZGBsxYEK). See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works 1. Generate a personal API refresh token from the Questrade desktop portal 2. Paste the token into Sure 3. Sure discovers your Questrade accounts and begins syncing balances, holdings, and activities 4. Choose how each discovered account should appear in Sure ## Prerequisites * A [Questrade](https://my.questrade.com) account with IQ API access enabled * A personal API refresh token generated from the Questrade portal (desktop only — the mobile app does not have API settings) ## Setting up Questrade ### Get your refresh token The Questrade IQ API settings are only available on a desktop browser. 1. Sign in to the [Questrade portal](https://my.questrade.com) on a desktop browser 2. Open **Settings** and find **General settings**, then edit **IQ API settings** 3. In the API access modal, click **Manage** under **My applications** 4. Register a personal app with a name and description, then save 5. Add a new device and generate a token 6. Copy the generated refresh token ### Connect Questrade in Sure 1. In Sure, go to **Settings > Bank sync** 2. Find the **Questrade** panel and paste your refresh token 3. Click **Save** — Sure initiates a first sync to discover your accounts 4. Go to the **Accounts** tab and run account setup to choose how each Questrade account should appear ### Set up discovered accounts After the first sync, choose how each Questrade account maps to a Sure account type: * **Investment** (brokerage, RRSP, TFSA, RESP, and other registered accounts) * **Loan** (margin accounts) * **Skip** accounts you do not want to track You can also choose how far back to sync transaction history during initial setup. ## Token refresh Questrade refresh tokens renew automatically each time your accounts sync. If a connection sits unused for more than 7 days, the token may go stale. Paste a new refresh token into the Questrade panel in **Settings > Bank sync** to reconnect without losing your linked accounts. ## Supported data * Account balances * Holdings (positions and quantities) * Trade activities (buys, sells, dividends, and other transactions) ## Troubleshooting **Connection shows "requires update"**: The refresh token has expired or been revoked. Generate a new token from the Questrade portal and paste it into **Settings > Bank sync > Questrade**. **Accounts not appearing after setup**: Trigger a manual sync from the Questrade provider panel. If accounts still do not appear, confirm that your token is valid and that the accounts are visible in the Questrade portal. **Activities missing**: Make sure you selected a sufficient history range during account setup. You can adjust the sync start date per account if needed. For Questrade API documentation, see the [Questrade IQ Edge API docs](https://www.questrade.com/api/documentation/getting-started). # Redbark Source: https://docs.sure.am/providers/redbark Connect bank accounts via Redbark's open banking aggregator Redbark is a banking aggregator that connects bank accounts to Sure through multiple upstream data providers. Data flows one way, from your banks into Sure, using read-only consented access. Your bank credentials are never shared with Redbark or Sure. Redbark routes your accounts through one of two upstream providers depending on your region: * **Fiskil** — Australian institutions, via the [Consumer Data Right](https://www.cdr.gov.au/) (CDR) open banking framework * **Plaid** — US and Canadian institutions See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works 1. You connect your banks in Redbark through each bank's official consent flow 2. You create a Redbark API key and paste it into Sure 3. Sure pulls your accounts, balances, and transactions from the Redbark API 4. Syncs run automatically to keep your data current ## Setting up Redbark > [!NOTE] > > API access requires a Redbark Developer or Professional plan. It is not available on the Saver plan. 1. Sign up at [app.redbark.com](https://app.redbark.com) and connect your bank accounts 2. In Redbark, go to **Settings > API Keys** and create a new key (it is only shown once) 3. In Sure, go to **Settings > Providers**, find the **Redbark** panel, and paste the key 4. Link each bank account to an existing Sure account or create a new one from it ## Features ### Account syncing * **Account listing**: All connected bank accounts with institution names and logos * **Balances**: Current balances fetched from your bank on every sync * **Transaction history**: The first sync pulls 90 days of history by default, or from a start date you choose (up to 2,550 days back). Later syncs are incremental with a 7-day lookback. * **Deduplication**: Transactions are deduplicated by their Redbark transaction id, so re-syncing never creates duplicates ### Choosing a sync start date During account setup, each account has an optional **Start syncing transactions from:** field. Set this before the account’s first transaction fetch to request older history. Sure caps the lookback at 2,550 days, leaving a safety margin inside Redbark’s boundary. The source records that Redbark rejected dates 2,555 or more days back; 2,550 is Sure’s cap, not that upstream boundary. If you leave the field blank, Sure defaults to 90 days. Incremental fetching requires both stored transactions for the account and a recorded last-sync time on its Redbark connection. With both present, Sure fetches from last sync minus 7 days. Otherwise, it uses the configured start date, clamped to the rolling 2,550-day window, or the 90-day default. As of October 22, 2026, this setup field and lookback-cap behavior are on `main` in [Sure PR #4306](https://github.com/we-promise/sure/pull/4306), but are not in the latest stable release, `v0.7.5-hotfix.2`. ### Variable loan rates For eligible linked loan accounts, Sure calls Redbark’s `GET /v1/account-details` endpoint during sync. For a variable-rate loan with a usable reported rate, Sure can record changes in its variable rate schedule. What Sure does with the reported rate: * For a variable-rate loan with no recorded rate, Sure sets the reported rate as its base rate unless that field is locked. A blank rate type can be adopted as variable when the bank identifies the product as variable. * If the rate has moved since the last sync, Sure adds a dated row to the variable rate schedule, updating the loan's projection and repayment schedule going forward. * If the loan is marked fixed and the bank reports a different rate, Sure logs the discrepancy and records nothing. * If the loan's rate or schedule is locked, the locked value is preserved. The date recorded is the day Sure detected the change. Redbark's API does not carry an effective date for rate changes, so the recorded date reflects when the change was seen rather than when the bank applied it. Sure reads the batch limit of 100 account IDs per API call. If a multi-account batch is rejected with a bad-request or not-found error, each account is retried individually so a single stale account does not block the others. A failed `account-details` fetch does not replace the stored details snapshot. Non-authentication failures are logged and allow the sync to continue; authentication failures propagate and require reconnecting the connection. ### Pending transactions Only posted transactions are imported by default. To also import pending transactions, set this in your Sure environment: ``` REDBARK_INCLUDE_PENDING=true ``` When a pending transaction settles, the posted version replaces it automatically. ## Limitations * Banking accounts only; brokerage accounts connected to Redbark are not imported * Data is read-only; Sure never writes anything back to your banks * Fiskil covers Australian institutions under the CDR regime; Plaid covers US and Canadian institutions ## Troubleshooting **Connection requires update**: your API key was revoked or expired. Create a new key in Redbark and update it in the Sure provider panel. **An account is missing**: check the account's consent is still active in Redbark under **Settings > Consents**, and note that brokerage accounts are not synced. **Sync errors**: Provider sync failures are captured in Sure's debug log. Super admins can find them at **Settings > Debug**, including counts of skipped and failed rows. **Credit card or loan balance was incorrect before**: earlier versions of Sure negated all Redbark credit card and loan balances regardless of the upstream provider. Fiskil (AU/CDR) reports those balances as negative, so negating them is correct. Plaid (US/CA) reports them as positive, so negating them produced the wrong sign and overstated net worth by twice the amount owed. Sure now applies the correct sign for each provider. If your net worth figure changed after updating, this correction is the cause. Trigger a manual sync from the account page to confirm the balance is current. For more detail, see the [Redbark documentation](https://docs.redbark.com/sure). # SimpleFIN Source: https://docs.sure.am/providers/simplefin Connect US bank accounts with a cost-effective provider SimpleFIN is a paid third-party provider focused on US bank account connectivity. It offers a simpler, more affordable alternative to Plaid for personal finance management. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works SimpleFIN uses a setup token system to establish secure access to your bank accounts: 1. Obtain a setup token from SimpleFIN 2. Sure claims the setup token to get an access URL with embedded credentials 3. The access URL is used to fetch account data, balances, and transactions 4. Data syncs automatically to keep your information current ## Setting up SimpleFIN To connect your US bank accounts: 1. Sign up for a SimpleFIN account at [simplefin.org](https://www.simplefin.org/) 2. Generate a setup token from your SimpleFIN dashboard 3. In Sure, provide the setup token 4. Sure will claim the token and establish access to your accounts ### Setup token claiming The setup token is a base64-encoded claim URL. When you provide it to Sure: 1. Sure decodes the token to get the claim URL 2. Validates the URL's target address before sending any request 3. Makes a POST request to claim the access URL 4. Receives an access URL with HTTP Basic Auth credentials embedded 5. Uses this access URL for all subsequent API requests If the claim URL decodes to an address that is not permitted (see [URL security checks](#url-security-checks) below), Sure rejects the token immediately and shows an invalid token error. No request is made to the disallowed address. ## Features ### Account syncing * **Account listing**: View all connected accounts with current balances * **Transaction history**: Import transactions with date range filtering * **Pending transactions**: Included by default. Not all institutions return pending transactions even when requested — this is a limitation of the institution's data feed. * **Multiple accounts**: Connect multiple bank accounts from different institutions * **Localized status messages**: Sync status summaries (such as "2 accounts synced" or "1 account needs setup") display in your chosen language ### Date range filtering When syncing transactions, you can specify: * **Start date**: Fetch transactions from this date forward * **End date**: Fetch transactions up to this date SimpleFIN expects Unix timestamps for date parameters. ### Pending transaction inclusion Pending transactions are included by default. Sure resolves whether to request them in this order: 1. An explicit argument passed internally by the sync flow 2. The `SIMPLEFIN_INCLUDE_PENDING` environment variable (`1` = include, `0` = exclude) 3. The shared **Include pending transactions** setting under **Settings → Self-Hosting** The setting and the environment variable both default to `1` (on). To disable pending transactions globally, set: ```txt theme={null} SIMPLEFIN_INCLUDE_PENDING=0 ``` Note that sending `pending=0` to the SimpleFIN API is not the same as omitting the parameter. The low-level client only adds `pending=1` when inclusion is enabled and omits the parameter otherwise, because some bridges treat the parameter's presence — regardless of value — as a request to include pending. ### Error handling Sure supports both the legacy SimpleFIN `errors` field and the structured `errlist` field introduced in protocol v2. When `errlist` is nonempty, it takes precedence over legacy `errors`. Error responses are classified as either partial or fatal: * **Partial errors** (`act.*` error codes): affect one or more individual accounts but accounts data is still returned. Sure records these errors in sync stats for visibility and continues importing the remaining accounts. * **Fatal errors**: errors accompanied by no accounts, or a structured `gen.*` error even when accounts are present. Sure stops the import and raises an error. The connection requires an update for structured `gen.auth`, `auth_failure`, `token_expired`, or `authentication_error` errors, or for legacy text mentioning authentication or reauthentication. An account-scoped `act.auth` code alone does not invalidate the entire connection. `gen.*`-coded errors (general errors) always trigger the fatal path, even when some account data is present in the same response. The account data alongside a general error may be stale or incomplete and cannot be safely imported. ### Reliability features Sure's SimpleFIN integration includes automatic retry logic: * Exponential backoff for transient network failures * Up to 3 retry attempts for network errors * Handles temporary connection issues gracefully * Prevents sync failures from intermittent network problems ## URL security checks Sure validates every SimpleFIN URL — both the setup token's claim URL and the stored access URL used on every sync — against a set of network address rules before making any request. This prevents a crafted token or bridge from directing the server to internal services. ### What is always blocked The following addresses are blocked regardless of whether you self-host Sure or use the project-operated instance: * Non-http(s) URLs * Link-local addresses (169.254.0.0/16), including the AWS instance metadata endpoint (169.254.169.254) * Unspecified, multicast, and reserved IPv4 ranges * The AWS IPv6 metadata address (fd00:ec2::254) * The Alibaba Cloud metadata address (100.100.100.200) * IPv6 addresses that carry an embedded IPv4 address (IPv4-mapped, NAT64, 6to4, IPv4-translated) are resolved to their underlying IPv4 address and checked against the same rules ### Additional restrictions on managed instances On the project-operated Sure instances (app.sure.am and demo.sure.am), the following addresses are also blocked to prevent access to private infrastructure: * http\:// URLs (https is required) * Loopback addresses (127.0.0.0/8, ::1) * Private network ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) * Carrier-grade NAT range (100.64.0.0/10) * IETF protocol assignment and benchmarking ranges (192.0.0.0/24, 198.18.0.0/15) Self-hosted instances are not subject to these additional restrictions, so a SimpleFIN bridge running on a local network or over plain http continues to work. ### How checks are applied Sure resolves the hostname to its IP addresses before each request and connects to the checked address directly. This prevents DNS rebinding attacks, where a hostname initially resolves to a public address but later resolves to an internal one mid-connection. Redirects are not followed, so a redirect to an internal address cannot bypass the check. When the stored access URL fails a check during a sync, Sure marks the connection as requiring reconnection and records a debug log entry under **Settings → Debug**. Providing a new setup token from your SimpleFIN dashboard resolves this. ## API structure SimpleFIN uses a simple REST API with embedded authentication: * **POST /claim**: Exchange setup token for access URL * **GET /accounts**: Fetch all accounts with balances and transactions * **GET /info**: Get server information The access URL contains HTTP Basic Auth credentials, so no separate authentication headers are needed. ## API reference For detailed protocol documentation, see the [SimpleFIN Protocol](https://www.simplefin.org/protocol.html). ## Pricing SimpleFIN is a paid service, but typically more affordable than alternatives like Plaid. Check [simplefin.org](https://www.simplefin.org/) for current pricing. ### Investment holdings and lot aggregation SimpleFIN reports one record per lot, so a single position can arrive as several records sharing the same security. A 401k that splits employee deferral from employer match is a common example. Sure combines these lots into a single position per security before storing the holding. Quantity and market value are summed across all lots. Cost basis is stored per share, so lots are combined into a share-weighted average — but only when every lot reported a basis. If any lot omits its cost basis, the entire position's cost basis is left unknown rather than averaging over partial data, which would invent cost and produce incorrect gain/loss figures. If your investment account shows a total value that matches your institution's balance but individual holdings appear at less than their full value, a manual sync from **Settings → Providers → SimpleFIN** will re-import the combined positions correctly. ### Holdings history Holdings are stored by date: a sync on a new day creates that day’s row, while another sync on the same day updates it instead of overwriting the previous day’s record. This means Sure accumulates a daily history of your positions so you can see how your portfolio has changed over time. ### User corrections carried forward When you remap a holding to a different security or lock a cost basis, Sure preserves that correction when a new day's sync creates the next holding row. Sure uses the latest earlier row for the same account, provider, provider security, and currency, carrying its active security and cost-basis locks forward. If you have since undone a correction, the undone state is not revived — only the latest version is carried forward. ### Institution-specific cost basis corrections The SimpleFIN specification says the `cost_basis` field is a per-share value, but some brokerages populate it with the total position cost instead. Sure detects these cases by institution name or domain and divides by quantity automatically, so the stored per-share figure stays correct. Institutions where Sure applies this correction: Vanguard, Fidelity, Schwab, and E\*Trade. If your institution sends a total cost in `cost_basis` but is not in this list, the holding will show an inflated per-share basis. In that case, you can correct the value by setting a manual cost basis on the holding. ## Limitations * **US-focused**: Primarily supports US financial institutions * **Setup token security**: Setup tokens can only be claimed once and may expire * **Pending transactions**: Not all institutions return pending transactions, even when requested * **Rate limits**: Subject to SimpleFIN API rate limits * **Access URL validity**: Access URLs can be revoked or expire (returns 403 error) ## Troubleshooting ### Incorrect balance sign on credit cards or loans SimpleFIN reports liability balances from the bank's perspective (positive = you owe money). Sure converts these into the correct sign for net worth calculations — liabilities reduce net worth, so their balances are stored as negative values. For **loans**, Sure trusts the bank's sign directly and stores the absolute value of the reported balance. Earlier versions incorrectly ran a transaction-history heuristic on loans, which could invert the balance and make the loan appear to add to your net worth instead of subtracting from it. This is now fixed. For **credit cards**, Sure uses recent transaction history to determine whether a positive balance represents debt (normal) or an overpayment credit (unusual). When there is not enough transaction history to decide, Sure falls back to sign-based normalization using both the posted and available balances reported by the institution. If a credit card balance still looks wrong after syncing, you can override the automatic sign detection. Open the account's edit form (from **Settings → Providers → SimpleFIN** or the account detail page) and find the **SimpleFIN balance meaning** dropdown: * **Automatic** (default): Sure uses transaction history and provider balance to determine the correct sign. * **Debt (you owe the bank)**: Forces the balance to be treated as a positive debt amount. * **Credit (bank owes you)**: Forces the balance to be treated as a credit in your favor (for example, an overpayment). Use an override only when SimpleFIN consistently reports an ambiguous sign for a specific card. The automatic setting is correct for most accounts. If a credit card or loan balance looks wrong after syncing: 1. Re-sync the account from **Settings → Providers → SimpleFIN**. 2. If the balance is still incorrect, check whether the account type is set to **Credit Card** or **Loan** in your account settings. An incorrect account type can cause the wrong normalization to be applied. 3. For credit cards connected through SimpleFIN, set **SimpleFIN balance meaning** to **Debt** or **Credit** in the account's edit form if the automatic detection is wrong for your institution. ### Duplicate accounts with the same name If you have two accounts at the same institution with identical display names (for example, two accounts both named "CHECKING (0001)"), Sure uses the upstream account ID to distinguish them during sync. Only accounts whose ID is genuinely absent from the upstream response are treated as stale and eligible for re-linking. Ambiguous cases where multiple local accounts share a name are skipped rather than resolved automatically, preventing one account from silently inheriting another's transaction history. If you notice an account that appears to have lost its transaction history after a sync, check **Settings → Debug** for any skipped stale-linkage repair entries that may indicate an ambiguous name match. ### Setup token issues If you receive a 403 error when claiming a setup token: * The token may have already been used * The token may have expired * The token may have been compromised Generate a new setup token from your SimpleFIN dashboard. ### Invalid token or disallowed address error If Sure shows an invalid token error immediately when you enter a setup token, the token's embedded claim URL may point to a network address that Sure does not permit. This can happen with tokens generated by a bridge misconfigured to use a private or metadata address. Check that your SimpleFIN bridge is reachable at a public address. On the project-operated instance, https is required and private network addresses are blocked. On a self-hosted instance, http and local network addresses are allowed. If the connection was working and now requires reconnection after a sync, check **Settings → Debug** for a `SimpleFIN access URL rejected` entry. This indicates the stored access URL now resolves to a blocked address. Provide a new setup token from your SimpleFIN dashboard to reconnect. ### Missing pending transactions Pending transactions are requested by default. Some institutions don't return them even when `pending=1` is sent. This is a limitation of the institution's data feed, not a bug in SimpleFIN or Sure. If you want to disable pending transactions entirely, set `SIMPLEFIN_INCLUDE_PENDING=0` in your environment or turn off **Include pending transactions** under **Settings → Self-Hosting**. ### Network errors If you experience intermittent sync failures: * Sure automatically retries failed requests up to 3 times * Network errors are logged for troubleshooting * Manual sync attempts may succeed where automatic syncs fail # SnapTrade Source: https://docs.sure.am/providers/snaptrade Connect brokerage accounts through the SnapTrade aggregation network SnapTrade is a third-party provider for brokerage connectivity. In Sure, it is focused on **investment** and **crypto** accounts rather than checking or credit card accounts. It is a good fit if you want to import holdings, balances, and brokerage activity from supported brokers such as Fidelity, Vanguard, Schwab, and Robinhood without building a custom brokerage integration yourself. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works Sure uses your SnapTrade **Client ID** from an OAuth app to create a per-family SnapTrade user and sync the accounts you authorize. Personal API keys are not supported because they do not use SnapTrade's Register User flow. Sure supports two ways to authorize a brokerage connection, and the setup steps differ slightly between them. ### Device code flow The device code flow (RFC 8628) requires only a **Client ID**. When you connect a brokerage, Sure displays a short code that you confirm on the SnapTrade website. No redirect URI registration is needed, so this works on any deployment including those that cannot expose a public callback URL. ### Authorization code flow (browser redirect) The browser redirect flow requires a **Client ID** and a **Client Secret**, plus the redirect URI `https:///snaptrade_items/oauth_callback` registered on your OAuth app. When you connect a brokerage, you are sent to SnapTrade in the same browser tab and redirected back after approval. Sure prefers the browser redirect when both flows are available, because it is the shorter path for the user. Both flows produce the same access and refresh tokens and result in the same ongoing sync behavior — holdings, activity, and token rotation all work identically after authorization. ## Setting up SnapTrade To connect your brokerage accounts: 1. Create an account at [dashboard.snaptrade.com](https://dashboard.snaptrade.com/) 2. Create or open a SnapTrade OAuth app and copy its **Client ID** 3. In Sure, go to **Settings > Bank sync > SnapTrade** 4. Paste the credentials and click **Save Configuration** 5. Click **Connect Brokerage** and complete the authorization flow 6. After authorization, open the account setup screen and choose which discovered brokerage accounts to link If you are using the browser redirect flow, also: * Copy the **Client Secret** from your SnapTrade OAuth app and paste it into the Sure settings alongside the Client ID * Register `https:///snaptrade_items/oauth_callback` as a redirect URI on the OAuth app If you already have an unlinked investment or crypto account in Sure, you can link the SnapTrade account to that existing account instead of creating a duplicate. ## Environment variables | Variable | Required | Description | | - | - | - | | `SNAPTRADE_OAUTH_CLIENT_ID` | Yes | Client ID from your SnapTrade OAuth app. Enables the device code flow on its own. | | `SNAPTRADE_OAUTH_CLIENT_SECRET` | No | Client Secret from your SnapTrade OAuth app. Required only for the browser redirect flow. | Setting only `SNAPTRADE_OAUTH_CLIENT_ID` enables the device code flow. Setting both variables enables the browser redirect flow as the default, with the device code flow available as a fallback where shown. ## Managing connections SnapTrade connections are managed per family inside Sure. To open the connections panel, click the menu on a SnapTrade account card and select **Manage Connections**, or go to **Settings > Providers > SnapTrade** and expand the connections section directly. After your first successful connection, Sure lets you: * Add another brokerage connection * Review connected brokerages * Remove a brokerage connection * Delete unused or stale brokerage connections before adding more > [!WARNING] > > SnapTrade's free tier covers **5 brokerage connections**. If you hit the limit, remove unused connections from Sure or upgrade your SnapTrade plan. ## Supported account types Sure currently uses SnapTrade for: * **Investment** accounts * **Crypto** accounts Brokerage-specific account subtypes such as IRA, Roth IRA, 401(k), TFSA, RRSP, margin, cash, joint, and Cash Management Account (CMA) are mapped into Sure's investment account model automatically. ## Features ### Brokerage syncing * **Brokerage aggregation**: Connect supported brokerages through a single provider * **Holdings sync**: Import securities positions and cash balances * **Activity sync**: Import brokerage activity and trade history * **Multiple brokerages**: Connect more than one brokerage under the same SnapTrade configuration * **Link existing accounts**: Attach a discovered SnapTrade account to an existing Sure investment or crypto account ### Account setup flow After authorization, Sure separates discovered SnapTrade accounts into: * **Linked accounts**: Already attached to a Sure account * **Unlinked accounts**: Ready to be linked or created in Sure This makes it easier to avoid duplicates when you reconnect a brokerage or add another account later. ### Activity type coverage Sure maps the full range of SnapTrade activity types to trades or cash entries: **Trade activities** (always imported as investment trades): BUY, SELL, REI, REINVEST, OPTION\_BUY, OPTION\_SELL, OPTIONASSIGNMENT, ASSIGNED, OPTIONEXERCISE, EXERCISED, OPTIONEXPIRATION, EXPIRED, STOCK\_DIVIDEND, SPLIT, REVERSE\_SPLIT, SPINOFF, and asset transfer variants (EXTERNAL\_ASSET\_TRANSFER\_IN/OUT, INTERNAL\_ASSET\_TRANSFER\_IN/OUT). When SnapTrade supplies an `option_symbol` object with a ticker, Sure prefers that option ticker (for example, `TQQQ 260220C00051000`) over the regular symbol, which may identify the underlying equity. OPTION\_BUY and OPTION\_SELL are imported as trades, but the activity type alone does not supply an option ticker; without one, Sure falls back to the regular symbol data. Fees on option trades are stored separately and factored into realized gain/loss the same way as equity trades. **Unit-dependent activities** (ADJUSTMENT, STOCK\_MERGER, MERGER, CORP\_ACTION): imported as trades when SnapTrade reports a non-zero share quantity, and as cash entries when the quantity is absent or zero. This lets zero-cash corporate actions (splits, mergers with no cash consideration) record correctly as unit-only trades while still capturing any cash component when it is present. **Cash activities**: DIVIDEND, DIV, CONTRIBUTION, WITHDRAWAL, TRANSFER, TRANSFER\_IN/OUT, INTERNAL\_CASH\_TRANSFER\_IN/OUT, INTEREST, FEE, TAX, CASH, REBATE, RETURN\_OF\_CAPITAL, DISTRIBUTION, SUBSTITUTE\_DIVIDEND, JOURNAL, OTHER. ### Security row disambiguation A ticker can have more than one security row in Sure's database when it trades on multiple exchanges. Sure selects a security row in a fixed, deterministic order: 1. The row from a matching SnapTrade or providerless holding in the account, preserving user remaps and locked cost basis. Holdings from another provider are excluded. 2. The row matching the exchange SnapTrade reports for the ticker. 3. Online rows first, then rows with a price provider, then the oldest row. If the fallback (step 3) applies and more than one candidate exists, Sure records a warning entry in the debug log at **Settings > Debug** with the ticker, the reported exchange, the chosen row, and each candidate. A single candidate at step 3 does not generate a log entry. This fallback does not establish the correct exchange: it can consistently retain a wrong match that requires manual correction. ### Resync reclassification If a later sync determines an activity should be classified differently (for example, a CORP\_ACTION that previously had units is re-fetched without units), Sure reclassifies the entry automatically. Entries that have been manually edited or locked by an import are protected and will not be reclassified; these cases are recorded in the debug log at **Settings > Debug**. ### Option contract support Sure imports option trades from SnapTrade, including standard and mini-option contracts. When SnapTrade reports an `option_symbol` alongside a plain `symbol`, Sure uses the option symbol. This prevents brokerages such as Robinhood, which populate `symbol` with the underlying equity even on options activity, from importing option trades as common stock. Option contracts are displayed with a formatted name that includes the underlying ticker, strike price, option type, and expiration date. For example: `AAPL $150 CALL (2026-01-20)`. SnapTrade reports option quantity in contracts but quotes price per underlying share. Sure converts the per-share price to a per-contract price by applying the contract multiplier (100 for standard options, 10 for mini-options) so that `quantity × price` correctly represents total contract value. ### Trade amount and fee accuracy Sure uses SnapTrade's reported trade amount directly rather than computing it as quantity × price. Brokerage-reported prices are often rounded or estimated, so the computed value can drift by a few cents from the cash that actually moved — most visibly for reinvestments that should match their dividend exactly. When SnapTrade reports a fee for the trade, Sure stores it on the trade record. If a resync omits the fee (SnapTrade only reports it "if provided by the brokerage"), the previously stored value is preserved rather than overwritten. If SnapTrade reports an amount but no price, Sure derives the price from the reported amount, fee, and quantity so the trade can still be imported. These derived-price trades are recorded in the debug log at **Settings > Debug** so you can inspect them. When a trade cannot be imported — for example because SnapTrade omitted both quantity and amount — it is also recorded in the debug log with the reason, so support can identify the gap without requiring a full sync replay. ### Background activity import Fresh brokerage connections may take a little longer to finish importing activity history. Sure continues fetching account activity in the background after the initial connection when needed. ## Security Sure encrypts sensitive SnapTrade data at rest using ActiveRecord Encryption when encryption keys are configured in your deployment. Configure `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY`, `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY`, and `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT`, or the corresponding Rails encryption credentials, before connecting a SnapTrade integration in a production environment. Without encryption configuration, the fields below are stored in plaintext. The following fields on each SnapTrade account record are encrypted: * **Account number** — encrypted with non-deterministic encryption; never looked up by value, so it does not need to be deterministic * **Raw API payloads** — the raw account, transaction, holdings, activities, and balance payloads returned by SnapTrade The SnapTrade item credentials (Client ID, Consumer Key, OAuth access token, and OAuth refresh token) are encrypted on the item record separately. ### Encrypting existing records If you configured encryption keys after your initial setup, use the `security:backfill_encryption` rake task to backfill the supported fields: The backfill covers `account_number` and raw account, transaction, holdings, and activities payloads. It currently does not backfill `raw_balances_payload` or SnapTrade item credentials; it is not a complete migration of all existing SnapTrade data. ```bash theme={null} bin/rails security:backfill_encryption ``` The task is idempotent and defaults to a dry run. Pass `dry_run=false` to apply changes: ```bash theme={null} bin/rails security:backfill_encryption[100,false] ``` The task processes records in batches and prints a JSON summary of results when it finishes. See the task description for full argument details. ## Limitations * **Investment-focused**: SnapTrade is not the right provider for checking, savings, or credit card syncing * **Connection caps**: Free-tier SnapTrade accounts have limited brokerage connection slots * **Provider coverage**: Only brokerages supported by SnapTrade can be connected * **Beta maturity**: SnapTrade support in Sure is still marked beta in the app * **Activity timing**: Activity availability depends on SnapTrade's data timing and the connected brokerage * **Options in holdings**: Option positions are not shown in the holdings view; only options activity (trades) is imported ## Troubleshooting ### Credentials save, but brokerage connection does not start * Verify the **Client ID** was copied from the correct SnapTrade OAuth app * If using the browser redirect flow, confirm the **Client Secret** is also set and the redirect URI is registered * Re-open **Settings > Bank sync > SnapTrade** and save the credentials again * Try the **Connect Brokerage** button again so Sure can re-register the SnapTrade user if needed ### Holdings show as empty after connecting a brokerage SnapTrade deprecated the `/positions` endpoint for apps registered after their 2026 cutoff. Sure now uses the `/positions/all` replacement endpoint, so holdings should import correctly for all new and existing connections. If you connected a brokerage before this fix and see no holdings, run a manual sync from the account card to refresh. ### No accounts appear after connecting a brokerage * Wait for the initial sync to finish and refresh the setup page * Check whether the brokerage was connected successfully in **Manage Connections** * Try running another sync from the SnapTrade account card in Sure ### Hit the free-tier connection limit * Open **Manage Connections** in Sure and delete old brokerage connections you no longer use * Delete unused or stale brokerage connections first; the limit applies to brokerage connections, not registrations alone * Upgrade your SnapTrade plan if you need more simultaneous brokerage connections ### Device code expires before confirmation The device code has a limited validity window. If Sure shows "This device code expired. Start the authorization again.", click the start button to request a fresh code. If Sure shows "SnapTrade hasn't seen your confirmation yet. Approve the code in SnapTrade, then try again.", the confirmation is still pending. Approve the code in the SnapTrade app and click the complete button again. If Sure shows "SnapTrade authorization was declined.", the authorization was rejected. Start a new connection attempt if you want to try again. ## API reference For SnapTrade API details and broker coverage, see the [official SnapTrade documentation](https://docs.snaptrade.com/). # Sophtron Source: https://docs.sure.am/providers/sophtron Connect US and Canadian bank accounts via Sophtron's aggregation API Sophtron is a third-party provider that connects bank, credit card, investment, loan, insurance, utility, and other financial accounts in the US and Canada. It is currently in **alpha**. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works Sophtron uses HMAC-SHA256 (FIApiAUTH) signed API calls to securely aggregate your financial data: 1. Obtain a Sophtron User ID and Access Key 2. Configure your credentials in Sure 3. Sure provisions a Sophtron Customer for your family (created or reused automatically through the API) 4. You connect a bank institution by searching for it and entering your bank login credentials 5. Sure fetches your accounts, balances, and transactions through Sophtron's API 6. Data syncs automatically to keep your information current ## Setting up Sophtron > [!NOTE] > > Connecting institutions and managing Sophtron connections requires a family > admin role. Non-admin members can view linked accounts but cannot start a new > institution connection or submit MFA answers. To connect your accounts: 1. Register a Sophtron account at [sophtron.com](https://sophtron.com/account/register) 2. Obtain your **User ID** and **Access Key** from the [Sophtron dashboard](https://sophtron.com/Manage/Developer) 3. In Sure, go to **Settings > Bank sync > Sophtron** and add your Sophtron credentials 4. Open the Sophtron connection dialog and search for your bank institution 5. Enter your bank login credentials (and complete any MFA challenge if prompted) 6. Sure will discover your accounts and prompt you to select which ones to link ### Credential configuration Sophtron credentials are stored per-family. Each family configures their own User ID and Access Key. Credentials are encrypted at rest when ActiveRecord Encryption is enabled. You can optionally configure a custom **base URL** if you use a non-production Sophtron environment. The default base URL is `https://api.sophtron.com/api`. When you save your credentials, Sure automatically creates or reuses a Sophtron **Customer ID** for your family by calling the Sophtron Customer API. You do not need to provision the customer manually. ### Connecting an institution Before you can link accounts, you must connect a bank institution to Sophtron: 1. Search for your bank by name in the connection dialog 2. Select the institution from the results 3. Enter your bank username and password 4. If the institution requires it, complete the MFA challenge #### Multi-factor authentication Sophtron supports several MFA challenge types. Depending on your institution, you may be asked to: * Answer one or more security questions * Choose how you want to receive a verification code (for example, email or SMS) * Enter a verification code (OTP) sent to your email or phone * Type the text shown in a captcha image * Confirm the login attempt by phone Sure polls Sophtron for the connection status while the institution login is in progress and prompts you when an MFA step is required. After you submit a challenge, Sure continues polling so any follow-up step (such as entering an OTP after choosing a delivery method) is shown automatically. #### Connection timeouts and retries If Sophtron does not finish connecting within the expected time, the connection dialog gives you the option to check again or retry. Failed or timed-out connection jobs are reset so you can start a fresh attempt without re-entering your provider credentials. ### Linking accounts After the institution is connected, Sure fetches available accounts from Sophtron. You can: * **Link new accounts**: Select from your Sophtron accounts and choose the account type (depository, credit card, investment, or loan) * **Link existing accounts**: Connect an existing Sure account to a Sophtron account for automatic syncing ## Supported account types Sophtron supports the following account types: | Account type | Description | | - | - | | Depository | Checking, savings, and other deposit accounts | | Credit card | Credit card accounts | | Investment | Brokerage and retirement accounts | | Loan | Mortgage, student loan, and other loan accounts | When linking accounts, you can also select a subtype (e.g., checking vs. savings for depository accounts). ## Features ### Account syncing * **Account discovery**: Automatically finds all accounts available on the connected institution * **Balance tracking**: Fetches current balances for all linked accounts * **Transaction history**: Imports transactions with date range filtering * **Refresh polling**: Sync jobs poll Sophtron's job status endpoint and complete once the refresh job finishes * **Reconnect on auth recovery**: When an institution refresh requires re-authentication or a new MFA challenge, Sure marks the connection as `requires_update` so you can complete the challenge and resume syncing ### Transaction syncing When syncing transactions, Sure: * Fetches transactions within a configurable date range * Maps transaction data including amount, date, merchant, and description * Supports both income and expense transaction types * Defaults the currency to USD when not specified by the provider ### Sync start date You can configure a **sync start date** to control how far back Sure fetches transaction history. This is useful when you only want recent transactions rather than a full history. ## Limitations * **Alpha status**: Sophtron integration is currently in alpha and may have rough edges * **US and Canada only**: Primarily supports financial institutions in the United States and Canada * **Rate limits**: Subject to Sophtron API rate limits (returns a 429 status when exceeded) * **No pending transactions**: Pending transaction support is not currently available * **Holdings**: Investment holdings sync is not currently supported ## Troubleshooting ### Incorrect balance sign on credit cards Sophtron institutions do not all use the same balance sign. Sure stores credit-card debt as a positive amount owed and an overpayment as a negative credit. For **credit cards**, Automatic mode negates the provider balance. This is suitable when that institution reports debt as negative; institutions that report debt as positive may need an override. If a card balance looks wrong after syncing, you can override this automatic behavior. Open the account's edit form and find the **Sophtron balance meaning** dropdown: * **Automatic** (default): Sure negates the credit card balance from the provider. * **Debt (you owe the bank)**: Forces the absolute value of the reported balance to be stored as debt. * **Credit (bank owes you)**: Forces the balance to be treated as a credit in your favor (for example, an overpayment). Use an override only when Sophtron consistently reports an ambiguous sign for a specific card. Choose Debt or Credit according to what the balance means at your institution. When you change the setting, Sure applies the override to the stored balance immediately and schedules a sync so the account reflects the corrected value without delay. If applying the override fails, Sure rolls back the change so you can retry the selection. ### Authentication errors If you receive an "Invalid User ID or Access key" error: * Verify your User ID and Access Key are correct * Ensure your Access Key is the base64-encoded version provided by Sophtron * Check that your Sophtron account is active ### Institution connection errors If Sure cannot complete the institution connection: * **Bank credentials**: Double-check the username and password you entered for the institution * **Verification code**: Make sure you entered the latest MFA code before it expired * **Institution timeout**: The bank login page may not have finished in time. Try connecting again * **Unsupported MFA**: Sophtron may not support the institution's current verification flow ### No accounts found If Sure cannot find any accounts: * Confirm that you have completed the institution connection step * Check that your credentials have the correct permissions * Try re-entering your credentials in Sure's Bank sync settings ### No institution connected If Sure tells you that no bank institution is connected when syncing or linking accounts, open the Sophtron connection dialog and connect an institution before retrying. Sync attempts fail until at least one institution is linked. ### Sync failures If syncing fails intermittently: * Check whether you have hit the API rate limit (wait and retry) * Verify your credentials have not been revoked * If the connection is marked **requires update**, reopen the connection dialog and complete the new MFA challenge * Review the sync status in your accounts page for specific error messages # Trade Republic Source: https://docs.sure.am/providers/trade-republic Connect a Trade Republic investment account via secure web login Trade Republic is a European neo-broker that lets you buy stocks, ETFs, bonds, crypto, and private market assets. Sure connects to Trade Republic directly using its authenticated web API — no third-party aggregator is required. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works Sure authenticates to Trade Republic using the same web login flow as the Trade Republic web app. After you confirm the login on your phone, Sure stores an encrypted session token and uses it for all future syncs. Your PIN or password is never stored. It is used only to start a new login session and is discarded immediately after. The credential is also filtered from request logs so it never appears in server-side log output. Sure discovers up to three accounts from your Trade Republic connection: * **Portfolio account** — holds your securities positions (stocks, ETFs, bonds, private market instruments) and tracks their current value * **Cash account** — holds your Trade Republic cash balance and records deposits, withdrawals, card payments, interest, and dividends * **Crypto account** — holds your crypto positions and their trade history; created automatically once the portfolio holds or has traded crypto ## Logging in Sure supports two login methods: ### Phone number and PIN or password 1. Enter your Trade Republic phone number and your PIN or password 2. Sure starts a web login session with Trade Republic 3. Trade Republic sends a push notification or authenticator code to confirm the login 4. Confirm the login in the Trade Republic app, then click **Confirm login** in Sure ### QR code 1. Click **QR login** in the Trade Republic panel 2. Sure fetches a QR code from Trade Republic 3. Scan the QR code with your phone camera, then approve the login in the Trade Republic app 4. Sure detects the approved session automatically Use the QR login if you prefer not to enter your PIN or password in Sure, or if you do not have the Trade Republic authenticator set up. ## Setting up Trade Republic 1. In Sure, go to **Settings > Providers** 2. Find the **Trade Republic** section and click to expand it 3. Choose your login method (phone number and PIN or password, or QR code) and complete the login 4. After a successful login, click **Sync** to discover your accounts 5. Once the sync finishes, click **Set up accounts** to link the discovered accounts to Sure accounts Sure discovers a Portfolio account and a Cash account for every connection. If your portfolio holds or has traded crypto, a Crypto account is also discovered and shown in the account setup flow. If you already have a manual investment account in Sure, you can link the discovered Trade Republic portfolio account to it instead of creating a new one. A Crypto provider account can be linked to an existing Crypto (exchange) or Investment account. ## Multiple connections Sure supports more than one Trade Republic connection per family. Each connection is shown as a separate card in the Trade Republic panel. To add another connection, click **Add another connection** at the bottom of the Trade Republic section and complete the login for the second account. Each connection card shows a short identifier to help you tell them apart. For phone number logins, Sure displays the last four digits of the phone number. For QR-code logins with no phone number on file, Sure falls back to the last four characters of the linked brokerage account number once a sync has run. If you complete a login and Sure detects that the Trade Republic account is already linked through another connection in the same family, the new connection is discarded automatically and you will see a notice explaining the duplicate was removed. ## Account types | Account | Sure account type | What it tracks | | - | - | - | | Portfolio | Investment | Securities positions (excluding crypto once the Crypto account is linked) and their current value | | Cash | Depository | Cash balance, deposits, withdrawals, card payments, interest, dividends | | Crypto | Crypto (exchange) | Crypto positions and trade history; only created when the portfolio holds or has traded crypto | The portfolio account subtype follows the non-crypto assets held. Sure maps Trade Republic's portfolio categories to account subtypes: | Trade Republic category | Sure account subtype | | - | - | | Stocks and ETFs | Brokerage | | Private markets | Private markets | | Interest / bonds | Interest products | ### Crypto account linkage The Crypto provider account links only to a **Crypto** account in Sure (exchange subtype) or to an **Investment** account. Portfolio and Cash provider accounts continue to link to Investment and Depository accounts respectively. Account setup shows only compatible account types for each provider account. Until you link the Crypto provider account to a Sure account, crypto positions and trades remain on the Portfolio account. Once you link it, crypto positions and trades move to the Crypto account and the Portfolio leaves them and their value out of its total. ## What gets imported ### Portfolio account * Current holdings with quantities and market values (crypto excluded once the Crypto account is linked) * Trade history (buys and sells for stocks, ETFs, and bonds), including fees recorded separately on each trade * Bond purchases: the nominal amount is imported as quantity and the quotation (price as a percent of par) is converted to a per-unit price — for example, a quotation of 92.67% becomes a price of 0.9267 per nominal unit * Savings plan executions, including historical savings-plan invoices * Saveback reinvestments (recorded as portfolio trades; no cash leg, because Trade Republic pays for the shares) * Stock Bonus shares (ACQUISITION\_TRADE\_PERK events, recorded as portfolio trades; no cash leg, because Trade Republic pays for the shares) * Private Markets bonus units — the 1 % bonus units Trade Republic adds to a Private Markets order are recorded as a portfolio trade with no cash leg; no cash outflow is created for them * Round Up investments (recorded as portfolio trades) ### Cash account * Cash balance * Deposits and withdrawals, including Google Pay deposits and credit card top-ups (recorded as standard transactions; automatic transfer matching turns a deposit into a transfer when the counterpart bank account is also in Sure) * Card payments and ATM withdrawals, including card-funded transfers out such as topping up PayPal, Revolut, or Paysafecard (CARD\_AFT events, labeled Card payment) * Card refunds, including card credits such as merchant refunds pushed directly to the card (CARD\_OCT events, labeled Card refund) * Italian stamp duty charges (imposta di bollo); cancelled charges book nothing new, and earlier entries are removed unless protected from sync or part of a split * Interest payouts (labeled Interest) * Dividends, including per-share amount and withholding tax where available (labeled Dividend) * Fees (labeled Fee) * Tax refunds * Trade settlements: each buy and sell settlement records a cash outflow or inflow linked to the portfolio by a confirmed transfer when both accounts are linked. When available, the settled amount uses the detail total from Trade Republic (fees and taxes included). Until that detail is fetched, Sure can use the timeline amount * Round Up outflows (labeled Buy, linked to the portfolio by a confirmed transfer when both accounts are linked) ### Crypto account * Crypto positions taken from the portfolio snapshot, with quantities and market values * Crypto trade history (buys, sells, round-up settlements) moved over from the portfolio once the Crypto account is linked * Trades the user has not edited are moved automatically; edited trades stay on the Portfolio When all three accounts are linked: * Non-crypto buy and sell trades are recorded on the Portfolio account. Each trade also produces a corresponding entry on the Cash account: buys appear as uncategorized investment contributions and sale proceeds appear as funds movements. * Crypto buys, sells, and round-up settlements are recorded on the Crypto account. Each trade produces a corresponding Cash entry linked to it as a confirmed transfer. * Cash movements (deposits, withdrawals, card payments, interest, dividends) are recorded on the Cash account only. * Saveback events and Stock Bonus events are recorded as Portfolio trades only, with no cash leg on either account. * Round Up events produce a trade on whichever account holds the position (Portfolio or Crypto) and a corresponding cash outflow linked by a confirmed transfer. ## Trade names Trades are labelled using the format `{ticker} · {quantity}x {name}`. When the security name matches the ticker, the name is omitted: `{ticker} · {quantity}x`. The Buy or Sell direction appears as an activity label rather than in the entry name. ## Securities and market data Sure resolves holdings and historical trades to exchange tickers when Trade Republic provides a venue symbol. Exchange-listed securities use real ticker symbols for market data lookups. When no usable exchange symbol is available for a position, the security is marked offline and price importers skip it automatically. Sure retries unresolved ISINs at most once per day for up to 30 days. ### Bonds Trade Republic lists every bond on its exchange under the placeholder symbol "BOND". Sure bypasses that listing and resolves each bond directly to an offline ISIN security instead. Each bond gets its own security, so two bonds in the same portfolio no longer share a single holding row. Bonds are priced using Trade Republic's own snapshot prices rather than a market data feed. Bond securities are named using the format `{issuer} {coupon} {maturity}` — for example, "Italy 3.1% Mar 2040". A fixed coupon is included when available; floating or unavailable coupons are omitted. If the issuer or maturity is unavailable, the name falls back to the instrument name from Trade Republic. Holdings that were previously stored on the shared BOND listing are moved to each bond's own ISIN security automatically on the next sync. ### Crypto holdings Trade Republic identifies crypto positions using pseudo-ISINs that encode the coin symbol — for example, `XF000BTC0017` for Bitcoin and `XF000ETH0019` for Ether. When the crypto price provider is enabled in Sure, holdings and trades for these ISINs are resolved to the shared `CRYPTO:` security used by on-chain wallets and exchange integrations. Any existing rows stored under the Trade Republic ISIN are migrated over automatically. When the crypto price provider is not enabled, the offline ISIN security is kept and positions remain valued at Trade Republic's own snapshot prices. Crypto positions and trades import on the **Crypto account** once it is linked. Before linking, they remain on the Portfolio account. Sure creates the Crypto provider account automatically the first time a sync detects crypto holdings or trades in your Trade Republic portfolio. Bond positions are quoted by Trade Republic as a percentage of par (for example, 84.04 means 84.04% of face value). Sure converts this to a per-unit price before computing market value, so the holding value matches the true market price of your nominal bond position. Private market positions are valued using quotes from Trade Republic's private markets feed when available. If no live quote exists, Sure uses the average cost basis as the holding value. Other positions without a live price show a price-unavailable indicator rather than a flat return. ## Syncing Sure syncs Trade Republic accounts on the same schedule as other connected providers. You can also trigger a manual sync from the Trade Republic panel in **Settings > Providers**. Session tokens are refreshed automatically during each sync when Trade Republic returns a renewed token. ### Session expiry Trade Republic login sessions expire after 24 hours, but earlier server revocation may require you to log in sooner. When a session ends, Sure stops syncing that connection until you log in again. * The Accounts page and the Trade Republic settings card both show when the current login expires. * The providers list shows a warning two hours before the session is due to end. * Sure schedules a sync approximately one hour before the session ends so the day's activity is still imported. * Once the session has expired, the status changes to **Re-authentication required**. The Accounts page and the Settings card both offer the QR login so you can log in again without going to **Settings > Bank sync**. * The Sync button is disabled while a session has ended. Triggering a sync from the panel or the API requires a valid session. ### Categories and labels on cash deposits Categories and activity labels assigned to cash deposits by a Rule are preserved across syncs. Rule-assigned categories and labels on Trade Republic cash deposits are not removed when you sync. ## Troubleshooting ### Re-authentication required Your Trade Republic session expired. Log in again using your phone number and PIN or password, or the QR code method. You can start the QR login directly from the Accounts page or from **Settings > Bank sync > Trade Republic**. ### Provider not configured If you see a "not configured" error when trying to add a Trade Republic account, Sure could not find an active Trade Republic connection. This alert does not by itself establish whether a previous login completed. Go to **Settings > Providers > Trade Republic**, complete the login flow, and then add accounts. ### Accounts need setup A sync discovered your Trade Republic accounts, but they have not been linked to Sure accounts yet. Click **Set up accounts** from the Trade Republic panel and complete the account setup. ### No accounts discovered yet The login succeeded, but no accounts have been found yet. Click **Sync** from the Trade Republic panel and wait for the sync to finish, then try **Set up accounts** again. ### Trade history not showing If buy or sell trades are missing from your portfolio account, run a manual sync from **Settings > Providers > Trade Republic**. Previous syncs may have skipped order executions due to a locale mismatch — a sync after updating Sure will import them correctly. If trades are still missing after syncing, check the activity feed on your portfolio account. Trades are recorded in the format `{ticker} · {quantity}x {name}` with Buy or Sell as the activity label. ### Some trades listed as not imported yet During a sync, Sure may encounter order executions whose detail Trade Republic has not fully delivered yet — the response is missing an ISIN or a quantity. Sure skips those executions and records a warning in the sync diagnostics with the total affected count and details for up to 50 executions: event ID, type, date, and what is missing. The Trade Republic panel’s data quality section shows a pending-trade-details count. The detailed warning is recorded in the debug log. Later syncs retry incomplete details within the sync’s fetch budget; a trade can import once the required detail arrives. If it remains missing across syncs, check the Trade Republic app and the debug log to investigate. ### Trade prices were corrected after a sync Sure prefers an explicit share price, bond quotation, or the trade detail’s `quantity × price` row. When those are unavailable, it can still derive a price from the total after accounting for fees and taxes. Deriving a price from a cent-rounded total can introduce small differences. Stored trades without a confirmed detail price are eligible for automatic detail backfill during later syncs. When a better price arrives, unprotected trades can be corrected and their calculated cost basis refreshed. Fetches share a bounded sync budget: a never-attempted trade is eligible even if older than 30 days; unsuccessful newer trades retry at most daily until they reach 30 days old. User-protected fields are preserved. ### Holdings show the wrong value If a position shows no price or an incorrect value: * Run a manual sync to refresh market prices * Check the **Data quality** section on the Trade Republic panel for positions flagged as unpriced * Private market positions without a live quote are valued at their average cost basis * Other positions without a live price display a price-unavailable indicator **Bond values were previously inflated 100x.** Trade Republic quotes bond prices as percentages of par while position sizes represent nominal amounts. Older syncs could multiply the two directly. Current syncs divide bond quotes by 100. An upgrade migration rescales eligible historical provider snapshots and cached positions. **Repair** reprocesses stored provider data but does not rerun that migration. If older values remain inflated after upgrading and syncing, report the affected holdings for investigation. ### Deposits showing as transfers or investment contributions Earlier syncs classified Trade Republic cash-account deposits as funds movements (which appeared as transfers) or investment contributions. A sync resets those entries to standard transactions automatically, unless you edited them or they are part of a matched transfer. If any deposits still appear incorrectly after syncing, run a manual sync from **Settings > Providers > Trade Republic**. ### Balance does not match the Trade Republic app Sure uses the booked cash balance from Trade Republic, which matches the balance shown in the Trade Republic app. Funds reserved for open orders (such as pending limit orders) are not subtracted from this balance — those orders have not settled, so no matching transaction exists yet. For sales where Trade Republic withholds tax, the settled cash amount can differ from the headline order value shown in the timeline list. Once the detail is available, Sure prefers its total (the figure Trade Republic posts against your cash balance, taxes included) over the list amount, so the cash account should stay consistent with the Trade Republic app. If the balance still does not match, a sync may have captured a partial response. Run a manual sync to refresh. If the discrepancy persists, click **Repair** in the data quality section of the Trade Republic panel to re-process imported data. ### QR code login appears to expire right after scanning If Sure shows a login-expired or already-used error immediately after you scan the QR code in the Trade Republic app, start a new QR login from **Settings > Providers > Trade Republic**. The previous code was single-use and cannot be retried — the new code will work correctly. ### Phone number and PIN or password login confirmation times out The push login confirmation window is open for approximately two minutes. Sure polls Trade Republic at one-second intervals and backs off automatically if Trade Republic is rate-limiting or temporarily unavailable. If the window closes before you confirm: 1. Click **Cancel** or wait for the panel to reset 2. Start a new login from **Settings > Providers > Trade Republic** and enter your PIN or password again If the panel shows a rate-limit or outage alert, wait a moment and then click **Check login status** to retry manually. Sure will resume automatic polling on the next login attempt. ## Limitations * **European accounts only**: Trade Republic operates in Europe. Accounts in unsupported regions cannot be connected. * **Session expiry**: Trade Republic login sessions expire after 24 hours and may require login sooner if the server revokes the session. A new login is required once the session ends. * **Unpriced positions**: Some securities (particularly private market instruments) may not have a current price available from Trade Republic. * **No options or derivatives**: Derivative instruments are not imported. # Trading 212 Source: https://docs.sure.am/providers/trading212 Connect a Trading 212 investment account via API key Trading 212 is a European investment platform for stocks, ETFs, and fractional shares. Sure connects to Trading 212 using a read-only API key and imports your portfolio positions, order history, dividends, and cash transactions. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## What gets imported Sure imports one investment account per Trading 212 connection, containing: * Current positions with prices and quantities * Full order history (buys and sells) * Dividends * Cash transactions (deposits, withdrawals, interest, interest on free cash, fees) ## Setting up Trading 212 ### Step 1: Generate a Trading 212 API key 1. Open the Trading 212 web app or mobile app. 2. Go to **Settings → API**. 3. Generate a new API key. Trading 212 shows you an **API ID** and a **Secret Key**. 4. Copy both values — the Secret Key is only shown once. ### Step 2: Add the connection in Sure 1. In Sure, go to **Settings → Providers**. 2. Find the **Trading 212** section and expand it. 3. Paste your **API ID** and **Secret Key** into the corresponding fields. 4. Select your **environment** (Live account or Demo account). 5. Select your **account currency**. 6. Click **Save Configuration**. Sure begins syncing your Trading 212 account automatically after saving. ### Step 3: Set up your account After the first sync, your Trading 212 account appears in the setup queue. Click **Set up accounts** in the Trading 212 panel to link the discovered account to a Sure account. If you already have a manual investment account in Sure, you can link the discovered Trading 212 account to it instead of creating a new one. ## Environments Trading 212 offers two environments: | Environment | Description | | - | - | | Live account | Your real Trading 212 investment account | | Demo account | The Trading 212 practice account with virtual funds | Select the environment that matches the API key you generated. ## Syncing Sure syncs your Trading 212 account on the same schedule as other connected providers. You can also trigger a manual sync by clicking **Sync** in the Trading 212 panel under **Settings → Providers**. ## Troubleshooting ### Provider not configured If you see a "not configured" error when trying to add a Trading 212 account, Sure could not find an active Trading 212 connection. This alert is about the connection record, not a check that the credentials are valid. Go to **Settings → Providers → Trading 212**, enter your API ID and Secret Key, and save before adding accounts. ### API key needs attention Your API key may have been revoked or the credentials may no longer be valid. Generate a new API key from Trading 212 and update the connection in **Settings → Providers → Trading 212**. ### No account discovered yet After saving your API key, Sure needs to run an initial sync to discover your account. Click **Sync** from the Trading 212 panel and wait for it to complete, then click **Set up accounts**. ### Account needs setup A sync discovered your Trading 212 account, but it has not been linked to a Sure account yet. Click **Set up accounts** from the Trading 212 panel and complete the account setup. ## Cash transaction types Sure maps Trading 212 cash transaction types to the following labels: | Trading 212 type | Sure label | | - | - | | Deposit | Contribution | | Withdrawal | Withdrawal | | Interest | Interest | | Interest on free cash | Interest | | Lending interest | Interest | | Fee | Fee | ## Multi-currency accounts If your Trading 212 account holds instruments listed in a different currency from your account currency, Sure books each trade in the instrument’s currency. It derives a trade-level exchange rate when a usable net wallet value is available in the account currency; otherwise no trade-level rate is recorded. For example, a EUR-account holder buying a USD stock will see the trade recorded in USD with a rate derived from the wallet movement when those values are available. Sure also converts prices for instruments quoted in pence (GBX) — such as London-listed stocks — to pounds (GBP) to match the convention used by market data providers. ## Limitations * **Single connection per family**: Sure supports one Trading 212 connection per family account. * **Investment accounts only**: Trading 212 is an investment platform. Sure imports your portfolio and associated cash movements — it is not a general banking connection. * **Read-only access**: Sure uses only read permissions. No trades or account changes can be made through Sure. # Transaction history and import limits Source: https://docs.sure.am/providers/transaction-history How far back Sure requests transactions, what can limit the results, and how to fill gaps Sure does **not** always request all available history on the first sync. The result depends on your bank or provider, Sure's integration defaults, your settings, and pagination or processing limits. A correct current balance does not mean all historical transactions have been imported. > [!NOTE] > > Last verified: **3 October 2026**, against [Sure main at `14638a7`](https://github.com/we-promise/sure/tree/14638a70181d9adadc75e7d47d5b2975ee18bf46). These are source-verified defaults, not live-bank guarantees. Your installed release may behave differently. FinanceKit mobile-client query behavior was not audited. The Trade Republic row was reverified on **16 October 2026** against [Sure `25b5f48`](https://github.com/we-promise/sure/tree/25b5f484984959f2b11dd652fcf47af1656c4604). The Kraken row was reverified on **16 October 2026** against [Sure `3801111`](https://github.com/we-promise/sure/tree/38011119bd2926ddb4f98aa8b10075843e0d15e9). ## How to read this reference * **Initial request** assumes a fresh account without a custom date, unless stated otherwise. * **Limits** distinguish Sure's implementation limits from bank/provider availability. A 30-day request window can be repeated to retrieve years of history; it is not necessarily a total-history limit. * **Older history / later sync** explains whether subsequent syncs revisit older dates. Changing a start date or pressing Sync is not a universal backfill operation. * Source links point to the inspected implementation. Configuration fields mentioned below are not necessarily exposed in every setup screen. The tables cover all account-source adapter families at the verified commit, plus file-import routes. Market-price, exchange-rate, and property-valuation providers are not transaction import sources. ## Bank connections | Source | Sure initial request/default | Limits and caveats | Older history / later sync | | - | - | - | - | | Plaid (US and EU) [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/plaid.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/plaid_item/importer.rb) | 730 days requested outside development; 90 days in development. Investment requests use the same default lookback. | Bank availability can be shorter. Transaction sync pages through the history Plaid has stored; 730 days is the initial request, not a lifetime retention limit. | Initial Plaid history can arrive asynchronously. A larger initial request cannot retroactively expand an already initialized Plaid item. | | SimpleFIN [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/simplefin_item/importer.rb) | Walks backward in 60-day chunks, up to 6 requests (about 360 days). | Stops after two consecutive empty chunks; requested target clamped to one year. Sure comments describe commonly available 60–90 days, not a universal provider guarantee. | Custom start date is supported, but cannot overcome the six-chunk budget or upstream availability. Regular sync is incremental. | | Enable Banking [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/enable_banking_item/importer.rb) | 3 calendar months unless an explicit start date is configured. | 100-page guard per paginated fetch. Banks may expose older history only shortly after authorization, then restrict access to about 90 days. | Choose the intended initial date before the first transaction fetch. After stored transactions exist, normal sync uses last sync minus 7 days; changing the date alone does not guarantee backfill. | | Akahu [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/akahu_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/akahu.rb) | No start-date bound on a fresh account unless account/item start date is configured. | Fetches the full accessible range. Akahu personal apps have a 730-day pre-consent allowance; bank limits and production-app scope can differ. | Explicit account/item date overrides are honored. Otherwise subsequent fetches are incremental. | | Sophtron [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/sophtron_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/sophtron_item.rb) | 120 days by default. | Configured initial date is clamped to at most 3 years ago. Actual bank availability can be shorter. | Explicit sync window/item start supported; subsequent normal fetches use an overlap window. | | Lunch Flow [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/lunchflow_item/importer.rb) | Later of local provider-account creation minus 7 days and now minus 90 days: normally about 7 days for a new connection. | This is a Sure-side restriction, not proof of a Lunch Flow/bank history limit. | The importer does not consult the saved item sync\_start\_date. Subsequent syncs use last sync minus 7 days; older history needs an integration correction or file import. | | Mercury [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/mercury_item/importer.rb) | Later of local provider-account creation minus 7 days and now minus 90 days: normally about 7 days for a new connection. | Sure-side restriction; not a verified Mercury retention limit. | The importer does not consult the saved item sync\_start\_date. Subsequent syncs use last sync minus 7 days. | | Brex [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/brex_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/brex_item/syncer.rb) | Without a passed sync window: later of local provider-account creation minus 7 days and now minus 90 days. Normally about 7 days. | Applies to card and cash transaction fetches. Sure-side default, not an upstream retention claim. | An explicitly passed sync.window\_start\_date overrides this calculation; do not assume the saved item date alone does. | | Fio [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/fio_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/config/initializers/fio.rb) | 90 days by default; configurable account/item date or FIO\_INITIAL\_HISTORY\_DAYS. | Older data requires the bank’s temporary full-history authorization. When refused, Sure records the lock and confines later attempts to the allowed recent window. | Unlock history at Fio and use the connection recovery path; Sure tracks covered-from/through dates and can backfill an unfinished range. | | Monobank [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/monobank_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/config/initializers/monobank.rb) | 31 days by default; account/item start date or MONOBANK\_INITIAL\_HISTORY\_DAYS can extend target. | 31-day statement windows; default budget 4 statement requests across the connection per sync. | Older requested history is accumulated across later syncs, not necessarily returned on the first run. | | Up Bank [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/up_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/up.rb) | 90 days unless account/item date is configured. | Sure default, not a claim that Up only stores 90 days. Provider pagination follows available results. | Account/item start date overrides are honored; otherwise normal sync uses a recent overlap. | | Wise [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/wise_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/controllers/wise_items_controller.rb) | 365 days by default, or an explicit sync/item date. Optional import-all-history mode. | Full-history statements start at the reported balance creation date, falling back to 2000-01-01. Transfers/activities and statements have distinct fetch paths; API permissions still matter. | Use import-all-history or the appropriate explicit date. Existing statement history can trigger a 7-day incremental overlap; toggling a flag is not a universal forced-backfill guarantee. | | Redbark [Source 1](https://github.com/we-promise/sure/blob/73917b2f78bd7c09f4ba7ad6df18c3be2c5adce4/app/models/redbark_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/73917b2f78bd7c09f4ba7ad6df18c3be2c5adce4/app/models/redbark_account.rb) | 90 days unless a per-account sync\_start\_date is set during setup. Sure caps the lookback at 2,550 days for safety; its source records Redbark rejecting dates 2,555 or more days back. A stored date that has since drifted outside the rolling 2,550-day window is clamped at fetch time rather than sent as-is. | Pages through results and subdivides saturated date windows; safety limits can still fail a too-large fetch. | Incremental fetching requires both stored transactions and a recorded last-sync time on the connection; it then uses last sync minus 7 days. Otherwise, it uses the configured date (clamped to the rolling window) or the 90-day default. The setup field and cap are on main in #4306, not stable v0.7.5-hotfix.2 as of October 22, 2026. | ## Brokerages and investments | Source | Sure initial request/default | Limits and caveats | Older history / later sync | | - | - | - | - | | SnapTrade [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/snaptrade_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/snaptrade.rb) | Account start date, else broker-reported first transaction date, else 1,095 days ago. | The three-year value is a fallback, not a hard oldest-date cap. Brokerage coverage and asynchronous activity retrieval can limit the first result. | Full-history versus incremental mode depends on stored activity and sync markers; established accounts normally use a 30-day overlap. | | Questrade [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/questrade_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/questrade.rb) | 1,095 days unless an account start date is configured. | Requested range is split into 30-day inclusive windows; this per-request restriction is not a 30-day total-history limit. | Configured start takes precedence; established accounts otherwise use last activity sync minus 30 days. | | Interactive Brokers (IBKR Flex) [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/ibkr_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/ibkr_flex.rb) | Whatever dates and sections are included in the configured Flex statement. | Sure downloads and parses the report; it does not independently ask for all IBKR history. | Configure/export an appropriate historical report. Missing statement sections cannot be reconstructed by Sure. | | Trading 212 [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/trading212_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/trading212.rb) | No date cutoff passed to history endpoints; orders, dividends and cash transactions are paginated. | 200-page cap × 50 rows per endpoint (nominally 10,000 per stream). Upstream availability still applies. | A very active account can exceed the page cap even without a date cutoff. | | Trade Republic [Source 1](https://github.com/we-promise/sure/blob/25b5f484984959f2b11dd652fcf47af1656c4604/app/models/trade_republic_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/25b5f484984959f2b11dd652fcf47af1656c4604/app/models/provider/trade_republic_client.rb) | Fetches timeline topics without a fixed lookback date on first sync. | Up to 50 pages per pagination pass for each timeline topic; head and backfill passes can both run in one sync; up to 200 detail enrichments per sync; raw merged timeline cache capped at 5,000 events per Sure provider account. | Sure stores a per-topic pagination cursor after each sync and continues the history backfill from that cursor on the next sync, working backwards until the topic is exhausted or the 5,000-event cache cap is reached. Backfill stops after five consecutive failed attempts without cursor progress; a websocket failure during a backfill carries the cursor forward so the next sync resumes at the failed page rather than starting over. Do not describe this as guaranteed all-time history, or the raw-cache cap as a blanket deletion of already imported entries. | | Indexa Capital [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/indexa_capital_item/importer.rb) | No transaction-history fetch in the current importer. | Current path imports accounts, balances and holdings. Presence of activity-processing classes/start-date fields does not mean historical activities are fetched. | Use exported transaction data where supported; no promised date-based backfill through this sync path. | ## Crypto exchanges | Source | Sure initial request/default | Limits and caveats | Older history / later sync | | - | - | - | - | | Coinbase [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/coinbase_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/coinbase.rb) | Up to 100 transactions per wallet/account. | 100 is a total returned-record cap in paginated\_get, not merely the page size. Zero-balance non-USD wallets can also be skipped. | The history fetch does not use the saved sync\_start\_date; an earlier date alone cannot lift the cap. | | Kraken [Source 1](https://github.com/we-promise/sure/blob/38011119bd2926ddb4f98aa8b10075843e0d15e9/app/models/kraken_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/38011119bd2926ddb4f98aa8b10075843e0d15e9/app/models/kraken_account/processor.rb) | No start bound unless sync\_start\_date is configured; fetches both TradesHistory and ledgers. Quantity and cash independently prefer their ledger side (net of fees), falling back to TradesHistory where that side is absent. | 200 pages × 50 records each: up to 10,000 trades and 10,000 ledger records per fetch. Unprotected trades can be corrected when missing ledger sides arrive. | Configured start supported, subject to the independent record caps. Existing unprotected trades can be corrected once their missing ledger sides are fetched; user-protected trades are preserved. | | CoinSpot [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/coinspot_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/coinspot.rb) | 365 days unless sync\_start\_date is configured. | Order history is requested in 30-day windows, subdividing saturated windows. A saturated single day fails rather than being accepted as complete. Other history endpoint availability still applies. | Set an earlier date to request a wider range; cannot promise upstream completeness. | | Binance — spot [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/binance_account/processor.rb) | 24 hours by default; configured start date enables an older initial walk. | 24-hour API windows with trade pagination. Sure probes discovered/cached asset symbols against a fixed set of quote currencies; this is not an exhaustive historical pair inventory. | Choose the start date before initial history fetch. Cached pairs subsequently advance by trade ID. | | Binance — futures [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/binance_account/processor.rb) | 7 days by default; configured start is clamped to 180 days ago. | 7-day fetch windows. Current implementation enforces a six-times-30-day oldest-date clamp. Pair-discovery limits also apply. | An earlier configured date cannot override the 180-day clamp. | | Binance — P2P [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/binance_account/processor.rb) | 30 days by default, or configured start date. | Walks history in 30-day request windows. Do not confuse this with all Binance wallet transfers, deposits, withdrawals or earn activity. | With cached P2P trades, advances from their latest timestamp. | | CoinStats — exchanges [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/coinstats_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/coinstats.rb) | No from-date unless sync\_start\_date is set; paginated exchange history with portfolio-history fallback. | Actual history depends on what CoinStats has ingested and exposes for the exchange. No universal upstream age guarantee verified. | Explicit start is passed to exchange/portfolio endpoints. | | CoinStats — wallets [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/coinstats_item/importer.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/coinstats.rb) | One bulk wallet-transactions response; no date or pagination parameters passed by this path. | No evidence that this response represents all-time wallet history; the exchange pagination logic does not apply here. | Do not promise an earlier saved date will page through older wallet activity. | ## On-chain wallets and Apple FinanceKit | Source | Sure initial request/default | Limits and caveats | Older history / later sync | | - | - | - | - | | On-chain — Bitcoin [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/onchain/history_budget.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/onchain/bitcoin_adapter.rb) · [Source 3](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/mempool_space.rb) | Recent address activity, bounded by a default 10-page history budget. | Page size 25 for confirmed history; unconfirmed activity and source response shape are separate. This is an address integration, not a full xpub wallet scan. | ONCHAIN\_HISTORY\_MAX\_PAGES can raise budget up to 200. Date filter only removes fetched older records; it does not remove pagination limits. | | On-chain — EVM [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/onchain/history_budget.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/onchain/chains.rb) · [Source 3](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/onchain/evm_adapter.rb) · [Source 4](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/provider/etherscan.rb) | Default 10-page budget per history stream; Ethereum, Base, Arbitrum, Optimism, Polygon and Gnosis. | Blockscout page semantics differ from optional Etherscan (1,000 rows/page). Native and token activity have separate streams; not an all-chain all-history guarantee. | History budget can be raised up to 200 pages; usable history depends on explorer coverage and source availability. | | On-chain — Solana [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/onchain/history_budget.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/onchain/solana_adapter.rb) | Default 25 transaction-detail reads per sync from bounded signature discovery. | Signature-source limits and detail budget can omit older activity even when balances are correct. | History page setting scales the detail budget; no guarantee of complete archival history. | | Apple FinanceKit [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/financekit_batch.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/financekit_item.rb) | Server receives device-supplied batches; there is no server-side bank lookback request. | Availability is constrained by FinanceKit data and the time range the user consents to share. Mobile-client query behavior was not audited here. | Check Wallet/FinanceKit sharing scope and device sync; do not assign a universal 90-day limit. | ## Files and statements | Source | Sure initial request/default | Limits and caveats | Older history / later sync | | - | - | - | - | | CSV transactions / trades [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/transaction_import.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/trade_import.rb) · [Source 3](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/import.rb) · [Source 4](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/controllers/imports_controller.rb) · [Source 5](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/import/account_mapping.rb) | Dates contained in the supplied file; no provider-style lookback cutoff found. | Validation, mapping, duplicate handling and import size apply; base Import row ceiling is 10,000. A file cannot supply missing transactions it does not contain. | Useful for older history missing from a bank feed. Linked-account targeting is supported by backend; general mapping dropdown is manual-account-only. | | QIF / Mint / Actual / YNAB / Sure export imports [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/qif_import.rb) · [Source 2](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/mint_import.rb) · [Source 3](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/actual_import.rb) · [Source 4](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/ynab_import.rb) · [Source 5](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/sure_import.rb) | History contained in the supplied export; no uniform 90-day provider cutoff. | Each format has its own supported fields, validation and account mapping. Metadata-only imports (accounts/categories/rules/merchants) are not transaction backfills. | Import historical exports through their matching importer; review account mapping and overlaps. | | PDF / document statements [Source 1](https://github.com/we-promise/sure/blob/14638a70181d9adadc75e7d47d5b2975ee18bf46/app/models/pdf_import.rb) | Dates and transactions actually extracted from the uploaded statement. | Statement date coverage, extraction accuracy and validation matter; this is not a provider-history request. | Review extracted rows and reconciliation before publishing. | ## Recovering older history 1. Check the source's row above and its setup page. Choose your intended initial date **before the first fetch** where the integration supports it. 2. Distinguish missing older history from an incomplete first sync. Some providers deliver data asynchronously or spread historical requests over multiple syncs. 3. Check bank-specific authorization limits. [Enable Banking explains](https://enablebanking.com/docs/faq/) that some banks allow deeper history only briefly after authorization, often about an hour, and then restrict later requests to approximately 90 days. Consent duration and transaction-history depth are different limits. 4. If the connection cannot retrieve the missing range, use a supported historical export. See [CSV and other file imports](/guides/app-features/csv-imports#importing-older-history) for preparation and limitations. Do not delete or unlink an account merely to test history recovery. Review overlapping dates and do not assume automatic deduplication between a bank feed and a file import. ## Provider references * [Plaid transaction history](https://plaid.com/docs/transactions/) and [initial-history API constraints](https://plaid.com/docs/api/products/transactions/) * [Enable Banking historical access FAQ](https://enablebanking.com/docs/faq/) * [Akahu accessible date ranges](https://developers.akahu.nz/docs/accessing-transactional-data) * [Apple FinanceKit consent and time range](https://developer.apple.com/financekit/) ## Maintaining this reference When an integration changes its initial date, pagination budget, or backfill behavior, update its row and the verification date/commit together. Keep the comparison here and setup instructions on the individual provider pages, rather than copying the entire table into the FAQ. # Up bank Source: https://docs.sure.am/providers/up-bank Connect your Up bank account to Sure Up bank is an Australian neobank. Sure connects to it directly using the Up API, syncing your accounts, balances, and transactions automatically. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works 1. Generate a personal access token in the Up app 2. Paste the token into Sure 3. Sure discovers your Up accounts and begins syncing balances and transactions 4. Categories you have set in the Up app are mapped to your Sure categories on import ## Setting up Up bank 1. Open the Up app on your phone 2. Go to **Settings > API** and create a personal access token 3. In Sure, go to **Settings > Bank sync**, find the **Up** panel, and paste the token 4. Link each discovered account to an existing Sure account or create a new one ## Features ### Account syncing * **Account listing**: All Up accounts (spending and savers) with current balances * **Transaction history**: Transactions are imported with date, amount, description, and category * **Deduplication**: Transactions are matched by their Up transaction ID, so re-syncing never creates duplicates ### Category mapping When you import transactions from Up, Sure maps Up's category slugs to your existing Sure categories automatically. This means transactions you have already tagged in the Up app arrive in Sure with the correct category applied — no manual re-categorisation needed. The mapping uses high-confidence matches only. Up categories that do not have a clear Sure equivalent (for example, Booze, Pets, Apps & Games, Life Admin, and Technology) are left uncategorised so you can apply your own rules or let the AI assistant categorise them. If you have already set or locked a category on a transaction in Sure, a re-sync will not overwrite it. To turn off automatic category mapping, open the account in Sure, go to its settings, and disable the **Automatic category mapping** toggle. When disabled, imported transactions carry no auto-assigned category and are left for your rules or the AI categorizer to handle. The raw Up metadata is still imported; only the auto-category assignment is skipped. > [!NOTE] > > Category mapping only applies to your existing Sure categories. If your family has no categories set up yet, transactions will arrive uncategorised until you create categories through the normal setup flow. ## Limitations * Australian accounts only * Personal access tokens are scoped to a single Up account holder * Data is read-only; Sure never writes anything back to Up ## Troubleshooting **"Configure Up in provider settings first" error**: If you see this alert when trying to add an Up account, the selected connection has no configured personal access token. Go to **Settings > Providers > Up**, paste your token, and save before adding accounts. **Missing categories after sync**: Check that you have categories configured in Sure under **Settings > Categories**. If no categories exist, Up transactions arrive uncategorised by design. **Transactions not updating**: Try triggering a manual sync from the account card. If the issue persists, check that your personal access token is still valid in the Up app. For more detail, see the [Up API documentation](https://developer.up.com.au/). # Wise Source: https://docs.sure.am/providers/wise Connect your Wise multi-currency account using a personal API token Wise integration connects your Wise multi-currency account to Sure using a personal API token. Sure syncs your currency balances, Jars (savings pots), transfers, and Wise Assets activity directly from the Wise API — no OAuth flow required. See [Transaction history and import limits](/providers/transaction-history) for initial sync defaults, history limits, and options for older transactions. ## How it works 1. You create a personal API token in Wise and paste it into Sure 2. Sure fetches the profiles (personal and/or business) available to that token 3. You choose which profile(s) to connect — each becomes its own connection in Sure 4. Sure discovers every currency balance and Jar under the connected profile(s) 5. You link each discovered balance to a new or existing Sure account 6. Syncs then run automatically, pulling balances, transfers, and Jar activity ## Setting up Wise 1. Sign in to your Wise business account at [wise.com](https://wise.com) (personal API tokens are issued from business account settings, even if you're only connecting a personal profile) 2. Go to **Settings → Connect and manage apps → Developer tools → API tokens** (requires two-factor authentication on the account) 3. Create a new personal API token and choose an access level: **read only** lets Sure read balances, transfers, and Jar activity; **full** additionally allows the token to authorize recipients and transfers, so prefer read-only unless you need that capability elsewhere 4. In Sure, go to **Settings > Providers**, find the **Wise** panel, and paste the token 5. If the token has access to more than one profile (for example, a personal and a business profile), select which ones to connect — Sure creates a separate connection for each 6. Open **Set Up Accounts** on the new connection and link each currency balance to a Sure account 7. To enable full transaction history including incoming payments, complete the [SCA setup](#strong-customer-authentication-sca) below > [!NOTE] > > For testing, Wise provides a sandbox environment at `https://api.wise-sandbox.com` (the V2 sandbox host; the legacy `api.sandbox.transferwise.tech` URL was retired). Set `WISE_BASE_URL` in your Sure environment to point at it instead of the default live API (`https://api.wise.com`). ## Features ### Multi-currency balances * **Standard balances**: one balance per currency held in your Wise account, refreshed (including reserved amount) on every sync * **Jars (savings pots)**: synced alongside standard balances and mapped to a savings-type account in Sure * New balances discovered on a sync are shown as "needs setup" until linked to a Sure account ### Transaction syncing * The first sync imports history from the date you configure (or 365 days by default); later syncs use a 7-day lookback from the last successful sync * Transactions are fetched from the Wise balance-statement endpoint, which covers both incoming and outgoing payments. The statement endpoint requires [SCA](#strong-customer-authentication-sca) — without it, Sure falls back to the outgoing-only transfers endpoint, so incoming payments will be missing until SCA is configured * Transfers are matched to their linked balance by Wise balance ID, so Jars that share the same currency are still tracked as separate accounts * Cross-currency incoming transfers use the amount actually received, not the amount sent * When a same-currency transfer includes a fee, the fee is imported as a separate "Wise fee" transaction ### Jar activity * Deposits and withdrawals to a Jar are imported as "Transfer to Jar" / "Transfer from Jar" transactions * Interest and Wise Assets fees are imported automatically * Transfers between a standard balance and a Jar are automatically linked as Sure Transfers, so the same movement is never double-counted as separate income and expense ### Multiple profiles If your Wise account has both personal and business profiles, you can connect several profiles from the same token at once. Each profile is a separate connection that can be synced, updated, or disconnected independently. ## Strong Customer Authentication (SCA) Wise requires Strong Customer Authentication on the balance-statement endpoint. SCA uses an RSA keypair: Sure signs a one-time challenge with the private key, and Wise verifies it against the public key you register in your Wise account. Without SCA, the statement endpoint returns 403 and Sure falls back to the outgoing-only transfers endpoint, so incoming payments will not appear. ### Enabling SCA > [!WARNING] > > SCA keypair generation requires Active Record encryption to be configured. On a self-hosted instance that has not set the `ACTIVE_RECORD_ENCRYPTION_*` environment variables or a `SECRET_KEY_BASE`-derived equivalent, the **Generate SCA keypair** button will return a validation error. See [encryption keys for bank sync](/self-hosting#encryption-keys-for-bank-sync) in the self-hosting guide before proceeding. 1. In Sure, go to **Settings > Providers** and open the Wise panel for the connection 2. Click **Generate SCA keypair** — Sure creates a 2048-bit RSA keypair and stores the private key encrypted at rest 3. Copy the public key that appears in the panel 4. In Wise, go to **Settings → Connect and manage apps → Developer tools → Public keys → Add public key** and paste the public key 5. Run a sync — the statement endpoint should now succeed and incoming payments will be imported > [!WARNING] > > Generating a new keypair does not automatically revoke the previous public key in Wise. If you regenerate the keypair in Sure (for example, after a key rotation), remove the old public key from Wise manually and register the new one. ### Troubleshooting SCA **Incoming payments are missing**: SCA is not yet configured or the public key has not been registered with Wise. Follow the steps above. **Statement fetch fails after configuring SCA**: confirm the public key in Wise matches the one shown in the Sure Wise panel. If the key was regenerated, the old public key must be removed from Wise and the new one registered. ## Limitations * Uses a Wise personal API token rather than OAuth; the token carries whatever account access you grant it in Wise * Wise Assets (investment) balances are not tracked as accounts — only fees charged against them are imported * Each discovered currency balance must be linked to a Sure account manually after the first sync; balances aren't created automatically * Incoming payments only sync after [SCA is configured](#strong-customer-authentication-sca) ## Troubleshooting **"No Wise connection configured" error**: If you see this alert when trying to add a Wise account, Sure could not find an active Wise connection for the request. The selected connection may have been removed; this alert is not itself a token-validity check. Go to **Settings > Providers > Wise**, paste your personal API token, and save before adding accounts. **Invalid token / connection requires update**: your API token was revoked, is invalid, or lacks permissions (Wise personal API tokens don't expire on their own). When Wise rejects the token with a 401 or 403, Sure marks the connection as requiring an update and the sync fails — the connection card shows a **Reconnect** prompt instead of a green "Connected" status. Create a new personal token in Wise and update it in the Wise provider panel. **No profiles found**: the token doesn't have access to any Wise profile. Check the token's permissions in Wise and try again. **A currency balance is missing**: run a sync, then check **Set Up Accounts** on the connection — new balances only become Sure accounts once you link them. **Incoming payments are missing**: the balance-statement endpoint requires SCA. Follow the [SCA setup steps](#strong-customer-authentication-sca) to generate a keypair and register the public key with Wise. **Connection appears under Available instead of Your connections**: after a successful setup, the Wise panel should move to the "Your connections" section of **Settings → Providers** and show a status pill, sync button, and last-synced line. If it stays in Available, the connection was not saved. Re-enter the API token and save again. # Quickstart Source: https://docs.sure.am/quickstart Get started with Sure in minutes Get your Sure account up and running in three simple steps. ## 1. Create your account Navigate to [localhost:3000](http://localhost:3000) and click **Sign Up**. Complete the setup screens to configure your login details and preferences. ## 2. Add your first account Click **+ Add Account** and select an account type: * **Cash** for checking/savings accounts * **Credit Card** for credit cards * **Investment** for brokerage accounts * **Loan** for mortgages or other debts Enter your account name and current balance, then click **Create Account**. ## 3. Record a transaction Go to **Transactions** in the sidebar and click **+ New Transaction**. Choose a type: * **Expense** for spending money * **Income** for receiving money * **Transfer** for moving money between accounts Fill in the details and click **Add transaction**. ## Next steps > **[Complete guide](/guide)** > > Learn about account types, investment tracking, and advanced features > **[Self-hosting](/self-hosting)** > > Deploy Sure with Docker on your own infrastructure ## Development setup Want to contribute to Sure? Set up your local development environment. Run the full test suite after setup to confirm everything is working: ```bash theme={null} bin/rails test ``` The suite should report zero failures and zero errors. If you are using the devcontainer, the PostgreSQL connection is configured with `username:` (the Rails-documented key), so no authentication errors should appear. The devcontainer runs `pgvector/pgvector:pg16-trixie` as its database image rather than plain `postgres:16`. This is a drop-in replacement that ships the `vector` extension, which supplies the vector-storage prerequisite for document import. You still need to configure the chosen vector-store and embedding provider; PDF statement processing also requires a suitable AI provider. After running `bin/setup`, you can optionally load demo data with: ```bash theme={null} rake demo_data:default ``` By default this appends a new demo family without touching existing data (`SKIP_CLEAR=1`). To wipe all existing data first and start fresh, set `SKIP_CLEAR=0`: ```bash theme={null} SKIP_CLEAR=0 rake demo_data:default ``` You can also pin the random seed to reproduce the same dataset across runs: ```bash theme={null} SEED=12345 rake demo_data:default ``` > [!NOTE] > > Demo data is only available when running Sure in development mode, not in production or self-hosted deployments. ### Design system previews Sure uses [Lookbook](https://lookbook.build/) to render component previews. After starting `bin/dev`, open `/design-system` in your browser to browse and preview all `DS::*` components. The preview routes are only available outside of production. If a preview returns an error, confirm you are running in development mode. ### Form action buttons Use these conventions when adding action buttons to forms built with Sure’s `styled_form_with` helper: * A form with one action ends in `f.submit`, which renders a full-width primary `DS::Button`. Do not pass `class:` to `f.submit` — it is ignored. * A form with Cancel and a primary action ends in a right-aligned pair of natural-width buttons: Cancel (`variant: :secondary` or `:ghost`), then the primary (`type: :submit`). The variant carries the hierarchy, not the width. ```erb theme={null}
<%= render DS::Button.new(text: t(".cancel"), variant: :secondary, data: { action: "DS--dialog#close" }) %> <%= render DS::Button.new(text: t(".save"), type: :submit) %>
``` * Do not use `f.submit` in a pair — it is always full-width and ignores `class:`. Render the primary button explicitly with `type: :submit` instead. * A destructive single action uses `DS::Button` with `full_width: true`, `type: :submit`, and `variant: :destructive` — `f.submit` always renders primary and cannot be used here. * Keep the default button size. `size: :sm` text buttons are 28 px tall and the 44 px coarse-pointer target only applies to icon-only buttons. * When a `DS::Dialog`'s buttons do not submit a form, use `dialog.with_action`. Pass `cancel_action: true` to make a button close the dialog. * Amount inputs stay left-aligned. Use `numeric: true` for displayed figures. Inputs inside a column of figures, such as the budget grid, can also be right-aligned. ### Setup guides > **[Mac setup](https://github.com/we-promise/sure/wiki/Mac-Dev-Setup-Guide)** > > Development setup guide for macOS > **[Linux setup](https://github.com/we-promise/sure/wiki/Linux-Dev-Setup-Guide)** > > Development setup guide for Linux > **[Windows setup](https://github.com/we-promise/sure/wiki/Windows-Dev-Setup-Guide)** > > Development setup guide for Windows > **[Dev containers](https://code.visualstudio.com/docs/devcontainers/containers)** > > Use VS Code dev containers for isolated development # Roadmap Source: https://docs.sure.am/roadmap What Sure is working on now, planning next, and exploring for the future Sure's roadmap is organized into three phases. Items have one of three statuses: **In progress** means active work is happening now, **Planned** means the item is scoped and prioritized, and **Exploring** means the team is researching and gathering signal before committing. ## Short term Stabilize and polish the core. ### Reliability, performance, and technical debt **In progress** — Make the everyday experience dependable, fast, and easier to maintain. ### Web UX/UI polish **Planned** — Refine the web experience around the details that make Sure feel clear and cohesive. ### AI controls and transparency **Planned** — Give people understandable controls and visibility into how AI works with their data. ### Documentation and onboarding **Planned** — Help new people get value from Sure quickly, whether they use the hosted app or self-host it. ### Mobile app planning and delivery **Planned** — Establish and ship a thoughtful mobile experience for managing money on the go. ### Quality-focused release cadence **Planned** — Build a sustainable rhythm for shipping improvements with confidence. ## Medium term Expand personal-finance capability. ### First-class AI **Exploring** — Make AI a useful, transparent part of the core financial workflow. ### Transaction intelligence **Planned** — Turn transaction data into better organization, context, and decisions. ### Savings, retirement, and investments **Planned** — Support more of the financial picture beyond day-to-day budgeting. ### Scenario simulation **Exploring** — Help people understand the possible outcomes of financial choices before they make them. ### Localization and country support **Planned** — Make Sure useful and natural for people across more countries, currencies, and financial systems. ### Themes and customization **Planned** — Let people shape their financial workspace to fit the way they think and work. ## Long term Open the platform carefully. ### External-agent integration and execution **Exploring** — Create safe, permissioned ways for outside agents to work with Sure. ### Agent-assisted cleanup and memory **Exploring** — Use agents to reduce financial-data maintenance while keeping people in control. ### Polished mobile ecosystem **Planned** — Grow mobile into a complete, reliable part of the Sure experience. ### Improved macOS and desktop experience **Planned** — Make Sure feel at home across desktop platforms and workflows. ### Business finance support **Exploring** — Carefully extend Sure to the needs of people managing business finances. # Self-hosting with Docker Source: https://docs.sure.am/self-hosting Deploy Sure on your own infrastructure using Docker Compose This guide shows you how to set up, update, and maintain a self-hosted Sure application with Docker Compose. ## Prerequisites * Docker Engine installed and running * Basic familiarity with the command line ## Installation ### Install Docker 1. Follow the [official Docker installation guide](https://docs.docker.com/engine/install/) 2. Start the Docker service on your machine 3. Verify the installation: ```bash theme={null} docker run hello-world ``` If Docker is set up correctly, this command will succeed. ### Create your application directory Create a directory where your app will run: ```bash theme={null} mkdir -p ~/docker-apps/sure cd ~/docker-apps/sure ``` ### Download the Docker Compose file Download the sample compose file from the Sure repository: ```bash theme={null} curl --fail --location --silent --show-error --output compose.yml https://raw.githubusercontent.com/we-promise/sure/main/compose.example.yml ``` This creates a `compose.yml` file in your current directory with the default configuration. ## Configuration By default, the `compose.example.yml` file runs without any configuration. For production deployments or if you're running outside of a local network, follow these steps to add security. ### Email configuration To enable email notifications and password resets, configure SMTP settings in your `.env` file: ```txt theme={null} SMTP_ADDRESS=smtp.example.com SMTP_PORT=587 SMTP_DOMAIN=example.com SMTP_USERNAME=your-username SMTP_PASSWORD=your-password SMTP_AUTHENTICATION=plain SMTP_ENABLE_STARTTLS_AUTO=true ``` #### SSL/TLS options For SMTP servers with custom SSL certificates or self-signed certificates: **Skip TLS verification** (not recommended for production): ```txt theme={null} SMTP_OPENSSL_VERIFY_MODE=none ``` **Use custom CA certificate**: ```txt theme={null} SSL_CA_FILE=/path/to/ca-certificate.pem ``` The `SSL_CA_FILE` option allows you to specify a custom CA certificate file for SSL verification when connecting to SMTP servers with self-signed or internal certificates. ### Create an environment file Create a `.env` file where Docker will read environment variables: ```bash theme={null} touch .env ``` ### Generate a secret key Generate a secret key using one of these methods: **With OpenSSL:** ```bash theme={null} openssl rand -hex 64 ``` **Without OpenSSL:** ```bash theme={null} head -c 64 /dev/urandom | od -An -tx1 | tr -d ' \n' && echo ``` Save the generated key for the next step. ### Configure environment variables Open the `.env` file in your text editor and add: ```txt theme={null} SECRET_KEY_BASE="your-generated-secret-key-here" POSTGRES_PASSWORD="your-database-password-here" ``` Replace the placeholder values with your generated secret key and a secure database password. ### Optional: expose Sure with Cloudflare Tunnel If you want to reach your self-hosted instance from the public internet without opening router ports, you can put a [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/) in front of the `web` container. 1. Create a tunnel in Cloudflare Zero Trust and copy the tunnel token. 2. Add the token to your `.env` file: ```txt theme={null} CLOUDFLARE_TUNNEL_TOKEN="your-cloudflare-tunnel-token" ``` 3. Edit `compose.yml` and set: ```yaml theme={null} RAILS_ASSUME_SSL: "true" ``` This tells Sure to generate HTTPS URLs correctly when Cloudflare terminates TLS before forwarding traffic to the container over HTTP. 4. Add a `cloudflared` service to your `compose.yml`: ```yaml theme={null} cloudflared: image: cloudflare/cloudflared:latest restart: unless-stopped command: tunnel run environment: TUNNEL_TOKEN: ${CLOUDFLARE_TUNNEL_TOKEN} depends_on: - web networks: - sure_net ``` 5. In the Cloudflare tunnel dashboard, add a public hostname such as `sure.example.com` and point it at the internal Docker service: ```txt theme={null} Service type: HTTP URL: http://web:3000 ``` 6. Start the tunnel connector: ```bash theme={null} docker compose up -d cloudflared docker compose logs cloudflared --tail 20 ``` Look for a successful tunnel registration message in the logs, then open `https://sure.example.com`. > [!NOTE] > > Cloudflare should connect to `http://web:3000`, not `https://web:3000`. Sure speaks plain HTTP inside Docker and relies on `RAILS_ASSUME_SSL` to know the original request was HTTPS. > [!TIP] > > If you enable passkeys or security keys on a public hostname, also set `WEBAUTHN_RP_ID` and `WEBAUTHN_ALLOWED_ORIGINS` in `.env` to match that hostname. > [!WARNING] > > If you only want Cloudflare Tunnel access, do not leave port `3000` broadly exposed to the internet. Keep the host firewall closed or bind the published port more narrowly. ### Passkeys and security keys If people will use passkeys, Touch ID, Windows Hello, or hardware security keys as MFA credentials, pin the WebAuthn relying party settings in `.env`: ```txt theme={null} WEBAUTHN_RP_ID="example.com" WEBAUTHN_ALLOWED_ORIGINS="https://sure.example.com" ``` `WEBAUTHN_RP_ID` should usually be the registrable domain, not a full URL. For example, use `example.com` for `https://sure.example.com`. `WEBAUTHN_ALLOWED_ORIGINS` must include the full origin where people access Sure, including `https://`. > [!WARNING] > > Changing `WEBAUTHN_RP_ID` after people register credentials can make existing passkeys and security keys unavailable. Configure it before rollout and keep it stable across reverse proxy, domain, and hostname changes. See [Passkeys and security keys](/guides/app-features/passkeys) for user setup steps. Passwordless passkey login is enabled by default: ```txt theme={null} AUTH_PASSKEY_LOGIN_ENABLED="true" ``` Set it to `"false"` if you only want registered passkeys and security keys to work as a second factor after email/password sign-in. ### Reverse proxy sub-path deployments Sure can be served under a path prefix by a reverse proxy — for example `https://home.example.com/sure` instead of the root. The web app works at that address with no extra configuration. When using the macOS desktop app with a sub-path deployment, enter the full mounted URL (including the path prefix) when adding the server. The app probes the health endpoint at the address you enter and walks up to the origin to find the correct mount point, so pasting a deep link such as `https://home.example.com/sure/sessions/new` also works. > [!NOTE] > > The `RAILS_RELATIVE_URL_ROOT` environment variable tells Rails that it is mounted under a prefix. Set it to the path portion if your reverse proxy strips the prefix before forwarding, or configure the proxy to preserve the path and leave the variable unset. ### Import size variables By default, Sure NDJSON imports are limited to a fixed maximum file size. Self-hosted admins can raise this limit with: ```txt theme={null} SURE_IMPORT_MAX_NDJSON_SIZE_MB=50 ``` This applies to both the GUI upload and the API upload paths. If you do not set this variable, the default limit is used. ### Encryption keys for bank sync When you configure a bank sync provider (such as Plaid, SimpleFIN, or Brex) on a self-hosted instance that has not set explicit Active Record encryption keys, Sure shows a warning before you save your credentials: > **Encryption keys missing** — This self-hosted install has not configured explicit Active Record encryption keys. Configure `primary_key`, `deterministic_key`, and `key_derivation_salt` before saving provider credentials in production. The trust statement on the provider form also changes to remind you that credentials will not be stored encrypted until you configure those keys. If encryption is not configured at all when you visit **Settings > Bank Sync**, Sure blocks access and redirects you with the same "Encryption keys missing" message. To resolve the warning, add these three variables to your `.env` file before saving any provider credentials in production: ```txt theme={null} ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=your-primary-key ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY=your-deterministic-key ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=your-key-derivation-salt ``` You can generate values with `openssl rand -hex 32` for each one. Once all three are present, the warning disappears and credentials are stored encrypted. > [!NOTE] > > Encryption is also required to generate a Wise SCA keypair. Without it, the **Generate SCA keypair** button returns a validation error. See [Enabling SCA](/providers/wise#enabling-sca) for details. > [!NOTE] > > Sure can derive these values from `SECRET_KEY_BASE` automatically, so the warning only appears when none of the three environment variables are explicitly set. If you already set `SECRET_KEY_BASE`, encryption is still active — you will only see the warning if you want to use dedicated keys instead. See [Turning on Active Record encryption after first boot](#turning-on-active-record-encryption-after-first-boot) if you need to backfill existing data. ### Brand logo variables Sure uses [Brandfetch](https://brandfetch.com/) to show each provider's own icon on Bank Sync cards, drawers, and Accounts connection cards, as well as merchant and institution logos throughout the app. Set your Brandfetch client ID to enable these logos: ```txt theme={null} # Required to show provider, merchant, and institution logos from Brandfetch BRAND_FETCH_CLIENT_ID=your-brandfetch-client-id # Optional: fetch larger (120 px) icons instead of the default 40 px BRAND_FETCH_HIGH_RES_LOGOS=false ``` When `BRAND_FETCH_CLIENT_ID` is not set, Bank Sync cards and Accounts fall back to each provider's initials on a colored background. You can also toggle high-resolution logos from **Settings → Self-Hosting** in the UI. Merchant logo discovery works as follows: * When Brandfetch is configured, Sure generates a logo from the website domain when a provider merchant is saved with a website but no logo. This includes Akahu or Plaid merchants when a website is supplied, and merchants whose website comes from the AI detector. * A logo that the provider already supplies (for example, from Plaid or CoinStats) is never replaced by a Brandfetch logo. * After a family sync, Sure attempts to fill missing logos for provider merchants linked to that family’s transactions that already have a website. This also runs before AI merchant enhancement and does not require an LLM. It does not backfill every merchant record in the instance. ### Application name variables By default, Sure uses "Sure" as the product name and "FOSS" as the brand name throughout the UI, emails, and page titles. You can override both to white-label your instance: ```txt theme={null} # Display name for the application (default: Sure) PRODUCT_NAME=MySure # Brand prefix shown in the footer and email sender name (default: FOSS) BRAND_NAME=MyOrg ``` The combined value appears in the footer as `© , `, and in the default email sender name. Other UI copy can use the product name or brand name separately. ### Market data provider variables Sure supports multiple securities pricing providers. You can configure them through environment variables or in the UI under **Settings > Self-Hosting**. See [market data providers](/providers/market-data) for details on each provider. ```txt theme={null} # Comma-separated list of securities providers (e.g. yahoo_finance,tiingo,mfapi) SECURITIES_PROVIDERS="yahoo_finance" # Exchange rate provider (default: twelve_data) EXCHANGE_RATE_PROVIDER="twelve_data" # API keys (only needed for providers that require them) TWELVE_DATA_API_KEY="your-key-here" TIINGO_API_KEY="your-key-here" EODHD_API_KEY="your-key-here" ALPHA_VANTAGE_API_KEY="your-key-here" TINKOFF_INVEST_API_KEY="your-read-only-token-here" # Cross-currency transfer auto-match tolerance (default: 0.1, i.e. 10%) # Sure uses this band when automatically linking cross-currency transfer pairs # during a sync. The value is a decimal fraction: 0.03 = 3%, 0.1 = 10%. # Values above 0.5 are capped at 0.5. At 1.0 the lower bound reaches zero, # meaning any two cross-currency amounts within the date window would match. # Tighten this if you see unrelated transactions being auto-linked as transfers. # The manual "match as transfer" dialog always uses max(10%, this value) so # real candidates remain visible even when the automatic tolerance is narrowed. TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE=0.1 ``` > [!NOTE] > > Setting `SECURITIES_PROVIDERS` as an environment variable takes precedence over the UI setting. Leave it unset to manage providers from the UI only. > [!NOTE] > > `TINKOFF_INVEST_API_KEY` serves two purposes: it enables T-Invest as a securities price provider when `tinkoff_invest` is included in `SECURITIES_PROVIDERS`, and it allows Sure to fetch brand logos for all securities (including MOEX-priced ones) via T-Invest's CDN. When a token is configured but T-Invest is not enabled for prices, the T-Invest settings block shows a notice: "Not enabled for prices above — T-Invest is used to fetch brand logos for all your securities whenever a token is configured, independent of the checkbox above." Logo fetching happens regardless of whether T-Invest is selected as a price provider. ### Categorization provider variables By default, Sure categorizes transactions using your configured LLM provider. You can optionally switch to **Jev** (by TypeSafe), a classification provider that answers typed questions about a transaction with calibrated probabilities. Because Jev only handles classification it is never used for chat, PDF processing, or merchant detection, and is configured independently of `LLM_PROVIDER`. Jev is a per-family opt-in behind the preview features gate. When the preview gate is open, each family can select their categorization provider from **Settings > Self-Hosting > Categorization provider**. The ENV override `CATEGORIZATION_PROVIDER` applies to every family on the instance. ```txt theme={null} # Required to enable Jev — no fallback to other keys JEV_API_KEY=your-jev-api-key # Override the categorization provider for every family on this instance # Accepted values: llm | jev CATEGORIZATION_PROVIDER=jev # Jev endpoint (default: https://api.typesafe.ai/v1/systemone) # To route through OpenRouter instead, set both variables: # JEV_ENDPOINT=https://openrouter.ai/api/alpha/decisions # JEV_MODEL=~typesafe/jev-latest # Note: routing through a gateway means transaction descriptions transit that # third party as well as TypeSafe. JEV_ENDPOINT=https://api.typesafe.ai/v1/systemone # Jev model (default: jev-latest) JEV_MODEL=jev-latest # Confidence threshold below which a Jev answer is not applied (default: 0.7, range: 0.0–1.0) # Answers below the threshold are left uncategorized for a later retry. # LLM providers, which do not report confidence, are never gated by this value. CATEGORIZATION_CONFIDENCE_THRESHOLD=0.7 # Shadow mode: probability (0.0–1.0) that a run also queries the unselected provider # for comparison, without applying its answers. Off by default. Doubles spend when active. CATEGORIZATION_SHADOW_RATE=0.0 ``` > [!NOTE] > > `JEV_ENDPOINT` must use HTTPS. An HTTP endpoint (other than loopback addresses such as `localhost` or `127.0.0.1`) is rejected because it would transmit the API key and transaction descriptions in cleartext. If a mis-typed or invalid endpoint is configured, Sure falls back to the LLM provider rather than stopping categorization entirely. > [!NOTE] > > When `JEV_ENDPOINT` is not set, you can edit the endpoint in the settings panel. On initial display, the field redacts userinfo, query string, and fragment from the effective URL; after a validation error, it can redisplay your submitted value. The field auto-submits on blur. Submitting the redacted form of the stored endpoint preserves the original stored URL, including its credentials. See [Jev (TypeSafe)](/providers/jev) for details on the provider, data-sharing considerations, and how to choose between Jev and the LLM path. ### Property valuation provider variables Sure supports three automated valuation model (AVM) providers for property accounts: RentCast and Realie for US properties, and Chimnie for UK residential properties. Configure them through environment variables or in the UI under **Settings > Self-Hosting**. See [property valuations](/providers/property-valuations) for details on each provider. ```txt theme={null} # RentCast — US property valuations (50 requests/month on the free tier) RENTCAST_API_KEY="your-rentcast-api-key" # Realie — US property valuations (25 requests/month on the free tier) REALIE_API_KEY="your-realie-api-key" # Chimnie — UK residential property valuations by UPRN (free, 1,000 requests/month default cap) # Sign up at dashboard.chimnie.com CHIMNIE_API_KEY="your-chimnie-api-key" # Override monthly request caps for paid plans or to raise the Chimnie default RENTCAST_MAX_REQUESTS_PER_MONTH=500 REALIE_MAX_REQUESTS_PER_MONTH=200 CHIMNIE_MAX_REQUESTS_PER_MONTH=2000 ``` > [!NOTE] > > RentCast and Realie only support US addresses and return values in USD. Chimnie only supports UK residential properties and returns values in GBP. A property account must be denominated in the provider's currency for automatic refreshes to run. ### On-chain wallet variables On-chain wallet tracking uses public block explorers by default. You can override any endpoint with your own instance, and tune history and token limits. ```txt theme={null} # Override block explorer / RPC endpoints (no trailing slash) MEMPOOL_SPACE_URL="https://mempool.space" BLOCKSCOUT_ETHEREUM_URL="https://eth.blockscout.com" BLOCKSCOUT_BASE_URL="https://base.blockscout.com" BLOCKSCOUT_ARBITRUM_URL="https://arbitrum.blockscout.com" BLOCKSCOUT_OPTIMISM_URL="https://optimism.blockscout.com" BLOCKSCOUT_POLYGON_URL="https://polygon.blockscout.com" BLOCKSCOUT_GNOSIS_URL="https://gnosis.blockscout.com" SOLANA_RPC_URL="https://api.mainnet-beta.solana.com" SOLANA_TOKEN_LIST_URL="https://lite-api.jup.ag" # History depth per address (default: 10, max: 200) # Solana transaction budget scales proportionally ONCHAIN_HISTORY_MAX_PAGES="10" # Max tokens surfaced per address in the review screen (default: 200, max: 5000) ONCHAIN_MAX_TOKENS_PER_ADDRESS="200" ``` To enable crypto pricing for on-chain wallets, include `binance_public` in `SECURITIES_PROVIDERS`. If your family currency is not USD, also set `EXCHANGE_RATE_PROVIDER` to a provider that needs no API key (e.g. `frankfurter`). See [on-chain wallets](/providers/onchain-wallets) for details. ### Redis Sentinel (high availability) By default Sure connects to Redis using `REDIS_URL`. For high-availability deployments that use Redis Sentinel, set `REDIS_SENTINEL_HOSTS` instead. When that variable is present it takes precedence over `REDIS_URL`. ```txt theme={null} # Comma-separated list of Sentinel nodes (host:port) REDIS_SENTINEL_HOSTS=sentinel1:26379,sentinel2:26379,sentinel3:26379 # Name of the monitored master (default: mymaster) REDIS_SENTINEL_MASTER=mymaster # Sentinel authentication username (default: default) REDIS_SENTINEL_USERNAME=default # Password for both the Redis master and the Sentinel nodes REDIS_PASSWORD=your-redis-password ``` If `REDIS_SENTINEL_HOSTS` is set but no valid hosts can be parsed from it, Sure falls back to `REDIS_URL` and logs a warning. ### Analytics (PostHog) Sure can send product analytics events to a PostHog instance. This is off by default and only activates when `POSTHOG_KEY` is set. ```txt theme={null} # Required to enable analytics POSTHOG_KEY=your-posthog-project-api-key POSTHOG_HOST=https://us.i.posthog.com ``` `POSTHOG_HOST` defaults to `https://us.i.posthog.com` when not set. Point it at your own PostHog instance if you self-host PostHog. When analytics are enabled, Sure registers a `sure_version` property on every browser event. The value comes from the `.sure-version` file bundled in the Docker image and matches the release tag (for example, `0.7.5-alpha.10`). This lets you filter PostHog events by the exact Sure version that produced them. Sure also enables PostHog's person profiles for all events, which allows PostHog to enrich events with GeoIP data based on the client IP address. Two optional variables give you finer control over analytics behavior: ```txt theme={null} # Emit analytics events in development (default: false) POSTHOG_DEVELOPMENT_ENABLED=false # Enable the in-app feedback widget (default: true) POSTHOG_FEEDBACK_ENABLED=true ``` `POSTHOG_DEVELOPMENT_ENABLED` is only read in the `development` environment. Set it to `true` if you want analytics events to fire during local development. In production the key presence alone controls whether events are sent. `POSTHOG_FEEDBACK_ENABLED` controls whether the in-app feedback widget appears. Set it to `false` to hide the widget on your instance. When `POSTHOG_FEEDBACK_ENABLED` is `true` and `POSTHOG_KEY` is set, Sure emits one `web_ui_served_daily` event per user per calendar day. The event carries a daily pseudonym derived from the user ID and the current date — no account ID or persistent person profile is created. It also includes the `sure_version`, whether the user has preview features enabled, and the client IP for GeoIP enrichment. The pseudonym rotates every day, so the event counts daily active web users without linking activity across days. A shared Redis cache prevents duplicate events from parallel sessions or tab reloads; cache loss can allow a repeat event for the same user on the same day. ## Running the application ### Start the application Start the app to verify everything is working: ```bash theme={null} docker compose up ``` This pulls the official Docker image and starts the app. You'll see logs in your terminal. Open your browser and navigate to `http://localhost:3000`. You should see the Sure login screen. ### Create your account On first run, register a new account: 1. Click "Create your account" on the login page 2. Enter your email 3. Enter a password The first user to register on a fresh instance is automatically assigned the `super_admin` role. If two registrations happen at the same time, Sure uses a database lock to ensure exactly one of them becomes `super_admin` and the other becomes `admin`. ### Restrict future signups After creating your initial admin account, you can control how other people join your self-hosted instance from **Settings > Self-Hosting > Onboarding**. * **Open**: Anyone can create an account from the registration page. * **Invite-only**: Signups stay enabled, but a valid invite code is required unless a default family is configured for invite-only onboarding. * **Closed**: The registration page is disabled for new signups. If you do not want additional self-service registrations, switch the instance to **Closed** after the initial setup. ### Run in the background To run Sure in the background: 1. Stop the current process with `Ctrl+C` 2. Start in detached mode: ```bash theme={null} docker compose up -d ``` Verify it's running: ```bash theme={null} docker compose ls ``` Your app is now accessible at `http://localhost:3000`. ## Updating The Docker image in your `compose.yml` file controls which version of Sure you're running: ```yml theme={null} image: ghcr.io/we-promise/sure:latest ``` ### Recommended images * `ghcr.io/we-promise/sure:latest` - Latest alpha release * `ghcr.io/we-promise/sure:stable` - Latest stable release You can also pin to a specific version from the [packages page](https://github.com/we-promise/sure/pkgs/container/sure). ### Update to the latest version Your app does not automatically update. To update: ```bash theme={null} cd ~/docker-apps/sure docker compose pull docker compose build docker compose up --no-deps -d web worker ``` ### Change update channel To switch between update channels, edit the `compose.yml` file: ```yml theme={null} image: ghcr.io/we-promise/sure:stable ``` Then restart the app: ```bash theme={null} docker compose pull docker compose build docker compose up --no-deps -d web worker ``` ## Backups, upgrades, and rollbacks Current `main` includes a bundle-based backup service for the database, mounted local uploaded files, and available deployment configuration. As of October 22, 2026, this service is not included in the latest stable release, `v0.7.5-hotfix.2`. The Compose service requires a Sure image containing [PR #3909](https://github.com/we-promise/sure/pull/3909). For older images, use the host-script method below. Run all commands from the directory that holds `compose.yml`. ### Taking backups Take a backup now (recommended before every upgrade): ```bash theme={null} docker compose run --rm backup create ``` Take a backup every day at 02:00 UTC, keeping the last 7 days: ```bash theme={null} docker compose --profile backup up -d backup ``` See all backups: ```bash theme={null} docker compose run --rm backup list ``` ### What a backup contains With the default backup directory, each bundle is stored under `backups//-/`. Check the backup log: missing storage mounts, `.env`, or compose files produce warnings and those files are omitted. | File | Contents | | - | - | | `manifest.json` | App version, commit when known, database schema, image references, and dump-client version | | `db.dump` | PostgreSQL custom-format dump | | `storage.tar.gz` | Uploaded files from the `app-storage` volume | | `config/` | `.env`, `compose.yml`, and `bin/sure-backup` | | `restore.sh` | Restores the backup into a new folder (see below) | | `SHA256SUMS` | Checksums verified before every restore | The dump-client version is recorded in `manifest.json`. Restore with `sure-backup` (`restore`, `recover`, or `restore.sh`), which checks client compatibility and handles newer-client settings when restoring to an older server. If you store uploaded files in S3, Cloudflare R2, or another bucket (`ACTIVE_STORAGE_SERVICE`), those files are not in the backup. Use your provider's versioning or replication for them. > [!WARNING] > > When present, `config/.env` can contain `SECRET_KEY_BASE`, API keys, and encryption settings. Preserve the encryption keys your installation actually uses: self-hosted defaults derive them from `SECRET_KEY_BASE`, while explicit Active Record encryption keys or Rails credentials take precedence. Separately preserve any secrets or credentials files supplied outside the backed-up configuration. Keep backups private and encrypt off-site copies (for example with [rclone crypt](https://rclone.org/crypt/)). ### Backup configuration Add these variables to your `.env` to control where and how often backups run: | Variable | Default | Description | | - | - | - | | `BACKUP_DIR` | `./backups` | Host folder for backups | | `BACKUP_SCHEDULE` | `0 2 * * *` | Daily time for scheduled backups (`minute hour * * *`, UTC) | | `BACKUP_KEEP_DAYS` | `7` | Scheduled backups older than this many days are deleted; manual `create` backups are kept | | `INSTANCE_ID` | `default` | Scopes backups under `//` when using off-site copies | ### Off-site copies The optional `backup-offsite` service copies the backup folder to any [rclone](https://rclone.org/) remote (S3, Cloudflare R2, Backblaze B2, SFTP, Google Drive, and 70+ others) every hour and removes scheduled backups there after `BACKUP_KEEP_DAYS` days. Set `BACKUP_DESTINATION` and the `RCLONE_CONFIG_*` variables in your `.env` file (see `.env.example`), then: ```bash theme={null} docker compose --profile backup-offsite up -d backup-offsite ``` Example `.env` for an S3-compatible provider such as Cloudflare R2: ```txt theme={null} # Required: rclone remote format — remote:bucket/path BACKUP_DESTINATION="s3:my-bucket" RCLONE_CONFIG_S3_TYPE=s3 RCLONE_CONFIG_S3_PROVIDER=Cloudflare RCLONE_CONFIG_S3_ACCESS_KEY_ID=your-access-key-id RCLONE_CONFIG_S3_SECRET_ACCESS_KEY=your-secret-access-key RCLONE_CONFIG_S3_ENDPOINT=https://your-account.r2.cloudflarestorage.com ``` For other providers (Google Drive, SFTP, Backblaze B2, etc.), add the equivalent variables to both `.env` and the `backup-offsite` service’s `environment` block; the example Compose file only maps S3 variables. See the [rclone documentation](https://rclone.org/docs/) for the full list. ### Restoring in place Use this to roll back the current install to an earlier backup: ```bash theme={null} docker compose stop web worker docker compose run --rm backup restore 0.7.4/2026-10-01_080524-manual # or "latest" ``` `restore` replaces the database and, when `storage.tar.gz` is present, replaces the mounted local file storage. Without that archive, it leaves local files unchanged and warns. It refuses while other database clients are connected unless explicitly forced, and asks for confirmation. Pass `--yes` to skip the prompt in scripts. It does not restore configuration automatically; restore the matching encryption settings before starting the app. After restoring a release backup, set `SURE_IMAGE_TAG` in `.env` to the backed-up version and restart. If `compose.restore.yml` overrides the image, edit that override instead. For a non-release build, use the matching commit image recorded in `manifest.json` when available. ```bash theme={null} # In .env: SURE_IMAGE_TAG=0.7.4 ``` ```bash theme={null} docker compose up --no-deps -d web worker ``` ### Restoring to a new folder Every backup bundle contains a `restore.sh` script. Run it on any machine that has Docker to bring up a fresh instance from the backup: ```bash theme={null} sh backups/0.7.4/2026-10-01_080524-manual/restore.sh ``` The script verifies the bundle and asks for a folder for the new instance (the folder name becomes the Compose project name). It then: * warns if other Sure instances are running on the machine, and offers to start the restored one without `worker`; * picks the next free port if the backup's port is already in use; * stops with a list of files to copy over if your compose files mount local files not included in the backup (custom certificates, for example); * copies configuration and data in, pins `web` and `worker` to the backed-up version, and starts the app. For scripts, pass options directly: `sh restore.sh --target ~/sure-restored --port 3001 --without-worker --yes`. Add `--no-start` to prepare the folder without starting the app. > [!WARNING] > > Do not run a restored copy alongside the original instance with both `worker` processes active. Both would sync the same bank connections and run scheduled jobs twice. ### Verifying backups ```bash theme={null} # View backup service logs docker compose logs backup # List all backups docker compose run --rm backup list ``` ### Without the backup service (any version, including 0.7.5 and older) You can run backups with the script on its own, without the `backup` service. Download it once next to `compose.yml`: ```bash theme={null} curl --fail --location --silent --show-error --output sure-backup \ https://raw.githubusercontent.com/we-promise/sure/main/bin/sure-backup chmod +x sure-backup ``` Then use it from your compose directory: ```bash theme={null} sh sure-backup create # Take a backup now sh sure-backup list # List backups sh sure-backup restore latest # Roll back in place (stop web and worker first) sh sure-backup recover backups// # Restore into a new folder ``` For create and restore, the script finds an existing `web` container and runs itself from that exact image with its volumes and database settings. The app must have been started at least once. Automatic version detection requires a valid runtime stamp or matching embedded version and schema metadata; otherwise it asks for `--version`. ### Upgrading from the database-only backup service (v0.7.5) Sure v0.7.5 shipped a `backup` service that ran `bin/db-backup.sh` and uploaded database-only dumps via rclone. To upgrade to the full-instance backup service: 1. Replace the `backup` service in your `compose.yml` with the `backup` and `backup-offsite` services from the current [`compose.example.yml`](https://github.com/we-promise/sure/blob/main/compose.example.yml). 2. In `.env`, remove `BACKUP_OVERWRITE`. `BACKUP_SCHEDULE` must be a daily time (`minute hour * * *`). Move `BACKUP_DESTINATION`, `INSTANCE_ID`, and all `RCLONE_CONFIG_*` variables to the `backup-offsite` service. 3. Use an image containing `bin/sure-backup`, then start both services: `docker compose --profile backup --profile backup-offsite up -d backup backup-offsite`. Keep using the host-script method if your app image predates the new service. Off-site backups now go to `///-/` and include `.env`. Earlier `backup_*.sql.gz` files are left in place and are no longer pruned automatically; delete them once you no longer need them. To restore an older `backup_*.sql.gz` file, stop `web` and `worker`, then load it with: ```bash theme={null} gunzip -c backup_.sql.gz | docker compose exec -T db psql -U -d ``` ## SSL certificate configuration For self-hosted environments using self-signed certificates or custom certificate authorities, Sure provides SSL configuration options. ### Environment variables Add these variables to your `.env` file: ```txt theme={null} SSL_CA_FILE=/path/to/ca-bundle.pem SSL_VERIFY=true # Optional: enable verbose SSL logging for debugging SSL_DEBUG=false ``` **SSL\_CA\_FILE**: Path to a custom CA certificate bundle (PEM format). Use this when: * Your environment uses self-signed certificates * You need to trust a custom certificate authority * Corporate proxies inject their own certificates **SSL\_VERIFY**: Controls SSL certificate verification (default: `true`) * Set to `false` to disable SSL verification (not recommended for production) * Only disable verification in development or testing environments **SSL\_DEBUG**: Set to `true` to enable verbose SSL logging at startup. Sure logs the active CA file, verification status, and the path of the combined CA bundle it writes to `tmp/ssl_ca_bundle.pem`. Use this to diagnose certificate trust issues in development or staging environments. If you're using a custom CA bundle, mount it into your containers in `compose.yml`: ```yml theme={null} services: web: volumes: - /path/to/your/ca-bundle.pem:/path/to/your/ca-bundle.pem:ro worker: volumes: - /path/to/your/ca-bundle.pem:/path/to/your/ca-bundle.pem:ro ``` Restart the application after updating your configuration: ```bash theme={null} docker compose restart web worker ``` ### Optional: SSL/TLS Configuration Sure supports additional SSL/TLS configuration options for secure email delivery and API connections. #### Custom CA Certificate If you're using a custom Certificate Authority (CA) or self-signed certificates, you can specify a CA file: ```txt theme={null} SSL_CA_FILE="/path/to/your/ca-certificate.pem" ``` This is useful when: * Running Sure in a corporate environment with internal CAs * Using self-signed certificates for development * Connecting to services with custom certificate chains #### Skip TLS Verification for Email For development or testing environments, you can disable TLS verification for the email mailer: ```txt theme={null} SMTP_ENABLE_STARTTLS_AUTO=false SMTP_TLS_VERIFY=false ``` > [!WARNING] > > Only disable TLS verification in development or trusted environments. In production, always use proper TLS verification to ensure secure email delivery. **When to use this:** * Development environments with self-signed certificates * Testing email functionality locally * Internal mail servers with custom certificates **Production recommendations:** * Always use valid SSL/TLS certificates in production * Use the `SSL_CA_FILE` option instead of disabling verification * Ensure your SMTP server supports STARTTLS ### Mailer SSL configuration For SMTP connections, additional SSL options are available: ```txt theme={null} SMTP_ENABLE_STARTTLS_AUTO=true SMTP_OPENSSL_VERIFY_MODE=none ``` **SMTP\_ENABLE\_STARTTLS\_AUTO**: Enable STARTTLS for SMTP connections (default: `true`) **SMTP\_OPENSSL\_VERIFY\_MODE**: SSL verification mode for SMTP * `none`: Skip SSL verification * `peer`: Verify the server certificate (default) ### Security considerations > [!WARNING] > > Disabling SSL verification (`SSL_VERIFY=false` or `SMTP_OPENSSL_VERIFY_MODE=none`) exposes your application to man-in-the-middle attacks. Only use these settings in trusted networks or development environments. For production deployments: * Use properly signed certificates from a trusted CA * Keep `SSL_VERIFY=true` * Use `SMTP_OPENSSL_VERIFY_MODE=peer` * If you must use self-signed certificates, provide a CA bundle via `SSL_CA_FILE` ## Monitoring system health When the Sidekiq worker container isn't running, background jobs silently never execute. Balance calculations, net-worth updates, and account syncs stall, and the UI may show zeros or "No balance data available" without explaining why. ### Sidekiq queue dashboard credentials The Sidekiq queue dashboard is available at `/sidekiq` for signed-in super admins only. You can add a second HTTP basic-auth layer on top of that by setting both of these variables: ```txt theme={null} SIDEKIQ_WEB_USERNAME=your-username SIDEKIQ_WEB_PASSWORD=your-password ``` Both variables must be set for basic auth to activate. When only one is present, the extra layer is skipped and the dashboard remains accessible to signed-in super admins as normal. ### Sidekiq health banner If Sure detects that Sidekiq is not processing jobs, a warning banner appears above the main content area on every page for super-admins. The banner indicates that data may be stale and links to the system health page. It is positioned so it does not overlap the page header or other admin bars that may be visible at the top of the screen. The banner title, body, and reason message are displayed in the super-admin's configured interface language. The check is conservative by design: * A worker process is considered stale if its heartbeat is older than 2 minutes, which tolerates brief deploy restarts and Redis blips. * A queue is considered backed up if its latency exceeds 5 minutes. The health snapshot is cached for 60 seconds to avoid extra Redis round-trips on every page load. You can override the thresholds and cache TTL with environment variables: ```txt theme={null} # Seconds before a worker heartbeat is considered stale (default: 120) SIDEKIQ_HEALTH_HEARTBEAT_TIMEOUT=120 # Seconds of queue latency before the queue is considered backed up (default: 300) SIDEKIQ_HEALTH_LATENCY_THRESHOLD=300 # Seconds to cache the health snapshot (default: 60) SIDEKIQ_HEALTH_CACHE_TTL=60 ``` ### System health page Super-admins can view live Sidekiq state at **Settings → Advanced → System health**. The page shows: * Worker process count and last heartbeat time * Maximum queue latency * Job counters (processed, failed, enqueued, retries) * Per-queue depth breakdown The system health page always bypasses the cache and fetches fresh state, so you can confirm a worker restart took effect immediately. ### Hosted usage tab On the two project-operated installations (`app.sure.am` and `demo.sure.am`), the system health page shows a **Hosted usage** tab. The tab is not available on self-hosted instances and does not appear when `APP_DOMAIN` is set to any other value. The tab loads a read-only snapshot of the database. It does not contact Stripe, run cleanup jobs, or modify any data. The snapshot covers: * **Summary** — trial household and member counts for the last 30 days, trials expiring in the next 7 days, cleanup-eligible households, and local supporter status counts. * **Recent trial households** — up to 100 subscriptions recorded in the last 30 days that retain a trial end date, including converted trials. The table shows retained sign-in session counts, not currently-online users or visit counts. Signing out deletes a session record. * **Cleanup eligibility** — households that match the existing cleanup scope (a paused or trialing subscription ended more than 14 days ago, or no subscription and a household older than 59 days). Matching the scope does not confirm deletion. * **Local supporter status** — current subscription rows with Stripe-shaped customer and subscription IDs, grouped by status. No Stripe request is made; these reflect the local database only. The tab is loaded lazily and does not affect the initial page load time. Click the **Hosted usage** tab to fetch the snapshot. The page rejects the tab parameter on installations where the feature is unavailable and falls back to the **Background jobs** tab. ### AI status tab The system health page has an **AI** tab at `/admin/system_health?tab=ai`. When you first open the tab, Sure shows a loading placeholder and then fetches the results in the background. This keeps the page responsive while up to six live probes run. The checks are bounded, non-destructive, and cover the effective AI configuration: * **LLM probe** — Verifies the configured model is available. For standard OpenAI, it queries the models list. For OpenAI-compatible endpoints (Ollama, OpenRouter, etc.), it sends a short chat completion request instead, since many compatible providers do not implement the models list endpoint. * **Function calling (tools) probe** — Asks the configured model for one trivial tool call using the same `tools` payload the assistant sends for its own function calls. A pass means tool calls work end-to-end. Two distinct failure outcomes are reported separately: if the tools request is rejected as a client error but the same request without tools succeeds, the probe marks tool support as **unsupported** (common with models on providers like OpenRouter that answer a bare 404); if the endpoint accepted the tools parameter but the model replied with text instead of calling the tool, the probe marks it as **tools accepted, but the model called none**. The probe uses the same API route the assistant takes — Responses API for hosted OpenAI when `supports_responses_endpoint?` is true, Chat Completions otherwise — so it always reflects the path live chat follows. * **PDF text extraction probe** — Sends a synthetic PDF to the model and checks that the response correctly identifies the institution name embedded in the document. This probe only runs when the effective provider is OpenAI and the model reports PDF text extraction support. The synthetic document contains no customer data. * **PDF vision processing probe** — Same synthetic PDF check using the vision processing path. Runs for any provider that reports vision-based PDF support, including Anthropic. The synthetic document contains no customer data. If the probe fails with "The pdftoppm renderer (poppler-utils) is not available in this container", your image predates the fix that bundled `poppler-utils`; pull the latest image and restart. * **Vector store probe** — For OpenAI vector stores, confirms a list request succeeds without creating or modifying a store. For pgvector, checks that the `vector` extension is enabled and the chunks table exists. * **Embedding probe** — For pgvector, sends a short test embedding request and verifies the returned vector matches `EMBEDDING_DIMENSIONS`. The test vector is not stored. When the pgvector setup is failing, the tab shows a specific alert explaining the cause instead of a generic failure message. The possible alerts and what to do for each are: | Alert | Cause | Fix | | - | - | - | | The PostgreSQL vector extension is not enabled | `pgvector` is selected but the `vector` extension is not enabled in the database | Use a PostgreSQL image that includes pgvector, then enable the extension as a database owner or superuser and re-run migrations with `VECTOR_STORE_PROVIDER=pgvector` | | The vector\_store\_chunks table is missing | The extension is enabled but the chunks table was not found | Check migration status, then re-run the vector-store migration with `VECTOR_STORE_PROVIDER=pgvector` | | The pgvector storage check failed | Sure could not query the chunks table | Check PostgreSQL permissions, the `vector` extension, and the `vector_store_chunks` migration | | The embedding dimensions do not match | The embedding endpoint returned a vector whose length does not match `EMBEDDING_DIMENSIONS` | Set `EMBEDDING_MODEL` and `EMBEDDING_DIMENSIONS` to the model's documented vector size, restart Sure, then recreate the pgvector table and re-embed documents if existing data used a different size | | The embedding live check timed out | The embedding endpoint did not respond before `AI_HEALTH_PROBE_TIMEOUT` | Raise `AI_HEALTH_PROBE_TIMEOUT`, restart Sure, then re-run the checks. If normal chat calls also time out, raise `OPENAI_REQUEST_TIMEOUT` separately | | The embedding live check failed | Sure could not create a test embedding through the configured endpoint | Check `EMBEDDING_URI_BASE`, `EMBEDDING_MODEL`, `EMBEDDING_ACCESS_TOKEN`, and the embedding provider logs | The tab also shows the active provider, model, endpoint (credentials are always redacted), function calling status, LLM request timeout, health-check probe timeout, PDF text extraction and vision processing status, and pgvector extension and table status. The model settings field links super-admins to this tab and notes that the assistant requires a model with function-calling support. The LLM request timeout and health-check probe timeout are displayed as separate rows because they bound different operations: the LLM request timeout covers normal chat and PDF import calls, while the health-check probe timeout covers only the live checks run on this page. When `OPENAI_URI_BASE` points to a custom endpoint, the page identifies the provider where possible — Ollama, OpenRouter, Together AI, Kilo, Cloudflare Workers AI or AI Gateway — and labels unrecognized services as **Custom endpoint**. Results are cached for 60 seconds by default. Click **Run checks again** to bypass the cache and get fresh results. Failures are written to the system debug log and to `Rails.logger`; credentials are never included. Failure reason labels and failure code messages are displayed in the super-admin's configured interface language. You can tune the AI status checks with these environment variables: | Variable | Description | Default | | - | - | - | | `AI_HEALTH_PROBE_TIMEOUT` | Per-request timeout in seconds for each live check | `5` | | `AI_HEALTH_PROBE_CACHE_TTL` | Seconds to cache probe results. Also deduplicates failure log entries | `60` | `AI_HEALTH_PROBE_TIMEOUT` is also configurable from the Settings UI without a restart. Go to **Settings → Self-Hosting**, scroll to the **Timeouts** section under AI Provider, and enter a value in the **Health Check Timeout in Seconds** field. The environment variable takes precedence over the UI setting when set to a positive value. Raise this value if PDF text or vision probes time out with a cloud model like gpt-4.1 — the PDF probes do a full extraction round trip that can take longer than the 5-second default, even when real PDF imports succeed. ### Config tab The system health page has a **Config** tab at `/admin/system_health?tab=configuration`. It gives a read-only snapshot of how optional services are configured — it does not test credentials or fetch live data. Resolving securities and exchange-rate providers constructs their clients; the optional-service checks do not initialize clients. The tab has two sections. **Core services** — checks four services that affect core app functionality: | Service | What is checked | | - | - | | SMTP | Address, port, sender address, app domain, and whether any credential pair is only half-configured. Disabled delivery and non-SMTP transports report their own status. | | Securities pricing | Whether each enabled provider in `SECURITIES_PROVIDERS` has its required credentials. | | Exchange rates | Whether the selected provider has its required credentials. An unrecognized provider name reports as not configured. | | File storage | The active Active Storage backend (disk, S3, GCS) and whether required settings such as bucket, region, and credentials are present. SDK credential chains (instance role, Application Default Credentials) report as **Not verified** rather than **Not configured** when the remaining checked settings are complete. | Each check shows one of these statuses: * **Configured** — all required settings are present. * **Not configured** — the service has not been set up. * **Incomplete configuration** — the check found missing or invalid settings, or a mixed provider configuration. The tab lists what needs attention. * **Disabled** — the service is explicitly turned off (for example, `ActionMailer.perform_deliveries = false`). * **Not verified** — the service uses a non-SMTP transport, a custom storage configuration, or an ambient storage credential source that this configuration check does not verify. This status does not simply mean that settings are partially filled in. On self-hosted instances, the securities and exchange-rate checks link super-admins to **Settings → Self-Hosting** to manage provider selection. **Optional services** — reports configuration-only status for operator integrations. These services are not required for the app to run: | Service | What is checked | | - | - | | Langfuse | Whether `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` are both set. | | Sentry | Whether a DSN is configured and whether Sentry is enabled in the current environment. | | Skylight | Whether `SKYLIGHT_AUTHENTICATION` is present and whether `SKYLIGHT_ENABLED=false` has explicitly disabled it. | | Stripe | Whether `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` are set. On managed instances, `STRIPE_MONTHLY_PRICE_ID` and `STRIPE_ANNUAL_PRICE_ID` are also required. On self-hosted instances those price IDs are noted as not required because the hosted checkout UI is disabled. | | PostHog | The effective key and host loaded at boot, plus browser analytics status and, on self-hosted instances, shared feedback status. An unset `POSTHOG_HOST` defaults to `https://us.i.posthog.com`; an explicitly blank host with a key reports incomplete configuration. | | Logtail | Whether `LOGTAIL_API_KEY` and `LOGTAIL_INGESTING_HOST` are set. Reports as disabled outside the `production` environment even when both keys are present. | An optional service can report **Incomplete configuration** when required settings are missing and either some settings are present or configuration signals an intent to enable it. For example, a nonblank `SKYLIGHT_ENABLED` other than `false` can trigger this status even with no authentication key; Stripe price IDs can also signal intent. The tab lists missing setting names without displaying their values. ### Verifying worker configuration The checks above all run from the `web` process. Most AI work — assistant responses, PDF processing, embeddings, auto-categorization, and merchant detection — actually executes in a Sidekiq `worker` process, which can differ from `web` in network access, DNS, proxy rules, or the credentials it loaded. This is most common in Kubernetes deployments using workload-specific environment overrides or a Secret updated without a pod restart. A passing web check does not prove a worker can reach the same provider. Click **Verify worker configuration** on the AI status tab to queue an asynchronous check (`WorkerAiHealthCheckJob`). It runs the same live probes from inside whichever worker process dequeues it, and the tab lists the result: that worker's process identity, when it checked in, whether its effective configuration matches what `web` resolved, and probe outcomes. All labels and status messages in the worker verification section are displayed in the super-admin's configured interface language. A few things this does and does not prove: * **One check verifies one worker.** Sidekiq does not broadcast a job to every process, so a passing result confirms the named process is healthy, not your whole fleet. With multiple worker replicas, queue the check again to sample another. Only the 5 most recently checked-in distinct processes are kept. A 6th check-in can evict an older entry before its own 15-minute retention window expires. A result older than `WorkerAiHealth::STALE_AFTER` displays as **Stale** rather than pass or fail. * **Worker checks never reuse a web-cached result, or vice versa.** The web page's probes are cached briefly so repeat page loads do not re-hit providers. The worker job bypasses that shared cache so its result always reflects a live call from its own network context, and never leaves an entry the web process could read back as its own. * **In local development, web and worker results will not show up together.** `bin/dev` runs `web` and `worker` as separate OS processes. The development environment uses Sidekiq, so jobs do reach the worker process, but `config/environments/development.rb` uses a process-local memory store when development caching is enabled, or a null store when it is disabled, rather than a shared Redis cache. With development caching enabled, a worker check result is written to the worker’s own memory cache; with caching disabled, the result is not retained, so the **Verify worker configuration** button can appear to do nothing from the web process. This is expected; production's shared Redis store is unaffected. * **Which settings need a restart depends on how they are set.** Provider, model, and API-key settings changed in **Settings → Self-Hosting** are stored in the database and take effect automatically on both `web` and `worker` without a restart. Embedding configuration and anything set only through an environment variable is fixed when each container starts. Changing those requires restarting or recreating both `web` and `worker`. The AI status tab labels this distinction next to the worker results. ### OpenAI request timeout The LLM request timeout controls how long each OpenAI-compatible HTTP request is allowed to take before it is cancelled. It applies to auto-categorization, merchant detection, chat completions, PDF processing, and vector-store calls. The default is 60 seconds, which works well for hosted models. Raise it when using slow local models (for example, Ollama on modest hardware). You can configure the timeout in two ways: * **Environment variable** — set `OPENAI_REQUEST_TIMEOUT` to a number of seconds. This takes precedence over the UI setting. * **Settings UI** — go to **Settings > Self-Hosting** and enter a value in the **Request Timeout in Seconds** field under the OpenAI section. ```txt theme={null} OPENAI_REQUEST_TIMEOUT=120 # raise for slow local models ``` The minimum accepted value is 1 second. If both the environment variable and the UI setting are present, the environment variable wins. ### AI response timeout The response timeout is a whole-turn watchdog for chat. It bounds how long Sure waits for a complete assistant turn — including all tool calls and their results — before giving up. The default is 90 seconds. Size this as a sum of the per-call request timeout across the maximum number of tool-call iterations, plus tool execution and queue wait time: `(1 + ASSISTANT_MAX_TOOL_CALL_ITERATIONS) × OPENAI_REQUEST_TIMEOUT`. The 90-second default is sized for typical cloud model latency. For local models where each request is slow, either raise this value or lower `ASSISTANT_MAX_TOOL_CALL_ITERATIONS`. You can configure the timeout in two ways: * **Environment variable** — set `AI_RESPONSE_TIMEOUT` to a number of seconds. This takes precedence over the UI setting. * **Settings UI** — go to **Settings > Self-Hosting** and enter a value in the **Response Timeout in Seconds** field under the OpenAI section. ```txt theme={null} AI_RESPONSE_TIMEOUT=180 # raise for slow local models with multiple tool calls ``` The minimum accepted value is 30 seconds. If both the environment variable and the UI setting are present, the environment variable wins. ### Extra HTTP headers for OpenAI-compatible requests `OPENAI_EXTRA_HEADERS` lets you attach custom HTTP headers to every request Sure sends to the OpenAI-compatible endpoint. This is useful for AI gateways that require routing or authentication headers — for example, sending a session identifier to a proxy that tracks usage per conversation. Set the variable to a JSON object of header names and values: ```txt theme={null} # Static header — sent on every request OPENAI_EXTRA_HEADERS='{"x-my-gateway-key": "abc123"}' # Session-scoped header — value is replaced with the chat's UUID per request OPENAI_EXTRA_HEADERS='{"x-opencode-session": "{session_id}"}' ``` **How it works:** * The value must be a valid JSON object. If it is missing, not an object, or not valid JSON, Sure logs an error and falls back to no extra headers. Chat continues normally. * String keys and values are used as-is. Blank values are dropped. * If a header value contains the literal `{session_id}`, Sure substitutes the current chat's UUID at request time. This identifies requests per conversation rather than per installation. The substitution only happens for chat requests — batch flows such as auto-categorization, merchant detection, and PDF processing never receive session headers. * This variable is environment-only. There is no Settings UI equivalent. > [!NOTE] > > The Sidekiq health banner, system health page, and AI status tab are only available in self-hosted mode. Managed deployments do not show these features. ## Demo data refresh Self-hosted super admins can opt into a daily demo family refresh from **Settings > Self-Hosting > Demo data refresh**. When enabled, Sure automatically regenerates the designated demo family's data every day — removing all its existing transactions, accounts, and logins and replacing them with freshly generated sample data. All other families on the instance are untouched. ### Requirements * A running `worker` process with at least 2 GiB of RAM. The demo generator is memory-intensive and will fail on smaller workers. * A disposable demo family that was created with Sure's built-in demo generator. Do not select a real user's family. ### Setup 1. Load sample data to create a demo family: go to **Settings** and use the demo data generator. This creates a family owned by the configured demo email address. 2. Go to **Settings > Self-Hosting > Demo data refresh**. 3. Under **Disposable demo family**, select the demo family you just created. The dropdown only shows families that own the demo email address and have no super-admin members. 4. Click **Save demo family**. 5. Toggle **Enable daily demo family refresh** on. After you save a demo family and enable the toggle, Sure runs the refresh job once a day. The job: * Generates a fresh set of demo data under the same demo email address. * Retires and destroys the previous demo family. * Updates the stored family ID to point at the newly created family. If the selected family no longer meets the safety checks (for example, a super-admin was added to it), the job skips that run and logs a warning instead of destroying data. ### Completion notification email After each successful refresh, Sure queues a summary email to every super admin on the instance. The email includes: * **Activity during this period** — the number of unique login sessions recorded for the previous demo family and the number of new family accounts created during the same window. * **Reporting period (UTC)** — the start and end timestamps of the 24-hour window the job reviewed. * **Previous demo family** — the name and ID of the previous family, whose deletion is queued separately. The email does not confirm that deletion has finished. The email is sent to the super admin's registered email address and uses a plain-text fallback for mail clients that do not render HTML. > [!WARNING] > > The refresh permanently destroys all data in the selected demo family. Select only a disposable family that was created specifically for this purpose. ## Running Sure on small (512 MB) hosts Sure runs comfortably on hosts or containers limited to 512 MB of RAM, which makes it a good fit for the smallest tiers on platforms like Render, Fly.io, or a cheap VPS. ### What fits in 512 MB Measured on a production deploy of the official image with the tuning below: * Boot, first-run onboarding, and everyday use (dashboard, transactions, budgets, reports) * Small bank syncs and CSV imports * Scheduled cron jobs such as exchange-rate refreshes Steady-state memory sits around 352 MB, leaving comfortable headroom under a 512 MB limit. ### What does not fit in 512 MB * **The demo-data generator** ("Load sample/demo data"): this is the one operation that deterministically exceeds 512 MB. On a 512 MB container it climbs to the limit and gets OOM-killed mid-generation. Because the generation runs in the worker, the symptom is a sample-data load that never completes, sometimes with all rows silently rolled back. * **Very large first-time imports or historical syncs** (tens of thousands of rows) can also exceed the limit. Import your history in smaller batches, or temporarily raise the memory limit for the initial import and lower it afterwards. * **AI features**: the assistant needs extra headroom. If you enable AI, run at least 1 GB. ### Tuning already in the image The official image ships with the memory tuning that makes 512 MB viable, so no extra configuration is needed: * **jemalloc** preloaded to reduce memory fragmentation * **YJIT** (Ruby's JIT) enabled * **Puma constrained to 1 worker × 3 threads** (`WEB_CONCURRENCY=1`, `RAILS_MAX_THREADS=3`) If you run your own process supervisor instead of the official image, set those same values. ### Loading sample data on a small host If you want to load sample data on a 512 MB host: 1. Raise the **worker's** memory limit. The generator runs in the worker process, not the web process. On Render, bump the worker service's plan; on Docker Compose, raise the worker container's memory limit. 2. Apply the change with a **fresh deploy or restart of the worker**. On Render, plan changes only take effect on the next deploy and do not apply on a plain restart. 3. Load the sample data, then optionally lower the worker back to the smaller plan with another fresh deploy. ## Troubleshooting ### Database connection errors If you encounter `ActiveRecord::DatabaseConnectionError` on first startup, Docker may have initialized the Postgres database with a different default role from a previous attempt. > [!WARNING] > > The following commands will delete all existing data in your Sure database. Only proceed if you're comfortable losing this data. Reset the database: ```bash theme={null} docker compose down docker volume rm sure_postgres-data docker compose up docker compose exec db psql -U sure_user -d sure_development -c "SELECT 1;" ``` The last command verifies the issue is fixed. ### Turning on Active Record encryption after first boot Self-hosted Sure can derive Active Record encryption keys from `SECRET_KEY_BASE` automatically. If you prefer dedicated keys, you can add: ```txt theme={null} ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=... ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY=... ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=... ``` Keep the same `SECRET_KEY_BASE` for an existing instance unless you are restoring from a backup that was created with the new value. Sure uses it to derive encryption keys when the dedicated `ACTIVE_RECORD_ENCRYPTION_*` variables are not set. If `SECRET_KEY_BASE` changes, deterministic encrypted fields such as user email addresses may no longer be searchable, and email/password login can fail with "invalid username or password" even when the password is correct. If you add those keys after your instance already has data, the normal app startup path is not enough to rewrite older plaintext values: * `db:prepare` still runs automatically on startup for schema setup and migrations. * New writes use encryption after the app boots with the keys. * Existing rows are not automatically re-encrypted. Run the backfill task once after the app is up: ```bash theme={null} # Safe preview first (dry-run is the default) docker compose exec web bin/rails security:backfill_encryption # Perform the rewrite docker compose exec web env DRY_RUN=false bin/rails security:backfill_encryption ``` The task is idempotent, so it is safe to rerun if needed. If login started failing immediately after changing encryption settings, restore the previous `SECRET_KEY_BASE` or previous `ACTIVE_RECORD_ENCRYPTION_*` values first. After the app can read the existing data again, run the backfill task if you are intentionally moving to dedicated keys. ### Sure NDJSON import file size limit By default, Sure NDJSON imports are limited to a fixed maximum file size. Self-hosted admins can raise this limit with an environment variable: ```txt theme={null} SURE_IMPORT_MAX_NDJSON_SIZE_MB=100 ``` This setting applies to both the GUI upload and the API upload paths. Set the value to the maximum file size in megabytes that you want to allow. ### Slow CSV imports If CSV imports are processing rows slower than expected, check your worker logs for errors: ```bash theme={null} docker compose logs worker ``` Look for connection timeouts or Redis communication failures. The `sure-worker` container requires Redis to process CSV imports. ## AI features, external assistant, and Pipelock Sure ships a separate compose file for AI-related features: `compose.example.ai.yml`. It adds: * **Pipelock** (always on): AI agent security proxy for outbound tunnel controls and inbound MCP scanning * **Ollama + Open WebUI** (optional `--profile local-ai`): local LLM inference ### Using the AI compose file ```bash theme={null} # Download both compose files curl --fail --location --silent --show-error --output compose.yml https://raw.githubusercontent.com/we-promise/sure/main/compose.example.yml curl --fail --location --silent --show-error --output compose.ai.yml https://raw.githubusercontent.com/we-promise/sure/main/compose.example.ai.yml curl --fail --location --silent --show-error --output pipelock.example.yaml https://raw.githubusercontent.com/we-promise/sure/main/pipelock.example.yaml # Run with Pipelock (no local LLM) docker compose -f compose.ai.yml up -d # Run with Pipelock + Ollama docker compose -f compose.ai.yml --profile local-ai up -d ``` ### Setting up the external AI assistant The external assistant delegates chat to a remote AI agent instead of calling LLMs directly. The agent calls back to Sure's `/mcp` endpoint for financial data (accounts, transactions, balance sheet). 1. Set the MCP endpoint credentials in your `.env`: ```txt theme={null} MCP_API_TOKEN=generate-a-random-token-here MCP_USER_EMAIL=your@email.com # must match an existing Sure user ``` 2. Set the external assistant connection: ```txt theme={null} EXTERNAL_ASSISTANT_URL=https://your-agent/v1/chat/completions EXTERNAL_ASSISTANT_TOKEN=your-agent-api-token ``` 3. Choose how to activate: * **Per-family (UI):** Go to **Settings > Self-Hosting > AI Assistant**, select "External" * **Global (env):** Set `ASSISTANT_TYPE=external` to force all families to use external > [!NOTE] > > If you connect your own agent via MCP and want to remove the built-in chat UI entirely, set `ASSISTANT_TYPE=mcp_only` (or select "None in app (connect your own agent via MCP)" in the UI). This disables the in-app chat, chat API endpoints, bills AI shortcuts, and AI-written insight text. The `/mcp` endpoint and background auto-categorization stay active. 4. Select an agent. After you save a valid URL and token, Sure calls `/v1/models` on the endpoint and populates an agent dropdown in the UI. Select the agent you want to use and save. The external service manages the model behind each agent; Sure only handles routing. To skip the UI and pin an agent via environment variable, set: ```txt theme={null} EXTERNAL_ASSISTANT_MODEL=openclaw/my-agent ``` When `EXTERNAL_ASSISTANT_MODEL` is set, the dropdown in the UI is disabled and the environment value is always used. To use the bundled OpenClaw service instead of a separately hosted agent, start the `external-assistant` profile. This profile starts OpenClaw without the local Ollama or Open WebUI services: ```bash theme={null} docker compose -f compose.ai.yml --profile external-assistant up -d ``` **Connection resilience:** When Sure cannot reach the external agent before any response has started streaming, it retries the request up to 2 times with exponential backoff (1 second, then 2 seconds) on transient network errors: connection timeouts, read timeouts, refused connections, reset connections, unreachable hosts, and DNS failures. If the agent starts streaming a response and then the connection drops, Sure does not retry — it raises an interruption error immediately so the partial response is not silently discarded. See the `docs/hosting/ai.md` file in the Sure repository for full configuration details including agent model selection, session keys, and email allowlisting. ### Pipelock security proxy Pipelock sits between Sure and external services and provides: * MCP request and response scanning for DLP, prompt injection, and tool poisoning * HTTPS tunnel controls for destination, SSRF, rate, budget, CONNECT headers, and optional signed receipts When using `compose.example.ai.yml`, Pipelock is always running. External AI agents should connect to port `8889` (Pipelock's MCP reverse proxy) instead of directly to Sure's `/mcp` on port `3000`. > [!NOTE] > > The example compose file does not enable TLS interception, so Pipelock controls the tunnel destination but cannot read encrypted request or response bodies. Docker Compose also does not prevent a client from bypassing the proxy. For full Pipelock configuration including signed receipts, see [Self-hosting with Helm](/self-hosting-helm#pipelock-ai-agent-security-proxy) for Kubernetes options and the `pipelock.example.yaml` reference file in the Sure repository. ## Local development bind For `bin/dev` on your own machine, the server defaults to `localhost` (`127.0.0.1` and `[::1]`), reachable only from the same machine. If you need external access (phone on the same Wi-Fi, devcontainer port forwarding, LAN testing), set the `BINDING` environment variable: `Procfile.dev` starts three processes: the Rails web server, the Tailwind CSS watcher, and a Sidekiq worker. The worker process receives background jobs via Redis, as in production. Tests use the separate Active Job test adapter. Auto-categorization, syncs, and other background work all route through this worker when developing locally. ```bash theme={null} BINDING=0.0.0.0 bin/dev # reachable from LAN BINDING=:: bin/dev # IPv6 dual-stack ``` The bundled devcontainer at `.devcontainer/docker-compose.yml` already sets `BINDING: "0.0.0.0"`, so Docker port forwarding works without a manual override when using the devcontainer. ### GitHub Codespaces When developing inside a GitHub Codespace, the app accepts login requests from the Codespaces preview URL without any extra configuration. The app detects the standard Codespaces environment variables (`CODESPACES`, `CODESPACE_NAME`, and `GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN`) that GitHub sets automatically and narrows the allowed CSRF origin to the forwarded preview domain. The origin check applies only when `Rails.env.development?` and `CODESPACES=true` are both set, so it has no effect in staging or production. The Codespaces initializer also re-declares the cookie store with `SameSite=None; Secure` so the VS Code Preview iframe can read the session cookie. It uses the application-wide session cookie key (`_sure_session`, defined as `Sure::SESSION_COOKIE_KEY` in `config/application.rb`) rather than a hardcoded name, keeping the cookie name consistent whether the app boots with or without Codespaces. If you cannot log in through a Codespaces preview URL, confirm that the three environment variables above are present in your Codespace environment and that the app is running with `CODESPACES=true`. ## iOS push notifications Push notifications are available in hosted mode only. When `SELF_HOSTED=true` or `SELF_HOSTING_ENABLED=true` is set, push registration and delivery are disabled. ### Environment variables Set the following variables for both the `web` and `worker` services: | Variable | Description | | - | - | | `APNS_KEY_ID` | Apple APNs signing key ID | | `APNS_TEAM_ID` | Apple Developer team ID | | `APNS_BUNDLE_ID` | iOS app bundle ID (`am.sure.insights`) | | `APNS_PRIVATE_KEY_BASE64` | Base64-encoded APNs `.p8` private key | | `APNS_ENABLED` | Set to `false` to pause delivery without removing credentials. Defaults to enabled when the other variables are present | `APNS_PRIVATE_KEY_BASE64` is a server-side secret. Do not embed it in the iOS app, logs, or version control. Both `web` and `worker` must share the same `REDIS_URL` (or `REDIS_SENTINEL_HOSTS` for high-availability setups). A process-local memory cache cannot coordinate the push diagnostics between processes. ### Sending a test notification 1. Sign in to the Sure iOS app with the same account as the super-admin signed in to the web app, and enable push notifications in the app. 2. Open **System Health → Background jobs → Push notifications** in the web app. 3. Click **Send test push notification**. The test is sent only to the current account's recently registered iOS devices. 4. Click **Refresh results** to see each device's outcome. Results remain for 24 hours. **Accepted by APNs** confirms Apple's acceptance; verify presentation on a real device to confirm delivery. The results table is keyboard-navigable and can be scrolled with the keyboard when it overflows. The button is disabled when there is no current registration, APNs is unconfigured, delivery is disabled (`APNS_ENABLED=false`), or another test was requested in the last 30 seconds. ### Troubleshooting | Outcome | What to check | | - | - | | **Queued / retrying** | Worker availability and the `scheduled` Sidekiq queue | | **Skipped** | Eligibility, ownership, role, mode, configuration, or freshness changed after the test was requested | | **Rejected by APNs** | Check the `push_notifications` category in Debug logs. Verify bundle ID, key/team, and device environment. `BadDeviceToken` may indicate an environment mismatch | | **Device registration no longer valid** | Worker received APNs `410`; the registration was conditionally removed | | **Could not enqueue** | Check Sidekiq and Redis availability, then retry after the 30-second cooldown | | **Expired without final result** | The request outlived the send window; check worker connectivity and request a fresh test | ## Getting help If you find bugs or have feature requests: * Read the [contributing guide](https://github.com/we-promise/sure/wiki/How-to-Contribute-Effectively-to-Sure) * Ask in the [Discord](https://discord.gg/36ZGBsxYEK) * Open an [issue](https://github.com/we-promise/sure/issues/new/choose) # Self-hosting with Helm Source: https://docs.sure.am/self-hosting-helm Deploy Sure on Kubernetes using the official Helm chart This guide shows you how to deploy Sure on Kubernetes using the official Helm chart. The chart supports web (Rails) and worker (Sidekiq) workloads, optional in-cluster PostgreSQL and Redis, and production-grade features like pre-upgrade migrations, pod security contexts, and horizontal pod autoscaling. ## Prerequisites * Kubernetes >= 1.25 * Helm >= 3.10 * Basic familiarity with Kubernetes and Helm ## Features * Web (Rails) deployment with service and optional ingress * Worker (Sidekiq) deployment * Optional database migrations via Helm hook job or initContainer * Optional subcharts for PostgreSQL (CloudNativePG) and Redis (OT-CONTAINER-KIT redis-operator) * Security best practices: runAsNonRoot, readOnlyRootFilesystem, no hardcoded secrets * Scalability: replicas, resources, topology spread constraints, optional HPAs * Optional CronJobs for custom tasks ## Installation ### Add Helm repositories Add the Sure Helm repository: ```bash theme={null} helm repo add sure https://we-promise.github.io/sure helm repo update ``` If you plan to use the bundled PostgreSQL or Redis subcharts, add their repositories as well: ```bash theme={null} helm repo add cloudnative-pg https://cloudnative-pg.github.io/charts helm repo add ot-helm https://ot-container-kit.github.io/helm-charts helm repo update ``` ### Quickstart (turnkey self-hosting) This installs CloudNativePG operator with a Postgres cluster and Redis managed by the OT redis-operator. > [!WARNING] > > For production stability, use immutable image tags (for example, `image.tag=v1.2.3`) instead of `latest`. > [!WARNING] > > Do not pass production secrets with `--set` on the command line. Use a values file with restricted permissions or a Kubernetes Secret as described in [Secrets management](#secrets-management). ```bash theme={null} # Create namespace kubectl create ns sure || true # Create a values file for the initial secret SECRET_KEY_BASE=$(openssl rand -hex 32) cat > values-quickstart.yaml < Self-Hosting > Onboarding**: * **Open**: Anyone can create an account from the registration page. * **Invite-only**: Signups stay enabled, but a valid invite code is required unless a default family is configured for invite-only onboarding. * **Closed**: The registration page is disabled for new signups. If you do not want additional self-service registrations, switch the instance to **Closed** after the initial setup. ## Configuration ### Using external Postgres and Redis To use external managed databases instead of the bundled subcharts, store connection strings in a Kubernetes Secret and reference them from your values file. See [Secrets management](#secrets-management) for the general pattern. ```yaml theme={null} cnpg: enabled: false redisOperator: managed: enabled: false redisSimple: enabled: false rails: extraEnv: DATABASE_URL: valueFrom: secretKeyRef: name: external-db-credentials key: database-url REDIS_URL: valueFrom: secretKeyRef: name: external-db-credentials key: redis-url ``` ### Redis Sentinel (high availability) The OT-CONTAINER-KIT Redis Operator supports a Sentinel failover layer for production HA deployments. When you enable Sentinel mode, the chart automatically injects `REDIS_SENTINEL_HOSTS` and `REDIS_SENTINEL_MASTER` into the web and worker pods so Sidekiq can do automatic master discovery and failover. ```yaml theme={null} redisOperator: enabled: true managed: enabled: true mode: sentinel # enables RedisSentinel CR in addition to RedisReplication sentinel: enabled: true # must be true when mode=sentinel masterGroupName: mymaster replicas: 3 auth: existingSecret: sure-secrets passwordKey: redis-password persistence: className: longhorn size: 8Gi ``` * The application receives `REDIS_SENTINEL_HOSTS` (comma-separated Sentinel endpoints) and `REDIS_SENTINEL_MASTER` instead of `REDIS_URL`. * Sentinel authentication uses username `default` by default. Override with `REDIS_SENTINEL_USERNAME` if needed. * Provider precedence: explicit `rails.extraEnv.REDIS_URL` → `redisOperator.managed` (with Sentinel if configured) → `redisSimple`. * Only one in-cluster Redis provider should be enabled at a time. ### Active Record encryption keys In self-hosted mode, Sure can derive Active Record encryption keys from `SECRET_KEY_BASE` automatically. If you want dedicated keys instead, provide these values through your app secret: * `ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY` * `ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY` * `ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT` If you add custom encryption keys after the instance already has data, the chart's normal migration flow is not enough to rewrite older plaintext values. `db:prepare` still handles schema setup and migrations, but existing rows need a one-off backfill after the app is running with the new keys: ```bash theme={null} # Safe preview first (dry-run is the default) kubectl exec -it deploy/sure-web -- bundle exec rake security:backfill_encryption # Perform the rewrite kubectl exec -it deploy/sure-web -- env DRY_RUN=false bundle exec rake security:backfill_encryption ``` The task is idempotent, so it is safe to rerun if needed. Keep the same `SECRET_KEY_BASE` for an existing release unless you are restoring from a backup created with the new value. Sure derives encryption keys from `SECRET_KEY_BASE` when dedicated `ACTIVE_RECORD_ENCRYPTION_*` values are not set, so changing it can prevent lookup of encrypted fields such as user email addresses and make email/password login appear invalid. If that happens after an encryption change, restore the previous secret values first, then run the backfill task if you are intentionally moving to dedicated encryption keys. ### Email delivery Configure SMTP delivery with the top-level `email` values. The chart renders them into the Rails workloads as `EMAIL_SENDER`, `APP_DOMAIN`, and `SMTP_*` environment variables that Action Mailer reads. ```yaml theme={null} email: sender: do-not-reply@example.com appDomain: app.example.com smtpAddress: smtp.example.com smtpPort: 465 smtpUsername: smtp-user smtpTlsEnabled: true smtpTlsSkipVerify: false ``` For the SMTP password, add `SMTP_PASSWORD` to your app secret. When the chart creates the app secret (`rails.secret.enabled` is true and `rails.existingSecret` is empty), a non-empty `rails.secret.values.SMTP_PASSWORD` is injected automatically unless `SMTP_PASSWORD` is explicitly supplied through `rails.settings` or `rails.extraEnv`. When you manage the secret yourself, pass it through `rails.extraEnvVars`: ```yaml theme={null} rails: existingSecret: sure-secrets extraEnvVars: - name: SMTP_PASSWORD valueFrom: secretKeyRef: name: sure-secrets key: SMTP_PASSWORD ``` Values set in `rails.settings` or `rails.extraEnv` take precedence over the `email.*` generated vars, so you can override individual variables without changing the `email` block. ### Deployment profiles #### Simple single-node Minimal setup for development or small deployments: * `encryptionEnv.enabled: true` tells the chart to wire the Active Record encryption keys from your secret into the app container. * `SELF_HOSTED: "true"` enables self-hosted behavior inside Sure. * Replace `longhorn` with a storage class that exists in your cluster. ```yaml theme={null} image: repository: ghcr.io/we-promise/sure tag: "v1.0.0" pullPolicy: IfNotPresent rails: existingSecret: sure-secrets encryptionEnv: enabled: true settings: SELF_HOSTED: "true" cnpg: enabled: true cluster: enabled: true name: sure-db instances: 1 storage: size: 8Gi storageClassName: longhorn redisOperator: enabled: true managed: enabled: true mode: standalone replicas: 1 persistence: enabled: true className: longhorn size: 8Gi migrations: strategy: job ``` #### HA k3s profile High availability setup with multiple replicas and synchronous replication: ```yaml theme={null} cnpg: enabled: true cluster: enabled: true name: sure-db instances: 3 storage: size: 20Gi storageClassName: longhorn minSyncReplicas: 1 maxSyncReplicas: 2 topologySpreadConstraints: - maxSkew: 1 topologyKey: kubernetes.io/hostname whenUnsatisfiable: ScheduleAnyway labelSelector: matchLabels: cnpg.io/cluster: sure-db redisOperator: enabled: true managed: enabled: true mode: replication replicas: 3 persistence: enabled: true className: longhorn size: 8Gi migrations: strategy: job initContainer: enabled: true hpa: web: enabled: true minReplicas: 2 maxReplicas: 10 targetCPUUtilizationPercentage: 70 ``` ### Secrets management Generate strong secrets before creating the Kubernetes Secret: ```bash theme={null} openssl rand -hex 32 # SECRET_KEY_BASE openssl rand -hex 32 # ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY openssl rand -hex 32 # ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY openssl rand -hex 32 # redis-password openssl rand -hex 64 # ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT ``` Create a Kubernetes secret with the required credentials: ```yaml theme={null} apiVersion: v1 kind: Secret metadata: name: sure-secrets type: Opaque stringData: # Rails secrets SECRET_KEY_BASE: "__SET_SECRET__" # Active Record Encryption keys (required for self-hosted mode) ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY: "__SET_SECRET__" ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY: "__SET_SECRET__" ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT: "__SET_SECRET__" # Redis password redis-password: "__SET_SECRET__" # Optional external service URLs database-url: "postgresql://user:pass@db.example.com:5432/sure" redis-url: "redis://:pass@redis.example.com:6379/0" ``` Apply the secret: ```bash theme={null} kubectl apply -f sure-secrets.yaml -n sure ``` Reference the secret in your values: ```yaml theme={null} rails: existingSecret: sure-secrets redisOperator: managed: enabled: true auth: existingSecret: sure-secrets passwordKey: redis-password ``` ### Ingress configuration Enable ingress to expose Sure externally: ```yaml theme={null} ingress: enabled: true className: "nginx" hosts: - host: finance.example.com paths: - path: / pathType: Prefix tls: - hosts: [finance.example.com] secretName: finance-tls ``` ### Horizontal pod autoscaling Enable HPAs for automatic scaling based on CPU utilization: ```yaml theme={null} hpa: web: enabled: true minReplicas: 2 maxReplicas: 10 targetCPUUtilizationPercentage: 70 worker: enabled: true minReplicas: 2 maxReplicas: 10 targetCPUUtilizationPercentage: 70 ``` ## Updating To update to a new version of Sure: ```bash theme={null} # Update the Helm repository helm repo update sure # Update the deployment with a new image tag helm upgrade sure sure/sure -n sure \ --set image.tag=v1.2.4 \ -f your-values.yaml ``` The chart will automatically run database migrations before deploying the new version. ## Backup and restore > [!WARNING] > > These steps cover PostgreSQL backups and restore. They do not automatically back up or restore uploaded files if your deployment stores them outside PostgreSQL. ### PostgreSQL backups with CloudNativePG CloudNativePG supports volume snapshot backups: ```yaml theme={null} cnpg: cluster: backup: method: volumeSnapshot volumeSnapshot: className: longhorn ``` ### Manual backup Create a manual backup of your PostgreSQL database: ```bash theme={null} # Get the primary pod name PRIMARY_POD=$(kubectl get pod -n sure -l cnpg.io/cluster=sure-db,role=primary -o jsonpath='{.items[0].metadata.name}') # Create a backup kubectl exec -n sure $PRIMARY_POD -- pg_dump -U sure sure_production > backup.sql ``` > [!NOTE] > > If you customized the PostgreSQL username or database name in your chart values, replace `sure` and `sure_production` in the backup and restore commands below. ### Restore from backup 1. Make sure app traffic is stopped or the deployment is in maintenance mode. 2. Copy the SQL backup to the primary PostgreSQL pod: ```bash theme={null} kubectl cp backup.sql sure/$PRIMARY_POD:/tmp/backup.sql ``` 3. Restore the database: ```bash theme={null} kubectl exec -n sure $PRIMARY_POD -- psql -U sure sure_production -f /tmp/backup.sql ``` 4. If your deployment uses uploaded files stored outside PostgreSQL, restore those separately using the matching volume snapshot or object-storage recovery process. 5. Verify that the app starts cleanly and your data appears as expected. ## Troubleshooting ### View logs ```bash theme={null} # Web logs kubectl logs -n sure -l app.kubernetes.io/component=web # Worker logs kubectl logs -n sure -l app.kubernetes.io/component=worker # Migration job logs kubectl logs -n sure -l job-name=sure-migrate ``` ### Check pod status ```bash theme={null} kubectl get pods -n sure ``` ### Verify database connectivity ```bash theme={null} # Test connection from web pod kubectl exec -n sure deploy/sure-web -- rails runner "puts ActiveRecord::Base.connection.execute('SELECT 1').first" ``` ### Run Helm tests After installation, verify the deployment: ```bash theme={null} helm test sure -n sure ``` ## Uninstall To remove Sure from your cluster: ```bash theme={null} helm uninstall sure -n sure ``` > [!WARNING] > > This will not delete PersistentVolumeClaims. Before deleting PVCs, make sure the namespace does not contain volumes for anything other than Sure. ```bash theme={null} kubectl get pvc -n sure kubectl delete pvc -n sure ``` ## Pipelock (AI agent security proxy) [Pipelock](https://github.com/luckyPipewrench/pipelock) is an optional security proxy that scans AI agent traffic for secret exfiltration, prompt injection, tool poisoning, and SSRF. It runs as a separate Deployment with two listeners: * **Forward proxy** (port 8888): Applies destination, SSRF, rate, budget, CONNECT-header DLP, and receipt controls to HTTPS tunnels from clients that honor the proxy variables. The chart does not configure TLS interception, so encrypted bodies stay opaque. * **MCP reverse proxy** (port 8889): Scans inbound MCP traffic from external AI assistants. The chart pins Pipelock 3.4.0 by tag and multi-architecture image digest. Read the [Pipelock release notes](https://github.com/luckyPipewrench/pipelock/releases/tag/v3.4.0) before overriding that pin. ### Enabling Pipelock ```yaml theme={null} pipelock: enabled: true image: tag: "3.4.0@sha256:2e6caa43967a5ef19cacbce00188d829c1b5de1eb0ad304a51d2085f32c5694c" mode: balanced # strict, balanced, or audit ``` This creates a separate Deployment, Service, and ConfigMap. The chart auto-injects `HTTPS_PROXY`, `HTTP_PROXY`, and `NO_PROXY` into web and worker pods. ### Request body scanning Request body scanning covers cleartext HTTP, reverse-proxy, and WebSocket bodies. HTTPS tunnel bodies remain opaque without TLS interception. Enabled by default with `action: warn`. Review findings in logs before switching to `action: block`. ```yaml theme={null} pipelock: requestBodyScanning: enabled: true action: warn # warn or block maxBodyBytes: 5242880 # 5 MB; fail-closed above this scanHeaders: true headerMode: sensitive # "sensitive" or "all" ``` ### Health watchdog The wedge-detection watchdog returns `503` on `/health` when a subsystem heartbeat goes stale. It is enabled by default. Use `exposeSubsystems: true` to add per-subsystem detail to the health payload. ```yaml theme={null} pipelock: healthWatchdog: enabled: true intervalSeconds: 2 exposeSubsystems: true ``` ### Signed action receipts Pipelock can write hash-chained, Ed25519-signed receipts for proxied decisions. Recording is inert until you mount both a storage volume and a signing key. Generate a key and create a secret: ```bash theme={null} pipelock signing key generate --purpose receipt-signing --out "$PWD/flight-recorder-signing.key" --id sure-k8s kubectl create namespace sure kubectl create secret generic sure-pipelock-receipts \ --namespace sure \ --from-file=flight-recorder-signing.key=./flight-recorder-signing.key ``` If you do not have the `pipelock` binary installed, generate the key with the pinned image: ```bash theme={null} docker run --rm -v "$PWD:/out" ghcr.io/luckypipewrench/pipelock:3.4.0@sha256:2e6caa43967a5ef19cacbce00188d829c1b5de1eb0ad304a51d2085f32c5694c \ signing key generate --purpose receipt-signing --out /out/flight-recorder-signing.key --id sure-k8s ``` Example Helm values using an existing PVC named `sure-pipelock-evidence`: ```yaml theme={null} pipelock: enabled: true flightRecorder: enabled: true dir: /var/lib/pipelock/evidence signingKeyPath: /run/secrets/pipelock/flight-recorder-signing.key requireReceipts: false redact: true extraVolumes: - name: pipelock-evidence persistentVolumeClaim: claimName: sure-pipelock-evidence - name: pipelock-receipt-key secret: secretName: sure-pipelock-receipts defaultMode: 0440 extraVolumeMounts: - name: pipelock-evidence mountPath: /var/lib/pipelock/evidence - name: pipelock-receipt-key mountPath: /run/secrets/pipelock readOnly: true ``` Keep `requireReceipts: false` until you confirm receipts are being written. When set to `true`, allow-path requests are blocked if Pipelock cannot sign or write the receipt. ### Validating your config Pipelock includes CLI tools for config validation and deployment diagnostics. Run them from the Pipelock container or using the pinned image locally: ```bash theme={null} # Create and run a broader assessment workspace pipelock assess init --config pipelock.yaml # Score your config's security posture (0-100) pipelock audit score --config pipelock.yaml # Report whether configured protections are actually enforceable pipelock doctor # Explain a block and the exact config knob that applies pipelock explain --config pipelock.yaml "https://example.com/path" ``` In Kubernetes, run these against the running Pipelock pod: ```bash theme={null} kubectl exec -n sure deploy/sure-pipelock -- /pipelock doctor --config /etc/pipelock/pipelock.yaml ``` ### Require Pipelock for external assistants By default, the chart rejects an external AI assistant deployment without Pipelock: ```yaml theme={null} pipelock: requireForExternalAssistant: true ``` `helm template` and `helm install` fail when `rails.externalAssistant.enabled=true` and `pipelock.enabled=false`. Set `requireForExternalAssistant: false` only when you accept direct external-assistant traffic without scanning. ### Exposing the MCP proxy externally Enable the Pipelock Ingress so external agents can reach the MCP reverse proxy: ```yaml theme={null} pipelock: enabled: true ingress: enabled: true className: nginx hosts: - host: pipelock.example.com paths: - path: / pathType: Prefix tls: - hosts: [pipelock.example.com] secretName: pipelock-tls ``` Or port-forward for testing: ```bash theme={null} kubectl port-forward svc/sure-pipelock 8889:8889 -n sure ``` For full Pipelock configuration options, see [Self-hosting with Docker](/self-hosting#pipelock-security-proxy) and the `pipelock.example.yaml` reference file in the Sure repository. ## Getting help If you find bugs or have feature requests: * Read the [contributing guide](https://github.com/we-promise/sure/wiki/How-to-Contribute-Effectively-to-Sure) * Ask in the [Discord](https://discord.gg/36ZGBsxYEK) * Open an [issue](https://github.com/we-promise/sure/issues/new/choose) # Self-hosting with Hostim.dev Source: https://docs.sure.am/self-hosting-hostim Deploy Sure on Hostim.dev with a managed database, Redis, persistent storage, and automatic HTTPS [Hostim.dev](https://hostim.dev) is a managed container-hosting platform that runs Sure with a managed PostgreSQL database, managed Redis, persistent storage, and automatic HTTPS. You don't need to provision or maintain a server. ## One-click deploy Sure is available as a one-click template on Hostim.dev. It provisions the Rails web server, the Sidekiq background worker, PostgreSQL, and Redis, and generates `SECRET_KEY_BASE` automatically. 1. Open the [Sure template](https://console.hostim.dev/dashboard?preview=1\&modal=1\&template=sure). 2. Choose a resource plan. 3. Click **Deploy**. 4. Open the generated domain and create your first account. A full walkthrough is available in the [Hostim.dev Sure guide](https://hostim.dev/docs/templates/sure). ## Manual setup To configure the app yourself, create an app from the `ghcr.io/we-promise/sure:stable` image and set the following environment variables: | Variable | Value | | - | - | | `SECRET_KEY_BASE` | A long random hex string. Keep it stable across restarts. | | `DB_HOST` / `DB_PORT` | Your PostgreSQL host and port. | | `POSTGRES_DB` / `POSTGRES_USER` / `POSTGRES_PASSWORD` | Database credentials. | | `REDIS_URL` | `redis://:/1` | | `SELF_HOSTED` | `true` | Run the web server and a Sidekiq worker from the same image, both sharing the same `SECRET_KEY_BASE`. Run `bin/rails db:prepare` before the web server starts so migrations are applied. For example, use a start command like: ```bash theme={null} sh -c "./bin/rails db:prepare && (bundle exec sidekiq &) && exec ./bin/rails server -b 0.0.0.0" ``` Mount a persistent volume at `/rails/storage`. Sure stores uploaded files (such as imported statements) there via Active Storage's local disk service by default. Without a persistent volume, uploaded files are lost when the container is replaced, while the database still references them. # Self-hosting with Pethost Source: https://docs.sure.am/self-hosting-pethost Deploy Sure on Pethost with automatic HTTPS, persistent volumes, and nightly backups [Pethost](https://pethost.dev) is a hosting platform that runs Docker Compose projects with automatic HTTPS, persistent volumes, and nightly backups. ## Deploy with the CLI To deploy Sure's own `compose.example.yml` from a terminal: 1. Install the [`pethost` CLI](https://pethost.dev/docs/cli/). 2. Download the sample Compose file into a folder of its own, as in the [Docker guide](/self-hosting): ```bash theme={null} mkdir sure && cd sure curl --fail --location --silent --show-error --output compose.yml https://raw.githubusercontent.com/we-promise/sure/main/compose.example.yml ``` 3. Create a `.env` file beside it with your own secrets (`openssl rand -hex 64` generates the first): ```txt theme={null} SECRET_KEY_BASE="replacemewiththegeneratedstring" POSTGRES_PASSWORD="replacemewithyourdesireddatabasepassword" ``` 4. The app is served over HTTPS, so set this in `compose.yml`: ```txt theme={null} RAILS_ASSUME_SSL: "true" ``` 5. Deploy the folder: ```bash theme={null} pethost deploy ``` Pethost starts the Rails web server, the Sidekiq worker, PostgreSQL, and Redis from the file and prints the address (`https://sure.`). 6. Open the address and create your first account. To restrict future signups, see [Step 5a of the Docker guide](/self-hosting#step-5a-restrict-future-signups-optional). ## Data and updates The three volumes in the Compose file (`app-storage`, `postgres-data`, `redis-data`) are kept across deploys and included in the nightly backups. To update, set the image tag in the project's Compose file to the new release and deploy again. Update the tag in `compose.yml` for both `web` and `worker`, then run `pethost deploy` again. The address and data are preserved. A full walkthrough with each screen is in the [Pethost guide for Sure](https://pethost.dev/blog/self-host-sure/). # Self-hosting with Render Source: https://docs.sure.am/self-hosting-render Deploy Sure on Render using one-click deploy templates [Render](https://render.com) is a cloud hosting platform that can run Sure with managed PostgreSQL, managed Redis (Key Value), and automatic HTTPS. The Render templates provision the web server and Sidekiq worker for you. ## One-click deploy options Three templates are available depending on how you want to use AI features. Each is available in a `latest` (alpha) and `stable` channel. | Option | What it deploys | `latest` | `stable` | | - | - | - | - | | **Sure - No AI** | Web server, Sidekiq worker, Render Postgres, and Render Key Value. AI tokens are intentionally blank. | [Deploy to Render](https://render.com/deploy?repo=https://github.com/we-promise/sure-render-templates/tree/sure-no-ai-latest) | [Deploy to Render](https://render.com/deploy?repo=https://github.com/we-promise/sure-render-templates/tree/sure-no-ai) | | **Sure - Simple AI** | Sure with OpenAI-backed AI, pgvector-ready Postgres, Sidekiq, and Render Key Value. Render prompts for your OpenAI token during setup. | [Deploy to Render](https://render.com/deploy?repo=https://github.com/we-promise/sure-render-templates/tree/sure-simple-ai-latest) | [Deploy to Render](https://render.com/deploy?repo=https://github.com/we-promise/sure-render-templates/tree/sure-simple-ai) | | **Sure - External AI** | Sure with external assistant settings plus AlphaClaw, which manages the OpenClaw gateway on Render. | [Deploy to Render](https://render.com/deploy?repo=https://github.com/we-promise/sure-render-templates/tree/sure-external-ai-latest) | [Deploy to Render](https://render.com/deploy?repo=https://github.com/we-promise/sure-render-templates/tree/sure-external-ai) | > [!NOTE] > > Use `latest` for the most recent alpha release and `stable` for the latest stable release. If you are new to Sure, start with `stable`. Each alpha tag is automatically deployed to the Sure Render demo site, so the demo always reflects the latest `latest` release. ## How it works Each template uses a `render.yaml` Blueprint file from the [sure-render-templates](https://github.com/we-promise/sure-render-templates) repository. Render reads this file to create all the services, databases, and environment variables your deployment needs. Render expects the Blueprint file at the repository root of the target branch. The template branches in `sure-render-templates` are maintained separately from the main Sure codebase so that Render can read them directly. ## Choosing a template * **No AI** — suitable for users who want core budgeting and account tracking without LLM features. No API key is required. * **Simple AI** — adds the assistant, auto-categorization, and merchant detection backed by OpenAI. Render prompts for your `OPENAI_API_KEY` during setup. The Postgres database includes the `pgvector` extension for embeddings. * **External AI** — routes AI calls through an external agent (OpenClaw via AlphaClaw) instead of calling OpenAI directly. Choose this if you want to use an external AI provider or self-manage the gateway. ## After deploying Once Render finishes provisioning: 1. Open the generated `.onrender.com` URL. 2. Create your first account. The first user to register is automatically assigned the `super_admin` role. 3. To restrict future signups, go to **Settings > Self-Hosting > Onboarding** and set the mode to **Invite-only** or **Closed**. For environment variable configuration, updates, backup setup, and troubleshooting, refer to the [Docker self-hosting guide](/self-hosting) — the same environment variables apply.