Skip to content

fix(id-verification): record the charge before the client can make it - #949

Merged
thinkclay merged 2 commits into
mainfrom
fix/id-verification-record-before-charge
Oct 2, 2026
Merged

thinkclay merged 2 commits into
mainfrom
fix/id-verification-record-before-charge

Conversation

@thinkclay

Copy link
Copy Markdown
Contributor

First fix from the #948 audit — the one that turns an unrecoverable charge into a recoverable one.

POST /request created a Stripe PaymentIntent, returned the client_secret, and wrote nothing. The payment_transactions row was written at the very end of /confirm, after:

  1. paymentIntents.retrieve + succeeded check
  2. ensureCanRequestForWorker — can throw
  3. createPersonaInquiry — external API call, can throw
  4. insert id_verifications — can fail, returns 500
  5. insert payment_transactions — unchecked await

Any failure at 2, 3 or 4 left a paid customer with no database trace at all. Persona being down was enough.

And stripe-webhook could not have recovered it — it looks rows up by stripe_payment_intent_id, so with no row it logs "payment transaction not found" and returns. The only record of the money would have been in Stripe.

Step 5 was fragile even on the happy path: an unchecked await, so a failed insert still returned 200 with no financial record.

The row now exists before the money can move

/request inserts it immediately after creating the intent, and fails the request if that insert fails rather than returning the client_secret.

That refusal is the whole point. With no client_secret the intent is never confirmed, so no charge happens — which makes "there is a row for every charge" an invariant rather than a best effort. An unrecorded charge is no longer reachable through this route.

status defaults to 'pending', and the permission check already runs before the intent is created, so nothing fallible now sits between the charge and its record.

/confirm advances rather than inserting again

It updates the row by stripe_payment_intent_id and links id_verification_id. Matching on the intent id keeps a repeated /confirm idempotent — the existing check above returns early on the happy path, but a retry racing it lands here.

If no row is found — an intent created before this change, or by another path — it still inserts, tagged stage: "confirmed-backfill". The goal is that money is never unrecorded, not that /request always wins the race.

A failure to advance is logged, not fatal: the verification exists and the customer has paid, so failing the request would be worse than a ledger row the webhook or a reconciliation sweep can still fix. That replaces the unchecked await that returned 200 regardless.

Scope

Deliberately does not address the rest of #948 — the deposit path still charges without crediting, success fees still depend on the client calling /confirm, and there is still no reconciliation job. Stripe remains unconfigured in all three environments, so nothing is live either way.

Verification

  • deno fmt --check and deno lint clean on the file (this directory is fmt-enforced in CI, unlike stripe-webhook)
  • Edge-function ratchet unchanged: api 334, same as baseline — no new type errors
  • pnpm prepush green

Schema checked against prod before writing the insert: id_verification_id, organization_id and user_id are all nullable, and status defaults to 'pending'.

🤖 Generated with Claude Code

…#948)

`POST /request` created a Stripe PaymentIntent, returned the client_secret,
and wrote nothing. The `payment_transactions` row was written at the very END
of `/confirm`, after:

  1. paymentIntents.retrieve + succeeded check
  2. ensureCanRequestForWorker   — can throw
  3. createPersonaInquiry        — external API call, can throw
  4. insert id_verifications     — can fail, returns 500
  5. insert payment_transactions — unchecked await

Any failure at 2, 3 or 4 left a paid customer with no database trace at all.
Persona being down was enough. And `stripe-webhook` could not have recovered
it: it looks rows up by `stripe_payment_intent_id`, so with no row it logs
"payment transaction not found" and returns. The only record was in Stripe.

Step 5 was fragile even on the happy path — an unchecked `await`, so a failed
insert still returned 200 with no financial record.

## The row now exists before the money can move

`/request` inserts it immediately after creating the intent, and **fails the
request if that insert fails** rather than returning the client_secret. That
is the part that makes it an invariant instead of a best effort: with no
client_secret the intent is never confirmed, so no charge happens. An
unrecorded charge is no longer reachable through this route.

`status` defaults to 'pending'; the permission check already runs before the
intent is created, so nothing fallible sits between the charge and its record.

## /confirm advances rather than inserting again

It now updates the row by `stripe_payment_intent_id` and links
`id_verification_id`. Matching on the intent id keeps a repeated /confirm
idempotent — the `existing` check above returns early on the happy path, but a
retry racing it lands here.

If no row is found — an intent created before this change, or by another path
— it still inserts, tagged `stage: "confirmed-backfill"`. The goal is that
money is never unrecorded, not that /request always wins the race.

A failure to advance is logged rather than fatal: the verification exists and
the customer has paid, so failing the request would be worse than a ledger row
the webhook or a reconciliation sweep can still fix. That replaces the
unchecked await, which returned 200 regardless.

Does not address the rest of #948 — the deposit path still charges without
crediting, success fees still depend on the client calling /confirm, and there
is still no reconciliation job. This is the one that turned an unrecoverable
charge into a recoverable one.

