@assinafy/sdk 2.4.2 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.5.0] - 2026-09-25
11
+
12
+ ### Added
13
+
14
+ - `IDocumentVerification.agreement_code`: the agreement code printed on the
15
+ document certificate, returned by `documents.verify()` (`null` when the hash
16
+ does not verify).
17
+
18
+ ### Changed
19
+
20
+ - `oauth.exchangeCode()`, `oauth.refreshToken()` and `oauth.revokeToken()` send
21
+ `application/x-www-form-urlencoded` bodies, the encoding RFC 6749 and RFC 7009
22
+ define. The fields are unchanged.
23
+ - `oauth.readAuthorizationCallback()` always checks `iss`. When the stored
24
+ request carries no `issuer`, the callback must come from
25
+ `https://auth.assinafy.com.br`; pass the stored request for any other
26
+ authorization server, such as the sandbox's.
27
+
28
+ ### Security
29
+
30
+ - `oauth.refreshToken()` rejects a successful response that carries no
31
+ replacement `refresh_token` instead of returning it: the token that was sent
32
+ has already been retired, so the connection must be re-established.
33
+ - Migration: callers of `oauth.readAuthorizationCallback()` that stored only
34
+ `state` now get the production issuer check; callbacks without `iss` are
35
+ refused. Store and pass the whole authorization request.
36
+
37
+ ### Fixed
38
+
39
+ - The OAuth documentation describes the refresh-token lifetime correctly: a
40
+ refresh token is valid for 30 days and every refresh returns a new one with a
41
+ fresh 30 days, so a connection only expires after 30 days without a refresh.
42
+ - The README OAuth example revokes the most recently saved refresh token, and
43
+ the docs say never to resend a refresh token after an ambiguous timeout.
44
+
10
45
  ## [2.4.2] - 2026-09-23
11
46
 
12
47
  ### Changed
package/README.en.md CHANGED
@@ -53,6 +53,8 @@ afterwards.
53
53
  CJS and ESM imports are tested on 22 (maintenance LTS), 24 (active LTS), and
54
54
  26 (Current); Node 20 reached end-of-life in April 2026 and is unsupported.
55
55
  - or Bun 1.4.0 (the version pinned for development and CI)
56
+ - HTTPS with TLS 1.2 or higher, which the API requires; Node.js 22+ and Bun
57
+ negotiate it by default
56
58
 
57
59
  ## Installation
58
60
 
@@ -202,9 +204,10 @@ const renewed = await client.oauth.refreshToken({
202
204
  });
203
205
  await connection.save({ refreshToken: renewed.refresh_token }); // BEFORE using it
204
206
 
