italia / verificac19-sdk Goto Github PK
View Code? Open in Web Editor NEW✅ Official VerificaC19 Node.js SDK
License: MIT License
✅ Official VerificaC19 Node.js SDK
License: MIT License
This can help other users which has problems by setting the environment variable for the MongoDB. By setting the env with powershell or Windows GUI the default connection string is set all the times so i needed to use dotenv to set the custom one.
By trying to make my connection string work i've used the dotenv for settings and reading the environmental variable so once dotenv is installed
npm install dotenv
i've created a .env
file in my root project with the following content:
#MongoDB Connection String
VC19_MONGODB_URL=mongodb://root:example@localhost:27017/VC19?authSource=admin
And set this in crl.js or as soon as the application runs (ex: app.js):
require('dotenv').config()
Implementare nuova modalità di ingresso IT con regole per ingresso a utenti di età inferiore ai 18 anni, nello specifico sono state sviluppate lato SDK Android le seguenti funzionalità:
vaccino_end_day_complete_under_18
per il numero di giorni da aggiungere e under_18_offset
per aggiungere eventualmente alcuni giorni in modo da consentire agli utenti di completare la vaccinazione pochi giorni dopo aver compiuto 18 anniCommit di riferimento qui
@astagi scusa se ti disturbo, ma ho questo problema quando eseguo l'istruzione:
const dccTest = await Certificate.fromRaw(qrcode)
mi da questo errore
CertificateParsingError: certificate can't be parsed, Invalid base45 string
il qrCode della prova è quello del mio certificato personale e sono sicuro che sia valido.
Cosa posso aver sbagliato?
Grazie
Describe the bug
Sto cercando di validare un greenPass terza dose che dovrebbe, credo, avere validità 540 gironi. Invece viene applicata la regola 180 giorni.
Come di può vedere qua:
person: 'xxx',
date_of_birth: '1974-01-24',
result: true,
code: 'VALID',
message: 'Doses 3/2 - Vaccination is valid [ 2021-09-18T00:00:00.000Z - 2022-03-17T00:00:00.000Z ] '
Guardando sul codice e sulle regole in effetti cade su questa regola:
{ "name": "vaccine_end_day_complete", "type": "EU/1/20/1528", "value": "180" },
e non su questa:
{ "name": "vaccine_end_day_booster_IT", "type": "GENERIC", "value": "540" },
dove sta l'errore?
Grazie
Is your feature request related to a problem? Please describe.
Implement a cache manager like CRL system
I made a try to implement a CRL manager with Redis instead of lowdb and the performance i think is even better than MongoDB, I think that you should give a try.
On windows i used memurai as Redis replacement.
[...]
async setUp() {
const client = createClient();
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
this._db = client;
}
async storeRevokedUVCI(revokedUvci) {
for (const element of revokedUvci) {
this._db.set(element, 'true');
}
}
async isUVCIRevoked(uvci) {
return await this._db.get(uvci) || false;
}
async clean() {
return await this._db.sendCommand(['FLUSHDB']);
}
I also would like to report an issue on the custom CRL manager example:
as it should be:
return !await this._db.get('uvcis').find(uvci);
Ho cercato di trovare una soluzione per 2 giorni, ma sono nuovo di JavaScript e non so come far funzionare gli script.
Per favore aiutami, puoi darmi i passaggi da seguire per convalidare un pass non valido.
"Per scopi didattici".
Si prega di procedere all'aggiornamento del core di questo SDK per allineamento a release DGC-SDK Android/Kotlin 1.1.11.
Rimozione delle modalità di verifica RSA (booster) e Rafforzata (2G)
Aggiornamento del flusso di validazione con solo i controlli previsti per la modalità di verifica Base (3G)
Maggiori dettagli: ministero-salute/it-dgc-documentation#29
Salve a tutti, sono alle prime armi con NodeJs e cercando di seguire la documentazione passo ho provato ad eseguire i file contenuti nella cartella examples dopo aver clonato il repository e installato le dipendenze.
Quando do il comando
node syncdata.js
il processo riscontra il seguente errore:
ReferenceError: TextDecoder is not defined at Object.202 (/root/test_sdk_verificac19/verificac19-sdk-master/node_modules/cbor-web/dist/cbor.js:2:59224) at r (/root/test_sdk_verificac19/verificac19-sdk-master/node_modules/cbor-web/dist/cbor.js:2:114825) at Object.873 (/root/test_sdk_verificac19/verificac19-sdk-master/node_modules/cbor-web/dist/cbor.js:2:55961) at r (/root/test_sdk_verificac19/verificac19-sdk-master/node_modules/cbor-web/dist/cbor.js:2:114825) at Object.20 (/root/test_sdk_verificac19/verificac19-sdk-master/node_modules/cbor-web/dist/cbor.js:2:27297) at r (/root/test_sdk_verificac19/verificac19-sdk-master/node_modules/cbor-web/dist/cbor.js:2:114825) at Object.141 (/root/test_sdk_verificac19/verificac19-sdk-master/node_modules/cbor-web/dist/cbor.js:2:26717) at r (/root/test_sdk_verificac19/verificac19-sdk-master/node_modules/cbor-web/dist/cbor.js:2:114825) at /root/test_sdk_verificac19/verificac19-sdk-master/node_modules/cbor-web/dist/cbor.js:2:115792 at /root/test_sdk_verificac19/verificac19-sdk-master/node_modules/cbor-web/dist/cbor.js:2:115800
Ottengo un errore molto simile con "ReferenceError: TextDecoder is not defined" se provo a lanciare
npm run test
Qualcuno può aiutarmi?
Please explain database and cache use. Even though the database is not connected, I can still fully check signature, rules and validation (with existing cache files). Just Service.updateAll()
is not working. What is the database used for?
Furthermore Service.updateAll()
is rejecting a promise if the database is not reachable, which is killing the whole process, can't even try/catch. That could be classified as a bug.
$ docker run -it -v $(pwd):/app --env VC19_CACHE_FOLDER=./cache -w /app node:16-alpine node alone.js
Certificate: {
person: {
standardisedFamilyName: 'X',
familyName: 'X',
standardisedGivenName: 'Y',
givenName: 'Y'
},
dateOfBirth: '1900-01-01',
vaccinations: [
{
disease: '840539006',
vaccine: 'J07BX03',
medicinalProduct: 'EU/1/20/1528',
manufacturer: 'ORG-100030215',
doseNumber: 2,
totalSeriesOfDoses: 2,
dateOfVaccination: '2021-10-01',
countryOfVaccination: 'FR',
certificateIssuer: 'CNAM',
certificateIdentifier: 'URN:UVCI:01:FR:T5DWTJYS4XYZ#4'
}
],
tests: undefined,
recoveryStatements: undefined,
kid: '53FOjX/4XYZ='
}
Signature: true
Rules: { result: false, code: 'REVOKED', message: 'UVCI is in blacklist' }
Validation: {
person: 'X Y',
date_of_birth: '1900-01-01',
result: false,
code: 'REVOKED',
message: 'UVCI is in blacklist'
}
Starting update...
TEST: Can not connect to MongoDB
<now it takes some time before killing the whole process>
REJECTION: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:801:32)
at Mongoose.createConnection (/app/node_modules/mongoose/lib/index.js:285:10)
at CRL.setUp (/app/node_modules/verificac19-sdk/src/crl.js:7:41)
at Cache.setUp (/app/node_modules/verificac19-sdk/src/cache.js:34:30)
at setUp (/app/node_modules/verificac19-sdk/src/service.js:7:15)
at Object.updateAll (/app/node_modules/verificac19-sdk/src/service.js:109:9)
at main (/app/alone.js:28:23)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
// alone.js
const { MongoClient } = require('mongodb');
const { Certificate, Service, Validator } = require('verificac19-sdk')
let mongo_default = 'mongodb://root:example@localhost:27017/VC19?authSource=admin'
let cert = 'HC1:A1B2C3D4E5...';
process.on('SIGINT', function () { process.exit() });
process.on('SIGTERM', function () { process.exit() });
process.on('unhandledRejection', (reason, promise) => {
console.log('REJECTION:', reason.stack || reason)
});
const main = async () => {
certificate = await Certificate.fromRaw(cert);
console.log('Certificate:', certificate, '\n')
signature = await Validator.checkSignature(certificate);
console.log('Signature':, signature, '\n');
rules = await Validator.checkRules(certificate);
console.log('Rules:', rules, '\n');
validation = await Validator.validate(certificate)
console.log('Validation:', validation, '\n');
console.log('Starting update...');
try {
await Service.updateAll();
} catch (err) {
// THIS IS NEVER REACHED
console.log('ERROR:', err)
}
console.log('...finished update');
}
// check ourself if the database is reachable
MongoClient.connect(process.env.VC19_MONGODB_URL || mongo_default, {
connectTimeoutMS: 1000,
serverSelectionTimeoutMS: 1000,
}, function (err, db) {
if (err) {
console.log('TEST: Can not connect to MongoDB')
} else {
console.log('TEST: Connected to MongoDB')
db.close();
}
});
main();
@astagi: Ottimo lavoro, gran cosa! Solo una piccolo dubbio.. anche questo è un SDK "UFFICIALE" come quello Android o è un progetto personale? Lo chiedo perché non è tra i repo del Ministero.... In ogni caso grazie
Rimuovere e adeguarsi all'ultima versione del SDK ufficiale rimuovendo la modalità di ingresso IT. CHANGELOG
Inserire all'interno delle richieste verso le API l'apposito header User-Agent nella forma
User-Agent: <sdk>-<sdk-technology>/<sdk-version>
È possibile omettere -<sdk-technology>
se la tecnologia è già specificata nel nome (ad esempio verificac19-sdk-php).
Ad esempio nel caso verificac19-sdk
per Node.js lo User-Agent sarà
User-Agent: verificac19-sdk-node/0.9.3
I get "Not Valid" reply when I send payloads to the validator using recently issued Green Passes.
Certificate type: recovery
I get instead "Valid" reply while using older certificates of the same type.
{
"result": "KO",
"reason": "NOT_VALID",
"person_data": {
"person": "--- --- ---",
"dob": "23/01/1987"
},
"device_id": 1,
"instance_id": 1,
"ci": "--- --- ---",
"certificate_type": "recovery"
}
I can privately share the payloads I am working with.
Describe the bug
Trying to validate several third doses Moderna Green Pass Certificates with VISITORS_RSA scan mode, the validate
function returns TEST_NEEDED.
Doing some reverse engineering, we've found that third doses Green Pass Certificates are uncorrectly defined with validationStatus = complete
, which represent just a complete cycle Green Pass Certificate (two doses or one dose for Johnson&Johnson), instead of a validationStatus = booster
(check code at line 168
of validator.js
).
This issue happen because of a bad comparison of last.doseNumber > last.totalSeriesOfDoses
. My personal Green Pass certificate (three doses) has doseNumber = 3
and a totalSeriesOfDoses = 3
, in this situation, the condition will be always false and all the newer Green Pass Certificates with totalSeriesOfDoses = 3
will fail the validation.
I found that today the function updateSignatures fails for a 502 error on an endpoint. Adding a try/catch block is preventing the error, maybe it's just an error due to a invalid endpoint, but it should be managed.
Thank you
Sebastiano
We are using verificac19-sdk mostly because of the support for revoked certificates, we don't won't to allow fake ones.
The in-famous Adolf certificate is marked as revoked, but Spongebob is still valid. Why is that?
(It's probably a bigger question why EU politics have not managed to get a common revoked list on a CDN, accessible to everyone)
We build a web service that checks certificates with verificac19-sdk. It seems that a call to await Service.updateAll()
is blocking validation at the same time, even when MongoDB database and cache files are present.
Signature ERROR: certificate can't be verified, undefined
Rules ERROR: certificate can't be verified, undefined
Validation ERROR: certificate can't be verified, undefined
Can you confirm that we can not use Validator.validate()
at the same time while Service.updateAll()
is still running?
We saw that updateAll()
sometimes takes minutes to finish, then we need to find a workaround to be able to continue processing incoming verification requests (load balancer, separate instances, closing port during update, etc.).
Come si verifica se un green pass è stato revocato o meno? Intendo revocato anche per chi diventa positivo... Da quanto ho capito l'ultima versione di VerificaC19 permette di scaricare la lista delle certificazioni revocate.
Is there any Green Pass QR code (or string) usable for testing? We have some integration tests and API monitoring tools that run periodically and do not want to expose the personal information of our developers. Is there such thing as a valid test for Green Pass?
In README specify Node.js supported versions
@astagi ,
validator.js has this hardcoded check (below), which is not dependent on the settings file that can be downloaded from dgc official site, nor can be found in any of the files that can be cached by the library:
72 if (type === 'Sputnik-V' && last.countryOfVaccination !== 'SM') {
73 return {
74 code: NOT_VALID,
75 message: 'Vaccine Sputnik-V is valid only in San Marino',
76 };
77 }
Is there a place where all these special rules are listed (and maybe can also be downloaded like the settings file)?
Thank you.
Describe the bug
Expected behavior
EMA list shoud be fetched from settings, not hardcoded
verificac19-sdk/src/validator.js
Line 149 in 6326798
Oggi ho ricevuto, valutando una certificazione, con sdk attuale:
NOT_VALID - Vaccination format is invalid
con
startDate: 2021-09-15T00:00:00.000Z
endDate: 2022-03-14T00:00:00.000Z
endNow: 2022-03-14T23:59:59.999Z
chiaramente settando: endNow.setUTCHours(0, 0, 0, 0);
la validazione passa.
Lo stesso certificato valutato con VerificaC19 e sdk php viene verificato normalmente.
Chi sbaglia?
Un saluto
Sto utilizzando pm2 come load balancer e gestione processi per un backend in azienda.
Quando arrivo la mattina mi accorgo che il processo sul quale gira NodeJS utilizza 700/800 MB di memoria (a fronte dei 30/40 MB con la versione SDK 0.5.1).
Il processo esegue periodicamente (ogni 4 ore) Service.updateAll()
per tener aggiornato il database (il programma gira 24/7).
Non ho ancora profilato il consumo di memoria ma sospetto che qualche dato proveniente dalla cache non viene smaltito correttamente dal garbage collector.
Grazie mille in anticipo e complimenti per l'SDK!
ciao @astagi,
per quanto riguarda la modalità di validazione "work" (vedi app Verifica C19), con la gestione degli over 50, avete in programma di rilasciarla prima del 15 o conviene iniziare integrarla manualmente nei singoli progetti facendo un controllo sulla data i nascita?
Nessuna pressione è solo per sapere come muovermi... ;)
Grazie
Ciao
Ciao da ieri, effettuando dei test con l'ultima versione ottengo:
Processing new request... (node:2173378) UnhandledPromiseRejectionWarning: CertificateVerificationError: certificate can't be verified, undefined
at checkCacheIsReady (/home/test/sdk-0.9.4/node_modules/verificac19-sdk/src/validator.js:663:11)
at checkSignature (/home/test/sdk-0.9.4/node_modules/verificac19-sdk/src/validator.js:712:3)
at Object.validate (/home/test/sdk-0.9.4/node_modules/verificac19-sdk/src/validator.js:743:29)
at Server. (/home/test/sdk-0.9.4/app.js:105:44)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use node --trace-warnings ...
to show where the warning was created)
(node:2173378) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict
(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:2173378) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
La versione di node è la v14.19.1, a cosa può essere dovuto?
How often should await Service.updateAll();
be run? Or does it run automatically?
I build an small wrapper to use the certificate validation as a web service API: curl -X POST -d 'HC1:...' server.tld/validate
const express = require('express')
const bodyParser = require('body-parser')
const { Certificate, Service, Validator } = require('verificac19-sdk')
const app = express()
const port = 3000
app.use(bodyParser.text({ type: "*/*" }))
app.get('/', (req, res) => {
let html = `<html>
<body>
<h1>Certificate Validator</h1>
<p>Enter a certificate starting with <b>HC1:...</b></p>
<textarea id="cert" cols="55" rows="15"></textarea>
<br />
<button onclick="clickValidate()">Validate</button>
<pre id="result"></pre>
</body>
<script>
function clickValidate() {
document.getElementById('result').innerHTML = 'Waiting for response'
var xhr = new XMLHttpRequest();
xhr.onload = function() { document.getElementById('result').innerText = this.response };
xhr.open("POST", '/validate');
xhr.send(document.getElementById("cert").value);
}
</script>
</html>`
res.send(html)
})
app.post('/validate', async (req, res) => {
try {
cert = req.body
if (!cert || !cert.startsWith('HC1:')) {
return res.status(400).json({ error: { message: "Invalid certificate, needs to start with 'HC1:'" } })
}
const certificate = await Certificate.fromRaw(cert)
const validation = await Validator.validate(certificate)
const rules = await Validator.checkRules(certificate).result;
const signature = await Validator.checkSignature(certificate);
delete certificate.dcc
res.setHeader('Content-Type', 'application/json');
res.status(200).end(JSON.stringify({ certificate, rules, signature, validation }, null, 2) + '\n');
} catch (err) {
return res.status(400).json({ error: { message: err.message } })
}
})
const run = async () => {
console.log('Starting...');
await Service.updateAll();
app.listen(port, '0.0.0.0', () => {
console.log(`App listening on port: ${port}`)
})
}
run();
Describe the bug
Data fine validità non coerente con sdk android.
Dal codice in /src/validator.js , la data di fine validità è la somma di validUntil con RECOVERY_CERT_END_DAY,
mentre sull'sdk ( \sdk\src\main\java\it\ministerodellasalute\verificaC19sdk\model\VerificationViewModel.kt ):
NOT_VALID (scaduto)
data verifica > validFrom + RECOVERY_CERT_START_DAY + RECOVERY_CERT_END_DAY
PARTIALLY_VALID
data verifica > validUntil
/src/validator.js
startDate = addDays(startDate, recoveryCertStartDay.value);
endDate = addDays(endDate, recoveryCertEndDay.value);
...
if (startDate > now) {
return {
code: NOT_VALID_YET,
message:
`Recovery statement is not valid yet, starts at : ${
startDate.toISOString()}`,
};
}
if (now > endDate) {
return {
code: NOT_VALID,
message: `Recovery statement is expired at : ${endDate.toISOString()}`,
};
}
Expected behavior
valid_from = cert->validFrom;
start_date = addDays(valid_from, recoveryCertStartDay.value);
end_date = cert->validUntil;
if (start_date > validation_date) NOT_VALID_YET
if (validation_date > addDays(start_date, recoveryCertEndDay.value) ) NOT_VALID
if (validation_date > end_date ) PARTIALLY_VALID
In vista dell'aggiornamento SDK apro qua una richiesta di cambiamento per il SDK in questione.
L'opzione è stata eliminata in quanto fino al 30 aprile è possibile per tutti, compresi gli over 50, accedere ai luoghi di lavoro con il green pass BASE, come previsto dal DECRETO-LEGGE 24 marzo 2022, n. 24.
Describe the bug
Quando viene inviata alla libreria un QR-Code di un vaccinato con Novavax (Nuvaxoid) da più di 15 giorno, quindi valido, l'sdk ritorna: "Not EMA vaccine is not valid for worker with age < 50 years".
Il QR-Code verificato con l'app cverifica-19 risulta funzionare correttamente.
To Reproduce
Describe the bug
Sto provando a validare un GP, su app c19 risulta valido con modalità rafforzato mentre attraverso il test con questo modulo risulta scaduto 2 giorni fa.
{
person: '------',
date_of_birth: '1987-07-21',
result: false,
code: 'NOT_VALID',
message: 'Doses 2/1 - Vaccination is expired at : 2022-04-24T00:00:00.000Z'
}
Il vaccino è PFIZER e la regola per il calcolo dei giorni di validità prende 180.
Posso condividere il caso in privato.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.