deno fmt and deno lint clean; edge-function ratchet unchanged at api 334.

Co-Authored-By: Claude Opus 5 <[email protected]>
thinkclay added a commit that referenced this pull request Oct 2, 2026
…gger the job it breaks (#950)

#936 bumped the Supabase CLI 2.117.0 -> 2.118.0. 2.118.0 includes
"rewrite managed local stack runtime" (supabase/cli#6440), and after it the
api-tests step that runs `supabase gen types typescript --local` fails:

    no owned schemas found in /tmp/types-fresh.ts — the format changed,
    or the file is empty

scripts/types-owned-schemas.mjs matches top-level schema blocks with
`/^ {2}(\w+): \{$/`, so a change in the generated file's shape breaks it.

## How this was established

It surfaced on #949, an unrelated id-verification change, and read as that
PR's fault. Two runs failed identically at the same step. A control re-run of
main's own api-tests at 21b4dd3 — which predates the bump — passed, which
first looked like it convicted #949.

It did not: that control commit is nine commits behind, and the gap contains
#936. Nothing schema-related changed in between, and a TypeScript route file
cannot affect a generator that introspects the database.

## Why nobody saw it on main

api-tests is path-filtered to `functions/api/**`, migrations, `types.ts` and a
couple of scripts. A CLI bump touches none of those, so the job has not run on
main since 2026-10-01 — before the bump. main has been broken and silent.

So the filter is widened: `pnpm-workspace.yaml`, `pnpm-lock.yaml` and
`scripts/types-owned-schemas.mjs` now trigger it. The job shells out to the
Supabase CLI; a change to the pin that selects that CLI is a change to the job.

This is the same shape as #929 — a gate that could not run on the thing it
guards — and the third time this session a path filter has hidden a broken
check from itself. The cost is CI minutes on dependency PRs, which is the
trade I declined in #929 for a cheap ratchet and accept here for a job that
boots a full stack and is the only HTTP coverage the api has.

## Pin, not adapt

Reverting is the conservative move and restores green now. Whether 2.118's
`gen types` output is a deliberate format change or a side effect of the stack
rewrite wants its own look, with the job actually run against it — the comment
at the pin says so.

Not independently reproduced locally: no stack was running and this checkout
has 2.116.0, so the mechanism is inferred from the release contents, the error
text and the control. If this PR goes green, that is the proof — it touches
`pnpm-workspace.yaml`, which the widened filter now makes run api-tests.

Co-authored-by: Claude Opus 5 <[email protected]>
@github-actions

github-actions Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

📊 Performance Benchmark Results


@thinkclay
thinkclay merged commit dc9b5ce into main Oct 2, 2026
15 checks passed
@thinkclay
thinkclay deleted the fix/id-verification-record-before-charge branch October 2, 2026 19:30
thinkclay added a commit that referenced this pull request Oct 2, 2026
…ions writes (#948)

Both writes were bare `await`s. #948 item 6.

## The intent-creation insert (was line 429)

Two holes, not one:

  * the error was discarded, so a failed insert still returned a
    `client_secret` and the customer could pay with nothing recorded
  * it was gated on `createdNewSuccessFee || createdNewIntent`, so the
    RETRIEVE branch — a second call for an intent that already exists —
    skipped it entirely. If the first call's insert had failed, the retry
    handed out a secret for an intent that still had no row.

Now unconditional and idempotent. `payment_transactions` has a unique index on
`stripe_payment_intent_id`
(`payment_transactions_stripe_payment_intent_id_key`, confirmed against prod),
so an upsert with `ignoreDuplicates` is a no-op when the row is already there
and repairs the gap when it is not.

And it fails the request rather than returning the secret. With no
client_secret the intent is never confirmed, so no money moves — the same
invariant #949 established for id-verification: there is a row for every
charge, not usually a row.

## The confirmation update (was line 541)

This is the one that records a CONFIRMED payment, and a failure returned 200
with the ledger quietly disagreeing with `success_fees` about whether the money
arrived.

Left non-fatal — the fee is already marked `upfront_paid` above and the
customer has paid, so failing here would be worse than a row that lags, which
the webhook or a reconciliation sweep can still settle — but it now logs with
the intent id instead of vanishing.

Verified: `deno fmt --check` and `deno lint` clean, edge-function ratchet
unchanged at api 334, prepush green. No behaviour change on the happy path —
the upsert writes exactly what the insert did.

Remaining in #948: deploy and extend stripe-webhook for success_fees (item 3),
and a reconciliation job for rows left pending (item 5). Those two are really
one piece of work, and this change is what makes a reconciliation sweep
possible — it guarantees the rows exist to sweep.

Co-Authored-By: Claude Opus 5 <[email protected]>
thinkclay added a commit that referenced this pull request Oct 2, 2026
…ions writes (#948) (#958)

Both writes were bare `await`s. #948 item 6.

## The intent-creation insert (was line 429)

Two holes, not one:

  * the error was discarded, so a failed insert still returned a
    `client_secret` and the customer could pay with nothing recorded
  * it was gated on `createdNewSuccessFee || createdNewIntent`, so the
    RETRIEVE branch — a second call for an intent that already exists —
    skipped it entirely. If the first call's insert had failed, the retry
    handed out a secret for an intent that still had no row.

Now unconditional and idempotent. `payment_transactions` has a unique index on
`stripe_payment_intent_id`
(`payment_transactions_stripe_payment_intent_id_key`, confirmed against prod),
so an upsert with `ignoreDuplicates` is a no-op when the row is already there
and repairs the gap when it is not.

And it fails the request rather than returning the secret. With no
client_secret the intent is never confirmed, so no money moves — the same
invariant #949 established for id-verification: there is a row for every
charge, not usually a row.

## The confirmation update (was line 541)

This is the one that records a CONFIRMED payment, and a failure returned 200
with the ledger quietly disagreeing with `success_fees` about whether the money
arrived.

Left non-fatal — the fee is already marked `upfront_paid` above and the
customer has paid, so failing here would be worse than a row that lags, which
the webhook or a reconciliation sweep can still settle — but it now logs with
the intent id instead of vanishing.

Verified: `deno fmt --check` and `deno lint` clean, edge-function ratchet
unchanged at api 334, prepush green. No behaviour change on the happy path —
the upsert writes exactly what the insert did.

Remaining in #948: deploy and extend stripe-webhook for success_fees (item 3),
and a reconciliation job for rows left pending (item 5). Those two are really
one piece of work, and this change is what makes a reconciliation sweep
possible — it guarantees the rows exist to sweep.

Co-authored-by: Claude Opus 5 <[email protected]>
thinkclay added a commit that referenced this pull request Oct 2, 2026
…talled rows (#948) (#960)

Items 3 and 5 of #948, plus the reason neither could have worked.

core.payment_transactions has carried a set_updated_at trigger and no
updated_at column since migration 095. core.set_updated_at() assigns
NEW.updated_at, so every UPDATE on the payment ledger raised
`record "new" has no field "updated_at"` and rolled back: no row could
ever leave its 'pending' default, in any environment. Invisible because
the table is empty (Stripe unconfigured, #928) and because the /confirm
handlers discarded that error until #949 and #958. Migration 361 adds
the column; check-migrations.mjs gains a fourth invariant so the shape
cannot return.

stripe-webhook was in no deploy list, so no environment had it, and it
only touched payment_transactions — a paid upfront fee left success_fees
at 'pending' while the ledger said 'succeeded'. The ledger write and the
paid-state advance now share _shared/payments/settlement.ts, which also
backs the new payments-reconcile sweep, so a missed webhook settles
identically to a delivered one.

payments-reconcile asks Stripe about anything pending past a threshold
and applies the answer. pg_cron every 10 minutes via migration 362,
following 337's Vault pattern. It mirrors Stripe and never creates,
confirms or cancels anything: non-terminal intents stay pending, and an
intent absent at Stripe is logged rather than given a terminal status.

Only a success moves paid-state. A decline is retryable against the same
intent, so flipping the fee to 'failed' would end a live sale; the
attempt is recorded on the ledger row instead.

tests/routers/payments-settlement.test.ts covers all of it against the
real database and is in GATED.txt — 9 passed. It is the test that found
the missing column.

Co-authored-by: Claude Opus 5 <[email protected]>
thinkclay added a commit that referenced this pull request Oct 5, 2026
…ot after (#948) (#965)

Item 2 of #948, the last one open.

/confirm called createPersonaInquiry between a successful charge and the
id_verifications insert that records it. persona_inquiry_id is NOT NULL,
so Persona being down did not degrade the flow — it made the row
unwritable: the customer had paid, no verification could be created
without an inquiry, a retried /confirm called Persona again and failed
again, and once the client lost the payment intent id nothing could
finish the job. #949 made the charge recoverable; the verification was
not.

/request now mints the inquiry before the Stripe intent exists and
carries its id on the intent metadata and the ledger row, so /confirm
makes no network call on the normal path. Persona down means /request
returns 503 with nothing charged.

Chosen over "record the payment first and retry the inquiry" because
persona_inquiry_id is NOT NULL: that route needed a nullable-column
migration, a new status, a retry sweep and another cron. This needs
none. resolvePersonaInquiry keeps a fallback chain — intent metadata,
then ledger metadata, then a fresh inquiry — so intents in flight when
this deploys still complete.

tests/routers/id-verification-rest.test.ts asserts the inquiry stored on
id_verifications is the one that existed before the charge was possible.
Measured green, then red on the pre-fix route with the tests unchanged
(`ledger metadata carries no persona_inquiry_id`), then green again. It
is not in GATED.txt: it needs STRIPE_MOCK_MODE inside the function
runtime and `supabase start` has no --env-file, so CI cannot give it
that. The file carries the command it was verified with; wiring the gate
is #937.

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant