Skip to content

SCR-652: async requests and webhooks (submit/get/wait/callbackStatus, signature verify) - #96

Merged
0xGhostCasper merged 3 commits into
mainfrom
0xGhostCasper/scr-652-async
Nov 18, 2026
Merged

0xGhostCasper merged 3 commits into
mainfrom
0xGhostCasper/scr-652-async

Conversation

@0xGhostCasper

@0xGhostCasper 0xGhostCasper commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Node SDK part of SCR-652 (system-wide async API). It follows research/scr-652-async-api/CONTRACT.md, "SDKs (Node)". The gateway, docs and Python PRs for SCR-652 are separate. This PR matches the Python SDK (scrape-badger/scrapebadger-python#105) on retries, request ids and errors.

What it adds

client.requests

  • submit(path, { method, params, body, callbackUrl, wait, idempotencyKey }) sends Prefer: respond-async[, wait=N], plus X-Callback-URL and Idempotency-Key when given. It returns an AsyncRequest:
    • status: "running" on a 202;
    • status: "completed" when the call finished within wait.
  • A callbackUrl without a wait sends wait=0, so the call answers 202 at once.
  • The submit's HTTP timeout is raised to wait + 15 s when that is above the client timeout.
  • The path may omit /v1. Absolute URLs are refused, so the API key is never sent to another host.
  • No double billing:
    • Without an idempotencyKey, a submit is retried only when the connection failed before anything was sent: ECONNREFUSED, ENOTFOUND, EAI_AGAIN, EHOSTUNREACH, ENETUNREACH, or a connect timeout.
    • A timeout, any other network fault, a 429 or a 5xx is thrown, because after a lost 202 the call may already be running.
    • With a key, the usual retries are safe: a retry answers the existing call with replayed: true.
    • An error answered with Idempotent-Replayed: true is never retried, because it would come back the same every time.
  • get(id): one poll, same signature as before.
  • wait(id, { timeoutMs = 600000 }) polls until the call completes:
    • it pauses as long as Retry-After says (falling back to the body's retry_after_seconds, then 5 s);
    • a finished call's error status is thrown at once, as the mapped SDK error, and not retried (a stored result can't change). Network faults while polling get up to 2 retries;
    • it throws WaitTimeoutError (a TimeoutError with requestId) at the deadline.
  • callbackStatus(id): GET /v1/requests/{id}/callback.

client.account

  • webhookSecret(), rotateWebhookSecret() and webhookDeliveries({ limit }), typed.
  • A 403 full_access_required now throws PermissionDeniedError. That is a subclass of AuthenticationError, which it threw before.
  • The generated getTheWebhookSigningSecret and rotateTheWebhookSigningSecret are unchanged.

Root exports

  • verifyWebhookSignature(secret, rawBody, signature, { sentAt, toleranceS = 300 }):
    • node:crypto HMAC-SHA256 compared with timingSafeEqual;
    • needs exactly sha256= + 64 hex characters;
    • rejects a stale or invalid sentAt, and throws TypeError on a parsed object instead of the raw body;
    • it is the same function that scrapebadger/twitter already exported, and the 3-argument form is unchanged.
  • parseWebhookEvent(rawBody): returns a typed WebhookEvent<T> (the request.completed payload from long-running-requests.mdx).
  • Types: AsyncAccepted, SubmitOptions, WaitOptions, CallbackStatus, WebhookSecret, WebhookDelivery, WebhookDeliveries, WebhookEvent and VerifyWebhookSignatureOptions.
  • The ESM and CJS builds both export all of the above. I checked with require() and import of dist/.

One breaking change: AsyncRequest.status

The contract names AsyncRequest.status "running" | "completed" in both SDKs. In Node, status used to be the HTTP status number.

  • The HTTP status is now statusCode.
  • running still works, and data stays as a deprecated alias of body.
  • TypeScript users comparing status === 202 get a compile error. The CHANGELOG says so.
  • If you would rather avoid the break, the alternative is to keep status: number and name the field state. That would deviate from the contract.

Codegen safety

On main, the monorepo facade generator (sdk/codegen/facade/gen_node.py) would break once the OpenAPI document gains GET /v1/requests/{request_id}/callback:

  • there is no src/requests/ module, so it generates one;
  • it then registers a second requests property in client.ts, and tsc fails with TS2300 duplicate identifier.

I reproduced that locally. This PR prevents it:

  • RequestsClient moves to src/requests/client.ts. agent/client.ts re-exports it, so imports don't change.
  • src/account/client.ts becomes hand-written, with the generated methods inside a BEGIN/END block.

With both new paths added to the spec, the generator now appends getTheCallbackDeliveryStatus and listWebhookDeliveries into those classes, and tsc passes.

To avoid those raw duplicates, add these entries to the monorepo's sdk/codegen/facade/node-v1-surface.json:

"requests.callbackStatus": {"path": "/v1/requests/{request_id}/callback", "sig": " async callbackStatus(requestId: string)", "verb": "get"},
"account.webhookDeliveries": {"path": "/v1/account/webhook-deliveries", "sig": " async webhookDeliveries(options: WebhookDeliveriesOptions = {})", "verb": "get"},
"requests.submit": {"path": null, "sig": " async submit<T = unknown>(path: string, options: SubmitOptions = {})", "verb": "get"},
"requests.wait": {"path": null, "sig": " async wait<T = unknown>(requestId: string, options: WaitOptions = {})", "verb": "get"},
"account.webhookSecret": {"path": null, "sig": " async webhookSecret()", "verb": "get"},
"account.rotateWebhookSecret": {"path": null, "sig": " async rotateWebhookSecret()", "verb": "post"}

account.webhookSecret and account.rotateWebhookSecret must keep "path": null. With their real paths, the generator would stop emitting the published getTheWebhookSigningSecret and rotateTheWebhookSigningSecret. requests.get is already listed and its signature is unchanged.

Release notes

  • Version 0.79.0 → 0.80.0 (package.json, lockfile, src/internal/version.ts). The contract says 0.54.0 → 0.55.0, but npm and main are at 0.79.0.
  • Publishing runs only on a GitHub Release (publish.yml, npm trusted publishing). Merging this does not publish.
  • Since v0.79.0, main also carries the generated rufus client from Generated v2 SDK from OpenAPI spec #94. It has no CHANGELOG line, and a 0.80.0 release would ship it too.

Test plan

  • npm test: 503 tests pass. New: tests/async-requests.test.ts and tests/webhooks.test.ts. They cover:
    • submit: 202 → running, 200 inline → completed, non-JSON body as text, the header forms;
    • get of a completed call, and wait polling on Retry-After and timing out;
    • idempotent replay (Idempotent-Replayed → replayed: true), and which failures are retried with and without a key;
    • wait throwing a stored error without retrying it, and the 403 full_access_required mapping;
    • signature valid, invalid and stale, and parseWebhookEvent.
  • npm run typecheck, npm run lint, npm run build.
  • The README examples typecheck against the source.
  • I ran gen_node.py against this branch with the new paths added to the spec, then prettier, then tsc.

🤖 Generated with Claude Code

kasparasizi1 and others added 3 commits November 18, 2026 22:01
… signature verify)

- requests.submit(path, { method, params, body, callbackUrl, wait, idempotencyKey })
  sends Prefer: respond-async[, wait=N], X-Callback-URL and Idempotency-Key and
  returns an AsyncRequest (running on 202, completed when done within wait).
  Without an idempotency key a timed-out or network-failed submit is thrown,
  not retried (it could run and bill twice); a replayed error is never retried.
- requests.get(id), requests.wait(id, { timeoutMs }) (honours Retry-After,
  throws WaitTimeoutError), requests.callbackStatus(id).
- account.webhookSecret(), rotateWebhookSecret(), webhookDeliveries({ limit }).
- verifyWebhookSignature(secret, rawBody, signature, { sentAt, toleranceS })
  (constant-time, stale sentAt rejected; same function as the twitter export)
  and parseWebhookEvent(rawBody) with the typed request.completed payload.
- AsyncRequest.status is now "running" | "completed"; the HTTP status is
  statusCode; adds headers, body, replayed (data kept as a deprecated alias).
- RequestsClient moves to src/requests/ and the account client gets a
  hand-written part, so SDK codegen appends new spec ops instead of
  generating a clashing requests module.
- 0.80.0, CHANGELOG, README section with a Perplexity example and an
  Express receiver.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… -> PermissionDeniedError

- Without an Idempotency-Key, submit retries only a connection that failed
  before anything was sent (ECONNREFUSED, ENOTFOUND, EAI_AGAIN, EHOSTUNREACH,
  ENETUNREACH, connect timeout). A timeout, other network faults, 429 and
  5xx are thrown: after a lost 202 the call may already be running.
- wait() throws a finished call's error status at once instead of retrying
  it (a stored result answers the same every time); network faults while
  polling are still retried.
- BaseClient: RequestOptions.retry ("all" | "transport" | "connect")
  replaces the boolean idempotent option.
- 403 full_access_required (webhook secret / delivery log) maps to
  PermissionDeniedError, a subclass of the AuthenticationError it was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@0xGhostCasper
0xGhostCasper merged commit 986f789 into main Nov 18, 2026
4 checks passed
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.

2 participants