@12-apps/fiscal 1.4.0 → 1.6.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 (96) hide show
  1. package/README.md +46 -4
  2. package/dist/{chunk-EDEGIADD.js → chunk-2JVTHJAU.js} +3 -3
  3. package/dist/{chunk-2ISYBTCE.js → chunk-CEK2GDRY.js} +15 -6
  4. package/dist/chunk-CEK2GDRY.js.map +1 -0
  5. package/dist/{chunk-GF3DXCD2.js → chunk-GH452ITO.js} +1 -1
  6. package/dist/{chunk-GF3DXCD2.js.map → chunk-GH452ITO.js.map} +1 -1
  7. package/dist/{chunk-MGTROA7K.js → chunk-OAQSGDZ7.js} +11 -7
  8. package/dist/chunk-OAQSGDZ7.js.map +1 -0
  9. package/dist/{chunk-OSYB7CVT.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-F2PGQVWL.js → chunk-YHSO3476.js} +7 -6
  13. package/dist/chunk-YHSO3476.js.map +1 -0
  14. package/dist/{chunk-JVQKJNOC.js → chunk-ZKWVKCGJ.js} +1 -1
  15. package/dist/chunk-ZKWVKCGJ.js.map +1 -0
  16. package/dist/{context-CLSMOSuf.d.ts → context-Cyvfr2YB.d.ts} +167 -20
  17. package/dist/danfe/index.d.ts +7 -0
  18. package/dist/danfe/index.js +2 -2
  19. package/dist/documents/index.d.ts +154 -34
  20. package/dist/documents/index.js +1193 -306
  21. package/dist/documents/index.js.map +1 -1
  22. package/dist/engine/index.d.ts +2 -2
  23. package/dist/http.d.ts +6 -5
  24. package/dist/http.js +5 -5
  25. package/dist/issuer/index.d.ts +10 -3
  26. package/dist/issuer/index.js +27 -4
  27. package/dist/issuer/index.js.map +1 -1
  28. package/dist/jobs.d.ts +5 -5
  29. package/dist/jobs.js +4 -4
  30. package/dist/manifest/index.d.ts +6 -4
  31. package/dist/manifest/index.js.map +1 -1
  32. package/dist/manifest/server.d.ts +5 -5
  33. package/dist/manifest/server.js +7 -7
  34. package/dist/notifications.d.ts +4 -4
  35. package/dist/notifications.js +3 -3
  36. package/dist/sale/index.d.ts +29 -1
  37. package/dist/sale/index.js +7 -0
  38. package/dist/sale/index.js.map +1 -1
  39. package/dist/{service-hR3tgLpO.d.ts → service-BCK9aXop.d.ts} +99 -6
  40. package/dist/sidecar/index.d.ts +35 -210
  41. package/dist/sidecar/index.js +30 -2
  42. package/dist/sidecar/index.js.map +1 -1
  43. package/dist/{types-B1b8LIWX.d.ts → types-BLdkww6G.d.ts} +1 -1
  44. package/dist/{types-BIJqm5GM.d.ts → types-Sk010Em2.d.ts} +25 -4
  45. package/dist/types-Z5E14EPw.d.ts +254 -0
  46. package/package.json +2 -1
  47. package/prisma/fiscal.prisma +50 -1
  48. package/prisma/migrations/20261118120000_fiscal_link_payment_event/migration.sql +9 -0
  49. package/prisma/migrations/20261118180000_fiscal_contingency_blocks/migration.sql +64 -0
  50. package/sidecar/README.md +53 -1
  51. package/sidecar/bin/check-platform.php +29 -0
  52. package/sidecar/composer.json +1 -1
  53. package/sidecar/composer.lock +7 -7
  54. package/sidecar/extensions.json +12 -0
  55. package/sidecar/schema/sale-for-document.schema.json +18 -1
  56. package/sidecar/src/Http/Request.php +6 -1
  57. package/sidecar/src/Kernel.php +39 -1
  58. package/sidecar/src/Nfe/DocumentMapper.php +27 -0
  59. package/sidecar/src/Nfe/Input.php +10 -0
  60. package/sidecar/src/Nfe/NfeModule.php +1 -0
  61. package/sidecar/src/Nfe/NfeService.php +120 -0
  62. package/sidecar/src/Nfe/SefazReply.php +21 -0
  63. package/sidecar/src/Platform.php +84 -0
  64. package/src/danfe/render.ts +16 -5
  65. package/src/documents/contingency-gaps.ts +88 -0
  66. package/src/documents/contingency-pass.ts +157 -0
  67. package/src/documents/contingency-xml.ts +136 -0
  68. package/src/documents/contingency.ts +257 -0
  69. package/src/documents/errors.ts +8 -1
  70. package/src/documents/helpers.ts +5 -0
  71. package/src/documents/index.ts +25 -2
  72. package/src/documents/machine-steps.ts +12 -2
  73. package/src/documents/machine.ts +7 -0
  74. package/src/documents/memory-blocks.ts +118 -0
  75. package/src/documents/memory.ts +6 -2
  76. package/src/documents/payment-link.ts +156 -0
  77. package/src/documents/ports.ts +163 -13
  78. package/src/documents/service.ts +14 -0
  79. package/src/documents/sql-blocks.ts +202 -0
  80. package/src/documents/sql-store.ts +4 -3
  81. package/src/documents/types.ts +2 -1
  82. package/src/http.ts +1 -0
  83. package/src/issuer/port.ts +24 -1
  84. package/src/issuer/sidecar.ts +37 -3
  85. package/src/manifest/index.ts +6 -4
  86. package/src/sale/index.ts +1 -0
  87. package/src/sale/types.ts +30 -0
  88. package/src/sidecar/index.ts +2 -0
  89. package/src/sidecar/platform.ts +55 -0
  90. package/src/sidecar/types.ts +38 -0
  91. package/dist/chunk-2ISYBTCE.js.map +0 -1
  92. package/dist/chunk-F2PGQVWL.js.map +0 -1
  93. package/dist/chunk-JVQKJNOC.js.map +0 -1
  94. package/dist/chunk-MGTROA7K.js.map +0 -1
  95. /package/dist/{chunk-EDEGIADD.js.map → chunk-2JVTHJAU.js.map} +0 -0
  96. /package/dist/{chunk-OSYB7CVT.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,9 @@
1
+ -- @domains: fiscal
2
+ -- @12-apps/fiscal (FUT-2239): a document's events may record the event 110300
3
+ -- "Vinculação Pagamento" (NT 2026.006 v1.00), kind LINK_PAYMENT. The check only
4
+ -- widens: every row the previous release writes still passes it.
5
+
6
+ ALTER TABLE "fiscal_document_events" DROP CONSTRAINT "fiscal_document_events_kind_check";
7
+ ALTER TABLE "fiscal_document_events" ADD CONSTRAINT "fiscal_document_events_kind_check"
8
+ CHECK ("kind" IN ('SUBMIT', 'AUTHORIZE', 'DENY', 'REJECT', 'RETRY', 'SIGN_OFFLINE', 'REPLACE', 'CANCEL', 'LOOKUP', 'INUTILIZE',
9
+ 'DEFER', 'RESIGN', 'RELEASE', 'WARN', 'LINK_PAYMENT'));
@@ -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
@@ -29,6 +29,7 @@ SEFAZ carries `environment` (`homologacao` | `producao`) and `certificate`
29
29
  | `POST /<model>/transmit` | `{ environment, certificate, signedXml }` | as `/issue` |
30
30
  | `POST /<model>/cancel` | `{ environment, certificate, accessKey, protocol, reason }` | `CANCELLED`: the event's `protocol`, `registeredAt`, `eventXml` (each `null` when a retried cancel is settled by a lookup that does not carry them) |
31
31
  | `POST /nfce/cancel-substitution` | the cancel's body plus `substituteAccessKey`: the NFC-e "cancelamento por substituição" (event 110112), for an online NFC-e found authorised after its sale was issued again in contingency | as `/cancel` |
32
+ | `POST /<model>/link-payment` | `{ environment, certificate, accessKey, protocol, sequence, payments: [one { transactionId, meansCode, pspCnpjBase, receiverCnpj }] }`: the event 110300 "Vinculação Pagamento" (NT 2026.006) at `nSeqEvento` = `sequence` | `REGISTERED`: `protocol`, `registeredAt`, `eventXml`, `transaction` (the `gPgto` SEFAZ holds at that sequence). On 573 the key is looked up and the event already there is answered, which may carry another transaction; a 573 the lookup does not show is `RETRYABLE` |
32
33
  | `POST /<model>/lookup` | `{ environment, certificate, accessKey }` | `AUTHORIZED`, `CANCELLED`, `DENIED` or `NOT_FOUND`, with the authorisation `protocol` |
33
34
  | `POST /inutilize` | `{ environment, certificate, model, uf, cnpj, year, series, from, to, reason }` | `INUTILIZED`: `protocol`, `registeredAt`, `inutilizationXml` (`protocol` and the XML `null` on a retry SEFAZ answers 563) |
34
35
  | `GET /health` | | `{ status: "ok", libraries, nfeSchemas, sefazTlsVerify }` |
@@ -96,12 +97,63 @@ with the error: the key is spoken for, and an NFC-e can be signed offline.
96
97
  - The request log is one JSON line per call on stderr: time, method, path,
97
98
  status, duration, error class and SEFAZ code. Nothing read from the body is
98
99
  ever in it, and stack traces carry no arguments
99
- (`zend.exception_ignore_args`).
100
+ (`zend.exception_ignore_args`; in the image from `docker/php.ini`, on a
101
+ bundled PHP from the launch flags below — and the launch token is a
102
+ `#[\SensitiveParameter]` besides).
103
+
104
+ ## Running without Docker (a bundled PHP)
105
+
106
+ A host that cannot run the image — a desktop register that must issue
107
+ offline (FUT-4717) — runs the service with a PHP of its own, bound to the
108
+ loopback only, with a token minted at each launch:
109
+
110
+ ```sh
111
+ FLAGS="-d display_errors=0 -d log_errors=1 -d zend.exception_ignore_args=1 \
112
+ -d zend.exception_string_param_max_len=0 -d file_uploads=0"
113
+ php $FLAGS sidecar/bin/check-platform.php # exit 1, naming what this PHP or launch lacks
114
+ FISCAL_SIDECAR_TOKEN=<random, 32+ chars> \
115
+ php $FLAGS -S 127.0.0.1:<port> -t sidecar/public sidecar/public/index.php
116
+ ```
117
+
118
+ - **Always launch with those flags** (`SIDECAR_PHP_LAUNCH_FLAGS` in
119
+ `@12-apps/fiscal/sidecar`, `ini` in `extensions.json`). They are what the
120
+ image's `docker/php.ini` guarantees, and a bundled PHP has none of them on
121
+ its own: without them an error or a deprecation is printed into the response
122
+ ahead of the JSON (the issuer reads that call as unanswered, its outcome
123
+ unknown), and an escaping exception prints its trace WITH arguments.
124
+ `-d` flags rather than `-c docker/php.ini`, whose `error_log = /dev/stderr`
125
+ a Windows desktop does not have. `bin/check-platform.php` fails a launch
126
+ without them (`zend.exception_ignore_args` off, say), and the PHPUnit
127
+ suite starts the service with exactly these flags.
128
+
129
+ - **Bind `127.0.0.1`, never `0.0.0.0`.** Binding is the launcher's: the
130
+ service cannot tell a loopback caller from another. The token is what keeps
131
+ another process of the same machine out; the launcher passes it in the
132
+ environment, never on the command line (a process listing prints argv).
133
+ - **The PHP:** 8.3, with exactly the extensions `extensions.json` lists
134
+ (`@12-apps/fiscal/sidecar/extensions.json`; `SIDECAR_PHP_EXTENSIONS` in
135
+ `@12-apps/fiscal/sidecar`): `curl` (the SEFAZ transport), `dom`, `filter`
136
+ (json-schema), `json`, `libxml`, `mbstring` (sped-common), `openssl`,
137
+ `reflection` (php-enum), `simplexml`, `soap` and `zlib`, plus the
138
+ command-line SAPI with its built-in server. A PHPUnit test keeps the list
139
+ equal to every `ext-*` of `composer.json` and the locked libraries, so a
140
+ library bump that needs a new extension fails here, and
141
+ `bin/check-platform.php` fails the host's build that bundles a PHP without
142
+ it.
143
+ - **The libraries:** the tarball ships `composer.json` and `composer.lock`,
144
+ not `vendor/`. A host build runs
145
+ `composer install --no-dev --classmap-authoritative --ignore-platform-req=ext-soap`
146
+ in a copy of `sidecar/` (the Dockerfile's own command) and bundles the
147
+ result with `public/`, `src/` and `schema/`.
148
+ - The trust store and the OpenSSL legacy provider are the image's
149
+ (`docker/`): outside it, point `FISCAL_SEFAZ_CA_BUNDLE` at the system bundle
150
+ plus `docker/icp-brasil.pem`, and `OPENSSL_CONF` at `docker/openssl.cnf`.
100
151
 
101
152
  ## Configuration
102
153
 
103
154
  | variable | default | |
104
155
  |---|---|---|
156
+ | `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. |
105
157
  | `FISCAL_SEFAZ_TIMEOUT_SECONDS` | `30` | connect timeout, TLS handshake included; the whole request gets 20 s more |
106
158
  | `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. |
107
159
  | `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. |
@@ -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);
@@ -10,7 +10,7 @@
10
10
  "ext-json": "*",
11
11
  "ext-libxml": "*",
12
12
  "ext-openssl": "*",
13
- "nfephp-org/sped-nfe": "5.2.9"
13
+ "nfephp-org/sped-nfe": "5.2.11"
14
14
  },
15
15
  "require-dev": {
16
16
  "phpunit/phpunit": "^11.5"
@@ -4,7 +4,7 @@
4
4
  "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5
5
  "This file is @generated automatically"
6
6
  ],
7
- "content-hash": "235b7b4c51e141ac548ff87191f7615c",
7
+ "content-hash": "027ed9316c06b9379e46519353632da5",
8
8
  "packages": [
9
9
  {
10
10
  "name": "justinrainbow/json-schema",
@@ -306,16 +306,16 @@
306
306
  },
307
307
  {
308
308
  "name": "nfephp-org/sped-nfe",
309
- "version": "v5.2.9",
309
+ "version": "v5.2.11",
310
310
  "source": {
311
311
  "type": "git",
312
312
  "url": "https://github.com/nfephp-org/sped-nfe.git",
313
- "reference": "346c14d5b7e59ab9aab92e7a77c499a19d462fba"
313
+ "reference": "4596b89e457d27ad2c114dda2b2ed04043f6327c"
314
314
  },
315
315
  "dist": {
316
316
  "type": "zip",
317
- "url": "https://api.github.com/repos/nfephp-org/sped-nfe/zipball/346c14d5b7e59ab9aab92e7a77c499a19d462fba",
318
- "reference": "346c14d5b7e59ab9aab92e7a77c499a19d462fba",
317
+ "url": "https://api.github.com/repos/nfephp-org/sped-nfe/zipball/4596b89e457d27ad2c114dda2b2ed04043f6327c",
318
+ "reference": "4596b89e457d27ad2c114dda2b2ed04043f6327c",
319
319
  "shasum": ""
320
320
  },
321
321
  "require": {
@@ -382,9 +382,9 @@
382
382
  ],
383
383
  "support": {
384
384
  "issues": "https://github.com/nfephp-org/sped-nfe/issues",
385
- "source": "https://github.com/nfephp-org/sped-nfe/tree/v5.2.9"
385
+ "source": "https://github.com/nfephp-org/sped-nfe/tree/v5.2.11"
386
386
  },
387
- "time": "2026-10-02T12:40:30+00:00"
387
+ "time": "2026-11-13T20:31:48+00:00"
388
388
  },
389
389
  {
390
390
  "name": "psr/log",
@@ -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
+ }
@@ -415,7 +415,24 @@
415
415
  }
416
416
  ]
417
417
  },
418
- "description": { "oneOf": [{ "type": "null" }, { "type": "string", "minLength": 2, "maxLength": 60 }] }
418
+ "description": { "oneOf": [{ "type": "null" }, { "type": "string", "minLength": 2, "maxLength": 60 }] },
419
+ "linkedTransaction": {
420
+ "description": "gPgtoVinc (NT 2026.006 v1.00): the payment transaction started before the document, linked by its id. Absent or null: no link.",
421
+ "oneOf": [
422
+ { "type": "null" },
423
+ {
424
+ "type": "object",
425
+ "additionalProperties": false,
426
+ "required": ["transactionId", "meansCode", "pspCnpjBase", "receiverCnpj"],
427
+ "properties": {
428
+ "transactionId": { "type": "string", "pattern": "^[\\x21-\\x7E]{2,35}$" },
429
+ "meansCode": { "enum": ["15", "17", "18", "20", "23", "24"] },
430
+ "pspCnpjBase": { "type": "string", "pattern": "^[A-Z0-9]{8}$" },
431
+ "receiverCnpj": { "$ref": "#/definitions/cnpj" }
432
+ }
433
+ }
434
+ ]
435
+ }
419
436
  }
420
437
  }
421
438
  }
@@ -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'])
@@ -379,6 +379,7 @@ final class DocumentMapper
379
379
  'tpIntegra' => $card === null ? null : ($card['integrated'] ? 1 : 2),
380
380
  ]);
381
381
  }
382
+ $this->paymentLinks($make, $d['payments']);
382
383
  if ($d['intermediary'] !== null) {
383
384
  $make->tagIntermed((object) [
384
385
  'CNPJ' => $d['intermediary']['cnpj'],
@@ -400,6 +401,32 @@ final class DocumentMapper
400
401
  }
401
402
  }
402
403
 
404
+ /**
405
+ * `gPgtoVinc` (NT 2026.006 v1.00, YC01): every payment whose transaction was
406
+ * started before the document, linked by its id. `nPag` is the payment's
407
+ * position among the document's payments. The caller decides whether the
408
+ * environment accepts the group (it is optional in the layout, and the
409
+ * fisco's own production activation is announced for 2027).
410
+ *
411
+ * @param list<array<string, mixed>> $payments
412
+ */
413
+ private function paymentLinks(Make $make, array $payments): void
414
+ {
415
+ foreach (array_values($payments) as $index => $payment) {
416
+ $link = $payment['linkedTransaction'] ?? null;
417
+ if ($link === null) {
418
+ continue;
419
+ }
420
+ $make->tagPgtoVinc((object) [
421
+ 'nPag' => $index + 1,
422
+ 'idTransacao' => $link['transactionId'],
423
+ 'tpMeioPgto' => $link['meansCode'],
424
+ 'CNPJReceb' => $link['receiverCnpj'],
425
+ 'CNPJBasePSP' => $link['pspCnpjBase'],
426
+ ]);
427
+ }
428
+ }
429
+
403
430
  private static function reais(int $cents): string
404
431
  {
405
432
  return number_format($cents / 100, 2, '.', '');
@@ -105,6 +105,16 @@ final class Input
105
105
  return $value;
106
106
  }
107
107
 
108
+ /** @return list<mixed> */
109
+ public function list(string $field): array
110
+ {
111
+ $value = $this->body[$field] ?? null;
112
+ if (!is_array($value) || !array_is_list($value)) {
113
+ throw ServiceError::invalid("$field must be a list.");
114
+ }
115
+ return $value;
116
+ }
117
+
108
118
  public function text(string $field, int $min, int $max): string
109
119
  {
110
120
  $value = $this->body[$field] ?? null;
@@ -33,6 +33,7 @@ final class NfeModule implements Module
33
33
  $router->add('POST', "$prefix/transmit", fn (Request $r): Response => $this->service()->transmit($model, self::in($r)));
34
34
  $router->add('POST', "$prefix/cancel", fn (Request $r): Response => $this->service()->cancel($model, self::in($r)));
35
35
  $router->add('POST', "$prefix/lookup", fn (Request $r): Response => $this->service()->lookup($model, self::in($r)));
36
+ $router->add('POST', "$prefix/link-payment", fn (Request $r): Response => $this->service()->linkPayment($model, self::in($r)));
36
37
  }
37
38
  $router->add('POST', '/nfce/cancel-substitution', fn (Request $r): Response => $this->service()->cancelBySubstitution(self::in($r)));
38
39
  $router->add('POST', '/nfce/sign-contingency', fn (Request $r): Response => $this->service()->signContingency(self::in($r)));
@@ -116,6 +116,126 @@ final class NfeService
116
116
  );
117
117
  }
118
118
 
119
+ /**
120
+ * `POST /<model>/link-payment`: NT 2026.006 v1.00's event 110300
121
+ * "Vinculação Pagamento", one payment transaction linked to an authorised
122
+ * document after the fact. One transaction per event (the schema's single
123
+ * `gPgto`), numbered by the caller's `sequence` (`nSeqEvento`, 1–20).
124
+ *
125
+ * 573 "Duplicidade de Evento" means SEFAZ already holds an event 110300 at
126
+ * that `sequence`: a retry of one whose recording was lost, or another
127
+ * transaction's. The key is looked up and the registered event answered with
128
+ * its own `procEventoNFe` and the `transaction` it carries, which the caller
129
+ * compares with the one it sent. A 573 the lookup cannot show is RETRYABLE.
130
+ */
131
+ public function linkPayment(Model $model, Input $in): Response
132
+ {
133
+ $environment = $in->environment();
134
+ $key = self::keyOf($model, $in);
135
+ $protocol = $in->pattern('protocol', '/^[0-9]{15}$/', 'the 15-digit authorisation protocol');
136
+ $sequence = $in->digits('sequence', 1, 20);
137
+ $transaction = self::paymentOf($in);
138
+ $tagAdic = '<cOrgaoAutor>' . substr($key, 0, 2) . '</cOrgaoAutor><tpAutor>1</tpAutor>'
139
+ . '<verAplic>' . DocumentMapper::PROCESS_VERSION . '</verAplic>'
140
+ . "<nProt>$protocol</nProt>" . self::paymentGroup($transaction);
141
+ $tools = $this->toolsForKey($in, $model, $environment, $key);
142
+ $reply = $this->settled(
143
+ fn (): string => $tools->sefazEvento(UFList::getUFByCode((int) substr($key, 0, 2)), $key, Tools::EVT_VINCULACAO_PAGAMENTO, $sequence, $tagAdic),
144
+ false,
145
+ );
146
+ $status = $reply->status() === '128' ? (string) $reply->value('cStat', 'infEvento') : $reply->status();
147
+ if ($status === '573') {
148
+ return $this->linkSettledByLookup($tools, $key, $sequence, $reply);
149
+ }
150
+ if (!in_array($status, self::EVENT_REGISTERED, true)) {
151
+ throw Classifier::fromStatus($status, self::reasonOf($reply, 'infEvento'), $reply, false);
152
+ }
153
+ return new Response(200, self::answer($reply, $status, 'infEvento') + [
154
+ 'status' => 'REGISTERED',
155
+ 'accessKey' => $key,
156
+ 'protocol' => (string) $reply->value('nProt', 'infEvento'),
157
+ 'registeredAt' => (string) $reply->value('dhRegEvento', 'infEvento'),
158
+ 'eventXml' => self::protocolled($tools->lastRequest, $reply->raw),
159
+ 'transaction' => $transaction,
160
+ ]);
161
+ }
162
+
163
+ /**
164
+ * A 573 settled by the key's own events: the 110300 SEFAZ holds at
165
+ * `$sequence`, with its `procEventoNFe` and the transaction it carries.
166
+ */
167
+ private function linkSettledByLookup(Tools $tools, string $key, int $sequence, SefazReply $duplicate): Response
168
+ {
169
+ try {
170
+ $lookup = $this->exchange(fn (): string => $tools->sefazConsultaChave($key));
171
+ } catch (TransportFailure $failure) {
172
+ throw self::unsettled($failure, false, false);
173
+ }
174
+ foreach ($lookup->all('procEventoNFe') as $xml) {
175
+ $event = SefazReply::parse($xml);
176
+ if ($event->value('tpEvento') !== (string) Tools::EVT_VINCULACAO_PAGAMENTO || (int) $event->value('nSeqEvento') !== $sequence
177
+ || !in_array((string) $event->value('cStat', 'retEvento'), self::EVENT_REGISTERED, true)) {
178
+ continue;
179
+ }
180
+ return new Response(200, self::answer($duplicate, '573', 'infEvento') + [
181
+ 'status' => 'REGISTERED',
182
+ 'accessKey' => $key,
183
+ 'protocol' => $event->value('nProt', 'retEvento'),
184
+ 'registeredAt' => $event->value('dhRegEvento', 'retEvento'),
185
+ 'eventXml' => $xml,
186
+ 'transaction' => [
187
+ 'transactionId' => (string) $event->attribute('gPgto', 'idTransacao'),
188
+ 'meansCode' => (string) $event->value('tpMeioPgto', 'gPgto'),
189
+ 'receiverCnpj' => (string) $event->value('CNPJReceb', 'gPgto'),
190
+ 'pspCnpjBase' => (string) $event->value('CNPJBasePSP', 'gPgto'),
191
+ ],
192
+ ]);
193
+ }
194
+ throw new ServiceError(
195
+ ErrorClass::RETRYABLE,
196
+ "SEFAZ calls the event 110300 #$sequence a duplicate, and the key's lookup does not show it yet: send it again.",
197
+ '573',
198
+ [],
199
+ null,
200
+ null,
201
+ $lookup->raw,
202
+ );
203
+ }
204
+
205
+ /**
206
+ * The one transaction the event links (schema `TEventoPgto`). `payments`
207
+ * holds exactly one entry, since the event's schema carries a single `gPgto`.
208
+ *
209
+ * @return array{transactionId: string, meansCode: string, receiverCnpj: string, pspCnpjBase: string}
210
+ */
211
+ private static function paymentOf(Input $in): array
212
+ {
213
+ $payments = $in->list('payments');
214
+ if (count($payments) !== 1 || !is_array($payments[0])) {
215
+ throw ServiceError::invalid('payments must hold exactly one transaction: the event 110300 carries one gPgto.');
216
+ }
217
+ $one = new Input($payments[0]);
218
+ return [
219
+ 'transactionId' => $one->pattern('transactionId', '/^[\x21-\x7E]{2,35}$/', '2 to 35 printable characters'),
220
+ 'meansCode' => $one->pattern('meansCode', '/^(15|17|18|20|23|24)$/', 'an IT 2026.001 tpMeioPgto (15, 17, 18, 20, 23, 24)'),
221
+ 'receiverCnpj' => $one->pattern('receiverCnpj', '/^[A-Z0-9]{12}[0-9]{2}$/', 'a 14-character CNPJ'),
222
+ 'pspCnpjBase' => $one->pattern('pspCnpjBase', '/^[A-Z0-9]{8}$/', 'an 8-character CNPJ base'),
223
+ ];
224
+ }
225
+
226
+ /**
227
+ * The event's `gPgto`: the transaction id is an attribute, then the means,
228
+ * the receiver, the PSP.
229
+ *
230
+ * @param array{transactionId: string, meansCode: string, receiverCnpj: string, pspCnpjBase: string} $transaction
231
+ */
232
+ private static function paymentGroup(array $transaction): string
233
+ {
234
+ $id = htmlspecialchars($transaction['transactionId'], ENT_XML1 | ENT_QUOTES);
235
+ return "<gPgto idTransacao=\"$id\"><tpMeioPgto>{$transaction['meansCode']}</tpMeioPgto>"
236
+ . "<CNPJReceb>{$transaction['receiverCnpj']}</CNPJReceb><CNPJBasePSP>{$transaction['pspCnpjBase']}</CNPJBasePSP></gPgto>";
237
+ }
238
+
119
239
  /** One cancel event, sent and settled: 218/573 and a request with no answer are looked up. */
120
240
  private function sendCancel(Tools $tools, string $key, callable $send): Response
121
241
  {