---
name: qube-sync-audit
description: Audits an app's QuBe Sync integration (QuickBooks Desktop through qubesync.com) against QuBe Sync's 53 integration rules (onboarding, API calls and runs, webhooks, questions, stored QuickBooks data, QuickBooks behaviour and going live) and reports each finding with its rule id, severity and file:line, critical first. Reads the code only: it never opens secrets, and changes nothing unless asked. Use when asked to audit, review or check a QuBe Sync integration, or before one goes live.
---

<!-- Generated by QuBe Sync from its integration rules: don't edit it here. The latest:
curl -o .claude/skills/qube-sync-audit/SKILL.md --create-dirs https://qubesync.com/skills/qube-sync-audit/SKILL.md -->

# Audit a QuBe Sync integration

QuBe Sync (qubesync.com) connects an app to its customers' QuickBooks Desktop. The app creates a
connection for each customer, queues QuickBooks requests or starts workflow runs through the v2 API,
and takes the answers as signed webhooks. This runbook checks an app's code against the 53 rules an
integration has to get right, and reports what it finds. Every rule is below, so you need nothing
else, and each links its page on docs.qubesync.com.

## Ground rules

- **Read only.** Change nothing, commit nothing, and run nothing that writes: no migrations, no
  installs, no calls to QuBe Sync's API. Step 4's check, against the app running on this machine, is
  the one exception. Once the report is in, fix only what the user asks you to.
- **Never touch secrets.** Don't open `.env` files, credentials, key files or a secret store, and
  never print a key, secret or token. Search for variable names (`QUBE_API_KEY`), never for values.
  A secret written into the code is a finding of `no-secrets-in-logs-or-browser`: give its
  `file:line`, and don't quote it.
- **Evidence, not guesses.** Every finding cites a rule id and a `path:line` from the repo's root.
  When the code doesn't settle a rule, the verdict is `can't tell`, with what would settle it.
- **The rules as written.** Judge each rule by its own Wrong and Right, not by your preferences, and
  leave style out of the report.

## 1. Find the integration

Search the whole repo (`rg -n`, say), leaving out dependencies and build output, for:

- **Configuration:** `QUBE_API_KEY`, `QUBE_WEBHOOK_SECRET`, `QUBE_WEBHOOK_URL`, `QUBE_URL`,
  `qubesync.com`.
- **The API client and its calls:** `/api/v2`, `/connections`, `workflow-runs`, `queued-requests`,
  `Idempotency-Key`, `links.onboarding`, `links.decisions`, basic auth.
- **The webhook endpoint:** `X-Qube-Signature` in any case, `HMAC`, `sha256`, the raw body
  (`raw_post`, `express.raw`, `get_data`, `request.body`), a route under `/webhooks`.
- **The job it enqueues, and the handlers:** `workflow_run.`, `connection.`, `name_index.`,
  `awaiting_input`, `notification`, `delivery_id`, `revision`, `reference`, `page_request_id`,
  `iteration_state`.
- **Stored QuickBooks ids:** `list_id`, `txn_id`, `ListID`, `TxnID`, `edit_sequence`, and the
  tables, migrations and unique indexes that hold them.

An app built from QuBe Sync's integration kit is on QuBe Sync's package for its stack: the
`qube_rails` engine (or its copy in `vendor/qube_rails/`), PyPI `qubesync`'s `qubesync.kit` with its
Django, Flask or FastAPI adapter, or npm `qubesync`'s `qubesync/kit` and `qubesync/express`. The
package holds the webhook endpoint, the job with its fixed map of operation slugs, onboarding, the
question routes and the tables of connections, runs and QuickBooks ids; judge that part as each
rule's Right says the package does it, at the version the dependency line names. The app's own code
is one configuration file (`config/initializers/qube_rails.rb`, `quickbooks_desktop/config.py`,
`quickbooks-desktop/config.js`), a `ConnectionEvents` class, a class for each way it starts a
workflow and, with Express, the store that keeps the package's tables. A setting the app hasn't
written raises `NotConfigured` until it does, and one that still would is a finding of the rule it
leaves undone.

Write the map down before you judge anything: the configuration, the client, the connect action,
each place a run starts or a request is queued, the webhook endpoint, the job, the handlers, and
each table of QuickBooks ids with its columns and unique indexes. If the repo has no QuBe Sync code,
say so and stop.

## 2. Decide what applies

Each rule says when it applies. A rule that doesn't is `n/a`, with the reason: an app that only
starts workflows takes no request webhooks, so `dedupe-request-webhooks` is `n/a`. Code that's
missing doesn't make a rule `n/a`: when the rule applies and the code isn't there, it's a
`violation`.

## 3. Check each rule

For each rule that applies, read the code its Check names, compare it with Wrong and Right, and give
one verdict:

- `ok`: the code does what Right says. Cite where.
- `violation`: cite the line, say in a sentence what's wrong, and give the fix.
- `can't tell`: the answer is outside the repo, or in code you couldn't find. Say what would settle
  it.

The severity is the rule's: `critical` (data loss, a security hole, another customer's data),
`major` (wrong behaviour a user sees) or `minor`. Give one finding per place: a rule broken in three
handlers is three rows.

## 4. Check the endpoint live, when the app runs locally

QuBe Sync's CLI sends the app's own webhook endpoint signed test deliveries, and grades its answers.
It needs the CLI release that has `qube check webhooks`, a signed-in CLI (`qube login`: the CLI
fetches the app's webhook secret itself and never prints it), and the app running on this machine.
Then run:

```
qube check webhooks <QUBE_WEBHOOK_URL> [--operation <the segment its run webhook URLs start with>]
```

`<QUBE_WEBHOOK_URL>` is the base of the app's webhook URLs on this machine, the local URL a
`qube listen --forward-to` would forward to, such as `http://localhost:3000/webhooks/qube`: not a
`qube listen` relay URL, which the check refuses, and never a deployed app. A wrong signature and a
stale timestamp go to `<QUBE_WEBHOOK_URL>/runs/qube-check-<n>`, the published libraries' run path,
for a run no app has; `--operation` replaces `runs` when the app's run webhook URLs start with
something else. A signed delivery goes to a path no app routes. Each check sends only what the app
must refuse or can't route, so none reaches a real run or connection, and the rules it can't test
that way are checked in the code above. Each check is a rule's Live check. Fold each failed check
into the report as a `violation` of its rule, citing the check and the answer it got, and count a
passed one as evidence for `ok`. A `404` to a refusal check only means the check's path isn't routed
(one URL for everything, say), so give its rule `can't tell` rather than a `violation`. When the app
isn't running, the command doesn't exist or the CLI isn't signed in, skip this step and say so in
the report.

## 5. Report

Answer in this shape:

```markdown
# QuBe Sync audit: <the app>

<A paragraph: what the integration does (the workflows it starts, the requests it
queues), the stack, what you read, and the counts: violations by severity, can't tell,
ok and n/a.>

## Findings

| Severity | Rule | Verdict | Where | What's wrong | Fix |
| --- | --- | --- | --- | --- | --- |
| critical | `ids-keyed-by-connection` | violation | `app/models/item.rb:12` | Items are found by `list_id` alone. | Add the connection id, a unique index on it with the list and `list_id`, and look items up within the event's `connection_id`. |

## Passed

`verify-signature` (`app/controllers/qube_webhooks_controller.rb:9`), ...

## Not applicable

`dedupe-request-webhooks`: the app queues no requests itself. ...

## Live checks

<What qube check webhooks reported, or why it didn't run.>
```

List the findings critical first, then major, then minor, and within each severity the violations
before `can't tell`. Link each rule id to its docs when you can. End with the fixes for the critical
findings as next steps, and offer to make them; change nothing until the user says which.

## The rules

Each rule has an id that findings cite, a severity, when it applies, why, what to check, what
getting it wrong and right looks like, and its docs. The same rules, with their reasons, are at
https://docs.qubesync.com/integration-checklist.

### Onboarding

Connecting a customer's QuickBooks: the connection, its webhook and its events.

#### `connection-webhook-url` (major)

Create each customer's connection with a `webhook_url`, so QuBe Sync can tell your app when they're
connected.

- **Applies when** the app connects its customers' QuickBooks (it creates connections).
- **Why:** The setup ends on the QuickBooks computer and never comes back to your app: the
  connection's `webhook_url` hearing `connection.connected` is how the app knows. Without one, the
  app shows the customer's QuickBooks as waiting forever, and nothing tells it when requests stall.
- **Check:** The code that calls `POST /api/v2/connections`, and `PUT /api/v2/connections/{id}` for
  a connection made before: the body each sends.
- **Wrong:** The create sends only a `name`, or a `webhook_url` with no route behind it, and a
  connection made before is never given one.
- **Right:** `POST /api/v2/connections` with the customer's company as `name` and your endpoint as
  `webhook_url` (the `qube_rails` engine and the `qubesync` packages' kits add the id of the
  connection's own row: `/webhooks/qube/connections/<id>`), and a saved connection brought up to
  date with `PUT /api/v2/connections/{id}`.
- **Docs:**
  [Add the "Connect to QuickBooks" button](https://docs.qubesync.com/onboarding#add-the-connect-to-quickbooks-button),
  [Connection events](https://docs.qubesync.com/webhooks#connection-events).

#### `save-connection-id` (major)

Save the connection's `id` on the record that keeps it (the customer's account or shop, say) before
you send them to its `links.onboarding`, and reuse it when they click Connect again.

- **Applies when** the app connects its customers' QuickBooks (it creates connections).
- **Why:** Every request and run goes out on that id, and the connection's events are matched to it.
  A simulated connection is connected as it's made, so its `connection.connected` can arrive before
  the create call returns. A customer who comes back (a link past its 48 hours, QuickBooks on a new
  computer) needs the same connection's link again, not a second connection.
- **Check:** The connect action: where the create's `id` is stored, whether that happens before the
  redirect, and what a second click does when that record already has a connection.
- **Wrong:** The id is saved in the webhook handler, after the redirect, or not at all; or every
  click on Connect calls `POST /api/v2/connections` again.
- **Right:** Save `id` on that record, then redirect to `links.onboarding`. When the record already
  has a connection, update it and send them to a fresh link from
  `POST /api/v2/connections/{id}/onboarding-url`. `qube_rails` 0.2.0, PyPI `qubesync` 0.4.0's kit
  and npm `qubesync` 0.3.0's kit write the connection's row before they call QuBe Sync and save the
  id as soon as they have it, and their Connect reuses the account's connection that never finished
  setup (`new: 1` makes another).
- **Docs:**
  [Add the "Connect to QuickBooks" button](https://docs.qubesync.com/onboarding#add-the-connect-to-quickbooks-button),
  [Setting a connection up again](https://docs.qubesync.com/onboarding#setting-a-connection-up-again).

#### `workflow-connections-realtime` (major)

Create the connections your app runs workflows on as `realtime` (`"type": "realtime"` on
`POST /api/v2/connections`), and handle a start answered `422` with `errors.code`
`realtime_required`.

- **Applies when** the app creates connections and starts workflow runs on them.
- **Why:** Workflows run on realtime and simulated connections only: a start on a standard
  connection is refused with nothing stored, so its customer never gets the run. A connection's type
  can't be changed through the API, only upgraded from its page in the dashboard, and once a
  downgrade takes effect new runs are refused (runs already going finish). The same call with the
  same `Idempotency-Key` starts the run once the connection is upgraded.
- **Check:** The connect action's `POST /api/v2/connections` body (or the library call that makes
  it): its `type`; and the code that starts runs: what it does with a 422 whose `errors.code` is
  `realtime_required`.
- **Wrong:** Connections created without `type` (so `standard`) by an app that starts workflow runs,
  or a `realtime_required` answer swallowed, retried in a loop or shown as a generic error.
- **Right:** `type: "realtime"` on every connection the integration runs workflows on, and a
  `realtime_required` answer kept with the record and surfaced to whoever can upgrade the connection
  (the app's admin, or the customer's account page), then the start sent again with the same key.
- **Docs:**
  [Workflows run on realtime connections](https://docs.qubesync.com/workflows#workflows-run-on-realtime-connections),
  [When a workflow run is refused](https://docs.qubesync.com/error_handling#when-a-workflow-run-is-refused).

#### `connected-by-webhook` (major)

Show a customer's QuickBooks as connected only when a signed `connection.connected` arrives for
their connection, never when a browser comes back.

- **Applies when** the app connects its customers' QuickBooks (it creates connections).
- **Why:** The onboarding page doesn't send your customer back to your app: the setup ends on the
  QuickBooks computer, which usually isn't signed in to your app, and the v2 API refuses a
  `redirect_url`. Nothing has to wait for it either: runs started before the Web Connector connects
  wait in the queue.
- **Check:** Whatever marks the customer's QuickBooks connected: the connection event handler, and
  any callback route, `redirect_url` or polling of `GET /api/v2/connections/{id}`.
- **Wrong:** A `/quickbooks/callback` route that marks QuickBooks connected, a `redirect_url` on the
  create, or a timer that reads `last_connected_at` and calls it connected.
- **Right:** Until `connection.connected` comes, the app shows the customer's QuickBooks as waiting;
  the connection event handler marks it connected.
- **Docs:**
  [Add the "Connect to QuickBooks" button](https://docs.qubesync.com/onboarding#add-the-connect-to-quickbooks-button),
  [Connection events](https://docs.qubesync.com/webhooks#connection-events).

#### `connection-event-for-saved-connection` (critical)

Apply a connection event only to the record whose saved connection id is the event's
`connection.id`, and answer it `2xx` either way.

- **Applies when** the app takes connection events.
- **Why:** The signature covers the body, not the URL. A URL that names the record keeping the
  connection (the `qube_rails` engine's `/webhooks/qube/connections/<id>`) is only a pointer, so a
  signed event posted to another record's URL would change that record.
- **Check:** The connection event handler: how it finds the record that keeps the connection, and
  whether it compares the event's `connection.id` with the id saved on it before changing anything.
- **Wrong:** The record found from the URL (`Account.find(params[:account_id])`) and updated with no
  look at `connection.id`.
- **Right:** Find the record by `connection.id`, or, when the URL names it, log and skip an event
  whose `connection.id` isn't the one saved there. `qube_rails` 0.2.0 finds the connection's row by
  the URL's id and skips an event whose `connection.id` isn't the row's `qube_id`; for a row whose
  id isn't saved yet, it adopts QuBe Sync's connection made with that row's webhook URL, or raises
  `QubeRails::NotReady` so the job is retried. The `qubesync` packages' kits (PyPI 0.4.0, npm 0.3.0)
  do the same, raising `NotReady`.
- **Docs:** [Connection events](https://docs.qubesync.com/webhooks#connection-events),
  [Add the "Connect to QuickBooks" button](https://docs.qubesync.com/onboarding#add-the-connect-to-quickbooks-button).

#### `connection-event-newer-revision` (major)

Apply a connection event only when its `revision` is newer than the last you applied for that
connection, and save the revision with the change.

- **Applies when** the app takes connection events.
- **Why:** Deliveries can come out of order, a retried `connection.stalled` after its
  `connection.resumed` say. The `revision` counts up across all four events, per connection, and a
  retry of one event has the same `delivery_id` and `revision`.
- **Check:** The connection event handler: where the last applied revision is kept, and whether the
  compare and the save happen together, under a row lock or in one conditional update.
- **Wrong:** Every event overwrites the connection's status as it arrives, so a late
  `connection.stalled` leaves a working connection showing a stall.
- **Right:** Under the row lock of the record that keeps the connection, skip an event whose
  `revision` isn't higher than the one saved; otherwise apply it and save its `revision`.
- **Docs:** [Connection events](https://docs.qubesync.com/webhooks#connection-events).

#### `show-stall-reason` (minor)

Show your customer what `connection.stall_reason` says to do, and clear it on `connection.resumed`.

- **Applies when** the app takes connection events.
- **Why:** `not_checking_in` means the Web Connector hasn't checked in when it was due: turn on the
  QuickBooks computer and check the Web Connector. `quickbooks_unavailable` means it is checking in
  but can't reach QuickBooks: open QuickBooks with the company file. A stall can change its reason
  and send `connection.stalled` again, so show the newest.
- **Check:** The `connection.stalled` and `connection.resumed` branches, and the page that shows the
  customer's QuickBooks status.
- **Wrong:** `connection.stalled` is logged and never reaches the customer, one message stands for
  both reasons, or the warning never clears.
- **Right:** Save the reason with the status, show the guidance for that reason, and clear both on
  `connection.resumed`, whichever the last reason was.
- **Docs:** [Connection events](https://docs.qubesync.com/webhooks#connection-events),
  [Keep an eye on the connection](https://docs.qubesync.com/onboarding#keep-an-eye-on-the-connection).

#### `setup-cancelled-offers-connect` (minor)

On `connection.setup_cancelled`, offer the Connect button again.

- **Applies when** the app takes connection events.
- **Why:** Your customer chose Cancel setup on the onboarding page. The connection is unchanged and
  its onboarding link still works, so Connect can take them back to the same one.
- **Check:** The `connection.setup_cancelled` branch, and what the customer's page shows after it.
- **Wrong:** The event falls through to a default branch, and the customer's QuickBooks keeps
  showing as waiting.
- **Right:** The customer's QuickBooks goes back to not connected, with the Connect button, which
  reuses the saved connection.
- **Docs:** [Connection events](https://docs.qubesync.com/webhooks#connection-events).

### Calling the API and starting runs

The API key, the calls that queue requests or start workflow runs, and what each one carries.

#### `api-key-on-the-server` (critical)

Call the API only from your server, with HTTP basic auth: the API key as the username and an empty
password, read from the environment.

- **Applies:** always.
- **Why:** An app's key reaches every connection of that app. In a browser, a mobile app or the
  repo, anyone who sees it can read and write your customers' company files.
- **Check:** Where the API client sets its auth and where the key comes from, and whether any code
  that runs on the user's device (a JavaScript bundle, a mobile app) calls `qubesync.com/api`.
- **Wrong:** A key written into source, the key in frontend configuration (a `NEXT_PUBLIC_` or
  `VITE_` variable), or browser code that calls `https://qubesync.com/api/v2/` itself.
- **Right:** A client on the server that reads `QUBE_API_KEY` from the environment and sends it as
  the basic-auth username with a blank password. The libraries' clients do this with the key they're
  given: `QubeSync::Client.new(api_key: ENV.fetch("QUBE_API_KEY"))` (gem `qube_sync` 0.4.0 or
  later), `qubesync.Client(os.environ["QUBE_API_KEY"])` (PyPI `qubesync` 0.3.0 or later) or
  `new Client({ apiKey: process.env.QUBE_API_KEY })` (npm `qubesync` 0.2.0 or later). A Rails app on
  the `qube_rails` engine (0.2.0 or later) has this already: its client reads `QUBE_API_KEY` (or
  `config.api_key`), on the server. So does a Python or Node app on the `qubesync` package's kit
  (PyPI 0.4.0, npm 0.3.0, or later), from `QUBE_API_KEY` or its `api_key` / `apiKey` setting.
- **Docs:** [Do it from your code](https://docs.qubesync.com/quickstart#do-it-from-your-code).

#### `sandbox-production-apart` (major)

Keep sandbox and production apart: each environment uses its own app's API key and webhook secret,
and only that app's connection ids.

- **Applies:** always.
- **Why:** Your code doesn't change between the two; the API key, the webhook secret and the
  connection ids do. A sandbox key can't reach production connections, and the other way round, so a
  connection id kept under one app answers `404` to the other's key. Every webhook says which app
  sent it, in `app_id` and `sandbox`.
- **Check:** The configuration for each environment, any fallback from one key or secret to another,
  and, when one endpoint serves both apps, which secret it verifies with.
- **Wrong:** One key committed in a shared config file, production falling back to the sandbox key
  when its own is unset, or a sandbox connection id copied into production data.
- **Right:** `QUBE_API_KEY`, `QUBE_WEBHOOK_SECRET` and `QUBE_WEBHOOK_URL` set per environment with
  no default, and connection ids created and kept by the environment that uses them.
- **Docs:** [Launch checklist](https://docs.qubesync.com/going-live#launch-checklist).

#### `reference-saved-before-start` (major)

Start every run with a new `reference`, saved on your record before you send the start, and find the
record by it rather than by `run_id`.

- **Applies when** the app starts workflow runs.
- **Why:** Any run webhook can arrive before the `201` that starts the run. Revisions count per run,
  so a reference used for a second run lets the first run's webhooks be taken for the second's, and
  the second's skipped against the first's.
- **Check:** Each call to `POST /api/v2/connections/{id}/workflow-runs`: the `reference` it sends,
  whether it's new for every run, and whether it's saved before the call. Then how the webhook job
  finds the record.
- **Wrong:** The record's id sent as the reference for every run about it, the reference saved after
  the call returns, or the job finding the record by the `run_id` saved from the `201`.
- **Right:** A reference made for the run (`create_invoice-42-` and a UUID), saved on the record
  with its last applied revision reset, then the start; the job finds the record by `reference`.
- **Docs:** [Workflow runs](https://docs.qubesync.com/webhooks#workflow-runs),
  [Good to know](https://docs.qubesync.com/workflows#good-to-know).

#### `one-run-per-record-at-a-time` (major)

While a record's last run of an operation hasn't ended, give back that run (resending its start with
the same `reference` if QuBe Sync never confirmed it) rather than starting another.

- **Applies when** the app starts workflow runs.
- **Why:** A second click, a retried job or a page loaded twice would otherwise start a second run
  with a new reference, which QuBe Sync can't tell from a new one: the invoice is added twice.
- **Check:** What runs when a user starts an operation for a record: whether it looks for that
  record's unended run on the connection first, and whether that check and the new run's row are
  written under one lock.
- **Wrong:** Every click writes a new reference and starts a run, or the unended-run check reads
  outside the lock, so two requests at once both start.
- **Right:** Under a lock on the connection's row: the record's latest run of the operation,
  returned when it hasn't ended (its start resent with the same reference when it's still
  `starting`); a new reference and run only once it has.
- **Docs:** [Good to know](https://docs.qubesync.com/workflows#good-to-know).

#### `missing-records-in-adds` (major)

Send each customer, vendor, employee or item your transaction names that QuickBooks may not have yet
as an entry of `adds`, built from your own record, until it's linked.

- **Applies when** the app starts `add_transaction` (or another workflow that takes `adds`).
- **Why:** `add_transaction` creates a missing record only from an add your app sent for it. A
  reference with no entry is matched on its name alone, and when nothing matches, the run can only
  ask your user to pick an existing record: there's no choice to create it.
- **Check:** Each `add_transaction` input: the `*_ref` fields filled by name from the app's records,
  and whether `adds` carries an entry for each one that isn't linked yet.
- **Wrong:** A `customer_ref` by `full_name` from the app's customer and no `adds`, so a new
  customer stops the run at a question with no way to create it.
- **Right:** `adds: [{kind: "customer", add: {name:, email:, phone:}, fields: {email:, phone:}}]`
  from the invoice's customer when it has no ListID linked on the connection; left out once it has.
- **Docs:** [Pick a template](https://docs.qubesync.com/workflows#pick-a-template).

#### `webhook-url-per-run` (minor)

Give each run a webhook URL that names it, such as `/webhooks/qube/runs/<id>` (a row written for the
run before it starts, which keeps its operation and your record), or route one shared endpoint on
`event` and `reference`.

- **Applies when** the app starts workflow runs.
- **Why:** Each run takes its own `webhook_url`, so the URL can carry what the job needs: which
  class handles the run and which record it's about. One shared URL works too, when its job routes
  on `event` first and finds the record by `reference`.
- **Check:** The `webhook_url` each start sends, and the route and job that take it.
- **Wrong:** Every run sends the same URL, and the job guesses the record from `output` or a
  `run_id` it may not have saved yet.
- **Right:** `QUBE_WEBHOOK_URL` plus `/runs/<id>`, taken by `POST /webhooks/qube/runs/:id`, which
  `qube_rails` 0.2.0 and the `qubesync` packages' kits (PyPI 0.4.0, npm 0.3.0) do with their
  `qube_runs` row; a URL that names the operation and the record (`/create_invoice/42`); or one URL
  whose job routes on `event` and finds the record by `reference`.
- **Docs:** [Handle it in a job](https://docs.qubesync.com/webhooks#handle-it-in-a-job),
  [Workflow runs](https://docs.qubesync.com/webhooks#workflow-runs).

#### `idempotency-key` (major)

Make one `Idempotency-Key` for each call you mean to make once, from something new to that call (a
UUID, or the run's new `reference`), store it with the record before you send it, and resend it only
to retry that call.

- **Applies when** the app queues requests or starts workflow runs.
- **Why:** Every call queues a new request: two calls to create an invoice make two invoices, and
  starting a run twice runs it twice. With the same key, a call sent again after a timeout gets back
  what the first one queued (`Idempotent-Replayed: true`), and nothing new is queued. A key lasts
  until what it created is purged (60 days after a request is answered or a run ends), and then
  frees up.
- **Check:** The API client and each call that queues or starts: whether the header is sent, where
  the key comes from, and what a retry after a timeout or a dropped connection sends.
- **Wrong:** A key built from the record alone (`invoice-42`) or a constant, which turns the next
  real call into a replay of the first (or a `422`) and lets a retry 60 days later create a
  duplicate; or a new UUID made inside the retry loop, so each retry is a new request.
- **Right:** One key for each request you mean to make once (a UUID, or the run's new `reference`),
  stored with your record before you send it, and sent on the first call and every retry of it. The
  libraries' clients send it: `start_run` sends the run's `reference`, and `queue` and `queue_qbxml`
  send the `idempotency_key` you pass (pass the one stored with your record; left out, they make one
  for the call and resend it on their own retries, which a retry from another process or after a
  crash can't reuse). `qube_rails` 0.2.0 sends the run's reference, and keeps a start that got no
  answer `starting`: `run.retry_start!` resends the same reference and input, so QuBe Sync answers
  with the run it already started and never starts a second. The `qubesync` packages' kits do the
  same (`run.retry_start()` in Python 0.4.0, `run.retryStart()` in Node 0.3.0).
- **Docs:**
  [Retrying a call safely](https://docs.qubesync.com/making-requests#retrying-a-call-safely),
  [Good to know](https://docs.qubesync.com/workflows#good-to-know).

### Webhooks

The endpoint that takes QuBe Sync's deliveries, and the job that does the work.

#### `verify-signature` (critical)

Verify every delivery's `X-Qube-Signature` before you act on it, and answer `401` when no `v1` in it
matches.

- **Applies:** always.
- **Why:** Anyone can POST to a public URL. The header carries a timestamp `t` and one `v1` for each
  active webhook secret on your app, each the hex HMAC-SHA256 of `<t>.<raw body>` keyed with that
  secret.
- **Check:** The webhook endpoint, before anything else runs: how it splits the header, which secret
  it uses, how it compares every `v1`, and what a failure answers.
- **Wrong:** No check, a check that logs and carries on, `==` instead of a constant-time compare,
  only the first `v1` compared, or a failure that still answers `200`. The `qube_sync` gem before
  0.3.0 compares with `==`.
- **Right:** Split the header on `,` and each part on its first `=`, compute the HMAC with
  `QUBE_WEBHOOK_SECRET`, and accept when any `v1` matches in constant time
  (`Rack::Utils.secure_compare`, `crypto.timingSafeEqual`, `hmac.compare_digest`); otherwise answer
  `401` and enqueue nothing. Or call a library that does all of this: `QubeSync::Webhooks.verify`
  (gem `qube_sync` 0.3.0 or later), `webhooks.verify` (PyPI `qubesync` 0.2.0 or later) or `verify`
  (npm `qubesync` 0.1.0 or later), answering `401` on its `SignatureError` (the "Use a library" tab
  of Verify the signature). A Rails app on the `qube_rails` engine (0.2.0 or later, or the copy QuBe
  Sync's kit vendors below Ruby 3.3) is already doing this: its webhook endpoint verifies every
  delivery before it enqueues one, and so does a Python or Node app's on the `qubesync` package's
  kit (PyPI 0.4.0, npm 0.3.0, or later).
- **Live check:** `bad-signature-401` (step 4).
- **Docs:** [Verify the signature](https://docs.qubesync.com/webhooks#verify-the-signature).

#### `refuse-stale-timestamp` (major)

Refuse a delivery whose `t` is more than five minutes from now, with `401`.

- **Applies:** always.
- **Why:** It stops someone replaying a captured delivery. Every delivery, retries included, is
  signed afresh, so a healthy receiver never sees an old one.
- **Check:** The verify function: whether it reads `t`, and what it compares it with.
- **Wrong:** No age check, `t` read and never compared, a limit of hours, or one that only refuses
  old timestamps, not future ones. The `qube_sync` gem before 0.3.0 and PyPI `qubesync` before 0.2.0
  allow 500 seconds, and only into the past.
- **Right:** The difference between now and `t` at most 300 seconds either way, checked with the
  signature, and `401` otherwise. The libraries' `verify` does this by default (a `tolerance` of
  300).
- **Live check:** `stale-timestamp-401` (step 4).
- **Docs:** [Verify the signature](https://docs.qubesync.com/webhooks#verify-the-signature).

#### `verify-raw-body` (major)

Verify the signature over the raw bytes you received, before anything parses the body.

- **Applies:** always.
- **Why:** The signature is over the exact bytes QuBe Sync sent. Parsed and serialized again, JSON
  has other spacing, key order and escapes, so real deliveries fail, and a parser that runs before
  the check runs on bodies nobody has verified.
- **Check:** The webhook route's body handling: the framework's body parsers, and which bytes the
  HMAC is computed over.
- **Wrong:** The HMAC computed over `JSON.stringify(req.body)` or `params.to_json`, or
  `express.json()` mounted before the webhook route.
- **Right:** The raw body as the framework gives it (`request.raw_post` in Rails,
  `express.raw({ type: "application/json" })` on the webhook route alone in Express,
  `await request.body()` in FastAPI, `request.get_data()` in Flask, `request.body` in Django),
  verified first and parsed after. The libraries' `verify` takes those raw bytes, and refuses an
  already-parsed body with a `TypeError`.
- **Docs:** [Verify the signature](https://docs.qubesync.com/webhooks#verify-the-signature).

#### `answer-fast-work-in-job` (major)

Answer `2xx` within 5 seconds, and do the work in a background job.

- **Applies:** always.
- **Why:** Anything but a `2xx` within 5 seconds is a failed delivery: a timeout, a redirect, a
  `4xx` or a `5xx`. It's retried with backoff for about 8 hours, and then marked failed (a run's
  latest event can then be sent again with `POST .../workflow-runs/{run_id}/redeliver`), so work
  done before the answer can run past it and run again on each retry.
- **Check:** Everything the endpoint does before it answers.
- **Wrong:** The endpoint updates records, calls the QuBe Sync API or another service, or answers a
  run's question before it returns.
- **Right:** Verify, check the route, enqueue the event, answer `200`.
- **Docs:**
  [Four jobs for your endpoints](https://docs.qubesync.com/webhooks#four-jobs-for-your-endpoints),
  [When a delivery fails](https://docs.qubesync.com/webhooks#when-a-delivery-fails).

#### `durable-job-queue` (major)

Enqueue each delivery on a durable queue that retries a failed job, and answer `5xx` when the
enqueue itself fails.

- **Applies:** always.
- **Why:** Once QuBe Sync has its `2xx`, it won't send that event again: a job that raises, or one
  an in-process queue loses on a restart, is gone unless your queue keeps and retries it.
- **Check:** What the endpoint enqueues on and whether it waits for the enqueue, and the job's
  retries (the ActiveJob adapter and `retry_on`, Sidekiq, Celery, RQ, BullMQ, pg-boss).
- **Wrong:** In production, a thread, `setImmediate`, a thread pool or FastAPI's `BackgroundTasks`;
  a job that rescues every error and returns; or an enqueue error swallowed while the endpoint still
  answers `200`.
- **Right:** A persistent queue with retries, and an endpoint that answers `2xx` only once the
  enqueue has succeeded. `qube_rails` 0.2.0 does this: its endpoint answers `503` when the enqueue
  returns false or raises, and `QubeRails::WebhookJob` retries (`retry_on`, 10 attempts by default)
  and logs when it gives up. The `qubesync` packages' kits (PyPI 0.4.0, npm 0.3.0) answer `503` the
  same way, but their default queue runs in the web process, which a restart empties: it passes only
  once `enqueue` hands each delivery to a durable queue.
- **Docs:** [Handle it in a job](https://docs.qubesync.com/webhooks#handle-it-in-a-job),
  [When a delivery fails](https://docs.qubesync.com/webhooks#when-a-delivery-fails).

#### `fixed-operation-map` (critical)

Turn the operation slug in a webhook URL into its class through a fixed map, and answer `404` for
any other slug; never build a class name from the path.

- **Applies when** the webhook URL names its handler (an operation slug in the path).
- **Why:** The signature covers the body, not the URL, so a signed body can be posted to any path. A
  class looked up from the path lets the path choose which code runs.
- **Check:** The endpoint and the job: how the slug becomes a handler.
- **Wrong:** `constantize` or `const_get` on the slug, `getattr` on a module, `require` of a path
  built from it, or a plain JavaScript object lookup, where `__proto__` is a slug too.
- **Right:** A frozen map of slug to class (a `Map` in JavaScript), checked by the endpoint, which
  answers `404` when the slug isn't in it, and used by the job.
- **Live check:** `unknown-operation-404` (step 4).
- **Docs:** [Handle it in a job](https://docs.qubesync.com/webhooks#handle-it-in-a-job).

#### `route-on-event` (minor)

Route a webhook on its `event` first: run, connection and name index webhooks carry one, and a
request's answer doesn't.

- **Applies when** one endpoint takes more than one kind of webhook (request answers, run events,
  connection events, the name index's).
- **Why:** One endpoint can take a request's answers, a run's events, a connection's events and
  `name_index.ready`. A handler that treats every body as a request's answer finds no request for
  the others, and drops them.
- **Check:** The endpoint's or the job's dispatch.
- **Wrong:** Every body goes to the request-answer handler, which looks up `id` and returns when it
  finds nothing.
- **Right:** `workflow_run.` events to the run handler, `connection.` events to the connection
  handler, `name_index.` events to their own, and only a body with no `event` to the request-answer
  handler.
- **Docs:** [Handle it in a job](https://docs.qubesync.com/webhooks#handle-it-in-a-job),
  [Name index events](https://docs.qubesync.com/webhooks#name-index-events).

#### `skip-other-reference` (critical)

Skip, and log, a run event whose `reference` isn't the one saved on the record it's for.

- **Applies when** the app starts workflow runs.
- **Why:** The signature covers the body, not the URL, so a record id in the URL is only a pointer,
  and a record's earlier runs keep sending until they end. Applying another run's event writes its
  results to the wrong record, perhaps another customer's.
- **Check:** The job, once it has the record: the comparison of the event's `reference` with the
  saved one, before any revision check or handler.
- **Wrong:** The record found by the id in the URL and handed straight to a handler, or a match on
  the record id alone.
- **Right:** Return before anything else when the event's `reference` isn't the record's saved
  reference, and log it.
- **Docs:** [Workflow runs](https://docs.qubesync.com/webhooks#workflow-runs),
  [What your app receives](https://docs.qubesync.com/workflows#what-your-app-receives).

#### `run-event-newer-revision` (major)

Apply a run's webhook only when its `revision` is higher than the last you applied for that run, and
save the revision with the change; notifications are the exception.

- **Applies when** the app starts workflow runs.
- **Why:** Deliveries can repeat, cross each other and arrive before the response to the call that
  caused them. Every body of a run (a webhook, the `201`, a decision's response, a `GET`) carries
  its `revision`, which goes up with every change. A notification is data, not the run's state, so
  it's deduplicated on `delivery_id` and never skipped by revision.
- **Check:** The job's handling of `workflow_run.` events: where the last revision lives, whether
  the compare and the save happen under one lock, and that notifications are left out of it.
- **Wrong:** No revision check, so a retried `workflow_run.awaiting_input` reopens a question
  already answered; or the check and the save in separate transactions, so two workers let an older
  event through.
- **Right:** Under the record's row lock, skip a body whose `revision` isn't higher than the saved
  one; apply it, then save its `revision`. A new run starts the saved revision again from 0.
- **Docs:** [Workflow runs](https://docs.qubesync.com/webhooks#workflow-runs),
  [What your app receives](https://docs.qubesync.com/workflows#what-your-app-receives).

#### `notification-once` (major)

Take each `workflow_run.notification` once, by its `delivery_id`, in a store every worker shares.

- **Applies when** a workflow the app starts sends it data (`pull_changes`, `stream_query`, or any
  chart with a `notify` state).
- **Why:** Delivery is at least once: a failed delivery is retried up to 10 times over about an
  hour, with the same `delivery_id`. A record of handled ids in one process's memory misses a retry
  that reaches another worker.
- **Check:** The notification branch: what it records, where, and whether a second worker would see
  it. On the `qube_rails` engine, whether `config.dedupe` is overridden in
  `config/initializers/qube_rails.rb`, and if it's a cache store (`QubeRails::CacheDedupe`), whether
  `config.cache_store` in `config/environments/production.rb` is one every worker shares (Redis,
  Memcached, Solid Cache), not the memory or file store.
- **Wrong:** Notifications put through the revision check, delivery ids kept in process memory or a
  per-process cache, or no check at all where saving twice isn't harmless.
- **Right:** Each handled `delivery_id` recorded in the database or a shared cache and skipped when
  seen again; or a save that's harmless twice, an upsert by connection, kind and id. `qube_rails`
  0.2.0's default passes: its `qube_notifications` table, written in the same transaction as the
  handler under the run's lock. So do PyPI `qubesync` 0.4.0's (`DatabaseDedupe`) and npm `qubesync`
  0.3.0's (the store's `once`), on the same table. An app that sets `config.dedupe` to a cache store
  instead needs one its workers share, set in `config/environments/production.rb`.
- **Docs:** [Sending your app data](https://docs.qubesync.com/workflows#sending-your-app-data),
  [What your app receives](https://docs.qubesync.com/workflows#what-your-app-receives).

#### `dedupe-request-webhooks` (major)

Deduplicate a request's webhooks on `page_request_id` plus `state`: a `retryable` webhook isn't
final.

- **Applies when** the app queues QuickBooks requests itself, not only through workflows.
- **Why:** A `retryable` webhook and the answer that follows it share `id` and `page_request_id`,
  and only `state` differs. Keyed on an id alone, the answer looks like a repeat and is lost.
- **Check:** The request-answer handler: what it treats as already handled.
- **Wrong:** Returning early because the request's `id` was seen before, or a unique index on
  `page_request_id` alone.
- **Right:** Handled pairs of `page_request_id` and `state` kept, and only a second delivery of the
  same `state` skipped.
- **Docs:**
  [What to do with each `state`](https://docs.qubesync.com/webhooks#what-to-do-with-each-state),
  [Handling far edge cases](https://docs.qubesync.com/pagination#handling-far-edge-cases).

#### `pages-complete-1-to-n` (major)

Count a paged query as done once you've handled every page from 1 to the `done` page's `page`, not
when the `done` page arrives.

- **Applies when** the app queues paged list queries itself.
- **Why:** Pages can arrive out of order (page 4 before page 3), and a retried page twice. The
  `done` page (`max_sandbox_iterations_reached` in a sandbox) is the last sent, and its `page` says
  how many there are. If the session ends partway, the next page ends `error`, and the query has to
  be queued again from page 1.
- **Check:** Where the app decides an import is finished, and what it does with a page that ends
  `error`.
- **Wrong:** Finishing the import when `iteration_state` is `done`, or keeping only the last
  `iteration_state` seen.
- **Right:** The set of page numbers handled, kept per request `id`; the import finished once the
  `done` page is in and every page from 1 to its `page` is in the set. Or a workflow
  (`pull_changes`, `stream_query`), which sends the pages in order.
- **Docs:** [Handling far edge cases](https://docs.qubesync.com/pagination#handling-far-edge-cases),
  [If the session ends partway](https://docs.qubesync.com/pagination#if-the-session-ends-partway).

#### `fetch-omitted-response-xml` (minor)

When a request's webhook has `response_xml_omitted: true`, GET its `links.self` with your API key
for `response_xml`.

- **Applies when** the app reads `response_xml` from request webhooks.
- **Why:** A webhook that would be over 1 MB comes without `response_xml`: it's null, and
  `links.self` is the request's URL in the API, `response_xml` included. `response_json` is always
  there, so an app that reads only `response_json` needs nothing here. This one GET, in the
  webhook's job, isn't polling: the answer is already in.
- **Check:** Where the request webhook's job reads `response_xml`.
- **Wrong:** A null `response_xml` read as an empty answer or an error, or the webhook dropped.
- **Right:** In the job: if `response_xml_omitted` is true, GET `links.self` with the API key from
  the server's environment and read `response_xml` from that; otherwise take it from the webhook.
- **Docs:** [Payload fields](https://docs.qubesync.com/webhooks#payload-fields).

### Questions and endings

What a workflow run asks your app, and every way it ends.

#### `never-pick-an-answer` (major)

Show each question a run asks to your user, from its `message`, `details` and `choices`, and answer
with the choice they pick; never pick one in code.

- **Applies when** a workflow the app starts can ask a question (`workflow_run.awaiting_input`).
- **Why:** A run asks only when it can't decide: which of several records a name means, or whether a
  lost add went through. A guessed answer can put an invoice on the wrong customer or add it twice,
  and the run waits for an answer for as long as it takes, so there's nothing to gain by guessing. A
  rule your user set up ahead of time is still their choice.
- **Check:** The `workflow_run.awaiting_input` handler and the code that answers it: where the
  `choice` it sends comes from.
- **Wrong:** A choice such as `use_existing`, the first candidate's `use:1`, or `choices[0]` sent
  straight from the job, or a question logged and never shown.
- **Right:** The whole `prompt` and its links saved on the record, the question shown on the
  record's page with a form per choice, and the choice sent when your user picks it.
- **Docs:** [Answering a question](https://docs.qubesync.com/workflows#answering-a-question),
  [Two kinds of question](https://docs.qubesync.com/workflows#two-kinds-of-question),
  [What your app receives](https://docs.qubesync.com/workflows#what-your-app-receives).

#### `answer-at-links-decisions` (major)

Answer at the saved `links.decisions` as given, with the picked `choice` and its fields' `data`, and
take a `409` or a `400 not_awaiting_input` on a retry as already answered.

- **Applies when** a workflow the app starts can ask a question (`workflow_run.awaiting_input`).
- **Why:** `links.decisions` carries the question's `prompt_token`, so an answer sent again can't
  answer the run's next question. A `choice` names one the server offered, so what it fills in (a
  candidate's ListID, say) comes from the server, not your app. Without a token, an answer is taken
  for whatever the run is asking when it arrives.
- **Check:** The code that sends your user's answer: the URL it posts to, its body, and what it does
  with a `409` or a `400`.
- **Wrong:** A decisions URL built from the run id with no `prompt_token`, an `option` with a ListID
  your app filled in where the prompt offered a `choice`, or a `409` on a retry shown to the user as
  an error.
- **Right:** `{"choice": "use:1"}`, or a choice with its fields in `data`, POSTed from your server
  to the saved `links.decisions`; a `409` or a `400 not_awaiting_input` means it was answered or
  asked again since, so the page says the question has changed and reloads.
- **Docs:** [Answering a question](https://docs.qubesync.com/workflows#answering-a-question),
  [Good to know](https://docs.qubesync.com/workflows#good-to-know),
  [The API at a glance](https://docs.qubesync.com/workflows#the-api-at-a-glance).

#### `questions-passed-through` (major)

Show any question the same way, from its `message`, `details` and `choices`, and post the chosen
`choice`; never branch on a question's id, and never send a ListID or TxnID your user typed or your
app picked.

- **Applies when** a workflow the app starts can ask a question (`workflow_run.awaiting_input`).
- **Why:** Each prompt carries what a screen needs: what it's about in `details`, and every choice
  with the fields it takes, so one screen answers every question, including ones a workflow adds
  later. Code per question id falls behind the chart, and it's where guesses creep in. A candidate's
  choice carries its id from the server, and a `record` field's value comes from `links.search`, so
  every id the run uses is one QuickBooks has.
- **Check:** The question handler and the screen that shows it: whether either switches on
  `prompt.id` or on option ids, and where each value it sends comes from.
- **Wrong:** A `case prompt["id"]` with a screen per question, an id typed into a text box, or a
  ListID your app looked up and sent as `data` where the prompt offered choices or a search.
- **Right:** One handler that saves the whole `prompt` and its `links.decisions` and `links.search`
  on the record, and one screen that renders its `message`, `details` and a form per choice, with a
  search box for a `record` field and a table for a `rows` field (a row per `rows` entry, the
  columns each asks that apply under their `when`).
- **Docs:** [Answering a question](https://docs.qubesync.com/workflows#answering-a-question),
  [What your app receives](https://docs.qubesync.com/workflows#what-your-app-receives).

#### `question-route-authorized` (critical)

Check that the signed-in user may act on the record before an answer or search route reads its
question; never trust a record id from a form or URL alone.

- **Applies when** the app answers or searches a run's questions from routes of its own.
- **Why:** The route answers with your API key, which reaches every connection of your app, and the
  record id in its URL is the user's to change. Without the check, any signed-in user can answer
  another customer's question, or search their company file, by changing one number.
- **Check:** The answer and search routes: the sign-in in front of them, and the check between
  finding the record by its id and reading or answering its question.
- **Wrong:** A route that finds the record by `params[:record_id]` and answers at once, an
  `authorize_question!` that returns without checking, or the routes outside the app's sign-in.
- **Right:** Routes behind the app's sign-in that find the record, check it belongs to the signed-in
  user's account (or that they hold the permission it needs), answer `404` otherwise, and only then
  read the saved question.
- **Docs:** [Answering a question](https://docs.qubesync.com/workflows#answering-a-question),
  [Do it from your code](https://docs.qubesync.com/quickstart#do-it-from-your-code).

#### `handle-every-ending` (major)

Handle every way a run can end: each outcome of `workflow_run.completed`, `workflow_run.failed` and
`workflow_run.cancelled`, with a branch for an outcome you don't know.

- **Applies when** the app starts workflow runs.
- **Why:** A run ends once: `completed` with an `outcome` (a chart's own `cancelled` outcome is a
  completed run), `failed` with an `outcome` and an `error` in words, or `cancelled`, with an
  optional `cancel_reason`. What it changed in QuickBooks stays changed either way, and a record
  left sending after a failure tells your user nothing.
- **Check:** The handlers for the three endings, against the outcomes `qube workflows usage KEY`
  lists.
- **Wrong:** Only `workflow_run.completed` handled, or `outcome` ignored so that a `cancelled`
  outcome reads as success, or a failed run's record left pending.
- **Right:** Branch on `event`, then on `outcome`: store `output` for a success, show `error` for a
  failure and `cancel_reason` for a cancel, and log an outcome the code doesn't know.
- **Docs:** [How a run ends](https://docs.qubesync.com/workflows#how-a-run-ends).

### Stored QuickBooks data

The QuickBooks ids and records your app keeps, and how it finds them again.

#### `ids-keyed-by-connection` (critical)

Key every QuickBooks id you store by the QuBe Sync connection it came from (run events carry it as
`connection_id`) and its list or transaction type: never by the id alone, and never by your record
that keeps the connection (the customer's account or shop).

- **Applies when** the app stores QuickBooks ids (`list_id`, `txn_id`) or QuickBooks records.
- **Why:** QuickBooks makes a `list_id` unique only within one list family of one company file
  (customers, vendors, employees and other names share one; every item type shares another), and a
  `txn_id` within one transaction type: two of your customers' files can hold the same one, and a
  copy of a file (a restored backup, a test copy) holds every one the same. A customer who connects
  another company file gets a new connection, so nothing from the old file may match it.
- **Check:** Every table or model that holds a QuickBooks id: its columns and unique indexes, and
  every lookup or upsert by the id (`find_by`, `where`, `upsert`, `ON CONFLICT`).
- **Wrong:** A lookup or upsert by `list_id` alone, or by the customer's account (or shop) and
  `list_id`, or a unique index on the id alone.
- **Right:** A connection id column beside the QuickBooks id, a list column where one table holds
  several lists (a table that holds one list is keyed by it already), a unique index on the three,
  and every lookup made inside the event's `connection_id`. On the `qube_rails` engine (0.2.0 or
  later), keep each id with `connection.link(record, kind:, qb_id:)` and read it with
  `connection.qb_id_for(record, kind:)` or `connection.find_linked(qb_id, kind:)`: its
  `qube_quickbooks_records` table keys each id by connection and list family (the name lists share
  one ListID sequence, the item types another, every other list its own), so an id is never matched
  across company files or families. The `qubesync` packages' kits keep them the same way:
  `connection.link(record, kind=, qb_id=)` and `connection.qb_id_for(record, kind=)` (PyPI 0.4.0),
  `connection.link(record, { kind, qbId })` and `connection.qbIdFor(record, { kind })` (npm 0.3.0).
- **Docs:** [Create](https://docs.qubesync.com/making-requests#create),
  [Sending your app data](https://docs.qubesync.com/workflows#sending-your-app-data).

#### `stored-id-on-its-own-connection` (critical)

Send a stored QuickBooks id only on the connection it came from; on any other, send the name, or
find the record again.

- **Applies when** the app sends stored QuickBooks ids back (a `list_id` in a reference such as
  `customer_ref`, or a `txn_id`).
- **Why:** On another connection the same id is another company file's record, or none: an invoice
  can land on the wrong customer, or be refused with 3140. After a customer connects another company
  file, their old rows' ids mean nothing there.
- **Check:** Each place that builds a request or a run's input from stored ids (`customer_ref`,
  `item_ref`, `account_ref`, a `txn_id`): which connection the id came from, and which connection
  the call goes out on.
- **Wrong:** A reference filled with the stored `list_id` and no look at which connection the row
  came from.
- **Right:** The `list_id` sent when the row's connection is the one the call goes out on, and
  otherwise the `full_name`, which a workflow such as `add_transaction` looks for in that company
  file.
- **Docs:** [Create](https://docs.qubesync.com/making-requests#create).

#### `upsert-keeps-later-copy` (major)

Upsert each record you import, keeping the copy with the later `time_modified`, and don't let a page
saved later bring back a record that was deleted.

- **Applies when** the app imports or syncs QuickBooks records.
- **Why:** Pages can be saved in any order: by a queue with several workers, after a retried
  delivery, or when a query queued again after a session ended partway starts from page 1.
  `pull_changes` sends its deletions once the last page is answered, which can be before every page
  is saved.
- **Check:** The import's save: whether it creates or upserts, and what it compares before it
  overwrites.
- **Wrong:** A create for each record, so a repeated page duplicates rows; or an update that always
  overwrites, so an older copy undoes a newer one.
- **Right:** The row found by connection, kind and id; left alone when its saved `time_modified` is
  later than the copy's, or when it was deleted after the copy was made; otherwise updated, with the
  copy's `time_modified` saved.
- **Docs:**
  [If the session ends partway](https://docs.qubesync.com/pagination#if-the-session-ends-partway),
  [Sending your app data](https://docs.qubesync.com/workflows#sending-your-app-data).

#### `refer-by-id-not-name` (major)

Once you know a record's `list_id` or `txn_id`, store it on your own record and refer to the
QuickBooks record by it, not by its name.

- **Applies when** the app keeps references to QuickBooks records (customers, items, QuickBooks
  accounts).
- **Why:** A `list_id` is stable for the life of the company file; a `full_name` changes when
  someone renames the record in QuickBooks. Match a name again only when the id stops working: the
  record was deleted, or merged into another, and a request that references it is refused with 3120.
- **Check:** What the app saves after a create, a confirmed match or an import, and what later
  requests send.
- **Wrong:** Only the name saved, and every invoice sent with the customer's `full_name`, or the
  name matched again before every request.
- **Right:** The id from the create's `data`, the confirmed match or the import, saved with its
  connection, and sent from then on.
- **Docs:** [Create](https://docs.qubesync.com/making-requests#create).

#### `store-what-the-ending-carries` (major)

Store what a run's final webhook carries in `output`: the records and ids it made or found, such as
`add_transaction`'s `output.record` and each entry of its `output.refs`; with a `webhook_url`, take
each `records` notification's records as they come.

- **Applies when** the app keeps what its workflow runs make or find.
- **Why:** A run's `output` is built for your app. `add_transaction`'s holds the whole transaction
  with its lines, and `refs`: each reference keyed by where it sits in your `params`
  (`customer_ref`, `invoice_line_add.0.item_ref`), with the `list_id` and `type` of the record it
  was found, chosen or created as. Its `records` notifications say the same for the records that
  change what you hold, as each pass settles them, before the ending. `summary` is the run's own log
  of its steps.
- **Check:** The completed handler: which fields it reads, and what it does with the customers and
  items a run found or created.
- **Wrong:** Ids read out of `summary.changes`, or only the transaction's id kept, so the next run
  has to find its customer and items again.
- **Right:** The transaction's `txn_id` from `output.record` saved on your record, and each
  `output.refs` entry's `list_id` saved on your matching customer or item, keyed by the event's
  `connection_id` and the entry's `type`.
- **Docs:** [How a run ends](https://docs.qubesync.com/workflows#how-a-run-ends).

#### `prune-ended-runs-only` (major)

Prune only runs that have ended, at least a day after they ended, never the QuickBooks ids you keep,
and never the run your next sync's `since` comes from unless you keep that time elsewhere.

- **Applies when** the app deletes its run records.
- **Why:** A run deleted before it ends loses its reference, so the next start makes a new one and
  can add the record twice. A webhook for a deleted run is answered `404`, which QuBe Sync retries
  for hours and then reports. The ids are what say a record is in QuickBooks, and a lost `since`
  makes the next sync a full one.
- **Check:** Any job or task that deletes run rows: the states and ages it deletes, what else it
  deletes with them, and where the next sync's `since` is read from.
- **Wrong:** Runs deleted by age alone (`created_at < 30.days.ago`), whatever their state;
  QuickBooks id rows deleted with them; `since` read from the latest completed sync run, which the
  prune deletes.
- **Right:** Runs `completed`, `failed` or `cancelled` whose end (or, for one that never started,
  last update) is past the retention period and a day old; the ids and the last sync's start kept
  apart from runs.
- **Docs:** [When a delivery fails](https://docs.qubesync.com/webhooks#when-a-delivery-fails).

### QuickBooks behaviour

What QuickBooks Desktop and the Web Connector do that other APIs don't, for an app that sends
requests itself.

#### `timed-out-look-first` (major)

Treat a `timed_out` request, or an `error` with `error_type` `outcome_unknown` or
`response_too_large`, as perhaps applied: queue a query again (a too-large one paged or narrowed),
but look before you send a create or an update again.

- **Applies when** the app queues QuickBooks writes itself (a workflow settles its own).
- **Why:** `timed_out` means QuickBooks received the request but its answer never came back: the
  customer's computer lost its connection, or QuickBooks or the Web Connector was closed, while the
  request was being processed. An `Idempotency-Key` doesn't help here, since the request was queued
  and sent: sending it again with its key only returns it. `outcome_unknown` is the same for a write
  the Web Connector reported an error on mid-request: QuickBooks may have applied it.
  `response_too_large` means QuickBooks ran the request and answered with more than one answer may
  hold, so the answer wasn't kept: a write happened, and a query needs smaller pages or a narrower
  filter, not the same request again.
- **Check:** The `timed_out`, `outcome_unknown` and `response_too_large` branches of the
  request-answer handler (the kits' `perhaps_applied` reader and `timed_out` hook cover all three),
  and any automatic retry.
- **Wrong:** Every `timed_out`, `outcome_unknown` or `response_too_large` request queued again, or
  shown as failed with a Retry button, which can add the invoice twice.
- **Right:** A query first, then the write again only if it didn't happen (a transaction add with an
  `external_guid` of yours can be looked up by exactly that); or the write run as a workflow, which
  settles it.
- **Docs:**
  [When the answer is lost](https://docs.qubesync.com/error_handling#when-the-answer-is-lost),
  [When the outcome is unknown](https://docs.qubesync.com/error_handling#when-the-outcome-is-unknown),
  [When the answer is too large](https://docs.qubesync.com/error_handling#when-the-answer-is-too-large),
  [Lost answers](https://docs.qubesync.com/workflows#lost-answers).

#### `retryable-not-resent` (major)

Don't resend a `retryable` request: show your customer `error.user_message`, and wait for the
answer.

- **Applies when** the app queues QuickBooks requests itself.
- **Why:** The Web Connector couldn't get it into QuickBooks (QuickBooks wasn't running, a dialog
  was open, or the wrong company file was), so nothing was applied, and QuBe Sync keeps trying on
  the Web Connector's next runs, for as long as it takes. A copy sent beside it runs too, once
  QuickBooks is back.
- **Check:** The `retryable` branch, and any retry or timeout logic around queued requests.
- **Wrong:** The request queued again on `retryable`, or after a timer, while the first one still
  waits.
- **Right:** The request marked as waiting on the customer, with `error.user_message` shown, until
  the next webhook for it (the same `page_request_id`, another `state`); and a discard
  (`POST /api/v2/connections/{id}/queued-requests/{request_id}/discard`) to give up on it.
- **Docs:**
  [When QuickBooks is out of reach](https://docs.qubesync.com/error_handling#when-quickbooks-is-out-of-reach),
  [What to do with each `state`](https://docs.qubesync.com/webhooks#what-to-do-with-each-state).

#### `stale-edit-sequence-reapply` (major)

On a `stale_edit_sequence` (3200), re-apply your change on the record in
`response_json.error.current` and resend with its `edit_sequence`, deciding first which value wins
for a field someone else changed too.

- **Applies when** the app sends updates itself.
- **Why:** QuickBooks refuses an update whose `edit_sequence` is out of date and changes nothing,
  but answers with the record as it stands. Resending your fields with the new `edit_sequence`
  without a look quietly overwrites what the other person changed.
- **Check:** The update path's handling of 3200.
- **Wrong:** The same body resent with a fresh `edit_sequence` on every 3200, or a 3200 that just
  fails with no way forward.
- **Right:** `current` compared with what you read: the update resent when nobody else changed a
  field it sets, and otherwise your user asked which wins; the record queried first when `current`
  is missing. Or the `upsert` workflow, which asks with the diff.
- **Docs:**
  [When the record changed after you read it](https://docs.qubesync.com/error_handling#when-the-record-changed-after-you-read-it),
  [Conflicts](https://docs.qubesync.com/workflows#conflicts).

#### `names-unique-across-lists` (major)

Plan for a name another list already holds: names are unique across QuickBooks' customer, vendor,
employee and other-name lists together.

- **Applies when** the app creates customers, vendors, employees, other names or items itself.
- **Why:** Creating a customer whose name a vendor already has fails with error 3100
  (`name_in_use`), and items share one name space across every type. A sync that looks only among
  customers before adding one meets this on real company files.
- **Check:** The create path for list records: what it looks for first, and what it does with 3100.
- **Wrong:** A lookup in the customer list alone before `POST /customers`, and QuickBooks' message
  shown on 3100.
- **Right:** On 3100, the existing record used or another name asked for. The `ensure` workflow
  finds what holds the name and asks your app which.
- **Docs:** [Create](https://docs.qubesync.com/making-requests#create),
  [QuickBooks said no](https://docs.qubesync.com/error_handling#quickbooks-said-no).

#### `ref-number-not-unique` (major)

Key transactions by `txn_id`, not by their number: QuickBooks doesn't keep `ref_number` unique.

- **Applies when** the app stores or matches QuickBooks transactions.
- **Why:** QuickBooks accepts a new invoice with a number another invoice already has, and a voided
  invoice keeps its number, with its amounts at zero. An import keyed on the number merges different
  invoices.
- **Check:** Unique indexes and lookups on a transaction's number.
- **Wrong:** A unique index on the app's invoice number filled from `ref_number`, or imported
  transactions matched by `ref_number`.
- **Right:** Transactions keyed by connection, type and `txn_id`, with `ref_number` kept as data,
  and a clash with your own numbers decided on purpose: keep both, link them by `txn_id`, or skip
  one and log it.
- **Docs:** [Tips](https://docs.qubesync.com/pagination#tips).

#### `modified-date-filters` (minor)

Filter lists with `from_modified_date` and transactions with
`modified_date_range_filter[from_modified_date]`, from the newest `time_modified` you received, sent
back exactly as it came.

- **Applies when** the app syncs changes with modified-date queries itself.
- **Why:** A list query takes the filter directly, and a transaction query takes it nested.
  QuickBooks labels local times with the standard offset even in daylight saving time and reads the
  filter the same way, so its own value finds what it should, while a UTC time from your own clock
  reaches up to an hour further back. A modified-date filter never finds deletions.
- **Check:** The incremental sync's query parameters, and where its starting point comes from.
- **Wrong:** A nested filter on `/customers` or a flat one on `/invoices` (both refused with `400`),
  or the newest `time_modified` converted to UTC before it's sent back.
- **Right:** The newest `time_modified` kept per connection and kind as the string it came as, sent
  back unchanged, with that second's records expected again; or `pull_changes`, which also reports
  what was deleted.
- **Docs:** [Tips](https://docs.qubesync.com/pagination#tips),
  [Query](https://docs.qubesync.com/making-requests#query).

#### `max-returned-is-not-the-whole-list` (major)

Don't take the answer to a query sent with `max_returned` alone as the whole list: leave the paging
parameters out, or send `iterator=true` with it, when you need every record.

- **Applies when** the app queries QuickBooks lists itself.
- **Why:** A query sent with `max_returned` alone gets at most that many records, in one answer, and
  QuickBooks doesn't say whether more matched. What the app concludes about the records it didn't
  get, such as that they're gone, is then wrong on a large company file.
- **Check:** Each list query the app queues: its paging parameters, and what the app does with the
  records the answer doesn't list.
- **Wrong:** `max_returned: 500` with no `iterator`, then every row the answer doesn't list marked
  inactive or deleted.
- **Right:** No paging parameters (pages of 100, a webhook each, finished as `pages-complete-1-to-n`
  says), or `iterator=true` with `max_returned` for another page size; or `pull_changes`, which
  sends every record a page at a time and reports what was deleted.
- **Docs:** [Auto-Pagination](https://docs.qubesync.com/pagination).

#### `warning-is-success` (major)

Treat a `response_received` that carries a `warning` as saved: store the record's id and don't
resend it.

- **Applies when** the app queues QuickBooks writes itself.
- **Why:** A warning is still a success, and `data` is what QuickBooks saved; sent again, it's a
  second record. `530` means a field you sent isn't supported by this QuickBooks, so the record was
  saved without it: `message` names the field.
- **Check:** The `response_received` branch: what it does with `response_json.warning`.
- **Wrong:** Any `warning` treated as a failure, and the request queued again.
- **Right:** The id stored from `data`, `warning.code` and `warning.message` logged or shown, and
  the unsupported field left out next time or kept where QuickBooks does save it, such as a line's
  `memo`.
- **Docs:**
  [QuickBooks said yes, with a warning](https://docs.qubesync.com/error_handling#quickbooks-said-yes-with-a-warning).

#### `branch-on-codes` (minor)

Branch on `error.error_type` and then the status code (`error.error_code`, or
`response_json.error.code`), never on the message text, and show your customer `error.user_message`.

- **Applies when** the app queues QuickBooks requests itself.
- **Why:** The codes are stable things to branch on. `message` is QuickBooks' or the Web Connector's
  raw text, and `user_message` is plain language for your end user: what went wrong and what to do.
- **Check:** The `error` branch of the request-answer handler, and what the customer sees.
- **Wrong:** A branch on whether `message` contains a phrase, or `message` or `debug_message` shown
  to the customer.
- **Right:** A branch on `error_type`, then on the code (3100, 3200 and so on), with `user_message`
  on screen.
- **Docs:** [QuickBooks said no](https://docs.qubesync.com/error_handling#quickbooks-said-no),
  [Where each key lives](https://docs.qubesync.com/error_handling#where-each-key-lives).

### Going live

Production: answers by webhook, secrets kept secret, and the production app ready.

#### `webhooks-not-polling` (major)

Take answers from webhooks, not by polling: `links.self`, and a `GET` of a request or a run, are for
scripts and for looking into a problem.

- **Applies:** always.
- **Why:** A request is answered only when the customer's Web Connector checks in, every 5 minutes
  on a standard connection, so a poll mostly finds nothing. The webhook arrives the moment
  QuickBooks answers, and a run's notifications go only to its `webhook_url`.
- **Check:** Loops and scheduled jobs that read a queued request, `links.self`, a run or
  `links.pages` until its state changes.
- **Wrong:** A loop that sleeps until a request's `state` isn't `waiting`, or a scheduled job that
  reads every waiting request again.
- **Right:** A `webhook_url` on every call, and the work done in the webhook's job; `links.self`
  read only by hand, in a one-off script, or once in the job for a webhook sent with
  `response_xml_omitted`.
- **Docs:**
  [Handling the response](https://docs.qubesync.com/making-requests#handling-the-response),
  [Where to next](https://docs.qubesync.com/quickstart#where-to-next).

#### `no-secrets-in-logs-or-browser` (critical)

Keep the API key and the webhook secret out of logs, error reports, the browser and the repo.

- **Applies:** always.
- **Why:** Either is enough to act as your app: the key reads and writes every connected company
  file, and the secret signs webhooks your endpoint will trust. Logged request headers and committed
  environment files are where they leak.
- **Check:** Logging around the API client and the webhook endpoint (headers, the client's
  configuration), the error reporter's scrubbing, frontend code and committed configuration. Search
  for the variable names; never open the files that hold the values.
- **Wrong:** A request logged with its `Authorization` header, an exception that prints the client's
  configuration, the key handed to a template or the frontend, or a committed `.env`.
- **Right:** Both read from the environment where they're used and logged nowhere, and `.env` in
  `.gitignore`.
- **Docs:** [Do it from your code](https://docs.qubesync.com/quickstart#do-it-from-your-code),
  [Operating it](https://docs.qubesync.com/going-live#operating-it).

#### `production-credentials` (major)

Give production the production app's own API key and webhook secret, and rotate either by adding the
new one before expiring the old.

- **Applies:** always.
- **Why:** Deliveries are signed with every active secret on the app, one `v1` each, so a rotation
  drops nothing when your endpoint accepts any `v1`. Expiring an API key takes effect immediately,
  so deploy its successor first.
- **Check:** Production's configuration, by variable name only, and whether verification accepts any
  one of several `v1` signatures.
- **Wrong:** Production running on the sandbox app's key, or a verifier that reads only the first
  `v1`, so a rotation drops every delivery until the new secret is deployed.
- **Right:** `QUBE_API_KEY` and `QUBE_WEBHOOK_SECRET` from the production app in production, and a
  new secret or key deployed before the old one is expired.
- **Docs:** [Launch checklist](https://docs.qubesync.com/going-live#launch-checklist),
  [Rotate your webhook secret](https://docs.qubesync.com/webhooks#rotate-your-webhook-secret).

#### `production-runs-published` (major)

Publish every workflow your app starts in the production app before launch: production connections
run only published versions.

- **Applies when** the app starts workflow runs.
- **Why:** Sandbox and simulated connections run your latest edits, but a production connection
  always uses the workflow's published version. Promote each workflow from your sandbox app, which
  publishes it there too, and fix any company-file values the promotion warns about.
- **Check:** Code rarely shows this. Note the workflow keys the app starts, and give `can't tell`
  with the check to make (`qube workflows list` on the production app, or its dashboard), unless the
  repo has a setup script that installs and publishes them.
- **Wrong:** A workflow key the app starts that the production app doesn't have, or has only as a
  working copy.
- **Right:** Every key the app starts published in the production app.
- **Docs:** [Launch checklist](https://docs.qubesync.com/going-live#launch-checklist),
  [From sandbox to production](https://docs.qubesync.com/workflow-authoring#from-sandbox-to-production).

#### `public-webhook-url` (major)

In production, make every `webhook_url` your app's public `https` address: never localhost, a
private address, a tunnel or a `qube listen` URL, and never one that redirects.

- **Applies:** always.
- **Why:** QuBe Sync doesn't follow redirects, and a delivery to an address it can't reach, such as
  localhost or a private IP address, isn't sent or retried: it fails at once. A tunnel or relay URL
  from development stops working when the laptop does.
- **Check:** Where production sets `QUBE_WEBHOOK_URL`, or whatever each `webhook_url` is built from,
  and any webhook host written into the code.
- **Wrong:** A `webhook_url` of `http://localhost:3000/webhooks/qube`, a tunnel or `qube listen` URL
  in production configuration, or an `http` URL that redirects to `https`.
- **Right:** The base read from the environment, with production's set to the `https` URL of the
  app's own webhook route.
- **Docs:** [When a delivery fails](https://docs.qubesync.com/webhooks#when-a-delivery-fails),
  [Receiving webhooks in development](https://docs.qubesync.com/webhooks#receiving-webhooks-in-development).
