@assinafy/cli 2.0.2 → 2.1.1

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.
Files changed (48) hide show
  1. package/.env.example +54 -0
  2. package/CONTRIBUTING.md +29 -0
  3. package/README.en.md +559 -0
  4. package/README.md +314 -180
  5. package/SECURITY.md +10 -0
  6. package/THIRD_PARTY_NOTICES.md +3 -3
  7. package/dist/api.cjs +453 -74
  8. package/dist/api.cjs.map +1 -1
  9. package/dist/api.js +451 -74
  10. package/dist/api.js.map +1 -1
  11. package/dist/cli.cjs +1278 -228
  12. package/dist/types/api/client.d.ts +7 -0
  13. package/dist/types/api/client.d.ts.map +1 -1
  14. package/dist/types/api/errors.d.ts +42 -1
  15. package/dist/types/api/errors.d.ts.map +1 -1
  16. package/dist/types/api/index.d.ts +1 -0
  17. package/dist/types/api/index.d.ts.map +1 -1
  18. package/dist/types/api/resources/assignments.d.ts +3 -1
  19. package/dist/types/api/resources/assignments.d.ts.map +1 -1
  20. package/dist/types/api/resources/documents.d.ts +3 -3
  21. package/dist/types/api/resources/documents.d.ts.map +1 -1
  22. package/dist/types/api/resources/fields.d.ts.map +1 -1
  23. package/dist/types/api/resources/oauth.d.ts +20 -0
  24. package/dist/types/api/resources/oauth.d.ts.map +1 -0
  25. package/dist/types/api/resources/signer-documents.d.ts +9 -5
  26. package/dist/types/api/resources/signer-documents.d.ts.map +1 -1
  27. package/dist/types/api/resources/signers.d.ts.map +1 -1
  28. package/dist/types/api/resources/webhooks.d.ts.map +1 -1
  29. package/dist/types/api/support/webhook-verifier.d.ts.map +1 -1
  30. package/dist/types/api/types.d.ts +146 -56
  31. package/dist/types/api/types.d.ts.map +1 -1
  32. package/dist/types/api/utils.d.ts +18 -0
  33. package/dist/types/api/utils.d.ts.map +1 -1
  34. package/docs/README.md +4 -2
  35. package/docs/api-operations.json +33 -1
  36. package/docs/api-reference.md +323 -79
  37. package/docs/assignments.md +3 -3
  38. package/docs/documents.md +8 -8
  39. package/docs/fields.md +4 -4
  40. package/docs/migration-v2.md +6 -2
  41. package/docs/oauth-guide.md +343 -0
  42. package/docs/oauth.md +162 -0
  43. package/docs/releasing.md +16 -6
  44. package/docs/sdk-reference.md +121 -24
  45. package/docs/signer.md +3 -2
  46. package/install.ps1 +9 -2
  47. package/install.sh +5 -5
  48. package/package.json +8 -5
