@12-apps/fiscal 1.5.0 → 1.7.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.
Files changed (80) hide show
  1. package/README.md +46 -4
  2. package/dist/{chunk-HMTPJWXM.js → chunk-2JVTHJAU.js} +2 -2
  3. package/dist/{chunk-3E3NBXSW.js → chunk-CEK2GDRY.js} +5 -3
  4. package/dist/chunk-CEK2GDRY.js.map +1 -0
  5. package/dist/{chunk-MGTROA7K.js → chunk-OAQSGDZ7.js} +11 -7
  6. package/dist/chunk-OAQSGDZ7.js.map +1 -0
  7. package/dist/{chunk-ZKWVKCGJ.js → chunk-P5EDTNWE.js} +1 -1
  8. package/dist/{chunk-ZKWVKCGJ.js.map → chunk-P5EDTNWE.js.map} +1 -1
  9. package/dist/{chunk-G6QNU4FD.js → chunk-P7CRGZGO.js} +2 -2
  10. package/dist/{chunk-H33BK623.js → chunk-WRYCYXRA.js} +1 -1
  11. package/dist/{chunk-H33BK623.js.map → chunk-WRYCYXRA.js.map} +1 -1
  12. package/dist/{chunk-TJCUO6D6.js → chunk-YHSO3476.js} +6 -5
  13. package/dist/chunk-YHSO3476.js.map +1 -0
  14. package/dist/{context-CwZiHLnY.d.ts → context-D71ETH--.d.ts} +155 -19
  15. package/dist/danfe/index.d.ts +7 -0
  16. package/dist/danfe/index.js +2 -2
  17. package/dist/documents/index.d.ts +157 -36
  18. package/dist/documents/index.js +1104 -305
  19. package/dist/documents/index.js.map +1 -1
  20. package/dist/engine/index.d.ts +2 -2
  21. package/dist/http.d.ts +6 -5
  22. package/dist/http.js +4 -4
  23. package/dist/issuer/index.d.ts +10 -3
  24. package/dist/issuer/index.js +19 -4
  25. package/dist/issuer/index.js.map +1 -1
  26. package/dist/jobs.d.ts +5 -5
  27. package/dist/jobs.js +3 -3
  28. package/dist/manifest/index.d.ts +6 -4
  29. package/dist/manifest/index.js.map +1 -1
  30. package/dist/manifest/server.d.ts +5 -5
  31. package/dist/manifest/server.js +6 -6
  32. package/dist/notifications.d.ts +4 -4
  33. package/dist/notifications.js +2 -2
  34. package/dist/sale/index.d.ts +17 -4
  35. package/dist/sale/index.js.map +1 -1
  36. package/dist/{service-Cz2O84Xr.d.ts → service-DyA64Jc6.d.ts} +64 -5
  37. package/dist/sidecar/index.d.ts +38 -249
  38. package/dist/sidecar/index.js +30 -2
  39. package/dist/sidecar/index.js.map +1 -1
  40. package/dist/{types-DSYwap42.d.ts → types-6OiBrmZy.d.ts} +2 -2
  41. package/dist/{types-B1b8LIWX.d.ts → types-BLdkww6G.d.ts} +1 -1
  42. package/dist/types-BbTxBzsv.d.ts +252 -0
  43. package/package.json +2 -1
  44. package/prisma/fiscal.prisma +50 -1
  45. package/prisma/migrations/20261118180000_fiscal_contingency_blocks/migration.sql +64 -0
  46. package/sidecar/README.md +70 -10
  47. package/sidecar/bin/check-platform.php +29 -0
  48. package/sidecar/extensions.json +12 -0
  49. package/sidecar/schema/sale-for-document.schema.json +4 -0
  50. package/sidecar/src/Http/Request.php +6 -1
  51. package/sidecar/src/Kernel.php +39 -1
  52. package/sidecar/src/Nfe/DocumentMapper.php +27 -22
  53. package/sidecar/src/Platform.php +84 -0
  54. package/src/danfe/render.ts +16 -5
  55. package/src/documents/contingency-gaps.ts +88 -0
  56. package/src/documents/contingency-pass.ts +157 -0
  57. package/src/documents/contingency-xml.ts +136 -0
  58. package/src/documents/contingency.ts +257 -0
  59. package/src/documents/errors.ts +8 -1
  60. package/src/documents/helpers.ts +3 -0
  61. package/src/documents/index.ts +23 -1
  62. package/src/documents/lines.ts +6 -2
  63. package/src/documents/memory-blocks.ts +118 -0
  64. package/src/documents/memory.ts +6 -2
  65. package/src/documents/ports.ts +163 -13
  66. package/src/documents/service.ts +10 -0
  67. package/src/documents/sql-blocks.ts +202 -0
  68. package/src/documents/sql-store.ts +4 -3
  69. package/src/http.ts +1 -0
  70. package/src/issuer/sidecar.ts +27 -3
  71. package/src/manifest/index.ts +6 -4
  72. package/src/sale/types.ts +17 -4
  73. package/src/sidecar/index.ts +2 -0
  74. package/src/sidecar/platform.ts +55 -0
  75. package/src/sidecar/types.ts +1 -3
  76. package/dist/chunk-3E3NBXSW.js.map +0 -1
  77. package/dist/chunk-MGTROA7K.js.map +0 -1
  78. package/dist/chunk-TJCUO6D6.js.map +0 -1
  79. /package/dist/{chunk-HMTPJWXM.js.map → chunk-2JVTHJAU.js.map} +0 -0
  80. /package/dist/{chunk-G6QNU4FD.js.map → chunk-P7CRGZGO.js.map} +0 -0
