@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
@@ -14,7 +14,7 @@ Commands:
14
14
  list [options] List assignments across the account
15
15
  create [options] <documentId> Create a signing assignment for a document
16
16
  estimate-cost [options] <documentId> Estimate the credit cost of an assignment
17
- reset-expiration [options] <documentId> <assignmentId> Update or clear an assignment expiration date
17
+ reset-expiration [options] <documentId> <assignmentId> Update an assignment expiration date
18
18
  resend <documentId> <assignmentId> <signerId> Resend the signing notification to a signer
19
19
  estimate-resend-cost <documentId> <assignmentId> <signerId> Estimate the cost of resending a signer notification
20
20
  whatsapp-notifications <documentId> <assignmentId> List WhatsApp notifications sent for an assignment
@@ -84,7 +84,7 @@ Options:
84
84
  ```text
85
85
  Usage: assinafy assignments reset-expiration [options] <documentId> <assignmentId>
86
86
 
87
- Update or clear an assignment expiration date
87
+ Update an assignment expiration date
88
88
 
89
89
  Arguments:
90
90
  documentId Document ID
@@ -92,7 +92,7 @@ Arguments:
92
92
 
93
93
  Options:
94
94
  --expires-at <iso8601> New expiration timestamp
95
- --clear Remove the expiration entirely
95
+ --clear Remove the expiration when supported by the deployment
96
96
  -h, --help display help for command
97
97
  ```
98
98
 
package/docs/documents.md CHANGED
@@ -22,8 +22,8 @@ Commands:
22
22
  activities <id> Show the activity log for a document
23
23
  delete|rm [options] <id> Delete a document
24
24
  tags <id> List the tags attached to a document
25
- tags-set <id> [names...] Replace a document tag set (names; unknown names are auto-created)
26
- tags-add <id> <names...> Attach additional tags by name without removing existing ones
25
+ tags-set <id> [tagIds...] Replace a document tag set by tag ID
26
+ tags-add <id> <tagIds...> Attach additional tag IDs without removing existing ones
27
27
  tags-remove <id> <tagId> Detach a single tag from a document
28
28
  create-from-template [options] <templateId> Create a document from a template
29
29
  estimate-template-cost [options] <templateId> Estimate the credit cost of creating a document from a template
@@ -216,13 +216,13 @@ Options:
216
216
  ### `assinafy documents tags-set`
217
217
 
218
218
  ```text
219
- Usage: assinafy documents tags-set [options] <id> [names...]
219
+ Usage: assinafy documents tags-set [options] <id> [tagIds...]
220
220
 
221
- Replace a document tag set (names; unknown names are auto-created)
221
+ Replace a document tag set by tag ID
222
222
 
223
223
  Arguments:
224
224
  id Document ID
225
- names Tag names (pass none to detach all)
225
+ tagIds Tag IDs (pass none to detach all)
226
226
 
227
227
  Options:
228
228
  -h, --help display help for command
@@ -231,13 +231,13 @@ Options:
231
231
  ### `assinafy documents tags-add`
232
232
 
233
233
  ```text
234
- Usage: assinafy documents tags-add [options] <id> <names...>
234
+ Usage: assinafy documents tags-add [options] <id> <tagIds...>
235
235
 
236
- Attach additional tags by name without removing existing ones
236
+ Attach additional tag IDs without removing existing ones
237
237
 
238
238
  Arguments:
239
239
  id Document ID
240
- names Tag names to attach
240
+ tagIds Tag IDs to attach
241
241
 
242
242
  Options:
243
243
  -h, --help display help for command
package/docs/fields.md CHANGED
@@ -34,7 +34,7 @@ Options:
34
34
  --name <name> Field name
35
35
  --regex <regex> Validation regex
36
36
  --required Mark the field as required
37
- --inactive Create the field inactive
37
+ --inactive Compatibility: create the field inactive
38
38
  -h, --help display help for command
39
39
  ```
40
40
 
@@ -76,12 +76,12 @@ Arguments:
76
76
  id Field ID
77
77
 
78
78
  Options:
79
- --type <type> Field type
79
+ --type <type> Compatibility: change the field type
80
80
  --name <name> Field name
81
81
  --regex <regex> Validation regex
82
82
  --clear-regex Remove the existing validation regex
83
- --required Mark as required
84
- --optional Mark as not required
83
+ --required Compatibility: mark as required
84
+ --optional Compatibility: mark as not required
85
85
  --active Activate the field
86
86
  --inactive Deactivate the field
87
87
  -h, --help display help for command
@@ -4,14 +4,18 @@ Version 2 publishes the Node.js SDK at `@assinafy/cli/api` and requires Node.js
4
4
  `>=22.12.0`.
5
5
 
6
6
  - Credentialed clients now require HTTPS, reject redirects, and reject base URLs
7
- containing a query or fragment. Set `allowInsecureHttp: true` only for isolated
8
- local HTTP testing.
7
+ containing a query or fragment. `allowInsecureHttp: true` permits a plaintext
8
+ base URL only on a loopback host (`localhost`, `127.0.0.0/8`, `[::1]`), so a key
9
+ can never be sent in cleartext to a remote host.
9
10
  - Resource IDs, artifact names, sort fields, dates, mutually exclusive CLI
10
11
  options, and signer-code authentication are validated before a request.
11
12
  - Published `{ status, message }` bodies and delete `data: []` bodies are now
12
13
  returned as `IStatusResponse` and `IEmptyResult` instead of being discarded.
13
14
  - Phone-only signers in `uploadAndRequestSignatures` default to WhatsApp
14
15
  verification and notification. Explicit signer controls still take precedence.
16
+ - `uploadAndRequestSignatures` rejects with `PartialWorkflowError` when it fails
17
+ after the upload, exposing the `documentId` and `signerIds` it already created
18
+ so callers can clean up or resume without searching for orphans.
15
19
  - Signer artifact downloads perform an identity preflight because older sandbox
16
20
  deployments did not enforce the documented access code on the raw download route.
17
21
 
@@ -0,0 +1,343 @@
1
+ # OAuth connections for marketplace apps
2
+
3
+ Assinafy uses OAuth 2.1 authorization code with mandatory S256 PKCE for public and confidential clients. The SDK implements the four published resource operations plus authorization-server discovery, authorization URL creation, and callback validation. The [official integration guide](https://api.assinafy.com.br/v1/docs) defines the protocol; [api-reference.md](./api-reference.md#oauth) contains the complete published HTTP request and response examples.
4
+
5
+ Use a separate connection for each customer workspace. An OAuth access token carries the consenting user's permissions, the granted scopes, and exactly one workspace. It never grants billing, workspace creation/deletion, API-key management, or other platform administration. An API key remains available for direct owner integrations. Signer access codes remain a separate authentication mechanism.
6
+
7
+ ## Register the application
8
+
9
+ In Assinafy settings, create an OAuth application with its display name, permitted scopes, and exact HTTPS redirect URIs. Redirects cannot contain fragments. Plain HTTP localhost callbacks are not supported; use an HTTPS development endpoint or tunnel. Public clients omit a secret. Confidential clients keep their secret on the server and use `client_secret_post`, never browser code, a distributed binary, or a repository.
10
+
11
+ Production endpoints:
12
+
13
+ | Purpose | URL |
14
+ | --- | --- |
15
+ | Protected-resource discovery | `https://api.assinafy.com.br/.well-known/oauth-protected-resource` |
16
+ | Issuer | `https://auth.assinafy.com.br` |
17
+ | Authorization-server discovery | `https://auth.assinafy.com.br/.well-known/oauth-authorization-server` |
18
+ | Authorization | `https://auth.assinafy.com.br/oauth/authorize` |
19
+ | Token | `https://api.assinafy.com.br/v1/oauth/token` |
20
+ | Revocation | `https://api.assinafy.com.br/v1/oauth/revoke` |
21
+ | UserInfo | `https://api.assinafy.com.br/v1/oauth/userinfo` |
22
+ | Resource indicator | `https://api.assinafy.com.br` |
23
+
24
+ The resource indicator is an origin, distinct from the SDK `baseUrl`, which includes `/v1`. Discover the issuer and endpoints for the environment you use. A sandbox API-key account does not imply that the same deployment supports OAuth or that production application credentials work there.
25
+
26
+ ## Choose scopes
27
+
28
+ | Scope | Purpose |
29
+ | --- | --- |
30
+ | `documents:read` | Read documents and signing state. |
31
+ | `documents:write` | Upload and manage documents and request signatures. |
32
+ | `templates:read` | Read templates. |
33
+ | `templates:write` | Permitted template operations. |
34
+ | `account:read` | Read the selected workspace. |
35
+ | `openid` | Request OpenID Connect identity and UserInfo. |
36
+ | `profile` | Include permitted profile claims. |
37
+ | `email` | Include permitted email claims. |
38
+ | `offline_access` | Request rotating refresh tokens for background work. |
39
+
40
+ `oauth connect` requests all nine published scopes by default so the CLI can access documents, templates, the selected workspace, and UserInfo, and obtain refresh tokens. The public application registration must permit all nine. Existing connections need a new authorization with the larger scope set; refreshing an old token does not add permissions. Use `--scope` to explicitly select fewer scopes when needed. For other applications, request only scopes they use. Resource metadata lists API scopes; authorization-server metadata also describes authentication features such as `offline_access`. The returned `scope` string is authoritative for the access token; do not infer granted scopes from what the browser requested. A scope never bypasses a user's role or the token's workspace boundary. Billing, subscriptions, workspace membership, credential management, and administration remain unavailable to OAuth tokens; those CLI operations require the non-OAuth credential documented for each endpoint.
41
+
42
+ ## Discover and start authorization
43
+
44
+ ```ts
45
+ import { AssinafyClient } from '@assinafy/cli/api';
46
+
47
+ const oauthClient = new AssinafyClient({ allowUnauthenticated: true });
48
+ const resource = await oauthClient.oauth.metadata();
49
+ const server = await oauthClient.oauth.discovery(resource.authorization_servers[0]!);
50
+ const request = await oauthClient.oauth.authorize({
51
+ clientId: process.env.ASSINAFY_OAUTH_CLIENT_ID!,
52
+ redirectUri: 'https://example.com/assinafy/callback',
53
+ scopes: ['documents:read', 'documents:write', 'account:read', 'offline_access'],
54
+ });
55
+ ```
56
+
57
+ `metadata()` has no input or body. Its direct JSON response is:
58
+
59
+ ```json
60
+ {
61
+ "resource": "https://api.assinafy.com.br",
62
+ "authorization_servers": ["https://auth.assinafy.com.br"],
63
+ "scopes_supported": ["documents:read", "documents:write", "templates:read", "templates:write", "account:read", "openid", "profile", "email"],
64
+ "bearer_methods_supported": ["header"]
65
+ }
66
+ ```
67
+
68
+ `discovery(issuer)` has no request body and returns `IOAuthAuthorizationServer`, including:
69
+
70
+ ```json
71
+ {
72
+ "issuer": "https://auth.assinafy.com.br",
73
+ "authorization_endpoint": "https://auth.assinafy.com.br/oauth/authorize",
74
+ "token_endpoint": "https://api.assinafy.com.br/v1/oauth/token",
75
+ "revocation_endpoint": "https://api.assinafy.com.br/v1/oauth/revoke",
76
+ "userinfo_endpoint": "https://api.assinafy.com.br/v1/oauth/userinfo",
77
+ "jwks_uri": "https://auth.assinafy.com.br/.well-known/jwks.json",
78
+ "scopes_supported": ["documents:read", "documents:write", "templates:read", "templates:write", "account:read", "openid", "profile", "email", "offline_access"],
79
+ "response_types_supported": ["code"],
80
+ "grant_types_supported": ["authorization_code", "refresh_token"],
81
+ "code_challenge_methods_supported": ["S256"],
82
+ "token_endpoint_auth_methods_supported": ["client_secret_post", "none"],
83
+ "authorization_response_iss_parameter_supported": true,
84
+ "client_id_metadata_document_supported": true
85
+ }
86
+ ```
87
+
88
+ `authorize(options)` performs both discovery requests and returns this complete `IOAuthAuthorizationRequest` shape. Values below are illustrations; each real invocation generates fresh cryptographic randomness. `nonce` is included only when `openid` is requested.
89
+
90
+ ```ts
91
+ interface IOAuthAuthorizationRequest {
92
+ authorization_url: string;
93
+ code_verifier: string;
94
+ state: string;
95
+ issuer: string;
96
+ client_id: string;
97
+ redirect_uri: string;
98
+ resource: string;
99
+ nonce?: string;
100
+ }
101
+ ```
102
+
103
+ The authorization URL contains `response_type=code`, `client_id`, `redirect_uri`, a space-separated `scope`, random `state`, `code_challenge=BASE64URL(SHA256(code_verifier))`, `code_challenge_method=S256`, `resource`, and optional `nonce`. The verifier is 43 base64url characters generated from 32 random bytes. Never put the verifier or client secret in the authorization URL.
104
+
105
+ Store the entire request server-side in the initiating user's authenticated session with a short expiry. Bind it to that user and consume it once. Redirect the browser to `request.authorization_url`; Assinafy handles login, workspace selection, and consent. The SDK creates protocol values, but does not implement your session store, browser routing, expiry, or single-use consumption.
106
+
107
+ ## Validate the callback and exchange the code
108
+
109
+ A successful callback includes `code`, `state`, and `iss`:
110
+
111
+ ```text
112
+ https://example.com/assinafy/callback?code=example_code&state=example_state&iss=https%3A%2F%2Fauth.assinafy.com.br
113
+ ```
114
+
115
+ Load and atomically consume the pending request for the same user. Pass the complete callback URL and stored request to the SDK:
116
+
117
+ ```ts
118
+ const tokens = await oauthClient.oauth.exchangeCode(
119
+ callbackUrl,
120
+ pendingRequest,
121
+ process.env.ASSINAFY_OAUTH_CLIENT_SECRET, // undefined for a public app
122
+ );
123
+ ```
124
+
125
+ `exchangeCode(callbackUrl, request, clientSecret?)` checks the callback origin/path and registered query parameters, rejects duplicate protocol parameters, compares `state` in constant time, and requires the exact stored issuer. It rejects denied authorization before calling the token endpoint. Authorization codes expire after 60 seconds and can be used once. Exchange immediately and never retry a code blindly after a timeout.
126
+
127
+ For applications that already perform callback validation, `token(payload)` accepts the same complete code grant directly:
128
+
129
+ ```json
130
+ {
131
+ "grant_type": "authorization_code",
132
+ "client_id": "example_client_id",
133
+ "client_secret": "example_client_secret",
134
+ "code": "example_authorization_code",
135
+ "redirect_uri": "https://example.com/assinafy/callback",
136
+ "code_verifier": "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
137
+ "resource": "https://api.assinafy.com.br"
138
+ }
139
+ ```
140
+
141
+ The SDK posts JSON. Omit `client_secret` for public clients. `resource` is optional in the token request; if provided, use the authorization resource. A direct `token()` call does not validate a browser callback, state, issuer, or session. The verifier must contain 43–128 RFC 7636 unreserved characters.
142
+
143
+ Both methods return the direct `IOAuthTokenResponse`, without an Assinafy `{ data }` envelope:
144
+
145
+ ```json
146
+ {
147
+ "access_token": "example_access_token",
148
+ "token_type": "Bearer",
149
+ "expires_in": 3600,
150
+ "scope": "documents:read documents:write account:read openid profile email",
151
+ "refresh_token": "example_refresh_token",
152
+ "id_token": "example_id_token"
153
+ }
154
+ ```
155
+
156
+ `refresh_token` is optional and depends on `offline_access`. `id_token` is optional and depends on `openid`. The SDK preserves optional null values from the server. Calculate expiration from the time the token response is received and the returned `expires_in`.
157
+
158
+ If you use an ID token to establish identity, validate it with an OIDC library using the discovered JWKS: signature, allowed algorithm, issuer, audience, expiry, and the stored nonce. The SDK returns the token; it does not verify JWT signatures or claims. Decoding a JWT is not identity verification.
159
+
160
+ ## Bind the token to its workspace
161
+
162
+ ```ts
163
+ const connected = new AssinafyClient({ token: tokens.access_token });
164
+ const { data: workspaces } = await connected.workspaces.list();
165
+ if (workspaces.length !== 1) throw new Error('Expected one authorized workspace');
166
+ const accountId = workspaces[0]!.id;
167
+
168
+ const workspaceClient = new AssinafyClient({
169
+ token: tokens.access_token,
170
+ accountId,
171
+ });
172
+ const documents = await workspaceClient.documents.list({ page: 1, per_page: 20 });
173
+ ```
174
+
175
+ Persist the workspace ID with the application's tenant/customer ID, issuer, resource, client ID, granted scopes, expiry, and encrypted tokens. Obtain the workspace ID from the authenticated `/accounts` response, not a callback query or an untrusted front end. OAuth `GET /accounts` exposes only the authorized workspace. All data access in a marketplace application must select the connection belonging to the current tenant.
176
+
177
+ ## Refresh without losing the connection
178
+
179
+ `token(payload)` accepts the refresh grant:
180
+
181
+ ```ts
182
+ const next = await oauthClient.oauth.token({
183
+ grant_type: 'refresh_token',
184
+ client_id: process.env.ASSINAFY_OAUTH_CLIENT_ID!,
185
+ client_secret: process.env.ASSINAFY_OAUTH_CLIENT_SECRET,
186
+ refresh_token: storedRefreshToken,
187
+ resource: 'https://api.assinafy.com.br',
188
+ });
189
+ ```
190
+
191
+ The complete wire body is:
192
+
193
+ ```json
194
+ {
195
+ "grant_type": "refresh_token",
196
+ "client_id": "example_client_id",
197
+ "client_secret": "example_client_secret",
198
+ "refresh_token": "example_current_refresh_token",
199
+ "resource": "https://api.assinafy.com.br"
200
+ }
201
+ ```
202
+
203
+ Its response has the same token shape above, with new access and refresh values. Each successful refresh consumes the previous refresh token. Reusing it revokes the entire connection. Serialize refreshes per connection across every worker and process; atomically store the complete new response before releasing the lock or using it. A lock local to one process is insufficient for a distributed application.
204
+
205
+ The documented authorization lifetime is 30 days and is not extended by refresh. A transport timeout can leave rotation outcome unknown; do not replay the old token automatically. Mark that connection for recovery/reconnection. On `invalid_grant`, require new consent. The SDK has no automatic refresh or request retry and never persists tokens. Construct a new authenticated `AssinafyClient` with the current access token after rotation.
206
+
207
+ ## UserInfo and disconnect
208
+
209
+ `userinfo()` uses the current bearer token and requires `openid`; `profile` and `email` control optional claims. It has no request body and returns flat `IOAuthUserInfo`:
210
+
211
+ ```ts
212
+ const identity = await new AssinafyClient({ token: tokens.access_token }).oauth.userinfo();
213
+ ```
214
+
215
+ ```json
216
+ {
217
+ "sub": "example_user_id",
218
+ "name": "Example User",
219
+ "email": "user@example.com",
220
+ "email_verified": true
221
+ }
222
+ ```
223
+
224
+ Only `sub` is mandatory; other claims can be missing or null. Prefer the stable subject over an email address as an identity key, and include the issuer in that key.
225
+
226
+ To disconnect, `revoke(payload)` posts:
227
+
228
+ ```json
229
+ {
230
+ "token": "example_refresh_token",
231
+ "client_id": "example_client_id",
232
+ "client_secret": "example_client_secret",
233
+ "token_type_hint": "refresh_token"
234
+ }
235
+ ```
236
+
237
+ ```ts
238
+ await oauthClient.oauth.revoke({
239
+ token: storedRefreshToken,
240
+ client_id: process.env.ASSINAFY_OAUTH_CLIENT_ID!,
241
+ client_secret: process.env.ASSINAFY_OAUTH_CLIENT_SECRET,
242
+ token_type_hint: 'refresh_token',
243
+ });
244
+ ```
245
+
246
+ `token_type_hint` is optional and accepts `access_token` or `refresh_token`. Successful revocation returns HTTP 200 with no required response body; the SDK resolves to `undefined`. Unknown/already revoked tokens also succeed for an authenticated client. Invalid client authentication returns 401. Revoke the connection before removing local credentials when possible, then mark it disconnected and stop its background work. CLI success prints `{ "revoked": true }`, a local confirmation rather than an API response payload.
247
+
248
+ ## CLI flow
249
+
250
+ ### Automatic browser return
251
+
252
+ The distributed CLI includes the official **Public** application's client ID, `96BZZ0sZTb2NkEXt1GCaIRCTprI2YKHZr8JDHawuXUyCLC88`. This public identifier is not a secret. The CLI uses PKCE S256 and the scopes `account:read documents:read documents:write templates:read templates:write openid profile email offline_access`; keep the registered permissions consistent with the requested scopes. No client secret is used by `oauth connect`, including when `ASSINAFY_OAUTH_CLIENT_SECRET` is set for another application.
253
+
254
+ Application maintainers must deploy the callback from `integrations-generic-callback` and register this exact HTTPS URI, without an extension or trailing slash:
255
+
256
+ ```text
257
+ https://integrations.assinafy.com.br/assinafy-cli/oauth-callback
258
+ ```
259
+
260
+ Leave `ASSINAFY_OAUTH_CLIENT_ID` unset to use the official application. `connect`, `authorize`, `refresh`, and `revoke` resolve the client ID in this order: `--client-id`, `ASSINAFY_OAUTH_CLIENT_ID`, then the bundled ID. Use an override for your own application or another environment, with that application's registered callback and permissions. SDK calls still require an explicit client ID. Use a private directory outside the repository. On POSIX shells:
261
+
262
+ ```bash
263
+ umask 077
264
+ assinafy oauth connect --json > tokens.json
265
+ unset ASSINAFY_API_KEY
266
+ export ASSINAFY_TOKEN="$(jq -er '.access_token' tokens.json)"
267
+ assinafy workspaces list --json
268
+ # Select the single returned workspace as ASSINAFY_ACCOUNT_ID.
269
+ assinafy documents list --json
270
+ ```
271
+
272
+ `oauth connect` opens the system browser, waits for approval, and prints the complete flat token response described in the token-exchange section above. The authorization URL and browser instructions go to stderr, including with `--json` or `--quiet`; token output goes to stdout. It does not save a profile, persist tokens, or automatically refresh them. On Windows, restrict the output directory ACL before writing credentials.
273
+
274
+ | Option | Behavior |
275
+ | --- | --- |
276
+ | `--client-id <id>` | Override the bundled public application ID; takes precedence over `ASSINAFY_OAUTH_CLIENT_ID`. |
277
+ | `--redirect-uri <uri>` | Registered HTTPS relay URI; defaults to the extensionless URL above. Query parameters and fragments are unsupported for this browser relay. |
278
+ | `--scope '<scopes>'` | Space-separated scopes; defaults to `account:read documents:read documents:write templates:read templates:write openid profile email offline_access`. |
279
+ | `--timeout <seconds>` | Browser response deadline, 1–600 seconds; default 180. API calls use the SDK's network timeout. |
280
+ | `--no-browser` | Print the authorization URL for manual opening; the local listener still receives the return automatically. |
281
+
282
+ The browser must run on the same computer as the CLI. A browser on your laptop cannot reach a listener in a remote SSH session or container without deliberate port forwarding; use the manual flow below when appropriate. Ctrl+C cancels and closes the listener. If browser launch is unavailable, open the printed URL on the same computer. An expired authorization code requires a fresh connection attempt; it is never retried automatically.
283
+
284
+ The callback protocol is:
285
+
286
+ 1. Discover the API resource and issuer, generate a random 32-byte PKCE verifier and state, and bind an ephemeral port on `127.0.0.1` only.
287
+ 2. Set `state` to `<43-character base64url random value>.<local port>` and send the registered HTTPS `redirect_uri` with the S256 challenge. Keep the verifier in the CLI process.
288
+ 3. After consent, Assinafy returns `code`, `state`, and `iss` (or `error`) to the HTTPS page. The code is single-use and expires 60 seconds after approval.
289
+ 4. The standalone page clears its query from browser history, checks the exact state syntax (including rejection of trailing line breaks), port range, issuer allowlist, parameter uniqueness, and exactly one nonblank code or error, then navigates to `http://127.0.0.1:<port>/callback` with only `code`, `state`, `iss`, or `error`.
290
+ 5. The CLI accepts only GET on `/callback` with the exact loopback Host, the original state, and the discovered issuer. Malformed or unrelated requests do not consume the pending connection. A valid authorization response is accepted once; the browser receives a page clearing its query and directing the user to the terminal.
291
+ 6. Close the listener and remove its timeout/signal handlers. Reconstruct the response against the saved HTTPS redirect URI and call `oauth.exchangeCode`; the token request still uses that exact HTTPS URI. Tokens and the PKCE verifier are never sent to the callback site.
292
+
293
+ The shared callback page accepts the production and staging issuers configured by the integration site. A custom issuer needs a compatible relay allowlist as well as `--base-url` and `--redirect-uri`. Do not add access logging, analytics, third-party scripts, or caching to callback routes. Deploy the site and register the application before using the default URL; installing the CLI does not deploy that site.
294
+
295
+ ### Manual authorization and exchange
296
+
297
+ For a server application or an existing callback handler, provision `ASSINAFY_OAUTH_CLIENT_ID` and, for a confidential app, `ASSINAFY_OAUTH_CLIENT_SECRET` through your secret manager. Use a private directory outside the repository:
298
+
299
+ ```bash
300
+ umask 077
301
+ assinafy oauth metadata --json
302
+ assinafy oauth discovery https://auth.assinafy.com.br --json
303
+ assinafy oauth authorize \
304
+ --redirect-uri https://example.com/assinafy/callback \
305
+ --scope 'documents:read documents:write account:read offline_access' \
306
+ --json > pending-request.json
307
+ jq -r '.authorization_url' pending-request.json
308
+ ```
309
+
310
+ Open the displayed URL and complete consent. Your HTTPS callback handler must capture the complete callback URL and supply it through `ASSINAFY_OAUTH_CALLBACK_URL` in the same private session. Then:
311
+
312
+ ```bash
313
+ assinafy oauth exchange --request pending-request.json --json > tokens.json
314
+ unset ASSINAFY_API_KEY
315
+ export ASSINAFY_TOKEN="$(jq -er '.access_token' tokens.json)"
316
+ assinafy workspaces list --json
317
+ ```
318
+
319
+ Select the single returned workspace as `ASSINAFY_ACCOUNT_ID`. Remove the consumed pending request. `authorize` does not launch a browser or start a listener; its state format is intended for your own callback, not the integration site's loopback relay.
320
+
321
+ ### Token use and rotation
322
+
323
+ An API key wins when both credential types are supplied at the same precedence level. A higher-precedence `--token` overrides environment or profile credentials as a group. Avoid leaving a stale `ASSINAFY_API_KEY` in an OAuth session.
324
+
325
+ Provision the current refresh token as `ASSINAFY_OAUTH_REFRESH_TOKEN`; `assinafy oauth refresh --resource https://api.assinafy.com.br --json` emits the rotated token response. Save to a private new file and atomically replace the previous file only on success. Never launch concurrent refresh commands. Use `ASSINAFY_OAUTH_REVOKE_TOKEN` for `assinafy oauth revoke --token-type-hint refresh_token --json`. For UserInfo, request `openid` during consent and run `assinafy oauth userinfo --json` with the access token.
326
+
327
+ Request files, callback URLs, token output, and environment variables are sensitive. Protect them using the OS's user-only permissions, keep them out of logs and version control, and remove consumed requests. The CLI's temporary listener serves only a browser handoff; token storage and connection lifecycle remain the caller's responsibility.
328
+
329
+ ## Failures and application lifecycle
330
+
331
+ | Result | Application behavior |
332
+ | --- | --- |
333
+ | `400 invalid_grant` | Code expired/used or refresh no longer usable; reconnect rather than retrying the old grant. |
334
+ | `401 invalid_client` | Check application type, client ID, client secret, and environment. |
335
+ | API `401` | Access token invalid/expired; perform one serialized refresh if the connection is recoverable. |
336
+ | `403` with `insufficient_scope` | Read `ApiError.wwwAuthenticate`; obtain consent for the missing scope. |
337
+ | Other `403` | Check user role, selected workspace, or a platform-administration restriction. |
338
+ | `429` | Respect `ApiError.retryAfter`; retry only operations whose semantics allow it. |
339
+ | Network failure on token exchange/refresh | Outcome may be ambiguous; never blindly replay a one-time credential. |
340
+
341
+ `ApiError.responseData` preserves `{ error, error_description? }` for OAuth failures. `wwwAuthenticate` preserves the Bearer challenge, including `scope` and `resource_metadata` when supplied. JSON CLI errors expose these as `error.details`, `error.wwwAuthenticate`, and `error.retryAfter`. Axios configuration and request credentials are not attached to SDK errors.
342
+
343
+ Unverified apps are limited to 25 workspaces by the documented platform policy. Complete application verification before wider marketplace distribution. Provide connection status, a user-triggered reconnect/disconnect flow, and tenant-scoped background jobs. Keep secrets on the server, use least-privilege scopes, and require the customer to consent to each connection.
package/docs/oauth.md ADDED
@@ -0,0 +1,162 @@
1
+ # `assinafy oauth`
2
+
3
+ ## `assinafy oauth`
4
+
5
+ ```text
6
+ Usage: assinafy oauth [options] [command]
7
+
8
+ OAuth 2.1 authorization, PKCE, token rotation, and OpenID Connect
9
+
10
+ Options:
11
+ -h, --help display help for command
12
+
13
+ Commands:
14
+ connect [options] Open browser consent for a public OAuth app, receive its
15
+ loopback return, and print tokens
16
+ metadata Read protected-resource metadata from the API origin
17
+ discovery <issuer> Read authorization-server metadata from an HTTPS issuer
18
+ authorize [options] Create an authorization URL and a sensitive PKCE/state
19
+ request; save the JSON securely
20
+ exchange [options] Validate the callback against a saved authorization
21
+ request and exchange its code
22
+ refresh [options] Rotate a refresh token once; securely persist the full
23
+ response before using it
24
+ revoke [options] Revoke an access or refresh token for this application
25
+ userinfo Read OIDC claims using --token / ASSINAFY_TOKEN with
26
+ openid scope
27
+ help [command] display help for command
28
+ ```
29
+
30
+ ### `assinafy oauth connect`
31
+
32
+ ```text
33
+ Usage: assinafy oauth connect [options]
34
+
35
+ Open browser consent for a public OAuth app, receive its loopback return, and
36
+ print tokens
37
+
38
+ Options:
39
+ --client-id <id> OAuth application client ID (default:
40
+ "96BZZ0sZTb2NkEXt1GCaIRCTprI2YKHZr8JDHawuXUyCLC88", env:
41
+ ASSINAFY_OAUTH_CLIENT_ID)
42
+ --redirect-uri <uri> Exactly registered HTTPS relay URI (default:
43
+ "https://integrations.assinafy.com.br/assinafy-cli/oauth-callback")
44
+ --scope <scopes> Space-separated scopes; defaults to all supported OAuth
45
+ scopes (default: "account:read documents:read
46
+ documents:write templates:read templates:write openid
47
+ profile email offline_access")
48
+ --timeout <seconds> Wait for browser consent (1–600 seconds) (default:
49
+ "180")
50
+ --no-browser Print the authorization URL without opening the system
51
+ browser
52
+ -h, --help display help for command
53
+ ```
54
+
55
+ ### `assinafy oauth metadata`
56
+
57
+ ```text
58
+ Usage: assinafy oauth metadata [options]
59
+
60
+ Read protected-resource metadata from the API origin
61
+
62
+ Options:
63
+ -h, --help display help for command
64
+ ```
65
+
66
+ ### `assinafy oauth discovery`
67
+
68
+ ```text
69
+ Usage: assinafy oauth discovery [options] <issuer>
70
+
71
+ Read authorization-server metadata from an HTTPS issuer
72
+
73
+ Arguments:
74
+ issuer Issuer from protected-resource metadata
75
+
76
+ Options:
77
+ -h, --help display help for command
78
+ ```
79
+
80
+ ### `assinafy oauth authorize`
81
+
82
+ ```text
83
+ Usage: assinafy oauth authorize [options]
84
+
85
+ Create an authorization URL and a sensitive PKCE/state request; save the JSON
86
+ securely
87
+
88
+ Options:
89
+ --client-id <id> OAuth application client ID (default:
90
+ "96BZZ0sZTb2NkEXt1GCaIRCTprI2YKHZr8JDHawuXUyCLC88", env:
91
+ ASSINAFY_OAUTH_CLIENT_ID)
92
+ --redirect-uri <uri> Exactly registered HTTPS callback URI
93
+ --scope <scopes> Space-separated scopes; offline_access requests refresh
94
+ tokens
95
+ -h, --help display help for command
96
+ ```
97
+
98
+ ### `assinafy oauth exchange`
99
+
100
+ ```text
101
+ Usage: assinafy oauth exchange [options]
102
+
103
+ Validate the callback against a saved authorization request and exchange its
104
+ code
105
+
106
+ Options:
107
+ --request <path> Private JSON file returned by oauth authorize
108
+ --callback-url <url> Complete callback URL with code, state, and iss
109
+ (env: ASSINAFY_OAUTH_CALLBACK_URL)
110
+ --client-secret <secret> Confidential application secret; omit for public
111
+ applications (env: ASSINAFY_OAUTH_CLIENT_SECRET)
112
+ -h, --help display help for command
113
+ ```
114
+
115
+ ### `assinafy oauth refresh`
116
+
117
+ ```text
118
+ Usage: assinafy oauth refresh [options]
119
+
120
+ Rotate a refresh token once; securely persist the full response before using it
121
+
122
+ Options:
123
+ --client-id <id> OAuth application client ID (default:
124
+ "96BZZ0sZTb2NkEXt1GCaIRCTprI2YKHZr8JDHawuXUyCLC88",
125
+ env: ASSINAFY_OAUTH_CLIENT_ID)
126
+ --client-secret <secret> Confidential application secret; omit for public
127
+ applications (env: ASSINAFY_OAUTH_CLIENT_SECRET)
128
+ --refresh-token <token> Current refresh token (env:
129
+ ASSINAFY_OAUTH_REFRESH_TOKEN)
130
+ --resource <uri> Resource indicator used during authorization
131
+ -h, --help display help for command
132
+ ```
133
+
134
+ ### `assinafy oauth revoke`
135
+
136
+ ```text
137
+ Usage: assinafy oauth revoke [options]
138
+
139
+ Revoke an access or refresh token for this application
140
+
141
+ Options:
142
+ --client-id <id> OAuth application client ID (default:
143
+ "96BZZ0sZTb2NkEXt1GCaIRCTprI2YKHZr8JDHawuXUyCLC88",
144
+ env: ASSINAFY_OAUTH_CLIENT_ID)
145
+ --client-secret <secret> Confidential application secret; omit for public
146
+ applications (env: ASSINAFY_OAUTH_CLIENT_SECRET)
147
+ --revoke-token <token> Token to revoke (env: ASSINAFY_OAUTH_REVOKE_TOKEN)
148
+ --token-type-hint <type> Type of token being revoked (choices:
149
+ "access_token", "refresh_token")
150
+ -h, --help display help for command
151
+ ```
152
+
153
+ ### `assinafy oauth userinfo`
154
+
155
+ ```text
156
+ Usage: assinafy oauth userinfo [options]
157
+
158
+ Read OIDC claims using --token / ASSINAFY_TOKEN with openid scope
159
+
160
+ Options:
161
+ -h, --help display help for command
162
+ ```