@assinafy/cli 2.0.3 → 2.1.2

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.
@@ -32,7 +32,7 @@ const client = AssinafyClient.create(
32
32
  );
33
33
  ```
34
34
 
35
- For the sandbox, add `baseUrl: 'https://sandbox.assinafy.com.br/v1'`. Create an unauthenticated client only for public or signer-access-code endpoints:
35
+ For the sandbox, add `baseUrl: 'https://sandbox.assinafy.com.br/v1'`. Create an unauthenticated client for public, OAuth bootstrap, or signer-access-code endpoints:
36
36
 
37
37
  ```ts
38
38
  const publicClient = new AssinafyClient({ allowUnauthenticated: true });
@@ -44,19 +44,19 @@ const publicClient = new AssinafyClient({ allowUnauthenticated: true });
44
44
 
45
45
  | Field | Type | Behavior |
46
46
  | --- | --- | --- |
47
- | `apiKey` | `string` | Preferred credential; sent as `X-Api-Key`. |
48
- | `token` | `string` | JWT fallback; sent as `Authorization: Bearer`. `apiKey` wins when both are set. |
47
+ | `apiKey` | `string` | Direct owner credential; sent as `X-Api-Key`. |
48
+ | `token` | `string` | OAuth access token or user JWT; sent as `Authorization: Bearer`. `apiKey` wins when both are set. |
49
49
  | `accountId` | `string` | Default for account-scoped methods; most methods also accept an override. |
50
50
  | `baseUrl` | `string` | HTTPS URL; defaults to `https://api.assinafy.com.br/v1`. Redirects are rejected. |
51
- | `allowInsecureHttp` | `boolean` | Explicit opt-in for isolated local development only. |
51
+ | `allowInsecureHttp` | `boolean` | Opt-in for a plaintext `http://` base URL. Restricted to loopback hosts (`localhost`, `127.0.0.0/8`, `[::1]`); any other host is rejected even with this enabled, so the API key can never travel in cleartext. |
52
52
  | `timeout` | `number` | Request timeout in milliseconds; default `30_000`. |
53
53
  | `logger` | `Logger` | Optional `debug`/`info`/`warn`/`error` functions; otherwise no-op. |
54
- | `allowUnauthenticated` | `boolean` | Permit construction without `apiKey`/`token`; use only for public and signer-code flows. |
54
+ | `allowUnauthenticated` | `boolean` | Permit construction without `apiKey`/`token`; use only for public, OAuth bootstrap, and signer-code flows. |
55
55
  | `webhookSecret` | `string` | Used only by the experimental `webhookVerifier`; see [Webhook verification](#webhook-verification-experimental). |
56
56
 
57
57
  | API | Result |
58
58
  | --- | --- |
59
- | `new AssinafyClient(options: AssinafyClientOptions)` | Client with `documents`, `signers`, `workspaces`, `assignments`, `webhooks`, `templates`, `tags`, `auth`, `fields`, `users`, `signerDocuments`, and `webhookVerifier`. |
59
+ | `new AssinafyClient(options: AssinafyClientOptions)` | Client with `documents`, `signers`, `workspaces`, `assignments`, `webhooks`, `templates`, `tags`, `auth`, `oauth`, `fields`, `users`, `signerDocuments`, and `webhookVerifier`. |
60
60
  | `AssinafyClient.create(apiKey, accountId, options?)` | Convenience constructor. |
61
61
  | `AssinafyClient.fromConfig(config: ClientConfigInput)` | Accepts snake-case or camel-case configuration keys. |
62
62
  | `client.uploadAndRequestSignatures(options)` | Uploads a PDF, optionally waits for processing, creates/reuses signers, and creates a virtual assignment; returns `IUploadAndRequestSignaturesResult`. |
@@ -87,7 +87,24 @@ const publicClient = new AssinafyClient({ allowUnauthenticated: true });
87
87
  }