package/.env.example ADDED
@@ -0,0 +1,54 @@
1
+ # Assinafy CLI environment variables (all optional — flags and config file also work)
2
+
3
+ # Direct server-to-server credential — sent as the X-Api-Key header.
4
+ ASSINAFY_API_KEY=
5
+
6
+ # Default workspace / account ID applied to account-scoped commands.
7
+ ASSINAFY_ACCOUNT_ID=
8
+
9
+ # Override the API base URL. Use the sandbox while testing:
10
+ # https://sandbox.assinafy.com.br/v1
11
+ # Defaults to https://api.assinafy.com.br/v1
12
+ ASSINAFY_BASE_URL=
13
+
14
+ # OAuth access token or user JWT (sent as Authorization: Bearer).
15
+ ASSINAFY_TOKEN=
16
+
17
+ # OAuth marketplace application. Public clients omit the client secret.
18
+ # Obtain the issuer and resource from `assinafy oauth metadata` / `discovery`.
19
+ # The official CLI includes its public client ID. Leave this unset to use it.
20
+ # Uncomment only to override it with your own registered application ID.
21
+ # ASSINAFY_OAUTH_CLIENT_ID=
22
+ ASSINAFY_OAUTH_CLIENT_SECRET=
23
+ ASSINAFY_OAUTH_CALLBACK_URL=
24
+ ASSINAFY_OAUTH_REFRESH_TOKEN=
25
+ ASSINAFY_OAUTH_REVOKE_TOKEN=
26
+
27
+ # Safer non-interactive alternatives to passing secrets on the command line.
28
+ ASSINAFY_PASSWORD=
29
+ ASSINAFY_NEW_PASSWORD=
30
+ ASSINAFY_PROVIDER_TOKEN=
31
+ ASSINAFY_RESET_TOKEN=
32
+ ASSINAFY_SIGNER_ACCESS_CODE=
33
+ ASSINAFY_VERIFICATION_CODE=
34
+
35
+ # Experimental verifier only: Assinafy does not publish its webhook signing scheme.
36
+ # Do not treat WebhookVerifier as a production trust boundary without independent validation.
37
+ ASSINAFY_WEBHOOK_SECRET=
38
+
39
+ # Named profile to select from the config file (~/.config/assinafy/config.json).
40
+ ASSINAFY_PROFILE=
41
+
42
+ # Override the directory containing config.json.
43
+ ASSINAFY_CONFIG_DIR=
44
+
45
+ # Release-installer settings (read by install.sh / install.ps1, not the CLI).
46
+ # Installation root; defaults to ~/.assinafy.
47
+ ASSINAFY_INSTALL=
48
+
49
+ # Set to 1 to keep the installer from changing the user PATH.
50
+ ASSINAFY_NO_PATH_UPDATE=
51
+
52
+ # Advanced mirror overrides; defaults shown in the installers are recommended.
53
+ ASSINAFY_REPO=
54
+ GITHUB_BASE=
@@ -0,0 +1,29 @@
1
+ # Contributing
2
+
3
+ Use Node.js 24 LTS for development; Node.js 22.12 and 26 remain CI compatibility
4
+ targets. Install exactly from the lockfile and run the complete local gate:
5
+
6
+ ```bash
7
+ npm ci
8
+ npm run typecheck
9
+ npm run lint
10
+ npm test
11
+ npm run build
12
+ npm run verify:bundle
13
+ npm run verify:api-docs
14
+ ```
15
+
16
+ Run `npm run docs` after CLI help changes and `npm run docs:api` only when syncing
17
+ the official OpenAPI reference. Never place credentials, live object IDs, or test
18
+ recipient data in fixtures or documentation.
19
+
20
+ `npm test` exercises SDK requests and responses, validation, CLI behavior, and
21
+ OAuth callbacks using controlled transports, synthetic data, and local loopback
22
+ servers. These checks require no Assinafy credentials. Release verification also
23
+ checks the current public production API documentation, generated files, packaged
24
+ CLI and SDK consumers, installers, reproducible archives, and checksums before
25
+ publishing the verified artifacts.
26
+
27
+ For publishing, follow [docs/releasing.md](./docs/releasing.md). Keep changes at the
28
+ shared root cause, reuse existing helpers, and include the smallest regression test
29
+ that proves non-trivial behavior.
package/README.en.md ADDED
@@ -0,0 +1,559 @@
1
+ # @assinafy/cli
2
+
3
+ *[Leia em português](README.md) · English*
4
+
5
+ The official command-line interface and Node.js SDK for the [Assinafy API](https://api.assinafy.com.br/v1/docs), a Brazilian digital-signature platform. Upload PDFs, manage signers, request signatures, track the audit trail, and download certified documents — from a terminal, a shell script, or an application.
6
+
7
+ The CLI is a single self-contained executable. It prints human-readable tables by default and structured JSON with `--json`, so the same commands serve both interactive use and automation. The same package exposes a fully typed SDK at `@assinafy/cli/api` covering all 93 published API operations.
8
+
9
+ This document reads top to bottom: install, authenticate, send your first signature request, then understand the model well enough to automate it. The [command reference](#command-reference) and [SDK](#nodejs-sdk) sections near the end are lookup tables you can jump to once the flow makes sense.
10
+
11
+ ## Contents
12
+
13
+ 1. [Requirements](#requirements)
14
+ 2. [Installation](#installation)
15
+ 3. [Authentication](#authentication)
16
+ 4. [Quick start](#quick-start)
17
+ 5. [How signing works](#how-signing-works)
18
+ 6. [The complete owner workflow](#the-complete-owner-workflow)
19
+ 7. [The signer side](#the-signer-side)
20
+ 8. [Webhooks](#webhooks)
21
+ 9. [Output and scripting](#output-and-scripting)
22
+ 10. [Configuration](#configuration)
23
+ 11. [Command reference](#command-reference)
24
+ 12. [Node.js SDK](#nodejs-sdk)
25
+ 13. [Security](#security)
26
+ 14. [Development](#development)
27
+ 15. [Release](#release)
28
+ 16. [Contract boundaries](#contract-boundaries)
29
+ 17. [License](#license)
30
+
31
+ ## Requirements
32
+
33
+ - Node.js `>=22.12.0`. Node.js 24 LTS is recommended and is what CI publishes with; CI also tests 22 and 26.
34
+ - An Assinafy account and an API key (see [Authentication](#authentication)).
35
+ - Linux, macOS, or Windows. Release archives ship for `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `windows-x64`, and `windows-arm64`.
36
+
37
+ ## Installation
38
+
39
+ ### From npm
40
+
41
+ ```bash
42
+ npm install -g @assinafy/cli@<version>
43
+ assinafy --help
44
+ ```
45
+
46
+ Pin `@<version>` in anything reproducible; omit it only when you deliberately want the newest published release.
47
+
48
+ ### From a GitHub release
49
+
50
+ Download and read the installer from the same immutable version tag you are installing, then run it:
51
+
52
+ ```bash
53
+ ASSINAFY_VERSION=vX.Y.Z # replace with a published release tag
54
+ curl -fsSLo assinafy-install.sh \
55
+ "https://raw.githubusercontent.com/assinafy/assinafy-cli/${ASSINAFY_VERSION}/install.sh"
56
+ less assinafy-install.sh
57
+ bash assinafy-install.sh "$ASSINAFY_VERSION"
58
+ ```
59
+
60
+ Windows PowerShell:
61
+
62
+ ```powershell
63
+ $Version = 'vX.Y.Z' # replace with a published release tag
64
+ Invoke-WebRequest "https://raw.githubusercontent.com/assinafy/assinafy-cli/$Version/install.ps1" -OutFile .\assinafy-install.ps1
65
+ Get-Content .\assinafy-install.ps1
66
+ & .\assinafy-install.ps1 -Version $Version
67
+ ```
68
+
69
+ The installers fetch the matching release archive and verify it against that release's `SHA256SUMS` before replacing the executable. They install to `~/.assinafy/bin`; set `ASSINAFY_INSTALL` to choose another directory, or `ASSINAFY_NO_PATH_UPDATE=1` to leave `PATH` untouched.
70
+
71
+ ### Without installing
72
+
73
+ ```bash
74
+ npx @assinafy/cli whoami
75
+ ```
76
+
77
+ ## Authentication
78
+
79
+ Use an API key for direct owner integrations, OAuth for customer-consented marketplace connections, or a user JWT for user-session operations.
80
+
81
+ | Credential | Header sent | Use it for |
82
+ | --- | --- | --- |
83
+ | API key | `X-Api-Key: <key>` | Direct owner integrations and permitted account operations. |
84
+ | OAuth access token | `Authorization: Bearer <token>` | Marketplace connections, limited to granted scopes and one workspace. |
85
+ | User JWT | `Authorization: Bearer <jwt>` | User sessions and permitted account operations. |
86
+
87
+ Generate an API key from the Assinafy dashboard, or from the CLI with an existing session:
88
+
89
+ ```bash
90
+ assinafy auth login you@example.com # returns a JWT
91
+ assinafy auth api-keys create --token <jwt> # generates (and rotates) the key
92
+ ```
93
+
94
+ Store the key once, then confirm it works:
95
+
96
+ ```bash
97
+ assinafy login # prompts for the API key and default workspace ID
98
+ assinafy whoami # lists the workspaces the credential can reach
99
+ ```
100
+
101
+ `whoami` lists accessible workspaces and validates the credential and base URL. Confirm that your configured account ID appears in that list. Most commands are workspace-scoped, so set a default account ID during `login` (or pass `--account-id` per command) to avoid repeating it.
102
+
103
+ Credentials resolve with a fixed precedence — **CLI flag → environment variable → config file** — which is covered in full under [Configuration](#configuration).
104
+
105
+ ### OAuth marketplace connections
106
+
107
+ The CLI includes the official application's public client ID and uses PKCE S256 without a client secret. Automatic browser return uses this exact HTTPS redirect URI, without an extension or trailing slash, served by `integrations-generic-callback`:
108
+
109
+ ```text
110
+ https://integrations.assinafy.com.br/assinafy-cli/oauth-callback
111
+ ```
112
+
113
+ The CLI requests all nine scopes by default: `account:read documents:read documents:write templates:read templates:write openid profile email offline_access`, including template read/write access. The application registration must permit all nine; existing connections need fresh consent to gain additional permissions. An explicit `--scope` requests a smaller set.
114
+
115
+ No `ASSINAFY_OAUTH_CLIENT_ID` configuration is needed for the official application. For your own application or another environment, use `--client-id` or that variable; the flag takes precedence. Register the callback URI and scopes for the selected application. In a private directory outside the repository:
116
+
117
+ ```bash
118
+ umask 077
119
+ assinafy oauth connect --json > tokens.json
120
+ unset ASSINAFY_API_KEY
121
+ export ASSINAFY_TOKEN="$(jq -er '.access_token' tokens.json)"
122
+ assinafy workspaces list --json
123
+ ```
124
+
125
+ The command opens the system browser and waits for consent. The HTTPS return page forwards the authorization response to a temporary listener on `127.0.0.1`. The CLI validates state and issuer, closes the listener, and exchanges the code using its local PKCE verifier. Use a browser on the same computer as the CLI. Tokens travel directly between the CLI and Assinafy.
126
+
127
+ Use `--no-browser` to open the URL printed to stderr manually while keeping automatic callback reception. `--timeout` sets the browser wait from 1 to 600 seconds (default 180), `--scope` selects permissions, and `--redirect-uri` selects another registered HTTPS page implementing the relay protocol. Ctrl+C cancels the wait. Token JSON goes to stdout; protect it from logs. `connect` does not modify a profile or automatically refresh tokens.
128
+
129
+ Select the single workspace returned and set `ASSINAFY_ACCOUNT_ID`. Keep refreshes serialized per connection and store each rotated result atomically. The existing `oauth authorize` and `oauth exchange` commands also support applications with their own callbacks and confidential server credentials. The [OAuth guide](./docs/oauth-guide.md#cli-flow) documents both flows, complete payloads, token rotation, identity validation, and disconnect behavior.
130
+
131
+ ## Quick start
132
+
133
+ ```bash
134
+ assinafy send contract.pdf \
135
+ --signer "Ana Lima <ana@example.com>" \
136
+ --signer "Bruno Souza <+5548999990000>" \
137
+ --message "Please sign this contract"
138
+ ```
139
+
140
+ `send` is the whole happy path in one command: it uploads the PDF, waits for the platform to finish processing it, creates or reuses each signer, and creates the signature assignment that sends out the invitations. A signer given only a phone number defaults to WhatsApp verification and notification; otherwise the platform's own defaults apply. Pass `--signers '<json>'` to set them explicitly.
141
+
142
+ It prints the document ID, the assignment ID, and the signer IDs — the three handles every later command needs.
143
+
144
+ If a step fails after the upload, the error names the document and signers that were created or reused, so nothing is left orphaned in your workspace without a handle:
145
+
146
+ ```text
147
+ error: Saldo insuficiente. (document doc_abc123 exists; 2 signer(s) created or reused)
148
+ (HTTP 402)
149
+ ```
150
+
151
+ Under `--json` the same information is machine-readable in `error.details`.
152
+
153
+ ## How signing works
154
+
155
+ Four resources make up the model:
156
+
157
+ - **Document** — an uploaded PDF. It moves through `uploading` → `uploaded` → `metadata_processing` → `metadata_ready`, then `pending_signature` once an assignment exists, and finally `certificating` → `certificated`. Terminal failure states are `expired`, `failed`, `rejected_by_signer`, and `rejected_by_user`. Run `assinafy documents statuses` for the authoritative list and which states allow deletion.
158
+ - **Signer** — a person in your workspace, identified by name plus an email address and/or a WhatsApp number. Signers are reusable across documents, and creating one with an email address that already exists reuses the existing record rather than duplicating it.
159
+ - **Assignment** — the request that binds signers to a document and sends the invitations. `--method virtual` (the default) collects signatures; `--method collect` also gathers custom field values and requires `--entries` describing where each field sits on the page.
160
+ - **Artifact** — the downloadable output. `original` is what you uploaded; `certificated` is the signed PDF; `certificate-page` is the signature-certificate sheet; `pades` is the PAdES-conformant PDF; `bundle` is a ZIP of everything. Only `original` exists before signing completes.
161
+
162
+ Two side notes worth knowing before you script anything:
163
+
164
+ - Processing is asynchronous. Wait for `metadata_ready` with `documents upload --wait` or `documents wait` before referencing pages in a collect assignment. Virtual assignments can also be submitted during processing. The `document_ready` webhook signals the last signature, not initial upload processing.
165
+ - Assignments cost credits. `assignments estimate-cost` and `documents estimate-template-cost` tell you the price, your balance, and any blocking reason before you commit.
166
+
167
+ ## The complete owner workflow
168
+
169
+ `send` is the shortcut. When you need explicit control over signing order, verification methods, tags, or expiration, run the steps yourself:
170
+
171
+ ```bash
172
+ # 1. Create (or find) each signer. Creation is idempotent by email address.
173
+ SIGNER_ID=$(assinafy signers create \
174
+ --name "Ana Lima" --email ana@example.com --json | jq -r '.id')
175
+
176
+ # 2. Upload the PDF and wait for the platform to finish processing it.
177
+ DOCUMENT_ID=$(assinafy documents upload contract.pdf \
178
+ --name "Service agreement" --wait --json | jq -r '.id')
179
+
180
+ # 3. Check the price before spending credits.
181
+ assinafy assignments estimate-cost "$DOCUMENT_ID" --signer-ids "$SIGNER_ID" --json
182
+
183
+ # 4. Request the signatures. This is what sends the invitations.
184
+ assinafy assignments create "$DOCUMENT_ID" \
185
+ --signer-ids "$SIGNER_ID" \
186
+ --message "Please review and sign" \
187
+ --expires-at "2026-12-31T23:59:59Z"
188
+
189
+ # 5. Track it.
190
+ assinafy documents progress "$DOCUMENT_ID" --json
191
+ assinafy documents activities "$DOCUMENT_ID" --json
192
+
193
+ # 6. Collect the record once every signer has completed.
194
+ assinafy documents download "$DOCUMENT_ID" --artifact certificated -o signed-contract.pdf
195
+ assinafy documents download "$DOCUMENT_ID" --artifact bundle -o signed-contract-bundle.zip
196
+ ```
197
+
198
+ For ordered signing or mixed verification methods, replace `--signer-ids` with `--signers` and pass the full objects:
199
+
200
+ ```bash
201
+ assinafy assignments create "$DOCUMENT_ID" --signers '[
202
+ {"id":"sig_1","verification_method":"Email","notification_methods":["Email"],"step":1},
203
+ {"id":"sig_2","verification_method":"Whatsapp","notification_methods":["Whatsapp"],"step":2}
204
+ ]'
205
+ ```
206
+
207
+ Steps must form a contiguous sequence starting at `1`, and a `DigitalCertificate` signer must be alone in its step — both are validated locally before the request is sent. `--copy-receivers` takes **signer IDs** (people who only receive a copy of the finished document), not arbitrary email addresses.
208
+
209
+ To start from a saved template instead of a PDF:
210
+
211
+ ```bash
212
+ assinafy templates list --json
213
+ assinafy documents create-from-template tmpl_123 --signers '[
214
+ {"role_id":"role_1","id":"sig_1","verification_method":"Email","notification_methods":["Email"]}
215
+ ]' --name "Q1 NDA"
216
+ ```
217
+
218
+ If a signer needs chasing, `assignments resend <documentId> <assignmentId> <signerId>` re-sends their invitation (priced by `assignments estimate-resend-cost`), and `assignments reset-expiration` moves the deadline.
219
+
220
+ Keep the certified PDF, the certificate page, the bundle, and the `documents activities` output together as the document record. Delete only disposable documents, and only once their retention obligations are satisfied.
221
+
222
+ ## The signer side
223
+
224
+ Signers do not use your API key. Each invitation carries a one-time **access code**, and the `assinafy signer` commands act as that signer:
225
+
226
+ ```bash
227
+ export ASSINAFY_SIGNER_ACCESS_CODE=<code-from-the-invitation>
228
+
229
+ assinafy signer self # who the code belongs to
230
+ assinafy signer assignment # the document as the signer sees it
231
+ assinafy signer accept-terms
232
+ assinafy signer upload-signature --file signature.png
233
+ assinafy signer sign <documentId> <assignmentId> --entries '[
234
+ {"itemId":"item_1","fieldId":"field_1","pageId":"page_1","value":"..."}
235
+ ]'
236
+ ```
237
+
238
+ Where email or WhatsApp verification is configured, the signer also confirms a 6-digit code: `documents send-token <documentId> --email <email>` issues it and `signer verify-email --code <otp>` redeems it. `signer decline` (or `decline-multiple`) rejects with a reason, and `sign-multiple` completes several documents in one call.
239
+
240
+ Owner API credentials are stripped from every public and signer-side request, so an access-code flow can never leak your workspace key. The published signer artifact download is public; passing `--access-code` adds an identity preflight that confirms the code belongs to the signer being downloaded for.
241
+
242
+ ## Webhooks
243
+
244
+ Polling works, but webhooks are the right way to react to signing events:
245
+
246
+ ```bash
247
+ assinafy webhooks event-types # what the platform can send
248
+ assinafy webhooks register \
249
+ --url https://example.com/hooks/assinafy \
250
+ --email ops@example.com \
251
+ --events document_ready,signer_signed_document,signer_rejected_document
252
+
253
+ assinafy webhooks dispatches --delivered false # what failed to deliver
254
+ assinafy webhooks retry <dispatchId> # redeliver one event
255
+ assinafy webhooks get # current subscription
256
+ assinafy webhooks inactivate # stop deliveries
257
+ ```
258
+
259
+ One subscription exists per workspace; `register` replaces it. Omitting `--events` subscribes to `document_ready`, `document_prepared`, `signer_signed_document`, `signer_rejected_document`, and `document_processing_failed`. The API has no delete-subscription operation — use `inactivate` to stop deliveries, and note that `retry` only works while the subscription is active.
260
+
261
+ Assinafy does not publish a webhook signing scheme, so the SDK's `WebhookVerifier` is experimental. See [Contract boundaries](#contract-boundaries).
262
+
263
+ ## Output and scripting
264
+
265
+ Human output goes to **stdout**; spinners and status lines go to **stderr**, so pipes stay clean.
266
+
267
+ - `--json` — structured JSON on stdout, with errors as JSON on stderr. Always machine-readable.
268
+ - `-q, --quiet` — suppress spinners and status messages.
269
+
270
+ Exit codes are `0` on success, `1` on error, and `130` on Ctrl-C. Paginated JSON keeps both the rows and the metadata:
271
+
272
+ ```bash
273
+ # IDs of every pending document
274
+ assinafy documents list --status pending_signature --json | jq -r '.data[].id'
275
+
276
+ # Page through a large workspace
277
+ assinafy documents list --page 2 --per-page 50 --json | jq '.meta'
278
+
279
+ # Upload and capture the new document ID
280
+ DOC=$(assinafy documents upload contract.pdf --json | jq -r '.id')
281
+
282
+ # Attach an existing tag by its ID
283
+ TAG_ID=$(assinafy tags list --search legal --json | jq -r '.[0].id')
284
+ assinafy documents tags-add "$DOC" "$TAG_ID"
285
+ ```
286
+
287
+ JSON errors carry a stable shape:
288
+
289
+ ```json
290
+ {
291
+ "error": {
292
+ "message": "Saldo insuficiente. (document doc_abc123 exists; 2 signer(s) created or reused)",
293
+ "code": "api_error",
294
+ "statusCode": 402,
295
+ "details": { "documentId": "doc_abc123", "signerIds": ["sig_1", "sig_2"] }
296
+ }
297
+ }
298
+ ```
299
+
300
+ Destructive commands prompt for confirmation and refuse to run unattended unless you pass `-y, --yes`.
301
+
302
+ ## Configuration
303
+
304
+ ### Precedence
305
+
306
+ Every setting resolves as **CLI flag → environment variable → config-file profile → built-in default**. Credentials are selected together from the first level that supplies either type; an API key wins only when both types are supplied at that same level. Saving one credential type with `config set` clears the other from that profile. The CLI reads process environment variables; it does not automatically load `.env` files. The OAuth variables are listed in [.env.example](./.env.example).
307
+
308
+ | What | Flag | Environment variable |
309
+ | --- | --- | --- |
310
+ | API key (sent as `X-Api-Key`) | `--api-key` | `ASSINAFY_API_KEY` |
311
+ | OAuth access token or user JWT (sent as `Bearer`) | `--token` | `ASSINAFY_TOKEN` |
312
+ | Default account / workspace ID | `--account-id` | `ASSINAFY_ACCOUNT_ID` |
313
+ | API base URL | `--base-url` | `ASSINAFY_BASE_URL` |
314
+ | Config profile | `-p, --profile` | `ASSINAFY_PROFILE` |
315
+ | Config directory | — | `ASSINAFY_CONFIG_DIR` |
316
+ | Experimental webhook-verifier secret | _(config only)_ | `ASSINAFY_WEBHOOK_SECRET` |
317
+ | Password / new password | `--password` / `--new-password` | `ASSINAFY_PASSWORD` / `ASSINAFY_NEW_PASSWORD` |
318
+ | Social provider / reset token | `--provider-token` / `--reset-token` | `ASSINAFY_PROVIDER_TOKEN` / `ASSINAFY_RESET_TOKEN` |
319
+ | Signer access code / email OTP | `--access-code` / `--code` | `ASSINAFY_SIGNER_ACCESS_CODE` / `ASSINAFY_VERIFICATION_CODE` |
320
+
321
+ `.env.example` documents every CLI and installer environment variable.
322
+
323
+ Public document verification and lookup, password reset, login and social login, and all signer access-code flows work without stored credentials.
324
+
325
+ ### Config file and profiles
326
+
327
+ `assinafy login` and `assinafy config set` write a JSON config file with owner-only (`0600`) permissions:
328
+
329
+ - Linux / macOS: `~/.config/assinafy/config.json` (honours `XDG_CONFIG_HOME`)
330
+ - Windows: `%APPDATA%\assinafy\config.json`
331
+ - Anywhere: `ASSINAFY_CONFIG_DIR`
332
+
333
+ Writes go through a temp file and a rename, so an interrupted write can never truncate the file. Read-only commands warn about and ignore a malformed config; `login`, `logout`, and profile mutations refuse to overwrite it, so its contents stay recoverable.
334
+
335
+ Profiles keep separate credentials — production and sandbox, or one per client:
336
+
337
+ ```bash
338
+ assinafy --profile sandbox \
339
+ --base-url "https://sandbox.assinafy.com.br/v1" \
340
+ login # prompts for that profile's key and account ID
341
+
342
+ assinafy config use sandbox # make it the default
343
+ assinafy config list # list profiles
344
+ assinafy config get # effective config, secrets masked
345
+ assinafy config path # where the file lives
346
+ ```
347
+
348
+ ### Sandbox
349
+
350
+ Assinafy runs a **separate sandbox** at `https://sandbox.assinafy.com.br/v1`. It has its own accounts and its own keys: a sandbox key returns `401` against production and vice versa. Target it per command with `--base-url`, for a session with `ASSINAFY_BASE_URL`, or permanently by storing it in a profile as shown above.
351
+
352
+ ## Command reference
353
+
354
+ Run `assinafy <command> --help` for the full flags of any command. Every command's help output is mirrored under [`docs/`](./docs), the [API reference](./docs/api-reference.md) holds the official request/response payloads for all 93 published operations, and the [SDK reference](./docs/sdk-reference.md) maps each SDK method to its operation.
355
+
356
+ Global flags accepted by every command: `--api-key`, `--token`, `--account-id`, `--base-url`, `-p, --profile`, `--json`, `-q, --quiet`. `assinafy -v` prints the version.
357
+
358
+ ### `send` — upload and request signatures
359
+
360
+ ```bash
361
+ assinafy send contract.pdf \
362
+ --signer "Ana <ana@example.com>" \
363
+ --signer "Bruno <+5548999990000>" \
364
+ --message "Please sign" \
365
+ --expires-at "2026-12-31T23:59:59Z" \
366
+ --copy-receivers sig_abc123,sig_def456
367
+ ```
368
+
369
+ `--signers '<json>'` replaces `--signer` when you need verification methods or signing order; `--no-wait` skips waiting for processing; `--metadata '<json>'` attaches integration data to the document.
370
+
371
+ ### `documents`
372
+
373
+ | Command | Description |
374
+ | --- | --- |
375
+ | `documents upload <file> [--name] [--metadata] [--wait]` | Upload a PDF (max 25 MiB) |
376
+ | `documents list [--status] [--method] [--tags] [--page] [--per-page] [--search] [--sort]` | List documents |
377
+ | `documents search [query] [--status] [--page] [--per-page] [--sort]` | Lightweight type-ahead search |
378
+ | `documents get <id>` | Show document details |
379
+ | `documents rename <id> <name>` | Rename a document (before signing starts) |
380
+ | `documents download <id> [--artifact] [-o] [--force]` | Download an artifact (`original`/`certificated`/`certificate-page`/`pades` PDFs, or `bundle` ZIP) |
381
+ | `documents thumbnail <id> [-o] [--force]` | Download the thumbnail (JPEG) |
382
+ | `documents download-page <id> <pageId> [-o] [--force]` | Download one page (JPEG) |
383
+ | `documents activities <id>` | Activity log |
384
+ | `documents delete <id> [-y]` | Delete a document |
385
+ | `documents tags <id>` | List attached tags |
386
+ | `documents tags-set <id> [tagIds...]` | Replace the tag set by ID (none detaches all) |
387
+ | `documents tags-add <id> <tagIds...>` | Attach tags by ID |
388
+ | `documents tags-remove <id> <tagId>` | Detach one tag |
389
+ | `documents create-from-template <templateId> --signers <json> [...]` | Create from a template |
390
+ | `documents estimate-template-cost <templateId> --signers <json>` | Estimate template cost |
391
+ | `documents verify <hash>` | Verify by signature hash (public) |
392
+ | `documents statuses` | List every document status and whether it is deletable |
393
+ | `documents public <id>` | Public unauthenticated lookup |
394
+ | `documents send-token <id> --email <email>` | Send a verification token (`--recipient`/`--channel` remains for the live legacy form) |
395
+ | `documents progress <id>` | Signing progress |
396
+ | `documents wait <id> [--timeout] [--interval]` | Poll until ready, failed, or timed out |
397
+
398
+ ### `signers`
399
+
400
+ `create` · `list` · `get <id>` · `update <id>` · `delete <id> [-y]` · `find-by-email <email>`
401
+
402
+ ```bash
403
+ assinafy signers create --name "Ana Lima" --email ana@example.com --cpf 000.000.000-00
404
+ ```
405
+
406
+ Only `--name` is required. `--cpf` strips non-digits. `list` supports `--search`, `--page`, `--per-page`, and `--sort full_name|-full_name`.
407
+
408
+ ### `assignments`
409
+
410
+ `list` · `create <documentId>` · `estimate-cost <documentId>` · `reset-expiration <documentId> <assignmentId>` · `resend <documentId> <assignmentId> <signerId>` · `estimate-resend-cost <documentId> <assignmentId> <signerId>` · `whatsapp-notifications <documentId> <assignmentId>`
411
+
412
+ ```bash
413
+ assinafy assignments create doc_123 --signer-ids sig_1,sig_2 --message "Please sign"
414
+ assinafy assignments reset-expiration doc_123 asg_1 --expires-at "2026-12-31T23:59:59Z"
415
+ ```
416
+
417
+ `reset-expiration --clear` removes the expiration where the deployment supports it.
418
+
419
+ ### `templates`
420
+
421
+ `list [--search] [--sort]` · `get <id>` · `download-page <templateId> <pageId> [-o] [--force]`
422
+
423
+ ### `tags`
424
+
425
+ `list [--search]` · `create --name [--color]` · `update <id> [--name] [--color] [--clear-color]` · `delete <id> [--force] [-y]`
426
+
427
+ Deleting a tag that is still attached to documents fails until you pass `--force`, which detaches it everywhere first.
428
+
429
+ ### `fields`
430
+
431
+ `create --type --name [--regex] [--required] [--inactive]` · `list [--include-inactive] [--include-standard]` · `get <id>` · `update <id> [...]` · `delete <id> [-y]` · `validate <id> <value> [--signer-access-code]` · `validate-multiple --entries <json> [--signer-access-code]` · `types`
432
+
433
+ Field definitions are what `--method collect` assignments gather. Run `fields types` for the supported types.
434
+
435
+ ### `webhooks`
436
+
437
+ `register --url --email [--events] [--inactive]` · `get` · `inactivate` · `event-types` · `dispatches [--event] [--delivered] [--from] [--to] [--page] [--per-page] [--sort]` · `retry <dispatchId>`
438
+
439
+ ### `workspaces` (alias `accounts`)
440
+
441
+ `create --name [--notification-sender] [--primary-color] [--secondary-color]` · `list` · `get <id>` · `theme <id>` · `stats <id> [--granularity] [--month]` · `logo download|upload|delete` · `update <id> [...]` · `delete <id> [--force] [-y]`
442
+
443
+ ### `users`
444
+
445
+ `self` · `stats [--granularity] [--month]` · `notification-preferences get|update`
446
+
447
+ `--granularity daily` requires `--month YYYY-MM`.
448
+
449
+ ### `signer` — signer-side flows
450
+
451
+ `document <signerId>` · `documents <signerId>` · `search <signerId> <query>` · `download <signerId> <documentId> <artifact>` · `self` · `accept-terms` · `verify-email --code` · `confirm-data <documentId>` · `upload-signature --file` · `download-signature` · `assignment` · `sign <documentId> <assignmentId> --entries` · `decline <documentId> <assignmentId> --reason` · `sign-multiple --document-ids` · `decline-multiple --document-ids --reason`
452
+
453
+ Every signer command except the public artifact `download` requires `--access-code <code>`; `download` accepts it optionally for an identity preflight. Use `ASSINAFY_SIGNER_ACCESS_CODE` to keep the code out of process arguments.
454
+
455
+ ### `auth`
456
+
457
+ `login <email>` · `social-login` · `link-social-login` · `change-password` · `request-password-reset <email>` · `reset-password --reset-token` · `api-keys create|get|delete`
458
+
459
+ For server-to-server use, prefer an API key (`assinafy login` or `--api-key`) and skip this group. `auth login`, `auth social-login`, `auth request-password-reset`, and `auth reset-password` run without stored credentials; the rest accept the API key or JWT documented for their endpoint.
460
+
461
+ ### `oauth`
462
+
463
+ `connect` · `metadata` · `discovery <issuer>` · `authorize --redirect-uri --scope` · `exchange --request --callback-url` · `refresh --refresh-token` · `revoke --revoke-token` · `userinfo`
464
+
465
+ `connect`, `authorize`, `refresh`, and `revoke` use the bundled public client ID unless overridden by `--client-id` or `ASSINAFY_OAUTH_CLIENT_ID`. Client secrets and sensitive callback/token flags have environment-variable alternatives. The [OAuth guide](./docs/oauth-guide.md) documents every method and payload.
466
+
467
+ ### Meta
468
+
469
+ `login` · `logout` · `whoami` · `config set|get|list|use|remove|path` · `docs [--open]`
470
+
471
+ ## Node.js SDK
472
+
473
+ The same package ships a typed SDK. It covers every published operation, unwraps the API envelope, and validates input before a request leaves the process.
474
+
475
+ ```ts
476
+ import { AssinafyClient, ApiError, PartialWorkflowError } from '@assinafy/cli/api';
477
+
478
+ const client = AssinafyClient.create(
479
+ process.env.ASSINAFY_API_KEY!,
480
+ process.env.ASSINAFY_ACCOUNT_ID!,
481
+ );
482
+
483
+ const { data, meta } = await client.documents.list({ status: 'pending_signature' });
484
+
485
+ const document = await client.documents.upload(
486
+ { filePath: './contract.pdf' },
487
+ { name: 'Service agreement', metadata: { external_id: 'order-123' } },
488
+ );
489
+ await client.documents.waitUntilReady(document.id);
490
+ ```
491
+
492
+ CommonJS uses `require('@assinafy/cli/api')`. JSON `data` envelopes are unwrapped, paginated calls resolve to `{ data, meta }` built from the `X-Pagination-*` headers, downloads resolve to a `Buffer`, and status-only responses keep their documented object.
493
+
494
+ Errors are typed: `ValidationError` for local input, `ApiError` (with `statusCode`, `responseData`, `wwwAuthenticate`, and `retryAfter`) for HTTP failures, `NetworkError` for transport failures, and `PartialWorkflowError` when `uploadAndRequestSignatures` fails after creating resources — it exposes the `documentId` and `signerIds` that already exist so you can inspect and resume. Never automatically delete these signers: they may have been reused from other documents. For example:
495
+
496
+ ```ts
497
+ try {
498
+ await client.uploadAndRequestSignatures({ source: { filePath: './contract.pdf' }, signers });
499
+ } catch (error) {
500
+ if (error instanceof PartialWorkflowError) {
501
+ console.error({ documentId: error.documentId, signerIds: error.signerIds });
502
+ // Inspect the document before resuming; signer IDs can belong to reused records.
503
+ }
504
+ throw error;
505
+ }
506
+ ```
507
+
508
+ Full method signatures, payload types, binary formats, and runtime caveats are in the [SDK reference](./docs/sdk-reference.md); every underlying HTTP payload is in the [API reference](./docs/api-reference.md).
509
+
510
+ ## Security
511
+
512
+ - **Transport.** Clients require HTTPS, reject redirects, and reject base URLs carrying credentials, a query string, or a fragment. The SDK's `allowInsecureHttp` escape hatch is limited to loopback hosts (`localhost`, `127.0.0.0/8`, `[::1]`), so an API key can never be sent in cleartext to a remote host.
513
+ - **Credential scope.** Owner credentials are stripped from every public and signer-access-code request. Axios request configuration — which carries auth headers and bodies — is never attached to a thrown error.
514
+ - **At rest.** The config file is written `0600` inside a `0700` directory, atomically, and re-`chmod`ed on every write so a previously loose file cannot keep loose permissions.
515
+ - **On the command line.** Secret-bearing flags are visible in shell history and process listings. Prefer the hidden `login` prompt, the config file, or the environment variables listed under [Configuration](#configuration). Never put API keys, tokens, passwords, reset or provider tokens, or signer access codes in shared scripts or logs.
516
+ - **Terminal output.** Values echoed from the API are stripped of control and bidirectional-override characters before they reach a terminal line.
517
+
518
+ Report vulnerabilities per [SECURITY.md](./SECURITY.md).
519
+
520
+ ## Development
521
+
522
+ ```bash
523
+ npm ci # install exactly from package-lock.json
524
+ npm run dev -- --help # run from source with tsx
525
+ npm run dev:watch # run from source, restart on change
526
+ npm run typecheck # tsc --noEmit
527
+ npm run lint # biome check
528
+ npm test # vitest
529
+ npm run build # bundle dist/cli.cjs plus the SDK ESM/CJS/types
530
+ npm run verify:bundle # verify the bundled executable and packed SDK
531
+ npm run docs # regenerate docs/ from CLI --help output
532
+ npm run docs:api # regenerate the HTTP payload reference from the live OpenAPI
533
+ npm run verify:api-docs # assert every published operation is documented and implemented
534
+ npm run pack:release # build reproducible release archives in dist/release/
535
+ ```
536
+
537
+ `npm test` checks SDK contracts, validation, CLI behavior, and OAuth callbacks with synthetic data, controlled transports, and local servers. It requires no Assinafy credentials. Release verification also checks the current public API documentation and packaged artifacts.
538
+
539
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) for the contribution workflow.
540
+
541
+ ## Release
542
+
543
+ CI runs typecheck, lint, tests, bundle verification, generated-file checks, installer checks, reproducible-archive checks, and package-content checks on Node 22, 24, and 26 across Linux, macOS, and Windows.
544
+
545
+ This repository is hosted directly on GitHub. Push changes to `main` and publish an annotated `vX.Y.Z` tag to run a two-stage release: `verify` rebuilds and checks the tagged commit, automated tests, current public API contract, and packaged artifacts, then uploads a single verified payload; `publish` consumes that payload, uploads the release assets, and publishes to both registries through the protected release environment.
546
+
547
+ The [release runbook](./docs/releasing.md) covers tags, trusted publishing, and recovery.
548
+
549
+ ## Contract boundaries
550
+
551
+ - The production OpenAPI publishes 93 operations and the SDK implements all of them. Sandbox deployments can lag individual routes — account/user statistics and user notification preferences may return route-level 404s there despite being documented in production.
552
+ - The SDK keeps two platform-compatible template routes (`GET /accounts/{id}/templates/{id}` and its page download) that are absent from the published OpenAPI paths.
553
+ - The API's digital-certificate prose mentions certificate start/complete routes that are not defined as OpenAPI paths. The SDK does not invent contracts for them.
554
+ - Both the published and legacy `send-token` payloads are supported for compatible deployments.
555
+ - `WebhookVerifier` is **experimental**. Assinafy does not publish the signature header, algorithm, encoding, timestamp, or replay-protection scheme, so it is not a production trust boundary until the exact scheme is published or independently verified against real deliveries.
556
+
557
+ ## License
558
+
559
+ MIT © Assinafy