node-red-contrib-afya-ksef 1.4.4
Node-RED node for KSeF, the Polish National e-Invoice System (API 2.0): this month's sales (revenue) and purchase (cost) invoices with KSeF numbers, new invoices as ready-made SMS text, and a password-protected journal page with bank accounts to copy, inv
node-red-contrib-afya-ksef
Node-RED node for KSeF (Krajowy System e-Faktur – the Polish National e-Invoice System, API 2.0): it reads this month's invoices – sales = revenue and purchases = costs – tells you which invoices are new, with their KSeF numbers, and gives a ready SMS text. Its web page shows both journals with totals and a “Do przelewu” list with the bank accounts of your suppliers – every number has a copy button – and makes a transfer file (XML / CSV / Excel) from the ticked invoices. Log in with a KSeF token or a KSeF certificate kept only in an encrypted vault; the invoices on disk are encrypted too. No dependencies.
English · Polski · part of dobry.doctor

English
[inject every 1 h] → [ksef invoices] ─┬─► [switch: payload.tekstPrzychody not empty] → [SMS: new revenue]
└─► [switch: payload.tekstKoszty not empty] → [SMS: new cost]
Example SMS (Polish, as it goes to Polish users):
Przychód 1 234,50 zł netto – Firma Pacjenta S.A., FV FV/12/11/2026, KSeF 1111111111-20261103-0100000000AA-01
Koszt 5 068,22 zł – Hurtownia Medyczna Sp. z o.o., termin 2026-11-16, FV HM/77/2026, KSeF 5555555555-20261102-0200000000CC-03
Flow library: library/flow.json – afya-week-calendar every 2 h (8–20) → KSeF → revenue and cost SMS → HTTP SMS gateway (description).
Install
Requires Node.js ≥ 18.17 and Node-RED ≥ 3.
cd ~/.node-red
npm install node-red-contrib-afya-ksef
# or straight from GitHub:
npm install github:mchuc/node-red-contrib-afya-ksef
Restart Node-RED. The node ksef invoices appears in the AFYA palette group.
Log in to KSeF
| Method | What you need |
|---|---|
| KSeF token | Generate it in Aplikacja Podatnika KSeF → Tokeny. Reading invoices needs only the permission przeglądanie faktur (InvoiceRead). The node encrypts `token |
| KSeF certificate | A certificate of type Uwierzytelnianie from Aplikacja Podatnika KSeF: the .crt file, the .key file and the password you set for the key. Upload both files in the edit dialog. The node signs the KSeF login request (AuthTokenRequest, XAdES-BES, RSA or EC) itself. |
Both go only into the vault on the node's web page (see below) – never into the Node-RED settings. The access
token is refreshed with the refresh token, so a full login happens only about once a week.
A .p12 / .pfx file has to be split first:
openssl pkcs12 -in cert.p12 -clcerts -nokeys -out cert.crt and openssl pkcs12 -in cert.p12 -nocerts -out cert.key.
Vault – the only way (all configured on the web page)
The KSeF token or certificate lives only in the vault – there is no other option. Recommended: a KSeF token
with only the przeglądanie faktur permission (InvoiceRead). Such a token cannot issue invoices, and tokens stay
in KSeF after 2026 as well.
- In Aplikacja Podatnika KSeF → Tokeny generate a token with only przeglądanie faktur.
- In the node: enter the company NIP and a page password (or access token). Deploy. Nothing secret is typed into Node-RED.
- Open the page (e.g.
http://<node-red>:1880/afya/ksef), log in, Create the vault: paste the token (or upload.crt+.key), optionally the bank account you pay from (for transfer files), choose a vault password (10+ characters) twice – keep it in a password manager. - Done – the node checks KSeF right away. The vault password is stored nowhere.
Invoices are encrypted too. The vault holds a random data key; the journal, the paid ticks and transfer plans
and the cached invoice XML are stored encrypted with it (AES-256-GCM, file name bound in) – <id>-dziennik.enc,
<id>-zaplacone.enc, <id>-xml/*.xml.enc. While the vault is locked nobody – not even the page – can read them.
Changing the vault password does not re-encrypt them (the data key stays); deleting the vault deletes them.
Upgrading from an older version (token / certificate in the node settings, plain <id>.json): the node no longer
uses those settings. The page offers “token z ustawień węzła” when creating the vault – it is moved into the vault
once and removed from Node-RED (flows_cred.json is rewritten at the next deploy); the plain journal, ticks and
XML files are encrypted and deleted at the first vault opening. The old token lay in plain text and may sit in
backups – best generate a new one and use Wymień token albo certyfikat.
After every restart of Node-RED or the machine the vault is locked: the node does not ask KSeF at all and puts a
text in msg.payload.tekstSejf – once after the restart, or at every check until the password is entered
(setting Vault locked). Send it as SMS (third branch in the example flow). Opening the page asks only for the
vault password; it unlocks the vault, logs you in to the page and runs a KSeF check. A flow deploy does not
lock the vault (it is not a restart); deleting the node does.
🔓 Sejf on the page: the status and Lock now are on top, everything else is folded – open only the section you need: bank account for transfers (add / change – only the last 6 digits are ever shown), change the vault password, replace the token or certificate (e.g. a new token after revoking the old one – same vault password), KSeF certificate with a key generated in the vault, delete the vault (with the encrypted invoices). Each one needs the vault password; after sending, the page opens the same section with the result.
How it works: the vault is ~/.node-red/afya-ksef/<node-id>-sejf.json (mode 0600) with only ciphertext:
key from the password by scrypt (N=2¹⁵, r=8, p=1, 16-byte salt), AES-256-GCM. In plain text there is only
what is inside (token / certificate subject and expiry). The open vault lives in Node-RED memory only.
What it protects and what not. The vault protects data at rest: a stolen disk, backups, flows_cred.json,
a git repository. It does not protect against someone who can use the Node-RED editor – a function node can
read the process memory – so secure the editor (adminAuth) and keep the page behind a password, ideally HTTPS.
Certificate with a key generated in the vault (optional)
If you prefer a certificate: on 🔓 Sejf → Certyfikat KSeF z kluczem z sejfu the node generates an EC P-256
private key in the vault, sends KSeF only the certificate request (PKCS#10 CSR, /certificates/enrollments)
and stores the issued certificate next to the key. The key never leaves the vault – there is no .key file
anyone could copy. KSeF accepts the request only after logging in with a signature (XAdES), not with a token:
- with the certificate already in the vault (and revoke the old one – its
.keyfile may have been copied), or - download the request document (
AuthTokenRequest.xml, valid 10 minutes), sign it with Profil Zaufany on gov.pl or a qualified signature, upload it. The certificate is issued to the person who signed.
With a token in the vault, login stays with the token (recommended); the certificate is kept as a spare unless you choose otherwise.
Configuration
| Field | Description |
|---|---|
| Labels | Language of the edit dialog: system language (Polish for a Polish system, English otherwise), English or Polski. Only the descriptions change. |
| Environment | Production (real invoices), Demo or Test. |
| Company NIP | The company the invoices belong to (login context). Checked against the NIP checksum. |
| Vault | Token / certificate only on the web page (see above). Vault locked: SMS text once after a restart or at every check. Identify by (certificate in the vault): certificate subject (NIP/PESEL) or fingerprint. |
| Amounts | net, gross or both (net, VAT, gross) – in the tables, totals and %kwota%. |
| Month by | issue date – an invoice belongs to the month it was issued in; date received in KSeF – the month the KSeF number was given (for costs, this is the legal date of receipt). |
| Also check the previous month | On (default): invoices dated last month that arrive late are caught too. |
| Send info about a new sales / purchase invoice | Texts in payload.tekstPrzychody and payload.tekstKoszty, each with its own template. |
| Without Polish letters | ą→a, ł→l and typographic dashes/quotes → ASCII, so one SMS holds 160 instead of 70 characters. |
| Append the month totals | Adds | 11.2026: przychody …, koszty …, wynik … to every line. |
| Transfers | Reads the bank account, due date, payment form, split payment (MPP) and “paid” flag from each purchase invoice XML (once per invoice). Transfer amount: gross (or do zapłaty from the invoice) or net. Copied amount: 1518.44 (dot) or 1518,44 (comma). |
| Invoice page | Always on – the vault is created and opened there. Page path, title, password and/or access token (see below). |
| Remember the view | Where the page keeps its layout (tiles / list, sorting, paid shown or folded, Ukryj zaplanowane): in the browser (default – each device its own) or in the node (the same on every device) – examples below. |
| Variable | Optional: the last msg.payload also in a global or flow context variable. |
Placeholders: %kwota% %netto% %vat% %brutto% %kontrahent% %nip% %numer% %ksef% %data% %typ%
%waluta% %miesiac% %suma% %firma%, and for purchase invoices %platnosc% (account, due date, ⚠ different amount in the notes) %przelew% (transfer amount) %konto% %termin%.
Defaults: Przychód %kwota% – %kontrahent%, FV %numer%, KSeF %ksef% and Koszt %kwota% – %kontrahent%, FV %numer%, %platnosc%, KSeF %ksef%.
KSeF limits
KSeF allows 20 invoice-list queries per hour per company. One check makes 2 queries per month (sales +
purchases) – 4 with the previous month – so inject every hour (never more often than every 15 minutes).
After 429 Too Many Requests the node waits as long as KSeF asks and does not call KSeF in between.
Invoice XML downloads (for the transfer data) have their own limit of 64 per hour; the node downloads at most 12
per check, new invoices first, and every invoice only once.
Invoice page
The node serves http://<node-red>:1880/afya/ksef (under httpNodeRoot). From the top: company name, the month and
the tiles with the operating profit, the status bar, open invoices from earlier months, the two tables, and at the
bottom the transfer cards.
- company and NIP, the month and tiles: revenue (received / waiting for), costs (paid / to pay) and operating profit – current (received − paid) and expected (all revenue − all costs), net, gross or both,
- a big status bar: when KSeF was checked and whether the login worked (green), the error (red) or a warning after 3 hours without a check – so you know the system works,
- two tables like a journal – Przychody (sales) and Koszty (purchases): issue date, due date, invoice number, counterparty with NIP (purchases: also the bank account with kopiuj), KSeF number with a kopiuj (copy) button, amounts and a total row; sort by issue date or by due date,
- a round tick in every row – costs: paid, revenue: received; click it on the page, it is saved in Node-RED (separate file, survives restarts), click again to undo; invoices marked as paid in their XML are ticked for good. Paid costs and received revenue fold under a Zapłacone / Otrzymane bar in the tables and under a Pokaż zapłacone button in the transfer list – only what is still open stays in view; the Data wyst. and Termin headers sort. A paid card stays fully readable – green border and a ✓ zapłacona badge,
- planned transfers: every unpaid cost card has Zaplanuj przelew na [date] – the card gets a blue border and
a 🗓 przelew 2026-12-20 badge (orange · po terminie when the date is after the due date); the day after that date the
invoice counts as paid (✓ zapłacona · przelew 2026-12-20). Zmień / Usuń plan in the card; the plan is saved with
the ticks and is in
koszty[].zaplanowana, - open invoices from earlier months carry over: unreceived revenue and unpaid costs stay at the very top (Nieotrzymane / Niezapłacone z poprzednich miesięcy) until you tick them; unpaid costs also stay among the transfer cards (with a z listopada 2026 badge) and the tiles show them in a separate z poprzednich miesięcy line,
- settlement on the invoice (
Rozliczenie– e.g. an instalment for a phone, housing-community charges): the amount to pay is the invoice's DoZaplaty, not its gross value – the transfer card says Do zapłaty with "faktura … + obciążenia … = …", the table shows a do zapłaty badge, the SMS says it. In the tiles paid / to pay are transfers (with the settlement), while costs and operating profit stay at the invoice value – a lease invoice for 90,08 zł interest with a 3 221,52 zł capital instalment is a 90,08 zł cost and a 3 311,60 zł transfer; an overpayment (DoRozliczenia) means nothing to pay, - PDF and XML for every invoice: PDF opens a readable invoice (parties, items with net, VAT and gross, VAT summary with gross per rate, settlement, payment, notes, attachment, KSeF verification link) with Save PDF / print; amounts in payment notes are highlighted. XML shows / downloads the KSeF file. Downloaded XML is cached for 30 days,
- ⚠ different amount in the notes – when a note on the invoice (additional description, payment description, attachment) mentions an amount to pay that is not the invoice amount, the row and the transfer card warn you,
- Do przelewu under the costs – big cards, 2 per row: issue date, a big due date with a badge (red PO TERMINIE · N days, pay today, tomorrow, in N days, paid), then amount, title, KSeF number and account. Ticking paid happens in place – the card gets a green border, nothing reloads or jumps; each card lists the recipient, bank account, amount, title (invoice number), each with a kopiuj button, and a big 📋 Kopiuj tytuł + nr KSeF button; due date (overdue in red), split payment (MPP) with the VAT amount, factor account, payment link; a wrong account checksum is flagged,
- costs as tiles or a list – ▦ Kafelki (the transfer cards, default) or ☰ Lista (the table) at the Koszty
heading; Ukryj zaplanowane hides invoices that already have a planned transfer. Every row and card has clear buttons:
Oznacz jako zapłaconą / Odznacz jako zapłaconą and + Do paczki przelewów. The page remembers your view –
tiles / list, the sorting, paid (received) invoices shown or folded and Ukryj zaplanowane – and opens the same way
next time; where it keeps it is set in the node (Remember the view):
- in the browser (default; cookies for a year, per node) – every device its own. Example: on the phone you keep the tiles to tick off transfers, on the computer the list sorted by due date with paid invoices folded; the wall tablet with the token link keeps whatever was left on it,
- in the node (file
~/.node-red/afya-ksef/<node-id>-widok.json, only the layout – no invoice data) – one view for everyone. Example: you set list, by due date, paid folded, Ukryj zaplanowane once on the computer – the phone, the accountant's browser and the kiosk tablet (cookies cleared every night) open exactly the same; a change on any device changes it for all (the last one wins),
- transfer file – add invoices with + Do paczki przelewów (or 🏦 Zaznacz wszystkie możliwe do paczki przelewów (N) at
a section heading – it selects every invoice of that section that can be paid with the file); the transfers bar appears at the bottom of the screen only once at least one
invoice is selected (an invoice with a planned transfer cannot be added – remove its plan first); it shows two totals:
Do zapłaty łącznie (what leaves the account – with the settlements on the invoices) and Wartość FV
netto / brutto (switch; the default follows Amounts, the browser remembers the choice) – with the difference
when they are not equal; then
🏦 Przelewy – wygeneruj plik: a calendar suggests the earliest due date of the selected invoices (weekend → Friday,
never before today) – pick another day if you like, all transfers get that date. Format (the default is set in the
node, Transfer file): Nest Bank XML or CSV (UTF-8), mBank Elixir-0 (UTF-8, at most 50 transfers / 10 KB),
ING Elixir-0 / PLI (Windows-1250), VeloBank XML (ISO-8859-2), PKO BP ISO 20022 pain.001.001.09 (XML,
without split payment) – split payment elsewhere as
/VAT/…/IDC/…/INV/…/TXT/…(Elixir-0: code 53) – or Excel (XLSX) to review / for the accountant. The formats were prepared only from publicly available descriptions – check that your bank accepts the file; bank names only identify the file format and belong to their owners. PLN invoices with a Polish account (NRB checksum) only. The account you pay from comes from the vault (shown as the last 6 digits); without it the button is inactive. After the download the page asks whether to mark the invoices as planned for payment on that day (Tak / Nie teraz) – the file alone changes nothing. Long invoice notes in the cards show 2 lines and … więcej. The file is a draft – whoever approves the transfers in the bank must check every one of them and is responsible for them (see LICENSE), - clicking an amount in the tables copies it as
1518.44(or1518,44), - arrows switch between the stored months (up to 13), badges for new invoices (last 48 h) and corrections,
- works on a phone and in dark mode, refreshes itself every 15 minutes.
Copying works over plain http:// in the local network too (where the browser blocks the clipboard API). At the bottom: the dobry.doctor logo and link and the author's ORCID iD.
Access – exactly like the Librus page: a password (login form, HttpOnly cookie for 30 days, changing the
password logs everyone out) and/or an access token (…/afya/ksef?token=…, no login – keep the link like a
password). Without either the page stays off; 10 wrong tries in 15 minutes block the address for a while.
Put the page behind HTTPS / VPN when it is reachable from the internet – it shows financial data.
Output (msg.payload)
| Field | Meaning |
|---|---|
ok |
true – read successfully; on error { ok: false, czas, blad, status } |
nowe, nowePrzychody, noweKoszty |
invoices that were not there at the previous check |
tekstPrzychody, tekstKoszty, tekst |
ready SMS texts; empty when nothing is new |
przychody, koszty |
this month's journal: ksef (KSeF number), numer (invoice number), data, otrzymana, kontrahent, nipKontrahenta, netto, vat, brutto, vatPln, waluta, typ, korekta, miesiac; costs also platnosc (konta, termin, forma, zaplacono, mpp, …) |
sumy |
{ przychody: { PLN: { ile, netto, vat, brutto } }, koszty: {…}, wynik: {…} } |
rozliczenie |
per currency ({ netto, vat, brutto }): otrzymano, czekamy, wydano, doWydania – money (transfers, with settlements from the invoices); przychody, koszty, zyskObecny, zyskOczekiwany – invoice values; rozliczenia ({ przychody, koszty }) – what settlements add to the transfers |
miesiace |
the checked months with their journals and totals |
firma, nip, miesiac, srodowisko, kwoty, typDaty |
context of the check |
pierwszyOdczyt |
true on the very first check – invoices are only remembered |
zapytan, pobranoFaktur |
KSeF queries made, invoice XML files downloaded |
koszty[].zaplacona, oznaczonaZaplacona |
paid (from the XML, ticked on the page or the day after a planned transfer) and when it was ticked |
koszty[].zaplanowana |
date of a transfer planned on the page (YYYY-MM-DD) |
koszty[].platnosc.uwagi, kwotyWUwagach |
notes from the invoice and the amounts mentioned in payment notes |
certyfikat |
with certificate login: subject, validity, fingerprint |
sejf, tekstSejf |
otwarty / zamkniety / brak; while locked ok: false, no KSeF query, tekstSejf = SMS text (once or at every check) |
SMS test
Send msg.test = true: when nothing is new, the latest sales and purchase invoice are reported as new.
Tests
npm install
npm test
The tests run against a fake KSeF that checks what KSeF checks: the RSA-OAEP encrypted token, the XAdES
signature (verified with xml-crypto for RSA and by hand for ECDSA), Bearer tokens, the query filters and the
invoice XML.
Credits
Based on the official KSeF API 2.0 documentation (CIRFMF/ksef-docs) and the Ministry's C# client (XAdES signature layout). Unofficial – not affiliated with the Ministry of Finance. Marcin Chuć · MIT · dobry.doctor
Polski
Węzeł Node-RED do KSeF (Krajowy System e-Faktur, API 2.0): czyta faktury bieżącego miesiąca (i poprzedniego) – sprzedaż = przychody, zakupy = koszty – i podaje, które faktury są nowe, z numerami KSeF. Gotowy tekst SMS, a do tego strona z dwiema tabelami jak w dzienniku i listą Do przelewu z kontami dostawców – każdy numer z przyciskiem kopiuj – i plikiem przelewów (XML / CSV / Excel) z zaznaczonych faktur. Logowanie tokenem KSeF albo certyfikatem KSeF trzymanym tylko w zaszyfrowanym sejfie; faktury na dysku też są zaszyfrowane.
Instalacja
cd ~/.node-red
npm install node-red-contrib-afya-ksef
# albo prosto z GitHuba:
npm install github:mchuc/node-red-contrib-afya-ksef
W Dockerze (nodered, katalog /data): docker exec -it nodered sh -c "cd /data && npm install node-red-contrib-afya-ksef"
i restart kontenera. Węzeł ksef invoices jest w grupie AFYA.
Logowanie do KSeF
- Token KSeF – w Aplikacji Podatnika KSeF → Tokeny; do odczytu faktur wystarczy uprawnienie przeglądanie faktur. Tokeny mają działać także po 2026 r.
- Certyfikat KSeF typu Uwierzytelnianie – pliki
.crti.keyz Aplikacji Podatnika i hasło klucza; węzeł sam podpisuje żądanie logowania (XAdES).
Token i certyfikat trafiają tylko do sejfu na stronie WWW węzła (niżej) – nigdy do ustawień Node-RED.
Sejf – jedyna droga (wszystko przez stronę WWW)
Token albo certyfikat KSeF jest tylko w sejfie – innej opcji nie ma. Zalecane: token KSeF tylko z uprawnieniem przeglądanie faktur. Taki token nie wystawi faktury, a tokeny zostają w KSeF także po 2026 r.
- W Aplikacji Podatnika KSeF → Tokeny wygeneruj token tylko z przeglądaniem faktur.
- W węźle wpisz NIP firmy i ustaw hasło strony (albo token dostępu). Wdróż (Deploy). Do Node-RED nie wpisujesz nic tajnego.
- Otwórz stronę (np.
http://<node-red>:1880/afya/ksef), zaloguj się, Utwórz sejf: wklej token (albo wgraj.crt+.key), opcjonalnie rachunek, z którego płacisz (do plików przelewów), dwa razy podaj hasło do sejfu (min. 10 znaków) – zapisz je w menedżerze haseł. - Gotowe – węzeł od razu sprawdza KSeF. Hasła do sejfu nie zapisujemy nigdzie.
Faktury też są zaszyfrowane. W sejfie jest losowy klucz danych; dziennik, odhaczenia „zapłacona” i plany przelewów
oraz pobrane XML faktur są nim szyfrowane (AES-256-GCM, z nazwą pliku) – <id>-dziennik.enc, <id>-zaplacone.enc,
<id>-xml/*.xml.enc. Przy zamkniętym sejfie nikt – nawet strona – ich nie odczyta. Zmiana hasła do sejfu nie szyfruje
ich od nowa (klucz danych zostaje); usunięcie sejfu usuwa też je.
Przejście ze starszej wersji (token / certyfikat w ustawieniach węzła, jawny <id>.json): węzeł już ich nie
używa. Przy tworzeniu sejfu strona proponuje „token z ustawień węzła” – przenosimy go do sejfu jednorazowo
i usuwamy z Node-RED (flows_cred.json zmieni się przy najbliższym wdrożeniu); jawne pliki dziennika, odhaczeń i XML
szyfrujemy i kasujemy przy pierwszym otwarciu sejfu. Stary token leżał jawnie i mógł trafić do kopii zapasowych –
najlepiej wygenerować nowy i użyć Wymień token albo certyfikat.
Po każdym restarcie Node-RED albo komputera sejf jest zamknięty: węzeł w ogóle nie pyta KSeF, a w
msg.payload.tekstSejf daje tekst do wysłania – raz po restarcie albo przy każdym sprawdzeniu, aż do podania
hasła (ustawienie Sejf zamknięty). Wyślij go SMS-em (trzecia gałąź w przykładowym przepływie). Strona pyta wtedy
tylko o hasło do sejfu – otwiera sejf, loguje na stronę i od razu sprawdza KSeF. Wdrożenie przepływu (deploy)
nie zamyka sejfu (to nie restart); usunięcie węzła – tak.
🔓 Sejf na stronie: na wierzchu stan sejfu i Zamknij sejf teraz, reszta zwinięta – rozwijasz tylko to, czego potrzebujesz: rachunek do przelewów (dodaj / zmień numer – wklejony numer czyścimy z „PL”, spacji i myślników, sprawdzamy 26 cyfr i sumę kontrolną, a na stronie widać tylko 6 ostatnich cyfr), zmień hasło do sejfu, wymień token albo certyfikat (np. nowy token po unieważnieniu starego – hasło do sejfu zostaje), certyfikat KSeF z kluczem wygenerowanym w sejfie, usuń sejf (razem z zaszyfrowanymi fakturami). Każda opcja wymaga hasła do sejfu; po wysłaniu strona rozwija tę samą sekcję z wynikiem.
Jak to działa: sejf to plik ~/.node-red/afya-ksef/<id-węzła>-sejf.json (prawa 0600) z samym szyfrogramem:
klucz z hasła przez scrypt (N=2¹⁵, r=8, p=1, sól 16 B), AES-256-GCM. Jawnie jest tylko to, co w środku (token /
podmiot i ważność certyfikatu). Otwarty sejf jest tylko w pamięci Node-RED.
Przed czym chroni, a przed czym nie. Sejf chroni dane w spoczynku: skradziony dysk, kopie zapasowe,
flows_cred.json, repozytorium. Nie chroni przed kimś, kto ma dostęp do edytora Node-RED – węzeł funkcji
przeczyta pamięć procesu – więc zabezpiecz edytor (adminAuth), a stronę trzymaj za hasłem, najlepiej po HTTPS.
Certyfikat z kluczem wygenerowanym w sejfie (opcjonalnie)
Jeśli wolisz certyfikat: 🔓 Sejf → Certyfikat KSeF z kluczem z sejfu – węzeł generuje klucz prywatny EC P-256
w sejfie, do KSeF wysyła tylko wniosek (CSR PKCS#10, /certificates/enrollments), a wydany certyfikat zapisuje
obok klucza. Klucz nigdy nie opuszcza sejfu – nie ma pliku .key, który ktoś mógłby skopiować. KSeF przyjmuje
wniosek tylko po logowaniu podpisem (XAdES), nie tokenem:
- certyfikatem, który już jest w sejfie (i unieważnij stary – jego plik
.keymógł zostać skopiowany), albo - pobierz dokument do podpisu (
AuthTokenRequest.xml, ważny 10 minut), podpisz go Profilem Zaufanym na gov.pl albo podpisem kwalifikowanym i wgraj. Certyfikat dostaje osoba, która podpisała.
Gdy w sejfie jest token, logowanie zostaje tokenem (zalecane), a certyfikat jest w zapasie – chyba że wybierzesz inaczej.
Konfiguracja
- Sejf: token / certyfikat tylko na stronie WWW (wyżej). Sejf zamknięty: tekst SMS raz po restarcie albo przy każdym sprawdzeniu. Identyfikacja (certyfikat w sejfie): dane z certyfikatu albo odcisk.
- Strona z fakturami – zawsze włączona (na niej tworzy się i otwiera sejf): ścieżka, tytuł, hasło i/lub token.
- Pamiętaj widok (Remember the view) – gdzie strona trzyma swój układ (kafelki / lista, sortowanie, zapłacone rozwinięte albo zwinięte, Ukryj zaplanowane): w przeglądarce (domyślnie – każde urządzenie swój) albo w węźle (ten sam na każdym urządzeniu) – przykłady niżej, w opisie strony.
- Kwoty: netto, brutto albo oba (netto, VAT, brutto) – w tabelach, sumach i
%kwota%. - Miesiąc wg: daty wystawienia albo daty otrzymania w KSeF (nadania numeru – dla kosztów to data otrzymania faktury).
- Sprawdzaj też poprzedni miesiąc – łapie faktury z poprzedniego miesiąca, które przyszły później.
- Nowy przychód / nowy koszt – osobne szablony SMS:
payload.tekstPrzychody,payload.tekstKoszty(oba razem wpayload.tekst). - Przelewy – z XML faktur zakupu: konto, bank, termin, forma płatności, split payment, „zapłacono”.
Kwota przelewu: brutto (albo „do zapłaty” z faktury) lub netto. Kopiowana kwota: z kropką
1518.44albo z przecinkiem1518,44.
Pola w szablonach: %kwota% %netto% %vat% %brutto% %kontrahent% %nip% %numer% %ksef% %data% %typ%
%waluta% %miesiac% %suma% %firma%, a dla kosztów także %platnosc% (konto, termin, ⚠ inna kwota w opisie) %przelew% %konto% %termin%.
Limity KSeF
KSeF pozwala na 20 zapytań o listę faktur na godzinę. Jedno sprawdzenie to 2 zapytania na miesiąc (4 z poprzednim
miesiącem) – inject co godzinę, najczęściej co 15 minut. Po 429 węzeł czeka tyle, ile każe KSeF.
XML faktur (dane do przelewu): najwyżej 12 przy jednym sprawdzeniu, każda faktura tylko raz.
Strona z fakturami
http://<node-red>:1880/afya/ksef – od góry: nazwa firmy, miesiąc i kafle przychody (otrzymano / czekamy),
koszty (wydano / do wydania) i zysk operacyjny – obecny (otrzymano − wydano) i oczekiwany (przychody − koszty),
duży pasek kiedy sprawdzono KSeF i czy logowanie się udało (zielony / czerwony, ostrzeżenie po 3 godz. bez
sprawdzenia), otwarte faktury z poprzednich miesięcy, tabele Przychody i Koszty
(data wystawienia, termin płatności, numer faktury z linkami PDF i XML, kontrahent z NIP-em – w kosztach
też konto z przyciskiem kopiuj – numer KSeF z przyciskiem kopiuj, kwoty, wiersz „Razem”), sortowanie po dacie
wystawienia albo terminie płatności (też klikając nagłówki „Data wyst.” / „Termin”), odhaczanie kółkiem – koszty „zapłacona”, przychody „otrzymana” (zapisywane
w Node-RED) i pod nimi
Do przelewu (na dole, karty): odbiorca, konto, kwota, tytuł, numer KSeF – wszystko z przyciskiem
kopiuj, do tego duży przycisk 📋 Kopiuj tytuł + nr KSeF; karty po 2 w rzędzie z dużym terminem płatności i znaczkiem (czerwone PO TERMINIE · N dni, „zapłać dziś”,
„jutro”, „za N dni”); odhaczenie działa w miejscu – karta dostaje zieloną ramkę i znaczek ✓ zapłacona i zostaje
czytelna, strona się nie przeładowuje; zapłacone zjeżdżają pod kreskę przy następnym otwarciu; termin (po terminie na
czerwono), split payment z kwotą VAT, konto faktora. Plan przelewu: w karcie niezapłaconego kosztu Zaplanuj przelew
na [dzień] – karta dostaje niebieską ramkę i znaczek „🗓 przelew 2026-12-20” (pomarańczowy „· po terminie”, gdy dzień
przelewu jest po terminie płatności), a następnego dnia po dniu przelewu faktura jest zapłacona („✓ zapłacona ·
przelew 2026-12-20”); Zmień / Usuń plan w karcie, plan w koszty[].zaplanowana. Kliknięcie kwoty w tabeli kopiuje ją jako
1518.44. Kopiowanie działa też przez zwykłe http:// w sieci lokalnej. Strzałki – poprzednie miesiące (do 13).
Zapłacone koszty i otrzymane przychody chowają się pod paskiem Zapłacone / Otrzymane (w tabelach) i pod przyciskiem
Pokaż zapłacone (w przelewach) – na wierzchu zostaje tylko to, co otwarte. Otwarte faktury z poprzednich
miesięcy przechodzą na bieżący: nieotrzymane przychody i niezapłacone koszty są na samej górze strony, dopóki ich
nie odhaczysz; niezapłacone koszty są też w kartach przelewów (ze znaczkiem „z listopada 2026”), a kafle pokazują je
w osobnym wierszu „z poprzednich miesięcy” (sumy miesiąca i zysk się nie zmieniają).
Koszty jako kafelki albo lista. Przy nagłówku Koszty: ▦ Kafelki (karty przelewów, domyślnie) albo ☰ Lista (tabela); Ukryj zaplanowane chowa faktury z zaplanowanym przelewem. Strona pamięta Twój widok – kafelki / lista, sortowanie, zapłacone (otrzymane) rozwinięte albo zwinięte i Ukryj zaplanowane – i następnym razem otwiera się tak samo; gdzie go trzyma, ustawiasz w węźle (Remember the view):
- w przeglądarce (domyślnie; ciasteczka na rok, osobno dla każdego węzła) – każde urządzenie swój widok. Przykład: na telefonie trzymasz kafelki do odhaczania przelewów, na komputerze listę wg terminu płatności ze zwiniętymi zapłaconymi; tablet na ścianie z linkiem z tokenem zostaje przy tym, co na nim zostawiono,
- w węźle (plik
~/.node-red/afya-ksef/<id-węzła>-widok.json, tylko układ strony – bez danych faktur) – jeden widok dla wszystkich. Przykład: raz na komputerze ustawiasz lista, wg terminu, zapłacone zwinięte, Ukryj zaplanowane – telefon, przeglądarka księgowej i tablet w trybie kiosku (co noc czyści ciasteczka) otwierają dokładnie to samo; zmiana na którymkolwiek urządzeniu zmienia widok na wszystkich (wygrywa ostatnia).
W każdym wierszu i każdej karcie są wyraźne przyciski Oznacz jako zapłaconą / Odznacz jako zapłaconą i + Do paczki przelewów, a w liście stan terminu ma znaczek jak w kartach (🗓 przelew …, po terminie, zapłać dziś).
Plik przelewów. Dodaj faktury przyciskiem + Do paczki przelewów (albo 🏦 Zaznacz wszystkie możliwe do paczki przelewów (N)
przy nagłówku sekcji – zaznaczy wszystkie faktury tej sekcji, które da się zapłacić plikiem); pasek przelewów pojawia się na dole ekranu dopiero, gdy zaznaczysz choć jedną
fakturę (faktury z zaplanowanym przelewem nie da się dodać – najpierw „Usuń plan” w karcie); pokazuje dwie rubryki:
Do zapłaty łącznie (tyle wyjdzie z konta – z rozliczeniami z faktur) i Wartość FV netto / brutto (przełącznik;
domyślnie jak Amounts, przeglądarka pamięta wybór) – z różnicą, gdy kwoty się nie zgadzają; tam
🏦 Przelewy – wygeneruj plik: kalendarz podpowiada najbliższy termin płatności zaznaczonych faktur (weekend → piątek, nigdy przed
dziś) – możesz wybrać inny dzień, wszystkie przelewy dostaną tę datę. Format (domyślny ustawiasz w węźle, Plik
przelewów): Nest Bank XML albo CSV (UTF-8), mBank Elixir-0 (UTF-8, najwyżej 50 przelewów / 10 KB), ING
Elixir-0 / PLI (Windows-1250), VeloBank XML (ISO-8859-2), PKO BP ISO 20022 pain.001.001.09 (XML, bez podzielonej
płatności) – podzielona płatność w pozostałych jako /VAT/…/IDC/…/INV/…/TXT/… (Elixir-0: kod 53) – albo Excel (XLSX)
– zestawienie do wglądu, dla księgowej. Formaty opracowane wyłącznie na podstawie publicznie dostępnych w internecie
opisów – sprawdź, czy Twój bank przyjmuje plik; nazwy banków służą tylko do identyfikacji formatu i należą do ich
właścicieli. Tylko faktury w PLN z polskim kontem (poprawna suma kontrolna NRB). Rachunek, z którego płacisz, jest
w sejfie (na stronie 6 ostatnich cyfr); bez niego przycisk jest nieaktywny. Po pobraniu pliku strona pyta, czy oznaczyć
faktury jako zaplanowane do zapłaty na ten dzień (Tak / Nie teraz) – sam plik niczego nie zmienia. Długie uwagi
z faktury w kartach: 2 linijki i … więcej. Plik to tylko projekt – kto zatwierdza przelewy w banku, ma obowiązek sprawdzić każdy z nich i za nie
odpowiada (zob. LICENSE).
Rozliczenie na fakturze (Rozliczenie – np. rata za telefon, opłaty wspólnoty): do przelewu idzie kwota
do zapłaty z faktury, a nie samo brutto – karta pokazuje „faktura … + obciążenia … = …”, w tabeli jest znaczek
„do zapłaty”, SMS też to mówi. W kaflach „wydano / do wydania” to przelewy (z rozliczeniem), a koszty i zysk
operacyjny – z wartości faktur: faktura leasingowa na 90,08 zł odsetek z ratą kapitałową 3 221,52 zł to 90,08 zł
kosztu i 3 311,60 zł przelewu. Nadpłata „do rozliczenia” = nic do zapłaty.
Na dole strony: logo i link dobry.doctor oraz ORCID autora.
PDF otwiera czytelną fakturę (strony, pozycje z netto, VAT i brutto, podsumowanie z brutto dla każdej stawki, rozliczenie, płatność, uwagi i załącznik, link weryfikacyjny
KSeF) z przyciskiem Zapisz PDF / drukuj; kwoty w uwagach o płatności są podświetlone, a gdy w opisie jest inna kwota
niż na fakturze – ostrzeżenie ⚠ w tabeli, w karcie przelewu i w SMS-ie. XML pokazuje / pobiera plik z KSeF.
Pobrany XML jest trzymany 30 dni (zaszyfrowany, ~/.node-red/afya-ksef/<id-węzła>-xml/), potem pobierany od nowa.

Dostęp jak w Librusie: hasło (logowanie na 30 dni) i/lub token w linku ?token=…; bez nich strona jest
wyłączona, 10 błędnych prób w 15 minut blokuje adres na chwilę. Wystawiając stronę do internetu – tylko przez HTTPS / VPN.
Przykład
Menu → Import → Examples → node-red-contrib-afya-ksef → ksef-sms: co godzinę 7–21, nowy przychód i nowy koszt
osobnymi SMS-ami (przychody do właściciela, koszty do właściciela i księgowej), bramka SMS po HTTP z tokenem
w nagłówku, cały wynik do MQTT afya/ksef/dane. Pierwsze sprawdzenie tylko zapamiętuje faktury.
Biblioteka przepływów Node-RED: library/flow.json – harmonogram afya-week-calendar co 2 h (8–20) → KSeF → SMS o przychodzie i koszcie → bramka SMS po HTTP (opis).
Testy
npm install && npm test – testy na atrapie KSeF, która sprawdza szyfrowanie tokenu, podpis XAdES (RSA i EC),
tokeny Bearer, filtry zapytań i XML faktur.
Marcin Chuć · MIT · dobry.doctor · nieoficjalne, niezwiązane z Ministerstwem Finansów