205
- // 5 — when the user disconnects
207
+ // 5 — when the user disconnects: revoke the token you saved most recently
208
+ const current = await connection.load(); // never a retired copy
206
209
  await client.oauth.revokeToken({
207
- token: connection.refreshToken,
210
+ token: current.refreshToken,
208
211
  tokenTypeHint: 'refresh_token',
209
212
  clientId: process.env.ASSINAFY_CLIENT_ID!,
210
213
  clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
@@ -274,11 +277,15 @@ try {
274
277
 
275
278
  Refresh tokens **rotate**: every refresh returns a new one and retires the old
276
279
  one, and replaying a retired token ends the entire connection. Persist the new
277
- value before using the response, treat a timeout as "it may have worked" and
278
- re-read your stored token instead of retrying blindly, and never refresh one
279
- connection twice concurrently. A connection lasts 30 days from approval however
280
- often it is refreshed, and the authorize/token endpoints accept 50 requests per
281
- minute per IP.
280
+ value before using the response, and never refresh one connection twice
281
+ concurrently. Treat a timeout as "it may have worked": re-read your stored
282
+ token, and if it is still the one you sent, never send it again — ask the user
283
+ to reconnect. Only a failure that provably happened before sending (DNS,
284
+ refused connection, TLS handshake) is safe to retry. A refresh token is valid for 30 days, and every
285
+ refresh returns a new one with a fresh 30 days: a connection only expires if
286
+ your app goes 30 days without refreshing it, after which the user has to
287
+ connect again. The authorize/token endpoints accept 50 requests per minute per
288
+ IP.
282
289
 
283
290
  AI assistants such as Claude, Claude Code and ChatGPT connect to Assinafy
284
291
  through their own connector settings; your users do not need you to register
package/README.md CHANGED
@@ -49,6 +49,7 @@ recurso. Leia na ordem na primeira vez; use como referência depois.
49
49
  empacotados são testados no 22 (LTS de manutenção), 24 (LTS ativo) e 26 (Current). O Node 20
50
50
  chegou ao fim da vida em abril de 2026 e não é suportado.
51
51
  - ou Bun 1.4.0 (versão fixada no desenvolvimento e na CI)
52
+ - HTTPS com TLS 1.2 ou superior, exigido pela API; o Node.js 22+ e o Bun já negociam isso por padrão
52
53
 
53
54
  ## Instalação
54
55
 
@@ -196,9 +197,10 @@ const renovado = await client.oauth.refreshToken({
196
197
  });
197
198
  await conexao.save({ refreshToken: renovado.refresh_token }); // ANTES de usar
198
199
 
199
- // 5 — quando o usuário desconectar
200
+ // 5 — quando o usuário desconectar: revogue o token salvo mais recentemente
201
+ const atual = await conexao.load(); // nunca uma cópia aposentada
200
202
  await client.oauth.revokeToken({
201
- token: conexao.refreshToken,
203
+ token: atual.refreshToken,
202
204
  tokenTypeHint: 'refresh_token',
203
205
  clientId: process.env.ASSINAFY_CLIENT_ID!,
204
206
  clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
@@ -267,10 +269,13 @@ try {
267
269
 
268
270
  Refresh tokens **rotacionam**: cada renovação devolve um novo e aposenta o anterior, e reutilizar um
269
271
  token aposentado encerra a conexão inteira. Persista o novo valor antes de usar a resposta, trate um
270
- timeout como "talvez tenha funcionado" — releia o token guardado em vez de repetir às cegas — e
271
- nunca renove a mesma conexão duas vezes em paralelo. Uma conexão dura 30 dias a partir da aprovação,
272
- por mais que seja renovada, e os endpoints de autorização e token aceitam 50 requisições por minuto
273
- por IP.
272
+ timeout como "talvez tenha funcionado" e nunca renove a mesma conexão duas vezes em paralelo. Após
273
+ um timeout, releia o token guardado; se ainda for o enviado, nunca o envie de novo — peça ao
274
+ usuário para reconectar. Só uma falha que comprovadamente ocorreu antes do envio (DNS, conexão
275
+ recusada, handshake TLS) pode ser repetida. Um refresh token vale 30 dias, e cada renovação
276
+ devolve um novo com mais 30 dias: a conexão só expira se o seu app passar 30 dias sem renová-la, e
277
+ aí o usuário precisa conectar de novo. Os endpoints de autorização e token aceitam 50 requisições
278
+ por minuto por IP.
274
279
 
275
280
  Assistentes de IA como Claude, Claude Code e ChatGPT se conectam à Assinafy pelas próprias
276
281
  configurações de conector; seus usuários não precisam que você registre nada para eles.
package/SECURITY.md CHANGED
@@ -43,11 +43,12 @@ opportunity to upgrade.
43
43
  - Protected resources require explicit account credentials. Public,
44
44
  authentication, and signer-access-code flows use an auth-free transport so
45
45
  configured account credentials are not sent to public endpoints.
46
- - Consumers must use HTTPS endpoints and protect all SDK configuration as
47
- secrets. The client enforces this: a `baseUrl` using plaintext `http` is
48
- rejected unless its host is loopback, so a credential cannot be sent in the
49
- clear to a remote host. Debug logging and error telemetry must be reviewed
50
- for response data before being enabled in production.
46
+ - Consumers must use HTTPS endpoints (TLS 1.2 or higher) and protect all SDK
47
+ configuration as secrets. The client enforces this: a `baseUrl` using
48
+ plaintext `http` is rejected unless its host is loopback, so a credential
49
+ cannot be sent in the clear to a remote host. Debug logging and error
50
+ telemetry must be reviewed for response data before being enabled in
51
+ production.
51
52
  - An OAuth `client_secret` belongs only on a server you control: never in
52
53
  browser code, a mobile application, or a repository. A public application has
53
54
  no secret and authenticates with PKCE alone. The SDK sends the token and
package/dist/index.d.mts CHANGED
@@ -961,6 +961,11 @@ interface IPublicDocumentInfo extends Partial<Omit<IDocumentDetailsResponse, 'id
961
961
  interface IDocumentVerification {
962
962
  hash: string;
963
963
  id: string | null;
964
+ /**
965
+ * Agreement code printed on the document certificate; `null` when the hash
966
+ * does not verify. Absent from deployments that predate the field.
967
+ */
968
+ agreement_code?: string | null;
964
969
  status: DocumentStatus | AnyString | null;
965
970
  page_count: string | null;
966
971
  signer_count: string | null;
@@ -2006,6 +2011,7 @@ declare class DocumentResource extends BaseResource {
2006
2011
  * {
2007
2012
  * "hash": "FE32EDDADE7CBDDCBB934E7402047450B0E59C02",
2008
2013
  * "id": "63ddb172402799bfc991d10d",
2014
+ * "agreement_code": "550E8400-E29B-41D4-A716-446655440000", // printed on the certificate
2009
2015
  * "status": "certificated",
2010
2016
  * "page_count": "1",
2011
2017
  * "signer_count": "1",
@@ -4198,8 +4204,9 @@ type TokenEndpointAuthOptions = {
4198
4204
  * disconnects.
4199
4205
  *
4200
4206
  * Two facts that cause most integration bugs: a token works for exactly one
4201
- * workspace (any other answers `403`), and a connection expires 30 days after
4202
- * approval no matter how often it is refreshed.
4207
+ * workspace (any other answers `403`), and every refresh returns a new refresh
4208
+ * token that retires the old one. Each new refresh token is valid for a fresh
4209
+ * 30 days, so a connection only expires after 30 days without a refresh.
4203
4210
  *
4204
4211
  * @example
4205
4212
  * ```ts
@@ -4398,8 +4405,7 @@ declare class OAuthResource extends BaseResource {
4398
4405
  *
4399
4406
  * The `iss` check is strict because the authorization server advertises
4400
4407
  * RFC 9207 support and always sends the parameter: a missing `iss` is
4401
- * treated exactly like a wrong one. Omit `expected.issuer` only if
4402
- * something between the browser and your handler strips query parameters.
4408
+ * treated exactly like a wrong one, on success and error responses alike.
4403
4409
  *
4404
4410
  * This performs no network I/O.
4405
4411
  *
@@ -4407,7 +4413,9 @@ declare class OAuthResource extends BaseResource {
4407
4413
  * `req.query` record, a `URLSearchParams`, a `URL`, a full callback URL
4408
4414
  * string, or a bare `a=b&c=d` query string.
4409
4415
  * @param expected - The stored {@link IOAuthAuthorizationRequest} (or any
4410
- * object carrying its `state` and `issuer`).
4416
+ * object carrying its `state` and `issuer`). Without `issuer`, `iss` must
4417
+ * equal `https://auth.assinafy.com.br`; pass the stored one for any other
4418
+ * authorization server, such as the sandbox's.
4411
4419
  * @returns The validated response:
4412
4420
  * ```jsonc
4413
4421
  * {
@@ -4513,7 +4521,9 @@ declare class OAuthResource extends BaseResource {
4513
4521
  * and re-read your stored token instead of retrying blindly, and never run
4514
4522
  * two refreshes concurrently for one connection.
4515
4523
  *
4516
- * Refreshing does not extend the connection's 30-day life.
4524
+ * Each returned refresh token is valid for a fresh 30 days, so a connection
4525
+ * only expires if it goes 30 days without a refresh; after that the user
4526
+ * has to reconnect.
4517
4527
  *
4518
4528
  * @param options - Refresh options.
4519
4529
  * @param options.refreshToken - The current refresh token.
@@ -4521,7 +4531,8 @@ declare class OAuthResource extends BaseResource {
4521
4531
  * @param options.clientSecret - The `client_secret`, for confidential
4522
4532
  * applications only.
4523
4533
  * @param options.resource - RFC 8707 resource indicator. Defaults to this
4524
- * API's origin; pass `null` to omit it.
4534
+ * API's origin; pass `null` to omit it. A refresh may repeat the value the
4535
+ * connection was authorized with but never change it (`invalid_target`).
4525
4536
  * @returns A fresh token set, identical in shape to
4526
4537
  * {@link OAuthResource.exchangeCode}:
4527
4538
  * ```jsonc
@@ -4571,14 +4582,9 @@ declare class OAuthResource extends BaseResource {
4571
4582
  * @param options.tokenTypeHint - Optional `access_token` or
4572
4583
  * `refresh_token` hint that lets the server skip a lookup.
4573
4584
  * @returns Nothing; resolves once the API acknowledges the request.
4574
- * Request body:
4575
- * ```jsonc
4576
- * {
4577
- * "token": "def50200f1e2…",
4578
- * "token_type_hint": "refresh_token",
4579
- * "client_id": "cli_1a2b3c",
4580
- * "client_secret": "…"
4581
- * }
4585
+ * Request body (`application/x-www-form-urlencoded`):
4586
+ * ```text
4587
+ * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
4582
4588
  * ```
4583
4589
  * @throws {ValidationError} If `token` or `clientId` is missing, or
4584
4590
  * `tokenTypeHint` is not one of the two documented values.
@@ -4631,7 +4637,12 @@ declare class OAuthResource extends BaseResource {
4631
4637
  * ```
4632
4638
  */
4633
4639
  getUserInfo(accessToken?: string): Promise<IOAuthUserInfo>;
4634
- /** POST the token endpoint and assert the response actually carries a token. */
4640
+ /**
4641
+ * POST the token endpoint once and assert the response carries a token.
4642
+ *
4643
+ * Never retried: the code is single-use, and replaying a refresh token the
4644
+ * server may already have rotated ends the whole connection.
4645
+ */
4635
4646
  private requestToken;
4636
4647
  /** `client_secret_post` credentials, omitting the secret for public clients. */
4637
4648
  private clientAuth;
package/dist/index.d.ts CHANGED
@@ -961,6 +961,11 @@ interface IPublicDocumentInfo extends Partial<Omit<IDocumentDetailsResponse, 'id
961
961
  interface IDocumentVerification {
962
962
  hash: string;
963
963
  id: string | null;
964
+ /**
965
+ * Agreement code printed on the document certificate; `null` when the hash
966
+ * does not verify. Absent from deployments that predate the field.
967
+ */
968
+ agreement_code?: string | null;
964
969
  status: DocumentStatus | AnyString | null;
965
970
  page_count: string | null;
966
971
  signer_count: string | null;
@@ -2006,6 +2011,7 @@ declare class DocumentResource extends BaseResource {
2006
2011
  * {
2007
2012
  * "hash": "FE32EDDADE7CBDDCBB934E7402047450B0E59C02",
2008
2013
  * "id": "63ddb172402799bfc991d10d",
2014
+ * "agreement_code": "550E8400-E29B-41D4-A716-446655440000", // printed on the certificate
2009
2015
  * "status": "certificated",
2010
2016
  * "page_count": "1",
2011
2017
  * "signer_count": "1",
@@ -4198,8 +4204,9 @@ type TokenEndpointAuthOptions = {
4198
4204
  * disconnects.
4199
4205
  *
4200
4206
  * Two facts that cause most integration bugs: a token works for exactly one
4201
- * workspace (any other answers `403`), and a connection expires 30 days after
4202
- * approval no matter how often it is refreshed.
4207
+ * workspace (any other answers `403`), and every refresh returns a new refresh
4208
+ * token that retires the old one. Each new refresh token is valid for a fresh
4209
+ * 30 days, so a connection only expires after 30 days without a refresh.
4203
4210
  *
4204
4211
  * @example
4205
4212
  * ```ts
@@ -4398,8 +4405,7 @@ declare class OAuthResource extends BaseResource {
4398
4405
  *
4399
4406
  * The `iss` check is strict because the authorization server advertises
4400
4407
  * RFC 9207 support and always sends the parameter: a missing `iss` is
4401
- * treated exactly like a wrong one. Omit `expected.issuer` only if
4402
- * something between the browser and your handler strips query parameters.
4408
+ * treated exactly like a wrong one, on success and error responses alike.
4403
4409
  *
4404
4410
  * This performs no network I/O.
4405
4411
  *
@@ -4407,7 +4413,9 @@ declare class OAuthResource extends BaseResource {
4407
4413
  * `req.query` record, a `URLSearchParams`, a `URL`, a full callback URL
4408
4414
  * string, or a bare `a=b&c=d` query string.
4409
4415
  * @param expected - The stored {@link IOAuthAuthorizationRequest} (or any
4410
- * object carrying its `state` and `issuer`).
4416
+ * object carrying its `state` and `issuer`). Without `issuer`, `iss` must
4417
+ * equal `https://auth.assinafy.com.br`; pass the stored one for any other
4418
+ * authorization server, such as the sandbox's.
4411
4419
  * @returns The validated response:
4412
4420
  * ```jsonc
4413
4421
  * {
@@ -4513,7 +4521,9 @@ declare class OAuthResource extends BaseResource {
4513
4521
  * and re-read your stored token instead of retrying blindly, and never run
4514
4522
  * two refreshes concurrently for one connection.
4515
4523
  *
4516
- * Refreshing does not extend the connection's 30-day life.
4524
+ * Each returned refresh token is valid for a fresh 30 days, so a connection
4525
+ * only expires if it goes 30 days without a refresh; after that the user
4526
+ * has to reconnect.
4517
4527
  *
4518
4528
  * @param options - Refresh options.
4519
4529
  * @param options.refreshToken - The current refresh token.
@@ -4521,7 +4531,8 @@ declare class OAuthResource extends BaseResource {
4521
4531
  * @param options.clientSecret - The `client_secret`, for confidential
4522
4532
  * applications only.
4523
4533
  * @param options.resource - RFC 8707 resource indicator. Defaults to this
4524
- * API's origin; pass `null` to omit it.
4534
+ * API's origin; pass `null` to omit it. A refresh may repeat the value the
4535
+ * connection was authorized with but never change it (`invalid_target`).
4525
4536
  * @returns A fresh token set, identical in shape to
4526
4537
  * {@link OAuthResource.exchangeCode}:
4527
4538
  * ```jsonc
@@ -4571,14 +4582,9 @@ declare class OAuthResource extends BaseResource {
4571
4582
  * @param options.tokenTypeHint - Optional `access_token` or
4572
4583
  * `refresh_token` hint that lets the server skip a lookup.
4573
4584
  * @returns Nothing; resolves once the API acknowledges the request.
4574
- * Request body:
4575
- * ```jsonc
4576
- * {
4577
- * "token": "def50200f1e2…",
4578
- * "token_type_hint": "refresh_token",
4579
- * "client_id": "cli_1a2b3c",
4580
- * "client_secret": "…"
4581
- * }
4585
+ * Request body (`application/x-www-form-urlencoded`):
4586
+ * ```text
4587
+ * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
4582
4588
  * ```
4583
4589
  * @throws {ValidationError} If `token` or `clientId` is missing, or
4584
4590
  * `tokenTypeHint` is not one of the two documented values.
@@ -4631,7 +4637,12 @@ declare class OAuthResource extends BaseResource {
4631
4637
  * ```
4632
4638
  */
4633
4639
  getUserInfo(accessToken?: string): Promise<IOAuthUserInfo>;
4634
- /** POST the token endpoint and assert the response actually carries a token. */
4640
+ /**
4641
+ * POST the token endpoint once and assert the response carries a token.
4642
+ *
4643
+ * Never retried: the code is single-use, and replaying a refresh token the
4644
+ * server may already have rotated ends the whole connection.
4645
+ */
4635
4646
  private requestToken;
4636
4647
  /** `client_secret_post` credentials, omitting the secret for public clients. */
4637
4648
  private clientAuth;
package/dist/index.js CHANGED
@@ -634,7 +634,7 @@ var import_axios2 = __toESM(require("axios"));
634
634
  // package.json
635
635
  var package_default = {
636
636
  name: "@assinafy/sdk",
637
- version: "2.4.2",
637
+ version: "2.5.0",
638
638
  packageManager: "bun@1.4.0",
639
639
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
640
640
  type: "commonjs",
@@ -2582,6 +2582,7 @@ var DocumentResource = class extends BaseResource {
2582
2582
  * {
2583
2583
  * "hash": "FE32EDDADE7CBDDCBB934E7402047450B0E59C02",
2584
2584
  * "id": "63ddb172402799bfc991d10d",
2585
+ * "agreement_code": "550E8400-E29B-41D4-A716-446655440000", // printed on the certificate
2585
2586
  * "status": "certificated",
2586
2587
  * "page_count": "1",
2587
2588
  * "signer_count": "1",
@@ -4965,6 +4966,7 @@ var AuthenticationResource = class extends BaseResource {
4965
4966
  var import_node_crypto = require("crypto");
4966
4967
  var PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";
4967
4968
  var AUTHORIZATION_SERVER_PATH = "/.well-known/oauth-authorization-server";
4969
+ var ASSINAFY_ISSUER = "https://auth.assinafy.com.br";
4968
4970
  var CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/u;
4969
4971
  var OAuthResource = class extends BaseResource {
4970
4972
  publicHttp;
@@ -5197,8 +5199,7 @@ var OAuthResource = class extends BaseResource {
5197
5199
  *
5198
5200
  * The `iss` check is strict because the authorization server advertises
5199
5201
  * RFC 9207 support and always sends the parameter: a missing `iss` is
5200
- * treated exactly like a wrong one. Omit `expected.issuer` only if
5201
- * something between the browser and your handler strips query parameters.
5202
+ * treated exactly like a wrong one, on success and error responses alike.
5202
5203
  *
5203
5204
  * This performs no network I/O.
5204
5205
  *
@@ -5206,7 +5207,9 @@ var OAuthResource = class extends BaseResource {
5206
5207
  * `req.query` record, a `URLSearchParams`, a `URL`, a full callback URL
5207
5208
  * string, or a bare `a=b&c=d` query string.
5208
5209
  * @param expected - The stored {@link IOAuthAuthorizationRequest} (or any
5209
- * object carrying its `state` and `issuer`).
5210
+ * object carrying its `state` and `issuer`). Without `issuer`, `iss` must
5211
+ * equal `https://auth.assinafy.com.br`; pass the stored one for any other
5212
+ * authorization server, such as the sandbox's.
5210
5213
  * @returns The validated response:
5211
5214
  * ```jsonc
5212
5215
  * {
@@ -5248,14 +5251,13 @@ var OAuthResource = class extends BaseResource {
5248
5251
  "OAuth callback state does not match the stored authorization request"
5249
5252
  );
5250
5253
  }
5251
- const issuer = query.get("iss") ?? void 0;
5252
- if (expected.issuer !== void 0) {
5253
- if (issuer === void 0 || normaliseIssuer(issuer) !== normaliseIssuer(expected.issuer)) {
5254
- throw new ValidationError(
5255
- "OAuth callback issuer is missing or does not match the expected issuer",
5256
- { expected: expected.issuer, received: issuer ?? null }
5257
- );
5258
- }
5254
+ const issuer = query.get("iss");
5255
+ const expectedIssuer = expected.issuer ?? ASSINAFY_ISSUER;
5256
+ if (issuer === null || normaliseIssuer(issuer) !== normaliseIssuer(expectedIssuer)) {
5257
+ throw new ValidationError(
5258
+ "OAuth callback issuer is missing or does not match the expected issuer",
5259
+ { expected: expectedIssuer, received: issuer }
5260
+ );
5259
5261
  }
5260
5262
  const error = query.get("error");
5261
5263
  if (error !== null && error.length > 0) {
@@ -5268,9 +5270,7 @@ var OAuthResource = class extends BaseResource {
5268
5270
  if (code === null || code.length === 0) {
5269
5271
  throw new ValidationError("OAuth callback carries neither a code nor an error");
5270
5272
  }
5271
- const result = { code, state };
5272
- if (issuer !== void 0) result.issuer = issuer;
5273
- return result;
5273
+ return { code, state, issuer };
5274
5274
  }
5275
5275
  /**
5276
5276
  * Exchange an authorization code for tokens
@@ -5350,7 +5350,9 @@ var OAuthResource = class extends BaseResource {
5350
5350
  * and re-read your stored token instead of retrying blindly, and never run
5351
5351
  * two refreshes concurrently for one connection.
5352
5352
  *
5353
- * Refreshing does not extend the connection's 30-day life.
5353
+ * Each returned refresh token is valid for a fresh 30 days, so a connection
5354
+ * only expires if it goes 30 days without a refresh; after that the user
5355
+ * has to reconnect.
5354
5356
  *
5355
5357
  * @param options - Refresh options.
5356
5358
  * @param options.refreshToken - The current refresh token.
@@ -5358,7 +5360,8 @@ var OAuthResource = class extends BaseResource {
5358
5360
  * @param options.clientSecret - The `client_secret`, for confidential
5359
5361
  * applications only.
5360
5362
  * @param options.resource - RFC 8707 resource indicator. Defaults to this
5361
- * API's origin; pass `null` to omit it.
5363
+ * API's origin; pass `null` to omit it. A refresh may repeat the value the
5364
+ * connection was authorized with but never change it (`invalid_target`).
5362
5365
  * @returns A fresh token set, identical in shape to
5363
5366
  * {@link OAuthResource.exchangeCode}:
5364
5367
  * ```jsonc
@@ -5389,12 +5392,19 @@ var OAuthResource = class extends BaseResource {
5389
5392
  async refreshToken(options) {
5390
5393
  assertRecord(options, "refresh options");
5391
5394
  assertNonEmptyString(options.refreshToken, "refreshToken");
5392
- return this.requestToken("Failed to refresh the OAuth access token", {
5395
+ const tokens = await this.requestToken("Failed to refresh the OAuth access token", {
5393
5396
  grant_type: "refresh_token",
5394
5397
  refresh_token: options.refreshToken,
5395
5398
  ...this.clientAuth(options),
5396
5399
  ...this.resourceParam(options.resource)
5397
5400
  });
5401
+ if (typeof tokens.refresh_token !== "string" || tokens.refresh_token.length === 0) {
5402
+ throw new ValidationError(
5403
+ "Failed to refresh the OAuth access token: the token endpoint returned no replacement refresh_token; the connection must be re-established",
5404
+ { fields: Object.keys(tokens) }
5405
+ );
5406
+ }
5407
+ return tokens;
5398
5408
  }
5399
5409
  /**
5400
5410
  * Revoke an access or refresh token (`POST /oauth/revoke`, RFC 7009).
@@ -5414,14 +5424,9 @@ var OAuthResource = class extends BaseResource {
5414
5424
  * @param options.tokenTypeHint - Optional `access_token` or
5415
5425
  * `refresh_token` hint that lets the server skip a lookup.
5416
5426
  * @returns Nothing; resolves once the API acknowledges the request.
5417
- * Request body:
5418
- * ```jsonc
5419
- * {
5420
- * "token": "def50200f1e2…",
5421
- * "token_type_hint": "refresh_token",
5422
- * "client_id": "cli_1a2b3c",
5423
- * "client_secret": "…"
5424
- * }
5427
+ * Request body (`application/x-www-form-urlencoded`):
5428
+ * ```text
5429
+ * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
5425
5430
  * ```
5426
5431
  * @throws {ValidationError} If `token` or `clientId` is missing, or
5427
5432
  * `tokenTypeHint` is not one of the two documented values.
@@ -5443,7 +5448,7 @@ var OAuthResource = class extends BaseResource {
5443
5448
  if (options.tokenTypeHint !== void 0 && options.tokenTypeHint !== "access_token" && options.tokenTypeHint !== "refresh_token") {
5444
5449
  throw new ValidationError("tokenTypeHint must be access_token or refresh_token");
5445
5450
  }
5446
- const body = cleanParams({
5451
+ const body = formBody({
5447
5452
  token: options.token,
5448
5453
  token_type_hint: options.tokenTypeHint,
5449
5454
  ...this.clientAuth(options)
@@ -5504,13 +5509,18 @@ var OAuthResource = class extends BaseResource {
5504
5509
  })
5505
5510
  );
5506
5511
  }
5507
- /** POST the token endpoint and assert the response actually carries a token. */
5512
+ /**
5513
+ * POST the token endpoint once and assert the response carries a token.
5514
+ *
5515
+ * Never retried: the code is single-use, and replaying a refresh token the
5516
+ * server may already have rotated ends the whole connection.
5517
+ */
5508
5518
  async requestToken(label, body) {
5509
5519
  let tokens;
5510
5520
  try {
5511
5521
  tokens = await this.call(
5512
5522
  label,
5513
- () => this.publicHttp.post("/oauth/token", cleanParams(body))
5523
+ () => this.publicHttp.post("/oauth/token", formBody(body))
5514
5524
  );
5515
5525
  } catch (error) {
5516
5526
  throw OAuthError.upgrade(error);
@@ -5574,6 +5584,9 @@ var OAuthResource = class extends BaseResource {
5574
5584
  return new URL(baseUrl).origin;
5575
5585
  }
5576
5586
  };
5587
+ function formBody(fields) {
5588
+ return new URLSearchParams(cleanParams(fields));
5589
+ }
5577
5590
  function createCodeVerifier() {
5578
5591
  return (0, import_node_crypto.randomBytes)(32).toString("base64url");
5579
5592
  }
package/dist/index.mjs CHANGED
@@ -574,7 +574,7 @@ import axios2 from "axios";
574
574
  // package.json
575
575
  var package_default = {
576
576
  name: "@assinafy/sdk",
577
- version: "2.4.2",
577
+ version: "2.5.0",
578
578
  packageManager: "bun@1.4.0",
579
579
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
580
580
  type: "commonjs",
@@ -2522,6 +2522,7 @@ var DocumentResource = class extends BaseResource {
2522
2522
  * {
2523
2523
  * "hash": "FE32EDDADE7CBDDCBB934E7402047450B0E59C02",
2524
2524
  * "id": "63ddb172402799bfc991d10d",
2525
+ * "agreement_code": "550E8400-E29B-41D4-A716-446655440000", // printed on the certificate
2525
2526
  * "status": "certificated",
2526
2527
  * "page_count": "1",
2527
2528
  * "signer_count": "1",
@@ -4905,6 +4906,7 @@ var AuthenticationResource = class extends BaseResource {
4905
4906
  import { createHash, randomBytes, timingSafeEqual } from "crypto";
4906
4907
  var PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";
4907
4908
  var AUTHORIZATION_SERVER_PATH = "/.well-known/oauth-authorization-server";
4909
+ var ASSINAFY_ISSUER = "https://auth.assinafy.com.br";
4908
4910
  var CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/u;
4909
4911
  var OAuthResource = class extends BaseResource {
4910
4912
  publicHttp;
@@ -5137,8 +5139,7 @@ var OAuthResource = class extends BaseResource {
5137
5139
  *
5138
5140
  * The `iss` check is strict because the authorization server advertises
5139
5141
  * RFC 9207 support and always sends the parameter: a missing `iss` is
5140
- * treated exactly like a wrong one. Omit `expected.issuer` only if
5141
- * something between the browser and your handler strips query parameters.
5142
+ * treated exactly like a wrong one, on success and error responses alike.
5142
5143
  *
5143
5144
  * This performs no network I/O.
5144
5145
  *
@@ -5146,7 +5147,9 @@ var OAuthResource = class extends BaseResource {
5146
5147
  * `req.query` record, a `URLSearchParams`, a `URL`, a full callback URL
5147
5148
  * string, or a bare `a=b&c=d` query string.
5148
5149
  * @param expected - The stored {@link IOAuthAuthorizationRequest} (or any
5149
- * object carrying its `state` and `issuer`).
5150
+ * object carrying its `state` and `issuer`). Without `issuer`, `iss` must
5151
+ * equal `https://auth.assinafy.com.br`; pass the stored one for any other
5152
+ * authorization server, such as the sandbox's.
5150
5153
  * @returns The validated response:
5151
5154
  * ```jsonc
5152
5155
  * {
@@ -5188,14 +5191,13 @@ var OAuthResource = class extends BaseResource {
5188
5191
  "OAuth callback state does not match the stored authorization request"
5189
5192
  );
5190
5193
  }
5191
- const issuer = query.get("iss") ?? void 0;
5192
- if (expected.issuer !== void 0) {
5193
- if (issuer === void 0 || normaliseIssuer(issuer) !== normaliseIssuer(expected.issuer)) {
5194
- throw new ValidationError(
5195
- "OAuth callback issuer is missing or does not match the expected issuer",
5196
- { expected: expected.issuer, received: issuer ?? null }
5197
- );
5198
- }
5194
+ const issuer = query.get("iss");
5195
+ const expectedIssuer = expected.issuer ?? ASSINAFY_ISSUER;
5196
+ if (issuer === null || normaliseIssuer(issuer) !== normaliseIssuer(expectedIssuer)) {
5197
+ throw new ValidationError(
5198
+ "OAuth callback issuer is missing or does not match the expected issuer",
5199
+ { expected: expectedIssuer, received: issuer }
5200
+ );
5199
5201
  }
5200
5202
  const error = query.get("error");
5201
5203
  if (error !== null && error.length > 0) {
@@ -5208,9 +5210,7 @@ var OAuthResource = class extends BaseResource {
5208
5210
  if (code === null || code.length === 0) {
5209
5211
  throw new ValidationError("OAuth callback carries neither a code nor an error");
5210
5212
  }
5211
- const result = { code, state };
5212
- if (issuer !== void 0) result.issuer = issuer;
5213
- return result;
5213
+ return { code, state, issuer };
5214
5214
  }
5215
5215
  /**
5216
5216
  * Exchange an authorization code for tokens
@@ -5290,7 +5290,9 @@ var OAuthResource = class extends BaseResource {
5290
5290
  * and re-read your stored token instead of retrying blindly, and never run
5291
5291
  * two refreshes concurrently for one connection.
5292
5292
  *
5293
- * Refreshing does not extend the connection's 30-day life.
5293
+ * Each returned refresh token is valid for a fresh 30 days, so a connection
5294
+ * only expires if it goes 30 days without a refresh; after that the user
5295
+ * has to reconnect.
5294
5296
  *
5295
5297
  * @param options - Refresh options.
5296
5298
  * @param options.refreshToken - The current refresh token.
@@ -5298,7 +5300,8 @@ var OAuthResource = class extends BaseResource {
5298
5300
  * @param options.clientSecret - The `client_secret`, for confidential
5299
5301
  * applications only.
5300
5302
  * @param options.resource - RFC 8707 resource indicator. Defaults to this
5301
- * API's origin; pass `null` to omit it.
5303
+ * API's origin; pass `null` to omit it. A refresh may repeat the value the
5304
+ * connection was authorized with but never change it (`invalid_target`).
5302
5305
  * @returns A fresh token set, identical in shape to
5303
5306
  * {@link OAuthResource.exchangeCode}:
5304
5307
  * ```jsonc
@@ -5329,12 +5332,19 @@ var OAuthResource = class extends BaseResource {
5329
5332
  async refreshToken(options) {
5330
5333
  assertRecord(options, "refresh options");
5331
5334
  assertNonEmptyString(options.refreshToken, "refreshToken");
5332
- return this.requestToken("Failed to refresh the OAuth access token", {
5335
+ const tokens = await this.requestToken("Failed to refresh the OAuth access token", {
5333
5336
  grant_type: "refresh_token",
5334
5337
  refresh_token: options.refreshToken,
5335
5338
  ...this.clientAuth(options),
5336
5339
  ...this.resourceParam(options.resource)
5337
5340
  });
5341
+ if (typeof tokens.refresh_token !== "string" || tokens.refresh_token.length === 0) {
5342
+ throw new ValidationError(
5343
+ "Failed to refresh the OAuth access token: the token endpoint returned no replacement refresh_token; the connection must be re-established",
5344
+ { fields: Object.keys(tokens) }
5345
+ );
5346
+ }
5347
+ return tokens;
5338
5348
  }
5339
5349
  /**
5340
5350
  * Revoke an access or refresh token (`POST /oauth/revoke`, RFC 7009).
@@ -5354,14 +5364,9 @@ var OAuthResource = class extends BaseResource {
5354
5364
  * @param options.tokenTypeHint - Optional `access_token` or
5355
5365
  * `refresh_token` hint that lets the server skip a lookup.
5356
5366
  * @returns Nothing; resolves once the API acknowledges the request.
5357
- * Request body:
5358
- * ```jsonc
5359
- * {
5360
- * "token": "def50200f1e2…",
5361
- * "token_type_hint": "refresh_token",
5362
- * "client_id": "cli_1a2b3c",
5363
- * "client_secret": "…"
5364
- * }
5367
+ * Request body (`application/x-www-form-urlencoded`):
5368
+ * ```text
5369
+ * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
5365
5370
  * ```
5366
5371
  * @throws {ValidationError} If `token` or `clientId` is missing, or
5367
5372
  * `tokenTypeHint` is not one of the two documented values.
@@ -5383,7 +5388,7 @@ var OAuthResource = class extends BaseResource {
5383
5388
  if (options.tokenTypeHint !== void 0 && options.tokenTypeHint !== "access_token" && options.tokenTypeHint !== "refresh_token") {
5384
5389
  throw new ValidationError("tokenTypeHint must be access_token or refresh_token");
5385
5390
  }
5386
- const body = cleanParams({
5391
+ const body = formBody({
5387
5392
  token: options.token,
5388
5393
  token_type_hint: options.tokenTypeHint,
5389
5394
  ...this.clientAuth(options)
@@ -5444,13 +5449,18 @@ var OAuthResource = class extends BaseResource {
5444
5449
  })
5445
5450
  );
5446
5451
  }
5447
- /** POST the token endpoint and assert the response actually carries a token. */
5452
+ /**
5453
+ * POST the token endpoint once and assert the response carries a token.
5454
+ *
5455
+ * Never retried: the code is single-use, and replaying a refresh token the
5456
+ * server may already have rotated ends the whole connection.
5457
+ */
5448
5458
  async requestToken(label, body) {
5449
5459
  let tokens;
5450
5460
  try {
5451
5461
  tokens = await this.call(
5452
5462
  label,
5453
- () => this.publicHttp.post("/oauth/token", cleanParams(body))
5463
+ () => this.publicHttp.post("/oauth/token", formBody(body))
5454
5464
  );
5455
5465
  } catch (error) {
5456
5466
  throw OAuthError.upgrade(error);
@@ -5514,6 +5524,9 @@ var OAuthResource = class extends BaseResource {
5514
5524
  return new URL(baseUrl).origin;
5515
5525
  }
5516
5526
  };
5527
+ function formBody(fields) {
5528
+ return new URLSearchParams(cleanParams(fields));
5529
+ }
5517
5530
  function createCodeVerifier() {
5518
5531
  return randomBytes(32).toString("base64url");
5519
5532
  }
@@ -113,8 +113,9 @@ Response shapes diverge from the rest of the API on purpose:
113
113
  | `GET /oauth/userinfo` | flat claims object (OIDC Core §5.3.2) | the usual `{ status, message, data }` envelope |
114
114
 
115
115
  Both JSON and `application/x-www-form-urlencoded` bodies are accepted by the
116
- token and revocation endpoints; the SDK sends JSON because that is what the
117
- published `requestBody` documents.
116
+ token and revocation endpoints. The published `requestBody` lists only JSON,
117
+ but the SDK sends `application/x-www-form-urlencoded`: the encoding RFC 6749
118
+ and RFC 7009 define and the OAuth Integration Guide uses.
118
119
 
119
120
  The RFC 8707 `resource` indicator defaults to the configured API origin, and is
120
121
  omitted when that origin is a loopback `http://` host — the shape used by mock
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assinafy/sdk",
3
- "version": "2.4.2",
3
+ "version": "2.5.0",
4
4
  "packageManager": "bun@1.4.0",
5
5
  "description": "TypeScript SDK for Assinafy API - Digital signature platform",
6
6
  "type": "commonjs",