@assinafy/sdk 2.5.0 → 2.5.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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.5.2] - 2026-10-05
11
+
12
+ ### Fixed
13
+
14
+ - OAuth callbacks reject repeated protocol parameters before exchanging a code.
15
+ - API errors preserve authentication challenges and decoded binary error bodies
16
+ when a custom transport resolves a non-success response. OAuth errors retain
17
+ the authentication challenge when converted to `OAuthError`.
18
+ - Sandbox OAuth setup uses discovery and keeps client registration, issuer and
19
+ API requests in the same environment.
20
+ - Resource reference documentation includes JSON request payloads alongside
21
+ response examples; upload examples describe filename handling accurately.
22
+
23
+ ### Security
24
+
25
+ - Update the development dependency override for `brace-expansion` to 5.0.12.
26
+
27
+ ## [2.5.1] - 2026-09-28
28
+
29
+ ### Fixed
30
+
31
+ - JSDoc reference corrections: missing response payloads and examples added to
32
+ public methods (`OAuthError.upgrade()`, `parseWwwAuthenticate()`,
33
+ `signerDocuments.search()`, `signerDocuments.confirmData()`,
34
+ `signerDocuments.getAssignment()`, `users.updateNotificationPreferences()`),
35
+ and stale `@throws` clauses corrected on `documents.details()` and
36
+ `signerDocuments.getCurrent()`. No behavior changes.
37
+ - `README.en.md` reaches parity with the pt-BR README: the Environments
38
+ section (sandbox base URL and explicit `issuer`/`authorizationEndpoint`
39
+ configuration), the verification/notification channel table with per-signer
40
+ costs, and the A1/A3 certificate-media note.
41
+ - The two browser URL helpers (`auth.getSocialLoginUrl()`,
42
+ `auth.getSocialLoginCallbackUrl()`) are listed in the coverage ledger's
43
+ compatibility extensions.
44
+ - OAuth callback examples use reserved example domains, and the CONTRIBUTING
45
+ live-test examples point at the sandbox API.
46
+
10
47
  ## [2.5.0] - 2026-09-25
11
48
 
12
49
  ### Added
@@ -146,10 +183,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
146
183
  **A3** are recorded explicitly as certificate media — a file in software or a
147
184
  token/smartcard, chosen by the signer in the browser — both modelled by the
148
185
  single `DigitalCertificate` value, with no separate field to send.
149
- - `bun run audit:api` additionally fetches the two OAuth discovery documents
150
- and checks the issuer, the authorization and token endpoints, PKCE `S256` and
151
- the RFC 9207 `iss` parameter against the published contract. They are the
152
- only part of the OAuth surface that does not live in the OpenAPI document.
153
186
  - `docs/API_COVERAGE.md` maps the four new OAuth operations, bringing the
154
187
  ledger to 93 of 93.
155
188
  - The Portuguese README is now the complete reference rather than a summary
@@ -275,7 +308,7 @@ type, or API surface changed.
275
308
  operations across 68 paths**, including account theme/logo/statistics, OAuth
276
309
  URL helpers/linking, authenticated-user profile/statistics, and all signer
277
310
  response/acknowledgement shapes.
278
- - An exhaustive machine-auditable endpoint ledger (`docs/API_COVERAGE.md`),
311
+ - A complete endpoint ledger (`docs/API_COVERAGE.md`),
279
312
  compatibility record, and a scheduled OpenAPI operation-drift gate.
280
313
  - Strict test-source typechecking and enforced Bun coverage floors. The suite
281
314
  now executes every public HTTP wrapper and covers the production source at
@@ -305,8 +338,9 @@ type, or API surface changed.
305
338
  request credentials or user payloads.
306
339
  - Restored the official name-only signer request and account
307
340
  `notification_sender_type` field. Both are now represented exactly as the
308
- OpenAPI defines them; the live audit records the sandbox's lagging rejection
309
- of `notification_sender_type` without blocking unrelated endpoint tests.
341
+ OpenAPI defines them; the sandbox's lagging rejection of
342
+ `notification_sender_type` is recorded as a known deployment divergence
343
+ without blocking unrelated endpoint tests.
310
344
  - Restored the official public, code-free signer artifact download while
311
345
  retaining an optional access-code argument for legacy deployments, and made
312
346
  owner-only assignment-signer fields optional in signer-context responses.
@@ -320,12 +354,7 @@ type, or API surface changed.
320
354
  - Clarified that webhook HMAC verification is an opt-in utility: the current
321
355
  Assinafy OpenAPI document does not specify a signing header or algorithm.
322
356
 
