forked from obrassard/shc-extractor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparsers.js
82 lines (66 loc) · 1.88 KB
/
parsers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const jsQR = require('jsqr');
const PNG = require('pngjs').PNG;
const zlib = require("zlib");
const axios = require("axios").default;
const jose = require('node-jose');
const readQrCode = (fileBuffer) => {
const qrCodeFile = process.argv[2]
if (!qrCodeFile) throw new Error('Please provide the file path to the PNG QR code to decode')
// Read the QR code
const imageData = PNG.sync.read(fileBuffer)
const scannedQR = jsQR(new Uint8ClampedArray(imageData.data.buffer), imageData.width, imageData.height)
// Extract the QR data
if (!scannedQR) throw new Error('Invalid QR code')
return scannedQR.data
}
const parseShc = async (schRaw) => {
const jwt = numericShcToJwt(schRaw);
const splitJwt = jwt.split(".")
const header = parseJwtHeader(splitJwt[0])
const payload = parseJwtPayload(splitJwt[1])
const verifications = await verifySignature(jwt, payload.iss)
return {
header,
payload,
verifications
}
}
function numericShcToJwt(raw) {
// Convert the data to a JWT
return raw
.split("/")[1]
.match(/(..?)/g)
.map((number) => String.fromCharCode(parseInt(number, 10) + 45))
.join("")
}
function parseJwtHeader(header) {
const headerData = Buffer.from(header, "base64");
return JSON.parse(headerData)
}
function parseJwtPayload(payload) {
const buffer = Buffer.from(payload, "base64");
// Uncompress the payload and print the result
const payloadJson = zlib.inflateRawSync(buffer)
return JSON.parse(payloadJson);
}
async function verifySignature(jwt, issuer) {
try {
const response = await axios.get(`${issuer}/.well-known/jwks.json`)
const jwks = response.data;
const keystore = await jose.JWK.asKeyStore(jwks)
const result = await jose.JWS.createVerify(keystore).verify(jwt)
return {
trustable: true,
verifiedBy: result.key.kid
}
} catch (err) {
console.log(err)
return {
trustable: false
}
}
}
module.exports = {
readQrCode,
parseShc
}