Author SHA1 Message Date
BobbyandClaude Opus 5.5 85cc7961b8 task: add history and spot probes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:15:57 -05:00
BobbyandClaude Opus 5.5 06c7091bb3 task: set User-Agent on claim (Cloudflare 1010), show error bodies
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:06:40 -05:00
BobbyandClaude Opus 5.5 76ee576a02 task: SimpleFIN coverage probe for #66
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:47:39 -05:00
BobbyandClaude Opus 5.5 5e8e2b8c0a new: public edge gateway, certificates, and DNS (ADR-0010)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:39:14 -05:00
BobbyandClaude Opus 5.5 8519546269 new: Smart home scope line (Jobs only, HA owns house state)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:22:05 -05:00
BobbyandClaude Opus 5.5 3f9a4b880a new: Maintenance vocabulary (Asset, Task, Service, Reading)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:05:53 -05:00
BobbyandClaude Opus 5.5 ef87951061 new: Fitness vocabulary (Workout, Exercise, Set, Measurement)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:07:07 -05:00
BobbyandClaude Opus 5.5 d49485ef21 new: Finance vocabulary and ADR-0001 Financial Account exception
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:17:55 -05:00
BobbyandClaude Opus 5.5 a132594b8b new: health, logs, and metrics (ADR-0009)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:51:57 -05:00
BobbyandClaude Opus 5.5 eb0022d94a new: secrets via SOPS in git, Owner roots in Vaultwarden (ADR-0008)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:08:56 -05:00
BobbyandClaude Opus 5.5 3d8e3c7e6f new: delivery via Flux pull and CI-committed digests (ADR-0007)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:36:41 -05:00
BobbyandClaude Opus 5.5 86281226fc new: Home Assistant job bridge (ADR-0006)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:18:38 -05:00
BobbyandClaude Opus 5.5 a8c7464e56 new: authentication and authorization (ADR-0005)
Amends ADR-0004 (RLS on Household data, Binding-aware policies) and adds
Token, Scope, and Household grant to the glossary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 10:40:48 -05:00
BobbyandClaude Opus 5.5 f82b8cbd82 new: database access (ADR-0004)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:54:39 -05:00
Bobby 2aea5ebaef gitignore 2026-11-24 07:28:43 -05:00
BobbyandClaude Opus 5.5 672c46de04 new: cluster distribution and topology (ADR-0003)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 22:28:41 -05:00
BobbyandClaude Opus 5.5 d746472e66 new: network exposure (ADR-0002)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 22:09:35 -05:00
BobbyandClaude Opus 5.5 8b1edd38c1 new: data ownership model (ADR-0001) and ownership glossary terms
Resolves wayfinder ticket #50: every record is Personal data or
Household data; Bots reach Personal data only via Bindings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 21:24:40 -05:00
Bobby 3161f2888c new: glossary from first wayfinding session 2026-11-23 21:08:15 -05:00
14 changed files with 651 additions and 302 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
.claude/
+145
View File
@@ -0,0 +1,145 @@
# hAPI
hAPI ("home API") is a personal, cloud-hosted API serving one household and its automations: finance, fitness, maintenance, and smart home. Access is restricted to a small, known set of Principals.
## Language
### Access
**Principal**:
Anything that authenticates to hAPI.
_Avoid_: User, account, client
**Person**:
A human Principal (the Owner, family, friends).
_Avoid_: User, human user, member
**Bot**:
A non-human Principal: a script, automation, or integration such as Home Assistant.
_Avoid_: Service account, machine user, integration account
**Owner**:
The single Person with administrative authority over hAPI and every other Principal. That authority covers Principals and the platform, not other Persons' Personal data.
_Avoid_: Admin, root, superuser
**Token**:
A Principal's secret credential for the API.
_Avoid_: API key, password
**Scope**:
A domain paired with read or write access: the unit of access that Household grants and Bindings carry.
_Avoid_: Permission, privilege
**Binding**:
A Person's consent letting a specific Bot act on that Person's Personal data in one domain, up to a given Scope.
_Avoid_: Delegation, impersonation, link
**Household grant**:
The Owner's permission for a specific Bot to act on one domain's Household data, up to a given Scope.
_Avoid_: Permission, role
### Ownership
**Household**:
The single group of Persons that hAPI serves. There is exactly one.
_Avoid_: Family, tenant, organization, group
**Household member**:
A Person who belongs to the Household. A Person can be a Principal without being a Household member (e.g. a friend).
_Avoid_: Family member, resident
**Personal data**:
A record owned by one Person, visible only to that Person (and to Bots bound to them).
_Avoid_: Private data, user data
**Household data**:
A record owned by the Household, visible to every Household member.
_Avoid_: Shared data, common data
**Recorded by**:
The Principal that created or last changed a record, distinct from who owns it.
_Avoid_: Author, owner, creator
### Smart home
Smart home is hAPI's side of the house: queuing Jobs for Home Assistant, which remains the source of truth for the house's state.
**Job**:
A request, queued in hAPI, for Home Assistant to carry out an action in the house. Jobs are Household data. Domain code, Persons, and Bots can all create them.
_Avoid_: Task, command, message
### Finance
**Financial Account**:
A bank, credit card, or cash account whose money hAPI tracks. It is owned by a Person or by the Household, and its Transactions share that owner.
_Avoid_: Account (on its own), bank account, wallet
**Transaction**:
A single posted movement of money into or out of one Financial Account.
_Avoid_: Entry, charge, payment
**Category**:
A named bucket that Transactions are sorted into, of kind expense, income, or transfer. Household Categories can be used by the Household and by every Household member; Personal Categories only by their Person.
_Avoid_: Tag, label, envelope
**Budget**:
One owner's zero-based monthly plan: expected income assigned across Categories, then rebalanced during the month with Moves. The Household has one, and each Person may have one.
_Avoid_: Plan, envelope
**Target**:
A Budget's standing amount for one Category over a period (monthly, quarterly, or annual), spread into even monthly shares.
_Avoid_: Goal, limit
**Allocation**:
What a Budget assigns to one Category in one month: the Target's monthly share, adjusted by Moves.
_Avoid_: Budgeted amount, envelope
**Move**:
A shift of money from one Category's Allocation to another's within one month of a Budget. It never changes the month's total.
_Avoid_: Transfer (a kind of Category), reallocation
**Banked**:
Said of a Category whose Target period is longer than a month. Its unspent Allocations carry forward as a banked balance until the bill draws it down.
_Avoid_: Sinking fund, rollover, savings
**Payee mapping**:
An owner's remembered link from a payee to a Category, learned from manual categorization and applied to newly ingested Transactions.
_Avoid_: Rule, auto-categorization
### Maintenance
Maintenance is the upkeep of the Household's physical property: the home, its land, its equipment, and its vehicles.
**Asset**:
A physical thing the Household keeps up, such as the roof, the furnace, a fridge, or a car. It may have a meter whose Readings track its use.
_Avoid_: Equipment, item, entity (a Home Assistant term); in Finance, use another word
**Task**:
A recurring piece of upkeep, due either a fixed interval after it was last done or on a calendar rhythm, and optionally also after a set amount of use. Tasks always recur; one-off work is recorded only as a Service.
_Avoid_: Chore, reminder, to-do (and never a Job)
**Service**:
One piece of maintenance work done on a date. It may fulfill a Task, and may concern an Asset.
_Avoid_: Completion, repair, log entry
**Reading**:
An Asset's meter value (an odometer's distance or a runtime counter) taken on a date, used to decide when usage-based Tasks come due.
_Avoid_: Measurement (a Fitness term), metric
### Fitness
**Workout**:
One session of exercise by one Person: an ordered list of Exercises performed, with what was done in each. A run is a Workout with a single cardio Exercise.
_Avoid_: Session, activity, training
**Exercise**:
A named movement that Workouts record, of kind strength, bodyweight, timed, or cardio; the kind decides what is recorded for it. Household Exercises can be used by every Household member; Personal Exercises only by their Person.
_Avoid_: Movement, lift, activity
**Set**:
One bout of a strength, bodyweight, or timed Exercise within a Workout: reps and load, or a duration. A warmup Set doesn't count toward records.
_Avoid_: Rep, round
**Measurement**:
One reading of a Person's body (weight, body fat, or a circumference) at a point in time.
_Avoid_: Metric, stat, body stat
+13
View File
@@ -0,0 +1,13 @@
# Every record is owned by a Person or by the Household
hAPI serves exactly one Household, so there is no multi-tenancy. Every record is either **Personal data**, owned by one Person and visible only to them, or **Household data**, owned by the Household and visible to every Household member on equal terms. Each record type declares which kind it is: fitness is personal, home maintenance and smart home are household, and finance has both. We chose this over per-record sharing (which needs sharing lists and revocation) and over "everything household" (which gives no privacy for personal finances). Anything that needs to be shared is modelled as Household data.
## Consequences
- **The Owner has no special read access to Personal data.** Owner authority covers Principals and the platform only. Bots reach Personal data only through a **Binding** that the bound Person grants and can revoke. The Owner cannot grant one on another Person's behalf.
- Every record carries its owner plus **Recorded by**: the Principal that created it and the one that last changed it. Principals are deactivated, never hard-deleted, so Recorded by never dangles.
- Ownership is fixed when a record is created, except that a Person may move their own Personal record to the Household (one way only).
- **Finance exception:** Financial Accounts and their Transactions never move. To bring an account into the Household, the Personal Financial Account stops tracking at a date and a new Household one starts tracking from it, so spending history stays with the owner who spent it. Finance Categories can still be promoted.
- When a Person is removed, their Personal data is exported and then explicitly deleted. Household data they recorded stays with the Household.
- Persons who are not Household members (e.g. friends) see only their own Personal data.
- Not in v1: roles within the Household, sharing outside the Household, and guest access to Household data.
+18
View File
@@ -0,0 +1,18 @@
# One public surface, gated only by hAPI's own auth; no tunnel to home
Persons must reach hAPI from anywhere without a VPN. The home network sits behind ISP CGNAT with a changing IP, so the cluster can never open a connection into the home, and the home IP can't be allowlisted. A CGNAT address is shared with other customers, so allowlisting it would also let them in. We therefore expose **one public surface**, the hAPI API over HTTPS on `:443`, used by Persons and Bots alike, with **hAPI's own authentication as the only gate**. Bots get no separate network path: no VPN, no separate port, no client certificates. Writing a cron job then takes nothing more than `curl` with a token. We chose this over a tunnel for Bots (Tailscale or WireGuard, with a client on every Bot) and over a client-cert-gated Bot port. Both were workable but added setup to every Bot. Client certs stay available as later hardening.
## Considered Options
- **A tunnel for every Bot (Tailscale + k8s operator, or plain WireGuard).** Works behind CGNAT because home dials out. Rejected: every Bot needs a client, and the Tailscale operator can't be used with Tailnet Lock, which leaves Tailscale's control plane trusted.
- **Client-cert-gated Bot endpoints.** Gateway API enforces client certs per port, not per hostname, so this needs its own port. Home Assistant can present a client cert only over MQTT. Rejected as v1 friction.
- **An identity-aware proxy or CDN in front (e.g. Cloudflare).** Rejected: we want no third party in the public request path, meaning no browser challenge pages and no outage when a vendor has one.
## Consequences
- **Traffic between the cluster and home only ever starts from home.** hAPI never calls into the house. The job bridge to Home Assistant must be one that HA connects out to (pulls or holds open).
- **Every public endpoint is TLS-only and requires per-Principal auth.** No anonymous endpoints, including health: Uptime Kuma is a Bot with a health-only scope. `:80` is closed, so certificates use ACME DNS-01. A broker, if the bridge needs one, may be public under the same rule.
- **Bot credentials carry the security a network gate would have.** Each is per-Bot, scoped, individually revocable, and stored hashed. A long-lived JWT that can't be revoked is not acceptable as a Bot credential.
- **Owner administration has no HTTP route.** Creating Principals, issuing and revoking credentials, and Household grants are done through an admin CLI inside the hAPI pod, reached only through cluster management access. Persons' own actions, including granting Bindings, stay on the public API.
- **Cluster and node management APIs (Kubernetes, Talos) are never public.** They're reachable only over a management-only Tailscale tailnet (node extension plus the Owner's devices) with Tailnet Lock on. This tailnet is not in the public request path, so a Tailscale outage never takes hAPI down. Break-glass: the Linode LISH console, or a temporary firewall rule for the Owner's current IP.
- **Never public:** the database, metrics, detailed health, and any internal service.
@@ -0,0 +1,18 @@
# Talos on Linode with one control-plane node, Cilium, and OpenTofu
The hAPI cluster runs **Talos Linux** on Linode compute in `us-iad`: **one control-plane node and two workers**, all `g6-standard-2`, provisioned with **OpenTofu**. Its CNI is **Cilium**, with WireGuard encrypting traffic between nodes. We chose Talos because it is immutable and managed only through an authenticated API, with no shell or SSH. That fits a security-first, one-operator cluster better than RKE2 (CIS-hardened, but a general-purpose OS to patch), k3s (defaults favor convenience) or kubeadm (most learning, weakest defaults). A single control-plane node keeps cost and moving parts proportionate to a small load. Postgres is a managed service outside the cluster, so etcd holds no hAPI data, and the cluster can be rebuilt from code.
## Considered Options
- **Three control-plane nodes (HA etcd).** Rejected for v1 as oversized. With dedicated workers it costs about $48/mo more. Running workloads on the control plane instead would mix them with etcd. Moving to three is an additive Talos change.
- **A NodeBalancer in front of the Kubernetes and Talos APIs**, as the Talos Linode guide describes. Rejected: ADR-0002 keeps those APIs off the internet. The cluster endpoint is the control-plane node's tailnet name instead.
- **VPC-only nodes behind a NAT gateway.** Rejected for now: Tailscale would fall back to DERP relays, and the NAT gateway is newer. Nodes have public IPv4 with a firewall that denies all inbound traffic except Tailscale's UDP port.
- **Terraform.** OpenTofu is chosen for its open licence and its client-side state encryption. The state holds Talos machine secrets.
## Consequences
- **Losing the control-plane node means rebuilding it from code.** Workloads keep serving in the meantime, but the cluster can't be changed until it is back.
- **No SSH, ever.** All node access goes through `talosctl` over the management tailnet. Break-glass is the Linode LISH console.
- **Every node joins the management tailnet** with a pre-signed auth key, so Tailnet Lock stays on.
- **OpenTofu and Talos install only Cilium and the Linode CCM.** These are what nodes need to become Ready. Everything else arrives through delivery.
- **Disks are encrypted at rest** with Talos LUKS on STATE and EPHEMERAL, in addition to Talos's default encryption of Secrets in etcd.
+33
View File
@@ -0,0 +1,33 @@
# Database access: VPC-only, two roles, Personal data isolated by row-level security
hAPI uses a **Linode Managed PostgreSQL 18** cluster (Shared 2 GB, 1 node) attached to the cluster's VPC with `public_access = false`, and its allowlist holds only the VPC subnet. Clients connect with `sslmode=verify-full` and scram-sha-256 passwords. Two roles share the `hapi` database. **`hapi_migrator`** owns every schema and table and runs `hapi migrate`. **`hapi_app`** has DML only; the running app and the admin CLI both connect as it. Personal-data tables have `ENABLE ROW LEVEL SECURITY` (not `FORCE`), with policies keyed on a per-transaction `SET LOCAL hapi.principal_id`, so a forgotten `WHERE` in a handler returns nothing instead of leaking another Person's data. `hapi_app` never owns a table and has no `BYPASSRLS`. That keeps ADR-0001's rule (not even the Owner reads others' Personal data) in the database for everything the app does. We accept that VPC for Managed Databases is still labelled beta, because ADR-0002 rules out a public database endpoint. It was verified working in `us-iad`.
**Amended by ADR-0005:** RLS also covers **Household data** tables. Their policies allow an active Household member or a Bot with a Household grant for that domain. Personal-data policies also allow a Bot that holds an active Binding from the record's owner. In both cases `USING` checks the read Scope and `WITH CHECK` checks the write Scope. `hapi.principal_id` is always the authenticated Principal, Person or Bot. The CI isolation check below covers every owned table, Personal or Household.
## Considered Options
- **Public endpoint with a node-IP allowlist.** Rejected: it contradicts ADR-0002 ("Never public: the database").
- **App-only filtering (no RLS).** Rejected: one missed filter becomes a data leak. Wrong-Principal tests stay mandatory on top of RLS.
- **`FORCE ROW LEVEL SECURITY`.** Rejected: it binds the owner `hapi_migrator` too, so every data migration and break-glass session would need `ALTER TABLE … NO FORCE`. The only thing it adds is protection against the migrator, which is the operator, and the operator is outside RLS's guarantee anyway.
- **Signed principal context, or one role per Person.** Rejected as protection against leaked `hapi_app` credentials. A signing key would live in the same pod as the password. Per-Person roles would all have to be grantable to `hapi_app`, so leaked credentials could switch to any of them.
- **A single role, or one role per domain schema.** One role lets the app run DDL and own tables, and owners bypass RLS. Per-domain roles add no isolation, because the monolith process would hold all of them anyway.
- **A `BYPASSRLS` role for admin tooling.** Rejected: the Owner has no read access to Personal data, so nothing in the request path or admin CLI needs one.
- **Managed or self-hosted PgBouncer.** Not needed at this load (see the connection budget below).
- **PostgreSQL 19.** Newly offered on the platform. We stay on 18, which all our verification ran on and which nothing in v1 outgrows. Revisit at the first major-upgrade window.
## Consequences
- **What RLS protects against:** app bugs only. Anyone holding `hapi_app` credentials can set any `hapi.principal_id`. Leaked credentials are contained by the network, because the VPC-only allowlist (verified as the enforcing control) limits use to the cluster and VPC. Whoever holds `akmadmin` (which has `BYPASSRLS`), `hapi_migrator` or the OpenTofu state can read everything. Owner non-access is enforced by policy and audit, not cryptography. Per-Person encryption is out of scope for v1.
- **Policies treat an unset principal as no principal.** After a transaction, the setting reads `''`, not NULL, so policies use `nullif(current_setting('hapi.principal_id', true), '')`.
- **CI enforces isolation:** every owner-mixin table must have `relrowsecurity` set and be owned by `hapi_migrator`, never `hapi_app`. Tests and local dev use the same bootstrap and connect as `hapi_app`.
- **`akmadmin` is never in the cluster.** An idempotent `hapi db bootstrap` admin CLI command creates the roles and the database. The Owner runs it in a pod and pastes in the `akmadmin` password at run time. It does the following:
1. Waits until the private hostname resolves (about 60 s after the cluster reports ready).
2. Creates `hapi_migrator` and `hapi_app`.
3. Runs `CREATE DATABASE hapi OWNER hapi_migrator`.
4. Runs `SET ROLE hapi_migrator` for the database-level `REVOKE`/`GRANT`s and `ALTER DEFAULT PRIVILEGES`. Run as `akmadmin`, these silently do nothing.
- **Cross-Person work runs per Person.** Purging a removed Person's data, or a job such as reminders, sets `hapi.principal_id` to each Person in turn.
- **Data repairs** normally ship as reviewed Alembic data migrations run as `hapi_migrator`, targeting rows by id or condition without printing them.
- **Break-glass goes through `hapi db breakglass --reason "…"`.** It opens `psql` as `hapi_migrator` from a pod and emits structured audit events to hAPI's centralized logs: start, end, reason, and every statement. Query results are never logged. The platform offers no statement logging or pgaudit, so this is the only audit trail.
- **Connection budget:** the plan allows 50 connections. That leaves about 46 usable after 3 reserved superuser slots and one platform backend. Each app pod holds at most 10 (`pool_size=5`, `max_overflow=5`), and the admin CLI holds 1–2. The rule is: (maximum concurrent app pods, including rollout surge) × 10, plus about 6 for migrate, CLI, break-glass and bootstrap, must be ≤ 46. That caps app pods at 4. Any future worker process counts against the same budget.
- **Plan changes are restores.** An in-place resize stalled during verification. Changing size or node count is done as a restore-to-new-cluster, with the same runbook as disaster recovery: fork, wait for DNS, `hapi db bootstrap`, repoint the app. Single-node maintenance windows (pinned to a quiet slot) cause short downtime, covered by 14-day point-in-time recovery.
- Passwords are rotated manually with a runbook. `password_encryption` is set explicitly to `scram-sha-256`.
@@ -0,0 +1,26 @@
# Opaque per-Principal tokens; authorization by ownership, grants and row-level security
In v1, every Principal (Person or Bot) authenticates with a bearer **Token**. There is no identity provider and no interactive login, because there's no frontend: Persons use scripts, HTTP clients and Shortcuts, just as Bots do. A Token is opaque: `hapi_<public-id>_<secret>`, where the secret has 256 bits of entropy. hAPI stores only a SHA-256 of the secret and looks the Token up in Postgres on every request, so revoking a Token takes effect immediately, as ADR-0002 requires. Authorization keys off the **Principal**, never the credential. Persons are authorized purely by ownership (ADR-0001). Bots have no access until they're given a **Scope** (`<domain>:read` or `<domain>:write`, where write implies read, plus the special `health` scope). A Bot gets Scopes through **Household grants**, which the Owner gives through the admin CLI, and **Bindings**, which a Person gives through the API, one domain at a time. Enforcement sits in row-level security as well as in the app, so a forgotten check fails closed.
## Considered Options
- **OIDC with a self-hosted IdP** (Authelia, Kanidm, Pocket ID). Rejected for v1. It's another public-facing service to run and secure, every request would depend on it, and refresh flows are painful for curl cron jobs.
- **Passkeys served by hAPI.** These need a web origin and a login page, which amounts to a frontend. Deferred until a frontend exists (see Consequences).
- **Short-lived JWTs signed by hAPI, plus refresh tokens.** Rejected. Revocation lags by up to a token lifetime, there's a signing key to manage, and every client needs refresh logic. At our load, one indexed lookup per request costs nothing, and it uses the request's own pooled connection.
- **mTLS client certificates.** Already rejected in ADR-0002.
- **Per-resource or per-record-type Scopes** (e.g. `finance.transactions:write`). Rejected as premature. A domain Scope can later be split into finer ones without breaking anything.
- **Choosing whose Personal data a Bot means with a request header** (`Hapi-Acting-For`). Rejected because the same URI would then name different resources depending on the header.
- **Nested owner paths** (`/persons/{id}/workouts`, `/household/transactions`). Rejected. ADR-0001 lets a record move from Personal to Household, and nesting would change its URI when it does. Listing everything a Bot may see would also take one call per Person.
- **Owner powers on the public API** (e.g. revoking a Bot from a phone). Rejected. If the Owner's Token leaks, it should do no more harm than any other Person's.
## Consequences
- **Resources are flat and ownership is an attribute.** Each record has exactly one URI, `/v1/<domain>/<things>/{id}`, and keeps it when it moves to the Household. Every record exposes `owner` (a Person id or `household`) and `recorded_by`. Lists accept `?owner=me|household|<person-id>`, and without a filter they return everything the caller may see. When creating a record, `owner` is required for a Bot writing Personal data. For a Person it defaults to themselves on Personal types and to the Household on Household types.
- **`hapi.principal_id` is always the authenticated Principal.** Personal-data policies allow rows where the owner is the principal, **or** the owner has an active Binding to the principal for that domain. Household-data policies (amending ADR-0004) allow an active Household member **or** a Bot with a Household grant for that domain. `USING` checks the read Scope and `WITH CHECK` checks the write Scope. Routes also declare `require_scope(...)`, so a caller missing a Scope gets a clean `403` and the Scope appears in the OpenAPI export. Recorded by is simply the principal.
- **Responses:** any missing, malformed, unknown, expired or revoked Token gets the same `401` with `WWW-Authenticate: Bearer`. A missing Scope or Binding returns `403`. A record the caller can't see returns `404`. Tests cover wrong Person, wrong Bot, a revoked Binding and a read-only Scope attempting a write.
- **Token lifecycle:** Tokens expire after 365 days by default, with the lifetime configurable when issued. `--no-expiry` is allowed only for Bots, and the CLI lists such Tokens in a warning. A Principal may hold several live Tokens, so rotation goes issue, swap, revoke. `last_used_at` is written at most about once an hour, and `hapi token list` flags Tokens that are near expiry or unused for 90 days.
- **Issuing stays in the CLI** (ADR-0002). On the public API, a Person may list and revoke their own Tokens (but not mint them), grant, list, change and revoke their Bindings, and list Bots (id, name, description). The Owner cannot create a Binding on a Person's behalf.
- **Deactivation** revokes all of a Principal's Tokens and makes its Household grants and Bindings inert, whichever side of a Binding it was on. Household membership is a flag the Owner sets in the CLI. The Owner can't be deactivated; ownership is transferred through a CLI command that needs the current Owner's confirmation.
- **Auth is audited in the logs.** Every auth decision is logged as a structured event with the principal id, the credential's public id, the outcome and the reason. Changes to Tokens, grants and Bindings are logged as audit events. Secrets are never logged. There's no app-level rate limiting, since 256-bit secrets can't be brute-forced. Any per-IP limits belong at the Gateway.
- **The Token prefix is deliberate.** It lets secret scanners and push protection recognise a leaked Token.
- **A future frontend adds a credential kind and changes nothing else.** Credentials carry a `kind`, which is `api_token` in v1. A browser login (passkeys or OIDC) would add, say, a `session` kind that resolves to the same Person. Scopes, Bindings and RLS stay as they are. Cookie, CSRF and CORS handling arrive with that frontend.
@@ -0,0 +1,20 @@
# Home Assistant polls hAPI for Jobs that name allowlisted HA scripts
hAPI needs Home Assistant to carry out actions in the house: things queued while a Person is away, or one-offs not worth configuring in HA. Traffic between the cluster and home only ever starts from home (ADR-0002), so HA has to come to hAPI. A **Job** is Household data (ADR-0001), created by domain code, Persons, or Bots through `/v1/smart_home/jobs`. **HA polls** `GET /v1/smart_home/jobs/next` every 15–30 s with its built-in `rest` sensor. An HA automation runs the Job and reports back through `rest_command` to `POST /v1/smart_home/jobs/{id}/result`. A Job never names an arbitrary HA action. It names an **HA script** (`hapi_*`) plus variables, and HA only runs `script.hapi_*`, so HA decides what hAPI can ever trigger. Jobs tolerate about 30 s of latency: anything interactive and real-time goes from the Person straight to HA's own app, not through hAPI. This bridge carries only Jobs and their results. HA sends other data to ordinary domain endpoints as a Bot.
## Considered Options
- **MQTT through a Mosquitto broker in the cluster.** HA's supported message bus gives sub-second delivery. Rejected for v1: it means running and exposing a broker, plus an auth bridge so the broker understands hAPI Tokens, plus a single publisher process inside hAPI. HA's client always uses a clean session, so durability would live in hAPI regardless. MQTT remains the upgrade path if real-time Jobs ever matter.
- **RabbitMQ / AMQP.** HA has no AMQP integration and explicitly doesn't support RabbitMQ's MQTT plugin.
- **A custom HA integration** (long-poll or SSE against hAPI). This has the cleanest semantics, but it's Python to keep working through every HA release. Since 2026.11 it also can't be installed through the Marketplace from a private Gitea repo.
- **hAPI calling HA's REST or WebSocket API.** Ruled out by ADR-0002, because traffic only starts from home.
- **Jobs naming arbitrary HA actions** (e.g. `lock.unlock`). Rejected: any holder of `smart_home:write` could do anything HA can do.
## Consequences
- **The bridge needs no new infrastructure or credentials.** HA is the `home-assistant` Bot with a Household grant of `smart_home:write`, and its Token lives in HA's `secrets.yaml`. There's no `jobs` Scope: `smart_home:write` both creates Jobs and consumes them, and ADR-0005 allows splitting the Scope later.
- **Delivery is at-least-once, FIFO by `not_before` (or creation time).** `next` hands out the oldest eligible Job and hides it for a 2-minute lease. After 3 deliveries with no result, the Job becomes `failed` (`no_result`), so one broken Job can't stall the queue. HA scripts must be idempotent: set states, don't toggle. After each result, HA calls `homeassistant.update_entity` on the sensor so a backlog drains without waiting for the next poll.
- **Job lifecycle:** `pending → succeeded | failed | expired | cancelled`. A Job may carry an optional `not_before`. `expires_at` defaults to 1 h after `not_before` (or after creation), and an expired Job is never delivered. A result is `{status, error?, response?}`, where `response` holds the script's response variables. The first result wins, and a later one gets `409`. Any Household member, or any Bot with `smart_home:write`, can cancel a `pending` Job. Finished Jobs are immutable and are kept for 90 days. Until scheduling exists, `hapi jobs purge` removes them.
- **hAPI checks only the shape of a Job, not what it does.** Script names must match `hapi_[a-z0-9_]+`, and variables are capped at 16 KB. hAPI keeps no catalogue of HA scripts. HA rejects unknown scripts, which comes back as a failed result.
- **HA-side configuration** is a reference package in this repo (`integrations/home-assistant/hapi_jobs.yaml`: rest sensor, automation, rest_command), copied into HA by hand. The `hapi_*` scripts themselves live in a separate HA configuration repo.
- **hAPI records HA's last poll**, so a stalled bridge can be detected. Turning that into an alert is part of observability.
+24
View File
@@ -0,0 +1,24 @@
# Flux pulls from git; CI builds images and commits their digest
Every green merge to protected `main` reaches production, with no release tags and no staging. **Gitea Actions** runs CI on a dedicated runner VM. On a PR it runs lint, pyright, import-linter, the testcontainers test suite, the image build, a smoke test, the OpenAPI export, and a Trivy scan that fails on fixable critical or high CVEs. On `main` it also pushes the image to **Gitea's container registry** and commits the new **digest** into `deploy/apps/hapi`. **Flux** in the cluster polls this repo every minute and applies what's committed. The cluster pulls; CI never pushes to it. CI holds no cluster credentials, and the cluster holds no git credentials (the repo is public, so Flux fetches anonymously over HTTPS). Kubernetes and Talos APIs stay reachable only from the management tailnet (ADR-0002), and no CI system ever joins it.
## Considered Options
- **CI push** (`kubectl apply` / `helm upgrade` from a workflow). Rejected: the runner would join the management tailnet with a kubeconfig, so a compromised workflow or dependency would become cluster-admin, and Tailnet Lock would have to trust another node.
- **Argo CD.** Rejected for its web UI, which would need keeping off the internet, and its weight. One operator with `flux`/`kubectl` over the tailnet doesn't need a UI.
- **Flux image automation** writing digest bumps back to git. Rejected: it needs a write deploy key inside the cluster, turning a cluster compromise into a source-code compromise. CI already decides which image runs, so giving CI the write key adds little.
- **A Flux webhook `Receiver`** for instant deploys. Rejected: it's a new public HTTP route without per-Principal auth (ADR-0002). A one-minute poll is fine.
- **A runner on the Gitea host or in the cluster.** Rejected: a job with Docker access on the Gitea host can read every repo and every Actions secret, and the cluster shouldn't run CI workloads.
## Consequences
- **Layout:** `deploy/clusters/prod` (Flux's entry point), `deploy/infrastructure` (`HelmRelease`s for upstream components), `deploy/apps/hapi` (the Kustomize base, including the migrate Job). Flux runs with `prune: true` and drift correction on. The Owner installs Flux once over the tailnet with `flux install` plus a `GitRepository`/`Kustomization`. From then on Flux manages itself from git.
- **Migrations run as a Job in their own Flux Kustomization** (`hapi-migrate`), using `hapi_migrator` credentials (ADR-0004). The Job name carries the image digest, so each release gets a new Job. The app Kustomization `dependsOn` it with `wait: true`, so a failed migration stops the rollout and the old pods keep serving. **Migrations must be backward-compatible** (expand, then contract in a later release) because old pods run against the new schema. **Migrations go forward only:** there are no down-migrations.
- **Rollout:** 2 replicas, `maxSurge: 1`, `maxUnavailable: 0`, no HPA, a PodDisruptionBudget with `minAvailable: 1`, and replicas spread across the two workers. That's at most 3 app pods, within ADR-0004's cap of 4.
- **Rollback is `git revert` of the digest bump.** A rollout that never becomes ready stalls, and the old pods keep serving. There's no automated rollback. Break-glass: `flux suspend`, then `kubectl rollout undo`, then bring git back in line.
- **Images are public**, because Gitea package visibility follows the owner. Images must never contain secrets. Deploys reference digests, never mutable tags. Builds are amd64 only.
- **The CI write credential is a deploy key with write access**, stored as an Actions secret and allowlisted past `main`'s branch protection. The build workflow's path filter skips bump commits, so a bump doesn't trigger another build.
- **Renovate runs nightly** on the same runner as its own bot user. It auto-merges only dev-only tooling. Anything that ships (runtime dependencies, base image, charts, Flux, Talos, OpenTofu providers) arrives as a PR the Owner merges.
- **Not delivered through Flux:** the runner VM, Cilium, and the Linode CCM live in OpenTofu under `infra/`, and the Owner runs `tofu apply` over the tailnet. Talos and Kubernetes upgrades are a manual `talosctl` runbook. CI never holds the Tofu state key.
- **Failures notify through ntfy:** a final `if: failure()` step in each workflow, and Flux's notification-controller for failed reconciles and rollouts. Topics and auth are designed with notifications.
- **Deferred:** having Flux verify commit signatures, and signing images (cosign) with admission-time verification. Both guard against a compromised Gitea and belong together in cluster hardening.
+33
View File
@@ -0,0 +1,33 @@
# Secrets are SOPS-encrypted in the public repo; Owner roots live in Vaultwarden
Secrets the cluster needs are committed to this **public** repo, encrypted with **SOPS + age**, and Flux's kustomize-controller decrypts them as it applies them. Flux pulls with no git credentials and CI holds no cluster credentials (ADR-0007), so secrets must either ride in git encrypted or be placed by hand. Encrypting them in git keeps the cluster rebuildable from git plus one key, with no extra service to run. The roots of trust (the age key, the OpenTofu state key, the Linode and Object Storage tokens, talosconfig and kubeconfig) never enter the cluster or CI. They live in the Owner's self-hosted **Vaultwarden**.
## Considered Options
- **External Secrets Operator with a store** (Bitwarden Secrets Manager, 1Password, OpenBao). Rejected. It adds a third-party dependency or a service to run, and the cluster still needs its own credential for the store, so the bootstrap problem remains.
- **Sealed Secrets.** Rejected. The ciphertext still sits in git, and the controller's private key is generated in the cluster and has to be backed up, which makes disaster recovery worse than SOPS.
- **Secrets created by hand with `kubectl` over the tailnet.** Rejected. Nothing records what should exist, drift goes unnoticed, and rebuilding the cluster needs a manual step for each secret.
## Consequences
- **The ciphertext is public forever.** Key names and encrypted values can be read by anyone, along with every past version in history. If the age key is ever exposed, **every value it protected is rotated**. Replacing the key alone isn't enough.
- **Layout:** `.sops.yaml` encrypts only `data`/`stringData` in `deploy/**/*.sops.yaml`. The Flux Kustomizations that carry secrets set `decryption.provider: sops`.
- **The age key:** there is one, for prod, generated offline. Its durable copy is in Vaultwarden. During the Flux install runbook, the Owner creates `flux-system/sops-age` from it by hand. OpenTofu never sees it, so it stays out of Tofu state.
- **Secrets reach the app as files, never env vars.** They're mounted read-only under pydantic-settings' `secrets_dir`. Env vars leak through `/proc`, into child processes such as break-glass `psql`, and into debug output. Non-secret config such as the DB CA certificate is committed in plaintext as a ConfigMap.
- **DB credentials are split** (ADR-0004):
- `hapi-db-app` is mounted only into the app Deployment, which also hosts the admin CLI.
- `hapi-db-migrator` is mounted only into the migrate Job and a runbook admin pod used for `hapi db bootstrap` and `hapi db breakglass`.
- No workload ServiceAccount can read Secrets.
- **Git is the source of truth for DB passwords.** The Owner generates them and commits them encrypted. The idempotent `hapi db bootstrap` reads them from its mounted files and runs `CREATE`/`ALTER ROLE … PASSWORD`. The `akmadmin` password is still pasted in at run time and never stored in git or the cluster.
- **Each integration gets its own narrow credential:**
- The CCM gets a dedicated Linode token with only the scopes it needs. OpenTofu creates it, never reusing the Owner's Tofu token.
- Later credentials (DNS-01, ntfy, the backup target) are each a narrow token delivered through SOPS.
- **CI secrets** (the write deploy key, the Renovate bot token, a publish-only ntfy token for the CI topic) are repo-level Gitea Actions secrets. CI never decrypts SOPS.
- **Guardrails against plaintext:**
- gitleaks runs in pre-commit and as a required CI check.
- A second CI check fails on any `kind: Secret` manifest without SOPS metadata, or any `*.sops.yaml` that isn't encrypted.
- A plaintext secret that reaches `main` is rotated. Rewriting history doesn't help, because clones and caches already have it.
- **Rotation is manual and event-driven**, with no schedule. It happens on suspicion of exposure, when the age key is exposed, or when who has access changes.
- **For a DB password:** merge the new SOPS value, wait for Flux, run `hapi db bootstrap` (which runs `ALTER ROLE`), then `kubectl rollout restart`.
- **The cost:** new connections fail for a few seconds between the last two steps, which is accepted. There's no Reloader controller.
- **Owner roots:** kubeconfig and talosconfig sit on local disk only while in use. Vaultwarden is cloud-hosted with its own backups. An additional offline copy (paper or encrypted USB, kept away from home) holds the age key, the OpenTofu state passphrase and the Linode account recovery codes, and is updated whenever one of them rotates.
+28
View File
@@ -0,0 +1,28 @@
# Probes on an internal port, authenticated three-state health, self-hosted Victoria stack
ADR-0002 allows no anonymous public endpoints, but kubelet probes can't carry a Token. So hAPI listens on two ports. **`:8000`** serves the API and is the only port the Gateway routes. **`:8081`** is internal: it is never routed, and a NetworkPolicy limits it to kubelet and the metrics scraper. It serves `/livez`, `/readyz` and `/metrics` without auth, from the **same process and event loop** as the API, so a wedged loop fails liveness. External health is **`GET /v1/health`** on the public API. It needs the `health` Scope, and it reports `ok`, `degraded` or `down` using only check names and `ok`/`fail`. Uptime Kuma, a Bot on its own public VM, polls it. Logs and metrics go to **VictoriaLogs and VictoriaMetrics**, self-hosted in the cluster. The Owner reads them through Grafana over a port-forward on the management tailnet. We chose this stack over Prometheus + Loki because it fits beside hAPI on two 4 GB workers, and over a SaaS because logs carry Principal ids and the breakglass audit trail (ADR-0004), which shouldn't leave the cluster.
## Considered Options
- **Probes on the public port, unauthenticated.** Rejected: it breaks ADR-0002's "no anonymous endpoints" rule. A probe path the Gateway happens not to route is also easier to expose by mistake than a port it never routes.
- **Readiness that checks the database.** Rejected: one blip of the managed database would mark every pod unready at once, and the NodeBalancer would serve nothing. A 503 with an RFC 9457 body is more honest. Database health goes into `/v1/health` and metrics instead.
- **Separate health endpoints per concern** (e.g. one for the HA bridge). Rejected in favour of one endpoint with critical and non-critical checks, which gives Kuma a "degraded" signal without a second route.
- **Prometheus + Loki (+ Alloy).** The industry standard. Rejected for v1 on footprint: it needs about 1.5–2 GB before tuning, on workers that also run hAPI, Flux and Cilium.
- **Grafana Cloud or another SaaS.** Rejected: it would put a vendor in the data path for Principal ids and audit events.
- **Built-in vmui / VictoriaLogs UI only.** Workable, but provisioned dashboards earn Grafana its place.
- **Write-once off-cluster storage for breakglass audit events.** Deferred: the Owner controls the cluster and is the one who runs breakglass. In v1, tamper-evidence comes from a Household ntfy alert on every breakglass start.
## Consequences
- **`/livez`** returns a constant. **`/readyz`** passes once startup is done (config loaded, pools created). On SIGTERM, `/readyz` fails first and the pod drains for about 5 s before it shuts down. Readiness also gates rollouts (ADR-0007): an image that never becomes Ready stalls the rollout.
- **`/v1/health`** checks `db` (a `SELECT 1` through the app pool) and `schema` (at the expected Alembic head). These are critical: if either fails, the status is `down` with HTTP 503. It also checks `ha_bridge` (no poll for 5 min, see ADR-0006) and `job_backlog` (oldest pending Job too old). These are non-critical: if one fails, the status is `degraded` with HTTP 200. Bodies carry no error text, hostnames, versions or latencies. Kuma points two monitors at it: *up* (HTTP status) and *healthy* (a JSON query asserting `status == "ok"`).
- **Collection:** vmagent scrapes the app, kubelet/cAdvisor, kube-state-metrics, node-exporter, Flux and Cilium. A Vector DaemonSet takes pod stdout and Talos service logs (`machine.logging`, JSON over TCP). An event exporter ships Kubernetes Events as logs. Everything lives in a `monitoring` namespace on Block Storage PVs and arrives as Flux `HelmRelease`s.
- **App metrics** come from `prometheus-client`: requests by route template, method and status; latency; DB pool usage; Job depth, age and failures; seconds since HA's last poll; auth failures by reason. **Labels never carry `principal_id` or Personal data.** Per-Principal detail stays in logs.
- **Retention:** logs and metrics are kept for 30 days, breakglass audit events for 1 year.
- **Locked down:** Grafana requires login, with analytics, update checks and Gravatar off. Datasource plugins are pinned in the image. Outbound traffic from `monitoring` is denied by default, except vmalert → ntfy and the Watchdog → Kuma push.
- **Every failure has one alerting owner.**
- Kuma: reachability and degraded status.
- Flux notification-controller: failed reconciles, migrate Jobs and rollouts.
- vmalert: PVs filling, crash loops, the DB pool near ADR-0004's budget, Jobs piling up or failing, a node NotReady.
- Watchdog: an always-firing alert pushes to a Kuma push monitor, so the monitoring stack dying is caught from outside. The push URL is a SOPS secret (ADR-0008).
- **Never public:** `:8081`, Grafana, VictoriaMetrics and VictoriaLogs. They're reachable only by `kubectl port-forward` over the management tailnet.
@@ -0,0 +1,37 @@
# Envoy Gateway at the edge, DNS-01 through a delegated challenge zone, CAA pinned to our account
Public traffic reaches hAPI on one hostname, **`hapi.bobbypalko.com`**, over IPv4 only. OpenTofu reserves the IPv4 address. A Linode NodeBalancer created by the CCM listens on that address in **TCP mode** and sends **Proxy Protocol v2** to an **Envoy Gateway**. Envoy Gateway terminates TLS and forwards plain HTTP to hAPI `:8000`; Cilium's WireGuard encrypts traffic between nodes. There's no CDN (ADR-0002), so the Gateway is the only shield and enforces the edge limits. Envoy Gateway was chosen over Cilium's built-in Gateway because Cilium's Gateway has none of the limits we need as typed policy. Certificates come from **cert-manager** and Let's Encrypt over DNS-01, because `:80` is closed. The DNS-01 credential can only edit a separate, delegated **`acme.bobbypalko.com`** zone, not `bobbypalko.com` itself. A **CAA record pinned to our ACME account** means that even a leaked DNS token can't get a certificate for us.
## Considered Options
- **Cilium's built-in Gateway** (it's already the CNI, ADR-0003). It has one component fewer, but as of v1.20 it offers only global switches (Proxy Protocol, ALPN, trusted XFF hops). It has no rate limiting, connection limits, body or header limits, client timeouts or minimum-TLS policy. The only workaround is hand-written CiliumEnvoyConfig, which doesn't cleanly patch the listeners Cilium generates. Rejected.
- **Traefik with built-in ACME.** It renews certificates just as cert-manager does, but Traefik OSS keeps ACME state in a local file, so it can't run more than one replica. It would also still need the same DNS credential. Rejected.
- **A DNS-01 token on the whole `bobbypalko.com` zone** (an IAM restricted user with `domain_admin` on it). Simpler, but a leaked token could repoint `git.` or any other record. Rejected under ADR-0008's narrow-token rule.
- **Moving DNS to Cloudflare** for per-zone tokens. Rejected: it moves the whole zone to buy a token scope we can get with a delegated subzone.
- **Self-hosted acme-dns.** It has the narrowest credential, but it means running a public DNS server. Kept as the fallback if the delegated-zone setup doesn't hold up (see Consequences).
- **TLS terminated at the NodeBalancer (HTTPS mode).** Rejected: cert-manager can't rotate a certificate uploaded to Linode, and traffic from the NodeBalancer to the nodes would cross the unencrypted VPC in plaintext.
- **A backup ACME CA (GTS, ZeroSSL).** Deferred: each needs EAB credentials, which is one more secret to manage, plus its own CAA entry.
## Consequences
- **Tofu owns the stable parts:** the reserved IPv4, the NodeBalancer's Cloud Firewall (inbound TCP 443 only), the `A` record, the `_acme-challenge.hapi` CNAME, the `acme.` delegation and the CAA record. The Gateway's Service references the IP and the firewall through the CCM's `reserved-ipv4` and `firewall-id` annotations. The CCM creates and recreates the NodeBalancer without changing the address. There's no external-dns.
- **No `AAAA`.** The NodeBalancer's IPv6 frontend address can't be reserved, so recreating the NodeBalancer would silently break the record.
- **NodeBalancer:** `default-protocol: tcp`, `default-proxy-protocol: v2`, `throttle: 20` (new connections per second per client IP; the Household shares one CGNAT IP), and VPC backends.
- **Envoy Gateway:** 2 Envoy replicas spread across both workers, with a PDB and memory requests tuned down from the chart's 512Mi. The Gateway accepts Proxy Protocol only.
- `ClientTrafficPolicy`: TLS 1.3 only; ALPN h2 and http/1.1 (no HTTP/3); headers up to 16 KiB; about 50 connections per IP; request timeout 30 s, idle 60 s; client IP taken from Proxy Protocol.
- `BackendTrafficPolicy`: per-IP local rate limit of about 20 req/s, burst 100 (per replica, no Redis), and bodies up to 1 MiB (413). The app caps `transactions/ingest` batches on its own.
- HSTS is set at the edge. There's no per-Principal rate limiting (ADR-0005).
- **uvicorn trusts `X-Forwarded-For` only from the Gateway's pod range.** That way, logs and limits see the real client.
- **Layout:** one `Gateway` in a `gateway` namespace with a single HTTPS listener for `hapi.bobbypalko.com` and `allowedRoutes` limited to the `hapi` namespace. One `HTTPRoute` sends traffic to `:8000`; `:8081` is never routed (ADR-0009). Any other SNI or Host gets no certificate and no route.
- **Certificates:**
- cert-manager uses an ACME ClusterIssuer for Let's Encrypt on the default profile, plus a staging issuer for bring-up. `renewBefore` stays at its default, which is a proportion of the lifetime, so lifetimes can shrink (64 days from Feb 2027, 45 from 2028) without changes on our side. The DNS-01 solver is `linode/cert-manager-webhook-linode` with `cnameStrategy: Follow`.
- The webhook's token belongs to a **restricted Linode user** with `domain_admin` on `acme.bobbypalko.com` only. It's delivered through SOPS (ADR-0008).
- **CAA on `hapi.bobbypalko.com`** (not the apex, so other hostnames are unaffected): `0 issue "letsencrypt.org; validationmethods=dns-01; accounturi=<our account>"`.
- **The ACME account key is generated offline and committed SOPS-encrypted.** A cluster rebuilt from code (ADR-0003) reuses the same account. Otherwise the CAA pin would block our own issuance.
- **Verify during the build:**
1. That a restricted user's token really is capped by the user's grants: it must fail to edit `bobbypalko.com`.
2. That Linode serves the delegated `acme.` subzone.
3. That the CCM copies Gateway `spec.infrastructure` / `EnvoyProxy` Service annotations onto the NodeBalancer.
If either of the first two fails, switch to acme-dns before going live.
- **Delivery (ADR-0007):** cert-manager with the webhook, and Envoy Gateway with the **Standard-channel** Gateway API CRDs, arrive as Flux `HelmRelease`s in `deploy/infrastructure`. Cilium runs with `gatewayAPI.enabled=false`, so two controllers never compete for the CRDs. Renovate opens PRs for these charts, but they aren't auto-merged.
- **Observability (ADR-0009):** Envoy writes JSON access logs to stdout (client IP, status, bytes, duration, rate-limit verdict), without `Authorization` or query strings. Vector ships them to VictoriaLogs with the standard 30-day retention. Kuma's TLS-expiry notification on the `/v1/health` monitor alerts at 14 days. A vmalert rule on `certmanager_certificate_expiration_timestamp_seconds` is the in-cluster backstop.
-302
View File
@@ -1,302 +0,0 @@
# Private connectivity between the home network and a Linode cluster
Research for Gitea issue #46 (part of map #44). Researched 2026-11-23.
## Question
What are the options for a private, authenticated link between the Owner's home
network (Home Assistant, LAN Bots) and a self-managed Kubernetes cluster on
Linode? Compare Tailscale (incl. the Kubernetes operator / subnet routers),
Headscale, plain WireGuard site-to-site, and Linode VPC features: setup,
security model, failure modes, how in-cluster Services are exposed over the
link, and cost.
## TL;DR
- **Linode VPC can't do this.** It is a single-data-center private network
with no VPN/on-prem attachment, no peering, and **no encryption**. Akamai
has no managed site-to-site VPN product. VPC only matters for
traffic inside the cluster. [VPC][akamai-vpc]
- **Tailscale + the Kubernetes operator is the lowest-effort fit.** You can
expose a Bot-facing Service to the tailnet with one annotation. Home Assistant
joins via the community add-on, which can also act as a subnet router for
other LAN Bots. Grants are deny-by-default, so you can limit LAN Bots
to the Bot-facing Service only. The free Personal plan covers this load.
- **Surprise: Tailnet Lock does not work with the operator.** Tailnet Lock is
Tailscale's defense against a compromised coordination server, and the
operator can't sign the proxy nodes it creates. The feature request is
still open. So with the operator you have to trust Tailscale's control plane.
[#13273][ts-13273]
- **Headscale removes that third-party trust, but it isn't ready yet for the
operator path.** Operator compatibility (OAuth clients on a v2 API) was
merged in June 2026 for v0.30.0, but the latest release is still v0.29.7. You'd
also have to host and secure the control server yourself.
[#3334][hs-3334] [releases][hs-releases]
- **Plain WireGuard has the smallest and most auditable surface**: a silent
UDP port and static keys. But you do all key management, routing into the
cluster, and HA by hand.
**Tentative recommendation** (a decision for the Owner, not made here):
Tailscale with the operator, an L3 `tailscale` Service for the Bot-facing
listener, tagged nodes, and a tight grants policy with `tests`. Keep the
Bot-facing listener off the public Ingress entirely. If the Owner wants
no third-party control plane, choose plain WireGuard (a single gateway now)
or wait for Headscale v0.30.0.
## Options compared
| | Tailscale (SaaS) + operator | Headscale + Tailscale clients | Plain WireGuard | Linode VPC |
|---|---|---|---|---|
| Reaches home LAN? | Yes | Yes | Yes | **No** |
| Encryption | WireGuard, keys never leave devices | Same | WireGuard | **None** (isolation only) |
| Control plane | Tailscale-hosted | Self-hosted | None (static config) | n/a |
| Inbound ports on cluster | None required (DERP relay fallback) | Control server must be reachable, and its DERP if embedded | One UDP port | n/a |
| Expose k8s Service | Annotation / `loadBalancerClass: tailscale` / Ingress class | Same operator, **only once v0.30.0 ships** | DIY routing | n/a |
| Access control | Grants/ACLs, deny-by-default, policy tests | ACLs/Grants supported | Cryptokey routing + your firewall rules | Cloud Firewall |
| Cost | $0 (Personal: 6 users, 50 tagged resources) | $0 + hosting a server | $0 | $0 |
## Linode VPC and Cloud Firewall
- VPCs connect Linodes **within one data center**. They can't span data
centers, and VPC peering isn't supported. [VPC][akamai-vpc]
- "Traffic is isolated but not encrypted." There's no IPv6 on VPC interfaces.
VPCs have no extra charge. [VPC][akamai-vpc]
- The docs mention no VPN or on-prem attachment. I found no official Akamai
site-to-site VPN product. The only guidance for on-prem links is community
posts about running your own IPsec/strongSwan gateway on a Linode
([community 21930][linode-c-21930]; low trust, used only to show that
nothing first-party exists).
- Cloud Firewall is stateful and free. It covers Linodes and NodeBalancers and
allows max 25 rules per firewall. Rules apply to public and private traffic.
For NodeBalancers, rules cover only the public IP, so backends need their own
firewall. [Cloud Firewall][akamai-fw]
**Verdict:** VPC is useful for node-to-node traffic inside the cluster. It
plays no part in the home link. Cloud Firewall is complementary: with WireGuard,
it limits the UDP port to the home public IP (if that IP is stable).
## Tailscale (SaaS) with the Kubernetes operator
### Setup
- The operator is available on all plans. It covers ingress (tailnet → cluster
workloads), egress (cluster → tailnet devices), API-server proxy, and
subnet routers/exit nodes via a `Connector` resource.
[operator][ts-operator]
- Prerequisites: in the policy file, set `tagOwners` with
`"tag:k8s-operator": ["autogroup:admin"]` and
`"tag:k8s": ["tag:k8s-operator"]`. Create an OAuth client with read/write on
Services, Devices Core, and Auth Keys, tagged `tag:k8s-operator`. The operator
stores the credentials in the `operator-oauth` secret in the `tailscale`
namespace. [quickstart][ts-quickstart]
- If you want non-default proxy tags (e.g. `tag:hapi-bot`), `tag:k8s-operator`
must own them, and the OAuth client must be allowed to use them. There's
a known startup failure with multiple `defaultTags`
([issue #15732][ts-15732]).
### Exposing in-cluster Services over the link
From [cluster ingress][ts-ingress]:
- **L3 (TCP/UDP):** annotate the Service with `tailscale.com/expose: "true"`, *or*
set `type: LoadBalancer` + `loadBalancerClass: tailscale`. A proxy Pod DNATs
its tailnet IP to the Service's ClusterIP.
- **L7 (HTTP/S):** use `Ingress` with `ingressClassName: tailscale`. You get a
MagicDNS name and a Let's Encrypt cert through Tailscale Serve.
- These are **not public** by default. Public needs Funnel, which you should
avoid for the Bot side.
- HA: a `ProxyGroup` (`tailscale.com/proxy-group` annotation) runs multiple
active proxies. Tailscale recommends it for production.
So a Bot-facing hAPI listener can be its own Service, reachable *only* via
the tailnet. Persons hit the public Ingress, which never routes to it.
### Home side
- **Home Assistant:** the community add-on supports `advertise_routes`
(subnet router), `accept_routes`, `advertise_tags`, `login_server` (custom
control server, e.g. Headscale), and `userspace_networking`.
[addon-tailscale docs][ha-addon]
- **Other LAN Bots** that can't run Tailscale go through a subnet router (the
HA add-on, or another always-on box). Devices behind a subnet router don't
count toward the device limit. SNAT is on by default, so cluster-side traffic
appears to come from the router, which loses per-Bot source IPs unless you set
`--snat-subnet-routes=false` (Linux only, needs return routes for
`100.64.0.0/10`). Route approval is separate from access: you need grants
too. [subnet routers][ts-subnets]
- Tailscale prefers installing the client directly on each device over
subnet routing. [subnet routers][ts-subnets]
### Security model
- Data plane: WireGuard. Private keys never leave the device. DERP relays
forward already-encrypted traffic they can't decrypt. Connections are usually
direct, with peer relays and then DERP as fallback. [DERP][ts-derp]
- Policy: deny-by-default grants (`src`/`dst`/`ip`). A `tests` section
rejects policy updates that break assertions. Example intent: `src:
["tag:home-bot"]`, `dst: ["tag:hapi-bot:443"]`. [policy syntax][ts-policy]
- **Trust in the control plane:** Tailscale's coordination server distributes
node keys, so a compromised control plane could inject nodes. Tailnet Lock
closes that gap: nodes must be signed by trusted keys held on your devices.
It's available on Personal. [Tailnet Lock][ts-lock]
- **But the operator can't add its proxies to a locked tailnet** without manual
signing of each proxy node key. Issue #13273 and PR #14404 are still open as
of this research. [#13273][ts-13273] This trade-off is the main thing to
weigh: operator convenience vs. control-plane-compromise resistance. One
workaround: skip the operator and run a single `tailscaled` gateway
(e.g. a Deployment with persisted state, or a node-level install) whose key
is signed once, routing to the Bot-facing Service.
### Failure modes
- Tailscale control plane outage: existing connections generally keep working,
but new nodes/key changes stall. (General property of the design. I didn't
find a precise first-party statement for this, so check before relying on it.)
- Proxy Pod restart blips the link unless you use `ProxyGroup` HA. [ingress][ts-ingress]
- A subnet router going offline drops its routes, and there's no fallback to a
less specific route. Run two routers for HA, without `--accept-routes` on
them. [subnet routers][ts-subnets]
- Let's Encrypt rate limits can bite L7 Ingress on frequent redeploys.
[ingress][ts-ingress]
### Cost
Personal plan: $0, non-commercial, up to 6 users, unlimited user devices,
**50 tagged resources** (then $1/mo each), 3 ACL groups. Operator proxies and
tagged gateways count as tagged resources. That's ample here. [pricing][ts-pricing]
## Headscale
- An open-source, self-hosted implementation of the Tailscale control server.
Its scope is deliberately narrow: **a single tailnet**, for self-hosters and
hobbyists. [headscale][hs-home]
- Supported: ACLs, Grants, Tailscale SSH, auto approvers, subnet routers, exit
nodes, tags, OIDC (but OIDC groups can't be used in ACLs), embedded DERP, and
Taildrop. Funnel/Serve and Tailnet Lock aren't listed as supported.
[features][hs-features]
- **Operator compatibility:** the operator chart has a `loginServer` value for a
non-Tailscale control plane ([values.yaml][ts-values]). Headscale PR #3334
("add OAuth clients and scopes to the v2 API") was merged on 2026-06-26 and
closed issue #1202 ("OAuth Provider + Tailscale Kubernetes operator
compatibility") under milestone v0.30.0. [#3334][hs-3334] [#1202][hs-1202]
**The latest release is v0.29.7, so it hasn't shipped yet.** [releases][hs-releases]
- The HA add-on supports `login_server`, so the home side works today.
[ha-addon][ha-addon]
- **Security trade-off:** you remove Tailscale Inc. from the trust base, but the
control server becomes your crown jewel. It must be reachable by home and
cluster nodes, so it's internet-exposed somewhere. Hosting it *inside* the
cluster it protects creates a bootstrap/circular dependency. You also own
its patching, backups, and DERP.
- **Cost:** software is free. Hosting is a small Linode or a cluster
workload, plus operations time.
## Plain WireGuard site-to-site
### Security model
- Cryptokey routing: each peer is a public key with a list of allowed IPs. Those
act as the routing table for outbound traffic and the ACL for inbound, so
firewall rules on source IP + interface are trustworthy. It uses Noise,
Curve25519, ChaCha20-Poly1305, BLAKE2, and HKDF, and the codebase is
small enough to audit. [wireguard.com][wg-home]
- The server "does not even *respond at all*" to unauthenticated packets. It's
silent to scanners, with a cookie mechanism under load. Handshakes occur
every few minutes for rotating session keys. [protocol][wg-protocol]
- Key distribution is out of scope: you exchange public keys out of band,
like SSH keys. [wireguard.com][wg-home]
### Setup and exposing Services
- Home side: a WireGuard peer on an always-on LAN box (or router). It
initiates toward the cluster's public UDP endpoint, with
`PersistentKeepalive = 25` to hold the NAT mapping (off by default).
[quickstart][wg-quick] The cluster doesn't need to know the home IP, because
WireGuard roams to the last authenticated endpoint. [wireguard.com][wg-home]
- Cluster side: you do all of it yourself. Options:
- A WireGuard interface on one node (host-level), routing the tunnel subnet
to the Bot-facing Service's ClusterIP or a dedicated internal IP.
- A gateway Pod with `hostNetwork` or a UDP NodePort/LoadBalancer.
Either way you handle iptables/nftables, return routes, and which node holds
the endpoint.
- Lock the UDP port down with Cloud Firewall (to the home public IP if it's
stable). [Cloud Firewall][akamai-fw]
### Failure modes
- A single gateway node is a single point of failure, and HA needs your own
failover (e.g. floating IP + keepalived). There's no built-in relay, so a home
network with broken outbound UDP just fails. Losing a key means editing
configs by hand on both sides.
### Cost
$0 (in-kernel software). You pay only in operator time.
## How this fits hAPI
- **Separation of Principals by network:** Persons → public Ingress. Bots →
a distinct Bot-facing Service exposed only on the private link. Defense in
depth: hAPI should still authenticate Bots at the application layer (the link
is a network control, not Principal authentication).
- With Tailscale/Headscale, tags give a stable identity per home device or
subnet router. With SNAT on, hAPI sees only the router's address, so per-Bot
identity must come from app-level credentials anyway.
## Open questions for the Owner
1. Is trusting Tailscale's hosted control plane acceptable, given Tailnet
Lock is unavailable with the operator? If not: plain WireGuard now, or
Headscale once v0.30.0 ships.
2. Can each LAN Bot run a Tailscale client, or do most need a subnet router
(which loses per-device source identity unless SNAT is disabled)?
3. Is the home public IP stable (relevant to firewalling a WireGuard port)?
## Sources
- [akamai-vpc]: https://techdocs.akamai.com/cloud-computing/docs/vpc
- [akamai-fw]: https://techdocs.akamai.com/cloud-computing/docs/cloud-firewall
- [linode-c-21930]: https://www.linode.com/community/questions/21930/site-to-site-vpn (community, low trust)
- [ts-operator]: https://tailscale.com/kb/1236/kubernetes-operator
- [ts-quickstart]: https://tailscale.com/docs/kubernetes-operator/quickstart
- [ts-ingress]: https://tailscale.com/kb/1439/kubernetes-operator-cluster-ingress
- [ts-15732]: https://github.com/tailscale/tailscale/issues/15732
- [ts-values]: https://github.com/tailscale/tailscale/blob/main/cmd/k8s-operator/deploy/chart/values.yaml
- [ts-subnets]: https://tailscale.com/kb/1019/subnets
- [ts-derp]: https://tailscale.com/kb/1232/derp-servers
- [ts-policy]: https://tailscale.com/kb/1337/policy-syntax
- [ts-lock]: https://tailscale.com/kb/1226/tailnet-lock
- [ts-13273]: https://github.com/tailscale/tailscale/issues/13273
- [ts-pricing]: https://tailscale.com/pricing
- [ha-addon]: https://github.com/hassio-addons/addon-tailscale/blob/main/tailscale/DOCS.md
- [hs-home]: https://headscale.net/stable/
- [hs-features]: https://headscale.net/stable/about/features/
- [hs-3334]: https://github.com/juanfont/headscale/pull/3334
- [hs-1202]: https://github.com/juanfont/headscale/issues/1202
- [hs-releases]: https://github.com/juanfont/headscale/releases
- [wg-home]: https://www.wireguard.com/
- [wg-protocol]: https://www.wireguard.com/protocol/
- [wg-quick]: https://www.wireguard.com/quickstart/
[akamai-vpc]: https://techdocs.akamai.com/cloud-computing/docs/vpc
[akamai-fw]: https://techdocs.akamai.com/cloud-computing/docs/cloud-firewall
[linode-c-21930]: https://www.linode.com/community/questions/21930/site-to-site-vpn
[ts-operator]: https://tailscale.com/kb/1236/kubernetes-operator
[ts-quickstart]: https://tailscale.com/docs/kubernetes-operator/quickstart
[ts-ingress]: https://tailscale.com/kb/1439/kubernetes-operator-cluster-ingress
[ts-15732]: https://github.com/tailscale/tailscale/issues/15732
[ts-values]: https://github.com/tailscale/tailscale/blob/main/cmd/k8s-operator/deploy/chart/values.yaml
[ts-subnets]: https://tailscale.com/kb/1019/subnets
[ts-derp]: https://tailscale.com/kb/1232/derp-servers
[ts-policy]: https://tailscale.com/kb/1337/policy-syntax
[ts-lock]: https://tailscale.com/kb/1226/tailnet-lock
[ts-13273]: https://github.com/tailscale/tailscale/issues/13273
[ts-pricing]: https://tailscale.com/pricing
[ha-addon]: https://github.com/hassio-addons/addon-tailscale/blob/main/tailscale/DOCS.md
[hs-home]: https://headscale.net/stable/
[hs-features]: https://headscale.net/stable/about/features/
[hs-3334]: https://github.com/juanfont/headscale/pull/3334
[hs-1202]: https://github.com/juanfont/headscale/issues/1202
[hs-releases]: https://github.com/juanfont/headscale/releases
[wg-home]: https://www.wireguard.com/
[wg-protocol]: https://www.wireguard.com/protocol/
[wg-quick]: https://www.wireguard.com/quickstart/
+254
View File
@@ -0,0 +1,254 @@
#!/usr/bin/env python3
"""SimpleFIN coverage probe for "Check whether SimpleFIN covers Capital One and Fulton with purchase dates".
Run by the Owner on their own machine, stdlib only:
python3 -I probe.py claim # exchange a Setup Token for an Access URL (one time)
python3 -I probe.py run # pull accounts and print a redacted summary
python3 -I probe.py recheck # a day or more later: did ids survive, did pending ids post?
Secrets are read with getpass and are never printed or written. Output contains no
amounts, descriptions, payees, or raw ids: ids are HMAC-hashed with a per-machine salt.
A redacted snapshot (hashed ids + dates) is kept in ~/.local/state/hapi-simplefin-probe/
(mode 0600) so `recheck` can compare. Delete that directory when the ticket closes.
Each `run` makes 4 requests and `recheck` makes 2; SimpleFIN allows ~24 per day.
"""
from __future__ import annotations
import base64
import getpass
import hashlib
import hmac
import json
import os
import re
import secrets
import statistics
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter
from datetime import UTC, datetime
from pathlib import Path
STATE = Path.home() / ".local/state/hapi-simplefin-probe"
DAY = 86400
# Cloudflare in front of SimpleFIN rejects Python-urllib's default UA (error 1010).
UA = "hapi-simplefin-probe/1"
def die(msg: str) -> None:
print(f"error: {msg}", file=sys.stderr)
sys.exit(1)
def salt() -> bytes:
STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
p = STATE / "salt"
if not p.exists():
p.write_bytes(secrets.token_bytes(32))
p.chmod(0o600)
return p.read_bytes()
def h(value: str) -> str:
return hmac.new(salt(), value.encode(), hashlib.sha256).hexdigest()[:16]
def id_shape(value: str) -> str:
"""Describe an id's shape without revealing it, e.g. 'TRN-<hex32>' or '<uuid>'."""
if re.fullmatch(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", value, re.I):
return "<uuid>"
m = re.fullmatch(r"([A-Za-z]+[-_])(.*)", value)
prefix, rest = (m.group(1), m.group(2)) if m else ("", value)
if re.fullmatch(r"[0-9a-fA-F]+", rest):
kind = "hex"
elif rest.isdigit():
kind = "digits"
else:
kind = "mixed"
return f"{prefix}<{kind}{len(rest)}>"
def day(ts: int | None) -> str:
return datetime.fromtimestamp(ts, UTC).date().isoformat() if ts else "-"
def access_url() -> str:
url = os.environ.get("SIMPLEFIN_ACCESS_URL") or getpass.getpass("Access URL (hidden): ")
if not url.startswith("https://"):
die("Access URL must start with https://")
return url.strip()
def get_accounts(url: str, **params: str) -> dict:
u = urllib.parse.urlsplit(url)
if not (u.username and u.password):
die("Access URL has no embedded credentials")
netloc = u.hostname + (f":{u.port}" if u.port else "")
base = urllib.parse.urlunsplit((u.scheme, netloc, u.path.rstrip("/") + "/accounts", "", ""))
full = base + ("?" + urllib.parse.urlencode(params) if params else "")
cred = base64.b64encode(f"{urllib.parse.unquote(u.username)}:{urllib.parse.unquote(u.password)}".encode()).decode()
req = urllib.request.Request(full, headers={"Authorization": f"Basic {cred}", "User-Agent": UA})
try:
with urllib.request.urlopen(req, timeout=120) as r:
return json.load(r)
except urllib.error.HTTPError as e:
die(f"HTTP {e.code} from /accounts (params {sorted(params)}): {e.read()[:200].decode(errors='replace')}")
return {}
def org_of(acct: dict, conns: dict) -> str:
org = acct.get("org") or conns.get(acct.get("conn_id"), {})
return org.get("name") or org.get("domain") or "?"
def errors_of(resp: dict) -> list[str]:
errs = list(resp.get("errors") or [])
for e in resp.get("errlist") or []:
errs.append(e.get("msg") or e.get("code") or str(e))
return errs
def summarize(label: str, resp: dict) -> dict[str, dict]:
conns = {c.get("conn_id"): c for c in resp.get("connections") or []}
out: dict[str, dict] = {}
print(f"\n== {label} ==")
for err in errors_of(resp):
print(f" server message: {err}")
for a in resp.get("accounts", []):
txns = a.get("transactions") or []
posted = [t for t in txns if t.get("posted")]
with_ta = [t for t in posted if t.get("transacted_at")]
lags = [(t["posted"] - t["transacted_at"]) / DAY for t in with_ta]
keys = Counter(k for t in txns for k in t)
shapes = Counter(id_shape(str(t.get("id", ""))) for t in txns)
ids = [str(t.get("id")) for t in txns]
key = h(f"{a.get('id')}")
out[key] = {
"org": org_of(a, conns),
"ids": {h(f"{a.get('id')}:{t.get('id')}"): {"posted": t.get("posted"), "ta": t.get("transacted_at"),
"pending": bool(t.get("pending"))} for t in txns},
}
print(f" account {key} org={org_of(a, conns)!r} name~{(a.get('name') or '')[:3]}… currency={a.get('currency')}")
print(f" transactions: {len(txns)} ({len(posted)} posted, {len(txns) - len(posted)} pending/unposted)")
print(f" posted range: {day(min((t['posted'] for t in posted), default=None))} .. {day(max((t['posted'] for t in posted), default=None))}")
print(f" transacted_at present: {len(with_ta)}/{len(posted)} posted"
+ (f"; posted − transacted_at days: min {min(lags):.1f}, median {statistics.median(lags):.1f}, max {max(lags):.1f}" if lags else ""))
print(f" fields seen: {dict(sorted(keys.items()))}")
print(f" id shapes: {dict(shapes)}; unique within account: {len(set(ids)) == len(ids)}")
if a.get("extra"):
print(f" account extra keys: {sorted(a['extra'])}")
return out
def save(name: str, data: dict) -> None:
p = STATE / f"{name}.json"
p.write_text(json.dumps({"at": int(time.time()), "accounts": data}))
p.chmod(0o600)
def compare(a: dict, b: dict, what: str) -> None:
print(f"\n== id stability: {what} ==")
for acct, snap in a.items():
other = b.get(acct)
if not other:
print(f" account {acct}: missing from second pull")
continue
overlap_window = [i for i, t in snap["ids"].items()
if t["posted"] and min(x["posted"] or 1e12 for x in other["ids"].values()) <= t["posted"]]
kept = sum(1 for i in overlap_window if i in other["ids"])
print(f" account {acct} ({snap['org']}): {kept}/{len(overlap_window)} posted ids reappear in the overlapping window")
def cmd_claim() -> None:
token = getpass.getpass("Setup Token (hidden): ").strip()
claim = base64.b64decode(token).decode()
if not claim.startswith("https://"):
die("Setup Token did not decode to an https URL")
req = urllib.request.Request(claim, method="POST", data=b"", headers={"Content-Length": "0", "User-Agent": UA})
try:
with urllib.request.urlopen(req, timeout=60) as r:
url = r.read().decode().strip()
except urllib.error.HTTPError as e:
die(f"HTTP {e.code} from claim: {e.read()[:200].decode(errors='replace')}")
print("\nAccess URL obtained (not printed). A Setup Token can be claimed only once,")
print("so save the Access URL to Vaultwarden now; `run` will prompt for it.")
if input("Show it once to copy into Vaultwarden? [y/N] ").lower() == "y":
print(url)
print("\n(Clear your terminal scrollback after saving it.)")
def cmd_run() -> None:
url = access_url()
now = int(time.time())
default = get_accounts(url)
summarize("default request (no params: posted only, server's default window)", default)
w90 = get_accounts(url, **{"start-date": str(now - 89 * DAY)})
s1 = summarize("start-date = 89 days ago", w90)
old = get_accounts(url, **{"start-date": str(now - 365 * DAY), "end-date": str(now - 276 * DAY)})
summarize("history probe: 365..276 days ago (is older history available?)", old)
pend = get_accounts(url, **{"start-date": str(now - 14 * DAY), "pending": "1"})
sp = summarize("last 14 days with pending=1", pend)
save("run", s1)
save("pending", sp)
print("\nSaved redacted snapshot for `recheck`. Run it again in ≥1 day.")
def cmd_recheck() -> None:
try:
first = json.loads((STATE / "run.json").read_text())["accounts"]
pend = json.loads((STATE / "pending.json").read_text())["accounts"]
except FileNotFoundError:
die("no snapshot: run `probe.py run` first")
url = access_url()
now = int(time.time())
again = summarize("start-date = 89 days ago (recheck)", get_accounts(url, **{"start-date": str(now - 89 * DAY)}))
compare(first, again, "posted ids across pulls")
later = summarize("last 14 days with pending=1 (recheck)", get_accounts(url, **{"start-date": str(now - 14 * DAY), "pending": "1"}))
print("\n== pending → posted ==")
for acct, snap in pend.items():
was_pending = [i for i, t in snap["ids"].items() if t["pending"] or not t["posted"]]
now_ids = later.get(acct, {}).get("ids", {})
same_id_posted = sum(1 for i in was_pending if i in now_ids and now_ids[i]["posted"])
still_pending = sum(1 for i in was_pending if i in now_ids and not now_ids[i]["posted"])
vanished = sum(1 for i in was_pending if i not in now_ids)
print(f" account {acct} ({snap['org']}): {len(was_pending)} were pending → "
f"{same_id_posted} posted under the same id, {still_pending} still pending, {vanished} id gone")
def cmd_history() -> None:
"""Pull 40-day slices back 200 days: is there a per-response cap, and how deep is history? (5 requests)"""
url = access_url()
now = int(time.time())
print("slice (days ago) per account: count, posted range")
for lo in range(0, 200, 40):
resp = get_accounts(url, **{"start-date": str(now - (lo + 40) * DAY), "end-date": str(now - lo * DAY)})
conns = {c.get("conn_id"): c for c in resp.get("connections") or []}
for a in resp.get("accounts", []):
ps = [t["posted"] for t in a.get("transactions") or [] if t.get("posted")]
print(f" {lo:3d}..{lo + 40:3d} {org_of(a, conns)!r}: {len(ps):3d} {day(min(ps, default=None))} .. {day(max(ps, default=None))}")
def cmd_spot() -> None:
"""LOCAL ONLY, do not paste: last 10 days, raw dates + amounts to compare with the bank's website. (1 request)"""
url = access_url()
now = int(time.time())
resp = get_accounts(url, **{"start-date": str(now - 10 * DAY)})
conns = {c.get("conn_id"): c for c in resp.get("connections") or []}
fmt = lambda ts: datetime.fromtimestamp(ts, UTC).strftime("%Y-%m-%d %H:%M:%SZ") if ts else "-" # noqa: E731
print("!! Contains amounts and descriptions. Compare with the bank site; do NOT paste this output.\n")
for a in resp.get("accounts", []):
print(f"{org_of(a, conns)} {(a.get('name') or '')[:3]}…")
print(f" {'posted':21} {'transacted_at':21} {'amount':>10} description")
for t in sorted(a.get("transactions") or [], key=lambda t: t.get("posted") or 0, reverse=True)[:15]:
print(f" {fmt(t.get('posted')):21} {fmt(t.get('transacted_at')):21} {t.get('amount', ''):>10} {(t.get('description') or '')[:30]}")
if __name__ == "__main__":
{"claim": cmd_claim, "run": cmd_run, "recheck": cmd_recheck, "history": cmd_history, "spot": cmd_spot}.get(
sys.argv[1] if len(sys.argv) > 1 else "", lambda: die("usage: probe.py claim|run|recheck|history|spot"))()