@@ -54,7 +54,8 @@ model FiscalIssuingPoint {
54
54
  contingencySeries Int? @map("contingency_series")
55
55
  createdAt DateTime @default(now()) @map("created_at")
56
56
 
57
- counters FiscalNumberCounter[]
57
+ counters FiscalNumberCounter[]
58
+ contingencyBlocks FiscalContingencyBlock[]
58
59
 
59
60
  @@index([ownerId])
60
61
  @@map("fiscal_issuing_points")
@@ -156,3 +157,51 @@ model FiscalDocumentEvent {
156
157
  @@index([documentId, at])
157
158
  @@map("fiscal_document_events")
158
159
  }
160
+
161
+ // A block of a contingency series handed to one holder (the host's opaque id
162
+ // of a register that may go offline) to sign on with no server (FUT-4717).
163
+ // Drawn from the series' counter, so no other document numbers inside it.
164
+ // The CHECKs (fate, range, usedUpTo) are the migration's.
165
+ model FiscalContingencyBlock {
166
+ id String @id
167
+ ownerId String @map("owner_id")
168
+ issuingPointId String @map("issuing_point_id")
169
+ issuerCnpj String @map("issuer_cnpj")
170
+ environment String
171
+ model String
172
+ series Int
173
+ firstNumber Int @map("first_number")
174
+ lastNumber Int @map("last_number")
175
+ holder String
176
+ // OPEN | CLOSED | ABANDONED
177
+ fate String @default("OPEN")
178
+ // The highest number the holder reported it used (CLOSED); null otherwise.
179
+ usedUpTo Int? @map("used_up_to")
180
+ reservedAt DateTime @map("reserved_at")
181
+ closedAt DateTime? @map("closed_at")
182
+ // Every number accounted for (a document, or voided).
183
+ settledAt DateTime? @map("settled_at")
184
+ issuingPoint FiscalIssuingPoint @relation(fields: [issuingPointId], references: [id], onDelete: Restrict)
185
+
186
+ voids FiscalContingencyVoid[]
187
+
188
+ @@unique([issuerCnpj, environment, model, series, firstNumber], map: "fiscal_contingency_blocks_first_key")
189
+ @@index([ownerId, holder])
190
+ @@index([issuingPointId])
191
+ @@map("fiscal_contingency_blocks")
192
+ }
193
+
194
+ // A range of a block inutilized at SEFAZ: a known gap, voided once.
195
+ model FiscalContingencyVoid {
196
+ id String @id
197
+ blockId String @map("block_id")
198
+ firstNumber Int @map("first_number")
199
+ lastNumber Int @map("last_number")
200
+ protocol String?
201
+ eventXmlKey String? @map("event_xml_key")
202
+ voidedAt DateTime @map("voided_at")
203
+ block FiscalContingencyBlock @relation(fields: [blockId], references: [id], onDelete: Restrict)
204
+
205
+ @@unique([blockId, firstNumber])
206
+ @@map("fiscal_contingency_voids")
207
+ }
@@ -0,0 +1,64 @@
1
+ -- @domains: fiscal
2
+ -- @12-apps/fiscal (FUT-4717): the blocks of a contingency series a host hands
3
+ -- to a holder (a register that may go offline) to sign on, and the ranges of
4
+ -- them voided at SEFAZ. A block is drawn from the series' ONE counter, so the
5
+ -- server's own contingency never numbers inside it. Additive only: two new
6
+ -- tables. `holder` is the host's opaque id, stored by value.
7
+
8
+ CREATE TABLE "fiscal_contingency_blocks" (
9
+ "id" TEXT NOT NULL,
10
+ "owner_id" TEXT NOT NULL,
11
+ "issuing_point_id" TEXT NOT NULL,
12
+ "issuer_cnpj" TEXT NOT NULL,
13
+ "environment" TEXT NOT NULL,
14
+ "model" TEXT NOT NULL,
15
+ "series" INTEGER NOT NULL,
16
+ "first_number" INTEGER NOT NULL,
17
+ "last_number" INTEGER NOT NULL,
18
+ "holder" TEXT NOT NULL,
19
+ "fate" TEXT NOT NULL DEFAULT 'OPEN',
20
+ "used_up_to" INTEGER,
21
+ "reserved_at" TIMESTAMP(3) NOT NULL,
22
+ "closed_at" TIMESTAMP(3),
23
+ -- Every number accounted for (a document, or voided): the gap job skips it.
24
+ "settled_at" TIMESTAMP(3),
25
+
26
+ CONSTRAINT "fiscal_contingency_blocks_pkey" PRIMARY KEY ("id"),
27
+ CONSTRAINT "fiscal_contingency_blocks_issuing_point_id_fkey"
28
+ FOREIGN KEY ("issuing_point_id") REFERENCES "fiscal_issuing_points"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
29
+ CONSTRAINT "fiscal_contingency_blocks_environment_check" CHECK ("environment" IN ('homologacao', 'producao')),
30
+ CONSTRAINT "fiscal_contingency_blocks_model_check" CHECK ("model" = 'NFCE'),
31
+ CONSTRAINT "fiscal_contingency_blocks_fate_check" CHECK ("fate" IN ('OPEN', 'CLOSED', 'ABANDONED')),
32
+ CONSTRAINT "fiscal_contingency_blocks_range_check"
33
+ CHECK ("first_number" >= 1 AND "last_number" >= "first_number" AND "last_number" <= 999999999),
34
+ -- What the holder said it used: from first - 1 (nothing) to the last number.
35
+ CONSTRAINT "fiscal_contingency_blocks_used_up_to_check"
36
+ CHECK ("used_up_to" IS NULL OR "used_up_to" BETWEEN "first_number" - 1 AND "last_number"),
37
+ CONSTRAINT "fiscal_contingency_blocks_closed_check"
38
+ CHECK (("fate" = 'OPEN') = ("closed_at" IS NULL))
39
+ );
40
+
41
+ -- A number belongs to at most one block: blocks are drawn from the series' counter.
42
+ CREATE UNIQUE INDEX "fiscal_contingency_blocks_first_key"
43
+ ON "fiscal_contingency_blocks"("issuer_cnpj", "environment", "model", "series", "first_number");
44
+ CREATE INDEX "fiscal_contingency_blocks_owner_id_holder_idx" ON "fiscal_contingency_blocks"("owner_id", "holder");
45
+ CREATE INDEX "fiscal_contingency_blocks_issuing_point_id_idx" ON "fiscal_contingency_blocks"("issuing_point_id");
46
+
47
+ CREATE TABLE "fiscal_contingency_voids" (
48
+ "id" TEXT NOT NULL,
49
+ "block_id" TEXT NOT NULL,
50
+ "first_number" INTEGER NOT NULL,
51
+ "last_number" INTEGER NOT NULL,
52
+ "protocol" TEXT,
53
+ "event_xml_key" TEXT,
54
+ "voided_at" TIMESTAMP(3) NOT NULL,
55
+
56
+ CONSTRAINT "fiscal_contingency_voids_pkey" PRIMARY KEY ("id"),
57
+ CONSTRAINT "fiscal_contingency_voids_block_id_fkey"
58
+ FOREIGN KEY ("block_id") REFERENCES "fiscal_contingency_blocks"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
59
+ CONSTRAINT "fiscal_contingency_voids_range_check" CHECK ("last_number" >= "first_number")
60
+ );
61
+
62
+ -- A range is voided once.
63
+ CREATE UNIQUE INDEX "fiscal_contingency_voids_block_id_first_number_key"
64
+ ON "fiscal_contingency_voids"("block_id", "first_number");
package/sidecar/README.md CHANGED
@@ -52,10 +52,20 @@ reach SEFAZ either does an NFC-e being issued answer `CONTINGENCY` (with
52
52
  `outcomeUnknown: true`); everywhere else it is `RETRYABLE`. A blind
53
53
  contingency could put a second document on the same sale.
54
54
 
55
- **Layout limit.** A document issued on or after 2027-01-01 is refused as
56
- `INVALID` with code `NT_2026_008_NOT_SUPPORTED`: from 2027 the IBS/CBS go
57
- inside `vProd` and the net price travels in NT 2026.008's `vProdLiq`, which
58
- sped-nfe 5.2.9 cannot write.
55
+ **The net value (NT 2026.008).** From 2027 the IBS/CBS go inside `vProd` and
56
+ the price without them travels in `vProdLiq`. A line's optional
57
+ `netValueCents` is that figure (the engine's `LineTax.netValueCents`), written
58
+ as given; `vUnComLiq` is derived from it over `quantity` with ten decimals, as
59
+ `vUnCom` is, and `vProdLiqTot` is their sum. The service derives the unit
60
+ value itself (half-up to ten decimals) rather than taking the engine's
61
+ `netUnitValue` string (exact, half-even), so the two may differ in the tenth
62
+ decimal only: `vUnComLiq × qCom` stays far inside I11c-20's ±0,01 of
63
+ `vProdLiq`. Absent or `null` writes none of
64
+ the three, byte for byte the document it was before. It is `INVALID` to carry
65
+ it on some lines only, or above the line's `valueCents`. Whether a period puts
66
+ the tax inside the price is the engine's rate table's call; the service
67
+ refuses no date (the `NT_2026_008_NOT_SUPPORTED` refusal of sped-nfe 5.2.9 is
68
+ gone with the bump to 5.2.11).
59
69
 
60
70
  **A return document.** `operation` maps to `tpNF` (`OUT` 1, `IN` 0) and
61
71
  `referencedDocuments[].accessKey` to `NFref/refNFe`, in order. Both are
@@ -80,7 +90,7 @@ Every failure is `{ error: { class, code, message, details, accessKey, signedXml
80
90
  | `RETRYABLE` | 503 | try again: nothing reached SEFAZ outside NFC-e issuing, a receipt with no protocol yet (103, 105), SEFAZ unable to reach a revocation list (286, 296), rate limiting (656), 999, SEFAZ stopped (108, 109) outside issuing, a reply with no status, a 4xx that is not SEFAZ's. With `outcomeUnknown: true`, look the key up before sending again. |
81
91
  | `CONTINGENCY` | 503 | issuing an NFC-e: nothing reached SEFAZ, or SEFAZ is stopped (108, 109), or a request with no answer could not be settled by a lookup. Go offline through `/nfce/sign-contingency`. **On an NF-e (model 55)** there is no offline path in this service (no SVC, no EPEC): only 108/109 answer `CONTINGENCY` there, and the host treats it as "retry later". |
82
92
  | `AUTH` | 401 | the `.pfx` does not open (wrong password, not PKCS#12), the certificate expired, the client certificate was refused at the TLS handshake or by an HTTP 403 from a verified SEFAZ host, or by code (213, 280–285, 290–295). Codes from sped-nfe's `storage/cstat.json`. An HTTP refusal's message names the IIS substatus (403.6 is an IP block, 403.7 a missing client certificate) or quotes the start of SEFAZ's page. |
83
- | `INVALID` | 400 | the request is malformed: the schema, a missing CSC, an XML the layout's XSD refuses, a quantity with more than four decimals, a document past the layout limit. Never retry it as is. |
93
+ | `INVALID` | 400 | the request is malformed: the schema, a missing CSC, an XML the layout's XSD refuses, a quantity with more than four decimals, a net value (`netValueCents`) on some lines only or above the line's `valueCents`. Never retry it as is. |
84
94
  | `INTERNAL` | 500 | a defect of the service, or a 4xx other than 403/408/429 from the verified SEFAZ host (a wrong web-service address); a retry would repeat it. |
85
95
 
86
96
  When the call got as far as signing, `accessKey` and `signedXml` come back
@@ -97,12 +107,63 @@ with the error: the key is spoken for, and an NFC-e can be signed offline.
97
107
  - The request log is one JSON line per call on stderr: time, method, path,
98
108
  status, duration, error class and SEFAZ code. Nothing read from the body is
99
109
  ever in it, and stack traces carry no arguments
100
- (`zend.exception_ignore_args`).
110
+ (`zend.exception_ignore_args`; in the image from `docker/php.ini`, on a
111
+ bundled PHP from the launch flags below — and the launch token is a
112
+ `#[\SensitiveParameter]` besides).
113
+
114
+ ## Running without Docker (a bundled PHP)
115
+
116
+ A host that cannot run the image — a desktop register that must issue
117
+ offline (FUT-4717) — runs the service with a PHP of its own, bound to the
118
+ loopback only, with a token minted at each launch:
119
+
120
+ ```sh
121
+ FLAGS="-d display_errors=0 -d log_errors=1 -d zend.exception_ignore_args=1 \
122
+ -d zend.exception_string_param_max_len=0 -d file_uploads=0"
123
+ php $FLAGS sidecar/bin/check-platform.php # exit 1, naming what this PHP or launch lacks
124
+ FISCAL_SIDECAR_TOKEN=<random, 32+ chars> \
125
+ php $FLAGS -S 127.0.0.1:<port> -t sidecar/public sidecar/public/index.php
126
+ ```
127
+
128
+ - **Always launch with those flags** (`SIDECAR_PHP_LAUNCH_FLAGS` in
129
+ `@12-apps/fiscal/sidecar`, `ini` in `extensions.json`). They are what the
130
+ image's `docker/php.ini` guarantees, and a bundled PHP has none of them on
131
+ its own: without them an error or a deprecation is printed into the response
132
+ ahead of the JSON (the issuer reads that call as unanswered, its outcome
133
+ unknown), and an escaping exception prints its trace WITH arguments.
134
+ `-d` flags rather than `-c docker/php.ini`, whose `error_log = /dev/stderr`
135
+ a Windows desktop does not have. `bin/check-platform.php` fails a launch
136
+ without them (`zend.exception_ignore_args` off, say), and the PHPUnit
137
+ suite starts the service with exactly these flags.
138
+
139
+ - **Bind `127.0.0.1`, never `0.0.0.0`.** Binding is the launcher's: the
140
+ service cannot tell a loopback caller from another. The token is what keeps
141
+ another process of the same machine out; the launcher passes it in the
142
+ environment, never on the command line (a process listing prints argv).
143
+ - **The PHP:** 8.3, with exactly the extensions `extensions.json` lists
144
+ (`@12-apps/fiscal/sidecar/extensions.json`; `SIDECAR_PHP_EXTENSIONS` in
145
+ `@12-apps/fiscal/sidecar`): `curl` (the SEFAZ transport), `dom`, `filter`
146
+ (json-schema), `json`, `libxml`, `mbstring` (sped-common), `openssl`,
147
+ `reflection` (php-enum), `simplexml`, `soap` and `zlib`, plus the
148
+ command-line SAPI with its built-in server. A PHPUnit test keeps the list
149
+ equal to every `ext-*` of `composer.json` and the locked libraries, so a
150
+ library bump that needs a new extension fails here, and
151
+ `bin/check-platform.php` fails the host's build that bundles a PHP without
152
+ it.
153
+ - **The libraries:** the tarball ships `composer.json` and `composer.lock`,
154
+ not `vendor/`. A host build runs
155
+ `composer install --no-dev --classmap-authoritative --ignore-platform-req=ext-soap`
156
+ in a copy of `sidecar/` (the Dockerfile's own command) and bundles the
157
+ result with `public/`, `src/` and `schema/`.
158
+ - The trust store and the OpenSSL legacy provider are the image's
159
+ (`docker/`): outside it, point `FISCAL_SEFAZ_CA_BUNDLE` at the system bundle
160
+ plus `docker/icp-brasil.pem`, and `OPENSSL_CONF` at `docker/openssl.cnf`.
101
161
 
102
162
  ## Configuration
103
163
 
104
164
  | variable | default | |
105
165
  |---|---|---|
166
+ | `FISCAL_SIDECAR_TOKEN` | unset | when set (32 characters or more), every route but `/health` answers only a call carrying `Authorization: Bearer <token>`, compared in constant time; any other call is `401` with `{ error: { class: "INVALID", code: "UNAUTHORIZED" } }`, refused before it is routed. The token is never logged nor answered. `createSidecarIssuer({ …, token })` sends it. A service embedded on a computer mints one per launch (FUT-4717); the container image, reached on a private network, may run without one. |
106
167
  | `FISCAL_SEFAZ_TIMEOUT_SECONDS` | `30` | connect timeout, TLS handshake included; the whole request gets 20 s more |
107
168
  | `FISCAL_SEFAZ_TLS_VERIFY` | on | SEFAZ's server certificate is verified. `off` is the only value that turns it off, and `/health` then reports `sefazTlsVerify: false`. Unverified, anyone on the path reads every document and can forge SEFAZ's answers. |
108
169
  | `FISCAL_SEFAZ_CA_BUNDLE` | the image's | a PEM replacing the trust store. The image builds `/etc/ssl/fiscal-sidecar-ca.pem` from its Mozilla bundle plus `docker/icp-brasil.pem` (the ICP-Brasil roots and intermediates ITI publishes, sha256-checked in the Dockerfile): some SEFAZ hosts present ICP-Brasil server certificates, others public ones. Outside the image the system bundle plus that PEM are used. |
@@ -157,7 +218,6 @@ SEFAZ directly.
157
218
 
158
219
  ## Versions
159
220
 
160
- sped-nfe `5.2.9`, schema package `PL_010_V1.30` (Pacote de Liberação 010f: NT
161
- 2025.002 v1.50 and NT 2026.007 v1.00). NT 2026.008's `vProdLiq` and
162
- `vProdLiqTot`, needed when the IBS/CBS move inside `vProd` in 2027, are on
163
- sped-nfe's `master` after 5.2.9 and arrive with its next release.
221
+ sped-nfe `5.2.11`, schema package `PL_010_V1.30` (Pacote de Liberação 010f: NT
222
+ 2025.002 v1.50 and NT 2026.007 v1.00), which carries NT 2026.008's
223
+ `vUnComLiq`/`vProdLiq`/`vProdLiqTot` and NT 2026.006's `gPgtoVinc`.
@@ -0,0 +1,29 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ /*
6
+ * Exits 0 when the PHP running it can run the service, 1 listing what it
7
+ * lacks otherwise. Run it with the PHP a desktop build bundles AND the launch
8
+ * flags the service runs with (sidecar/README.md, `SIDECAR_PHP_LAUNCH_FLAGS`),
9
+ * so a launch that drops `zend.exception_ignore_args` fails here:
10
+ *
11
+ * ./php -d display_errors=0 -d log_errors=1 -d zend.exception_ignore_args=1 \
12
+ * -d zend.exception_string_param_max_len=0 -d file_uploads=0 sidecar/bin/check-platform.php
13
+ *
14
+ * It needs no vendor/ folder: a build checks its PHP before it copies one in.
15
+ */
16
+
17
+ require dirname(__DIR__) . '/src/Platform.php';
18
+
19
+ $problems = [
20
+ ...Fiscal\Sidecar\Platform::missing(get_loaded_extensions(), PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION),
21
+ ...Fiscal\Sidecar\Platform::unsafeSettings('ini_get'),
22
+ ];
23
+ if (!in_array(PHP_SAPI, ['cli'], true)) {
24
+ $problems[] = 'run this with the command-line PHP (' . PHP_SAPI . ' is not cli)';
25
+ }
26
+ foreach ($problems as $problem) {
27
+ fwrite(STDERR, "fiscal sidecar: $problem\n");
28
+ }
29
+ exit($problems === [] ? 0 : 1);
@@ -0,0 +1,12 @@
1
+ {
2
+ "php": "8.3",
3
+ "extensions": ["curl", "dom", "filter", "json", "libxml", "mbstring", "openssl", "reflection", "simplexml", "soap", "zlib"],
4
+ "sapi": ["cli", "cli-server"],
5
+ "ini": {
6
+ "display_errors": "0",
7
+ "log_errors": "1",
8
+ "zend.exception_ignore_args": "1",
9
+ "zend.exception_string_param_max_len": "0",
10
+ "file_uploads": "0"
11
+ }
12
+ }
@@ -362,6 +362,10 @@
362
362
  "minimum": 1
363
363
  },
364
364
  "discountCents": { "$ref": "#/definitions/cents" },
365
+ "netValueCents": {
366
+ "description": "vProdLiq (NT 2026.008 v1.00): the line's value without the IBS/CBS, where they sit inside vProd (from 2027); at most valueCents. vUnComLiq and vProdLiqTot are derived from it. Absent or null: none of the three is written. Every line carries it or none does.",
367
+ "oneOf": [{ "type": "null" }, { "$ref": "#/definitions/cents" }]
368
+ },
365
369
  "approximateTaxCents": { "oneOf": [{ "type": "null" }, { "$ref": "#/definitions/cents" }] },
366
370
  "additionalInfo": { "oneOf": [{ "type": "null" }, { "type": "string", "minLength": 1, "maxLength": 500 }] },
367
371
  "icms": { "$ref": "#/definitions/icms" },
@@ -7,13 +7,17 @@ namespace Fiscal\Sidecar\Http;
7
7
  use Fiscal\Sidecar\ServiceError;
8
8
  use JsonException;
9
9
 
10
- /** One HTTP request, as the kernel sees it: the method, the path and the raw body. */
10
+ /**
11
+ * One HTTP request, as the kernel sees it: the method, the path, the raw body
12
+ * and the one header it reads, `Authorization` (the launch token, FUT-4717).
13
+ */
11
14
  final class Request
12
15
  {
13
16
  public function __construct(
14
17
  public readonly string $method,
15
18
  public readonly string $path,
16
19
  private readonly string $body,
20
+ public readonly ?string $authorization = null,
17
21
  ) {
18
22
  }
19
23
 
@@ -25,6 +29,7 @@ final class Request
25
29
  strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')),
26
30
  $path === '' ? '/' : $path,
27
31
  (string) file_get_contents('php://input'),
32
+ isset($_SERVER['HTTP_AUTHORIZATION']) ? (string) $_SERVER['HTTP_AUTHORIZATION'] : null,
28
33
  );
29
34
  }
30
35
 
@@ -16,16 +16,29 @@ use Throwable;
16
16
  * The service: a router over the library modules, one request at a time.
17
17
  * Built per request by `public/index.php`, so nothing a call brings in (a
18
18
  * certificate, above all) can outlive it.
19
+ *
20
+ * With a token (`FISCAL_SIDECAR_TOKEN`, FUT-4717), every route but
21
+ * `/health` answers only a call carrying `Authorization: Bearer <token>`,
22
+ * compared in constant time; any other call is refused 401 before it is
23
+ * routed. The token is never logged nor answered.
19
24
  */
20
25
  final class Kernel
21
26
  {
22
27
  private readonly Router $router;
23
28
 
29
+ /** The path no token guards: a liveness probe carries no secret and answers none. */
30
+ public const OPEN_PATH = '/health';
31
+
24
32
  /** @param list<Module> $modules */
25
33
  public function __construct(
26
34
  private readonly array $modules,
27
35
  private readonly RequestLog $log,
36
+ #[\SensitiveParameter]
37
+ private readonly ?string $token = null,
28
38
  ) {
39
+ if ($token !== null && strlen($token) < 32) {
40
+ throw new \InvalidArgumentException('FISCAL_SIDECAR_TOKEN must be at least 32 characters.');
41
+ }
29
42
  $this->router = new Router();
30
43
  $this->router->add('GET', '/health', fn (): Response => $this->health());
31
44
  foreach ($modules as $module) {
@@ -36,7 +49,27 @@ final class Kernel
36
49
  /** The production wiring: every module, talking to SEFAZ over cURL. */
37
50
  public static function production(?Transport $transport = null, ?RequestLog $log = null): self
38
51
  {
39
- return new self(self::modules($transport ?? CurlTransport::fromEnvironment()), $log ?? new RequestLog());
52
+ return new self(self::modules($transport ?? CurlTransport::fromEnvironment()), $log ?? new RequestLog(), self::tokenFromEnvironment());
53
+ }
54
+
55
+ /** `FISCAL_SIDECAR_TOKEN`, or `null` when unset or empty (the container image, reached on a private network). */
56
+ public static function tokenFromEnvironment(): ?string
57
+ {
58
+ $token = getenv('FISCAL_SIDECAR_TOKEN');
59
+ return is_string($token) && $token !== '' ? $token : null;
60
+ }
61
+
62
+ /** Whether the call may be routed: no token set, the open path, or the right bearer. */
63
+ private function authorized(Request $request): bool
64
+ {
65
+ if ($this->token === null || $request->path === self::OPEN_PATH) {
66
+ return true;
67
+ }
68
+ $header = $request->authorization ?? '';
69
+ if (!str_starts_with($header, 'Bearer ')) {
70
+ return false;
71
+ }
72
+ return hash_equals($this->token, substr($header, 7));
40
73
  }
41
74
 
42
75
  /**
@@ -57,6 +90,11 @@ final class Kernel
57
90
  public function handle(Request $request): Response
58
91
  {
59
92
  $startedAt = microtime(true);
93
+ if (!$this->authorized($request)) {
94
+ $error = new ServiceError(ErrorClass::INVALID, 'This call needs the service token.', 'UNAUTHORIZED');
95
+ $this->log->record($request->method, $request->path, 401, $startedAt, ErrorClass::INVALID, null, 'Unauthorized');
96
+ return new Response(401, $error->toBody());
97
+ }
60
98
  try {
61
99
  $response = $this->router->dispatch($request);
62
100
  $class = isset($response->body['error']['class'])
@@ -66,19 +66,6 @@ final class DocumentMapper
66
66
 
67
67
  public const PROCESS_VERSION = 'fiscal-sidecar-1';
68
68
 
69
- /**
70
- * From 2027 the IBS/CBS go INSIDE `vProd`, and the price without tax
71
- * travels in NT 2026.008's `vProdLiq`/`vUnComLiq`/`vProdLiqTot` (source: NT
72
- * 2026.008 v1.00 itself: from 2027 the IBS, CBS and IS values "deverão ser
73
- * acrescidos ao valor do produto ou serviço, compondo o valor informado no
74
- * campo vProd"). sped-nfe 5.2.9 cannot write those fields, and document
75
- * version 1 does not carry them, so a document issued on or after this day
76
- * is refused rather than emitted wrong. Lifted by the sped-nfe bump that
77
- * brings NT 2026.008, with document version 2.
78
- */
79
- public const LAYOUT_LIMIT = '2027-01-01';
80
- public const LAYOUT_LIMIT_CODE = 'NT_2026_008_NOT_SUPPORTED';
81
-
82
69
  /** A return (`finNFe` 4) quotes the document it returns (`NFref`); one without a reference is refused. */
83
70
  public const RETURN_NEEDS_REFERENCE_CODE = 'RETURN_NEEDS_REFERENCE';
84
71
 
@@ -127,20 +114,23 @@ final class DocumentMapper
127
114
  /** @param array<string, mixed> $document */
128
115
  private static function refuseWhatThisLayoutCannotSay(array $document): void
129
116
  {
130
- if (substr((string) $document['issuedAt'], 0, 10) >= self::LAYOUT_LIMIT) {
131
- throw new ServiceError(
132
- \Fiscal\Sidecar\ErrorClass::INVALID,
133
- 'A document issued on or after ' . self::LAYOUT_LIMIT . ' needs NT 2026.008 (vProdLiq), '
134
- . 'which this service\'s sped-nfe does not write yet.',
135
- self::LAYOUT_LIMIT_CODE,
136
- );
137
- }
138
117
  $details = [];
118
+ $withNetValue = 0;
139
119
  foreach (array_values($document['lines']) as $index => $line) {
140
120
  $quantity = (float) $line['quantity'];
141
121
  if (abs(round($quantity, 4) - $quantity) > 1e-9) {
142
122
  $details[] = "lines[$index].quantity: at most four decimals (qCom)";
143
123
  }
124
+ $net = $line['netValueCents'] ?? null;
125
+ if ($net !== null) {
126
+ $withNetValue++;
127
+ if ($net > $line['valueCents']) {
128
+ $details[] = "lines[$index].netValueCents: at most valueCents (vProdLiq is vProd without the IBS/CBS)";
129
+ }
130
+ }
131
+ }
132
+ if ($withNetValue !== 0 && $withNetValue !== count($document['lines'])) {
133
+ $details[] = 'lines: netValueCents on every line or on none (vProdLiqTot sums them all)';
144
134
  }
145
135
  if ($details !== []) {
146
136
  throw ServiceError::invalid('The document does not fit the NF-e layout.', $details);
@@ -263,10 +253,23 @@ final class DocumentMapper
263
253
  ];
264
254
  }
265
255
 
266
- /** @param array<string, mixed> $line */
256
+ /**
257
+ * From 2027 the IBS/CBS go INSIDE `vProd`, and the price without tax
258
+ * travels in NT 2026.008's `vProdLiq`/`vUnComLiq`/`vProdLiqTot` (source: NT
259
+ * 2026.008 v1.00 itself: from 2027 the IBS, CBS and IS values "deverão ser
260
+ * acrescidos ao valor do produto ou serviço, compondo o valor informado no
261
+ * campo vProd"). A line's `netValueCents` is the engine's `vProdLiq`,
262
+ * written as given; `vUnComLiq` is derived from it as `vUnCom` is from
263
+ * `vProd`, and sped-nfe (5.2.11) sums `vProdLiqTot` from the items. Whether
264
+ * a period puts the tax inside the price is the engine's rate table's
265
+ * call, never a date here.
266
+ *
267
+ * @param array<string, mixed> $line
268
+ */
267
269
  private function line(Make $make, int $item, array $line): void
268
270
  {
269
271
  $gtin = $line['gtin'] ?? 'SEM GTIN';
272
+ $net = $line['netValueCents'] ?? null;
270
273
  $make->tagprod((object) [
271
274
  'item' => $item,
272
275
  'cProd' => $line['code'],
@@ -283,6 +286,8 @@ final class DocumentMapper
283
286
  'uTrib' => $line['unit'],
284
287
  'qTrib' => self::quantity($line['quantity']),
285
288
  'vUnTrib' => self::unitValue($line['valueCents'], $line['quantity']),
289
+ 'vUnComLiq' => $net === null ? null : self::unitValue($net, $line['quantity']),
290
+ 'vProdLiq' => $net === null ? null : self::reais($net),
286
291
  'vDesc' => $line['discountCents'] > 0 ? self::reais($line['discountCents']) : null,
287
292
  'indTot' => 1,
288
293
  ]);
@@ -0,0 +1,84 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Fiscal\Sidecar;
6
+
7
+ /**
8
+ * What a PHP must carry to run the service (FUT-4717): the minor version and
9
+ * the extensions `extensions.json` lists — every `ext-*` the service and its
10
+ * locked libraries require. A bundled static PHP (a desktop install, no
11
+ * Docker) is checked against it at build time with `bin/check-platform.php`,
12
+ * so a library bump that needs a new extension fails that build, not a sale.
13
+ *
14
+ * `ini` is what the image's `docker/php.ini` guarantees and a bundled PHP is
15
+ * launched with as `-d` flags: no error printed into a response, a stack
16
+ * trace with no arguments (a password, a certificate, the launch token), no
17
+ * upload spooled to disk.
18
+ */
19
+ final class Platform
20
+ {
21
+ /** @return array{php: string, extensions: list<string>, sapi: list<string>, ini: array<string, string>} */
22
+ public static function required(?string $file = null): array
23
+ {
24
+ $raw = (string) file_get_contents($file ?? dirname(__DIR__) . '/extensions.json');
25
+ /** @var array{php: string, extensions: list<string>, sapi: list<string>, ini: array<string, string>} $decoded */
26
+ $decoded = json_decode($raw, true, 8, JSON_THROW_ON_ERROR);
27
+ return $decoded;
28
+ }
29
+
30
+ /**
31
+ * What this PHP lacks, as readable lines; empty when it can run the service.
32
+ *
33
+ * @param list<string> $loaded extension names, as `get_loaded_extensions()` answers them
34
+ * @return list<string>
35
+ */
36
+ public static function missing(array $loaded, string $phpVersion, ?array $required = null): array
37
+ {
38
+ $required ??= self::required();
39
+ $have = array_map('strtolower', $loaded);
40
+ $problems = [];
41
+ if (!str_starts_with($phpVersion . '.', $required['php'] . '.')) {
42
+ $problems[] = "PHP {$required['php']} is required, this is $phpVersion";
43
+ }
44
+ foreach ($required['extensions'] as $extension) {
45
+ if (!in_array($extension, $have, true)) {
46
+ $problems[] = "the extension $extension is missing";
47
+ }
48
+ }
49
+ return $problems;
50
+ }
51
+
52
+ /**
53
+ * The launch settings this PHP runs without, as readable lines; empty when
54
+ * it was launched with every one of `ini` (the `-d` flags of the README).
55
+ *
56
+ * @param callable(string): (string|false) $iniGet `ini_get`, or a stand-in
57
+ * @param array<string, string>|null $settings
58
+ * @return list<string>
59
+ */
60
+ public static function unsafeSettings(callable $iniGet, ?array $settings = null): array
61
+ {
62
+ $settings ??= self::required()['ini'];
63
+ $problems = [];
64
+ foreach ($settings as $name => $wanted) {
65
+ $value = $iniGet($name);
66
+ if ($value === false || self::normalised($value) !== $wanted) {
67
+ $shown = $value === false ? 'unknown' : "'$value'";
68
+ $problems[] = "the setting $name must be $wanted (launch with -d $name=$wanted), this is $shown";
69
+ }
70
+ }
71
+ return $problems;
72
+ }
73
+
74
+ /** An ini value as `-d` writes it: on/true/yes as 1, off/false/no/empty as 0. */
75
+ private static function normalised(string $value): string
76
+ {
77
+ $lower = strtolower(trim($value));
78
+ return match ($lower) {
79
+ 'on', 'true', 'yes' => '1',
80
+ 'off', 'false', 'no', '' => '0',
81
+ default => $lower,
82
+ };
83
+ }
84
+ }
@@ -46,6 +46,13 @@ export interface DanfeNfceInput {
46
46
  readonly xml: string;
47
47
  readonly paperWidth: PaperWidth;
48
48
  readonly labels: DanfeNfceLabels;
49
+ /**
50
+ * Frame the contingency notice of a note signed offline and not yet
51
+ * authorised in a box (a `=` rule above and below it), the paper a register
52
+ * signing on its own prints (FUT-4717). Off by default: the paper is as it
53
+ * always was.
54
+ */
55
+ readonly contingencyBox?: boolean;
49
56
  }
50
57
 
51
58
  /** `1234` cents → `12,34`; thousands with a dot, as the DANFE prints money. */
@@ -119,8 +126,8 @@ class Paper {
119
126
  for (const piece of closing) this.lines.push({ division, text: piece, align: "left", emphasis });
120
127
  }
121
128
 
122
- rule(division: DanfeDivision): void {
123
- this.lines.push({ division, text: "-".repeat(this.width), align: "left", emphasis: "normal" });
129
+ rule(division: DanfeDivision, char = "-"): void {
130
+ this.lines.push({ division, text: char.repeat(this.width), align: "left", emphasis: "normal" });
124
131
  }
125
132
  }
126
133
 
@@ -199,14 +206,18 @@ function totalsPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels, count: n
199
206
  paper.rule("IV");
200
207
  }
201
208
 
202
- function fiscalMessagePart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {
209
+ function fiscalMessagePart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels, box: boolean): void {
203
210
  if (doc.homologation) paper.add("V", labels.homologation, "center", "bold");
211
+ const pending = doc.contingency && doc.infProt === null;
212
+ const framed = box && pending;
213
+ if (framed) paper.rule("V", "=");
204
214
  if (doc.contingency) paper.add("V", labels.contingency, "center", "bold");
205
215
  // Offline and not yet authorised: ONE copy, the consumer's (reprints are the same paper).
206
- if (doc.contingency && doc.infProt === null) {
216
+ if (pending) {
207
217
  paper.add("V", labels.pendingAuthorization, "center", "bold");
208
218
  paper.add("V", labels.consumerCopy, "center", "bold");
209
219
  }
220
+ if (framed) paper.rule("V", "=");
210
221
  paper.add("V", labels.lookupByKey, "center");
211
222
  paper.add("V", text(doc.supl, "urlChave") ?? "", "center");
212
223
  paper.add("V", groupKey(doc.accessKey), "center");
@@ -257,7 +268,7 @@ export function renderDanfeNfce(input: DanfeNfceInput): DanfeLine[] {
257
268
  issuerPart(paper, doc, input.labels);
258
269
  const count = itemsPart(paper, doc, input.labels);
259
270
  totalsPart(paper, doc, input.labels, count);
260
- fiscalMessagePart(paper, doc, input.labels);
271
+ fiscalMessagePart(paper, doc, input.labels, input.contingencyBox === true);
261
272
  consumerPart(paper, doc, input.labels);
262
273
  identificationPart(paper, doc, input.labels);
263
274
  qrPart(paper, doc, input.labels);