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