# TimeWren documentation > TimeWren is open-source time tracking with prepaid hours, clients, projects, tasks and invoicing. It is self-hosted with Docker (one image, PostgreSQL, a small cron container) and has a REST API and an MCP server. --- # TimeWren documentation > Install, configure, run and integrate TimeWren, the open-source time tracker with prepaid hours and invoicing. Source: https://timewren.com/docs TimeWren is open-source time tracking for freelancers and small teams: clients, projects, tasks, a timer, prepaid hours and invoicing in one self-hosted app. It runs as one Docker image with PostgreSQL and a small cron container. A self-hosted instance has every feature open, with no plans, user limits or license keys, and sends no telemetry. ![The TimeWren dashboard with today's time, active projects and prepaid balances](https://timewren.com/brand/timewren/screens/en/dashboard.webp) ## Start here - [Quickstart](https://timewren.com/docs/quickstart.md): from an empty server to your first tracked hour in about ten minutes. - [One-line install](https://timewren.com/docs/install/quick.md): `curl -fsSL https://timewren.com/install.sh | bash` on a Linux server with Docker. - [Use these docs with your LLM](https://timewren.com/docs/llm.md): give the docs to Claude Code, Cursor, Codex or ChatGPT and let it install, upgrade or debug TimeWren for you. ## Install | Method | Best for | | --- | --- | | [One-line install](https://timewren.com/docs/install/quick.md) | A single Linux server with Docker. The fastest way. | | [Docker Compose](https://timewren.com/docs/install/docker-compose.md) | Full control over the Compose file and `.env`. | | [Coolify](https://timewren.com/docs/install/coolify.md) | You already run Coolify. | | [Dokploy](https://timewren.com/docs/install/dokploy.md) | You already run Dokploy. | | [Railway](https://timewren.com/docs/install/railway.md) | A managed platform, no server to maintain. | | [Render](https://timewren.com/docs/install/render.md) | A managed platform with a Blueprint. | | [Kubernetes](https://timewren.com/docs/install/kubernetes.md) | A Helm chart for an existing cluster. | | [From source](https://timewren.com/docs/install/from-source.md) | Building the image yourself or developing TimeWren. | ## Configure and run - [Environment variables](https://timewren.com/docs/configuration/environment.md): every variable the app reads, with defaults. - [Email](https://timewren.com/docs/configuration/email.md), [file storage](https://timewren.com/docs/configuration/storage.md) and [authentication](https://timewren.com/docs/configuration/authentication.md). - [Upgrading](https://timewren.com/docs/operations/upgrading.md), [backup and restore](https://timewren.com/docs/operations/backup-restore.md), [reverse proxy and TLS](https://timewren.com/docs/operations/reverse-proxy.md) and [troubleshooting](https://timewren.com/docs/operations/troubleshooting.md). ## Use and extend - [Prepaid hours](https://timewren.com/docs/concepts/prepaid-hours.md): how hour packages, balances and warnings work. - Integrations: [Billy](https://timewren.com/docs/integrations/billy.md), [Dinero](https://timewren.com/docs/integrations/dinero.md), [e-conomic](https://timewren.com/docs/integrations/e-conomic.md), [calendars](https://timewren.com/docs/integrations/calendar.md), [CVR lookup](https://timewren.com/docs/integrations/cvr.md) and [Zapier, Make and n8n](https://timewren.com/docs/integrations/automation.md). - Apps: [desktop](https://timewren.com/docs/apps/desktop.md), [mobile](https://timewren.com/docs/apps/mobile.md) and [browser extension](https://timewren.com/docs/apps/browser-extension.md). - Build on it: [REST API](https://timewren.com/docs/api/rest.md), [webhooks](https://timewren.com/docs/api/webhooks.md) and the [MCP server](https://timewren.com/docs/api/mcp.md) for AI assistants. - [Contributing](https://timewren.com/docs/contributing.md): set up a development environment and send a pull request. ## For LLMs and coding agents Every page is available as plain Markdown: add `.md` to the URL (for example `https://timewren.com/docs/quickstart.md`), or send `Accept: text/markdown`. [/llms.txt](https://timewren.com/llms.txt) lists every page, and [/llms-full.txt](https://timewren.com/llms-full.txt) contains the whole English documentation in one file. The source code is at [github.com/timewren/timewren](https://github.com/timewren/timewren). --- # Quickstart > From an empty Linux server to your first tracked hour: install TimeWren, create the admin account and log time against a prepaid package. Source: https://timewren.com/docs/quickstart This guide gets a TimeWren instance running on one Linux server and walks you through the first client, project, prepaid package and time entry. It takes about ten minutes. ## Before you start You need: - A Linux server (amd64 or arm64) with 2 vCPU, 2 GB RAM and 10 GB free disk. 4 GB RAM is more comfortable. - Docker Engine with Docker Compose v2.24 or newer. Check with `docker compose version`. - For anything beyond a local test: a domain name pointing at the server, so you can serve TimeWren over HTTPS. TimeWren does not install Docker for you. If it is missing, follow [Docker's install guide](https://docs.docker.com/engine/install/) first. ## 1. Install Run the installer as a normal user that can use Docker: ```bash curl -fsSL https://timewren.com/install.sh | bash ``` The script checks Docker and Compose, creates `.env` with fresh random secrets, pulls the prebuilt image, starts the stack and waits until the app is healthy. It never prints the secrets and never calls `sudo`. Running it again keeps your `.env` and only restarts the stack. Do you have a domain whose DNS already points at this server? Then let the installer add automatic HTTPS with Caddy: ```bash curl -fsSL https://timewren.com/install.sh | bash -s -- --with-caddy --domain timewren.example.com ``` Prefer to read the script first, or install another way? See [One-line install](https://timewren.com/docs/install/quick.md) for every option, or pick [Docker Compose](https://timewren.com/docs/install/docker-compose.md), [Kubernetes](https://timewren.com/docs/install/kubernetes.md) or a platform such as [Coolify](https://timewren.com/docs/install/coolify.md). ## 2. Create the admin account Open the URL the installer printed (for a local test, `http://localhost:3000`) and sign up. **The first account becomes the instance admin.** Create it right away, before anyone else can reach the instance. Without a mail server, the instance lets people sign up without email verification. That is fine for a first test, but it means anyone who can reach the instance can create an account. Set up [email](https://timewren.com/docs/configuration/email.md) before you expose TimeWren to the internet. ## 3. Track your first hours ![The timer running on a project](https://timewren.com/brand/timewren/screens/en/timer.webp) 1. Open **Clients** and add a client, for example the fictional "Acme ApS". 2. Open **Projects** and create a project for that client. Time on a project can be invoiced and can draw from a prepaid package. 3. Open **Prepaid Packages** and create a package for the client, for example 20 hours. Read [Prepaid hours](https://timewren.com/docs/concepts/prepaid-hours.md) for how balances and warnings work. 4. Start the timer on the project, stop it, and watch the package balance go down. 5. When you are ready to bill, create an invoice from the tracked time under **Invoices**, or connect [Billy](https://timewren.com/docs/integrations/billy.md), [Dinero](https://timewren.com/docs/integrations/dinero.md) or [e-conomic](https://timewren.com/docs/integrations/e-conomic.md). ## 4. Make it production ready Work through this list before you rely on the instance: - **HTTPS and the public URL.** Set `NEXT_PUBLIC_APP_URL` to the URL people open, and put a reverse proxy with TLS in front. See [Reverse proxy and TLS](https://timewren.com/docs/operations/reverse-proxy.md). - **Email.** Configure SMTP or Resend so verification, invitations and reminders are sent. See [Email](https://timewren.com/docs/configuration/email.md). - **Backups.** Back up the database, the storage volume and `.env`, and keep `ENCRYPTION_KEY` safe. See [Backup and restore](https://timewren.com/docs/operations/backup-restore.md). - **Upgrades.** Pin a version and learn the upgrade procedure. See [Upgrading](https://timewren.com/docs/operations/upgrading.md). Every setting is listed in [Environment variables](https://timewren.com/docs/configuration/environment.md). ## Check that it runs From the server: ```bash docker compose ps curl -i http://127.0.0.1:3000/api/health ``` Run these in the installation directory (where `docker-compose.yml` and `.env` are). If something is wrong, see [Troubleshooting](https://timewren.com/docs/operations/troubleshooting.md), or hand the problem to your coding agent with the prompts in [Use these docs with your LLM](https://timewren.com/docs/llm.md). --- # Use these docs with your LLM > Give the TimeWren docs to Claude Code, Cursor, Codex or ChatGPT, with ready-made prompts to install, upgrade, debug and integrate. Source: https://timewren.com/docs/llm The TimeWren documentation is written to be read by people and by language models. Every page exists as plain Markdown, and the whole documentation fits in one file. Point your coding agent or chat assistant at it, and it can install, upgrade or debug your instance, or write an integration against the API. ## What to give the model | URL | What it is | Use it when | | --- | --- | --- | | `https://timewren.com/llms-full.txt` | The whole English documentation in one Markdown file. | The model should know everything. Best for agents with a large context. | | `https://timewren.com/llms.txt` | An index of every page with a one-line summary and a link to its Markdown. | The model can fetch pages on its own and should pick what it needs. | | `https://timewren.com/docs/.md` | One page as Markdown, for example `https://timewren.com/docs/operations/upgrading.md`. | You know which topic matters. | Requests for a docs page with `Accept: text/markdown` also get the Markdown version, so tools that negotiate content work without the `.md` suffix. Links inside the Markdown point to other `.md` pages, so an agent can follow them. Every page has buttons at the top: **Copy as Markdown** puts the page on your clipboard, **Open in ChatGPT** and **Open in Claude** start a chat with a prompt that already points at the page's Markdown, and **View as Markdown** opens the raw page. The docs are also available in [Danish](https://timewren.com/da/docs), [German](https://timewren.com/de/docs) and [Spanish](https://timewren.com/es/docs). `llms-full.txt` is English only; models understand it fine and can answer in your language. ## Claude Code Start Claude Code on the server (or on the machine you deploy from), in the directory where TimeWren is or should be installed, and paste one of the [prompts](#ready-made-prompts) below. Claude Code fetches the URLs in the prompt by itself. To make the docs available in every session, add a line to the `CLAUDE.md` in that directory: ```text TimeWren docs: https://timewren.com/llms.txt (full text: https://timewren.com/llms-full.txt). Read the relevant page before changing the TimeWren installation. ``` Claude Code can also work with your TimeWren data (clients, projects, time entries) through the [MCP server](https://timewren.com/docs/api/mcp.md). That is separate from the docs: the docs tell the agent how TimeWren works, the MCP server lets it act in your account. ## Cursor In a chat, type `@Docs`, choose **Add new doc** and enter `https://timewren.com/llms-full.txt`. Then refer to it with `@TimeWren` (or the name you gave it) in your prompts. You can also paste a page URL ending in `.md` straight into the chat. ## Codex and other agents that read AGENTS.md Put the docs pointer in the `AGENTS.md` of the repository or directory you work in: ```text ## TimeWren Docs for the TimeWren installation: https://timewren.com/llms.txt Full text in one file: https://timewren.com/llms-full.txt Read the relevant page before changing the TimeWren installation. Never print the contents of .env. ``` The TimeWren source repository has its own `AGENTS.md` that points agents working on the code to the same docs. ## ChatGPT, Claude and other chat assistants Use the **Open in ChatGPT** or **Open in Claude** button on the page you need, or paste a prompt below. If the assistant cannot open links, use **Copy as Markdown** and paste the page into the chat. Chat assistants cannot run commands on your server. They give you commands to run; read each one before you run it. ## Ready-made prompts Replace the example values (domain, version) before you send a prompt. Each prompt tells the agent not to print secrets. Never paste your `.env`, API keys or database dumps into a chat yourself. ### Install TimeWren on my server ```text Install TimeWren on this Linux server. Read https://timewren.com/llms-full.txt first and follow the docs exactly, especially "Quickstart" and "One-line install". - Public URL: https://timewren.example.com (DNS already points at this server). - Use the official installer with automatic HTTPS if the docs offer it; otherwise set up a reverse proxy as described in "Reverse proxy and TLS". - Check that Docker and Docker Compose v2.24+ are installed before you start. Do not install Docker yourself; tell me if it is missing. - Never print the contents of .env or any secret. - When it runs, verify it as described in the docs (container status and the /api/health endpoint), and tell me which steps from "Make it production ready" are still open (email, backups, version pinning). ``` ### Upgrade my installation ```text Upgrade my TimeWren installation to the newest stable release. Read https://timewren.com/docs/operations/upgrading.md and https://timewren.com/docs/operations/backup-restore.md first and follow them exactly. - The installation is in the current directory (docker-compose.yml and .env are here). - Take a full backup first, as the docs describe, and show me where it is before you continue. - Tell me the current and the new version, and read the release notes on https://github.com/timewren/timewren/releases for anything that needs action. - After the upgrade, check the app logs for the migration result ("new migration(s) applied" or "Database is up to date") and the health endpoint. If a migration failed, stop and explain the recovery options from the docs before changing anything. - Never run "docker compose down -v" and never print .env. ``` ### Debug my installation ```text My TimeWren installation has a problem: . Read https://timewren.com/docs/operations/troubleshooting.md and https://timewren.com/docs/configuration/environment.md first. Then diagnose, read-only to begin with: - docker compose ps, docker compose logs --tail=200 app (and cron if relevant), the /api/health endpoint. - Compare the configuration with the docs. You may list which variables are set in .env, but never print their values. Explain the root cause with evidence from the logs, propose the smallest fix, and wait for my go before you change files or restart containers. Never delete volumes. ``` ### Build an integration against the API ```text Build an integration against my TimeWren instance at https://timewren.example.com. Read https://timewren.com/docs/api/rest.md and https://timewren.com/docs/api/webhooks.md first; the OpenAPI document described there is the source of truth for fields. Goal: . - Read the API key from the environment variable TIMEWREN_API_KEY; never hard-code it or print it. - Handle pagination, rate limits (HTTP 429) and errors as the docs describe. - If you need events instead of polling, use webhooks and verify the signature as shown in the docs. - Start with a small read-only call to prove the key works, then build the rest, with tests. ``` ## Tips - Give the agent the version you run (`TIMEWREN_VERSION` in `.env`, or the image tag). The docs describe the current release. - Ask the agent to quote the docs section it relies on. That makes it easy to check. - For changes to production, let the agent propose commands and run them yourself, or approve each one. --- # Contributing > Set up a development environment, run the checks, sign off your commits and find your way around the code and docs. Source: https://timewren.com/docs/contributing Bug fixes, translations, integrations and docs are all welcome. TimeWren lives at [github.com/timewren/timewren](https://github.com/timewren/timewren). ## Before you start - **Bugs:** search the existing issues first, then open one with steps to reproduce. - **Features and larger changes:** open an issue or a thread in Discussions (Ideas) before writing code, so the approach can be agreed first. - **Security issues:** never in public. See [Security](#security). - Issues labelled `good first issue` are a good place to begin. `help wanted` means a pull request is welcome. ## Development setup You need Node.js 26 or newer (`engines` in `package.json`), Docker for PostgreSQL, and npm. Fork the repository, clone your fork and run: ```bash npm run setup ``` This creates `.env.local` with local secrets (an existing file is left alone), installs dependencies, starts PostgreSQL in Docker, runs the migrations, seeds demo data and starts the dev server in the background on `http://localhost:3000`. The log is in `.next/dev.log`, and `npm run dev:stop` stops it. Afterwards, `npm run dev` runs the server in the foreground. To do the steps by hand, for example on a machine where you already have `.env.local`: ```bash npm ci npm run docker:up npm run db:migrate npm run db:seed npm run dev ``` Optional services (S3 storage, email, Valkey, payments, accounting integrations) are configured in `.env.local`. `.env.example` lists every option, and you can leave them empty when you do not need them. ## Making a change 1. Branch off `main` in your fork. 2. Keep the change focused: one fix or feature per pull request. 3. Run the checks before you push: ```bash npm run lint npx tsc --noEmit npm test npm run i18n:check ``` `npm test` runs the Vitest unit tests and needs no database. `npm run test:e2e` runs the Playwright tests against a local database, see `tests/e2e/README.md`. 4. Add or update tests when you change behaviour. For a bug, write a failing test first. 5. Database changes go through Drizzle: edit `src/lib/db/schema.ts`, then run `npm run db:generate`. Migrations are forward-only: add columns and tables, and do not drop or rename them in the same release. Never edit a migration that has been released. 6. Add a line under `## [Unreleased]` in `CHANGELOG.md` for anything a user or self-hoster would notice. 7. Open the pull request against `main`. For UI changes, add before and after screenshots made with demo data. ## Conventions - **Formatting and linting:** Biome only. Do not add ESLint or Prettier. Format only the files you changed. - **Code style:** the `@/*` alias maps to `src/*`, with 2-space indentation. - **Data:** archive instead of deleting user data (`isArchived`), and filter every query by `organizationId`. - **User-facing text** lives in `src/i18n/messages//`, never hardcoded. New text needs `en` and `da`. Other languages fall back to English. - **No gated features:** no feature may depend on a plan, license key, brand or billing setting. - **Commit messages** are short, in the imperative mood, with a Conventional Commits prefix: `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`. Mark breaking changes with `!`, as in `feat!: ...`. ## Sign off your commits (DCO) TimeWren uses the [Developer Certificate of Origin](https://developercertificate.org/) instead of a CLA. Signing off a commit certifies that you wrote the change or have the right to submit it under the project's license. You keep the copyright to your work. ```bash git commit -s -m "fix: round klippekort balance correctly" ``` This adds a `Signed-off-by: Jane Doe ` line using the name and email from your git config. Forgot it? Fix the last commit with `git commit --amend -s --no-edit`, or a whole branch with `git rebase --signoff main`, then force-push your branch. Pull requests with unsigned commits cannot be merged. Rebase on `main` instead of merging it into your branch. ## Documentation These docs live in the repository under `content/docs//`, one `.mdx` file per page. English (`en`) is the source. Danish (`da`), German (`de`) and Spanish (`es`) hold the translations, with the same file names. Each file starts with a front matter block with a `title` and a `description`. Write plain Markdown and keep the claims true to the code. Every page is also served as Markdown by adding `.md` to its URL, and `/llms.txt` and `/llms-full.txt` list and bundle the English docs for LLMs. See [Use these docs with your LLM](https://timewren.com/docs/llm.md). ## Security Do not open a public issue, discussion or pull request for a security problem. Report it privately through GitHub: [Report a vulnerability](https://github.com/timewren/timewren/security/advisories/new). If you cannot use GitHub, email `security@timetrack.dk`. Include a description and its impact, steps to reproduce, and the version or commit you tested. The security policy in `SECURITY.md` lists the response targets and which components are supported. ## Governance, license and trademark - **Governance:** the project is led by Mahope, which decides the roadmap and releases and appoints maintainers. Decisions are made in the open, in issues, pull requests and Discussions. There is no closed enterprise edition and no CLA. See `GOVERNANCE.md`. - **License:** the code is licensed under AGPL-3.0-only. The `browser-extension/` directory is MIT. Your contribution is licensed under the license of the files you change. See `LICENSE`. - **Name and logo:** the TimeWren name and logo are not covered by the code license. Forks must use their own name. See `TRADEMARK.md`. - **Code of Conduct:** everyone taking part follows the Contributor Covenant in `CODE_OF_CONDUCT.md`. ## Working with AI coding agents The repository ships `AGENTS.md` and `CLAUDE.md` with project guidance for coding agents. They follow the same rules as above, including the DCO sign-off. Do not add AI attribution trailers to commits. --- # Prepaid hours > How prepaid hour packages (klippekort) work in TimeWren: balance, deductions, overdraft, alerts, renewal and the rate hierarchy. Source: https://timewren.com/docs/concepts/prepaid-hours Prepaid hours are TimeWren's core concept. A client buys a block of hours up front, and the time you track for that client is deducted from the balance. The Danish word is "klippekort" (literally "clip card"), and you will see it in some API field names and in the Danish interface. ![A prepaid package with its remaining balance and usage history](https://timewren.com/brand/timewren/screens/en/prepaid-hours.webp) ## The model A package (`prepaid_packages`) belongs to one client and stores: | Field | Meaning | | --- | --- | | `totalHours`, `usedHours`, `remainingHours` | The balance. Remaining is never negative and never above the total. | | `hourlyRate`, `totalValue` | The price per hour you sold the package at, and `totalHours` times `hourlyRate`. | | `purchaseDate`, `expiryDate` | When it was bought, and an optional last day of validity. | | `clipSizeMinutes` | Optional rounding step, 1 to 480 minutes. | | `overdraftPolicy`, `overdraftRate` | What happens when the balance runs out. See [Overdraft](#overdraft). | | `autoDeduct` | Whether the package is suggested by default for new time (default on). | | `renewalInterval`, `renewalRollover` | Optional automatic renewal. See [Renewal](#renewal-and-invoicing). | | `isActive`, `isArchived`, `hiddenFromPortal` | Lifecycle and client portal visibility. | Every deduction is also written to a usage log (`prepaid_usage`) with the hours, the value, the linked time entry and a description. Manual deductions without a time entry are logged the same way. Manual deductions can exceed the balance when overdraft is allowed. The excess is recorded as overdraft debt. Block and invoice policies cap manual deductions at the largest amount the remaining balance covers after rounding up to whole clips. ## Which entries deduct Nothing is deducted automatically behind your back. The server only deducts when a time entry is saved with an explicit package id, or when you make a manual deduction. The apps suggest a package for you: - A package is suggested when it is active, has `autoDeduct` on, has hours left and has not expired. - With several candidates, the one that expires first wins. Packages without an expiry come last. Ties go to the oldest purchase date. - In the timer's save dialog, the web app and the browser extension use the same rule. You can pick another package or choose no package for any entry. - Through the REST API, send `"prepaid": "auto"` when creating a time entry to apply the same rule. If the client has no matching package, the entry is created without a deduction. Send either `prepaid: "auto"` or `prepaidPackageId`, not both. An entry can only be deducted from a package of its own client. The client is the entry's direct client, or the client of its project. Deducting from another client's package is rejected. A project is not required: an entry with only a client can be deducted. An entry with neither client nor project cannot be. Prepaid entries are left out when you create invoices from tracked time, because the client has already paid for them. Editing or deleting an entry reverses its deduction and gives the hours back, and the low-balance alert can fire again afterwards. ### Link or move existing time Open the destination package and choose **Link time**. The list starts with the client's uninvoiced time that has no package. Turn on **Include time on other prepaid packages** to see entries from the client's other packages, marked with the package name. Time in locked periods is excluded. When you attach time, it stays on its project and is deducted from the package balance. If overdraft is disabled, the balance must cover the entries after rounding to clips. Select fewer entries or allow overdraft under Edit on the package page. If the balance cannot cover one clip, you need to allow overdraft to attach time. If the selection is too large, the dialog shows the longest single entry the balance can cover. The deduction is calculated for each entry separately and rounded up to whole clips and hundredths of an hour, so several small entries can deduct more than one combined entry. Filter by project and dates, then select individual entries or all entries shown for a project. You can move up to 200 entries at a time. The dialog shows the selected hours and previews the remaining balance after clip rounding. Before confirming, review how many hours are credited back to each source package’s balance and how many are deducted on the destination package after its own clip rounding. Use the page controls to see more than 200 matches. If the package bills overflow, the review shows which hours become or stay billable outside a package. From **Time**, select up to 200 entries for one client and choose **Link to prepaid package**. Pick an active package to preview the balance and review transfers or billable overflow before confirming. To move time to the client directly, choose **Remove from project**. The rate is recalculated at client level and any deduction on a package for the same client stays in place. Removing an internal project keeps the client already assigned to the entry. Changing the date range or a filter clears the selection. ### Rounding - Without a clip size, the deducted hours are rounded to two decimals. - With a clip size, the entry is rounded up to whole clips. With `clipSizeMinutes` set to 15, a 50-minute entry deducts 60 minutes (four clips). A deduction fails if the package is inactive or expired. A package is valid through the whole expiry day in Danish time (Europe/Copenhagen). ### Overdraft `overdraftPolicy` decides what happens when an entry is larger than the remaining balance: | Policy | Behaviour | | --- | --- | | `block` (default) | The entry is rejected with an error. | | `allow` | The whole entry is deducted. The balance goes to zero and the excess is recorded as overdraft hours on the package. | | `invoice` | Nothing is deducted. The entry becomes a normal billable entry, at `overdraftRate` if you set one. | ## Alerts Two kinds of alert exist, both optional in practice because they only go to the recipients you choose. The setting `prepaidAlertRecipient` on the user is `owner` (default), `client` or `both`. Client recipients need an email address on the client, and their email links to the client portal. **Low balance.** After a deduction, if the remaining hours are at or below `PREPAID_LOW_BALANCE_THRESHOLD` of the total (default `0.2`, so 20%), an email is sent and the `prepaid.low_balance` webhook fires. It is sent once per package until the balance goes back up, for example because an entry was deleted. **Expiry.** A daily cron job (`/api/cron/prepaid-alerts`) emails about active packages that still have hours left and expire within `PREPAID_EXPIRY_WARNING_DAYS` days (default `30`). The same job deactivates expired packages and fires `prepaid.expired`. The balance indicators in the app use two levels. A package is "low" at or below the percentage threshold and "critical" at or below `PREPAID_CRITICAL_BALANCE_HOURS` hours (default `1`), so the last hour of a large package still reads as critical. The critical level changes the display only, it does not send an extra email. | Variable | Default | Meaning | | --- | --- | --- | | `PREPAID_LOW_BALANCE_THRESHOLD` | `0.2` | Fraction of the total that counts as low. | | `PREPAID_CRITICAL_BALANCE_HOURS` | `1` | Hours at or below which the balance is critical. | | `PREPAID_EXPIRY_WARNING_DAYS` | `30` | How many days before expiry the warning is sent. | See [Environment variables](https://timewren.com/docs/configuration/environment.md) for the full list. The alerts need working [email](https://timewren.com/docs/configuration/email.md) and the cron container running. ## Renewal and invoicing A package can renew itself with `renewalInterval` set to `monthly`, `quarterly` or `yearly`. The daily cron job `/api/cron/prepaid-renewals` handles packages that are due: - A new package is created with a new purchase date, and the old one is archived and deactivated. The chain is tracked through `renewedFromId`. - The hours per period stay constant (`renewalBaseHours`). - With `renewalRollover` set to `carry`, the remaining hours are carried into the new period. With `none`, the new period starts at the base hours. - Overdraft from the old period is always settled against the new hours, in both modes. It is logged as a usage row on the new package. - A draft invoice is created for base hours times the hourly rate, and you get a notification. You review and issue it yourself. If the package is linked to a recurring invoice, that template is used instead. - A webhook fires for the new package (`prepaid.created`). To top up without automatic renewal, create a new package for the client. Several active packages can exist side by side, and the suggestion rule above decides which is used first. ## Client portal Clients can see their packages in the client portal, on a Prepaid tab with balance and usage. Two switches control this: the portal permission `canViewPrepaid` (on by default) and the package setting `hiddenFromPortal`, which hides a single package completely, including from the history. Clients can also request a renewal, which shows up for you as a renewal request. Monetary values can be hidden from clients with the `hidePrepaidValue` setting, globally or per client. When invoicing is enabled, you can approve the request with a draft invoice or choose **Approve and review sending**. The package is renewed before the confirmation opens. It shows the client, recipient email, invoice number, amount including VAT and due date. Closing the confirmation leaves the invoice as a draft. The confirmation also shows the line count. If the invoice changes after the confirmation opened, TimeWren refuses to send it and you open the confirmation again. ## REST API Packages are available as the `prepaid-packages` resource, with the `prepaid:read` and `prepaid:write` scopes. List, get, create and update are supported, and `DELETE` archives a package rather than deleting it. Authentication and scopes are described in the [REST API](https://timewren.com/docs/api/rest.md) reference. Package events are delivered through [webhooks](https://timewren.com/docs/api/webhooks.md). ```bash curl -X POST https://timewren.example.com/api/v1/prepaid-packages \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "Support hours", "clientId": "CLIENT_UUID", "totalHours": 20, "hourlyRate": 100, "purchaseDate": "2026-01-05", "expiryDate": "2026-12-31"}' ``` ## Rate hierarchy The rate stored on a time entry decides what it is worth when billed. TimeWren picks it in this order and uses the first one that is set: 1. In an organization, a member rate for the project, then for the client, then the member's organization-wide rate. 2. The project's hourly rate. 3. The client's default hourly rate. 4. Your personal default hourly rate. The rate is chosen by the date of the entry, so time logged after the fact gets the rate that applied on that day. Rate changes can be scheduled for a future date and are recorded in the rate history of the user, client or project. A billed entry keeps its rate when its date is edited. The package's own `hourlyRate` is separate: it is the price of the prepaid hours and is used for the package value and renewal invoices, not for the entry rate. ## Worked example You sell Acme ApS a package of 20 hours at 100 per hour, valid until the end of the year, with a clip size of 15 minutes. 1. Create the package: `totalHours` 20, `hourlyRate` 100, so `totalValue` is 2,000. Remaining is 20. 2. You track 50 minutes of work for Acme. In the save dialog the package is preselected. The entry is rounded up to four clips, so 1.00 hour is deducted. Remaining is 19.00, used is 1.00. 3. Over the following weeks, deductions bring the balance to 4.00 hours. That is 20% of the total, so the low-balance email goes out and the `prepaid.low_balance` webhook fires. 4. At 1.00 hour left, the balance shows as critical. 5. The next entry is 1.5 hours. With the default policy `block`, it is rejected. With `allow`, the 1.00 remaining hour is used and 0.50 is recorded as overdraft. With `invoice`, nothing is deducted and the entry is billed normally. 6. Thirty days before 31 December, if hours are still left, the expiry warning is sent. On the day after, the cron job deactivates the package. --- # One-line install > Install TimeWren on a Linux server with Docker using one command: it generates secrets, starts the stack and waits until the app is healthy. Source: https://timewren.com/docs/install/quick Choose this method if you have a server with Docker and want a running instance in a few minutes without cloning the repository. The script downloads the Compose file for a release, creates a `.env` with fresh random secrets, starts the stack and waits for it to become healthy. ```bash curl -fsSL https://timewren.com/install.sh | bash ``` ## Requirements - Docker Engine with the Compose v2 plugin, version 2.24 or newer (`docker compose version`). - `curl`, and a user that can reach the Docker daemon. - A published TimeWren release. Unless you pass `--version`, the script asks the GitHub API for the latest release of `timewren/timewren`. - For automatic HTTPS: a DNS record pointing at the server and inbound TCP ports 80 and 443 open. The script does not install Docker and never calls `sudo`. If Docker is missing or the daemon is unreachable, it prints where to get it and stops. ## What the script does 1. Checks that `docker` exists, that `docker compose` is v2.24 or newer, and that the daemon is reachable. 2. Chooses the installation directory (see below) and, if `docker-compose.yml` or `.env.example` are missing there, downloads them from `https://raw.githubusercontent.com/timewren/timewren//`. The version is remembered in `.timewren-release`. 3. Creates `.env` from `.env.example` with new random values (64 hex characters each) for `POSTGRES_PASSWORD`, `BETTER_AUTH_SECRET`, `ENCRYPTION_KEY` and `CRON_SECRET`. The file gets mode 600 and the secrets are never printed. 4. Runs `docker compose pull` and `docker compose up -d`. Inside a source checkout (the directory has `Dockerfile` and `package.json`) it runs `docker compose up -d --build` instead and builds the image from the checkout. 5. Waits until the `app` container reports healthy, up to 900 seconds by default. If the container exits or becomes unhealthy, it prints `docker compose logs app` as the next step. When it finishes, open the URL you set as `NEXT_PUBLIC_APP_URL` and create your account. The first account becomes the instance admin. Migrations run on every start of the app. > **Note:** Back up `ENCRYPTION_KEY` from `.env`. Without it, connected integrations must be reconnected. ## Options Options go after `bash -s --` when you pipe the script: ```bash curl -fsSL https://timewren.com/install.sh | bash -s -- --help ``` | Option | Meaning | | ------ | ------- | | `--url URL` | Public URL people will open. Must start with `http://` or `https://`, no credentials. Default: `http://localhost:PORT`. | | `--port PORT` | Host port for the app (written as `APP_PORT`, default 3000). Without `--url`, the URL becomes `http://localhost:PORT`. | | `--version TAG` | GitHub release tag to install. Default: the latest release. | | `--dir PATH` | Installation directory. Default: the current directory. | | `--with-caddy --domain HOST` | Add automatic HTTPS for `HOST` with Caddy (see below). | | `--no-start` | Create `.env` and stop before starting the stack. | | `--timeout SEC` | How long to wait for the app to become healthy. Default 900. | | `-h`, `--help` | Print a short usage text. | The script also reads these environment variables as defaults: `NEXT_PUBLIC_APP_URL`, `APP_PORT`, `TIMEWREN_VERSION`, `CADDY_DOMAIN` and `TIMEWREN_INSTALL_DIR`. Example with a pinned release in its own directory and a custom URL: ```bash curl -fsSL https://timewren.com/install.sh | bash -s -- --dir /opt/timewren --version 1.2.3 --url https://timewren.example.com ``` ## Automatic HTTPS with Caddy ```bash curl -fsSL https://timewren.com/install.sh | bash -s -- --with-caddy --domain timewren.example.com ``` `--domain` must be a DNS hostname that already points at this server. The script sets the URL to `https://timewren.example.com`, downloads `docker-compose.caddy.yml` next to the main Compose file and adds these lines to `.env`: ```dotenv CADDY_DOMAIN=timewren.example.com COMPOSE_FILE=docker-compose.yml:docker-compose.caddy.yml ``` The overlay adds a `caddy` service (`caddy:2-alpine`) that listens on ports 80 and 443 and proxies the domain to `app:3000`. If you pass `--url` together with `--with-caddy`, it must equal `https://` plus the domain. For other proxies, see [Reverse proxy](https://timewren.com/docs/operations/reverse-proxy.md). ## Where files go Without `--dir`, everything is created in the directory you run the command from: `docker-compose.yml`, `.env.example`, `.env`, `.timewren-release` and, with Caddy, `docker-compose.caddy.yml`. Run the command in an empty directory of your choice, or use `--dir`. Inside a repository checkout, the script uses the checkout root instead, as `./scripts/install.sh`. ## Running it again The script is safe to repeat. If `.env` exists it is left untouched, so your secrets are kept, and the stack is simply pulled and started again. In that case `--url`, `--port` and `--version` are ignored: edit `.env` instead. It stops with an error if any of the four secrets is empty or missing in the existing `.env`. To enable Caddy on an existing `.env`, set `CADDY_DOMAIN` and `COMPOSE_FILE` yourself, as shown above. ## Read the script first ```bash curl -fsSL https://timewren.com/install.sh -o install.sh less install.sh bash install.sh ``` Arguments work the same way: `bash install.sh --with-caddy --domain timewren.example.com`. ## Next steps - [Quickstart](https://timewren.com/docs/quickstart.md): create your account and first client. - [Reverse proxy](https://timewren.com/docs/operations/reverse-proxy.md): TLS with your own proxy. - [Email](https://timewren.com/docs/configuration/email.md): configure mail before inviting other people. - [Environment variables](https://timewren.com/docs/configuration/environment.md) - [Docker Compose](https://timewren.com/docs/install/docker-compose.md): the same stack, set up by hand. --- # Docker Compose > Run TimeWren with the prebuilt image, PostgreSQL and a scheduler using Docker Compose, with optional Valkey and automatic HTTPS. Source: https://timewren.com/docs/install/docker-compose Choose this method if you want to see and control every step, or already manage servers with Compose. It uses the prebuilt multi-arch image `ghcr.io/timewren/timewren`, so nothing is built on your machine. For a scripted version of the same steps, see [One-line install](https://timewren.com/docs/install/quick.md). ## Requirements - Docker Engine with Compose v2.24 or newer. - `curl` and `openssl` (or another way to generate random hex strings). - A domain and a reverse proxy with TLS for anything other than localhost. ## Install 1. Create a directory and download the Compose file and the environment template. ```bash mkdir timewren && cd timewren curl -fsSLO https://raw.githubusercontent.com/timewren/timewren/main/docker-compose.yml curl -fsSLO https://raw.githubusercontent.com/timewren/timewren/main/.env.example ``` 2. Create `.env` and fill the four required secrets with random values. ```bash cp .env.example .env for v in POSTGRES_PASSWORD BETTER_AUTH_SECRET ENCRYPTION_KEY CRON_SECRET; do sed -i "s|^$v=.*|$v=$(openssl rand -hex 32)|" .env done ``` On macOS use `sed -i ''` instead of `sed -i`. `ENCRYPTION_KEY` must be exactly 64 hex characters, which `openssl rand -hex 32` produces. 3. Set the public URL in `.env`, without a trailing slash: ```dotenv NEXT_PUBLIC_APP_URL=https://timewren.example.com ``` 4. Start the stack. ```bash docker compose up -d ``` 5. Open the URL and create your account. The first account becomes the instance admin. Migrations run on every start, including on an empty database. The first start can take a while, and the app container has a 180 second start period before health checks count. > **Warning:** `.env.example` sets `REQUIRE_EMAIL_VERIFICATION=false` so you can sign up without a mail server. It only applies while no mail transport is configured, and it lets anyone who can reach the instance create an account. Configure [email](https://timewren.com/docs/configuration/email.md) and remove the line before you expose the instance. Back up `ENCRYPTION_KEY`: without it, stored integration tokens cannot be decrypted. ## Services | Service | Image | Role | | ------- | ----- | ---- | | `app` | `ghcr.io/timewren/timewren` | The web app on container port 3000. Runs migrations at start (`MIGRATE_ON_START=1`). Local files on the `storage` volume at `/app/data/storage`. | | `cron` | same image | Runs `node scripts/cron.mjs`, which calls the app's `/api/cron/*` endpoints with `CRON_SECRET`. Runs only after `app` is healthy. | | `db` | `postgres:18-alpine` | PostgreSQL, data on the `db-data` volume. Not published to the host. | | `valkey` | `valkey/valkey:8-alpine` | Optional, profile `valkey`. Data on the `valkey-data` volume. | The app port is published as `127.0.0.1:3000` by default. Set `APP_PORT` to change the host port and `APP_BIND=0.0.0.0` to expose it on all interfaces. Keep exactly one `cron` service. `DATABASE_URL` is built by Compose from `POSTGRES_PASSWORD`, so you do not set it yourself. The password is only used when the database is first created: changing it later does not change the existing database. For all variables, see [Environment variables](https://timewren.com/docs/configuration/environment.md). ## Pin a version By default the image tag is `latest`. To control upgrades, pin a release in `.env`: ```dotenv TIMEWREN_VERSION=1.2.3 ``` Then `docker compose pull && docker compose up -d` applies it. Both `app` and `cron` use the same tag. ## Optional: Valkey Valkey provides shared rate limits and realtime timer sync. Add to `.env`: ```dotenv COMPOSE_PROFILES=valkey VALKEY_URL=redis://valkey:6379 RATE_LIMIT_BACKEND=valkey ``` Then run `docker compose up -d`. You can also start it for one run with `docker compose --profile valkey up -d`. A single app replica does not need Valkey. ## Optional: automatic HTTPS with Caddy The repository ships an overlay that adds a Caddy reverse proxy on ports 80 and 443. Point a DNS record at the server, open TCP 80 and 443, and download the overlay: ```bash curl -fsSLO https://raw.githubusercontent.com/timewren/timewren/main/docker-compose.caddy.yml ``` Add to `.env`: ```dotenv CADDY_DOMAIN=timewren.example.com COMPOSE_FILE=docker-compose.yml:docker-compose.caddy.yml NEXT_PUBLIC_APP_URL=https://timewren.example.com ``` Then `docker compose up -d`. Without `COMPOSE_FILE`, pass both files explicitly: `docker compose -f docker-compose.yml -f docker-compose.caddy.yml up -d`. For other proxies, see [Reverse proxy](https://timewren.com/docs/operations/reverse-proxy.md). ## Operate ```bash docker compose ps docker compose logs -f app ``` To upgrade, see [Upgrading](https://timewren.com/docs/operations/upgrading.md); for backups, [Backup and restore](https://timewren.com/docs/operations/backup-restore.md). ## Next steps - [Quickstart](https://timewren.com/docs/quickstart.md) - [Reverse proxy](https://timewren.com/docs/operations/reverse-proxy.md) - [Email](https://timewren.com/docs/configuration/email.md) and [Storage](https://timewren.com/docs/configuration/storage.md) - [Troubleshooting](https://timewren.com/docs/operations/troubleshooting.md) --- # Coolify > Deploy TimeWren on Coolify as a Docker Compose resource with generated secrets, PostgreSQL and a scheduler. Source: https://timewren.com/docs/install/coolify Choose this method if you already run Coolify. The Compose file pulls the published image, so nothing is built locally, and Coolify generates every secret for you. ## Requirements - A running Coolify instance with a server, and a domain you can point at it. - Access to the repository `https://github.com/timewren/timewren` (public). ## Deploy 1. In Coolify, create a new resource: **Docker Compose**, from a Git repository, using `https://github.com/timewren/timewren`. 2. Set the Compose file path to `/deploy/coolify/docker-compose.yml`. (The root file `docker-compose.coolify.yml` is a compatibility symlink to the same file.) 3. Give the `app` service a domain, for example `https://timewren.example.com`. The template routes it to container port 3000. 4. Deploy. Coolify generates the public app URL (`NEXT_PUBLIC_APP_URL`), the database password, the session secret (`BETTER_AUTH_SECRET`), the cron secret (`CRON_SECRET`) and a 64-character hexadecimal `ENCRYPTION_KEY`. You do not have to set anything. ## What gets deployed | Service | Image | Role | | ------- | ----- | ---- | | `app` | `ghcr.io/timewren/timewren:${TIMEWREN_VERSION:-latest}` | The web app. Runs migrations at start. Files on the `storage` volume. | | `cron` | same image | Runs `node scripts/cron.mjs` against `http://app:3000`. | | `db` | `postgres:18-alpine` | PostgreSQL, data on the `db-data` volume. | To pin a release, set `TIMEWREN_VERSION` in the resource's environment variables. ## Create your account first The domain is public as soon as it deploys, and the first account becomes admin. The template sets `REQUIRE_EMAIL_VERIFICATION` to `false` by default so the instance works without a mail server. Open the URL and create your account immediately, or set `ADMIN_EMAIL` and a mail transport (`SMTP_HOST` or `RESEND_API_KEY`) before the first deploy. Setting `REQUIRE_EMAIL_VERIFICATION=true` restores verification. ## Optional settings The Compose file exposes optional variables for mail (`SMTP_*`, `RESEND_*`), S3 storage (`S3_*`, together with `STORAGE_DRIVER=s3`), Google and Microsoft sign-in, Dinero, e-conomic and `OPENAI_API_KEY`, plus `TZ`, `ADMIN_EMAIL`, `DESKTOP_UPDATER_REPO` and `CHANGELOG_REPO`. Set them as environment variables on the resource. See [Environment variables](https://timewren.com/docs/configuration/environment.md). ## Back up Back up the generated secrets and both named volumes (`db-data` and `storage`). Keep `ENCRYPTION_KEY`: replacing it makes saved integration tokens unreadable. Changing the database password later does not change the password stored in Postgres. ## Next steps - [Quickstart](https://timewren.com/docs/quickstart.md) - [Email](https://timewren.com/docs/configuration/email.md) - [Upgrading](https://timewren.com/docs/operations/upgrading.md) and [Backup and restore](https://timewren.com/docs/operations/backup-restore.md) - [Troubleshooting](https://timewren.com/docs/operations/troubleshooting.md) --- # Dokploy > Deploy TimeWren on Dokploy from a custom template with a generated domain, four generated secrets and named volumes. Source: https://timewren.com/docs/install/dokploy Choose this method if you already run Dokploy. The template pulls the published image and generates all secrets. ## Requirements - A running Dokploy instance with a server and a domain. - The files from `deploy/dokploy/` in the repository: `docker-compose.yml` and `template.toml`. > **Note:** The template has not been submitted to the Dokploy template library, so it does not appear in the catalog. You import it yourself as a custom template. ## Deploy 1. Download the two files: ```bash curl -fsSLO https://raw.githubusercontent.com/timewren/timewren/main/deploy/dokploy/docker-compose.yml curl -fsSLO https://raw.githubusercontent.com/timewren/timewren/main/deploy/dokploy/template.toml ``` 2. In Dokploy, import them as a custom template (Compose and TOML). 3. Review the generated domain, or replace it with your own, then deploy. ## What the template sets `template.toml` generates a domain and four independent 64-character hexadecimal secrets, and routes the domain to the `app` service on port 3000: | Variable | Value | | -------- | ----- | | `NEXT_PUBLIC_APP_URL` | `https://` plus the generated domain | | `POSTGRES_PASSWORD` | generated | | `BETTER_AUTH_SECRET` | generated | | `ENCRYPTION_KEY` | generated, 64 hex characters | | `CRON_SECRET` | generated | PostgreSQL data and uploads live in named volumes; the template defines no host mounts (`mounts = []`). The `app` and the scheduler pull the same image, and migrations run when the app starts. Set `TIMEWREN_VERSION` to pin both services to a release. Optional mail, S3 and integration variables are exposed in the Compose file and use the names from `.env.example`. See [Environment variables](https://timewren.com/docs/configuration/environment.md). ## Create your account first The first account becomes admin. Register immediately, or set `ADMIN_EMAIL` and a mail transport before you expose the URL. ## Back up Back up both volumes and `ENCRYPTION_KEY`. ## Next steps - [Quickstart](https://timewren.com/docs/quickstart.md) - [Email](https://timewren.com/docs/configuration/email.md) - [Upgrading](https://timewren.com/docs/operations/upgrading.md) and [Backup and restore](https://timewren.com/docs/operations/backup-restore.md) - [Troubleshooting](https://timewren.com/docs/operations/troubleshooting.md) --- # Railway > Deploy TimeWren on Railway with a web service, PostgreSQL, a storage volume and a separate scheduler service. Source: https://timewren.com/docs/install/railway Choose this method if you want managed hosting on Railway. The setup has three parts: the web service, a PostgreSQL database and a scheduler service. Both services pull the published image and never build the app. > **Note:** A one-click Railway template with all services has not been published yet. Railway's config-as-code describes one service, not a whole project, so you add the database, volume and scheduler yourself as described below. ## Requirements - A Railway account and project. - The repository `timewren/timewren`, which contains `railway.json` and `deploy/railway/`. ## Set up 1. Add PostgreSQL to the project. Then deploy the web service from the GitHub repository `timewren/timewren` with `/railway.json` as the config path. Mount a volume at `/app/data/storage` and keep a single replica. 2. Set these variables on the web service. Railway references such as `${{Postgres.DATABASE_URL}}` are literal values, and the name must match your database service: | Variable | Value | | -------- | ----- | | `DATABASE_URL` | `${{Postgres.DATABASE_URL}}` | | `BETTER_AUTH_SECRET` | an independent random secret | | `ENCRYPTION_KEY` | output of `openssl rand -hex 32` | | `CRON_SECRET` | an independent random secret | | `NEXT_PUBLIC_APP_URL` | public HTTPS URL, no trailing slash | | `NEXT_PUBLIC_BRAND` | `timewren` | | `MIGRATE_ON_START` | `1` | | `STORAGE_DRIVER` | `local` | | `STORAGE_LOCAL_PATH` | `/app/data/storage` | | `REQUIRE_EMAIL_VERIFICATION` | `false` until mail is configured | | `HOSTNAME` | `0.0.0.0` | | `PORT` | `3000` | 3. Generate a public domain for the web service, set `NEXT_PUBLIC_APP_URL` to that HTTPS URL and redeploy. Add optional mail and integration variables from `.env.example` when you need them. 4. Add a second service from the same repository. Select `/deploy/railway/cron.json` as its config path and set: | Variable | Value | | -------- | ----- | | `CRON_SECRET` | `${{TimeWren.CRON_SECRET}}` | | `APP_URL` | `http://${{TimeWren.RAILWAY_PRIVATE_DOMAIN}}:3000` | Replace `TimeWren` with the actual name of your web service. Keep one scheduler replica, no public domain, no volume and no serverless sleeping. Do not skip the scheduler: exports, imports, syncs and reminders need it. It runs `node scripts/cron.mjs`, never needs database credentials, and migrations only run in the web service at startup. ## How the config works `railway.json` points both services at `deploy/railway/Dockerfile`, which only contains `FROM ghcr.io/timewren/timewren:latest`. To pin a release, change the tag in that Dockerfile. The web service uses `/api/health` as its health check and requires the mount path `/app/data/storage`. Valkey is optional and not needed for one app replica. ## Create your account first The first registered account becomes admin. Set `ADMIN_EMAIL` and a mail transport before you expose the service if you need to reserve that account. Back up the database, the storage volume and `ENCRYPTION_KEY`. ## Next steps - [Quickstart](https://timewren.com/docs/quickstart.md) - [Environment variables](https://timewren.com/docs/configuration/environment.md) - [Email](https://timewren.com/docs/configuration/email.md) - [Upgrading](https://timewren.com/docs/operations/upgrading.md) and [Backup and restore](https://timewren.com/docs/operations/backup-restore.md) --- # Render > Deploy TimeWren on Render from the repository Blueprint: a web service with a disk, a scheduler worker and managed PostgreSQL 18. Source: https://timewren.com/docs/install/render Choose this method if you want managed hosting on Render. The Blueprint `render.yaml` pulls the published image for a web service and a scheduler worker, creates managed PostgreSQL 18 and attaches a 10 GB persistent disk at `/app/data/storage`. Nothing is built. > **Warning:** The web service, the worker and the database all use paid plans (`starter`, `starter` and `basic-256mb`), because persistent disks and background workers need them. Check Render's cost estimate before you deploy. ## Requirements - A Render account. - A 64-character hex string for `ENCRYPTION_KEY`: `openssl rand -hex 32`. ## Deploy 1. Open the Blueprint deploy link for the repository: [render.com/deploy?repo=https://github.com/timewren/timewren](https://render.com/deploy?repo=https://github.com/timewren/timewren). Alternatively create a Blueprint in the Render dashboard from the repository `timewren/timewren`. 2. When asked, enter `ENCRYPTION_KEY` as exactly 64 hexadecimal characters. Render generates the session and cron secrets itself, but its generator emits base64, which is why it cannot generate the encryption key. 3. Deploy. Migrations run when the web service starts. 4. Open the service URL and create your account. ## What the Blueprint creates | Resource | Name | Notes | | -------- | ---- | ----- | | Web service | `timewren` | Image `ghcr.io/timewren/timewren:latest`, region Frankfurt, health check `/api/health`, one instance, disk `timewren-storage` (10 GB) at `/app/data/storage`. | | Worker | `timewren-cron` | Same image, runs `node scripts/cron.mjs` against the web service over Render's private network using `CRON_SECRET`. No disk, no database credentials. | | Database | `timewren-db` | PostgreSQL 18, plan `basic-256mb`, database and user `timetrack`. | Both services set `TZ` to `Europe/Copenhagen`. The web service also sets `NEXT_PUBLIC_BRAND=timewren`, `MIGRATE_ON_START=1`, `STORAGE_DRIVER=local` and `REQUIRE_EMAIL_VERIFICATION=false`. ## Public URL By default `NEXT_PUBLIC_APP_URL` is taken from `RENDER_EXTERNAL_URL`. If you add a custom domain later, set `NEXT_PUBLIC_APP_URL` to its HTTPS URL without a trailing slash. Optional mail and integration variables use the names in `.env.example`: see [Environment variables](https://timewren.com/docs/configuration/environment.md). ## Things to know - Do not scale either service beyond one instance. - A web service with a disk cannot do rolling deploys, so it briefly stops during redeploys. - Both image URLs default to `latest`. Edit `render.yaml` in your own fork to pin both to the same release tag before an operational rollout. - The first account becomes admin. Create it immediately, or configure `ADMIN_EMAIL` and a mail transport before you expose the service. - Back up the database, the disk and `ENCRYPTION_KEY`. - The Blueprint has been validated against Render's schema but has not been deployed to a Render account by the maintainers. After the first deploy, check registration, an upload and download, and a scheduled export. ## Next steps - [Quickstart](https://timewren.com/docs/quickstart.md) - [Email](https://timewren.com/docs/configuration/email.md) - [Upgrading](https://timewren.com/docs/operations/upgrading.md) and [Backup and restore](https://timewren.com/docs/operations/backup-restore.md) - [Troubleshooting](https://timewren.com/docs/operations/troubleshooting.md) --- # Kubernetes > Install TimeWren on Kubernetes with the Helm chart: optional bundled PostgreSQL and Valkey, a persistent volume, Ingress and one CronJob per scheduled endpoint. Source: https://timewren.com/docs/install/kubernetes Choose this method if you already run a Kubernetes cluster. The chart `charts/timewren` has no third-party chart dependencies. It deploys the app, optionally a single-node PostgreSQL and Valkey, a PVC for uploads and one CronJob per scheduled job. ## Requirements - Helm 3 and Kubernetes 1.27 or newer (CronJob time zones). - A default StorageClass, or storage classes you configure explicitly. - An ingress controller if you want to publish the app. The chart does not configure DNS or issue certificates. ## Install 1. Clone the repository. The chart is installed from the checkout. ```bash git clone https://github.com/timewren/timewren.git ``` 2. Install the release. Replace `1.2.3` with the release you want and the host with your own. ```bash helm upgrade --install timewren ./timewren/charts/timewren \ --namespace timewren --create-namespace \ --set image.tag=1.2.3 \ --set appUrl=https://timewren.example.com \ --set ingress.enabled=true \ --set ingress.className=nginx \ --set ingress.host=timewren.example.com ``` 3. Add TLS through `ingress.tls` and the annotations your TLS controller needs (see below). 4. Open the URL and create your account. The first account becomes admin unless `extraEnv.ADMIN_EMAIL` is set. Without an Ingress, use a port forward and set `appUrl=http://localhost:3000`: ```bash kubectl port-forward -n timewren service/timewren-timewren 3000:3000 ``` The app waits for PostgreSQL in an init container and runs with `MIGRATE_ON_START=1`, so migrations run when it starts. The chart sets `REQUIRE_EMAIL_VERIFICATION` to `false` by default; mail is optional, and verification becomes required when a mail transport is configured. ## Key values | Key | Default | Purpose | | --- | ------- | ------- | | `image.repository`, `image.tag`, `image.pullPolicy` | `ghcr.io/timewren/timewren`, `latest`, `IfNotPresent` | Image to run. Pin `image.tag`. | | `appUrl` | `http://localhost:3000` | Public origin used by authentication and links (`NEXT_PUBLIC_APP_URL`). Set it before installing. | | `existingSecret` | empty | Name of a Secret you manage (see below). | | `secrets.*` | empty | `DATABASE_URL`, `POSTGRES_PASSWORD`, `BETTER_AUTH_SECRET`, `ENCRYPTION_KEY`, `CRON_SECRET`. Empty keys are generated. | | `extraEnv` | `{}` | Additional variables from `.env.example`, such as `SMTP_HOST` or `ADMIN_EMAIL`. | | `service.port` | `3000` | Service port. | | `resources` | `{}` | Resource requests and limits of the app. | | `persistence.enabled`, `.existingClaim`, `.size`, `.storageClass` | `true`, empty, `5Gi`, empty | Storage for uploads at `/app/data/storage`. | | `ingress.enabled`, `.className`, `.host`, `.annotations`, `.tls` | `false`, empty, `timewren.example.com`, `{}`, `[]` | Ingress. | | `postgresql.enabled`, `.image`, `.size`, `.storageClass`, `.resources` | `true`, `postgres:18-alpine`, `10Gi`, empty, `{}` | Bundled single-node PostgreSQL. | | `valkey.enabled`, `.image`, `.size`, `.storageClass`, `.resources` | `false`, `valkey/valkey:8-alpine`, `1Gi`, empty, `{}` | Optional Valkey. | | `cron.enabled`, `.image`, `.timeZone`, `.resources`, `.jobs` | `true`, `curlimages/curl:8.12.1`, `Europe/Copenhagen`, `{}`, see `values.yaml` | Scheduled jobs. | Variables for mail, S3 and integrations use the names in [Environment variables](https://timewren.com/docs/configuration/environment.md). For example, a values file with SMTP: ```yaml extraEnv: SMTP_HOST: smtp.example.com SMTP_PORT: "587" SMTP_FROM: "TimeWren " ADMIN_EMAIL: jane@example.com ``` Put credentials in `existingSecret`, not in `extraEnv` or values files. ## Secrets By default the chart generates `POSTGRES_PASSWORD`, `BETTER_AUTH_SECRET`, `ENCRYPTION_KEY` (64 hex characters) and `CRON_SECRET` on first install and keeps them on upgrades by looking them up with Helm `lookup`. Values you set under `secrets` override the generated ones. Do not pass secrets on the command line or commit them. Helm stores rendered Secrets in the release history, so restrict access accordingly. Back up the Secret, especially `ENCRYPTION_KEY`. For GitOps or an external secret manager, create the Secret yourself and point the chart at it. Offline `helm template` cannot reuse generated secrets. The Secret needs these exact keys: | Key | Required | | --- | -------- | | `DATABASE_URL` | Always. With bundled PostgreSQL: host `-timewren-postgresql`, port 5432, database `timewren`, user `timewren`. | | `BETTER_AUTH_SECRET` | Always. | | `ENCRYPTION_KEY` | Always, 64 hexadecimal characters. | | `CRON_SECRET` | Always. Used by the app and the CronJobs. | | `POSTGRES_PASSWORD` | With bundled PostgreSQL, matching the password in `DATABASE_URL`. | | `VALKEY_URL` | With bundled or external Valkey. | An installation with an external database and Valkey then looks like this: ```yaml postgresql: enabled: false valkey: enabled: false existingSecret: timewren-secrets extraEnv: RATE_LIMIT_BACKEND: valkey # only when using external Valkey ``` Alternatively set `secrets.DATABASE_URL` with `postgresql.enabled=false`. Restart the app after you change an external Secret: `kubectl rollout restart -n timewren deployment/timewren-timewren`. With `valkey.enabled=true` the chart sets `VALKEY_URL` and `RATE_LIMIT_BACKEND=valkey`. The bundled PostgreSQL and Valkey are single-node services for small installations, without automatic backups or failover. Use managed services when you need those. ## Ingress and TLS Set `ingress.enabled=true`, `ingress.className`, `ingress.host` and, for TLS, `ingress.tls` plus the annotations of your controller, for example in a values file: ```yaml appUrl: https://timewren.example.com ingress: enabled: true className: nginx host: timewren.example.com tls: - secretName: timewren-tls hosts: - timewren.example.com ``` Keep `appUrl` equal to the public HTTPS URL. ## Persistence The app runs as a single replica with the `Recreate` strategy and a ReadWriteOnce PVC at `/app/data/storage`; the pod uses UID and GID 1001. Reuse a prepared claim with `persistence.existingClaim`, or set `persistence.storageClass` and `persistence.size`. To use S3-compatible storage instead, set `persistence.enabled=false` and provide `STORAGE_DRIVER=s3`, `S3_ENDPOINT`, `S3_REGION`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY` and `S3_BUCKET` through `extraEnv` and `existingSecret`. Disabling persistence without an external storage driver is not durable. See [Storage](https://timewren.com/docs/configuration/storage.md). The app PVC is kept on `helm uninstall`. PVCs are not backups: schedule database dumps and storage snapshots separately. ## Scheduled jobs With `cron.enabled=true` the chart creates one CronJob per entry in `cron.jobs`, keyed by endpoint name with a cron schedule as value, in the time zone `cron.timeZone` (default `Europe/Copenhagen`). Each job calls `/api/cron/` on the app Service with the `CRON_SECRET` as bearer token, using `concurrencyPolicy: Forbid`. Override schedules by changing `cron.jobs`. Set `cron.enabled=false` only if something else already calls the endpoints. ## Upgrade Take a database and file backup first: rolling back the image does not roll back schema changes. Then run the same command with the new tag: ```bash helm upgrade --install timewren ./timewren/charts/timewren \ --namespace timewren \ --reuse-values \ --set image.tag=1.2.4 ``` Pull the matching chart version first (`git -C timewren pull` or check out the release tag). If you used a values file, pass it with `-f` instead of `--reuse-values`. Migrations run at app start; check the app logs after the upgrade. See [Upgrading](https://timewren.com/docs/operations/upgrading.md). ## Next steps - [Quickstart](https://timewren.com/docs/quickstart.md) - [Email](https://timewren.com/docs/configuration/email.md) - [Backup and restore](https://timewren.com/docs/operations/backup-restore.md) - [Troubleshooting](https://timewren.com/docs/operations/troubleshooting.md) --- # From source > Build the TimeWren image yourself from a clone with Docker Compose, or run the development server with Node.js and PostgreSQL. Source: https://timewren.com/docs/install/from-source Choose this method if you want to run modified code or contribute. If you only want to run TimeWren, the prebuilt image in [Docker Compose](https://timewren.com/docs/install/docker-compose.md) is simpler and needs far less memory. ## Build the image yourself ### Requirements - Docker Engine with Compose v2.24 or newer. - About 4 GB of RAM or more for the build; it takes roughly 7 to 11 minutes and around 5 GB at peak. - About 10 GB of free disk space. ### Steps 1. Clone the repository and create `.env`. ```bash git clone https://github.com/timewren/timewren.git cd timewren cp .env.example .env for v in POSTGRES_PASSWORD BETTER_AUTH_SECRET ENCRYPTION_KEY CRON_SECRET; do sed -i "s|^$v=.*|$v=$(openssl rand -hex 32)|" .env done ``` 2. Set `NEXT_PUBLIC_APP_URL` in `.env` to the URL people will open. 3. In `docker-compose.yml`, comment out the `image:` line of the `app` service and uncomment the `build:` block below it. 4. Build and start. ```bash docker compose up -d --build ``` The `cron` service uses the prebuilt image by default. If you change `scripts/cron.mjs` or want it to run your build, also point the `cron` service at your image or build it in the same way. The build arguments `NEXT_PUBLIC_DESKTOP_RELEASES_REPO`, `NEXT_PUBLIC_REALTIME_ENABLED`, `NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL`, `NEXT_PUBLIC_SENTRY_DSN` and `NEXT_PUBLIC_SENTRY_BROWSER_ENABLED` are compiled into the browser bundle, so changing them in `.env` needs `docker compose up -d --build` again. The app URL, marketing URL and brand are read at runtime and need no rebuild. The compose build block sets the build argument `BUILD_PROFILE: selfhost`. That profile leaves the Cloud marketing site (pricing, blog, landing pages) and the TimeWren website out of the build, so the build is shorter and the image smaller. The cookies, contact, download and account-deletion pages, the instance's own privacy, GDPR, terms and data processing pages, and the app itself are unaffected. The prebuilt image is built this way. To build the full app, including the marketing pages that `NEXT_PUBLIC_MARKETING_URL` enables, remove the argument or set `BUILD_PROFILE: full`. You can also run the checkout's installer, `./scripts/install.sh`. In a checkout it builds the image and starts the stack with `docker compose up -d --build`, on every run. See [One-line install](https://timewren.com/docs/install/quick.md). ## Run the development server ### Requirements - Node.js 26 or newer and npm. - Docker, for the development PostgreSQL container. ### Steps 1. Clone the repository and install dependencies. ```bash git clone https://github.com/timewren/timewren.git cd timewren npm ci ``` 2. Create `.env.local` with at least a database URL and an auth secret. The development container from `docker-compose.dev.yml` listens on port 5432 with database `freelance_crm` and user and password `postgres`. ```dotenv DATABASE_URL=postgresql://postgres:postgres@localhost:5432/freelance_crm BETTER_AUTH_SECRET=replace-with-a-long-random-string NEXT_PUBLIC_APP_URL=http://localhost:3000 CRON_SECRET=replace-with-another-random-string ``` 3. Start PostgreSQL, apply migrations and start the server. ```bash npm run docker:up npm run db:migrate npm run dev ``` 4. Open `http://localhost:3000`. `npm run dev:setup` starts PostgreSQL, migrates, seeds demo data and starts the dev server in the background. Other useful commands: | Command | What it does | | ------- | ------------ | | `npm run docker:down` | Stops the development PostgreSQL container. | | `npm run db:seed` | Seeds the database with test data. | | `npm run db:studio` | Opens Drizzle Studio. | | `npm run build` | Production build. | | `npm test` | Unit tests (Vitest, no database needed). | | `npm run lint` | Biome linter. | Without `NEXT_PUBLIC_MARKETING_URL`, the marketing pages of the `timewren` brand are switched off and `/` redirects to the dashboard. ## Next steps - [Contributing](https://timewren.com/docs/contributing.md) - [Environment variables](https://timewren.com/docs/configuration/environment.md) - [Docker Compose](https://timewren.com/docs/install/docker-compose.md) --- # Environment variables > Complete reference of every TimeWren environment variable: defaults, which ones are required, which are baked in at build time, and what each one does. Source: https://timewren.com/docs/configuration/environment TimeWren is configured entirely through environment variables. This page lists every variable the code reads, grouped by purpose. Most self-hosted instances only need the [minimum configuration](#minimum-configuration) and, later, mail and storage. ## How variables are set With the Docker Compose setup, put variables in a `.env` file next to `docker-compose.yml`. The `app` service loads that file (`env_file: .env`), and a few values are also passed explicitly by `docker-compose.yml`. After editing `.env`, run `docker compose up -d` to apply runtime variables. Compose recreates the containers whose configuration changed. An empty value counts as "not set". `NEXT_PUBLIC_APP_URL=` falls back to its default, and a variable with an empty value behaves like one that is missing. Lines starting with `#` are comments, so `.env.example` ships with everything optional commented out. ### Build time and runtime Variables named `NEXT_PUBLIC_*` are inlined into the browser bundle when the image is built. Changing them in `.env` afterwards has no effect on the prebuilt image. Three exceptions are read at runtime, with the build value only as a fallback: `NEXT_PUBLIC_APP_URL`, `NEXT_PUBLIC_MARKETING_URL` and `NEXT_PUBLIC_BRAND`. The server reads them from its environment, and the browser gets them from `/runtime-config.js`, which the server generates per request. Marketing pages exist only in a build made with `BUILD_PROFILE=full`. The prebuilt image and the compose example use `selfhost`, which has none, so `NEXT_PUBLIC_MARKETING_URL` has no marketing pages to enable there. Instance pages such as cookies, contact and account deletion use the running app URL and brand. Set `NEXT_PUBLIC_MARKETING_URL` explicitly to enable marketing on a self-hosted domain. Shared navigation and site metadata use the running marketing URL and brand. Editorial metadata and page copy describe TimeTrack Cloud, including its pricing and publisher. The public Cloud data processing agreement PDF is only available on TimeTrack Cloud. The prebuilt image `ghcr.io/timewren/timewren` therefore has the other build-time variables fixed (for example `NEXT_PUBLIC_REALTIME_ENABLED`, `NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL` and the Sentry browser settings). To change those, build your own image with the matching build arguments, see [Install from source](https://timewren.com/docs/install/from-source.md). The `Build time` column below says which variables this applies to. The Content-Security-Policy headers are generated in `next.config.ts` from `NEXT_PUBLIC_APP_URL`, `NEXT_PUBLIC_MARKETING_URL`, `NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL`, `NEXT_PUBLIC_UMAMI_COLLECT_URL` and `NEXT_PUBLIC_UMAMI_SCRIPT_URL`, so they use the values present at build time. > **Note:** Billing variables (`ALUNTA_API_KEY`, `STRIPE_SECRET_KEY`, `STORE_BILLING_ENABLED` and everything that goes with them) are inert for self-hosting. Billing is switched on only when at least one of those three is set. Without them every feature is open: there are no user or client limits, no trial that expires, no upgrade buttons and no payment mails. ## Minimum configuration These five lines are enough to start an instance. Generate each secret with `openssl rand -hex 32`. ```dotenv POSTGRES_PASSWORD=replace-with-a-random-secret BETTER_AUTH_SECRET=replace-with-a-random-secret ENCRYPTION_KEY=replace-with-64-hex-characters CRON_SECRET=replace-with-a-random-secret NEXT_PUBLIC_APP_URL=https://timewren.example.com ``` Without a mail transport, sign-up needs `REQUIRE_EMAIL_VERIFICATION=false` (see [Required](#required)). Configure [email](https://timewren.com/docs/configuration/email.md) as soon as you can. ## Required Compose refuses to start when `POSTGRES_PASSWORD`, `BETTER_AUTH_SECRET`, `ENCRYPTION_KEY` or `CRON_SECRET` is missing. | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `POSTGRES_PASSWORD` | none | yes | no | Password of the bundled PostgreSQL. Compose builds `DATABASE_URL` from it. It is only used when the database is first created: changing it later does not change the existing database. | | `BETTER_AUTH_SECRET` | none | yes | no | Secret that signs sessions. Changing it logs everybody out. The container refuses to start without it. | | `ENCRYPTION_KEY` | none | yes | no | AES-256-GCM key for stored tokens and credentials (calendar, accounting, webhooks). Exactly 64 hex characters. If you lose it, those integrations must be reconnected, so back it up. | | `CRON_SECRET` | none | yes | no | Shared secret between the `cron` service and the app. Also needed for `/api/health?detail=1`. | | `DATABASE_URL` | set by Compose | conditional | no | PostgreSQL connection string. Compose sets it to the bundled `db` service, so you do not set it yourself. Only needed with a different database or when running without Compose, for example `postgresql://user:password@host:5432/timetrack`. | | `NEXT_PUBLIC_APP_URL` | `http://localhost:3000` | yes | no | The URL users open, without a trailing slash. Must match what the browser sees: use your `https://` domain behind a reverse proxy. See [URLs, hosts and brand](#urls-hosts-and-brand). | | `REQUIRE_EMAIL_VERIFICATION` | `true` | no | no | Set to `false` (or `0`) to let people sign up and log in without a mail server. Only honoured while no mail transport is configured: with `RESEND_API_KEY` or `SMTP_HOST` set, the flag is ignored with a warning. Anyone who can reach the instance can then create an account, so remove it once mail works. | | `ADMIN_EMAIL` | none | no | no | Instance admin addresses, comma separated. The account with a matching, verified address becomes admin. Empty: the oldest account becomes admin, but only while the instance has no admin. | ## URLs, hosts and brand | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `NEXT_PUBLIC_APP_URL` | `http://localhost:3000` | yes | no | Public URL of the app. Read at runtime; the build value is the fallback. Used for links in mails, OAuth callbacks and the default redirect URIs of the integrations. | | `NEXT_PUBLIC_MARKETING_URL` | the app URL | no | no | Separate public or marketing host. Without an explicit marketing URL, self-hosted instances of either brand redirect `/` to the dashboard and return 404 for other marketing paths. If the runtime app URL or brand changes, set the marketing URL again to opt in. Read at runtime. Needs an image built with `BUILD_PROFILE=full`; the prebuilt image has no marketing pages. | | `NEXT_PUBLIC_BRAND` | `timewren` | no | no | `timewren` (self-hosting) or `timetrack` (the Danish hosted sibling, TimeTrack Cloud). Any other value, or none, gives TimeWren. Read at runtime. | | `SUPPORT_EMAIL` | `support@` | no | no | Support address shown in mails and the UI. | | `NEXT_PUBLIC_SUPPORT_EMAIL` | none | no | yes | Older alias of `SUPPORT_EMAIL`. `SUPPORT_EMAIL` wins when both are set. | | `CONTACT_EMAIL` | `support@` | no | no | Personal contact address on marketing pages and in personal mails. Default: the support address (`SUPPORT_EMAIL`). | | `EMAIL_DOMAIN` | host of the marketing URL, else of the app URL | no | no | Domain for generated mail addresses such as `noreply@` and the `task+id@` addresses. | | `TRUSTED_ORIGINS` | none | no | no | Extra origins accepted by the auth and CSRF checks, comma separated. Invalid entries are skipped. | | `CORS_ALLOWED_ORIGINS` | browser-extension origins | no | no | Replaces the CORS allowlist of the tRPC API. Exact origins, comma separated, without trailing slashes or wildcards. Unset accepts browser-extension origins. Empty disables cross-origin access. It does not replace token authentication. | | `APP_SCHEMES` | `timetrack://,timetrack.preview://` | no | no | Native app schemes accepted by auth, comma separated. Set it to the scheme of a custom app build, for example `timewren://`. Empty disables native origins. | | `DEVICE_CALLBACK_URL` | `timewren://auth/callback` (TimeWren) / `timetrack://auth/callback` | no | no | Callback of the device login. Must be a native scheme with exactly `auth/callback`; web URLs, credentials, query and fragment are rejected. Match it to `APP_SCHEMES`. Without a value the instance brand decides (`timewren://auth/callback` for TimeWren, else `timetrack://auth/callback`); a client's `redirect_uri` is honoured only if it is on the `APP_SCHEMES` allowlist, one of the default callbacks (`timetrack://`, `timewren://`) or this value. Older clients that send no `redirect_uri` to a default self-host instance (brand TimeWren) get `timewren://`; set `DEVICE_CALLBACK_URL=timetrack://auth/callback` for them. | | `CALLBACK_BASE_URL` | the app URL | no | no | Base for stored and registered callback links, for example webhook callbacks. | | `AUTH_COOKIE_DOMAIN` | none | no | no | Shares the session cookie across hosts, for example `.example.com`. Only needed with a split app and marketing host. | | `AUTH_RP_ID` | marketing host when the hosts are split, else the app host | no | no | Passkey relying-party ID, for example `example.com`. Only needed with a split app and marketing host. | | `AUTH_COOKIE_PREFIX` | `better-auth` | no | no | Prefix of the auth cookie names. | | `SUBDOMAIN_REDIRECT_STATUS` | `308` | no | no | HTTP status of redirects between the app and marketing hosts. Set `307` while you test a host split, because browsers cache `308`. | | `APP_PORT` | `3000` | no | no | Compose only: host port of the app. | | `APP_BIND` | `127.0.0.1` | no | no | Compose only: bind address of the app port. `0.0.0.0` exposes it on all interfaces. Keep the default behind a reverse proxy, see [Reverse proxy](https://timewren.com/docs/operations/reverse-proxy.md). | | `CADDY_DOMAIN` | none | no | no | Compose only: domain for the optional automatic HTTPS overlay (`docker-compose.caddy.yml`). DNS must point at the server and TCP 80/443 must be open. | | `COMPOSE_FILE` | `docker-compose.yml` | no | no | Compose only: set to `docker-compose.yml:docker-compose.caddy.yml` to turn on the automatic HTTPS overlay together with `CADDY_DOMAIN`. | | `NEXT_PUBLIC_GOOGLE_ADS_ID` | none | no | yes | Google Ads tag ID for the marketing pages. Without it nothing is loaded on self-hosted instances. | ## Mail Pick one transport: SMTP or Resend. Without either, the server logs skipped sends. Details and examples are in [Email](https://timewren.com/docs/configuration/email.md). The transport is chosen in this order: `MAIL_TRANSPORT` if set to a valid value, otherwise Resend when `RESEND_API_KEY` is set, otherwise SMTP when `SMTP_HOST` is set, otherwise log only. | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `MAIL_TRANSPORT` | automatic | no | no | `resend`, `smtp` or `log`. Forces the transport. `smtp` requires `SMTP_HOST`. | | `SMTP_HOST` | none | conditional | no | SMTP server. Setting it selects SMTP unless `RESEND_API_KEY` is set or `MAIL_TRANSPORT` says otherwise. | | `SMTP_PORT` | `587` | no | no | SMTP port. Port `465` uses implicit TLS. | | `SMTP_SECURE` | `true` on port 465, else `false` | no | no | `true` for implicit TLS, `false` for STARTTLS. Empty uses the port rule. | | `SMTP_USER` | none | no | no | SMTP username. Authentication is only used when this is set. | | `SMTP_PASSWORD` | none | no | no | SMTP password. | | `SMTP_FROM` | the sender chosen by the app | no | no | Sender address for all SMTP mails, for example `TimeWren `. Recommended with SMTP. | | `RESEND_API_KEY` | none | conditional | no | API key for Resend. Setting it selects Resend. | | `RESEND_FROM_EMAIL` | `TimeWren >` | no | no | Default sender when sending through Resend. Use an address on a domain verified in Resend. | | `FROM_EMAIL` | `TimeWren >` | no | no | Sender of the task and notification mails. | | `PERSONAL_FROM_EMAIL` | the default sender | no | no | Sender of personal lifecycle mails. | | `PERSONAL_REPLY_TO_EMAIL` | none | no | no | Reply-To of personal lifecycle mails. Empty means no Reply-To header. | | `RESEND_WEBHOOK_SECRET` | none | no | no | Svix signing secret for Resend delivery webhooks (`/api/webhooks/resend`). | | `RESEND_AUDIENCE_ID` | none | no | no | Resend audience used for newsletter signups. | | `ADMIN_NOTIFICATION_EMAIL` | none | no | no | Receives admin alerts and digests, comma separated. An address saved in the admin settings takes precedence. | | `ADMIN_DISCORD_WEBHOOK_URL` | none | no | no | Discord webhook for admin alerts and in-app feedback. Must be `https://discord.com/api/webhooks//` (or the same on `discordapp.com`); other hosts are rejected. A URL saved in the admin settings takes precedence. | | `FEEDBACK_TO_EMAIL` | none | no | no | Receives in-app feedback by mail. Empty: feedback goes to the Discord webhook only. | ## File storage Uploads, email attachments and data exports need storage. Compose sets the local driver and mounts the `storage` volume. For S3-compatible storage (AWS, Hetzner, MinIO, R2) see [Storage](https://timewren.com/docs/configuration/storage.md). The driver is chosen like this: `STORAGE_DRIVER=local` wins; otherwise S3 is used when `S3_ENDPOINT` is set; otherwise there is no storage and uploads are switched off. The code never reads the value `s3` of `STORAGE_DRIVER`, so setting `S3_ENDPOINT` is what selects S3. | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `STORAGE_DRIVER` | `local` in Compose, otherwise none | no | no | `local` stores files on disk. Anything else falls through to the `S3_ENDPOINT` rule. | | `STORAGE_LOCAL_PATH` | `./data/storage` (Compose: `/app/data/storage`) | no | no | Directory of the local driver. Compose sets it to the `storage` volume; change it only outside Compose. | | `S3_ENDPOINT` | none | conditional | no | Endpoint of the S3-compatible service. Setting it selects S3 (path-style addressing is always used). | | `S3_REGION` | `fsn1` | no | no | Region sent to the S3 client. Most S3-compatible services accept any value, but set the real one for AWS. | | `S3_ACCESS_KEY_ID` | empty | conditional | no | S3 access key. | | `S3_SECRET_ACCESS_KEY` | empty | conditional | no | S3 secret key. | | `S3_BUCKET` | `timetrack` | no | no | Bucket name. | | `S3_PREFIX` | empty | no | no | Optional namespace for all keys inside the bucket. | | `EMAIL_ATTACHMENT_DIR` | `storage/email-attachments` | no | no | Directory that older email attachments are read from on disk. | | `EMAIL_SYNC_STORE_ATTACHMENTS` | `false` | no | no | `true` uploads attachments from email-to-task sync to the configured storage. | ## Authentication and login providers Email and password, magic links and passkeys work without any of these. Each social provider needs your own OAuth app, with the callback URL `{NEXT_PUBLIC_APP_URL}/api/auth/callback/`. A provider is enabled when both its ID and secret are set. See [Authentication](https://timewren.com/docs/configuration/authentication.md). | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `GOOGLE_CLIENT_ID` | none | no | no | Google sign-in. Also used by the Google Calendar integration. | | `GOOGLE_CLIENT_SECRET` | none | no | no | Secret for the Google OAuth app. | | `GITHUB_CLIENT_ID` | none | no | no | GitHub sign-in. | | `GITHUB_CLIENT_SECRET` | none | no | no | Secret for the GitHub OAuth app. | | `DISCORD_CLIENT_ID` | none | no | no | Discord sign-in. | | `DISCORD_CLIENT_SECRET` | none | no | no | Secret for the Discord OAuth app. | | `MICROSOFT_CLIENT_ID` | none | no | no | Microsoft Entra ID (Azure AD) sign-in, for example company SSO. Callback: `{NEXT_PUBLIC_APP_URL}/api/auth/callback/microsoft-entra-id`. | | `MICROSOFT_CLIENT_SECRET` | none | no | no | Secret for the Entra ID app. | | `MICROSOFT_TENANT_ID` | `common` | no | no | `common`, `organizations` or a tenant GUID. | | `APPLE_CLIENT_ID` | none | no | no | Sign in with Apple: the Services ID, used for web login. | | `APPLE_TEAM_ID` | none | no | no | Apple developer team ID. | | `APPLE_KEY_ID` | none | no | no | ID of the Sign in with Apple key. | | `APPLE_PRIVATE_KEY` | none | no | no | Contents of the `.p8` key. The client secret is generated from it at startup. | | `APPLE_APP_BUNDLE_IDENTIFIER` | `dk.timetrack.app` | no | no | iOS bundle ID, used for native login and for revoking the token when an account is deleted. Set your own if you build the mobile app yourself. | | `SESSION_EXPIRY_DAYS` | `7` | no | no | Session lifetime in days. | | `BETTER_AUTH_SECRETS` | none | no | no | Versioned secrets for rotating `BETTER_AUTH_SECRET` without losing encrypted tokens. | ## Integrations Billy needs nothing here: each user pastes their own Billy API key in the app. See [Billy](https://timewren.com/docs/integrations/billy.md), [Dinero](https://timewren.com/docs/integrations/dinero.md), [e-conomic](https://timewren.com/docs/integrations/e-conomic.md), [Calendar](https://timewren.com/docs/integrations/calendar.md) and [CVR](https://timewren.com/docs/integrations/cvr.md). | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `GOOGLE_REDIRECT_URI` | `{NEXT_PUBLIC_APP_URL}/api/integrations/google/callback` | no | no | OAuth redirect URI of the Google Calendar integration. Uses `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`. | | `OUTLOOK_CALENDAR_CLIENT_ID` | none | no | no | Client ID of a Microsoft Entra ID app registration for the Outlook calendar integration (Microsoft Graph, read only). With its secret, the Outlook calendar is offered under Settings, Integrations; without it, Outlook is hidden. The sign-in app (`MICROSOFT_CLIENT_ID`) is never used for it. | | `OUTLOOK_CALENDAR_CLIENT_SECRET` | none | no | no | Client secret of the Outlook calendar app. | | `OUTLOOK_CALENDAR_TENANT_ID` | `common` | no | no | Microsoft tenant for the Outlook calendar: `common`, `organizations`, `consumers` or a tenant GUID. | | `OUTLOOK_CALENDAR_REDIRECT_URI` | `{NEXT_PUBLIC_APP_URL}/api/integrations/outlook/callback` | no | no | OAuth redirect URI of the Outlook calendar integration. | | `DINERO_CLIENT_ID` | none | conditional | no | Visma Connect OAuth app for Dinero. Both ID and secret are needed to enable the integration. | | `DINERO_CLIENT_SECRET` | none | conditional | no | Secret of the Visma Connect app. | | `DINERO_REDIRECT_URI` | `{NEXT_PUBLIC_APP_URL}/api/integrations/dinero/callback` | no | no | OAuth redirect URI for Dinero. | | `DINERO_WEBHOOK_SECRET` | none | no | no | Secret used to verify Dinero webhooks. | | `BILLY_WEBHOOK_SECRET` | none | no | no | Secret used to verify Billy webhooks. | | `ECONOMIC_APP_PUBLIC_TOKEN` | none | conditional | no | Public token of your app registered at the e-conomic developer portal. Both tokens are needed to enable the integration. | | `ECONOMIC_APP_SECRET_TOKEN` | none | conditional | no | Secret token of the e-conomic app. | | `ECONOMIC_REDIRECT_URI` | `{NEXT_PUBLIC_APP_URL}/api/integrations/economic/callback` | no | no | Redirect URI for e-conomic. | | `CVR_SERVICE_API_KEY` | none | no | no | Key for the CVR lookup service. Empty: lookups fall back to the free cvrapi.dk. | | `CVR_SERVICE_URL` | the maintainer's CVR service | no | no | Base URL of the CVR lookup service used together with `CVR_SERVICE_API_KEY`. | | `CVR_API_TIMEOUT_MS` | `10000` | no | no | Timeout of CVR lookups in milliseconds. | | `GITHUB_TOKEN` | none | no | no | GitHub token for desktop-update lookups, giving a higher rate limit. | | `NEXT_PUBLIC_DESKTOP_RELEASES_REPO` | `mahope/timetrack-releases` (TimeTrack) | no | yes | GitHub `owner/repo` for desktop downloads. Defaults to `mahope/timetrack-releases` in TimeTrack builds and is otherwise disabled unless set. A runtime brand change keeps the build’s download repository. | | `DESKTOP_UPDATER_REPO` | none | no | no | GitHub `owner/repo` for legacy desktop updates. Disabled unless set. | | `CHANGELOG_REPO` | none | no | no | GitHub `owner/repo` the changelog is read from. Disabled unless set. | ## AI, SMS, push and email-to-task | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `OPENAI_API_KEY` | none | no | no | Enables AI suggestions and categorisation. | | `AI_PROVIDER` | `openai` | no | no | The server's own AI provider: `openai`, `anthropic`, `mistral` or `openai-compatible` (Ollama, vLLM, LM Studio). See [AI](https://timewren.com/docs/configuration/ai.md). | | `AI_BASE_URL` | none | no | no | URL of the server's model, for example `http://ollama:11434/v1`. Required for `openai-compatible`. | | `AI_MODEL` | per provider (`gpt-4o-mini` for OpenAI) | no | no | Model name of the server's AI, for example `qwen2.5:3b`. | | `AI_API_KEY` | `OPENAI_API_KEY` for OpenAI | no | no | Key for the server's AI provider. Not needed for a local server. | | `AI_SYSTEM_FOR_ALL` | `false` | no | no | Set to `true` to let every AI feature use the server's AI, including those that otherwise need a personal or organisation key. Meant for self-hosted instances with a local model. | | `AI_SYSTEM_ONLY` | `false` | no | no | Set to `true` to use only the server's AI. Keys saved on organisations or by users are ignored, so no text reaches a cloud provider. Set by `docker-compose.ollama.yml`. | | `AI_ALLOW_PRIVATE_URLS` | `false` | no | no | Set to `true` to let users and organisations point AI at private or plain HTTP addresses, such as a local Ollama. Leave it off on a public multi-tenant instance. | | `AI_ENGINE` | `ai-sdk` | no | no | Set to `openai-legacy` to run OpenAI-compatible providers through the older `openai` client instead of the AI SDK. A kill switch while the new layer settles. | | `AI_CACHE_TTL_MS` | `60000` | no | no | Lifetime of cached AI results in milliseconds. | | `AI_HIGH_CONFIDENCE_THRESHOLD` | `0.8` | no | no | Confidence from which an AI suggestion counts as high confidence. | | `MESSAGEBIRD_API_KEY` | none | no | no | Enables SMS login via MessageBird. | | `MESSAGEBIRD_ORIGINATOR` | the brand short name (`TimeWren`) | no | no | Sender name of SMS messages. | | `NEXT_PUBLIC_VAPID_PUBLIC_KEY` | none | no | no | Public VAPID key for Web Push. The server hands it to the browser, so it is read at runtime. Generate a key pair with `npx web-push generate-vapid-keys`. | | `VAPID_PRIVATE_KEY` | none | no | no | Private VAPID key. Web Push is on when both keys are set. | | `VAPID_EMAIL` | `mailto:support@` | no | no | Contact sent with push messages, as a `mailto:` URL. | | `EXPO_ACCESS_TOKEN` | none | no | no | Optional Expo access token for push notifications to the mobile app. | | `INBOUND_EMAIL_DOMAIN` | the email domain | no | no | Domain of the email-to-task addresses. | ## Valkey and realtime Valkey is optional. It gives rate limits shared between processes and realtime timer sync. Start it with `docker compose --profile valkey up -d`, or set `COMPOSE_PROFILES=valkey` in `.env`. | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `VALKEY_URL` | none | no | no | Connection URL, for example `redis://valkey:6379`. Without it everything falls back to in-memory behaviour. | | `RATE_LIMIT_BACKEND` | in-memory | no | no | `valkey` stores rate limits in Valkey. Any other value keeps them in memory. | | `REALTIME_ENABLED` | `true` in the Docker image | no | no | Server flag for realtime timer events. Realtime also needs `VALKEY_URL`. Set `false` to switch it off without a rebuild. | | `NEXT_PUBLIC_REALTIME_ENABLED` | none | no | yes | Client flag, must be `true` at build time. Both this and `REALTIME_ENABLED` must be `true`. The prebuilt image does not set it. | | `BUILD_PROFILE` | `full` | no | yes | Build argument and variable for `npm run build`. `selfhost` leaves the Cloud marketing site and the TimeWren website out of the build (shorter build, smaller image); the prebuilt image uses it. `full` also builds the marketing pages that `NEXT_PUBLIC_MARKETING_URL` enables. | | `REACT_COMPILER` | `annotation` | no | yes | Build argument and variable for `npm run build`. React Compiler mode: `annotation` compiles only components marked `"use memo"`, `infer` compiles every component it can analyse, `off` turns it off. Any other value fails the build. | | `REACT_COMPILER_RUST` | unset | no | yes | Build variable. `1` also uses Next.js' experimental Rust port of React Compiler. Ignored when `REACT_COMPILER=off`. | | `ELECTRIC_URL` | none | no | no | Experimental ElectricSQL timer shape proxy. Inert unless both variables are set; the endpoints then answer 503 and clients fall back. | | `ELECTRIC_SECRET` | none | no | no | Secret for the ElectricSQL proxy. | ## Telemetry and monitoring Nothing is sent to the maintainers unless you set these. See also [Troubleshooting](https://timewren.com/docs/operations/troubleshooting.md). | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL` | none | no | yes | URL of a Plausible analytics script. Empty: no Plausible script is loaded. Also added to the CSP. | | `NEXT_PUBLIC_UMAMI_SCRIPT_URL` | none | no | yes | URL of the Umami tracker script. Used when no collection URL is configured. Events go to the collector built into the tracker. A same-origin script that proxies Umami Cloud (for example `/stats.js`) sends through `/api/send` next to it instead of `gateway.umami.is`. | | `NEXT_PUBLIC_UMAMI_COLLECT_URL` | none | no | yes | Full collection URL or same-origin path, including any custom path. With the website ID and analytics consent, sends tool events immediately with keepalive. | | `NEXT_PUBLIC_UMAMI_WEBSITE_ID` | none | no | yes | Website ID for the Umami collector. | | `PLAUSIBLE_BASE_URL` | `https://plausible.io` | no | no | Plausible host used by the admin analytics page. | | `PLAUSIBLE_SITE_ID` | none | no | no | Plausible site ID for the admin analytics page. | | `PLAUSIBLE_API_KEY` | none | no | no | Plausible API key. The admin analytics page needs this and `PLAUSIBLE_SITE_ID` (for both brands) or a brand's `plausibleSiteId` in `BRANDS_CONFIG`. | | `NEXT_PUBLIC_SENTRY_DSN` | none | no | yes | Sentry DSN for errors. Empty: Sentry reports nothing. | | `NEXT_PUBLIC_SENTRY_BROWSER_ENABLED` | enabled | no | yes | `false` disables Sentry in the browser. | | `NEXT_PUBLIC_SENTRY_ENVIRONMENT` | derived from the host | no | yes | Environment name sent with browser errors. | | `SENTRY_AUTH_TOKEN` | none | no | no | Source map upload at build time, and API access for the Sentry issue lookup. | | `SENTRY_ACCESS_TOKEN` | none | no | no | Token for the Sentry issue lookup; takes precedence over `SENTRY_AUTH_TOKEN`. | | `SENTRY_API_URL` | `https://sentry.io` | no | no | Sentry API base URL, for self-hosted Sentry. | | `SENTRY_WEBHOOK_SECRET` | none | no | no | Secret that verifies Sentry webhooks. | | `SENTRY_DISABLED` | none | no | yes | `1` turns the Sentry build plugin off. The Dockerfile sets it during the image build. | ## Tuning All optional. The defaults are the values used by TimeWren unless you change them. | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `DEFAULT_WEEKLY_HOUR_GOAL` | `37` | no | no | Default weekly hour goal for new users. | | `PRODUCTIVITY_HEATMAP_DAYS` | `90` | no | no | Number of days in the productivity heatmap. | | `PREPAID_LOW_BALANCE_THRESHOLD` | `0.2` | no | no | Fraction of a [prepaid hours](https://timewren.com/docs/concepts/prepaid-hours.md) package left that counts as low. | | `PREPAID_CRITICAL_BALANCE_HOURS` | `1` | no | no | Hours left that count as critical, on top of the fraction rule. | | `PREPAID_EXPIRY_WARNING_DAYS` | `30` | no | no | How many days before expiry a package triggers a warning. | | `MAX_MONETARY_AMOUNT` | `100000000` | no | no | Upper limit for a single monetary amount. | | `PDF_ENGINE` | `react-pdf` | no | no | Invoice PDF renderer. `takumi` is an experimental alternative. | | `CHURN_PLAYBOOKS_DISABLED` | none | no | no | `1` switches the churn-playbook cron job off. | | `CRON_LOG_RETENTION_DAYS` | `90` | no | no | Days of cron run history kept in `cron_job_logs`. The daily `webhook-cleanup` job deletes older rows, and the admin cron overview looks no further back. Values below 62 days (twice the longest job interval) are raised to 62. | | `MIGRATE_ON_START` | `1` in Compose | no | no | `1` runs database migrations on every start. Without it migrations are skipped (outside Compose the default is off). See [Upgrading](https://timewren.com/docs/operations/upgrading.md). | | `MIGRATION_LOCK_TIMEOUT_MS` | `300000` | no | no | How long a starting container waits for another one to finish migrating. Invalid values use the default. | | `SEED_DEMO_ORGS` | `false` | no | no | `true` seeds a demo organisation on startup. | | `MIN_CLIENT_VERSIONS` | none | no | no | Minimum client versions per client type, for example `extension=2.5.2,mobile=1.0.0+5,desktop=0.2.21`. Older clients can still read but timer and time writes are rejected. Empty: no enforcement. | | `MIN_CLIENT_VERSIONS_MODE` | enforce | no | no | `observe` evaluates the minimums and shows outdated clients in the admin area without rejecting anything. | | `SYNTHETIC_USER_EMAILS` | none | no | no | Email addresses of monitoring or test accounts that are excluded from stats and mails, comma separated. | | `SYNTHETIC_USER_IDS` | none | no | no | User IDs of those accounts, comma separated. | ## Docker Compose and startup Compose sets some of these itself; they are listed so you know where they come from. | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `TIMEWREN_VERSION` | `latest` | no | no | Compose only: image tag to run. Pin it, for example `1.2.3`, to control upgrades. | | `COMPOSE_PROFILES` | none | no | no | Read by Docker Compose, not by the app. Use `valkey` to start the optional Valkey service. | | `TZ` | `Europe/Copenhagen` | no | no | Timezone of the app and database containers. The `cron` container always runs in `Europe/Copenhagen`. | | `APP_URL` | `http://app:3000` | yes (cron) | no | Only read by the `cron` container: the internal URL it calls the `/api/cron/*` endpoints on. Compose sets it; do not confuse it with `NEXT_PUBLIC_APP_URL`. | | `NODE_ENV` | `production` in the image | no | no | Set by the image and by `npm run dev`. Leave it alone when self-hosting. | | `NEXT_PHASE` | set by Next.js | no | no | Set by Next.js (`phase-production-build` during `next build`). During the build the MCP OAuth resource is not written to the database. Never set it yourself. | | `NEXT_RUNTIME` | set by Next.js | no | no | Set by Next.js (`nodejs` or `edge`). Never set it yourself. | | `CI` | none | no | no | Silences build logs of the Sentry plugin when set. Set by CI systems. | | `CI_SKIP_TYPECHECK` | `false` | no | yes | Build argument of the Dockerfile: `true` skips the type check during `next build`. Only for CI builds that type-check separately. | | `APP_VERSION` | none | no | no | Version string of the deploy, read by the server at runtime and used to detect a new deploy in open tabs. The Dockerfile sets it from the `APP_VERSION` build argument; changing it needs no rebuild. Empty uses the Next.js build ID. | | `NEXT_PUBLIC_APP_VERSION` | none | no | no | Old name for `APP_VERSION`, still read as a fallback at runtime when `APP_VERSION` is empty. | ## Hosted service only > **Warning:** Not for self-hosting. These variables belong to the hosted TimeTrack Cloud and TimeWren Cloud deployments. Leave them unset on your own instance. The `ALUNTA_*`, `STRIPE_*`, `STORE_BILLING_ENABLED` and `GOOGLE_PLAY_*` variables are the billing variables described at the top of the page. | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `DEMO_MODE` | none | no | no | `1` turns the instance into the public demo: one sandbox per visitor, no mail, payments or integrations, and accounts deleted after 24 hours. Only for demo.timewren.com; see `docs/demo.md` in the repository. | | `ALUNTA_API_KEY` | none | no | no | Turns billing on and enables the Alunta payment provider. | | `ALUNTA_WEBHOOK_SECRET` | none | with `ALUNTA_API_KEY` | no | Verifies Alunta webhooks. Without it the webhook answers 503 and processes nothing. | | `ALUNTA_WEBHOOK_ALLOW_UNSIGNED` | none | no | no | `1` or `true` accepts Alunta webhooks without a signature when the secret is set. Development only; ignored when `NODE_ENV=production`. | | `ALUNTA_PLAN_MONTHLY` | empty | no | no | Alunta plan ID of the monthly plan. | | `ALUNTA_PLAN_YEARLY` | empty | no | no | Alunta plan ID of the yearly plan. | | `ALUNTA_PLAN_TEAM_MONTHLY` | empty | no | no | Alunta plan ID, Team, monthly. | | `ALUNTA_PLAN_TEAM_YEARLY` | empty | no | no | Alunta plan ID, Team, yearly. | | `ALUNTA_PLAN_BUSINESS_MONTHLY` | empty | no | no | Alunta plan ID, Business, monthly. | | `ALUNTA_PLAN_BUSINESS_YEARLY` | empty | no | no | Alunta plan ID, Business, yearly. | | `ALUNTA_PLAN_TEAM_SEATS` | empty | no | no | Alunta plan ID for extra Team seats. | | `ALUNTA_PLAN_BUSINESS_SEATS` | empty | no | no | Alunta plan ID for extra Business seats. | | `ALUNTA_PLAN_PRIVAT_MONTHLY` | empty | no | no | Alunta plan ID, Privat, monthly. | | `ALUNTA_PLAN_PRIVAT_YEARLY` | empty | no | no | Alunta plan ID, Privat, yearly. | | `ALUNTA_PLAN_FOUNDING_MONTHLY` | empty | no | no | Alunta plan ID, founding plan, monthly. | | `ALUNTA_PLAN_FOUNDING_YEARLY` | empty | no | no | Alunta plan ID, founding plan, yearly. | | `ALUNTA_PLAN_LEGACY_SOLO` | empty | no | no | Alunta plan IDs of the legacy solo plan. | | `ALUNTA_PLAN_LEGACY_TEAM` | empty | no | no | Alunta plan IDs of the legacy Team plan. | | `ALUNTA_PLAN_LEGACY_BUSINESS` | empty | no | no | Alunta plan IDs of the legacy Business plan. | | `ALUNTA_PLAN_LEGACY_TEAM_SEATS` | empty | no | no | Alunta plan ID for extra seats on the legacy Team plan. | | `ALUNTA_PLAN_LEGACY_BUSINESS_SEATS` | empty | no | no | Alunta plan ID for extra seats on the legacy Business plan. | | `STRIPE_SECRET_KEY` | none | no | no | Turns billing on and enables Stripe. | | `STRIPE_WEBHOOK_SECRET` | none | no | no | Verifies Stripe webhooks. | | `STRIPE_TAX_ENABLED` | `false` | no | no | `true` enables Stripe Tax. | | `STRIPE_DESKTOP_LIFETIME_PRICE_ID` | empty | no | no | Stripe price ID of the desktop lifetime licence. | | `STRIPE_TIMEWREN_PORTAL_CONFIGURATION` | empty | no | no | Multibrand Cloud only: Stripe billing portal configuration for TimeWren accounts. Empty: found or created by metadata `brand=timewren`. | | `STORE_BILLING_ENABLED` | none | no | no | `1` turns billing on for in-app purchases (App Store and Google Play). | | `GOOGLE_PLAY_SERVICE_ACCOUNT_JSON` | none | no | no | Service account for verifying Google Play purchases. | | `GOOGLE_PLAY_PACKAGE_NAME` | none | no | no | Android package name for Google Play. | | `GOOGLE_PLAY_WEBHOOK_TOKEN` | none | no | no | Token in the Google Play notification URL. | | `FREE_TRIAL_DAYS` | `30` | no | no | Length of the free trial. Only has an effect when billing is on. | | `DOKPLOY_API_URL` | none | no | no | Hosting API used to register customer domains. | | `DOKPLOY_API_TOKEN` | none | no | no | Token for that hosting API. | | `DOKPLOY_APP_ID` | none | no | no | Application ID in that hosting API. All three `DOKPLOY_*` variables are needed. | | `CLAUDE_AGENT_API_KEY` | none | no | no | Key used by the Sentry webhook to trigger an automated fix agent. | | `CLAUDE_AGENT_TRIGGER_URL` | none | no | no | Trigger URL for that agent. | | `UNBLOCK_PLAN_EMAIL` | none | no | no | One-off plan grant applied during the migration step at release. | | `UNBLOCK_PLAN_TIER` | `team` | no | no | Plan tier for that grant. | | `UNBLOCK_PLAN_SEATS` | none | no | no | Seat count for that grant. | | `SHARED_PROD_DB` | none | no | no | `1` when the database is shared with an older version; disables features that older version cannot handle. | | `MULTIBRAND_ENABLED` | none | no | no | `1` enables the multi-brand host registry of the hosted service. | | `BRANDS_CONFIG` | built-in placeholders | no | no | JSON with the real brand hosts of the hosted multi-brand setup. | | `TIMEWREN_APP_ENABLED` | none | no | no | `1` opens the app (login, sign-up, dashboard) on the hosted TimeWren hosts. | | `TIMEWREN_GOOGLE_CLIENT_ID` | none | no | no | Client ID of the TimeWren Cloud Google app. With its secret, Google sign-in is offered on the TimeWren hosts; without it, the button is hidden and the provider is not registered there. The TimeTrack keys are never used on TimeWren hosts. | | `TIMEWREN_GOOGLE_CLIENT_SECRET` | none | no | no | Client secret of the TimeWren Cloud Google app. | | `TIMEWREN_GITHUB_CLIENT_ID` | none | no | no | Client ID of the TimeWren Cloud GitHub app. With its secret, GitHub sign-in is offered on the TimeWren hosts; without it, the button is hidden and the provider is not registered there. The TimeTrack keys are never used on TimeWren hosts. | | `TIMEWREN_GITHUB_CLIENT_SECRET` | none | no | no | Client secret of the TimeWren Cloud GitHub app. | | `TIMEWREN_DISCORD_CLIENT_ID` | none | no | no | Client ID of the TimeWren Cloud Discord app. With its secret, Discord sign-in is offered on the TimeWren hosts; without it, the button is hidden and the provider is not registered there. The TimeTrack keys are never used on TimeWren hosts. | | `TIMEWREN_DISCORD_CLIENT_SECRET` | none | no | no | Client secret of the TimeWren Cloud Discord app. | | `TIMEWREN_MICROSOFT_CLIENT_ID` | none | no | no | Client ID of the TimeWren Cloud Microsoft Entra ID app. With its secret, Microsoft Entra ID sign-in is offered on the TimeWren hosts; without it, the button is hidden and the provider is not registered there. The TimeTrack keys are never used on TimeWren hosts. | | `TIMEWREN_MICROSOFT_CLIENT_SECRET` | none | no | no | Client secret of the TimeWren Cloud Microsoft Entra ID app. | | `TIMEWREN_MICROSOFT_TENANT_ID` | `common` | no | no | Microsoft tenant for TimeWren Cloud sign-in, like `MICROSOFT_TENANT_ID`. | | `TIMEWREN_GOOGLE_REDIRECT_URI` | `https:///api/integrations/google/callback` | no | no | Google Calendar redirect URI for TimeWren Cloud accounts. Google Calendar on TimeWren uses `TIMEWREN_GOOGLE_CLIENT_ID` and `TIMEWREN_GOOGLE_CLIENT_SECRET`; without them TimeWren accounts see "coming soon". | | `TIMEWREN_OUTLOOK_CLIENT_ID` | none | no | no | Client ID of the TimeWren Cloud Outlook calendar app. Without it, the TimeWren Microsoft sign-in app (`TIMEWREN_MICROSOFT_CLIENT_ID`) is used for the calendar too, if set. | | `TIMEWREN_OUTLOOK_CLIENT_SECRET` | none | no | no | Client secret of the TimeWren Cloud Outlook calendar app. | | `TIMEWREN_OUTLOOK_REDIRECT_URI` | `https:///api/integrations/outlook/callback` | no | no | Outlook calendar redirect URI for TimeWren Cloud accounts. | | `TIMEWREN_APPLE_CLIENT_ID` | none | no | no | Services ID of the TimeWren Cloud Sign in with Apple app. Signed with the team key (`APPLE_TEAM_ID`, `APPLE_KEY_ID`, `APPLE_PRIVATE_KEY`). | **TimeWren Cloud trial reminders.** Enable trial-ending reminder emails in Stripe Dashboard under Subscriptions and emails. Stripe sends these reminders for Stripe trials. The app does not send its own. [Stripe setup guide](https://docs.stripe.com/billing/subscriptions/trials/manage-trial-compliance#stripe-hosted-reminder-emails) ## Development and tests only > **Warning:** These variables are for developing TimeWren itself. Do not set them in production. For a local setup without Docker (`npm run dev`), put `DATABASE_URL` in `.env.local`, for example `postgresql://postgres:postgres@localhost:5432/freelance_crm`. `npm run docker:up` starts a matching PostgreSQL from `docker-compose.dev.yml`. | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `TT_DB_TESTS` | none | no | no | `1` runs the database-backed timer model tests. They need `DATABASE_URL` pointing at a disposable database. | | `DATABASE_CONNECT_TIMEOUT` | `10` | no | no | Seconds the app waits for a new database connection. CI sets `60` for the model tests on shared runners. | | `TT_MODEL_RUNS` | `150` | no | no | Number of generated command sequences in the timer model test. | | `TT_MODEL_SEED` | fixed seed | no | no | Seed of the timer model test. `random` explores new sequences. | | `TT_MODEL_MAX_COMMANDS` | `30` | no | no | Maximum commands per generated sequence. | | `TT_MODEL_PATH` | none | no | no | Replays one counterexample, for example `4:2:1`, together with `TT_MODEL_SEED`. | | `TT_MODEL_DEBUG` | none | no | no | When set, the timer model test prints extra debug output. | | `TT_QUERY_COUNT` | none | no | no | `1` counts database queries per tRPC request. Ignored when `NODE_ENV` is `production`. | ## Instance operations | Variable | Default | Required | Build time | Description | | --- | --- | --- | --- | --- | | `UPDATE_CHECK` | on | no | no | Set to `off` to disable the release check and lock its setting. The check only runs in `BUILD_PROFILE=selfhost` builds. | | `BACKUP_STATUS_FILE` | none | no | no | Path in the app container to a marker file whose modification time records the last successful backup. | --- # Email > Send mail from TimeWren with SMTP or Resend, choose the transport, set sender addresses and check that delivery works. Source: https://timewren.com/docs/configuration/email TimeWren sends mail for sign-up verification, invitations, reminders, invoices and reports. You choose one transport in `.env`: SMTP, Resend, or none (log only). Without a transport, nothing is sent. ## Choosing a transport The app picks the first rule that matches: 1. `MAIL_TRANSPORT` is set to `resend`, `smtp` or `log` (case-insensitive). This forces the choice. 2. `RESEND_API_KEY` is set: Resend. 3. `SMTP_HOST` is set: SMTP. 4. Otherwise: log only. If both `RESEND_API_KEY` and `SMTP_HOST` are set, Resend wins unless you set `MAIL_TRANSPORT=smtp`. Forcing `MAIL_TRANSPORT=smtp` without `SMTP_HOST` makes every send fail with an error. ## SMTP ```dotenv SMTP_HOST=smtp.example.com SMTP_PORT=587 SMTP_USER=jane@example.com SMTP_PASSWORD=YOUR_SMTP_PASSWORD SMTP_FROM="TimeWren " ``` | Variable | Behaviour | | -------- | --------- | | `SMTP_HOST` | Server name. Required for SMTP. | | `SMTP_PORT` | Defaults to `587`. | | `SMTP_SECURE` | `true` means implicit TLS. Any other non-empty value means STARTTLS. When empty or unset, it is `true` only on port 465. | | `SMTP_USER`, `SMTP_PASSWORD` | Used for authentication only when `SMTP_USER` is set. | | `SMTP_FROM` | Overrides the sender of every mail. Recommended with SMTP, because your provider usually only accepts verified addresses. | ## Resend ```dotenv RESEND_API_KEY=YOUR_RESEND_API_KEY RESEND_FROM_EMAIL="TimeWren " ``` `RESEND_FROM_EMAIL` must belong to a domain you have verified in Resend. ## Sender addresses | Variable | Used for | | -------- | -------- | | `SMTP_FROM` | Sender of all mail when the SMTP transport is used. | | `RESEND_FROM_EMAIL` | Default sender for most mail (invoices, reminders, reports). | | `EMAIL_DOMAIN` | Domain for generated addresses such as `noreply@`. When empty it is the host of `NEXT_PUBLIC_MARKETING_URL`, else of `NEXT_PUBLIC_APP_URL`. | | `SUPPORT_EMAIL` | Support address shown in mails and the UI. When empty it is `support@` plus `EMAIL_DOMAIN`. | | `FROM_EMAIL` | Sender for some notification mails. | | `PERSONAL_FROM_EMAIL` | Sender of personal lifecycle mails. When empty the default sender is used. | Without `RESEND_FROM_EMAIL`, the default sender is `TimeWren `, where `DOMAIN` comes from `EMAIL_DOMAIN`. With Resend you will want to set `RESEND_FROM_EMAIL` explicitly. ## Email verification People must verify their address before they can sign in. `REQUIRE_EMAIL_VERIFICATION=false` skips this, but only while no transport is configured. As soon as SMTP or Resend is set up, the flag is ignored (a warning is logged) and verification is required again. Running without mail and without verification means anyone who can reach the instance can create an account with any address. Configure mail and remove the flag before you expose the instance. ## ADMIN_EMAIL `ADMIN_EMAIL` is a comma-separated list of the admin addresses. When it is empty, the first account created becomes the instance admin. With verification switched off, an unverified sign-up can claim an `ADMIN_EMAIL` address before you do, so create your account first or configure mail. ## Testing that mail works Once SMTP or Resend is configured, open Admin → Settings → Instance and choose **Send test mail**. The message goes to the email address of the administrator who is signed in. Restart the app after changing `.env` (`docker compose up -d`), then trigger a mail, for example by inviting a user or signing up a second account. Watch the log: ```bash docker compose logs -f app ``` | Log line | Meaning | | -------- | ------- | | `[Mail] Ingen mail-transport er sat (RESEND_API_KEY eller SMTP_HOST)...` | No transport is configured. Printed once per start. | | `[Mail:log] Mail suppressed` | The transport skipped sending a mail. It logs no message details. | | `[Mail] SMTP-afsendelse fejlede` | The SMTP send failed. Check your provider’s sending log for details. | Some of these messages are in Danish, because they come from the same code base as TimeTrack Cloud. No log line is written for a successful SMTP send. If there is no error and the mail does not arrive, check the spam folder and your provider's sending log. ## Resend webhooks Resend delivery webhooks are optional. The endpoint is `/api/webhooks/resend`. 1. In Resend, create a webhook with the URL `https://timewren.example.com/api/webhooks/resend`. 2. Select the events `email.delivered`, `email.bounced`, `email.failed` and, for inbound mail, `email.received`. 3. Copy the signing secret into `.env` as `RESEND_WEBHOOK_SECRET` and run `docker compose up -d`. Requests without a valid Svix signature are rejected, and the endpoint refuses requests while `RESEND_WEBHOOK_SECRET` is unset. --- # File storage > Where TimeWren keeps uploads, attachments and exports: a local Docker volume or an S3-compatible bucket. Source: https://timewren.com/docs/configuration/storage TimeWren stores files on local disk by default. You can switch to any S3-compatible service instead. ## What is stored - Uploads: avatars, logos and task images. - Email attachments, only when `EMAIL_SYNC_STORE_ATTACHMENTS=true` (see below). - Data exports. Without any storage configured, uploads are switched off. ## Local volume `docker-compose.yml` sets `STORAGE_DRIVER=local` and `STORAGE_LOCAL_PATH=/app/data/storage`, and mounts the named volume `storage` there. Under the default project name the volume is called `timetrack_storage`. Files live in `objects/` and their metadata in `meta/` below that path. The app runs as uid 1001 (user `nextjs`). The volume must be writable by that user. If uploads fail with a permission error, fix the ownership: ```bash docker run --rm -v timetrack_storage:/data alpine chown -R 1001:1001 /data ``` Include the volume in your [backups](https://timewren.com/docs/operations/backup-restore.md); `scripts/backup.sh` archives it for you. ## S3-compatible storage Works with AWS S3, Hetzner Object Storage, Cloudflare R2, MinIO and similar. In `.env`: ```dotenv S3_ENDPOINT=https://s3.example.com S3_REGION=eu-central-1 S3_ACCESS_KEY_ID=YOUR_ACCESS_KEY_ID S3_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY S3_BUCKET=timewren S3_PREFIX=prod ``` The driver is chosen like this: - `STORAGE_DRIVER=local`: local disk, even if `S3_ENDPOINT` is set. - Otherwise, S3 when `S3_ENDPOINT` is set. - Otherwise, no storage. `docker-compose.yml` defaults `STORAGE_DRIVER` to `local`, so to use S3 you must change it. Set `STORAGE_DRIVER` to any value other than `local` (for example `s3`) and set `S3_ENDPOINT`; the value `s3` itself is not read, only `local` has a meaning. Then run `docker compose up -d`. | Variable | Notes | | -------- | ----- | | `S3_ENDPOINT` | Full URL of the service. Required. Path-style addressing is always used. | | `S3_REGION` | Defaults to `fsn1`. Set it to your provider's region. | | `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY` | Credentials with read, write and delete access to the bucket. | | `S3_BUCKET` | Defaults to `timetrack`. | | `S3_PREFIX` | Optional. Prefixes every key, so several instances can share one bucket. | The app lists and deletes object versions when it removes personal data, so give the credentials the rights for that if your bucket is versioned. ## Switching drivers Files are not migrated automatically in either direction. After switching from local to S3 (or back), existing files stay where they were and the app will not find them. Copy them yourself, keeping the layout the app expects, before you switch, or accept that old uploads disappear from the interface. ## Email attachments By default the IMAP email sync keeps only attachment metadata (name, size, type). Set `EMAIL_SYNC_STORE_ATTACHMENTS=true` to upload the files to your storage (local or S3). Attachments larger than 10 MB are never stored, and with no storage configured the sync falls back to metadata only. `EMAIL_ATTACHMENT_DIR` (default `storage/email-attachments`, relative to the app's working directory) is the legacy local path that older attachments are read from. You normally leave it alone. --- # Authentication > Sign-in methods in TimeWren: email and password, magic link, passkeys, 2FA, SMS, OAuth providers, the first admin account and secret rotation. Source: https://timewren.com/docs/configuration/authentication TimeWren uses [Better Auth](https://www.better-auth.com). Email and password sign-in always works. Everything else is optional and switches on when you set the matching variables. All variables are listed in `.env.example`; see also [Environment variables](https://timewren.com/docs/configuration/environment.md). ## Email and password Users sign up with email and password. Passwords are reset by mail (the link is valid for 1 hour). Email verification is required by default: a new user must click the link in the verification mail (valid for 24 hours) before signing in. Verification mails need a configured mail transport, see [Email](https://timewren.com/docs/configuration/email.md). You can switch verification off only when no mail transport is configured: ```dotenv REQUIRE_EMAIL_VERIFICATION=false ``` The flag is ignored as soon as SMTP or Resend is set. The app logs a warning in that case. > **Warning:** With verification off, anyone who can reach the instance can create an account with any address, including the address in `ADMIN_EMAIL`. Use it to get started, then configure mail and remove the line before exposing the instance. Sign-in attempts are rate limited: 5 password sign-ins per 15 minutes, 10 sign-ups per 15 minutes. ## The first admin The instance admin role is assigned automatically: - If `ADMIN_EMAIL` is set (comma separated list), the account with that address becomes instance admin. - If it is empty, the first account created becomes admin, but only while the instance has no admin yet. Promotion happens at sign-up and at sign-in. When verification is required, only a verified address is promoted. Every new user also gets a personal workspace (an organization of which they are the owner). ```dotenv ADMIN_EMAIL=you@example.com ``` ## Magic link Passwordless sign-in by mail. The link is valid for 15 minutes. It needs a working mail transport and has no setting of its own. ## Passkeys Users can register passkeys (WebAuthn) under their security settings and sign in with them. Passkeys are bound to a domain, called the relying-party ID. By default it is the hostname of `NEXT_PUBLIC_APP_URL`, so the app must be served over HTTPS on its final domain before people register passkeys. If you change the domain, existing passkeys stop working. Set `AUTH_RP_ID` only if you split the app and marketing site across hosts and want passkeys bound to the parent domain: ```dotenv AUTH_RP_ID=example.com ``` ## Two-factor authentication Users can turn on two-factor authentication in their security settings. It supports: - TOTP authenticator apps (6 digits, 30 second period) - 10 backup codes - A one-time code by mail as a fallback (needs a mail transport) Two-factor verification attempts are rate limited to 10 per 15 minutes. ## SMS login Sign-in with a phone number and a 6-digit code (valid for 5 minutes). Sending uses MessageBird: ```dotenv MESSAGEBIRD_API_KEY=your-messagebird-key MESSAGEBIRD_ORIGINATOR=TimeWren ``` Without `MESSAGEBIRD_API_KEY`, requesting a code fails with a "not configured" error. A user who signs up by phone only gets a placeholder email address on your mail domain (`EMAIL_DOMAIN`, defaulting to the marketing or app host). The text message itself is currently written in Danish. ## OAuth providers Each provider needs an OAuth app that you register yourself. A provider is offered only when both its variables are set. The callback URL is always `{NEXT_PUBLIC_APP_URL}/api/auth/callback/`. | Provider | Id | Variables | Callback URL | | --- | --- | --- | --- | | Google | `google` | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | `https://timewren.example.com/api/auth/callback/google` | | GitHub | `github` | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET` | `https://timewren.example.com/api/auth/callback/github` | | Discord | `discord` | `DISCORD_CLIENT_ID`, `DISCORD_CLIENT_SECRET` | `https://timewren.example.com/api/auth/callback/discord` | | Apple | `apple` | `APPLE_CLIENT_ID`, `APPLE_TEAM_ID`, `APPLE_KEY_ID`, `APPLE_PRIVATE_KEY` | `https://timewren.example.com/api/auth/callback/apple` | | Microsoft Entra ID | `microsoft-entra-id` | `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`, `MICROSOFT_TENANT_ID` | `https://timewren.example.com/api/auth/callback/microsoft-entra-id` | Notes: - The Google client is shared with the [Google Calendar integration](https://timewren.com/docs/integrations/calendar.md), which has its own callback URL. - Sign in with Apple: `APPLE_CLIENT_ID` is the Services ID. The client secret is generated from your `.p8` key (`APPLE_PRIVATE_KEY`, PEM text with `\n` line breaks or the whole file base64 encoded) when the app starts. `APPLE_APP_BUNDLE_IDENTIFIER` (default `dk.timetrack.app`) is the iOS bundle id used for native sign-in. - Microsoft: `MICROSOFT_TENANT_ID` defaults to `common` (any Microsoft account). Set a tenant GUID to restrict sign-in to one organization. See `docs/MICROSOFT-LOGIN-SETUP.md` in the repository for the Azure steps. - Accounts from Google and GitHub are linked automatically when the email address matches an existing account. Discord accounts are only linked when Discord reports the email address as verified. ## Trusted origins Browsers send requests from the origin of `NEXT_PUBLIC_APP_URL`, which is always trusted. If the app is also reached from another web origin (for example a second domain), add it: ```dotenv TRUSTED_ORIGINS=https://timewren.example.org,https://time.example.com ``` The value is a comma separated list of `https://host` origins. Invalid entries are skipped. ## Sessions Sessions last 7 days. An active session is extended at most once every 24 hours. The session cookie is host-only by default. `AUTH_COOKIE_DOMAIN` shares it across subdomains and `AUTH_COOKIE_PREFIX` changes its name (default `better-auth`); both are only needed with a split app and marketing host. ## Rotating BETTER_AUTH_SECRET `BETTER_AUTH_SECRET` is the Better Auth secret. Among other things it encrypts the OAuth login tokens stored in the database, and changing it directly makes those tokens unreadable until users sign in again. To rotate it safely, use versioned secrets: ```dotenv BETTER_AUTH_SECRETS=2:the-new-long-random-secret,1:the-old-long-random-secret ``` The format is `:` separated by commas. The first entry is the current secret, used for new data. Keep older versions in the list for as long as you need to read data written with them. Versions are non-negative integers and must be unique. Use at least 32 characters per secret. `BETTER_AUTH_SECRET` itself must stay set. The app also reads it directly to sign the older desktop device tokens and mail unsubscribe links, so changing its value invalidates those; users of the desktop app then sign in again. `ENCRYPTION_KEY` is a separate key (it protects integration credentials) and is not affected by this rotation. Back both up. --- # AI > Run TimeWren's AI features on a local model with Ollama, an EU provider or your own key, and control what is sent. Source: https://timewren.com/docs/configuration/ai TimeWren has optional AI features: the timesheet autopilot, the "write what you did" fallback, task parsing from text and email, project suggestions, prioritisation and email triage. All of them go through one provider-neutral layer (Vercel AI SDK), so you choose where the model runs. ## Nothing is sent without consent Calendar titles, tasks, emails and descriptions can be personal data. The server sends no text to a model until an owner or admin of the organisation ticks **AI may process the organisation's data** under **Settings → AI**. This applies to every provider, including a personal key a member has set up and the server's own AI. Turning the box off stops all AI calls for the organisation straight away, on every server instance. Changes are written to the organisation's audit log. Upgrading does not tick the box for you: an organisation that used AI with a personal key before has to turn it on once. ## Choose a provider There are three places a model can come from, checked in this order: 1. **The organisation's own model** (Settings → AI, "AI for the organisation"): OpenAI, Anthropic, Mistral (EU) or any local or OpenAI-compatible server. Keys are encrypted at rest. 2. **A member's own key** (Settings → AI, provider presets). 3. **The server's AI**, configured with environment variables. Some features only use it when `AI_SYSTEM_FOR_ALL=true`. ## AI with Ollama only This keeps every AI call on your own server. The compose overlay adds an Ollama container on the internal network and points TimeWren at it. ```bash docker compose -f docker-compose.yml -f docker-compose.ollama.yml up -d docker compose -f docker-compose.yml -f docker-compose.ollama.yml exec ollama ollama pull qwen2.5:3b ``` The overlay sets these variables, which you can also set yourself if Ollama runs elsewhere: ```bash AI_PROVIDER=openai-compatible AI_BASE_URL=http://ollama:11434/v1 AI_MODEL=qwen2.5:3b AI_SYSTEM_FOR_ALL=true AI_SYSTEM_ONLY=true AI_ALLOW_PRIVATE_URLS=true ``` Then log in as an organisation owner, open **Settings → AI** and tick the consent box. **Test the connection** sends a short request to the server's model, so you can check it answers. `AI_SYSTEM_ONLY=true` makes the server use only its own model: keys saved earlier on the organisation or by members are ignored, so no text can reach a cloud provider, also on an instance that used cloud keys before. Sizing: a 3B model needs about 3 GB of RAM and runs on CPU. On a 16-core server it answers a short request in a few seconds; the first request after a restart is slower while the model loads. A larger model (7B to 8B) gives better project suggestions but needs about 6 GB and is slower on CPU. See the measurements in the spike report linked below. ## An EU provider Pick **Mistral (EU)** as the organisation's provider and paste a key from console.mistral.ai. The default model is `mistral-small-latest`. Or set it for the whole server: ```bash AI_PROVIDER=mistral AI_API_KEY=your-mistral-key AI_MODEL=mistral-small-latest ``` ## Private addresses By default a URL set in the app must be public HTTPS, so a user cannot make the server call internal services. On a self-hosted instance where the model lives on a private address, set `AI_ALLOW_PRIVATE_URLS=true`. Leave it off on a public instance with many customers. ## Timesheet autopilot **Time → Today's suggestions** proposes the day's entries from your synced calendars (Google, Outlook, iCloud, CalDAV). Each suggestion shows its source, a confidence score and a one-line reason, and you can accept, edit or dismiss it. Scoring uses your calendar rules, earlier entries with the same title, and project or client names in the title; it needs no AI. With AI allowed, **Improve uncertain suggestions with AI** sends only the uncertain titles and project names (under short keys, no ids, descriptions or attendees) to the model. Only meetings that have ended are suggested, so a meeting later in the day that gets cancelled is never logged. Browser and desktop activity is not collected automatically yet. As a prototype, **Add browser history** in the review takes a `BrowserHistory.json` from Google Takeout: the file is read in your browser and not stored, only the day's blocks (domain, page title, time span) are sent with the request, and browser suggestions are never logged automatically. Integrations can send activity blocks through the API. Automatic logging is off by default. Under **Settings → AI → Timesheet autopilot** a user can turn it on with a minimum confidence; suggestions above it are logged when the review opens, and every evening at 21:00 by the `timesheet-autopilot` cron job, also when the app is closed. When two suggestions overlap, only the more certain one is logged. A suggestion is never logged automatically if the day already has an entry without a start time on the same project or with the same text. An AI guess on its own is capped at 75 %, so a high threshold only logs suggestions backed by your own rules or history. ## Fallback switch `AI_ENGINE=openai-legacy` routes OpenAI-compatible providers through the older `openai` client instead of the AI SDK. Use it only if the new layer misbehaves with your provider. ## Measurements The model comparison behind these defaults is in the repository at `docs/research/2026-11-28-ai-sdk-spike.md`, with the raw numbers next to it. --- # Upgrading > Update a self-hosted TimeWren instance safely: back up, pull, restart, pin versions and recover from a failed migration. Source: https://timewren.com/docs/operations/upgrading Updates are manual. Admin → Settings → Instance checks for the latest stable TimeWren release by default and compares it with the deployed version when available. Opening Settings makes an anonymous GET from the server to `https://api.github.com/repos/timewren/timewren/releases/latest`. The request contains no instance identifiers, installed version, account data or credentials. Each running app process caches the latest release for 24 hours and retries a failed lookup after one hour. The TimeWren image carries its version (`APP_VERSION`, for example `1.4.0-3f2a9c1`), so the comparison works without extra configuration. Turn the check off in Settings, or set `UPDATE_CHECK=off` in the environment to turn it off and lock the setting. The check never downloads or installs updates. It runs only in images built with `BUILD_PROFILE=selfhost`, as the prebuilt image is; a build with `BUILD_PROFILE=full` shows it as not applicable. ## Update procedure 1. Take a [backup](https://timewren.com/docs/operations/backup-restore.md) of the database, the `storage` volume and `.env`. Do this every time: migrations only go forward. 2. Read the release notes for what changes. 3. Pull and restart. The commands depend on how you installed. **Image install** ([one-line install](https://timewren.com/docs/install/quick.md) or [Docker Compose](https://timewren.com/docs/install/docker-compose.md)): the directory has no git checkout, and `.env` may pin `TIMEWREN_VERSION` (the one-line installer always writes it). Set `NEW` to the release tag you want, then point `.env` at it, fetch that release's stack files and start: ```bash NEW=1.3.0 sed -i "s|^TIMEWREN_VERSION=.*|TIMEWREN_VERSION=$NEW|" .env grep -q '^TIMEWREN_VERSION=' .env || echo "TIMEWREN_VERSION=$NEW" >> .env if [ -f .timewren-release ]; then echo "$NEW" > .timewren-release; fi curl -fsSLO https://raw.githubusercontent.com/timewren/timewren/$NEW/docker-compose.yml curl -fsSL https://raw.githubusercontent.com/timewren/timewren/$NEW/.env.example -o .env.example if [ -f docker-compose.caddy.yml ]; then curl -fsSLO https://raw.githubusercontent.com/timewren/timewren/$NEW/docker-compose.caddy.yml; fi docker compose pull docker compose up -d ``` On macOS use `sed -i ''` instead of `sed -i`. Compare `.env.example` with your `.env` afterwards to spot new variables; your `.env` itself is not touched. If you deliberately run the `latest` tag without a `TIMEWREN_VERSION` line, `docker compose pull && docker compose up -d` is enough. **Source checkout** ([from source](https://timewren.com/docs/install/from-source.md)): update the code and rebuild the image: ```bash git pull docker compose up -d --build ``` The `NEXT_PUBLIC_*` values for realtime, Plausible and browser Sentry are compiled into the image, so they only change with a rebuild. 4. Check the result: ```bash docker compose ps docker compose logs app ``` Look for the migration lines described below. `curl -i http://127.0.0.1:3000/api/health` only shows that the app is running. The app also starts after a failed migration, so a healthy answer is not proof that the update succeeded. Compose recreates the containers whose image or configuration changed. The database container is normally left alone, and its volume always is. > **Warning:** Never add `-v` to `docker compose down`, and never run `docker compose down -v` on an instance with data. It deletes the database and your uploads. ## Pinning a version `docker-compose.yml` runs `ghcr.io/timewren/timewren:${TIMEWREN_VERSION:-latest}`. The default tag is `latest`. To pin a version, set it in `.env`: ```bash echo 'TIMEWREN_VERSION=1.2.3' >> .env docker compose pull && docker compose up -d ``` Use a full `X.Y.Z` version, or `X.Y` for the newest patch release of that line. The image is also on Docker Hub as `mahoje/timewren`, and it is published for `linux/amd64` and `linux/arm64`. If you already have a `TIMEWREN_VERSION` line in `.env`, edit it instead of appending a second one. ## What happens to the database The compose file sets `MIGRATE_ON_START=1`. Every time the `app` container starts, `scripts/startup.sh` runs `scripts/migrate-safe.ts` before the web server starts. The image carries it as a bundled JavaScript file (`scripts/runtime/migrate-safe.mjs`), so it needs no `node_modules`; from a source checkout the same script runs with `npm run db:migrate`: - It takes a Postgres advisory lock, so two containers starting at once do not migrate in parallel. A second one waits up to 5 minutes (`MIGRATION_LOCK_TIMEOUT_MS`) and then fails. - It applies the pending migrations from `drizzle/` through Drizzle's migrator, which runs them in a transaction. - On an empty database it installs the checked-in SQL checkpoint through migration `0160` and records that history in the same transaction. It then runs `0161` and any later migrations. - On an existing database with missing or empty migration history, it restores the history through `0161` and ensures the test-account schema exists in the same transaction. It preserves saved test-account flags even if the entry for `0161` is missing from an otherwise populated migration journal. If the flag column was missing, it restores the column and recovers flags from the audit log. In an existing column, saved flags are never lowered or rewritten from the audit log; an unflagged organization is raised only when the older `testAccount` metadata marker still marks it (a database that recorded `0160` before the flags were restored) and its latest audit-log entry also marks it as a test account. Running the versioned SQL by hand gives the same result. - A start with nothing new prints `Database is up to date`; otherwise `N new migration(s) applied`. ## If a migration fails The log shows `Migration failed:` followed by the error, and the startup script prints the exit code. Read it with: ```bash docker compose logs app ``` The pending migrations run in one transaction, so a failing migration is not recorded. The script also runs idempotent schema patches (`ADD COLUMN IF NOT EXISTS` and similar) before the migrations, and those are committed separately. The schema can therefore differ slightly from the previous version even when the migration failed. The backup is the only guarantee of the exact previous state. The app still starts afterwards, running the new code against the old schema. Pages that use new columns or tables can fail until you fix it. If `ADMIN_DISCORD_WEBHOOK_URL` is set, a Discord alert is sent; otherwise the log is the only trace. Check the log after every update. To recover, do one of these: - Fix the cause and retry. Often it is disk space or a database user without rights. Then run `docker compose restart app`, and the migrations are retried on the next start. - Go back to the previous version using the backup you took in step 1. ### Rolling back Do not roll back only the code after a successful migration. The older code does not know the new schema, and nothing reverses migrations. Restore the database from the backup, then start the previous version: ```bash docker compose stop app cron ``` Restore the dump as described in [Backup and restore](https://timewren.com/docs/operations/backup-restore.md#restore), then set `TIMEWREN_VERSION` in `.env` to the previous version and start again: ```bash docker compose up -d ``` If you build yourself, run `git checkout PREVIOUS_TAG_OR_COMMIT` and `docker compose up -d --build` instead. > **Warning:** Very old installs whose `user.id` column is of type `uuid` are reset by the migration script: all tables are dropped and recreated. A backup before updating such an install is not optional. If a migration keeps failing, report it as an issue on [GitHub](https://github.com/timewren/timewren) with the lines from `docker compose logs app`. --- # Backup and restore > Back up the database, the storage volume and your encryption key, restore them into a fresh stack and verify the result. Source: https://timewren.com/docs/operations/backup-restore Three things hold state: the PostgreSQL database, the `storage` volume (uploads, attachments, data exports) and your `.env`, especially `ENCRYPTION_KEY`. The scripts in `scripts/` back up and restore all three. ## Backup status in Settings To show the last successful backup in Admin → Settings → Instance, have your backup job touch a separate marker file only after it succeeds. For example, create a directory called `backup-status` next to your Compose file and run `scripts/backup.sh && touch backup-status/last-success` from the stack directory. Mount only that marker directory into the `app` service as a read-only volume (`./backup-status:/backup-status:ro`) and set `BACKUP_STATUS_FILE=/backup-status/last-success` in `.env`. The timestamp is the file's modification time. ## Scripts The [one-line install](https://timewren.com/docs/install/quick.md) and [Docker Compose](https://timewren.com/docs/install/docker-compose.md) only create the stack files, not `scripts/`. In that case, fetch the backup tools into the stack directory (the one with `docker-compose.yml` and `.env`) first: ```bash mkdir -p scripts/lib for f in backup.sh restore.sh lib/backup-common.sh; do curl -fsSL "https://raw.githubusercontent.com/timewren/timewren/main/scripts/$f" -o "scripts/$f" done chmod +x scripts/backup.sh scripts/restore.sh ``` The scripts use the directory above `scripts/` as the stack, so no further setup is needed. If you keep them elsewhere, set `TIMETRACK_DIR` to the stack directory. In a source checkout they are already there. Run them from the stack directory: ```bash scripts/backup.sh scripts/restore.sh backups/timetrack-20260101-030000 scripts/test-restore.sh ``` ### backup.sh `backup.sh` needs the `db` service running. It writes a timestamped directory `backups/timetrack-YYYYMMDD-HHMMSS/` containing: - `db.dump`: `pg_dump -Fc` of the database. - `storage.tgz`: an archive of the storage volume. - `rowcounts.tsv`: the row count of every table, counted in a scratch restore of the dump. - `env`: a copy of `.env`, mode 600. - `SHA256SUMS`: checksums of the files above. Options: `--out DIR` chooses the parent directory (default `backups` in the stack directory, or `BACKUP_DIR`), and `--no-env` leaves `.env` out. The environment variables `TIMETRACK_DIR`, `ENV_FILE` and `COMPOSE_PROJECT_NAME` change which stack it works on. > **Warning:** Keep `ENCRYPTION_KEY` with every backup. Without the exact key, encrypted fields (integration tokens, API keys, 2FA secrets) are unreadable after a restore. The `env` copy holds the key, so protect and encrypt the backup before it leaves the machine. If you use `--no-env`, store the key yourself. ### restore.sh `restore.sh` is meant for a fresh stack with the same `.env`. It: 1. Verifies the checksums. 2. Refuses to continue if `ENCRYPTION_KEY` in `.env` differs from the one in the backup's `env` copy. 3. Stops `app` and `cron`, starts `db`, and runs `pg_restore --clean --if-exists --no-owner`. 4. Extracts the storage archive into the volume and fixes ownership to uid 1001. 5. Compares the row count of every table with the backup and exits non-zero on any difference. 6. Starts the full stack. Options: `--yes` skips the confirmation, `--skip-start` leaves `app` and `cron` stopped, and `--force` allows extracting onto a storage volume that already has files (without it, the script stops; existing files are kept, files not in the backup stay behind). The backup directory is the only argument. ### test-restore.sh `scripts/test-restore.sh` proves that backups can be restored. It seeds test data in a temporary stack, backs it up, restores into an empty second stack and checks that every table has identical row counts and the storage file is identical. It also checks that a damaged or altered backup is rejected. It needs Docker and the repository's `node_modules` (`npm ci`), uses no fixed ports and removes what it creates. Run it from a source checkout. ## Manual commands The same steps by hand. The compose project is called `timetrack`, and the database name and user are both `timetrack`: ```bash docker compose exec -T db pg_dump -U timetrack -Fc timetrack > timewren-$(date +%F).dump docker run --rm -v timetrack_storage:/data -v "$PWD":/backup alpine \ tar czf /backup/storage-$(date +%F).tgz -C /data . cp .env env-backup-$(date +%F) ``` ## Restore Restore into a fresh stack with the same `.env`: ```bash docker compose up -d db docker compose exec -T db pg_restore -U timetrack -d timetrack --clean --if-exists --no-owner < timewren-2026-01-01.dump docker run --rm -v timetrack_storage:/data -v "$PWD":/backup alpine \ tar xzf /backup/storage-2026-01-01.tgz -C /data docker run --rm -v timetrack_storage:/data alpine chown -R 1001:1001 /data docker compose up -d ``` If you set `COMPOSE_PROJECT_NAME` in `.env`, the volume is called `_storage` instead of `timetrack_storage`. ## Nightly backups `backup.sh` can run unattended. This host crontab line takes a backup at 03:00 and keeps the output in a log: ```text 0 3 * * * cd /opt/timewren && ./scripts/backup.sh --out /var/backups/timewren >> /var/log/timewren-backup.log 2>&1 ``` Adjust the paths to your install. The script does not delete old backups, so prune them yourself, for example with `find /var/backups/timewren -maxdepth 1 -name 'timetrack-*' -mtime +14 -exec rm -rf {} +`. ## Off-site copies and testing A backup on the same machine is lost with the machine. Copy the backup directories to another host or to object storage, and encrypt them first, because they include the `env` file with your secrets. Test a restore before you need one, either with `scripts/test-restore.sh` or by restoring into a spare machine. --- # Reverse proxy and TLS > Put TimeWren behind Caddy, Traefik or nginx with HTTPS, and set the public URL and trusted origins correctly. Source: https://timewren.com/docs/operations/reverse-proxy The app container listens on port 3000 and is published on `127.0.0.1:3000` only. For anything other than localhost, put a reverse proxy with TLS in front of it. ## Public URL Point a DNS record at your server, then set the URL people will open in `.env`: ```dotenv NEXT_PUBLIC_APP_URL=https://timewren.example.com ``` Apply it with `docker compose up -d`. No rebuild is needed: the value is read at runtime. Links in mails, OAuth callbacks and the origin checks all use it. If the browser URL does not match, sign-in fails (see [Troubleshooting](https://timewren.com/docs/operations/troubleshooting.md)). The proxy must pass the `Host` header and the `X-Forwarded-*` headers on unchanged. The examples below do. ## Port and bind address | Variable | Default | Effect | | -------- | ------- | ------ | | `APP_PORT` | `3000` | Host port that maps to the container's port 3000. | | `APP_BIND` | `127.0.0.1` | Host address the port is bound to. Set `0.0.0.0` to expose the port on all interfaces. | Keep the default bind address when a proxy runs on the same host. Change them in `.env` and run `docker compose up -d`. ## Caddy Caddy gets and renews certificates by itself. In `/etc/caddy/Caddyfile`: ```text timewren.example.com { reverse_proxy 127.0.0.1:3000 } ``` Caddy forwards the `Host` and `X-Forwarded-*` headers and handles streaming responses without extra settings. ## Traefik If Traefik already runs on the host with a Docker provider, add labels to the `app` service in a `docker-compose.override.yml`: ```yaml services: app: ports: !reset [] networks: [default, traefik] labels: - traefik.enable=true - traefik.docker.network=traefik - traefik.http.routers.timewren.rule=Host(`timewren.example.com`) - traefik.http.routers.timewren.entrypoints=websecure - traefik.http.routers.timewren.tls.certresolver=letsencrypt - traefik.http.services.timewren.loadbalancer.server.port=3000 networks: traefik: external: true ``` Adjust the network, entrypoint and certificate resolver names to your Traefik setup. The `!reset` tag needs Docker Compose v2.24 or newer. ## nginx Create `/etc/nginx/conf.d/timewren.conf`, with certificates from Let's Encrypt (for example through `certbot`): ```nginx server { listen 80; server_name timewren.example.com; return 301 https://$host$request_uri; } server { listen 443 ssl; http2 on; server_name timewren.example.com; ssl_certificate /etc/letsencrypt/live/timewren.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/timewren.example.com/privkey.pem; client_max_body_size 25m; location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_read_timeout 300s; } # Live updates (server-sent events), only used when REALTIME_ENABLED=true location ~ ^/api/(realtime|ext/stream)$ { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header Connection ""; proxy_buffering off; proxy_cache off; proxy_read_timeout 1h; } } ``` Test and reload with `sudo nginx -t && sudo systemctl reload nginx`. The `http2 on;` directive needs nginx 1.25.1 or newer; on older versions use `listen 443 ssl http2;` instead. The upload endpoint accepts files up to 8 MB, so keep `client_max_body_size` above that (nginx defaults to 1 MB). The app does not use WebSockets: live updates use server-sent events (`/api/realtime` and `/api/ext/stream`), which is why the second block turns buffering off. They are only served when `REALTIME_ENABLED=true`. ## Extra hostnames If people reach the same instance under a second hostname, list the extra origins in `TRUSTED_ORIGINS`, comma-separated, and run `docker compose up -d`: ```dotenv TRUSTED_ORIGINS=https://time.example.com,https://www.timewren.example.com ``` Entries must be full `http(s)` origins; anything else is ignored. ## Custom domains and certificates Customer-facing custom portal domains use the hostname from `NEXT_PUBLIC_MARKETING_URL`, or from `NEXT_PUBLIC_APP_URL` when that is unset. A CNAME alone does not configure your proxy: set up the proxy and the TLS certificates for those domains yourself. --- # Troubleshooting > Fix common problems with a self-hosted TimeWren instance: startup, sign-in, mail, uploads, cron jobs and migrations. Source: https://timewren.com/docs/operations/troubleshooting Start with the status of the containers and the app log: ```bash docker compose ps docker compose logs -f app ``` ## Health endpoint ```bash curl -i http://127.0.0.1:3000/api/health ``` The endpoint returns HTTP 200 when everything is fine and 503 when a check fails: ```json { "status": "healthy", "timestamp": "2026-01-01T12:00:00.000Z", "service": "timetrack", "checks": { "database": { "status": "ok" }, "auth": { "status": "ok" }, "signing_secret": { "status": "ok" }, "realtime": { "status": "disabled" } } } ``` `status` is `healthy` or `unhealthy`. The `database`, `auth` and `signing_secret` checks are `ok` or `error`, and any `error` makes the response 503. The `realtime` check can also be `degraded`, which never fails the health check. The `service` field says `timetrack` for historical reasons. A healthy answer does not prove that the last migration succeeded; read the log for that. The `app` container shows `starting` until it is healthy. The first start can take a minute or two, because migrations run before the server listens (the health check allows 180 seconds). ## docker compose up says a variable is missing The message names it, for example `Set POSTGRES_PASSWORD in .env`. Fill it in `.env` and run the command again. `POSTGRES_PASSWORD`, `BETTER_AUTH_SECRET`, `ENCRYPTION_KEY` and `CRON_SECRET` are required. ## Sign-in or sign-up fails with 403 or "invalid origin" The URL in the browser differs from `NEXT_PUBLIC_APP_URL`. Fix the value in `.env` and run `docker compose up -d`, or add the extra hostname to `TRUSTED_ORIGINS`. See [Reverse proxy and TLS](https://timewren.com/docs/operations/reverse-proxy.md). ## Links in the app or in mails point at localhost `NEXT_PUBLIC_APP_URL` is unset, so it falls back to `http://localhost:3000`. Set it in `.env` and run `docker compose up -d`. ## The build is killed or hangs Building the image yourself needs about 5 GB of RAM at peak. The prebuilt image avoids this. If you must build, add swap or use a bigger machine: ```bash sudo fallocate -l 4G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile ``` ## Mails do not arrive Look for mail lines in the log: ```bash docker compose logs app | grep "\[Mail" ``` `[Mail:log]` means no transport is configured and nothing was sent. `[Mail] SMTP-afsendelse fejlede` indicates an SMTP delivery failure. Check your provider's sending log for details. See [Email](https://timewren.com/docs/configuration/email.md). ## Stored integrations stop working `ENCRYPTION_KEY` changed, so the stored tokens cannot be decrypted. Put the old value back from your backup and run `docker compose up -d`. Without the old key, reconnect the integrations. ## Uploads fail with a permission error The `storage` volume must be writable by uid 1001: ```bash docker run --rm -v timetrack_storage:/data alpine chown -R 1001:1001 /data ``` Uploads also fail when neither the local driver nor `S3_ENDPOINT` is configured. See [File storage](https://timewren.com/docs/configuration/storage.md). ## Scheduled jobs do not run The `cron` container calls the app's `/api/cron/*` endpoints: ```bash docker compose logs cron ``` A failed call shows only a curl exit status 22, which means an HTTP error such as 401, 404 or 500. Check first that `CRON_SECRET` is identical for `app` and `cron`, then recreate both: ```bash docker compose up -d --force-recreate app cron ``` ## A migration failed The log shows `Migration failed:` with the error. The app keeps running on the old schema. Fix the cause (often disk space) and restart: ```bash docker compose restart app ``` See [Upgrading](https://timewren.com/docs/operations/upgrading.md#if-a-migration-fails) for recovery and rollback. ## Start over > **Warning:** `docker compose down -v` deletes the database and all uploads. Only do this on a throwaway instance. ```bash docker compose down -v docker compose up -d ``` ## Ask an AI to help The docs are available as plain text for language models. Paste a page, or the whole set, into your assistant together with your log output (with secrets removed), and ask it to diagnose the problem. See [Docs for LLMs](https://timewren.com/docs/llm.md) for the URLs. --- # Billy > Connect Billy, the Danish accounting system, to TimeWren: import contacts, export clients and invoices, and sync payment status. Source: https://timewren.com/docs/integrations/billy Billy is a Danish accounting system. The integration needs no setup on the server: each user pastes their own Billy API key. Without a key, nothing Billy-related happens. ## What it does - Imports Billy contacts as clients. Contacts already imported, or whose CVR number matches an existing client, are skipped. - Exports a client to Billy. - Exports an invoice to Billy as a draft, approved, or approved and sent by mail. You choose the product, payment terms and whether each time entry is its own line or all entries are combined into one line. The line text is a template. - Syncs the payment status back: invoices paid in Billy are marked as paid in TimeWren. Billy requires a product on every invoice line. Choose a default product in the settings, or let TimeWren create one on the first export. You can choose a separate product for prepaid package hours. ## Sending by email When you choose to approve and send the invoice, TimeWren first shows a confirmation with the recipient, invoice number, amount including VAT, line count and due date as TimeWren calculates them. Billy calculates the final amount with its own VAT settings. If the invoice changes after you open the confirmation, TimeWren refuses to send it and you open the confirmation again. The same invoice is never exported twice at once. If you click twice, or retry while the export is running, TimeWren refuses the second attempt, so Billy neither creates nor emails the invoice twice. If Billy does not answer while the email is being sent, or TimeWren is interrupted in the middle of it, TimeWren cannot tell whether the client received the invoice. The invoice page then shows a warning, and the invoice cannot be sent again from TimeWren until you have checked the email status in Billy and marked whether it was sent. If you delete the invoice in Billy, automatic status sync releases the link in TimeWren, but only when the connected Billy organization is provably the one the invoice was exported to: TimeWren recorded the organization at the export, or, for an invoice exported before that, the client has not changed since the day before the export and the client's contact still exists in the connected organization. Otherwise TimeWren keeps the link. A draft without a link can be exported again. ## Server setup Requirements on the server: - `ENCRYPTION_KEY` must be set. The API key is stored encrypted, and saving fails without the key. See [Environment variables](https://timewren.com/docs/configuration/environment.md). - The `cron` container must be running. It calls `/api/cron/invoice-sync` every 15 minutes, which is what updates payment status for users who have automatic status sync turned on. There are no Billy-specific client credentials to register. ## Connect as a user 1. In Billy, create an API key under Settings, Integrations, API. 2. In TimeWren, open Settings, Integrations and paste the key in the Billy section. 3. Save, then use Test connection. 4. Choose the default product and line settings. 5. Under Default accounting system, choose Billy if it is the one you use, and turn on Automatic status sync if you want payments picked up automatically. You can also run a manual sync from the same page. Contacts are imported from the Sync page under Integrations. Invoices are exported from the invoice itself. The key belongs to the user who saved it. In a team, each person who exports uses their own key. ## Webhooks (optional) The endpoint `/api/webhooks/billy` accepts Billy webhooks and marks an invoice as paid on `invoice.paid`. Set a secret on the server and configure the same secret in Billy; requests are verified with an HMAC-SHA256 signature in the `x-billy-signature` header: ```dotenv BILLY_WEBHOOK_SECRET=a-long-random-string ``` TimeWren processes byte-identical signed deliveries once while their record is retained (90 days). A failed delivery can be processed again. This includes payment events received before TimeWren has saved the external invoice ID. The endpoint finds the user by their stored Billy organization id. The web settings do not store it, so for most setups rely on the 15 minute sync above instead of webhooks. --- # Dinero > Connect Dinero, the Danish accounting system, to TimeWren via Visma Connect OAuth: import contacts, export invoices and sync payments. Source: https://timewren.com/docs/integrations/dinero Dinero is a Danish accounting system. Because TimeWren is self-hosted, you register your own OAuth app at Visma Connect and give the credentials to the server. After that, every user connects their own Dinero account with one click. > **Note:** API access requires a Dinero Pro organization. Without one, connecting fails with "No Dinero Pro organisation found". ## What it does - Imports Dinero contacts as clients (already imported contacts are skipped). - Exports a client to Dinero. - Exports an invoice as a draft, booked, or booked and sent. You choose the revenue account, payment terms and one line per entry or a combined line. - Syncs payment status back, so paid invoices are marked as paid in TimeWren. ## Sending by email When you choose to book and send the invoice, TimeWren first shows a confirmation with the recipient, invoice number, amount including VAT, line count and due date as TimeWren calculates them. Dinero calculates the final amount with its own VAT settings. If the invoice changes after you open the confirmation, TimeWren refuses to send it and you open the confirmation again. The same invoice is never exported twice at once. If you click twice, or retry while the export is running, TimeWren refuses the second attempt, so Dinero neither creates nor emails the invoice twice. If Dinero does not answer while the email is being sent, or TimeWren is interrupted in the middle of it, TimeWren cannot tell whether the client received the invoice. The invoice page then shows a warning, and the invoice cannot be sent again from TimeWren until you have checked the email status in Dinero and marked whether it was sent. If you delete the invoice in Dinero, automatic status sync releases the link in TimeWren, but only when the connected Dinero organization is provably the one the invoice was exported to: TimeWren recorded the organization at the export, or, for an invoice exported before that, the client has not changed since the day before the export and the client's contact still exists in the connected organization. Otherwise TimeWren keeps the link. A draft without a link can be exported again. ## Server setup 1. Register an application at Visma Connect (the developer portal for Dinero's public API) and set this redirect URI, exactly as written: ```text https://timewren.example.com/api/integrations/dinero/callback ``` 2. Add the credentials to `.env`: ```dotenv DINERO_CLIENT_ID=your-client-id DINERO_CLIENT_SECRET=your-client-secret # Only if the callback differs from NEXT_PUBLIC_APP_URL + /api/integrations/dinero/callback # DINERO_REDIRECT_URI=https://timewren.example.com/api/integrations/dinero/callback ``` 3. Restart the app. The sign-in uses the scopes `openid`, `dineropublicapi:read`, `dineropublicapi:write` and `offline_access`. The flow posts back to your callback URL from another site, so your instance must run on HTTPS. Local plain-HTTP testing needs an HTTPS tunnel. `ENCRYPTION_KEY` must be set, because the OAuth tokens are stored encrypted. See [Environment variables](https://timewren.com/docs/configuration/environment.md). Without the client id, the Connect button redirects back with a `dinero_not_configured` error. ## Connect as a user 1. Open Settings, Integrations and choose Connect to Dinero. 2. Sign in at Visma Connect and approve access. If you have access to several Dinero organizations, choose which one to connect. 3. Choose the default revenue account (required for invoice export). Optionally map Dinero products for hours and for prepaid packages. 4. Under Default accounting system, optionally turn on Automatic status sync. Contacts are imported from the Sync page under Integrations. Invoices are exported from the invoice itself. Older connections made with a Dinero API key keep working. The settings page offers an upgrade to OAuth. ## Sync and webhooks The `cron` container calls `/api/cron/invoice-sync` every 15 minutes to update payment status for users with automatic sync on. The endpoint `/api/webhooks/dinero` is optional. It marks invoices as paid on `InvoicePaid` events and logs booked and sent events. Requests are verified with an HMAC-SHA256 signature in the `x-dinero-signature` header, using a secret you set on the server and in Dinero: ```dotenv DINERO_WEBHOOK_SECRET=a-long-random-string ``` TimeWren processes byte-identical signed deliveries once while their record is retained (90 days). A failed delivery can be processed again. This includes payment events received before TimeWren has saved the external invoice ID. --- # e-conomic > Connect e-conomic to TimeWren with an app you register yourself: import customers, export clients and invoices, and sync payment status. Source: https://timewren.com/docs/integrations/e-conomic e-conomic is a Danish accounting system. You register your own app at the e-conomic developer portal and give its two tokens to the server. After that, every user grants the app access to their own e-conomic agreement with one click. ## What it does - Imports e-conomic customers as clients. - Exports a client to e-conomic. - Exports an invoice. You choose layout, payment terms, product, and one line per entry or a combined line. Optionally the invoice is booked on export. - Syncs payment status back to TimeWren. ## Server setup 1. Create an app at [https://www.e-conomic.com/developer](https://www.e-conomic.com/developer). You get an app public token and an app secret token. 2. Add them to `.env`: ```dotenv ECONOMIC_APP_PUBLIC_TOKEN=your-public-token ECONOMIC_APP_SECRET_TOKEN=your-secret-token # Only if the callback differs from NEXT_PUBLIC_APP_URL + /api/integrations/economic/callback # ECONOMIC_REDIRECT_URI=https://timewren.example.com/api/integrations/economic/callback ``` 3. Restart the app. After a user approves access, e-conomic redirects back to: ```text https://timewren.example.com/api/integrations/economic/callback ``` The secret token stays on the server and is never shown to users. `ENCRYPTION_KEY` must be set, because each user's agreement grant token is stored encrypted. See [Environment variables](https://timewren.com/docs/configuration/environment.md). Without both tokens, the Connect button redirects back with an `economic_not_configured` error. ## Connect as a user 1. Open Settings, Integrations and choose Connect to e-conomic. 2. Sign in at e-conomic and approve access for your agreement. 3. Back in TimeWren, choose the default invoice layout, payment terms, products and line settings. 4. Under Default accounting system, optionally turn on Automatic status sync. Customers are imported from the Sync page under Integrations. Invoices are exported from the invoice itself. ## Payment status The `cron` container calls `/api/cron/invoice-sync` every 15 minutes to update payment status for users with automatic sync on. You can also run a manual sync from the integrations settings. There is no e-conomic webhook endpoint. --- # Calendar > Connect Google Calendar, Outlook or iCloud to TimeWren to see meetings, plan time blocks and turn events into time entries. Source: https://timewren.com/docs/integrations/calendar TimeWren can read your calendar to show meetings next to your time entries, suggest free slots for tasks, and turn events into time entries. Three providers exist: Google Calendar, Outlook (Microsoft 365 and Outlook.com, via Microsoft Graph) and iCloud. Each is only shown when it is configured. ![The calendar view](https://timewren.com/brand/timewren/screens/en/calendar.webp) ## Google Calendar ### Server setup 1. In the Google Cloud console, create an OAuth client of type "Web application" and enable the Google Calendar API for the project. 2. Add this authorized redirect URI: ```text https://timewren.example.com/api/integrations/google/callback ``` 3. Set the credentials in `.env`: ```dotenv GOOGLE_CLIENT_ID=your-client-id GOOGLE_CLIENT_SECRET=your-client-secret # Only if the callback differs from NEXT_PUBLIC_APP_URL + /api/integrations/google/callback # GOOGLE_REDIRECT_URI=https://timewren.example.com/api/integrations/google/callback ``` 4. Restart the app. The same client also enables "Sign in with Google", which uses its own redirect URI (`/api/auth/callback/google`), see [Authentication](https://timewren.com/docs/configuration/authentication.md). Add both URIs to the client if you want both. Without these variables the settings page shows that Google Calendar is not configured. Stored tokens are encrypted, so `ENCRYPTION_KEY` must be set. Syncing runs from the `cron` container every 15 minutes (`/api/cron/calendar-sync`), and a daily job (`/api/cron/calendar-webhook-renew`) renews Google push notification channels. Push notifications arrive at `/api/webhooks/google-calendar`, so that path must be reachable from the internet over HTTPS. Without it, the 15 minute sync still works. ### Scopes A new connection asks for read access only: | Scope | Why | | --- | --- | | `https://www.googleapis.com/auth/calendar.readonly` | Read events | | `https://www.googleapis.com/auth/userinfo.email` | Show which Google account is connected | Write access is requested later, only when a user turns on a feature that needs it (time blocks for tasks, exporting time entries to the calendar): | Scope | Why | | --- | --- | | `https://www.googleapis.com/auth/calendar.events` | Create and change events | If your OAuth consent screen is in testing mode, add your users as test users, or publish the app. ### Connect as a user Open Settings, Integrations, choose Connect Google Calendar and approve access. Then pick which calendars to sync. You can set sync filters, a privacy mode, and matching rules that map event titles to projects. Disconnect removes the connection from the same page and at the same time revokes TimeWren's access at Google, so the app also disappears from the Google account's third-party connections (myaccount.google.com/connections). Deleting your account does the same for every Google connection. Access is only revoked when that is safe; otherwise the connection is only removed here. That happens when another connection (also another user's or another brand's) uses the same Google account, when an older connection has not synced yet so its Google account is unknown, and when Google cannot be reached. In those cases you can check and revoke access at myaccount.google.com/connections yourself. If you reconnect a few seconds after disconnecting, Google's revocation, which takes effect with a short delay ([Google's documentation](https://developers.google.com/identity/protocols/oauth2/web-server#tokenrevoke)), can also hit the new connection. If the calendar then shows "Reconnect", connect once more. ## Outlook Outlook uses Microsoft Graph and is read only: TimeWren reads the user's default calendar and never writes to it. ### Server setup 1. In the Microsoft Entra admin center, create an app registration. Choose the account types you want to allow (all organizations and personal accounts matches tenant `common`). 2. Add a redirect URI of platform type "Web": ```text https://timewren.example.com/api/integrations/outlook/callback ``` 3. Under API permissions, add the delegated Microsoft Graph permissions `offline_access`, `User.Read` and `Calendars.Read`. They need no admin consent. Create a client secret under Certificates & secrets and note its expiry date. 4. Set the credentials in `.env`: ```dotenv OUTLOOK_CALENDAR_CLIENT_ID=your-application-id OUTLOOK_CALENDAR_CLIENT_SECRET=your-client-secret # common (default), organizations, consumers or a tenant GUID # OUTLOOK_CALENDAR_TENANT_ID=common # Only if the callback differs from NEXT_PUBLIC_APP_URL + /api/integrations/outlook/callback # OUTLOOK_CALENDAR_REDIRECT_URI=https://timewren.example.com/api/integrations/outlook/callback ``` 5. Restart the app. The Microsoft Entra ID sign-in app (`MICROSOFT_CLIENT_ID`) is never used for the calendar. Without the variables above, Outlook is not shown. The flow uses PKCE and a signed state, and tokens are stored encrypted, so `ENCRYPTION_KEY` must be set. ### Connect as a user Open Settings, Integrations, choose Connect Outlook, sign in with Microsoft and approve access. Events from 30 days back to 90 days ahead are synced every 15 minutes by the same cron job, and Sync now runs it on demand. There are no push notifications for Outlook. The sync filters, privacy mode and matching rules are shared with the other providers. Disconnect deletes the stored tokens and the fetched Outlook events. Microsoft has no way to revoke a single app's token, so access is only removed in TimeWren. To remove the app from the Microsoft account too, go to account.live.com/consent/Manage (personal accounts) or myapps.microsoft.com (work accounts). ## iCloud iCloud works through CalDAV against `caldav.icloud.com`. It needs no server credentials, only `ENCRYPTION_KEY`, because each user's app-specific password is stored encrypted. Connection is read only: TimeWren never writes to iCloud. Generic CalDAV servers other than iCloud are not supported. To connect: 1. Go to [https://appleid.apple.com](https://appleid.apple.com), open Sign-In and Security, App-Specific Passwords, and create a password for TimeWren. This needs two-factor authentication on the Apple ID. 2. In TimeWren, open Settings, Integrations, find the iCloud calendar section, enter the Apple ID and the app-specific password, and connect. 3. Choose which calendars to read. Nothing is read from calendars you leave unticked. Events from 30 days back to 90 days ahead are synced. The same cron job refreshes them every 15 minutes, and Sync now runs it on demand. The sync filters, privacy mode and matching rules are shared with Google and Outlook. --- # CVR lookup > Fill in Danish company details from the CVR register when you create a client. Works without configuration through cvrapi.dk. Source: https://timewren.com/docs/integrations/cvr CVR is the Danish company register. When you create a client, enter a CVR number (or a company name or phone number) and TimeWren fills in the company details. It only helps for Danish businesses. ## What it fills in Name, address, postal code, city, country (Denmark), industry code and description, company status, phone, email and start date, where the source has them. You can edit everything before saving. ## Where it is used The lookup button on the new client form, and the CVR lookup in your company settings. Lookups are limited to 10 per minute per user. ## Sources and configuration No configuration is needed. By default TimeWren asks [cvrapi.dk](https://cvrapi.dk), a free public service, and the request fails with a timeout message after 10 seconds. cvrapi.dk limits how many requests it accepts, so a busy instance may occasionally see a "rate limited" message and need to retry. When [Valkey](https://timewren.com/docs/configuration/environment.md) is configured, answers are cached for 24 hours, which saves quota. These variables are optional: | Variable | Default | Meaning | | --- | --- | --- | | `CVR_API_TIMEOUT_MS` | `10000` | Timeout for cvrapi.dk requests in milliseconds | | `CVR_SERVICE_API_KEY` | empty | Key for an alternative CVR service. When set, that service is asked first | | `CVR_SERVICE_URL` | the service run by the TimeWren maintainers | Base URL of the alternative service | The alternative service is tried first with a 3 second timeout. If it fails or is not reachable, TimeWren falls back to cvrapi.dk. Unless you have been given a key for a service, leave `CVR_SERVICE_API_KEY` empty. > **Note:** A lookup sends the number or text you typed to the service that answers it (cvrapi.dk by default). Entering company details by hand always works. --- # E-invoice (OIOUBL and Peppol) > Download an issued invoice as Peppol BIS Billing 3.0 or OIOUBL 2.1 XML, with the client details and VAT rules an e-invoice needs. Source: https://timewren.com/docs/integrations/einvoice An issued invoice can be downloaded as an e-invoice: an XML file that the client's bookkeeping system reads without anyone typing it in. TimeWren writes two formats: - **Peppol BIS Billing 3.0**, the European standard. Use it for clients in the EU and for Danish clients on Nemhandel. - **OIOUBL 2.1**, the current Danish standard, still used by Danish public-sector clients. TimeWren does not send the file. You download it and pass it on yourself, for example by uploading it to your access point or your client's portal. Sending through a Peppol access point is a separate step that is not built yet. ## Download an e-invoice 1. Open an issued invoice. Drafts cannot become e-invoices, because their number is not final. 2. Choose E-invoice (XML) and pick Peppol BIS 3 or OIOUBL 2.1. If details are missing, TimeWren does not write the file. It lists what to add instead, for example your CVR number or the client's electronic address. The amounts are the same as on the PDF: the same lines, the same VAT rate from the invoice template, and the same total. ## What the e-invoice needs Your company details (Settings, Company): - A Danish company needs its CVR number. The CVR number is also your Peppol address (scheme 0184). - A VAT-registered company needs its VAT number. For a Danish company it is derived from the CVR number. - Peppol ID: only if your Peppol address is something other than your CVR number, for example 9930:DE123456789. - Bank details (registration and account number) are added as the payment method when they are filled in. The client (Clients, Edit, E-invoice): - **GLN (EAN number)**: 13 digits, the last one a check digit. TimeWren refuses a number with a wrong check digit. Danish public-sector clients receive invoices on their GLN. - **Peppol ID**: for example 0184:12345678. Only if the client has given you one. When the scheme has a check digit (Norwegian, Swedish and Belgian organisation numbers, for example), TimeWren refuses a number where it does not match. - **Client's reference**: an order number or contact reference the client asked for. Without one, the invoice number is used. - **VAT**: standard VAT, reverse charge (EU business) or no VAT for supplies outside the EU. For Peppol, the client needs a Peppol address: a Peppol ID, a GLN or a Danish CVR number. An email address is not a Peppol address. ## VAT on the invoice The VAT setting on the client changes both the PDF and the e-invoice: - **Standard VAT**: the template's rate, usually 25 %. - **Reverse charge**: 0 % VAT and the note "Reverse charge". Use it for business clients in other EU countries. The client's VAT number with country code is required, for example DE123456789. - **No VAT, supply outside the EU**: 0 % VAT and a note. A company that is not VAT registered never charges VAT, whatever the client setting. The setting applies to new invoices and to the client's drafts. An issued invoice keeps the VAT it was issued with, also when you change the client later, and a credit note credits the same VAT as the invoice. ## Billy, Dinero and e-conomic If the invoice is also exported to Billy, Dinero or e-conomic, the bookkeeping system may send its own e-invoice through Nemhandel. Send the invoice from one place only, or the client gets it twice. The e-invoice menu warns you when the invoice has been exported. Billy and Dinero add VAT from their own products. An invoice with reverse charge or without VAT for export can therefore not be sent by email through Billy or Dinero from TimeWren. Create it as a draft in the bookkeeping system, check the VAT there and send it from there. ## Validation The XML is checked in TimeWren's tests against the official rules: the UBL 2.1 schema, the CEN EN 16931 and Peppol BIS 3 schematrons, and the OIOUBL schematron from the Danish Business Authority. --- # Automation (Zapier, Make, n8n) > Connect TimeWren to Zapier, Make, n8n or any HTTP tool with an API key and outgoing webhooks. Source: https://timewren.com/docs/integrations/automation TimeWren has no special integration server for automation tools. Zapier, Make and n8n all work the same way: they call the [REST API](https://timewren.com/docs/api/rest.md) with an API key, and receive events through [webhooks](https://timewren.com/docs/api/webhooks.md). That also means any other tool that can send HTTP requests or receive webhooks works too. ## Create an API key 1. Open Settings, API in your instance. 2. Create a key, give it a name such as "Zapier", and choose scopes. Scopes are per resource (clients, projects, time, invoices, prepaid, tasks, reports, webhooks) with read, write or all, or full access. 3. Copy the key. It starts with `tk_live_` and is shown once. Send it as a bearer token with every request: ```bash curl -H "Authorization: Bearer YOUR_API_KEY" https://timewren.example.com/api/v1/me ``` `GET /api/v1/me` works with any valid key, so it is the right connection test. Use your own instance address as the base URL, never a hosted one. The limit is 300 requests per minute per user. The headers `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` show the state. ## Receive events Create a webhook with `POST /api/v1/webhooks` (the key needs the `webhooks:write` scope). Give it the URL of your Zap, scenario or n8n Webhook node and the events you want: ```bash curl -X POST https://timewren.example.com/api/v1/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "n8n", "url": "https://n8n.example.com/webhook/timewren", "events": ["invoice.paid", "client.created"]}' ``` Available events: | Area | Events | | --- | --- | | Clients | `client.created`, `client.updated`, `client.archived` | | Projects | `project.created`, `project.updated`, `project.status_changed`, `project.budget_threshold` | | Time entries | `time_entry.created`, `time_entry.updated`, `time_entry.deleted` | | Invoices | `invoice.created`, `invoice.sent`, `invoice.paid`, `invoice.overdue` | | Prepaid packages | `prepaid.created`, `prepaid.updated`, `prepaid.low_balance`, `prepaid.expired` | | Tasks | `task.created`, `task.updated`, `task.completed` | Each delivery is signed with `X-Webhook-Signature` (HMAC-SHA256 with the webhook secret) and carries `X-Webhook-Event`, `X-Webhook-Timestamp` and `X-Webhook-Delivery-Attempt`. The payload format and signature check are on the [Webhooks](https://timewren.com/docs/api/webhooks.md) page. `GET /api/v1/webhooks/event-types` returns the current list. The receiving URL must use HTTPS and must not point to a private or internal address (localhost, private IP ranges, or a name that resolves to one). Webhook management requires an organization admin or owner, which a solo account always is. Put a tool that runs on your own network behind a public HTTPS hostname. ## Do things Calls most automations use: | Action | Request | | --- | --- | | Create a time entry | `POST /api/v1/time-entries` with `hours`, `date` (YYYY-MM-DD), and optionally `projectId`, `clientId`, `description`, `isBillable` | | Create a client | `POST /api/v1/clients` | | Create a task | `POST /api/v1/tasks` with `title`, optionally `projectId`, `status`, `priority` | | Start or stop the timer | `POST /api/v1/timer` and `DELETE /api/v1/timer` | | Find a client | `GET /api/v1/clients?q=search` | | Find projects | `GET /api/v1/projects?clientId=...` | | Time report | `GET /api/v1/reports/time-summary?from=2026-01-01&to=2026-01-31` | | Revenue report | `GET /api/v1/reports/revenue` | | Mark an invoice paid | `POST /api/v1/invoices/{id}/mark-paid` | The full list with parameters is in the [REST API](https://timewren.com/docs/api/rest.md) reference, and every instance serves its own OpenAPI document at `/api/v1/openapi.json` and a browsable reference at `/api/v1/docs`. ## Zapier Use Webhooks by Zapier, or a private app built from the definition in the `integrations/zapier` folder of the repository. It defines API key authentication with a Base URL field (set it to your instance), webhook triggers for new time entries, updated time entries, new clients, new invoices, paid invoices, low prepaid balance and completed tasks, and actions and searches for the calls above. > **Warning:** The "Create Time Entry" action in that definition sends `durationMinutes`, but the API reads `hours`. Until that is changed, create time entries from Zapier with a Webhooks by Zapier custom request and a body like `{"hours": 1.5, "date": "2026-01-15", "projectId": "..."}`. ## Make Create a custom app from `integrations/make/modules.json` or use the HTTP module. Set the base URL to your instance and the connection header to `Authorization: Bearer YOUR_API_KEY`. The same `durationMinutes` warning applies to its Create Time Entry module. For triggers, use a Custom webhook module and register its URL with `POST /api/v1/webhooks`. ## n8n Use an HTTP Request node with a Header Auth credential (name `Authorization`, value `Bearer YOUR_API_KEY`) for calls, and a Webhook node for events. `integrations/n8n/example-workflow.json` in the repository is a daily time report workflow you can import. It points at `https://timetrack.dk`, so change the URL to your instance. --- # Desktop app > The TimeWren desktop app tracks activity automatically and syncs with your server. What the server provides, how devices sign in, and how to offer your own builds. Source: https://timewren.com/docs/apps/desktop The desktop app (Windows and macOS) records what you work on, classifies it, and keeps its data locally in a database on your computer. It syncs time entries, clients and projects with the server and supports offline use. Auto-tracking and classification run on the computer. If an offline edit reaches the server after the server entry changed, sync returns the current server entry as a conflict, even if the task referenced by the offline edit was deleted. The desktop app is built and released from its own repository, separate from the server. This page covers what your server provides for it. How the app's server address is entered is a setting of the app itself, so follow the app's own documentation for that. ## How a device signs in The app never sees your password. It opens your instance in the browser, you sign in there and approve the device, and the browser hands a one-time code back to the app through a deep link. - The newer device login uses PKCE and a `state` value. The one-time code is valid for 5 minutes and is exchanged for an access token (30 days) and a refresh token (180 days). The app renews them without a new login. - The older flow (`/auth/desktop`) issues a device token that is valid for 90 days. Make sure `NEXT_PUBLIC_APP_URL` is your real HTTPS address, because the approval page and redirects are built from it. The older device tokens are signed with `BETTER_AUTH_SECRET`, so changing that value signs desktop devices out, see [Authentication](https://timewren.com/docs/configuration/authentication.md#rotating-better_auth_secret). ## Manage devices Open Settings, Desktop in the web app to see connected devices (name, operating system, last sync) and remove one. A removed device must sign in again. Tokens of the newer login also appear under Settings, Integrations and can be revoked there. ## Downloads and updates A fresh TimeWren instance does not point at anyone's releases. If you build or host your own desktop releases on GitHub, tell the server where they are: ```dotenv # Build time (rebuild the image after changing) NEXT_PUBLIC_DESKTOP_RELEASES_REPO=your-org/your-desktop-releases # Server setting, used by the legacy updater endpoint DESKTOP_UPDATER_REPO=your-org/your-desktop-app ``` - `NEXT_PUBLIC_DESKTOP_RELEASES_REPO` (format `owner/repository`) is used by the `/download` page, which links the Windows installer (a file ending `-setup.exe`) and the macOS disk image (`.dmg`) from the latest release of a public repository. It does not publish anything. - `DESKTOP_UPDATER_REPO` is used by the update endpoint `/api/desktop/update/{target}/{arch}/{current_version}`, which turns the latest GitHub release into the answer the Tauri updater expects (Windows `.nsis.zip` and macOS `.app.tar.gz` assets with `.sig` signatures). Updates must be signed with the key your app build was made with. Keep the signing key and the public key inside your builds consistent. Leave both empty if you distribute the app another way. ## Minimum client versions You can stop old clients from writing time data to your server. Set a minimum per client type: ```dotenv MIN_CLIENT_VERSIONS=extension=2.5.2,mobile=1.0.0+5,desktop=0.2.21 # Only report outdated clients on the admin stability page, do not reject them MIN_CLIENT_VERSIONS_MODE=observe ``` Client types are `web`, `pwa`, `extension`, `mobile`, `desktop`, `api` and `mcp`. Clients identify themselves with an `x-timetrack-client: /` header. A client below its minimum is refused on time-entry, timer and extension writes with the error `CLIENT_TOO_OLD`, while reading and signing in stay allowed. Requests without the header (API keys, scripts, MCP) are never refused. Empty means no enforcement. The values above are examples; pick versions that exist for the clients you ship. --- # Mobile app > The TimeWren mobile app and what your self-hosted server provides for it: device login, push notifications and minimum versions. Source: https://timewren.com/docs/apps/mobile The mobile app is a native app that uses Expo. It is built and released from its own repository, separate from the server, and it signs in to the same account as the web app. This page covers what your server provides for it. How the app's server address is entered, and where the app is distributed, is not decided by the server and is covered by the app's own documentation. ## Signing in The app uses the same device login as the desktop app: it opens your instance in the browser, you sign in and approve the device, and the browser returns to the app through the deep link `timetrack://auth/callback` (`timewren://auth/callback` on a TimeWren instance). The access token lasts 30 days and is renewed with a refresh token (180 days), so you rarely sign in again. The app can also use the OAuth providers and Sign in with Apple that you configure, see [Authentication](https://timewren.com/docs/configuration/authentication.md). The server trusts the app schemes `timetrack://` and `timetrack.preview://` automatically (on a TimeWren instance also `timewren://`). You do not need to add them to `TRUSTED_ORIGINS`. For native Sign in with Apple, set `APPLE_APP_BUNDLE_IDENTIFIER` to the bundle id of the app build you use (default `dk.timetrack.app`), together with the other Apple variables. ## Push notifications The server sends push messages to the app through Expo. For notifications to work the server needs an Expo access token: ```dotenv EXPO_ACCESS_TOKEN=your-expo-access-token ``` Web Push for browsers and the PWA is separate and uses the VAPID keys. Both are optional. ## Minimum versions Operators can require a minimum build with `MIN_CLIENT_VERSIONS`, for example `mobile=1.0.0+5`. The app must send a numeric build after the plus sign for this to be decided. See [Desktop app](https://timewren.com/docs/apps/desktop.md#minimum-client-versions) for the format. ## Manage devices Signed-in devices appear as tokens under Settings, Integrations, with their device name and last use. Revoke one to sign that device out. --- # Browser extension > The TimeWren browser extension for Chrome and Firefox: timer, quick entries and prepaid balance in the toolbar. Connects to TimeWren Cloud or your own server. Source: https://timewren.com/docs/apps/browser-extension The browser extension puts a timer in your toolbar. You can start, pause and stop a timer, add time entries with project and client pickers, and see the status of your prepaid hour packages. It also has a new tab page and keyboard shortcuts: Alt+Shift+T opens the popup, Alt+Shift+S pauses or resumes the timer, and Alt+Shift+N opens quick entry. The interface is available in Danish, English, German and Spanish. ## New tab The extension shows TimeTrack when you open a new tab. You can turn it off with **Open TimeTrack on new tabs** in the popup settings or under **Settings** on the new tab itself. In Chrome you then get Chrome's own new tab page with its shortcuts, always in its Google version, even if your default search engine is a different one. In Edge, Firefox and other browsers an extension cannot hand the new tab back to the browser, so you get a simple page with a search box that uses the browser's default search engine instead. ## Connect to your own server The extension connects to TimeTrack Cloud by default. To use your own instance, open the popup and choose **Use own server** on the sign-in screen, or go to Settings, Advanced. Enter the public HTTPS address, for example `https://time.example.com`, and select **Connect to server**. 1. The browser asks for access to that one address. The extension never holds a blanket permission for all sites: the manifest lists `https://*/*` and `http://*/*` only as optional host permissions, and the request names the exact origin you typed. 2. The extension reads `/.well-known/timetrack.json` from your server and checks that it is a TimeTrack server with a compatible API version. Without a reachable discovery document the address is not saved. 3. Switching clears local account data and restarts the extension. Reopen it and sign in. Synchronise pending offline entries first, because they are not carried over. Select **Use TimeTrack Cloud** to switch back. Only HTTPS is accepted. In development builds, HTTP is also allowed for localhost and private network addresses, with a warning. The extension uses the browser's own certificate validation. A browser reports an invalid certificate as a generic network error, so the message asks you to check both the address and the certificate. Tokens belong to one server. They are never sent to another origin, and requests with a token do not follow redirects. On the server, `NEXT_PUBLIC_APP_URL` must be the public HTTPS origin, because the discovery document takes its URLs from it. Serve `/.well-known/timetrack.json` without a login. CORS for extension origins is on by default; `CORS_ALLOWED_ORIGINS` can restrict it to exact origins, see [Environment variables](https://timewren.com/docs/configuration/environment.md). ## Build and load it The extension lives in `browser-extension/` of the repository. It is MIT licensed, while the rest of the repository is AGPL-3.0. ```bash cd browser-extension npm install npm run build ``` For Chrome, open `chrome://extensions/`, enable Developer mode, choose Load unpacked and select `browser-extension/dist`. For Firefox, run `npm run build:firefox`, open `about:debugging#/runtime/this-firefox`, choose Load Temporary Add-on and select `dist-firefox/manifest.json`. This page does not claim that the extension is published in a browser store under the TimeWren name. ## Sign in The extension authenticates with a token, not with your password: 1. Open the web app, then Settings, Integrations, and find the Browser extension section. 2. Generate a token with a name such as "Chrome". It is shown once. 3. Paste it into the extension popup. You can see when each token was last used and revoke it in the same place. A revoked token stops working at once. ## Minimum versions As an operator you can require a minimum extension version with `MIN_CLIENT_VERSIONS`, see [Desktop app](https://timewren.com/docs/apps/desktop.md#minimum-client-versions). --- # REST API > Authenticate with an API key and manage clients, projects, time entries, the timer, invoices and prepaid packages over JSON. Source: https://timewren.com/docs/api/rest TimeWren exposes a JSON REST API under `/api/v1`. It uses the same business logic as the web app, so rules such as rate resolution, prepaid deductions and locks on billed entries apply to API calls too. For AI assistants there is also an [MCP server](https://timewren.com/docs/api/mcp.md), and you can receive events with [outgoing webhooks](https://timewren.com/docs/api/webhooks.md). ## Base URL Replace the host with your own instance (the value of `NEXT_PUBLIC_APP_URL`): ```text https://timewren.example.com/api/v1 ``` ## Create an API key 1. Sign in as an organization admin or owner. 2. Open **Settings**, then **API** (`/dashboard/settings/api`). 3. Create a key: give it a name, choose its scopes and optionally an expiry date. 4. Copy the key right away. It starts with `tk_live_` and is only shown once. Only a SHA-256 hash is stored. A key acts as the user who created it, inside the organization that was active at creation time. You can revoke a key at any time; a revoked or expired key returns `401`. The API-keys page requires the `public_api` module to be enabled for the organization. ## Authentication Send the key as a Bearer token on every request: ```bash curl https://timewren.example.com/api/v1/me \ -H "Authorization: Bearer YOUR_API_KEY" ``` `GET /me` needs no scope. It returns your profile and the `scopes` of the key, which makes it a good first check. The REST API accepts API keys only; OAuth tokens work on the [MCP endpoint](https://timewren.com/docs/api/mcp.md) but not here. ## Scopes Each key carries one or more scopes. A scope is `:`: | Resource | Covers | | --- | --- | | `clients` | Clients | | `projects` | Projects (also needed to schedule a project rate change) | | `time` | Time entries and the timer | | `invoices` | Invoices and invoice lines | | `prepaid` | Prepaid packages (klippekort) | | `tasks` | Tasks | | `reports` | Reports, rate history and listing rate changes | | `webhooks` | Outgoing webhook configuration | Permissions are `read`, `write` and `all`. `write` and `all` both include `read`. The scope `*` grants everything. Missing scopes return `403` with `Missing required scope: :`. ## Rate limits Authenticated requests are limited to 300 per minute per user. Every response carries `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (a Unix timestamp in seconds). When the limit is hit you get `429` with a `Retry-After` header in seconds. Failed authentication attempts are additionally limited per IP address. ## Requests and responses Request bodies are JSON (`Content-Type: application/json`). Successful responses wrap the result in `data`: ```json { "data": { "id": "..." } } ``` Creating a resource returns `201`. Money and rates are decimal strings such as `"850.00"` in responses. Dates are `YYYY-MM-DD`. CORS is open (`Access-Control-Allow-Origin: *`) for the documented methods. ### Pagination and sorting List endpoints take `page` (default 1) and `limit` (default 25, maximum 100). A `limit` above 100 is rejected with `400`, not cut off. They also accept `sort` and `order` (`asc` or `desc`); unknown sort fields fall back to `createdAt`. ```json { "data": [], "pagination": { "page": 1, "limit": 25, "total": 0, "totalPages": 0, "hasMore": false, "nextPage": null } } ``` Keep fetching while `hasMore` is `true`. `GET /tasks` supports sorting by `createdAt`, `status`, `priority` and `deadline`. Tasks without a value for the sort field appear last in either direction. ### Errors Errors share one shape: ```json { "error": { "code": "UNPROCESSABLE_CONTENT", "message": "Validation failed", "details": [{ "field": "hours", "message": "..." }] } } ``` `details` lists the failing fields. It is always present for validation errors (`422`), and some `400` responses carry it too, for example an invalid combination of prepaid fields on `POST /time-entries` or `PATCH /time-entries/{id}`. Treat it as optional on every error. Other codes you will see: `BAD_REQUEST` (400), `UNAUTHORIZED` (401), `FORBIDDEN` (403), `NOT_FOUND` (404), `CONFLICT` (409), `TOO_MANY_REQUESTS` (429) and `INTERNAL_SERVER_ERROR` (500). Unexpected errors never include stack traces. ## OpenAPI and the built-in docs | URL | Returns | | --- | --- | | `/api/v1/openapi.json` | The OpenAPI 3.1 document, public, no authentication | | `/api/v1/docs` | An interactive API reference rendered from the OpenAPI document | | `/api/v1/llms.txt` | A short plain-text guide for AI agents, public | The interactive reference loads the Scalar viewer script from `cdn.jsdelivr.net`, so the browser needs internet access to render it. The OpenAPI document is the most complete source for request and response fields. ## Resources All paths are relative to `/api/v1`. `{id}` is a UUID. | Resource | Methods and paths | Scope | | --- | --- | --- | | Me | `GET /me` | none | | Clients | `GET, POST /clients`; `GET, PATCH, DELETE /clients/{id}` | `clients` | | Projects | `GET, POST /projects`; `GET, PATCH, DELETE /projects/{id}` | `projects` | | Time entries | `GET, POST /time-entries`; `GET, PATCH, DELETE /time-entries/{id}`; `POST /time-entries/batch` | `time` | | Timer | `GET, POST, DELETE /timer` | `time` | | Tasks | `GET, POST /tasks`; `GET, PATCH, DELETE /tasks/{id}` | `tasks` | | Invoices | `GET, POST /invoices`; `GET, PATCH, DELETE /invoices/{id}`; `POST /invoices/from-time-entries`; `POST /invoices/{id}/send`; `POST /invoices/{id}/mark-paid`; `GET, POST /invoices/{id}/lines`; `PATCH, DELETE /invoices/{id}/lines/{lineId}` | `invoices` | | Prepaid packages | `GET, POST /prepaid-packages`; `GET, PATCH, DELETE /prepaid-packages/{id}` | `prepaid` | | Reports | `GET /reports/unbilled`; `GET /reports/revenue`; `GET /reports/time-summary` | `reports` | | Rate changes | `GET, POST /rate-changes`; `DELETE /rate-changes/{id}` | `reports` to list; `clients` or `projects` write to create or cancel | | Rate history | `GET /rate-history` | `reports` | | Webhooks | `GET, POST /webhooks`; `GET, PATCH, DELETE /webhooks/{id}`; `POST /webhooks/{id}/test`; `GET /webhooks/{id}/deliveries`; `GET /webhooks/event-types` | `webhooks`, see [Webhooks](https://timewren.com/docs/api/webhooks.md) | Notes on a few endpoints: - `GET /reports/revenue` and `GET /reports/time-summary` require both `from` and `to` as `YYYY-MM-DD`. - `GET /rate-changes` and `POST /rate-changes` need exactly one of `clientId` or `projectId`. The body of a `POST` is `{ "clientId" | "projectId", "newRate", "effectiveDate": "YYYY-MM-DD" }`. - `POST /invoices/from-time-entries` builds a draft invoice from time entries. Sending an invoice by email with `POST /invoices/{id}/send` cannot be undone. - `DELETE /timer` clears the running timer without saving a time entry. To record the time, create a time entry with `POST /time-entries`. ### Time entry filters `GET /time-entries` accepts `clientId`, `projectId`, `from`, `to` (`YYYY-MM-DD`), `isBillable` and `isBilled` (`true` or `false`), plus pagination. Sorting allows `createdAt`, `date` and `hours`. ## Examples ### List clients ```bash curl "https://timewren.example.com/api/v1/clients?limit=10&q=acme" \ -H "Authorization: Bearer YOUR_API_KEY" ``` `q` searches the client list; add `includeArchived=true` to include archived clients. ### Start and stop the timer Start (needs `time:write`). Without a body the timer starts now; here it is bound to a project and described. `projectId` and `clientId` must be UUIDs or `null`: ```bash curl -X POST https://timewren.example.com/api/v1/timer \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"projectId": "11111111-1111-4111-8111-111111111111", "description": "Design review"}' ``` Check the timer state: ```bash curl https://timewren.example.com/api/v1/timer \ -H "Authorization: Bearer YOUR_API_KEY" ``` Stop and discard it: ```bash curl -X DELETE https://timewren.example.com/api/v1/timer \ -H "Authorization: Bearer YOUR_API_KEY" ``` ### Create a time entry `hours` (a positive number), `date` (`YYYY-MM-DD`) and `description` are required. Optional fields are `projectId`, `clientId`, `notes`, `startTime` and `endTime` (ISO 8601 with offset, `endTime` after `startTime`), `isBillable`, `isBilled`, `taskId` and `billableRate`. Without `billableRate` the rate is resolved from the project, client and user rates for the entry's own date. ```bash curl -X POST https://timewren.example.com/api/v1/time-entries \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "clientId": "22222222-2222-4222-8222-222222222222", "projectId": "11111111-1111-4111-8111-111111111111", "description": "Wireframes for Acme ApS", "hours": 1.5, "date": "2026-11-09", "startTime": "2026-11-09T09:00:00+01:00", "endTime": "2026-11-09T10:30:00+01:00", "isBillable": true, "prepaid": "auto" }' ``` To deduct from a prepaid package, send either `"prepaid": "auto"` (the client's active auto-deduct package that expires first; no package means no deduction) or an explicit `prepaidPackageId`, never both. The response includes `prepaidDeduction` and `complianceWarnings`. Entries that are already billed are locked against edits and deletes. ### List prepaid packages ```bash curl "https://timewren.example.com/api/v1/prepaid-packages?clientId=22222222-2222-4222-8222-222222222222&activeOnly=true" \ -H "Authorization: Bearer YOUR_API_KEY" ``` Filters are `clientId`, `activeOnly=true` and `includeArchived=true`. Sorting allows `createdAt`, `name` and `totalHours`. See [Prepaid hours](https://timewren.com/docs/concepts/prepaid-hours.md) for how packages work. Creating a package with `POST /prepaid-packages` takes `name`, `clientId`, `totalHours` (number), `hourlyRate` (number) and `purchaseDate`, and optionally `expiryDate`, `description`, `clipSizeMinutes`, `overdraftPolicy` (`block`, `allow` or `invoice`), `overdraftRate` and `autoDeduct`. --- # Webhooks > Subscribe to TimeWren events with signed outgoing webhooks, manage them through the REST API and verify the HMAC signature. Source: https://timewren.com/docs/api/webhooks Outgoing webhooks let TimeWren call your server when something changes, for example when a time entry is created or an invoice is paid. Webhooks are managed through the [REST API](https://timewren.com/docs/api/rest.md) under `/api/v1/webhooks`. There is no settings page for them in the app. Creating, changing and deleting webhooks needs an organization admin or owner as the key's user. Your API key needs the `webhooks:write` scope for changes and `webhooks:read` to read. ## Create a webhook The URL must use HTTPS and must not point to a private or internal address. It is checked when you save it and again before each delivery. ```bash curl -X POST https://timewren.example.com/api/v1/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Accounting sync", "url": "https://hooks.example.com/timewren", "events": ["time_entry.created", "invoice.paid"] }' ``` | Field | Required | Notes | | --- | --- | --- | | `name` | yes | 1 to 100 characters | | `url` | yes | HTTPS URL | | `events` | yes | At least one valid event type, see below. Unknown types are dropped. | | `clientId` | no | Only send events for this client | | `projectId` | no | Only send events for this project | | `retryCount` | no | 0 to 10, default 3. The total number of delivery attempts, including the first. | | `timeoutMs` | no | 1000 to 60000, default 30000 | The response contains the signing secret (`whsec_...`) in `secret`. It is shown only this once; later reads return it masked. Store it where your receiver can read it. The REST API has no endpoint to rotate a secret, so if you lose it, create a new webhook and delete the old one. Other endpoints: | Method and path | Purpose | | --- | --- | | `GET /webhooks` | List webhooks | | `GET /webhooks/{id}` | Read one webhook | | `PATCH /webhooks/{id}` | Update `name`, `url`, `events`, `clientId`, `projectId`, `isActive`, `retryCount`, `timeoutMs` | | `DELETE /webhooks/{id}` | Delete the webhook and its delivery history | | `POST /webhooks/{id}/test` | Send a test delivery, limited to 5 per minute per webhook | | `GET /webhooks/{id}/deliveries` | Delivery log, `limit` up to 100 (default 50) | | `GET /webhooks/event-types` | List the available event types | ## Events | Category | Event types | | --- | --- | | Clients | `client.created`, `client.updated`, `client.archived` | | Projects | `project.created`, `project.updated`, `project.status_changed`, `project.budget_threshold` | | Time entries | `time_entry.created`, `time_entry.updated`, `time_entry.deleted` | | Invoices | `invoice.created`, `invoice.sent`, `invoice.paid`, `invoice.overdue` | | Prepaid packages | `prepaid.created`, `prepaid.updated`, `prepaid.low_balance`, `prepaid.expired` | | Tasks | `task.created`, `task.updated`, `task.completed` | Some events come from scheduled jobs rather than user actions: `invoice.overdue`, `prepaid.expired`, `project.budget_threshold` and automatic package renewals (`prepaid.created`). They only fire when the cron jobs are running, which the bundled cron container takes care of. ## Delivery Each delivery is an HTTP `POST` with a JSON body: ```json { "event": "time_entry.created", "timestamp": "2026-11-09T09:30:00.000Z", "data": { "timeEntry": { "id": "..." } } } ``` `data` holds the changed record under a key named after the resource (`client`, `project`, `timeEntry`, `invoice`, `prepaidPackage`, `task`). Some events add fields, such as `previousStatus` and `newStatus` on `project.status_changed`, or `changes` on `client.updated`. Headers sent with every delivery: | Header | Value | | --- | --- | | `Content-Type` | `application/json` | | `X-Webhook-Signature` | Hex HMAC-SHA256 of the raw request body | | `X-Webhook-Event` | The event type | | `X-Webhook-Timestamp` | Same value as `timestamp` in the body | | `X-Webhook-Delivery-Attempt` | 1 for the first try, then 2, 3, ... | | `User-Agent` | `TimeTrack-Webhooks/1.0` | Respond with any `2xx` status within `timeoutMs` to acknowledge. Anything else, a timeout or a connection error counts as a failure. ## Verify the signature The signature is the lowercase hex HMAC-SHA256 of the exact raw request body, keyed with your `whsec_...` secret. There is no prefix. Compute it over the raw bytes, before any JSON parsing: ```ts import crypto from "node:crypto"; import express from "express"; const secret = process.env.TIMEWREN_WEBHOOK_SECRET!; const app = express(); app.post("/timewren", express.raw({ type: "application/json" }), (req, res) => { const expected = crypto .createHmac("sha256", secret) .update(req.body) .digest("hex"); const received = String(req.header("X-Webhook-Signature") ?? ""); const a = Buffer.from(expected); const b = Buffer.from(received); if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) { return res.status(401).send("invalid signature"); } const payload = JSON.parse(req.body.toString("utf8")); console.log(payload.event, payload.data); res.sendStatus(200); }); app.listen(3001); ``` The signature does not cover replays. If that matters, also reject payloads whose `timestamp` is too old, and deduplicate on the record id. ## Retries and disabling The first attempt happens right after the event. If it fails, the delivery is marked `pending_retry` and a cron job (`/api/cron/webhook-retry`, every 5 minutes in the bundled cron container) retries it until `retryCount` attempts have been made, then marks it `failed`. There is no exponential backoff, so a retry waits for the next cron run. After 10 consecutive failed first attempts a webhook is disabled automatically (`isActive` becomes `false`, with a reason). Re-enable it with `PATCH /webhooks/{id}` and `{"isActive": true}`; this also resets the failure counter. A daily job removes old delivery logs: successful ones after 30 days, failed ones after 90. ## Incoming provider webhooks TimeWren also receives webhooks from other services, for example from Billy and from the mail provider Resend, under `/api/webhooks/*`. These are verified with each provider's own scheme and are not meant to be called by you. See [Billy](https://timewren.com/docs/integrations/billy.md) and [Email](https://timewren.com/docs/configuration/email.md) for setup. --- # MCP server > Connect Claude, Cursor, Codex and other MCP clients to TimeWren to log time, check prepaid hours and prepare invoices. Source: https://timewren.com/docs/api/mcp TimeWren includes a [Model Context Protocol](https://modelcontextprotocol.io) server, so an AI assistant can work with your clients, time entries, prepaid packages and invoices. It uses the same business logic as the [REST API](https://timewren.com/docs/api/rest.md). ## Endpoint ```text https://timewren.example.com/api/v1/mcp ``` The transport is Streamable HTTP. Discovery documents are served at `/.well-known/mcp/server-card.json` and `/.well-known/oauth-protected-resource/api/v1/mcp`. The URLs inside them are built from `NEXT_PUBLIC_APP_URL`, so make sure it matches the public address of your instance (see [Environment](https://timewren.com/docs/configuration/environment.md)). ## Authentication There are two ways to authenticate. Both send a Bearer token in the `Authorization` header. - **API key.** Create a `tk_live_...` key in **Settings**, then **API** and use it as the Bearer token. See [REST API](https://timewren.com/docs/api/rest.md#create-an-api-key). This is the simplest option for Claude Code, Cursor and scripts. - **OAuth.** Clients that support MCP authorization (for example Claude's custom connectors) discover the authorization server from the `401` response and let you sign in to TimeWren in the browser. The server supports dynamic client registration, PKCE and refresh tokens. On the consent screen you pick the organization and review the permissions. Access tokens start with `tt_at_` and can be revoked at any time. Without a valid token the endpoint answers `401`. ## What an MCP client can do An API key keeps exactly the scopes you gave it when you created it. An OAuth connection gets the read and write scopes shown on the consent screen (`clients`, `projects`, `time`, `invoices`, `prepaid`, `tasks` and `reports`; never `webhooks`, and never the all-access `*` scope), and is bound to the one organization you chose. Every tool checks the scope it needs before it runs, using the same rules as the REST routes, and returns an error if the connection lacks it. Requests are limited to 120 per minute per key or connected app and user. ## Tools | Tool | Scope | What it does | | --- | --- | --- | | `whoami` | none | Return the user id, organization and scopes of the current connection | | `list_clients` | `clients:read` | List clients with default hourly rate and contact info, with search and paging | | `get_client` | `clients:read` | Get one client by id | | `create_client` | `clients:write` | Create a client | | `list_time_entries` | `time:read` | List time entries, newest first, filtered by client, project, dates, billable and billed | | `create_time_entry` | `time:write` | Log time for a client or project, optionally drawing from a prepaid package with `prepaid: "auto"` or `prepaidPackageId` | | `update_time_entry` | `time:write` | Change fields of a time entry; billed entries are locked | | `list_prepaid_packages` | `prepaid:read` | List prepaid packages with total, used and remaining hours, expiry and status | | `unbilled_summary` | `reports:read` | Unbilled billable hours and amount per client | | `list_invoices` | `invoices:read` | List invoices, optionally for one client or status | | `invoice_from_time_entries` | `invoices:write` | Preview (`dryRun`) or create a draft invoice from a client's time entries; creating marks the entries as billed | | `send_invoice` | `invoices:write` | Email an invoice to the client, which cannot be undone | | `week_timesheet` | `time:read` | Your own time entries for one week (Monday to Sunday) per day with totals; an interactive timesheet in clients that support MCP Apps | | `klippekort_status` | `prepaid:read` | Prepaid packages with remaining hours, low or critical level and expiry, most urgent first; gauges in clients that support MCP Apps | List tools return a note telling the assistant which page to request next when the result is only partial. `invoice_from_time_entries` and `send_invoice` change data or contact your client, so ask your assistant to confirm with you before it calls them. ## Interactive views (MCP Apps) The server supports the MCP Apps extension (`io.modelcontextprotocol/ui`). In a client that supports it, for example Claude or ChatGPT, two tools show an interactive view in the conversation instead of plain text: - **Week timesheet** (`week_timesheet`). Ask "show my week". The view shows your entries per day with totals. Use the arrows to switch week, or **Edit** to change the hours or description of an entry. Billed entries are locked. - **Klippekort status** (`klippekort_status`). Ask "how much is left on Bageriet's klippekort". Each package has a gauge, its remaining hours and its expiry. **Draft invoice** sends a message asking the assistant for an invoice preview (`dryRun`) and to wait for your approval. The view cannot enforce that: creating the draft is a separate call to `invoice_from_time_entries`, which needs `invoices:write` (also for the preview) and marks the entries as billed. Keep tool approval on in your client so you confirm that call yourself. **Top up in TimeWren** opens the package in TimeWren. The views follow your instance's brand name and colours and the language and light or dark theme of the client. They are served as `ui://` resources, load nothing from the internet and get their data from the tool result. Everything a view changes goes through the same tools as the assistant, with the same scope checks. Editing an entry calls `update_time_entry`, so it needs `time:write`, and a key with only `time:read` can show the timesheet but not save changes. Clients without MCP Apps call the same tools and get a text summary with the data as JSON, so nothing needs to be configured. A client that says in its capabilities that it does not support the extension gets the tools without UI metadata. ## Client configuration Replace the URL and `YOUR_API_KEY` with your own values. ### Claude Code ```bash claude mcp add --transport http timewren https://timewren.example.com/api/v1/mcp --header "Authorization: Bearer YOUR_API_KEY" ``` ### Cursor Add this to `.cursor/mcp.json` in your project, or to `~/.cursor/mcp.json` for all projects: ```json { "mcpServers": { "timewren": { "url": "https://timewren.example.com/api/v1/mcp", "headers": { "Authorization": "Bearer YOUR_API_KEY" } } } } ``` ### Claude Desktop The simplest route is a custom connector: open **Settings**, then **Connectors**, add a custom connector and enter the endpoint URL. You sign in with OAuth, no key needed. To use an API key instead, bridge through `mcp-remote` in `claude_desktop_config.json` (requires Node.js): ```json { "mcpServers": { "timewren": { "command": "npx", "args": [ "-y", "mcp-remote", "https://timewren.example.com/api/v1/mcp", "--header", "Authorization:${TIMEWREN_AUTH}" ], "env": { "TIMEWREN_AUTH": "Bearer YOUR_API_KEY" } } } } ``` ### Codex Add this to `~/.codex/config.toml` and export the key as an environment variable: ```toml [mcp_servers.timewren] url = "https://timewren.example.com/api/v1/mcp" bearer_token_env_var = "TIMEWREN_API_KEY" ``` ```bash export TIMEWREN_API_KEY="YOUR_API_KEY" ``` ## Troubleshooting - `401`: the token is missing, wrong, revoked or expired. Test it with `curl https://timewren.example.com/api/v1/me -H "Authorization: Bearer YOUR_API_KEY"`. - A tool returns `Forbidden: missing required scope`: create a key with the scope listed in the table above. - `429`: you hit the rate limit. Wait for the number of seconds in the `Retry-After` header.