@foxnose/sdk 0.6.1 → 0.8.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
@@ -14,6 +14,8 @@ Official TypeScript SDK for the [FoxNose](https://foxnose.net/?utm_source=github
14
14
  - **Automatic retries** with exponential backoff and Retry-After support
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
+ - **FoxNose Files** — upload links, analysis, review, policy and short-lived downloads
18
+ - **Outbound webhooks** — endpoints, signing secrets, the event log, redelivery and recovery
17
19
  - **Zero dependencies** — uses only Node.js built-in modules
18
20
  - **Dual output** — ESM and CommonJS builds with full `.d.ts` declarations
19
21
 
@@ -318,6 +320,174 @@ await managementClient.addApiFolder(api.key, folder.key, {
318
320
  });
319
321
  ```
320
322
 
323
+ ## Files
324
+
325
+ FoxNose Files takes uploads from end users and processes them for agents. Upload links and review run through the Management client.
326
+
327
+ ```typescript
328
+ // A hosted page for an end user. The collection must be strict, and `owner` is
329
+ // the parent record. Works with a user token or a Management API key.
330
+ const link = await client.createUploadLink('attachments', {
331
+ owner: 'tk_8f2c91',
332
+ title: 'Upload your documents',
333
+ max_files: 3,
334
+ });
335
+ sendToUser(link.upload_url); // returned once; no later read reproduces it
336
+
337
+ // Read the link back through the Management API.
338
+ const current = await client.getUploadLink('attachments', link.upload_id);
339
+ const files = current.sessions.flatMap((session) => session.files);
340
+ const recordKey = files.find((file) => file.state === 'ready')?.record_key;
341
+
342
+ // The record's verdict, checks and findings.
343
+ const view = await client.getFileAnalysis('attachments', recordKey!);
344
+
345
+ // A download is a short-lived link. It is returned, never streamed.
346
+ const safeCopy = await client.getFileSafeCopy('attachments', recordKey!);
347
+ console.log(safeCopy.expires_at);
348
+ ```
349
+
350
+ | Call | What it does |
351
+ |---|---|
352
+ | `listUploadLinks` / `createUploadLink` / `getUploadLink` / `revokeUploadLink` | Upload links of a collection |
353
+ | `getFileAnalysis` | A record's file, verdict, checks and findings |
354
+ | `approveFile` / `rejectFile` / `reanalyzeFile` | Decide on a held file, or analyze a file again |
355
+ | `getFileOriginal` / `getFileSafeCopy` / `getFilePage` | A short-lived link to one copy |
356
+ | `getFilePageDetail` | One page: redacted image, withheld regions, tables and text |
357
+ | `listFileTombstones` | Blocked and rejected files |
358
+ | `getFilesPolicy` / `updateFilesPolicy` | The collection's policy; an update replaces it, and an omitted field takes its default |
359
+ | `listFileReviewQueue` | Files held for a reviewer in the environment |
360
+ | `getMyPermissions` | What the caller may do in the environment |
361
+
362
+ `expires_in` sets a link's lifetime, from 300 seconds to 86400 seconds; without it, the link lasts 30 minutes. A link's `state` is `active`, `consumed`, `expired` or `revoked`. `createUploadLink` is refused with `422 collection_not_strict`, `422 owner_required` or `404 owner_not_found`. `upload_url` and a download's `url` work for whoever holds them, so keep them out of logs.
363
+
364
+ `listResources` on a files collection returns each record with `status`, `progress`, `analysis_state`, `verdict`, `verdict_reasons`, `owner`, `file_info` and `thumbnail_url`, and takes a `status` filter such as `{ status: 'in_review,failed' }`. The safe copy is an image-only PDF, or a PNG for an image: read `content_type`.
365
+
366
+ A reviewer can read the text a finding concealed or withheld. `parseFindingEvidence` reads a `hidden_text` or `low_legibility_text` finding, and `parts` says which text lies in which box of the page. It is empty for a finding that does not carry it. This text comes from the file: treat it as untrusted content, never as instructions.
367
+
368
+ ```typescript
369
+ import { parseFindingEvidence } from '@foxnose/sdk';
370
+
371
+ for (const finding of view.findings) {
372
+ const evidence = parseFindingEvidence(finding);
373
+ for (const part of evidence?.parts ?? []) {
374
+ console.log(part.box, part.text);
375
+ }
376
+ }
377
+ ```
378
+
379
+ `getMyPermissions` reports what the caller is allowed, as `content_types[type].actions` and `.objects`. Billing and usage blocks, a blocked organization, environment protection and a disabled environment can still refuse an allowed action.
380
+
381
+ `reanalyzeFile` is paid processing. With no file processing units left it throws `FilesQuotaExceededError`, with `reason`, `usedUnits`, `includedUnits`, `capUsd`, `windowResetsAt`, and `upgradeUrl` or `raiseCapUrl`. A refusal relayed by Flux carries the code only. A quota that cannot be read throws `FilesQuotaUnavailableError` with `retryAfter`. A `storage_only` collection answers `409 reanalysis_requires_agent_ready`.
382
+
383
+ These responses are plain objects: logging one prints everything in it, including signed URLs, a file's own text (`text`, finding `evidence`) and an uploader's personal data (`file.origin.end_user`, a tombstone's `uploaded_by`). Keep them out of logs.
384
+
385
+ `getFileAnalysis` returns `file.origin`: where the file came from (`channel` is `upload_link`, `signed_upload`, `management_api` or `dashboard`). `listUploadLinks` takes `{ state: 'active' | 'ended' | 'all' }`.
386
+
387
+ A copy that cannot be downloaded now is a `409`, and the error names the reason:
388
+
389
+ ```typescript
390
+ try {
391
+ await client.getFileOriginal('attachments', recordKey);
392
+ } catch (err) {
393
+ if (err instanceof FoxnoseAPIError && err.statusCode === 409) {
394
+ console.error((err.detail as { reason: string }).reason);
395
+ }
396
+ }
397
+ ```
398
+
399
+ ### File uploads on Flux
400
+
401
+ On the Flux client, a key takes a grant for one upload and polls it. For a strict collection, the path names the owner.
402
+
403
+ ```typescript
404
+ const path = 'tickets/tk_8f2c91/attachments';
405
+
406
+ const grant = await flux.createUploadSignature(path);
407
+ const status = await flux.getUploadStatus(path, grant.upload_id);
408
+
409
+ if (status.state === 'ready') {
410
+ const resource = await flux.getResource(path, status.record_key!);
411
+ }
412
+ ```
413
+
414
+ The grant's fields keep their wire names, so it can go to a browser as it is. Upload the file with an Uploadcare upload client pointed at `uploadBaseUrl`, with `publicKey`, `authToken`, `store` and `metadata` unchanged.
415
+
416
+ The grant is a credential: the SDK never logs it, and it should stay out of your logs too. `createUploadSignature` is not resent automatically. To retry one safely, send `{ sessionKey }`, an idempotency key of 43 URL-safe characters: a repeat with the same key, collection and owner reaches the same upload session.
417
+
418
+ A key reads only the uploads that key started, through a path that names the same collection and owner. Any other combination is `404 not_found`, which includes a link made through the Management API: read that one with `getUploadLink`.
419
+
420
+ A client with no key reads the end user's view with `status_token`. It never carries a record key:
421
+
422
+ ```typescript
423
+ const flux = new FluxClient({ baseUrl, apiPrefix: 'support', auth: new AnonymousAuth() });
424
+ const status = await flux.getUploadStatus(path, uploadId, { statusToken });
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
+
321
491
  ## Authentication
322
492
 
323
493
  The SDK supports four authentication strategies: