{
  "name": "app-approvals",
  "title": "App API - Passkey Approvals",
  "description": "Ask one person to approve one exact action with their passkey (Face ID, Touch ID, a security key): the injected approval service, the hosted approve page, single-use consume, and a signed proof any device can verify offline",
  "guid": "sk_plat_aapr",
  "category": "App services",
  "requiredTools": [],
  "content": "# App API - Passkey Approvals\n\nAn app asks **one specific person** to approve **exactly one action**, right now. They get a push notification, open a Gipity-hosted page, see what they are approving, and confirm with a passkey (Face ID, Touch ID, Windows Hello, a security key). The approval is short-lived, single-use, and carries a WebAuthn signature from their passkey, so anything outside Gipity (a device at home, a CI job, a door controller) can verify it itself. Even a compromised server can't forge one.\n\nUse it whenever a human must sign off on a specific change before it runs:\n\n- A phone app that controls a machine at home: every write needs the owner's approval of that exact command.\n- An agent or job about to do something destructive (drop a table, send a payment, delete files).\n- Any \"are you sure, and prove it was you\" step.\n\nDon't build this yourself with WebAuthn in the app's own pages: apps share an origin (`app.gipity.ai`), so a passkey made there could be used by any other app. The approve page runs on the API host, where no app code runs.\n\nFor an automation pausing until its owner clicks approve in an email, a workflow `approval` step is simpler (see [workflow](workflow.md)). Passkey approvals are for when the approval itself must be **provable**.\n\n## The flow\n\n1. A function calls `approval.request({ summary, payload, approver })`. It returns at once with an `id`, the `payloadHash`, the `approveUrl` and `expiresAt`.\n2. The approver gets a Gipity Notify push (or an email if they have no push subscription) linking to `approveUrl`.\n3. They sign in as themselves, read the summary, details and the exact payload, and tap **Approve with passkey** (or **Deny**). The first time, the page has them set up a passkey.\n4. Your code reads `approval.get(id)` (from a function) or `GET /api/<appGuid>/approvals/<id>` (from outside), checks the proof, and calls `consume` exactly once before acting.\n\n## From a function\n\n```yaml\n# gipity.yaml\nfunctions:\n  - name: request-change\n    auth: user\n    services: ['approval']\n  - name: apply-change\n    auth: user\n    services: ['approval']\n```\n\n```js\n// functions/request-change.js\nexport default async function (ctx, { approval }) {\n  const req = await approval.request({\n    summary: 'Set boiler to 65C',                 // shown as the heading, max 200 chars\n    details: 'Kitchen controller, from the app',  // optional, max 4000 chars\n    payload: { cmd: 'set', device: 'boiler', target: 65 }, // the EXACT action, any JSON, max 16 KB\n    approver: 'owner',                            // 'owner' (default) or a user guid of this app\n    ttlSeconds: 300,                              // 30 to 3600, default 300\n  });\n  // req = { id, payloadHash, approveUrl, expiresAt, delivery }\n  return { id: req.id, approveUrl: req.approveUrl, delivery: req.delivery };\n}\n```\n\n```js\n// functions/apply-change.js\nexport default async function (ctx, { approval, crypto }) {\n  const { id, payload } = ctx.body;\n  const a = await approval.get(id);\n  // a = { id, status, summary, payloadHash, expiresAt, approver, resolvedAt, consumedAt, proof }\n  if (a.status !== 'approved') return { ok: false, status: a.status };\n  // Single use: consume compares the hash in constant time and flips approved -> consumed once.\n  const hash = crypto.hash('sha256', canonicalJson(payload));\n  if (!(await approval.consume(id, hash))) return { ok: false, status: 'not consumable' };\n  // ...now do exactly what payload says...\n  return { ok: true };\n}\n```\n\n- `approver` is `'owner'` (the app's owner) or the guid of one of **this app's own users** (`ctx.auth.userGuid` of an app user). An app can't send approvals to arbitrary Gipity accounts.\n- `delivery` always says what happened: `{ channel: 'push' }`, `{ channel: 'email' }` (only when the approver has no push subscription in this app), or `{ channel: 'none', reason }` (`notify: false`, a `gipity test` run, or no way to reach them). Show `approveUrl` yourself when it's `none`. The push or email bills like [app-notify](app-notify.md) and [email](email.md); the approval itself is free.\n- Statuses: `pending`, `approved`, `denied`, `expired` (pending or approved past `expiresAt`), `consumed`. A resolved approval never changes again (the database refuses it), and `consume` returns `false` for anything but an unexpired, approved approval with the matching hash.\n- In `gipity test` (`ctx.isTest`), `request` works and returns a real id, but nothing is pushed or emailed. A test can't approve (that needs a person and a passkey); test the `pending` and `consume -> false` paths.\n\n## Canonical JSON and the payload hash\n\n`payloadHash` is the lowercase hex SHA-256 of the **canonical JSON** of the payload (RFC 8785, JCS): object keys sorted, no whitespace, strings and numbers as `JSON.stringify` writes them. `{ \"b\": 1, \"a\": [true, null] }` becomes `{\"a\":[true,null],\"b\":1}`. A function's own helper:\n\n```js\nfunction canonicalJson(v) {\n  if (v === null || typeof v !== 'object') return JSON.stringify(v);\n  if (Array.isArray(v)) return '[' + v.map(canonicalJson).join(',') + ']';\n  return '{' + Object.keys(v).sort().map(k => JSON.stringify(k) + ':' + canonicalJson(v[k])).join(',') + '}';\n}\n```\n\nPython: the registry's device client ([examples/python](https://github.com/GipityAI/registry/tree/main/examples/python)) has `canonical_json` / `payload_hash` that match the server byte for byte, and `verify_approval` runs every check below. Hand-rolled, `json.dumps(payload, sort_keys=True, separators=(',', ':'), ensure_ascii=False)` matches for ASCII keys, strings, booleans, null and integers. Either way, keep payloads to those (send `\"65.5\"` or `655` tenths, not `65.5`) so every language hashes the same bytes.\n\n## From outside Gipity (devices, CI)\n\n```bash\ncurl -H \"X-Api-Key: $KEY\" https://a.gipity.ai/api/<appGuid>/approvals/<id>\ncurl -X POST -H \"X-Api-Key: $KEY\" -H 'Content-Type: application/json' \\\n  -d '{\"payloadHash\":\"<hex>\"}' https://a.gipity.ai/api/<appGuid>/approvals/<id>/consume\n```\n\n- Auth: a project API key for this app (`gipity key create`), as `X-Api-Key` or `Authorization: Bearer`. A key with resource scopes needs `--approvals read`, which covers both reading and consuming (e.g. `gipity key create front-door --tables commands:read --approvals read`); an unscoped key is the project's full-access key. The approver can also read it with their own sign-in.\n- `GET` returns `{ data: { id, status, summary, details, summaryHash, payloadHash, expiresAt, approver, resolvedAt, consumedAt, proof } }`. `proof` is null until approved, then `{ credentialId, publicKeyJwk, authenticatorData, clientDataJSON, signature, rpId, origin, challenge }` (binary fields base64url).\n- `consume` answers `{ data: { consumed: true } }`, or 409 when the approval isn't approved, has expired, was already consumed, or the hash doesn't match.\n\n## Verify offline (what a device does)\n\nPin the approver's public key once, out of band: take `proof.publicKeyJwk` from their first (test) approval, and check its **fingerprint** with them. The fingerprint is the first 16 hex characters of the key's RFC 7638 JWK thumbprint (sha256 of the required members in sorted order with no whitespace: EC `{\"crv\",\"kty\",\"x\",\"y\"}`, OKP `{\"crv\",\"kty\",\"x\"}`, RSA `{\"e\",\"kty\",\"n\"}`), in groups of four, e.g. `feed 9234 487a e4fe`. The approver's passkey page lists the fingerprint of each of their passkeys, and `gipity approval show` prints the one that signed. Gipity emails the approver whenever a passkey is added to or removed from their approvals.\n\nThen, for every approval, before running the action:\n\n1. Recompute `payloadHash` from the command you are about to run; it must equal the approval's.\n2. Recompute `summaryHash` = lowercase hex sha256 of the canonical JSON of `{\"details\": details or null, \"summary\": summary}` (the words the approver read on the page, from the approval you fetched).\n3. Recompute `challenge = sha256(\"gipity-approval:v2|\" + id + \"|\" + payloadHash + \"|\" + summaryHash + \"|\" + expiresAt)` (raw 32 bytes, UTF-8 input; `expiresAt` exactly as returned, e.g. `2026-11-18T21:40:00.000Z`). This is the WebAuthn challenge the passkey signed.\n4. Decode `clientDataJSON`: `type == \"webauthn.get\"`, `challenge == base64url(challenge)` (no padding), `origin == \"https://a.gipity.ai\"`.\n5. Decode `authenticatorData`: the first 32 bytes equal `sha256(\"a.gipity.ai\")`; the flags byte (offset 32) has UP (`0x01`) and UV (`0x04`) set.\n6. Verify `signature` over `authenticatorData || sha256(clientDataJSON)` with the **pinned** key (ES256: ECDSA P-256 + SHA-256, DER signature; also EdDSA and RS256), and check `proof.publicKeyJwk` is that key.\n7. Check `expiresAt` is in the future, then `consume`. Only act if consume succeeds.\n\n### Test vector\n\nA real approval the platform produced (software P-256 passkey, expired since). Every value recomputes from the ones above it: `payloadHash` from `payload`, `summaryHash` from `summary` + `details`, `challenge` from `id` + the two hashes + `expiresAt`, `fingerprint` from `publicKeyJwk`, and `signature` verifies over `authenticatorData || sha256(clientDataJSON)` with `publicKeyJwk`. A verifier in any language should reproduce each one (with `now` before `expiresAt`). The same proof is the fixture of `gipity approval verify` and of the Python device client.\n\n```json\n{\n  \"id\": \"ap_f6fqnxkk\",\n  \"summary\": \"Set boiler to 65C\",\n  \"details\": \"Kitchen controller\",\n  \"payload\": {\n    \"cmd\": \"set\",\n    \"target\": 65,\n    \"unit\": \"C\"\n  },\n  \"payloadHash\": \"e5077358c282959159ce2019ee996d068d65bd580a323329cb79f4b9f803b7a3\",\n  \"summaryHash\": \"420b7a5c41bf256ff007a819a194866b1b27342218da54a93ad443fc1533ff61\",\n  \"expiresAt\": \"2026-11-18T19:11:03.000Z\",\n  \"challenge\": \"dMRmST9w94cDZTeh61f3f5uI_lL94NcriT5Nko_UXOo\",\n  \"origin\": \"https://a.gipity.ai\",\n  \"publicKeyJwk\": {\n    \"kty\": \"EC\",\n    \"crv\": \"P-256\",\n    \"x\": \"mL_dOR6nPZJ-qrnmkV9duae4wibw_7l6efzJtbeaLCw\",\n    \"y\": \"3zSEhuyO8xQncBqJaesq9VtYFNzn_fRwN9h3lgN5MH8\",\n    \"alg\": \"ES256\"\n  },\n  \"fingerprint\": \"feed 9234 487a e4fe\",\n  \"authenticatorData\": \"N4A08rFf6oofD0rATEu86Zw9VoPTEyUl7LLGA6OQvyEFAAAAAQ\",\n  \"clientDataJSON\": \"eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiZE1SbVNUOXc5NGNEWlRlaDYxZjNmNXVJX2xMOTROY3JpVDVOa29fVVhPbyIsIm9yaWdpbiI6Imh0dHBzOi8vYS5naXBpdHkuYWkiLCJjcm9zc09yaWdpbiI6ZmFsc2V9\",\n  \"signature\": \"MEUCIQCJ0pgK93EnCSGBaXvI9e5Q9jBYpor5Jmd6uLtI4eXYpgIgf7OkMT0Z4ZEyXZqZrIWO5oVYPSTI-k9s7bRj_amuM-g\"\n}\n```\n\n## Passkeys\n\nEach approver enrolls their own passkeys at `https://a.gipity.ai/approvals/passkeys` (an app user adds `?app=<appGuid>`); the approve page links there when they have none. App users' passkeys belong to them in that app only (an app-user approver signs in on the app's own sign-in page, so the app needs `auth: { mode: app }` or `both`). Approving requires user verification (biometric or PIN), and the authenticator's signature counter must move forward, so a cloned key is refused. The page lists each passkey's fingerprint, and adding or removing a passkey emails the person, so a passkey added behind their back doesn't go unnoticed.\n\nThe approve page always shows the summary, the details and the full payload (open, not collapsed) before the passkey prompt, so a misleading summary can't hide a different action; the passkey signs all three.\n\n## CLI\n\n```bash\ngipity approval list                       # includes approvals you are the approver of ([..., passkey])\ngipity approval show <ap_id>               # status, payload hash, expiry, proof + the fingerprint of the passkey that signed\ngipity approval passkeys                   # your passkeys (with fingerprints) + where to add them\ngipity approval verify <ap_id> --payload payload.json --key approver-key.jwk\n```\n\n`verify` runs the offline checks above against the stored proof and exits non-zero if any fails; without `--key` it uses the proof's own key and says the key wasn't pinned.\n\n## Common mistakes\n\n- **Hashing something other than the payload you'll run.** Hash the exact command at the moment you execute it, not the object you sent earlier; that is the whole point.\n- **Acting without `consume`.** An approval is single-use only if you consume it first and act only on `true`.\n- **Polling `approval.get` in a tight loop.** Each call counts toward the function's service-call cap. Have the page or device ask again after the person approves, or poll every few seconds.\n- **Floats in the payload.** Number formatting differs across languages; use integers or strings.\n- **Showing `approveUrl` inside your own page in an iframe.** The approve page refuses to be framed; link to it or open it in a new tab.\n"
}
