@12-apps/fiscal 1.5.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.
- package/README.md +46 -4
- package/dist/{chunk-HMTPJWXM.js → chunk-2JVTHJAU.js} +2 -2
- package/dist/{chunk-3E3NBXSW.js → chunk-CEK2GDRY.js} +5 -3
- package/dist/chunk-CEK2GDRY.js.map +1 -0
- package/dist/{chunk-MGTROA7K.js → chunk-OAQSGDZ7.js} +11 -7
- package/dist/chunk-OAQSGDZ7.js.map +1 -0
- package/dist/{chunk-G6QNU4FD.js → chunk-P7CRGZGO.js} +2 -2
- package/dist/{chunk-H33BK623.js → chunk-WRYCYXRA.js} +1 -1
- package/dist/{chunk-H33BK623.js.map → chunk-WRYCYXRA.js.map} +1 -1
- package/dist/{chunk-TJCUO6D6.js → chunk-YHSO3476.js} +6 -5
- package/dist/chunk-YHSO3476.js.map +1 -0
- package/dist/{context-CwZiHLnY.d.ts → context-Cyvfr2YB.d.ts} +155 -19
- package/dist/danfe/index.d.ts +7 -0
- package/dist/danfe/index.js +2 -2
- package/dist/documents/index.d.ts +152 -34
- package/dist/documents/index.js +1103 -305
- package/dist/documents/index.js.map +1 -1
- package/dist/engine/index.d.ts +2 -2
- package/dist/http.d.ts +6 -5
- package/dist/http.js +4 -4
- package/dist/issuer/index.d.ts +10 -3
- package/dist/issuer/index.js +18 -3
- package/dist/issuer/index.js.map +1 -1
- package/dist/jobs.d.ts +5 -5
- package/dist/jobs.js +3 -3
- package/dist/manifest/index.d.ts +6 -4
- package/dist/manifest/index.js.map +1 -1
- package/dist/manifest/server.d.ts +5 -5
- package/dist/manifest/server.js +6 -6
- package/dist/notifications.d.ts +4 -4
- package/dist/notifications.js +2 -2
- package/dist/{service-Cz2O84Xr.d.ts → service-BCK9aXop.d.ts} +64 -5
- package/dist/sidecar/index.d.ts +38 -249
- package/dist/sidecar/index.js +29 -1
- package/dist/sidecar/index.js.map +1 -1
- package/dist/{types-B1b8LIWX.d.ts → types-BLdkww6G.d.ts} +1 -1
- package/dist/{types-DSYwap42.d.ts → types-Sk010Em2.d.ts} +2 -2
- package/dist/types-Z5E14EPw.d.ts +254 -0
- package/package.json +2 -1
- package/prisma/fiscal.prisma +50 -1
- package/prisma/migrations/20261118180000_fiscal_contingency_blocks/migration.sql +64 -0
- package/sidecar/README.md +52 -1
- package/sidecar/bin/check-platform.php +29 -0
- package/sidecar/extensions.json +12 -0
- package/sidecar/src/Http/Request.php +6 -1
- package/sidecar/src/Kernel.php +39 -1
- package/sidecar/src/Platform.php +84 -0
- package/src/danfe/render.ts +16 -5
- package/src/documents/contingency-gaps.ts +88 -0
- package/src/documents/contingency-pass.ts +157 -0
- package/src/documents/contingency-xml.ts +136 -0
- package/src/documents/contingency.ts +257 -0
- package/src/documents/errors.ts +8 -1
- package/src/documents/helpers.ts +3 -0
- package/src/documents/index.ts +23 -1
- package/src/documents/memory-blocks.ts +118 -0
- package/src/documents/memory.ts +6 -2
- package/src/documents/ports.ts +163 -13
- package/src/documents/service.ts +10 -0
- package/src/documents/sql-blocks.ts +202 -0
- package/src/documents/sql-store.ts +4 -3
- package/src/http.ts +1 -0
- package/src/issuer/sidecar.ts +27 -3
- package/src/manifest/index.ts +6 -4
- package/src/sidecar/index.ts +2 -0
- package/src/sidecar/platform.ts +55 -0
- package/dist/chunk-3E3NBXSW.js.map +0 -1
- package/dist/chunk-MGTROA7K.js.map +0 -1
- package/dist/chunk-TJCUO6D6.js.map +0 -1
- /package/dist/{chunk-HMTPJWXM.js.map → chunk-2JVTHJAU.js.map} +0 -0
- /package/dist/{chunk-G6QNU4FD.js.map → chunk-P7CRGZGO.js.map} +0 -0
package/prisma/fiscal.prisma
CHANGED
|
@@ -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
|
|
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
|
@@ -97,12 +97,63 @@ with the error: the key is spoken for, and an NFC-e can be signed offline.
|
|
|
97
97
|
- The request log is one JSON line per call on stderr: time, method, path,
|
|
98
98
|
status, duration, error class and SEFAZ code. Nothing read from the body is
|
|
99
99
|
ever in it, and stack traces carry no arguments
|
|
100
|
-
(`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`.
|
|
101
151
|
|
|
102
152
|
## Configuration
|
|
103
153
|
|
|
104
154
|
| variable | default | |
|
|
105
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. |
|
|
106
157
|
| `FISCAL_SEFAZ_TIMEOUT_SECONDS` | `30` | connect timeout, TLS handshake included; the whole request gets 20 s more |
|
|
107
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. |
|
|
108
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);
|
|
@@ -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
|
+
}
|
|
@@ -7,13 +7,17 @@ namespace Fiscal\Sidecar\Http;
|
|
|
7
7
|
use Fiscal\Sidecar\ServiceError;
|
|
8
8
|
use JsonException;
|
|
9
9
|
|
|
10
|
-
/**
|
|
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
|
|
package/sidecar/src/Kernel.php
CHANGED
|
@@ -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'])
|
|
@@ -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
|
+
}
|
package/src/danfe/render.ts
CHANGED
|
@@ -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:
|
|
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 (
|
|
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);
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which numbers of a contingency block are KNOWN unused and which are
|
|
3
|
+
* UNKNOWN — pure, from the block's state (FUT-4717). A holder signs its block
|
|
4
|
+
* in order and hands its notes in, in order, so:
|
|
5
|
+
*
|
|
6
|
+
* - below the highest number it handed in, a number with no document was
|
|
7
|
+
* never signed: KNOWN;
|
|
8
|
+
* - a CLOSED block's numbers above what the holder said it used are KNOWN;
|
|
9
|
+
* between the highest handed in and `usedUpTo` they were signed and are
|
|
10
|
+
* still to come: UNKNOWN until they arrive;
|
|
11
|
+
* - an ABANDONED block (its holder is gone) above the highest handed in may
|
|
12
|
+
* be on paper a buyer holds: UNKNOWN, flagged, never voided;
|
|
13
|
+
* - an OPEN block above the highest handed in is still in use: neither.
|
|
14
|
+
*
|
|
15
|
+
* A range already voided is neither.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { ContingencyBlockState, ContingencyGap, NumberRange } from "./ports";
|
|
19
|
+
|
|
20
|
+
/** Consecutive numbers as ranges, ascending. */
|
|
21
|
+
function rangesOf(numbers: readonly number[]): NumberRange[] {
|
|
22
|
+
const sorted = [...new Set(numbers)].sort((a, b) => a - b);
|
|
23
|
+
const ranges: NumberRange[] = [];
|
|
24
|
+
for (const number of sorted) {
|
|
25
|
+
const last = ranges[ranges.length - 1];
|
|
26
|
+
if (last !== undefined && last.to === number - 1) ranges[ranges.length - 1] = { from: last.from, to: number };
|
|
27
|
+
else ranges.push({ from: number, to: number });
|
|
28
|
+
}
|
|
29
|
+
return ranges;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function between(from: number, to: number, keep: (n: number) => boolean): number[] {
|
|
33
|
+
const out: number[] = [];
|
|
34
|
+
for (let n = from; n <= to; n += 1) if (keep(n)) out.push(n);
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The highest number of the block a document was recorded on (`from - 1`: none). */
|
|
39
|
+
function highestRecorded(block: ContingencyBlockState): number {
|
|
40
|
+
const inside = block.documented.filter((n) => n >= block.from && n <= block.to);
|
|
41
|
+
return inside.length === 0 ? block.from - 1 : Math.max(...inside);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface BlockAccount {
|
|
45
|
+
readonly known: NumberRange[];
|
|
46
|
+
readonly unknown: NumberRange[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The block's known and unknown ranges (see the module doc). */
|
|
50
|
+
export function accountFor(block: ContingencyBlockState): BlockAccount {
|
|
51
|
+
const documented = new Set(block.documented);
|
|
52
|
+
const voided = (n: number) => block.voided.some((range) => n >= range.from && n <= range.to);
|
|
53
|
+
const open = (n: number) => !documented.has(n) && !voided(n);
|
|
54
|
+
const highest = highestRecorded(block);
|
|
55
|
+
const known = between(block.from, highest, open);
|
|
56
|
+
let unknown: number[] = [];
|
|
57
|
+
if (block.fate === "CLOSED") {
|
|
58
|
+
const used = Math.max(highest, block.usedUpTo ?? block.from - 1);
|
|
59
|
+
known.push(...between(used + 1, block.to, open));
|
|
60
|
+
unknown = between(highest + 1, used, open);
|
|
61
|
+
} else if (block.fate === "ABANDONED") {
|
|
62
|
+
unknown = between(highest + 1, block.to, open);
|
|
63
|
+
}
|
|
64
|
+
return { known: rangesOf(known), unknown: rangesOf(unknown) };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A range of a block, as the gap the service reports. */
|
|
68
|
+
export function gapOf(block: ContingencyBlockState, range: NumberRange): ContingencyGap {
|
|
69
|
+
return {
|
|
70
|
+
blockId: block.id,
|
|
71
|
+
ownerId: block.ownerId,
|
|
72
|
+
issuingPointId: block.issuingPointId,
|
|
73
|
+
issuerCnpj: block.issuerCnpj,
|
|
74
|
+
environment: block.environment,
|
|
75
|
+
series: block.series,
|
|
76
|
+
holder: block.holder,
|
|
77
|
+
reservedAt: block.reservedAt,
|
|
78
|
+
from: range.from,
|
|
79
|
+
to: range.to,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Whether every number is a document or voided, with nothing left to come: the block needs no more work. */
|
|
84
|
+
export function isSettled(block: ContingencyBlockState): boolean {
|
|
85
|
+
if (block.fate === "OPEN") return false;
|
|
86
|
+
const { known, unknown } = accountFor(block);
|
|
87
|
+
return known.length === 0 && unknown.length === 0;
|
|
88
|
+
}
|