323
- ### Earlier 2.1.0 audit work (completed 2026-07-19)
324
-
325
- Full audit against the live sandbox API (`https://sandbox.assinafy.com.br/v1`)
326
- and the OpenAPI reference: every safely runnable operation was probed, fixture-
327
- or legal-consent-dependent operations were recorded as explicit skips, and the
328
- SDK was reconciled against the observed request/response shapes.
357
+ ### Additional fixes (completed 2026-07-19)
329
358
 
330
359
  #### Fixed
331
360
 
@@ -342,7 +371,7 @@ SDK was reconciled against the observed request/response shapes.
342
371
  `pages`, and the embedded `assignment` are current.
343
372
  - **README workspace example used an invalid colour.** `primary_color:
344
373
  '#ff0066'` is rejected by the account endpoints, which require exactly 6 hex
345
- characters with **no** leading `#` (verified live). Fixed the example and
374
+ characters with **no** leading `#`. Fixed the example and
346
375
  documented the format on the payload types.
347
376
 
348
377
  #### Added
@@ -397,7 +426,7 @@ SDK was reconciled against the observed request/response shapes.
397
426
 
398
427
  - **`per_page` was silently ignored on every list call.** The API reads only
399
428
  `per-page`; `per_page` is accepted and discarded, so the response fell back to
400
- 20 items (verified: `?per-page=2` → 2 items, `?per_page=2` → 20). Every list
429
+ 20 items. Every list
401
430
  method's documentation advertised `per_page`, so paging appeared to work while
402
431
  quietly returning the wrong page size. Both spellings are now honoured —
403
432
  `per_page` is normalised to `per-page`, and an explicit `per-page` wins.
@@ -500,22 +529,19 @@ SDK was reconciled against the observed request/response shapes.
500
529
  not return either field, so the old type promised a required `pages` array
501
530
  that was `undefined` at runtime.
502
531
  - **`ICreateAssignmentPayload.copy_receivers` is documented as unreliable.** On
503
- the sandbox plan the API accepts it and persists nothing — verified `[]` from
532
+ the sandbox plan the API accepts it and persists nothing — `[]` from
504
533
  `create`, `list` and `details().assignment`, for both emails and signer IDs.
505
534
  Kept (it may be plan-gated) but do not assume a CC was delivered.
506
535
 
507
536
  ## [1.5.0] - 2026-06-05
508
537
 