88
88
  ```
89
89
 
90
- It resolves to `{ document: IDocumentUploadResponse; assignment: IAssignment; signer_ids: string[] }`. A phone-only signer defaults to WhatsApp verification and notification unless those controls are supplied explicitly. The workflow is not transactional: if a later step fails, previously created documents/signers remain available for caller-directed cleanup.
90
+ It resolves to `{ document: IDocumentUploadResponse; assignment: IAssignment; signer_ids: string[] }`. A phone-only signer defaults to WhatsApp verification and notification unless those controls are supplied explicitly.
91
+
92
+ The workflow is not transactional. Once the upload succeeds, any later failure rejects with a `PartialWorkflowError` naming everything that already exists, so cleanup or a resume never needs to search the workspace for orphans. Nothing is deleted automatically. Signer IDs include reused records; never delete them as an automatic rollback. Validate local signer options before uploading, then inspect the document state before resuming a partially completed workflow.
93
+
94
+ ```ts
95
+ import { PartialWorkflowError } from '@assinafy/cli/api';
96
+
97
+ try {
98
+ await client.uploadAndRequestSignatures({ source, signers });
99
+ } catch (error) {
100
+ if (error instanceof PartialWorkflowError) {
101
+ console.error(error.message, error.cause); // original API/validation failure
102
+ console.error({ documentId: error.documentId, signerIds: error.signerIds });
103
+ // Inspect before resuming: these signers may be shared with existing documents.
104
+ }
105
+ throw error;
106
+ }
107
+ ```
91
108
 
92
109
  ## Documents (`client.documents`)
93
110
 
@@ -175,7 +192,7 @@ Assignment payload:
175
192
  }
176
193
  ```
177
194
 
178
- `buildAssignmentPayload(payload, options?)` is exported for callers that need the same normalization. `create` requires at least one signer and enforces the documented one-digital-certificate-signer-per-step rule. The estimate schema has no `step`, so `estimateCost` does not apply that create-only rule and permits zero signers for `collect`. Assignment list params are pagination plus the live-verified `sort?: 'created_at' | '-created_at'`; the runtime endpoint requires the SDK's `accountId` query even though the published parameter table omits it. The sandbox ignored an assignment `search` query, so the SDK does not expose it.
195
+ `buildAssignmentPayload(payload, options?)` is exported for callers that need the same normalization. It resolves synchronously to the JSON assignment body above; no HTTP call occurs. Options are `{ allowSignersWithoutId?: boolean; allowEmptySigners?: boolean; skipDigitalCertificateStepValidation?: boolean }`, all false by default. The first two support cost estimation; the third bypasses signing-order and certificate-step checks for estimates. `allowEmptySigners` applies only to `collect`. `create` requires at least one signer, enforces complete contiguous signing steps from 1 when supplied, and requires each digital-certificate signer to be alone in its step. The estimate schema has no `step`, so `estimateCost` does not apply that create-only rule and permits zero signers for `collect`. Assignment list params are pagination plus the compatible `sort?: 'created_at' | '-created_at'`; the runtime endpoint requires the SDK's `accountId` query even though the published parameter table omits it. Assignment `search` is unsupported and rejected locally.
179
196
 
180
197
  ## Signers (`client.signers`)
181
198
 
