@foxnose/sdk 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,6 +15,7 @@ Official TypeScript SDK for the [FoxNose](https://foxnose.net/?utm_source=github
15
15
  - **Four auth strategies** — Anonymous, JWT, Simple key, and Secure (ECDSA P-256)
16
16
  - **Flux introspection** — discover route contracts with `/_router` and `/_schema`
17
17
  - **FoxNose Files** — upload links, analysis, review, policy and short-lived downloads
18
+ - **Outbound webhooks** — endpoints, signing secrets, the event log, redelivery and recovery
18
19
  - **Zero dependencies** — uses only Node.js built-in modules
19
20
  - **Dual output** — ESM and CommonJS builds with full `.d.ts` declarations
20
21
 
@@ -423,6 +424,168 @@ const flux = new FluxClient({ baseUrl, apiPrefix: 'support', auth: new Anonymous
423
424
  const status = await flux.getUploadStatus(path, uploadId, { statusToken });
424
425
  ```
425
426
 
427
+ ## Webhooks
428
+
429
+ FoxNose sends a signed `POST` to your endpoint when a subscribed event happens. Endpoints and the event log run through the Management client. The calls need the `webhooks` permission: `read` to list and read, `create`, `update` for every action on an endpoint, `delete`.
430
+
431
+ ```typescript
432
+ const endpoint = await client.createWebhookEndpoint({
433
+ url: 'https://hooks.example.com/foxnose',
434
+ event_types: ['revision.published', 'resource.deleted'],
435
+ collection_keys: ['mK8nP3tYvBcX'], // omit for every collection
436
+ payload_mode: 'content', // or 'references' (the default)
437
+ });
438
+ storeSecret(endpoint.secret); // also readable later with getWebhookEndpointSecret
439
+
440
+ await client.sendWebhookTestEvent(endpoint.id, 'revision.published');
441
+
442
+ // After an outage: send the failed deliveries of the last day again.
443
+ const since = new Date(Date.now() - 24 * 60 * 60 * 1000);
444
+ let more = true;
445
+ while (more) {
446
+ ({ more } = await client.recoverWebhookDeliveries(endpoint.id, since));
447
+ }
448
+
449
+ const failed = await client.listWebhookEvents({ endpoint: endpoint.id, status: 'dead' });
450
+ for (const event of failed.results) {
451
+ await client.redeliverWebhookEvent(event.id, { endpoint_id: endpoint.id });
452
+ }
453
+ ```
454
+
455
+ | Call | What it does |
456
+ |---|---|
457
+ | `listWebhookEndpoints` / `createWebhookEndpoint` / `getWebhookEndpoint` / `updateWebhookEndpoint` / `deleteWebhookEndpoint` | Endpoints of the environment; a list carries `stats_24h` |
458
+ | `listWebhookEndpointDeliveries` | An endpoint's deliveries, each with the event it carries |
459
+ | `getWebhookEndpointSecret` / `rotateWebhookEndpointSecret` | Read or replace the signing secret |
460
+ | `sendWebhookTestEvent` | A sample event to one endpoint |
461
+ | `recoverWebhookDeliveries` | Send an endpoint's failed deliveries again |
462
+ | `listWebhookEvents` / `getWebhookEvent` / `listWebhookEventAttempts` | The 30-day event log |
463
+ | `redeliverWebhookEvent` | Send a logged event again |
464
+ | `listWebhookEventTypes` | The event-type catalogue with JSON Schemas |
465
+
466
+ `updateWebhookEndpoint` sends only the fields given, and `status: 'active'` resumes a paused or disabled endpoint. `rotateWebhookEndpointSecret` keeps the old secret valid for 24 hours unless you pass `{ expire_previous_now: true }`.
467
+
468
+ The signing `secret` is a credential. The responses that carry it (`createWebhookEndpoint`, `getWebhookEndpointSecret`, `rotateWebhookEndpointSecret`) define it as a non-enumerable property: `console.log`, `JSON.stringify`, `util.inspect` and a spread leave it out, and `response.secret` still returns it. Keep it out of logs.
469
+
470
+ Deliveries follow [Standard Webhooks](https://www.standardwebhooks.com/), so the SDK has no verifier of its own: use a Standard Webhooks library with the endpoint's secret.
471
+
472
+ ```typescript
473
+ // npm install standardwebhooks
474
+ import { Webhook } from 'standardwebhooks';
475
+
476
+ const event = new Webhook(secret).verify(rawBody, headers); // throws on a bad signature
477
+ ```
478
+
479
+ These errors are subclasses of `FoxnoseAPIError`:
480
+
481
+ | Error | Status / code |
482
+ |---|---|
483
+ | `WebhookEndpointNotFoundError` | 404 `webhook_endpoint_not_found` |
484
+ | `WebhookEventNotFoundError` | 404 `webhook_event_not_found` |
485
+ | `WebhookEndpointLimitExceededError` | 409 `limit_exceeded` (20 endpoints per environment) |
486
+ | `WebhookEndpointNotActiveError` | 409 `endpoint_not_active`, with `reason` and `skipped` |
487
+ | `WebhookEndpointNotSubscribedError` | 409 `endpoint_not_subscribed`, with `skipped` |
488
+
489
+ A rejected request body is a `400` `FoxnoseAPIError`: `errorCode` is the code (`invalid_url`, `unknown_event_type`, `unknown_collection`, ...) and `detail` says what is wrong when there is something to say: `field`, and for example `unknown` or `reason`.
490
+
491
+ ## Tenant Tokens
492
+
493
+ Your backend signs a short-lived token per end user; it reaches only that user's records and the shared collections its signing key allows. Make the key pair on your side and register the public key, so the private key never leaves your backend:
494
+
495
+ ```typescript
496
+ import { ManagementClient, generateTenantSigningKey } from '@foxnose/sdk';
497
+
498
+ const pair = generateTenantSigningKey();
499
+ storeSecret(pair.privateKey); // base64 PKCS#8 DER; not enumerable, so JSON.stringify(pair) leaves it out
500
+
501
+ const key = await management.createTenantSigningKey({
502
+ parent_key: 'dw2qC5qRwxuZ', // the parent Flux API key
503
+ anchor_collections: ['a8Lq3vNm2xKp'], // owner collections (keys, not aliases)
504
+ apis: { support: ['read'] },
505
+ public_key: pair.publicKey,
506
+ });
507
+ ```
508
+
509
+ `generate: true` has FoxNose generate the pair instead; the response carries `private_key` once.
510
+
511
+ Sign tokens and send them with the Flux client:
512
+
513
+ ```typescript
514
+ import { FluxClient, TenantTokenAuth, signTenantToken } from '@foxnose/sdk';
515
+
516
+ const mint = () =>
517
+ signTenantToken(privateKey, {
518
+ kid: 'tsk_Q7m2xPz9aLwK',
519
+ environmentKey: '7c9h4pwu',
520
+ sub: 'user-4821', // your id for the end user
521
+ anchors: [['a8Lq3vNm2xKp', 'cust-4821']], // [collection key, record key]
522
+ });
523
+
524
+ const flux = new FluxClient({
525
+ baseUrl: 'https://7c9h4pwu.fxns.io',
526
+ apiPrefix: 'support',
527
+ auth: new TenantTokenAuth(mint),
528
+ });
529
+ ```
530
+
531
+ `TenantTokenAuth` mints a new token 60 seconds before expiry, and when Flux answers `401` with `error="invalid_token"` it mints again and sends the request once more. One instance serves one end user: a token for another signing key, environment, `sub`, anchors or narrowing claims is refused. Do not let `mint` read the user from global or request-local state.
532
+
533
+ With the MCP TypeScript SDK, pass `tenantTokenFetch` as the transport's `fetch`:
534
+
535
+ ```typescript
536
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
537
+ import { tenantTokenFetch } from '@foxnose/sdk';
538
+
539
+ const transport = new StreamableHTTPClientTransport(
540
+ new URL('https://7c9h4pwu.fxns.io/support/_mcp'),
541
+ { fetch: tenantTokenFetch(mint) },
542
+ );
543
+ ```
544
+
545
+ `mint` may be async here. Flux keeps an MCP session across new tokens with the same scope.
546
+
547
+ | Call | What it does |
548
+ |---|---|
549
+ | `listTenantSigningKeys` / `createTenantSigningKey` / `getTenantSigningKey` | Signing keys of the environment, revoked ones included |
550
+ | `updateTenantSigningKey` | Label, per-key limits, or the `not_before` cutoff (`'now'`) |
551
+ | `deleteTenantSigningKey` | Revoke the key |
552
+ | `addTenantTokenRevocation` | Refuse one token (`jti`) or one end user's tokens (`sub`) |
553
+ | `getTenantLimits` / `updateTenantLimits` | Per-user and per-owner rate limits |
554
+
555
+ ## Guardrails
556
+
557
+ ```typescript
558
+ import { getUntrustedFields } from '@foxnose/sdk';
559
+
560
+ await management.updateGuardrailsPolicy('tickets', {
561
+ mode: 'screened',
562
+ overrides: { prompt_attack: 'block' },
563
+ });
564
+ const held = await management.listHeldRevisions('tickets', { status: 'needs_review' });
565
+ await management.releaseHeldRevision('tickets', held.results[0].resource_key, held.results[0].revision_key);
566
+ await management.markResourceReviewed('tickets', 'refund-4821');
567
+
568
+ // On Flux reads: the fields written by end users or agents.
569
+ const record = await flux.getResource('tickets', 'refund-4821');
570
+ const untrusted = getUntrustedFields(record); // e.g. ['body']
571
+ ```
572
+
573
+ `getRecordTrust(record)` reads `_sys.trust` (present when the collection's guardrails mode is `provenance` or `screened` and the Flux API's `trust_delivery` is `metadata`); `getFileTrust(record)` reads a files record's `data.trust`; a record counts as a files record when `data` holds a file block (`file` with `processing`, an object under the collection's own key with `uuid`, `processing` and `tainted_paths`, or an object with `processing` whose `uuid` is `data.trust.upload`) or a `trust` object with source `end_user_upload`. `upload` is the file block's `uuid` and `processing` is `agent_ready` exactly when the block's is (a files record without its file block is malformed), a region's `boxes` are `[x0, y0, x1, y1]` fractions of the page, and a flag's `scope` is `line`, `page` or `region`. `_sys.trust` carries `verdict` and `reasons` together or neither, and lists no paths when its `provenance` is `unknown`. A record without trust metadata says nothing about trust. Trust metadata that is present but malformed, or missing a field the server always sends, throws `MalformedTrustMetadataError`: treat that record as untrusted. Pass untrusted fields to a model as data, never as instructions.
574
+
575
+ A write can declare untrusted fields: `flux.createResource('tickets', data, { provenance: { untrusted_fields: ['body'], source: 'support-inbox' } })`.
576
+
577
+ | Call | What it does |
578
+ |---|---|
579
+ | `getGuardrailsPolicy` / `updateGuardrailsPolicy` | The collection's policy; only set fields are sent, unknown fields throw |
580
+ | `listHeldRevisions` | Retained held revisions, by `status` |
581
+ | `releaseHeldRevision` / `rejectHeldRevision` | Decide on one held revision |
582
+ | `rejectHeldRevisions` / `rescreenHeldRevisions` | Up to 50 at once; each item reports its own outcome |
583
+ | `getGuardrailsUsage` | Review backlog and this hour's screening budget |
584
+ | `listGuardrailsReviewQueue` | Everything waiting for a person in the environment |
585
+ | `getRevisionGuardrails` | The team view of a revision |
586
+ | `markResourceReviewed` | Vouch for a record's published content |
587
+ | `getGuardrailsCatalog` | The wording of findings, states and writers |
588
+
426
589
  ## Authentication
427
590
 
428
591
  The SDK supports four authentication strategies: