@digitap.eu/easyapi
v0.4.0
Published
TypeScript SDK and CLI for the easyapi Romanian government services API, with DPoP-bound machine authentication.
Readme
@digitap.eu/easyapi
TypeScript SDK and easyapi CLI for the easyapi Romanian government services API (ANAF, e-Factura,
e-Transport, REGES, company data). Two ways to authenticate:
- a plain API key (Bearer), for scripts and quick starts;
- a machine credential: a P-256 key that never leaves your machine (OAuth
private_key_jwtclient authentication plus DPoP proof-of-possession), so no long-lived bearer secret stays in your application. Server-side only (Node 20+).
Install
npm i @digitap.eu/easyapiQuickstart: API key
import { EasyApi } from "@digitap.eu/easyapi";
const easyapi = new EasyApi({ apiKey: process.env.EASYAPI_KEY });
const status = await easyapi.company.vatStatus("43020532");Quickstart: machine credential
Create a dedicated API key for this deployment in the dashboard, then run, from a host inside the key's IP allowlist:
npx easyapi setupThen:
import { fromMachineCredential } from "@digitap.eu/easyapi";
const easyapi = await fromMachineCredential({ profile: "default" }); // options > EASYAPI_* env > saved profile
const status = await easyapi.company.vatStatus("43020532");fromMachineCredential reads local files only; the first network call happens on first use. Tokens live in
memory, are renewed before they expire, and concurrent calls share one token exchange. Every request,
retries included, carries a fresh DPoP proof. Pass sdk: { retryConfig, timeoutMs, httpClient } to tune
the underlying client.
setup reads the key from a hidden prompt, or from EASYAPI_API_KEY if set. The key is never accepted as
a command-line argument and is never written to disk. It then:
- generates a P-256 key locally and saves it (
0600, directory0700) together with a pending profile holding a client-generated credential ID, before any network call; - registers the public key (enrollment);
- obtains a token and verifies
GET /v1/me; - marks the profile
verified.
Enrollment switches that API key to DPoP permanently: the raw key no longer works as a Bearer secret anywhere. Use a separate key per deployment.
If a response is lost or the process dies, run easyapi setup again: it resumes with the saved identity
(and does not need the API key if the enrollment already went through). It exits non-zero on any
failure, with a message naming the next step. Saved keys are never deleted after an ambiguous response.
easyapi status calls /v1/me with the saved credential and prints what the server reports.
Pagination
List operations that page return an async iterator of pages:
for await (const page of await easyapi.legislation.acts.list({})) {
console.log(page.result.data.items);
}Errors
Non-2xx answers throw a typed error (ErrorEnvelope, a subclass of EasyAPIError) with statusCode,
message (the API's error.message), error.code (stable machine-readable code), error.details,
headers (so error.headers.get("retry-after") gives the delay in seconds on a 429), body and
rawResponse. Transport failures throw ConnectionError, RequestTimeoutError or RequestAbortedError
(from @digitap.eu/easyapi/models/errors).
Machine-credential clients can additionally throw these (all extend MachineAuthError, none contains
secrets): OAuthError (token endpoint, e.g. invalid_client), RedirectRefusedError (a 3xx on a
credentialed request, never followed), ConfigError (bad local profile or key file). A failure of the
token exchange reaches you as UnexpectedClientError whose cause is the OAuthError.
Retries and idempotency
Reads (GET) retry on 429, 502, 503, 504 and connection errors with exponential backoff, honouring
Retry-After. The seven idempotent writes (company batch, connections create, e-Factura upload and
validate, e-Transport create, REGES contract create and terminate) retry on the same conditions. DELETE and
PATCH are never retried.
Every POST carries an Idempotency-Key: the one you pass, or a UUID the SDK generates once per call, so
all attempts of one call share it and the server applies the write once. Override retries per call with
{ retries } or for the whole client with retryConfig.
Profiles and environment
| Option / variable | Meaning |
| --- | --- |
| --profile, EASYAPI_PROFILE | Profile name ([A-Za-z0-9][A-Za-z0-9_-]{0,63}), default default |
| --config-dir, EASYAPI_CONFIG_DIR | Configuration root |
| --credential-id, EASYAPI_CREDENTIAL_ID | Credential UUID; must be paired with a key |
| --private-key-path, EASYAPI_PRIVATE_KEY_PATH | PKCS8 PEM file; must be paired with a credential ID |
| --base-url, EASYAPI_BASE_URL | API origin, e.g. https://host (no path or trailing slash; plain http only for localhost) |
| EASYAPI_API_KEY | Bootstrap key for setup only |
Precedence per field: explicit option, then environment, then the saved profile. A credential ID and its
key are only ever overridden together. fromMachineCredential({ privateKey }) takes PEM text or a
KeyObject, which suits deployments that inject the key from a secret store (a root-owned 0444 mounted
file is rejected by the file permission checks; pass its content instead). Relative paths resolve from the
current directory and are stored absolute.
Default configuration root: Linux and other POSIX systems ${XDG_CONFIG_HOME:-$HOME/.config}/easyapi;
macOS ~/Library/Application Support/easyapi. Inside it: profiles/<profile>.json,
keys/<credential-id>.pem.
Local file checks: directories 0700, files 0600, owned by the current user, no symlinks, no parent
directories writable by others, atomic writes with fsync, and a per-profile lock file so two setups
cannot interleave.
Rotation, revocation, recovery
- Rotate the signer:
easyapi rotate. The new key and apendingRotationentry are saved first; the old key signs an authorization and the new key signs a possession proof; the profile is replaced atomically only after the new key authenticates at the next generation. After a lost response, run it again: it checks which key the server accepts before doing anything. There is no overlap window, so a running application using the old key must be restarted (or its client re-created) afterwards. Rotate every replica of a deployment together. - Revoke: done in the customer dashboard (or by an operator). Revocation is final for that credential.
- Lost key or file: the credential cannot be recovered from the server. In the dashboard revoke the
API key, create a fresh dedicated one, and run
easyapi setup(use--profileto keep the old profile). Recovery never turns Bearer access back on.
IP binding
An API key can be bound to an IP allowlist. Product calls from outside it fail with
edge_binding_rejected. setup must run from an allowed IP; the SDK never loosens a binding. Run each
deployment from its own allowed egress address.
Limitations
- Machine credentials are not supported on Windows: the contract requires POSIX permission checks and
absolute
/paths, andsetuprefuses to run there. - Keep the system clock within about 30 seconds of real time: proofs are rejected outside the window.
- A 401 that asks for a DPoP nonce or reports an expired token is replayed once with a fresh proof; any other 401 is returned as an error.
- One signer per API key, so a credential cannot be shared by uncoordinated processes during rotation.
Development
npm install
npm run build && npx tsc -p tsconfig.json --noEmit
bun test # the suite runs under Bun
scripts/check-regen.sh # fails when regeneration changes a tracked file
scripts/pack.sh # build, strip generator wording, pack the tarball to publishMIT licensed.
Summary
Unified Romanian Government Services API: One API and one key for Romanian government services. Every response is { data } on success or { error: { code, message } } on failure. Authenticate with Authorization: Bearer <api key>.
Table of Contents
- @digitap.eu/easyapi
- Install
- Quickstart: API key
- Quickstart: machine credential
- Pagination
- Errors
- Retries and idempotency
- Profiles and environment
- Rotation, revocation, recovery
- IP binding
- Limitations
- Development
- SDK Installation
- Requirements
- SDK Example Usage
- Authentication
- Available Resources and Operations
- Standalone functions
- Pagination
- Retries
- Error Handling
- Server Selection
- Custom HTTP Client
- Debugging
SDK Installation
[!TIP] To finish publishing your SDK to npm and others you must run your first generation action.
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add <UNSET>PNPM
pnpm add <UNSET>Bun
bun add <UNSET>Yarn
yarn add <UNSET>[!NOTE] This package is published with CommonJS and ES Modules (ESM) support.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { EasyApi } from "@digitap.eu/easyapi";
const easyApi = new EasyApi();
async function run() {
const result = await easyApi.health.check();
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
| -------- | ---- | ----------- |
| apiKey | http | HTTP Bearer |
To authenticate with the API the apiKey parameter must be set when initializing the SDK client instance. For example:
import { EasyApi } from "@digitap.eu/easyapi";
const easyApi = new EasyApi({
apiKey: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await easyApi.health.check();
console.log(result);
}
run();
Available Resources and Operations
Bank
- validateIban - Validate an IBAN's structure and resolve its RO bank code
- getTreasury - Look up ANAF treasury IBANs for a CUI
- listInstitutions - List the bank institutions available for a connection
Bank.Accounts
- list - List all AIS-connected bank accounts for the tenant
- getBalances - Get current balances for one AIS-connected bank account
- listTransactions - Get date-windowed transactions for one AIS-connected bank account
CaseLaw
- getV1CaseLawDecisions - List ICCJ and CCR decisions
- getV1CaseLawDecisionsChanges - Poll the court decisions change-feed since a given timestamp
- getV1CaseLawDecisionsId - Get one court decision
Company
- get - Look up a company's identity and VAT status by CUI
- balanceByYear - Get a company's ANAF bilanț for a single filing year
- balance - Get a company's last filed bilanț years in one call
- vatStatus - Get a company's focused VAT/registry status by CUI
- litigation - Find ECRIS court cases matching this company's legal name
- getV1CompanyCuiInsolvency - List the insolvency cases (ECRIS) matching this company's legal name
- getV1CompanyCuiLei - Find the GLEIF LEI record and parent entities for a company by CUI
- batchGet - Look up up to 100 companies by CUI in one call
Connections
- create - Request a gov connection (returns the dashboard consent URL)
- list - List the tenant's gov connections
- get - Get one gov connection's metadata
- revoke - Revoke a gov connection and wipe its vault credential
Efactura
- upload - Upload a UBL/JSON invoice to e-Factura
- status - Get an invoice's e-Factura clearance state
- download - Get a signed download URL for an invoice's e-Factura result
- downloadZip - Download an invoice's e-Factura result zip through a signed link
- listMessages - List e-Factura messages for a connected company
- validate - Validate a UBL invoice offline, and with ?online=true also at ANAF (no ANAF connection required)
Efactura.Jobs
- get - Read one e-Factura submission job
- list - List e-Factura submission jobs, newest first
- cancel - Cancel an undelivered e-Factura submission job
Etransport
- create - Create an e-Transport declaration
- modify - Modify an e-Transport declaration by UIT
- get - Query an e-Transport declaration by UIT
Etransport.Jobs
- get - Read one e-Transport submission job
- list - List e-Transport submission jobs, newest first
- cancel - Cancel an undelivered e-Transport submission job
Fx
- listRates - List the latest BNR reference rates
- convert - Convert an amount between currencies at the latest rates
Geo
- getParcel - Look up a cadastral parcel by coordinates or INSPIRE id
Health
- check - Report db/redis/ANAF reachability
Justice
- listCourts - List or search the canonical ECRIS court identifiers
- searchCases - Search court cases by party, number, object, or court
- listCaseChanges - Search the litigation change-feed since a given timestamp
- listHearings - Get the hearing docket for a court on a date
Legislation.Acts
- list - List consolidated normative acts
- listChanges - Poll the acts change-feed since a given timestamp
- get - Get an act's current consolidated form
- listVersions - List an act's history: consolidations, republications and the base form
- getVersion - Get an act's body as it read on a given version date
Legislation.Bills
- list - List parliamentary bills
- listChanges - Poll the bills change-feed since a given timestamp
- get - Get a single parliamentary bill
- listStages - Get a bill's legislative stage history
- listDocuments - Get a bill's associated documents
Legislation.MonitorulOficial
- listIssues - List Monitorul Oficial issues
- listChanges - Poll the Monitorul Oficial change-feed since a given timestamp
- getAct - Get an act as it appeared in Monitorul Oficial
Me
- get - Get the resolved business, tier, effective scopes, and limits
Procurement
- listCompanyContracts - List a company's public procurement contracts by CUI
- listCompanyTenders - List a company's public procurement tenders by CUI
- listCompanyDirectPurchases - List a company's public procurement direct purchases by CUI
- listCpvContracts - List public procurement contracts for a CPV code
- getCpvAnalysis - Get market analysis for a CPV code
- getContract - Get a single public procurement contract's detail by number
Reges.Contracts
- create - Register a REGES employment contract, async
- terminate - Terminate a REGES employment contract, async
Reges.Employees
- list - List REGES employees for a connected company (CNP masked)
Reges.Jobs
- get - Get a REGES async job's status
Search
- companies - Search companies by name
Spv
- listMessages - List SPV inbox messages
- downloadDocument - Download one SPV document as a binary stream
- getEtvaDecont - Fetch the e-TVA pre-completed VAT return for a period
Stats
- getMatrix - Fetch a TEMPO matrix dataset with optional dimension filters
Vat
- validateVies - Validate an EU VAT number against VIES
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
bankAccountsGetBalances- Get current balances for one AIS-connected bank accountbankAccountsList- List all AIS-connected bank accounts for the tenantbankAccountsListTransactions- Get date-windowed transactions for one AIS-connected bank accountbankGetTreasury- Look up ANAF treasury IBANs for a CUIbankListInstitutions- List the bank institutions available for a connectionbankValidateIban- Validate an IBAN's structure and resolve its RO bank codecaseLawGetV1CaseLawDecisions- List ICCJ and CCR decisionscaseLawGetV1CaseLawDecisionsChanges- Poll the court decisions change-feed since a given timestampcaseLawGetV1CaseLawDecisionsId- Get one court decisioncompanyBalance- Get a company's last filed bilanț years in one callcompanyBalanceByYear- Get a company's ANAF bilanț for a single filing yearcompanyBatchGet- Look up up to 100 companies by CUI in one callcompanyGet- Look up a company's identity and VAT status by CUIcompanyGetV1CompanyCuiInsolvency- List the insolvency cases (ECRIS) matching this company's legal namecompanyGetV1CompanyCuiLei- Find the GLEIF LEI record and parent entities for a company by CUIcompanyLitigation- Find ECRIS court cases matching this company's legal namecompanyVatStatus- Get a company's focused VAT/registry status by CUIconnectionsCreate- Request a gov connection (returns the dashboard consent URL)connectionsGet- Get one gov connection's metadataconnectionsList- List the tenant's gov connectionsconnectionsRevoke- Revoke a gov connection and wipe its vault credentialefacturaDownload- Get a signed download URL for an invoice's e-Factura resultefacturaDownloadZip- Download an invoice's e-Factura result zip through a signed linkefacturaJobsCancel- Cancel an undelivered e-Factura submission jobefacturaJobsGet- Read one e-Factura submission jobefacturaJobsList- List e-Factura submission jobs, newest firstefacturaListMessages- List e-Factura messages for a connected companyefacturaStatus- Get an invoice's e-Factura clearance stateefacturaUpload- Upload a UBL/JSON invoice to e-FacturaefacturaValidate- Validate a UBL invoice offline, and with ?online=true also at ANAF (no ANAF connection required)etransportCreate- Create an e-Transport declarationetransportGet- Query an e-Transport declaration by UITetransportJobsCancel- Cancel an undelivered e-Transport submission jobetransportJobsGet- Read one e-Transport submission jobetransportJobsList- List e-Transport submission jobs, newest firstetransportModify- Modify an e-Transport declaration by UITfxConvert- Convert an amount between currencies at the latest ratesfxListRates- List the latest BNR reference ratesgeoGetParcel- Look up a cadastral parcel by coordinates or INSPIRE idhealthCheck- Report db/redis/ANAF reachabilityjusticeListCaseChanges- Search the litigation change-feed since a given timestampjusticeListCourts- List or search the canonical ECRIS court identifiersjusticeListHearings- Get the hearing docket for a court on a datejusticeSearchCases- Search court cases by party, number, object, or courtlegislationActsGet- Get an act's current consolidated formlegislationActsGetVersion- Get an act's body as it read on a given version datelegislationActsList- List consolidated normative actslegislationActsListChanges- Poll the acts change-feed since a given timestamplegislationActsListVersions- List an act's history: consolidations, republications and the base formlegislationBillsGet- Get a single parliamentary billlegislationBillsList- List parliamentary billslegislationBillsListChanges- Poll the bills change-feed since a given timestamplegislationBillsListDocuments- Get a bill's associated documentslegislationBillsListStages- Get a bill's legislative stage historylegislationMonitorulOficialGetAct- Get an act as it appeared in Monitorul OficiallegislationMonitorulOficialListChanges- Poll the Monitorul Oficial change-feed since a given timestamplegislationMonitorulOficialListIssues- List Monitorul Oficial issuesmeGet- Get the resolved business, tier, effective scopes, and limitsprocurementGetContract- Get a single public procurement contract's detail by numberprocurementGetCpvAnalysis- Get market analysis for a CPV codeprocurementListCompanyContracts- List a company's public procurement contracts by CUIprocurementListCompanyDirectPurchases- List a company's public procurement direct purchases by CUIprocurementListCompanyTenders- List a company's public procurement tenders by CUIprocurementListCpvContracts- List public procurement contracts for a CPV coderegesContractsCreate- Register a REGES employment contract, asyncregesContractsTerminate- Terminate a REGES employment contract, asyncregesEmployeesList- List REGES employees for a connected company (CNP masked)regesJobsGet- Get a REGES async job's statussearchCompanies- Search companies by namespvDownloadDocument- Download one SPV document as a binary streamspvGetEtvaDecont- Fetch the e-TVA pre-completed VAT return for a periodspvListMessages- List SPV inbox messagesstatsGetMatrix- Fetch a TEMPO matrix dataset with optional dimension filtersvatValidateVies- Validate an EU VAT number against VIES
Pagination
Some of the endpoints in this SDK support pagination. To use pagination, you
make your SDK calls as usual, but the returned response object will also be an
async iterable that can be consumed using the for await...of
syntax.
Here's an example of one such pagination call:
import { EasyApi } from "@digitap.eu/easyapi";
const easyApi = new EasyApi({
apiKey: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await easyApi.legislation.bills.list({});
for await (const page of result) {
console.log(page);
}
}
run();
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { EasyApi } from "@digitap.eu/easyapi";
const easyApi = new EasyApi();
async function run() {
const result = await easyApi.health.check({
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { EasyApi } from "@digitap.eu/easyapi";
const easyApi = new EasyApi({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
async function run() {
const result = await easyApi.health.check();
console.log(result);
}
run();
Error Handling
EasyAPIError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | --------------------------------------------------------------------------------------- |
| error.message | string | Error message |
| error.statusCode | number | HTTP response status code eg 404 |
| error.headers | Headers | HTTP response headers |
| error.body | string | HTTP body. Can be empty string if no body is returned. |
| error.rawResponse | Response | Raw HTTP response |
| error.data$ | | Optional. Some errors may contain structured data. See Error Classes. |
Example
import { EasyApi } from "@digitap.eu/easyapi";
import * as errors from "@digitap.eu/easyapi/models/errors";
const easyApi = new EasyApi();
async function run() {
try {
const result = await easyApi.health.check();
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.EasyAPIError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.ErrorEnvelope) {
console.log(error.data$.error); // models.ErrorT
}
}
}
}
run();
Error Classes
Primary errors:
EasyAPIError: The base class for HTTP error responses.ErrorEnvelope: Generic error.
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from EasyAPIError:
ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
Server Selection
Override Server URL Per-Client
The default server can be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { EasyApi } from "@digitap.eu/easyapi";
const easyApi = new EasyApi({
serverURL: "https://easyapi.ro",
});
async function run() {
const result = await easyApi.health.check();
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to:
- route requests through a proxy server using undici's ProxyAgent
- use the
"beforeRequest"hook to add a custom header and a timeout to requests - use the
"requestError"hook to log errors
import { EasyApi } from "@digitap.eu/easyapi";
import { ProxyAgent } from "undici";
import { HTTPClient } from "@digitap.eu/easyapi/lib/http";
const dispatcher = new ProxyAgent("http://proxy.example.com:8080");
const httpClient = new HTTPClient({
// 'fetcher' takes a function that has the same signature as native 'fetch'.
fetcher: (input, init) =>
// 'dispatcher' is specific to undici and not part of the standard Fetch API.
fetch(input, { ...init, dispatcher } as RequestInit),
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new EasyApi({ httpClient: httpClient });Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { EasyApi } from "@digitap.eu/easyapi";
const sdk = new EasyApi({ debugLogger: console });