@@ -188,7 +205,7 @@ Assignment payload:
188
205
  | `delete(signerId, accountId?)` | [`DELETE /accounts/{accountId}/signers/{signerId}`](./api-reference.md#delete-signer) | `IEmptyResult` (`unknown[]`) |
189
206
  | `findByEmail(email, accountId?)` | SDK helper over `list({ search: email })` | `ISigner | null` |
190
207
 
191
- Create payload: `{ full_name: string; email?; whatsapp_phone_number?; phone?; cpf?; metadata? }`. Update payload: `{ full_name?; email?; whatsapp_phone_number?; phone?; government_id?; cpf? }`. `phone`, create-time `cpf`/`metadata`, and update-time `cpf` are compatibility extensions; new integrations should use the published fields. Creation is idempotent by exact case-insensitive email when email is supplied; full-name-only signers are valid. List params support published `search` and live-verified `sort?: 'full_name' | '-full_name'`; ignored sort fields are rejected locally.
208
+ Create payload: `{ full_name: string; email?; whatsapp_phone_number?; phone?; cpf?; metadata? }`. Update payload: `{ full_name?; email?; whatsapp_phone_number?; phone?; government_id?; cpf? }`. `phone`, create-time `cpf`/`metadata`, and update-time `cpf` are compatibility extensions; new integrations should use the published fields. Creation is idempotent by exact case-insensitive email when email is supplied; full-name-only signers are valid. List params support published `search` and compatible `sort?: 'full_name' | '-full_name'`; ignored sort fields are rejected locally.
192
209
 
193
210
  ## Signer-side flows (`client.signerDocuments`)
194
211
 
@@ -265,7 +282,7 @@ Notification counters can overlap when a request uses multiple delivery channels
265
282
  | `getNotificationPreferences()` | [`GET /users/self/notification-preferences`](./api-reference.md#get-my-notification-preferences) | `INotificationPreferences` |
266
283
  | `updateNotificationPreferences(payload)` | [`PUT /users/self/notification-preferences`](./api-reference.md#update-my-notification-preferences) | `INotificationPreferences` |
267
284
 
268
- `IUserSelfResponse` accepts the published user object and the sandbox-observed `{ user, accounts }` envelope. Preference payloads are a non-empty partial mapping of the exported `NOTIFICATION_PREFERENCE_CODES` to booleans. The production OpenAPI publishes these routes; a lagging sandbox deployment may return route-level 404s for statistics/preferences.
285
+ `IUserSelfResponse` accepts the published user object and the compatible `{ user, accounts }` envelope. Preference payloads are a non-empty partial mapping of the exported `NOTIFICATION_PREFERENCE_CODES` to booleans. The production OpenAPI publishes these routes; a lagging sandbox deployment may return route-level 404s for statistics/preferences.
269
286
 
270
287
  ## Authentication (`client.auth`)
271
288
 
@@ -283,6 +300,22 @@ Notification counters can overlap when a request uses multiple delivery channels
283
300
 
284
301
  Login/social/reset bootstrap calls can use an unauthenticated client. The published authenticated user endpoints permit either a bearer JWT or `X-Api-Key`; use the credential type appropriate to the account and endpoint policy.
285
302
 
303
+ ## OAuth (`client.oauth`)
304
+
305
+ | SDK method | HTTP operation / behavior | Resolves to |
306
+ | --- | --- | --- |
307
+ | `metadata()` | [`GET /.well-known/oauth-protected-resource`](./api-reference.md#oauth-20-protected-resource-metadata), at the API origin outside `/v1` | `IOAuthProtectedResource` |
308
+ | `discovery(issuer)` | `GET {issuer}/.well-known/oauth-authorization-server`; requires HTTPS and matching issuer | `IOAuthAuthorizationServer` |
309
+ | `authorize({ clientId, redirectUri, scopes })` | Discover resource/server and generate a fresh S256 verifier, state, and optional OIDC nonce | `IOAuthAuthorizationRequest` |
310
+ | `exchangeCode(callbackUrl, request, clientSecret?)` | Validate callback URI/state/issuer and submit the authorization code | `IOAuthTokenResponse` |
311
+ | `token(payload)` | [`POST /oauth/token`](./api-reference.md#exchange-a-code-or-refresh-token-for-an-access-token), with code or refresh grant | `IOAuthTokenResponse` |
312
+ | `revoke(payload)` | [`POST /oauth/revoke`](./api-reference.md#revoke-a-token) | `void` |
313
+ | `userinfo()` | `GET /oauth/userinfo`, using the current OAuth bearer token with `openid` | `IOAuthUserInfo` |
314
+
315
+ All request types, full payload examples and response shapes are in the [OAuth guide](./oauth-guide.md). `IOAuthTokenPayload` is a discriminated union: code exchange requires `code`, `redirect_uri`, and `code_verifier`; refresh requires `refresh_token`; both require `client_id` and optionally accept `client_secret` and `resource`. `IOAuthRevokePayload` requires `token` and `client_id`, with optional `client_secret` and `token_type_hint`.
316
+
317
+ Metadata, discovery, token, and revoke calls remove owner headers. UserInfo uses the configured credential; construct the client with `token` for OAuth. OAuth bodies have no Assinafy envelope. The SDK returns credentials to the caller and does not persist, retry, or automatically refresh them. Store authorization requests in a single-use session; serialize refreshes across workers and atomically save the rotated result. Use an OIDC library to validate ID tokens before relying on identity claims.
318
+
286
319
  ## Fields (`client.fields`)
287
320
 
288
321
  | SDK method | HTTP operation | Resolves to |
@@ -352,7 +385,7 @@ interface ITemplateDetailsResponse {
352
385
 
353
386
  `downloadPage` returns the raw JPEG response as a Node.js `Buffer`; it does not unwrap JSON.
354
387
 
355
- Template list params support pagination, published `search`, and live-verified `sort?: 'name' | '-name'`; ignored sort fields are rejected locally. `ITemplatePage` contains document page dimensions/URL plus typed `ITemplateField[]` entries (`id`, `field_id`, `role_id`, `label`, `display_settings`, and timestamps). Template document creation accepts `editor_fields?: Array<{ field_id: string; value: string }>`.
388
+ Template list params support pagination, published `search`, and compatible `sort?: 'name' | '-name'`; ignored sort fields are rejected locally. `ITemplatePage` contains document page dimensions/URL plus typed `ITemplateField[]` entries (`id`, `field_id`, `role_id`, `label`, `display_settings`, and timestamps). Template document creation accepts `editor_fields?: Array<{ field_id: string; value: string }>`.
356
389
 
357
390
  ## Webhooks (`client.webhooks`)
358
391
 
@@ -365,16 +398,18 @@ Template list params support pagination, published `search`, and live-verified `
365
398
  | `listDispatches(params?, accountId?)` | [`GET /accounts/{accountId}/webhooks`](./api-reference.md#list-webhook-deliveries) | `PaginatedResult<IWebhookDispatch>` |
366
399
  | `retryDispatch(dispatchId, accountId?)` | [`POST /accounts/{accountId}/webhooks/{dispatchId}/retry`](./api-reference.md#retry-webhook-delivery) | `IWebhookDispatch` |
367
400
 
368
- Registration payload: `{ url: string; email: string; events?: string[]; is_active?: boolean }`. When `events` is omitted the SDK uses `document_ready`, `document_prepared`, `signer_signed_document`, `signer_rejected_document`, and `document_processing_failed`; pass `[]` deliberately for none. Dispatch filters extend pagination with `{ event?, delivered?, from?, to?, sort?: 'created_at' | '-created_at' }`; sort is a live-verified extension. The sandbox ignored dispatch `search`, so it is rejected locally. The API does not expose a delete-subscription operation; use `inactivate`.
401
+ Registration payload: `{ url: string; email: string; events?: string[]; is_active?: boolean }`. When `events` is omitted the SDK uses `document_ready`, `document_prepared`, `signer_signed_document`, `signer_rejected_document`, and `document_processing_failed`; pass `[]` deliberately for none. Dispatch filters extend pagination with `{ event?, delivered?, from?, to?, sort?: 'created_at' | '-created_at' }`; sort is a compatibility extension. Dispatch `search` is unsupported and rejected locally. The API does not expose a delete-subscription operation; use `inactivate`.
402
+
403
+ Decline operations require a non-empty reason of at most 2,000 Unicode characters. `signers.findByEmail` follows pagination metadata until an exact case-insensitive email match is found or the search is exhausted.
369
404
 
370
405
  ## Responses, pagination, errors, and binary data
371
406
 
372
407
  - JSON responses with `data` are unwrapped from the API envelope; direct status bodies remain `IStatusResponse`. Paginated calls resolve to `{ data: T[]; meta?: { current_page?, last_page?, per_page?, total? } }`; metadata comes from `X-Pagination-*` headers.
373
408
  - Binary methods resolve to Node.js `Buffer`; the SDK is not a browser package. It never writes downloaded data to disk.
374
- - `ValidationError` means local input validation failed before a request. `ApiError` exposes `statusCode` and `responseData`. `NetworkError` covers timeout/DNS/transport failures. All extend `AssinafyError`, which exposes `context` and preserves `cause` where available.
409
+ - `ValidationError` means local input validation failed before a request. `ApiError` exposes `statusCode`, `responseData`, `wwwAuthenticate` and `retryAfter`; binary JSON error bodies are decoded before normalization. OAuth responses are flat JSON, and OAuth revocation resolves to `undefined`. `NetworkError` covers timeout/DNS/transport failures. `PartialWorkflowError` reports `documents upload --wait` or a multi-step helper that failed after creating resources and exposes `documentId` and `signerIds`. All extend `AssinafyError`, which exposes `context` and preserves `cause` where available.
375
410
  - `normalizeBaseUrl(url)` is exported and removes one trailing slash.
376
411
 
377
- Exported error constructors/helpers are `new AssinafyError(message, context?, { cause? }?)`, `new ApiError(message, statusCode, responseData?, { cause? }?)`, `ApiError.fromResponse(statusCode, responseData)`, `new ValidationError(message?, errors?)`, and `new NetworkError(message, { cause? }?)`. Resource classes and all named request/response types are also exported for dependency injection and type annotations; normal applications should obtain resource instances from `AssinafyClient`.
412
+ Exported error constructors/helpers are `new AssinafyError(message, context?, { cause? }?)`, `new ApiError(message, statusCode, responseData?, { cause?, wwwAuthenticate?, retryAfter? }?)`, `ApiError.fromResponse(statusCode, responseData, headers?)`, `new ValidationError(message?, errors?)`, `new NetworkError(message, { cause? }?)`, and `new PartialWorkflowError(message, { documentId?, signerIds? }, { cause? }?)`. Resource classes and all named request/response types are also exported for dependency injection and type annotations; normal applications should obtain resource instances from `AssinafyClient`.
378
413
 
379
414
  ```ts
380
415
  try {
@@ -400,7 +435,7 @@ Assinafy's published API does **not** define a signature header, algorithm, dige
400
435
 
401
436
  ## Contract boundaries
402
437
 
403
- - Production OpenAPI currently publishes 89 operations. Some sandbox deployments lag it; account/user statistics and user notification-preference routes may return route-level 404s even though production documentation includes them.
438
+ - Production OpenAPI currently publishes 93 operations. Some sandbox deployments lag it; account/user statistics and user notification-preference routes may return route-level 404s even though production documentation includes them.
404
439
  - The API's digital-certificate description mentions certificate start/complete routes that are not defined as OpenAPI paths. The SDK does not invent undocumented request/response contracts for them.
405
- - The SDK retains the two template compatibility routes above and both published/legacy public `sendToken` payloads until the upstream contract converges.
406
- - The sandbox raw signer-artifact route ignored an invalid access code during sandbox verification. The SDK adds the identity preflight described above, but direct HTTP consumers remain exposed until Assinafy fixes the route.
440
+ - The SDK retains the two template compatibility routes above and both published/legacy public `sendToken` payloads for compatible deployments.
441
+ - Signer artifact downloads are public in the published contract. Supplying a signer access code opts into an SDK identity preflight; it does not change the server route into a private endpoint.
package/install.ps1 CHANGED
@@ -58,7 +58,7 @@ function Test-ArchiveLayout([string]$Archive, [string]$Target) {
58
58
  Fail "Release archive contained an unsafe path"
59
59
  }
60
60
  $allowed = $expectedExecutables -ccontains $entry -or
61
- $entry -cin @("VERSION", "README.md", "LICENSE", "THIRD_PARTY_NOTICES.md") -or
61
+ $entry -cin @("VERSION", "README.md", "README.en.md", "CONTRIBUTING.md", "SECURITY.md", ".env.example", "LICENSE", "THIRD_PARTY_NOTICES.md") -or
62
62
  $entry -cmatch '^docs/[^/]+\.md$' -or $entry -ceq "docs/api-operations.json"
63
63
  if (-not $allowed) {
64
64
  Fail "Release archive contained an unexpected path: $entry"
@@ -205,13 +205,20 @@ try {
205
205
  Move-Item $cmdReplacement $exe -Force
206
206
  $cmdReplacement = $null
207
207
 
208
- foreach ($file in @("README.md", "LICENSE", "THIRD_PARTY_NOTICES.md", "VERSION")) {
208
+ foreach ($file in @("README.md", "README.en.md", "CONTRIBUTING.md", "SECURITY.md", ".env.example", "LICENSE", "THIRD_PARTY_NOTICES.md", "VERSION")) {
209
209
  $source = Join-Path $extractDir $file
210
210
  if (Test-Path $source) {
211
211
  Copy-Item $source (Join-Path $installDir $file) -Force
212
212
  }
213
213
  }
214
214
 
215
+ $docsSource = Join-Path $extractDir "docs"
216
+ if (Test-Path $docsSource) {
217
+ $docsDestination = Join-Path $installDir "docs"
218
+ New-Item -ItemType Directory -Path $docsDestination -Force | Out-Null
219
+ Copy-Item (Join-Path $docsSource "*") $docsDestination -Recurse -Force
220
+ }
221
+
215
222
  if ($env:ASSINAFY_NO_PATH_UPDATE -ne "1") {
216
223
  Add-UserPath $binDir
217
224
  }
package/install.sh CHANGED
@@ -83,10 +83,10 @@ main() {
83
83
  mv -f "$assinafy_replacement" "$executable"
84
84
  assinafy_replacement=""
85
85
 
86
- if [ -f "$extract_dir/README.md" ]; then cp "$extract_dir/README.md" "$install_dir/README.md"; fi
87
- if [ -f "$extract_dir/LICENSE" ]; then cp "$extract_dir/LICENSE" "$install_dir/LICENSE"; fi
88
- if [ -f "$extract_dir/THIRD_PARTY_NOTICES.md" ]; then cp "$extract_dir/THIRD_PARTY_NOTICES.md" "$install_dir/THIRD_PARTY_NOTICES.md"; fi
89
- if [ -f "$extract_dir/VERSION" ]; then cp "$extract_dir/VERSION" "$install_dir/VERSION"; fi
86
+ for file in README.md README.en.md CONTRIBUTING.md SECURITY.md .env.example LICENSE THIRD_PARTY_NOTICES.md VERSION; do
87
+ if [ -f "$extract_dir/$file" ]; then cp "$extract_dir/$file" "$install_dir/$file"; fi
88
+ done
89
+ if [ -d "$extract_dir/docs" ]; then cp -R "$extract_dir/docs/." "$install_dir/docs"; fi
90
90
 
91
91
  ensure_path "$bin_dir"
92
92
  success "Installed $installed_version to $executable"
@@ -265,7 +265,7 @@ validate_archive() {
265
265
  fi
266
266
  ;;
267
267
  VERSION) version_count=$((version_count + 1)) ;;
268
- README.md | LICENSE | THIRD_PARTY_NOTICES.md | docs/*.md | docs/api-operations.json) ;;
268
+ README.md | README.en.md | CONTRIBUTING.md | SECURITY.md | .env.example | LICENSE | THIRD_PARTY_NOTICES.md | docs/*.md | docs/api-operations.json) ;;
269
269
  *) fail "Release archive contained an unexpected path: $entry" ;;
270
270
  esac
271
271
  done < <(tar -tzf "$archive")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assinafy/cli",
3
- "version": "2.0.3",
3
+ "version": "2.1.2",
4
4
  "description": "The official command-line interface for the Assinafy digital-signature API",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -29,6 +29,10 @@
29
29
  "install.sh",
30
30
  "install.ps1",
31
31
  "README.md",
32
+ "README.en.md",
33
+ "CONTRIBUTING.md",
34
+ "SECURITY.md",
35
+ ".env.example",
32
36
  "LICENSE",
33
37
  "THIRD_PARTY_NOTICES.md"
34
38
  ],
@@ -59,7 +63,6 @@
59
63
  "lint": "biome check .",
60
64
  "lint:fix": "biome check --write .",
61
65
  "test": "vitest run",
62
- "test:sandbox": "npm run build && node scripts/sandbox-smoke.mjs",
63
66
  "test:watch": "vitest",
64
67
  "docs": "npm run build && node scripts/gen-docs.mjs",
65
68
  "docs:api": "node scripts/gen-api-reference.mjs",