509
- Full production-readiness audit against [the live API docs](https://api.assinafy.com.br/v1/docs),
510
- re-verified end-to-end against the live **sandbox** (`https://sandbox.assinafy.com.br/v1`).
511
- Closes the last coverage gap (Template create/update/delete), removes a dead
512
- endpoint, tightens types to the real wire shapes, and modernises the toolchain.
538
+ Adds template management, aligns types with response payloads, and updates the toolchain.
513
539
 
514
540
  ### Removed
515
541
 
516
542
  - **`assignments.cancel`** — it called
517
543
  `POST /accounts/{id}/signature-requests/{id}/cancel`, which is undocumented and
518
- returns `404` on the live API (verified). There is no workspace-side cancel
544
+ returns `404` on the live API. There is no workspace-side cancel
519
545
  endpoint — cancel by deleting the document (`documents.delete`, when its status
520
546
  is deletable) or via the signer-side decline
521
547
  (`signerDocuments.decline(documentId, assignmentId, accessCode, reason)`).
@@ -574,19 +600,10 @@ endpoint, tightens types to the real wire shapes, and modernises the toolchain.
574
600
  for publishing, and npm provenance (`--provenance` + `id-token: write`).
575
601
  - esbuild pinned via `overrides` to keep the bun + npm lockfiles reproducible.
576
602
 
577
- ### Tests
578
-
579
- 113 unit tests pass (`bun test`). New suites cover `TemplateResource` (incl. the
580
- new CRUD), the `BaseResource` helpers (`callOptional` 404→null, `callVoid`,
581
- `callBinary`, `callList`), the rate-limit retry helpers, and assignment/document
582
- response shapes. All read and write paths re-verified against the live sandbox,
583
- including template create/get/update/downloadPage/delete.
584
603
 
585
604
  ## [1.4.0] - 2026-05-27
586
605
 
587
- Full file-by-file audit against [the live API docs](https://api.assinafy.com.br/v1/docs),
588
- re-validated end-to-end against the live API. Closes the last coverage gap (Tags)
589
- and fixes signer-creation and type accuracy.
606
+ Adds tags and fixes signer creation and response types.
590
607
 
591
608
  ### Added
592
609
 
@@ -619,18 +636,9 @@ and fixes signer-creation and type accuracy.
619
636
  is typed as the `{ ip, user-agent }` object the API actually returns, with the
620
637
  event `payload` snapshot added.
621
638
 
622
- ### Tests
623
-
624
- 86 unit tests pass (`bun test`). New `tags` and `documents` suites cover Tag CRUD
625
- and document-tag attach/detach; new signer tests cover WhatsApp-only creation and
626
- CPF normalisation. All read and write paths re-verified against the live API
627
- (`scripts/live-smoke.ts --write`).
628
639
 
629
640
  ## [1.3.0] - 2026-05-12
630
641
 
631
- 100% endpoint coverage of [the live API docs](https://api.assinafy.com.br/v1/docs).
632
- Audited file-by-file and validated end-to-end against the live API.
633
-
634
642
  ### Added
635
643
 
636
644
  - **`AuthenticationResource`** (new — `client.auth`): `login`, `socialLogin`,
@@ -661,16 +669,11 @@ Audited file-by-file and validated end-to-end against the live API.
661
669
  - Live smoke-test script (`scripts/live-smoke.ts`) covering every read-only
662
670
  endpoint plus optional `--write` and `--upload` modes.
663
671
 
664
- ### Tests
665
-
666
- 70 unit tests pass (`bun test`). New suites cover the authentication, fields,
667
- and signer-documents resources. Build + ESM/CJS bundles validated against the
668
- live API.
669
672
 
670
673
  ## [1.2.0] - 2026-05-06
671
674
 
672
- Full API parity audit. Adds the Template resource and missing Document operations, and aligns signer
673
- fields (`cpf`, `whatsapp_phone_number`) with the PHP SDK and n8n node.
675
+ Adds the Template resource and missing Document operations, and expands the
676
+ signer fields with `cpf` and `whatsapp_phone_number`.
674
677
 
675
678
  ### Added
676
679
 
@@ -681,7 +684,7 @@ fields (`cpf`, `whatsapp_phone_number`) with the PHP SDK and n8n node.
681
684
  - `createFromTemplate(templateId, signers, options?, accountId?)` — `POST /accounts/{accountId}/templates/{templateId}/documents`
682
685
  - `estimateCostFromTemplate(templateId, signers, accountId?)` — `POST /accounts/{accountId}/templates/{templateId}/documents/estimate-cost`
683
686
  - `verify(hash)` — `GET /documents/{hash}/verify`
684
- - **`cpf` field** in `ICreateSignerPayload`, `IUpdateSignerPayload`, `ISigner`, and `IUploadAndRequestSignaturesSigner`. The `normaliseSignerPayload` helper strips non-digit characters before sending (mirrors PHP SDK `sanitizeDocument` behaviour).
687
+ - **`cpf` field** in `ICreateSignerPayload`, `IUpdateSignerPayload`, `ISigner`, and `IUploadAndRequestSignaturesSigner`. The `normaliseSignerPayload` helper strips non-digit characters before sending.
685
688
  - New types: `ITemplateListItem`, `ITemplateListResponse`, `ITemplateDetailsResponse`, `ITemplateRole`, `ITemplateSigner`, `ICreateDocumentFromTemplateOptions`.
686
689
  - `TemplateResource` exported from `index.ts`.
687
690
 
@@ -702,7 +705,12 @@ fields (`cpf`, `whatsapp_phone_number`) with the PHP SDK and n8n node.
702
705
  - High-level `uploadAndRequestSignatures` helper on `AssinafyClient`.
703
706
  - `PaginatedResult<T>` with parsed `X-Pagination-*` header meta.
704
707
 
705
- [Unreleased]: https://github.com/assinafy/typescript-sdk/compare/v2.4.0...HEAD
708
+ [Unreleased]: https://github.com/assinafy/typescript-sdk/compare/v2.5.2...HEAD
709
+ [2.5.2]: https://github.com/assinafy/typescript-sdk/compare/v2.5.1...v2.5.2
710
+ [2.5.1]: https://github.com/assinafy/typescript-sdk/compare/v2.5.0...v2.5.1
711
+ [2.5.0]: https://github.com/assinafy/typescript-sdk/compare/v2.4.2...v2.5.0
712
+ [2.4.2]: https://github.com/assinafy/typescript-sdk/compare/v2.4.1...v2.4.2
713
+ [2.4.1]: https://github.com/assinafy/typescript-sdk/compare/v2.4.0...v2.4.1
706
714
  [2.4.0]: https://github.com/assinafy/typescript-sdk/compare/v2.3.0...v2.4.0
707
715
  [2.3.0]: https://github.com/assinafy/typescript-sdk/compare/v2.2.0...v2.3.0
708
716
  [2.2.0]: https://github.com/assinafy/typescript-sdk/compare/v2.1.2...v2.2.0
package/README.en.md CHANGED
@@ -45,7 +45,8 @@ afterwards.
45
45
  [signer-side endpoints](#signer-side-endpoints)
46
46
 
47
47
  **Everything else** — [High-level helper](#high-level-helper) ·
48
- [Errors](#errors) · [Development](#development) · [License](#license)
48
+ [Errors](#errors) · [Environments](#environments) ·
49
+ [Development](#development) · [License](#license)
49
50
 
50
51
  ## Requirements
51
52
 
@@ -172,20 +173,20 @@ const client = new AssinafyClient(); // no credentials needed
172
173
  // completes PKCE, `nonce` validates the id_token.
173
174
  const request = await client.oauth.createAuthorizationUrl({
174
175
  clientId: process.env.ASSINAFY_CLIENT_ID!,
175
- redirectUri: 'https://myapp.com/oauth/callback',
176
+ redirectUri: 'https://myapp.example.com/oauth/callback',
176
177
  scopes: ['documents:read', 'documents:write', 'offline_access'],
177
178
  });
178
179
  session.oauth = request;
179
180
  response.redirect(request.url); // full page navigation
180
181
 
181
- // 2 — on https://myapp.com/oauth/callback
182
+ // 2 — on https://myapp.example.com/oauth/callback
182
183
  const { code } = client.oauth.readAuthorizationCallback(query, session.oauth);
183
184
  const tokens = await client.oauth.exchangeCode({
184
185
  code,
185
186
  codeVerifier: session.oauth.codeVerifier,
186
- redirectUri: 'https://myapp.com/oauth/callback',
187
+ redirectUri: 'https://myapp.example.com/oauth/callback',
187
188
  clientId: process.env.ASSINAFY_CLIENT_ID!,
188
- clientSecret: process.env.ASSINAFY_CLIENT_SECRET, // confidential apps only
189
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!, // confidential apps only
189
190
  });
190
191
  // → { access_token, token_type: 'Bearer', expires_in: 3600,
191
192
  // scope: 'documents:read documents:write',
@@ -200,7 +201,7 @@ const accountId = data[0]?.id; // store it with the tokens
200
201
  const renewed = await client.oauth.refreshToken({
201
202
  refreshToken: connection.refreshToken,
202
203
  clientId: process.env.ASSINAFY_CLIENT_ID!,
203
- clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
204
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
204
205
  });
205
206
  await connection.save({ refreshToken: renewed.refresh_token }); // BEFORE using it
206
207
 
@@ -210,7 +211,7 @@ await client.oauth.revokeToken({
210
211
  token: current.refreshToken,
211
212
  tokenTypeHint: 'refresh_token',
212
213
  clientId: process.env.ASSINAFY_CLIENT_ID!,
213
- clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
214
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
214
215
  });
215
216
  ```
216
217
 
@@ -377,7 +378,7 @@ display-name override (used as that file part's filename) and an optional JSON
377
378
  `IDocumentUploadResponse`:
378
379
 
379
380
  ```ts
380
- {
381
+ type DocumentUploadShape = {
381
382
  resource?: string;
382
383
  id: string;
383
384
  account_id: string;
@@ -401,7 +402,7 @@ display-name override (used as that file part's filename) and an optional JSON
401
402
  is_closed: boolean;
402
403
  decline_reason: string | null;
403
404
  declined_by: ISigner | null;
404
- }
405
+ };
405
406
  ```
406
407
 
407
408
  `DocumentStatus` covers `uploading`, `uploaded`, `metadata_processing`,
@@ -437,7 +438,7 @@ const signerB = await client.signers.create({
437
438
  The wire body is `{ full_name, email }`. Each response is an `ISigner`:
438
439
 
439
440
  ```ts
440
- {
441
+ type SignerShape = {
441
442
  resource?: string;
442
443
  id: string;
443
444
  full_name: string;
@@ -449,7 +450,7 @@ The wire body is `{ full_name, email }`. Each response is an `ISigner`:
449
450
  has_initial?: boolean; // signer-self response only
450
451
  is_signature_reusable?: boolean; // signer-self response only
451
452
  metadata?: Record<string, unknown>;
452
- }
453
+ };
453
454
  ```
454
455
 
455
456
  When an email is present, `signers.create()` first looks up that email in the
@@ -506,7 +507,7 @@ const assignment = await client.assignments.create(uploaded.id, {
506
507
  The request returns an `IAssignment`:
507
508
 
508
509
  ```ts
509
- {
510
+ type AssignmentShape = {
510
511
  resource?: string;
511
512
  id: string;
512
513
  sender_email?: string;
@@ -523,7 +524,7 @@ The request returns an `IAssignment`:
523
524
  signers: Array<ISigner & { completed?: boolean }>;
524
525
  };
525
526
  signing_urls?: Array<{ signer_id: string; url: string }>;
526
- }
527
+ };
527
528
  ```
528
529
 
529
530
  The URLs and delivered messages contain signer credentials; treat them as
@@ -555,7 +556,7 @@ await signerClient.signerDocuments.verifyEmail({
555
556
  const confirmed = await signerClient.signerDocuments.confirmData(
556
557
  uploaded.id,
557
558
  accessCode,
558
- { full_name: self.full_name, email: self.email ?? undefined },
559
+ { full_name: self.full_name, ...(self.email === null ? {} : { email: self.email }) },
559
560
  ); // ISigner
560
561
 
561
562
  const signable = await signerClient.signerDocuments.getAssignment(accessCode, true);
@@ -575,8 +576,8 @@ can sign in parallel.
575
576
  accessCode, entries)` with a non-empty array of
576
577
  `{ itemId, fieldId, pageId, value }`. A virtual signer must confirm their data
577
578
  before signing. A `DigitalCertificate` signer cannot call `sign`; that branch
578
- uses Assinafy's certificate-start and certificate-complete flow, which is not
579
- part of this SDK's current 89-operation surface.
579
+ uses Assinafy's certificate flow, described in
580
+ [ICP-Brasil digital certificate](#icp-brasil-digital-certificate).
580
581
 
581
582
  ### 5. Observe completion and download artifacts
582
583
 
@@ -616,10 +617,10 @@ const doc = await client.documents.upload(
616
617
  { filePath: './contract.pdf' },
617
618
  { name: 'Service agreement', metadata: { type: 'service' } },
618
619
  );
619
- // `name` and `metadata` are compatibility multipart parts outside the published
620
- // file-only request schema.
621
- // `name` is optional and defaults to the file's own name. The API derives the
622
- // display name from the uploaded filename and appends `.pdf` when absent, so
620
+ // `metadata` is a compatibility multipart part outside the published schema.
621
+ // `name` sets the filename of the file part; it is not sent as a separate field.
622
+ // When omitted, it defaults to the original filename. The API appends `.pdf`
623
+ // when absent, so
623
624
  // the document above is stored as 'Service agreement.pdf'. Accents are
624
625
  // transliterated by the API ('Contrato de Serviço' → 'Contrato de Servico.pdf').
625
626
  // → {
@@ -826,6 +827,19 @@ Keep the email flow as the default. Enable either branch below only after the
826
827
  workspace has the required plan or feature and the returned cost estimate is
827
828
  acceptable.
828
829
 
830
+ The verification method and the notification method are **coupled**: send one,
831
+ both, or neither — the missing side is inferred. With neither, both default
832
+ to `Email`.
833
+
834
+ | Verification | How the signer proves who they are | Allowed notification | Cost per signer |
835
+ | --- | --- | --- | --- |
836
+ | `Email` *(default)* | One-time code (OTP) by email | `Email` | Free |
837
+ | `Whatsapp` | One-time code (OTP) by WhatsApp | `Whatsapp` | 0.45 credit (the notification), paid plans only |
838
+ | `DigitalCertificate` | The signer signs with their **own ICP-Brasil certificate — A1 or A3 —** through the Web PKI extension, producing a **qualified PAdES signature** | `Email` **or** `Whatsapp` | 2 credits + the notification |
839
+
840
+ Exactly one notification method per signer. The SDK rejects an invalid
841
+ combination before the request; the API would answer `400`.
842
+
829
843
  #### WhatsApp verification and notification
830
844
 
831
845
  WhatsApp is available only on paid subscriptions and costs 0.45 credit per
@@ -871,6 +885,14 @@ signer's `government_id`, and exactly one certificate signer in that signing
871
885
  step. It costs two credits per certificate signer in addition to the selected
872
886
  notification cost.
873
887
 
888
+ **A1 and A3 are certificate media**, chosen by the signer in their browser at
889
+ signing time: A1 lives in software (a file on the machine) and A3 in hardware
890
+ (a token or smartcard). The API models both with the single
891
+ `DigitalCertificate` value — there is no `A1`/`A3` field to send, and the
892
+ resulting PAdES signature is qualified in either case. Certificate signers
893
+ complete a Web PKI handshake on two production-only routes that are not part
894
+ of this SDK.
895
+
874
896
  ```ts
875
897
  const certificateSigner = await client.signers.update(signerId, {
876
898
  government_id: '390.533.447-05',
@@ -1143,7 +1165,7 @@ retains only the first 2,000 characters of the receiver's response body.
1143
1165
  Each history or retry result is an `IWebhookDispatch`:
1144
1166
 
1145
1167
  ```ts
1146
- {
1168
+ type WebhookDispatchShape = {
1147
1169
  resource?: string;
1148
1170
  id: string;
1149
1171
  event: string;
@@ -1156,13 +1178,13 @@ Each history or retry result is an `IWebhookDispatch`:
1156
1178
  error: string | null;
1157
1179
  created_at: string;
1158
1180
  updated_at?: string;
1159
- }
1181
+ };
1160
1182
  ```
1161
1183
 
1162
1184
  Every delivery body uses this envelope:
1163
1185
 
1164
1186
  ```ts
1165
- {
1187
+ type WebhookPayloadShape = {
1166
1188
  id: number; // use for idempotent processing
1167
1189
  event: string;
1168
1190
  message: string | null;
@@ -1172,7 +1194,7 @@ Every delivery body uses this envelope:
1172
1194
  subject: { type: 'User' | 'Signer' | 'Account' | 'Document' | 'Template'; [key: string]: unknown };
1173
1195
  object: { type: 'User' | 'Signer' | 'Account' | 'Document' | 'Template'; [key: string]: unknown };
1174
1196
  account_id: string;
1175
- }
1197
+ };
1176
1198
  ```
1177
1199
 
1178
1200
  Event-specific values are:
@@ -1340,7 +1362,8 @@ whether to retry the workflow.
1340
1362
  ## Errors
1341
1363
 
1342
1364
  HTTP methods reject with an `AssinafyError` subclass. Synchronous helpers such
1343
- as `getSocialLoginUrl()` can throw `ValidationError` before any request.
1365
+ as `getSocialLoginUrl()` and `readAuthorizationCallback()` can throw
1366
+ `ValidationError` before any request.
1344
1367
 
1345
1368
  ```ts
1346
1369
  import { ApiError, OAuthError, ValidationError, NetworkError, AssinafyError } from '@assinafy/sdk';
@@ -1365,6 +1388,35 @@ try {
1365
1388
  }
1366
1389
  ```
1367
1390
 
1391
+ ## Environments
1392
+
1393
+ | | |
1394
+ | --- | --- |
1395
+ | Production | `https://api.assinafy.com.br/v1` |
1396
+ | Sandbox | `https://sandbox.assinafy.com.br/v1` |
1397
+
1398
+ The sandbox runs its own authorization server at
1399
+ `https://auth-sandbox.assinafy.com.br`, with the consent screen at
1400
+ `/oauth/authorize`. Discovery is available and selects that server from the
1401
+ configured `baseUrl`:
1402
+
1403
+ ```ts
1404
+ const client = new AssinafyClient({ baseUrl: 'https://sandbox.assinafy.com.br/v1' });
1405
+ const metadata = await client.oauth.getAuthorizationServerMetadata();
1406
+ const request = await client.oauth.createAuthorizationUrl({
1407
+ clientId: process.env.ASSINAFY_CLIENT_ID!,
1408
+ redirectUri: 'https://myapp.example.com/oauth/callback',
1409
+ scopes: ['documents:read', 'account:read', 'offline_access'],
1410
+ });
1411
+ ```
1412
+
1413
+ Register the application in the matching environment. Production and sandbox
1414
+ have separate issuers, client IDs, credentials and workspaces; keep each
1415
+ connection entirely in one environment. Token, revocation and userinfo requests
1416
+ use the configured `baseUrl`. For local testing, expose only the callback
1417
+ through an HTTPS tunnel, register its exact URL and revoke tokens afterward.
1418
+ See [docs/COMPATIBILITY.md](docs/COMPATIBILITY.md).
1419
+
1368
1420
  ## Development
1369
1421
 
1370
1422
  ```bash
package/README.md CHANGED
@@ -165,20 +165,20 @@ const client = new AssinafyClient(); // nenhuma credencial nece
165
165
  // PKCE e `nonce` valida o id_token.
166
166
  const requisicao = await client.oauth.createAuthorizationUrl({
167
167
  clientId: process.env.ASSINAFY_CLIENT_ID!,
168
- redirectUri: 'https://meuapp.com.br/oauth/callback',
168
+ redirectUri: 'https://meuapp.exemplo.com.br/oauth/callback',
169
169
  scopes: ['documents:read', 'documents:write', 'offline_access'],
170
170
  });
171
171
  sessao.oauth = requisicao;
172
172
  resposta.redirect(requisicao.url); // navegação de página inteira
173
173
 
174
- // 2 — em https://meuapp.com.br/oauth/callback
174
+ // 2 — em https://meuapp.exemplo.com.br/oauth/callback
175
175
  const { code } = client.oauth.readAuthorizationCallback(query, sessao.oauth);
176
176
  const tokens = await client.oauth.exchangeCode({
177
177
  code,
178
178
  codeVerifier: sessao.oauth.codeVerifier,
179
- redirectUri: 'https://meuapp.com.br/oauth/callback',
179
+ redirectUri: 'https://meuapp.exemplo.com.br/oauth/callback',
180
180
  clientId: process.env.ASSINAFY_CLIENT_ID!,
181
- clientSecret: process.env.ASSINAFY_CLIENT_SECRET, // só aplicações confidenciais
181
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!, // só aplicações confidenciais
182
182
  });
183
183
  // → { access_token, token_type: 'Bearer', expires_in: 3600,
184
184
  // scope: 'documents:read documents:write',
@@ -193,7 +193,7 @@ const accountId = data[0]?.id; // guarde junto com os tok
193
193
  const renovado = await client.oauth.refreshToken({
194
194
  refreshToken: conexao.refreshToken,
195
195
  clientId: process.env.ASSINAFY_CLIENT_ID!,
196
- clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
196
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
197
197
  });
198
198
  await conexao.save({ refreshToken: renovado.refresh_token }); // ANTES de usar
199
199
 
@@ -203,7 +203,7 @@ await client.oauth.revokeToken({
203
203
  token: atual.refreshToken,
204
204
  tokenTypeHint: 'refresh_token',
205
205
  clientId: process.env.ASSINAFY_CLIENT_ID!,
206
- clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
206
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
207
207
  });
208
208
  ```
209
209
 
@@ -359,7 +359,7 @@ nome de arquivo dessa parte) e uma parte JSON `metadata` opcional, para deploys
359
359
  resposta de sucesso é `IDocumentUploadResponse`:
360
360
 
361
361
  ```ts
362
- {
362
+ type DocumentUploadShape = {
363
363
  resource?: string;
364
364
  id: string;
365
365
  account_id: string;
@@ -383,7 +383,7 @@ resposta de sucesso é `IDocumentUploadResponse`:
383
383
  is_closed: boolean;
384
384
  decline_reason: string | null;
385
385
  declined_by: ISigner | null;
386
- }
386
+ };
387
387
  ```
388
388
 
389
389
  `DocumentStatus` cobre `uploading`, `uploaded`, `metadata_processing`, `metadata_ready`,
@@ -418,7 +418,7 @@ const signatarioB = await client.signers.create({
418
418
  O corpo de rede é `{ full_name, email }`. Cada resposta é um `ISigner`:
419
419
 
420
420
  ```ts
421
- {
421
+ type SignerShape = {
422
422
  resource?: string;
423
423
  id: string;
424
424
  full_name: string;
@@ -430,7 +430,7 @@ O corpo de rede é `{ full_name, email }`. Cada resposta é um `ISigner`:
430
430
  has_initial?: boolean; // só na resposta de signers/self
431
431
  is_signature_reusable?: boolean; // só na resposta de signers/self
432
432
  metadata?: Record<string, unknown>;
433
- }
433
+ };
434
434
  ```
435
435
 
436
436
  Quando há e-mail, `signers.create()` primeiro procura esse endereço no workspace e reaproveita o
@@ -486,7 +486,7 @@ const assignment = await client.assignments.create(enviado.id, {
486
486
  A requisição devolve um `IAssignment`:
487
487
 
488
488
  ```ts
489
- {
489
+ type AssignmentShape = {
490
490
  resource?: string;
491
491
  id: string;
492
492
  sender_email?: string;
@@ -503,7 +503,7 @@ A requisição devolve um `IAssignment`:
503
503
  signers: Array<ISigner & { completed?: boolean }>;
504
504
  };
505
505
  signing_urls?: Array<{ signer_id: string; url: string }>;
506
- }
506
+ };
507
507
  ```
508
508
 
509
509
  As URLs e as mensagens entregues contêm credenciais do signatário; trate-as como segredo.
@@ -531,7 +531,7 @@ await clienteSignatario.signerDocuments.verifyEmail({
531
531
  const confirmado = await clienteSignatario.signerDocuments.confirmData(
532
532
  enviado.id,
533
533
  accessCode,
534
- { full_name: self.full_name, email: self.email ?? undefined },
534
+ { full_name: self.full_name, ...(self.email === null ? {} : { email: self.email }) },
535
535
  ); // ISigner
536
536
 
537
537
  const assinavel = await clienteSignatario.signerDocuments.getAssignment(accessCode, true);
@@ -588,9 +588,9 @@ const doc = await client.documents.upload(
588
588
  { filePath: './contrato.pdf' },
589
589
  { name: 'Contrato de prestação', metadata: { tipo: 'servico' } },
590
590
  );
591
- // `name` e `metadata` são partes multipart de compatibilidade, fora do schema
592
- // oficial (que só define o arquivo). `name` é opcional e assume o nome do
593
- // arquivo. A API deriva o nome de exibição do arquivo enviado e acrescenta
591
+ // `metadata` é uma parte multipart de compatibilidade fora do schema oficial.
592
+ // `name` define o nome do arquivo na parte multipart; não é enviado como campo
593
+ // separado. Se omitido, usa o nome do arquivo original. A API acrescenta
594
594
  // `.pdf` quando falta, então o documento acima é salvo como
595
595
  // 'Contrato de prestação.pdf'. A API translitera acentos
596
596
  // ('Contrato de Serviço' → 'Contrato de Servico.pdf').
@@ -1138,7 +1138,7 @@ primeiros 2.000 caracteres do corpo de resposta do receptor.
1138
1138
  Cada item do histórico (ou resultado de reenvio) é um `IWebhookDispatch`:
1139
1139
 
1140
1140
  ```ts
1141
- {
1141
+ type WebhookDispatchShape = {
1142
1142
  resource?: string;
1143
1143
  id: string;
1144
1144
  event: string;
@@ -1151,13 +1151,13 @@ Cada item do histórico (ou resultado de reenvio) é um `IWebhookDispatch`:
1151
1151
  error: string | null;
1152
1152
  created_at: string;
1153
1153
  updated_at?: string;
1154
- }
1154
+ };
1155
1155
  ```
1156
1156
 
1157
1157
  Todo corpo de entrega usa este envelope:
1158
1158
 
1159
1159
  ```ts
1160
- {
1160
+ type WebhookPayloadShape = {
1161
1161
  id: number; // use para processamento idempotente
1162
1162
  event: string;
1163
1163
  message: string | null;
@@ -1167,7 +1167,7 @@ Todo corpo de entrega usa este envelope:
1167
1167
  subject: { type: 'User' | 'Signer' | 'Account' | 'Document' | 'Template'; [key: string]: unknown };
1168
1168
  object: { type: 'User' | 'Signer' | 'Account' | 'Document' | 'Template'; [key: string]: unknown };
1169
1169
  account_id: string;
1170
- }
1170
+ };
1171
1171
  ```
1172
1172
 
1173
1173
  Os valores por evento são:
@@ -1371,23 +1371,23 @@ try {
1371
1371
  | Sandbox | `https://sandbox.assinafy.com.br/v1` |
1372
1372
 
1373
1373
  O sandbox tem servidor de autorização próprio em `https://auth-sandbox.assinafy.com.br`, com a tela
1374
- de consentimento em `/oauth/authorize`. Os documentos de descoberta dele não são alcançáveis:
1375
- o nginx recusa caminhos iniciados por ponto, então informe os endpoints explicitamente:
1374
+ de consentimento em `/oauth/authorize`. A descoberta está disponível e seleciona esse servidor
1375
+ automaticamente a partir do `baseUrl`:
1376
1376
 
1377
1377
  ```ts
1378
1378
  const client = new AssinafyClient({ baseUrl: 'https://sandbox.assinafy.com.br/v1' });
1379
-
1379
+ const metadados = await client.oauth.getAuthorizationServerMetadata();
1380
1380
  const requisicao = await client.oauth.createAuthorizationUrl({
1381
1381
  clientId: process.env.ASSINAFY_CLIENT_ID!,
1382
- redirectUri: 'https://meuapp.com.br/oauth/callback',
1383
- scopes: ['documents:read'],
1384
- issuer: 'https://auth-sandbox.assinafy.com.br',
1385
- authorizationEndpoint: 'https://auth-sandbox.assinafy.com.br/oauth/authorize',
1382
+ redirectUri: 'https://meuapp.exemplo.com.br/oauth/callback',
1383
+ scopes: ['documents:read', 'account:read', 'offline_access'],
1386
1384
  });
1387
1385
  ```
1388
1386
 
1389
- Os endpoints de token, revogação e userinfo seguem o `baseUrl` configurado. Confirme que o sandbox
1390
- os expõe antes de rodar a etapa de troca por lá — veja
1387
+ Cadastre o aplicativo no ambiente correspondente. Produção e sandbox têm emissores, client IDs,
1388
+ credenciais e workspaces próprios: mantenha cada conexão inteira no mesmo ambiente. Token,
1389
+ revogação e userinfo usam o `baseUrl` configurado. Para testar localmente, exponha somente o
1390
+ callback por um túnel HTTPS, registre a URL exata e revogue os tokens ao terminar. Veja
1391
1391
  [docs/COMPATIBILITY.md](docs/COMPATIBILITY.md).
1392
1392
 
1393
1393
  ## Desenvolvimento