-
Notifications
You must be signed in to change notification settings - Fork 0
/
verifier.js
286 lines (276 loc) · 9.11 KB
/
verifier.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import { createServer } from 'node:http'
import QRCode from 'qrcode'
import { v4 as uuidv4 } from 'uuid'
import { apiHeaders, config } from './init.js'
const states = {}
const pollingInterval = 3 // seconds
async function createRequest(id) {
const requestUrl = `${config.verifier_api}/openid4vc/verify`
const requestBody = {
"request_credentials": [
"PensionCredential"
],
"presentation_definition": {
"id": "<automatically assigned>",
"name": "Eläketodiste",
"purpose": "HSL:n eläkealennusoikeuden rekisteröintiin",
"input_descriptors": [{
"id": "Kela-HSL",
"constraints": {
"fields": [
{
"path": [
"$.credentialSubject.Person.givenName",
]
},
{
"path": [
"$.credentialSubject.Person.familyName",
]
},
{
"path": [
"$.credentialSubject.Person.birthDate",
]
},
{
"path": [
"$.credentialSubject.Pension.statusCode",
]
},
],
"limit_disclosure": "required"
}
}]
}
}
const requestParams = {
method: 'POST',
headers: Object.assign(apiHeaders, {
"Accept": "*/*",
"authorizeBaseUrl": "openid4vp://authorize",
"responseMode": "direct_post",
"successRedirectUri": `${config.verifier_base}/success?id=${id}`,
"errorRedirectUri": `${config.verifier_base}/error?id=${id}`,
"Content-Type": "application/json",
}),
body: JSON.stringify(requestBody)
}
// console.log(JSON.stringify(requestBody, null, 1))
// console.log(requestUrl, JSON.stringify(requestParams, null, 1))
const resp = await fetch(requestUrl, requestParams)
if (resp.status != 200) {
console.log(resp.status, requestUrl, JSON.stringify(requestParams, null, 1))
}
const credentialRequest = await resp.text()
const url = new URL(credentialRequest)
states[id] = url.searchParams.get('state')
console.log(resp.status, credentialRequest, id)
return credentialRequest
}
async function showRequest(res) {
const id = uuidv4()
const credentialRequest = await createRequest(id)
const dataURL = await QRCode.toDataURL(credentialRequest)
res.setHeader("Content-Type", "text/html")
res.writeHead(200)
res.end(`<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<style>
table {
max-width: 30em;
margin: 1em auto;
}
th, td {
text-align: left;
}
pre {
background-color: black;
color: green;
display: none;
text-align: left;
}
#content.full pre {
display: block;
}
</style>
<body style="text-align: center;">
<img src="https://cdn-assets-cloud.frontify.com/s3/frontify-cloud-files-us/eyJwYXRoIjoiZnJvbnRpZnlcL2FjY291bnRzXC8yZFwvMTkyOTA4XC9wcm9qZWN0c1wvMjQ5NjY1XC9hc3NldHNcLzAwXC80NTY4NzI2XC81MjA2ODk2MDdmZGRkYjBlMDEwMDhiOTVlMTk1OTRjMS0xNTk1NDI3ODE5LnN2ZyJ9:frontify:ToCDM7NDPWebZDLJcmAgDwA_EsA9XJBl3YroZI1XhA0?width=240" alt="HSL" />
<h1>Heippa vahvasti tunnistettu asiakas!</h1>
<div id="content">
<p>Lähetäpä eläketodiste niin tsekataan, että sinulla on oikeus eläkealennukseen...</p>
<a href="${credentialRequest}"><img src="${dataURL}" alt="Credential Request QR Code" /></a>
</div>
<script>
const c = document.querySelector('#content')
const a = document.createElement('a')
a.textContent = 'Kopioi todistepyyntö leikepöydälle.'
a.href = '${credentialRequest}'
a.style.display = 'block'
a.onclick = function(e) {
e.preventDefault()
try {
navigator.clipboard.writeText(this.href)
} catch (error) {
console.error(error.message)
}
}
// document.querySelector('#qrcode').onnoclick = () => {document.location.href = qrUrl}
const o = document.querySelector('#offer')
c.appendChild(a)
const uri = '/status?id=${id}'
let timer
async function checkStatus() {
const resp = await fetch(uri)
if (resp.status == 200) {
const status = await resp.json()
if (status.verificationResult) {
clearInterval(timer)
// console.log(JSON.stringify(status, null, 1))
const presentationPolicies = status.policyResults?.results?.at(0)?.policies
const sdjwt = presentationPolicies?.at(0)?.result?.vp?.verifiableCredential?.at(0)
// console.log(sdjwt)
const disclosures = sdjwt.split('~')
disclosures.splice(0, 1) // discard jwt
// console.log(disclosures)
const attributes = {}
for (const d of disclosures) {
const decoded = JSON.parse(atob(d))
// console.log(decoded[1], decoded[2])
attributes[decoded[1]] = decoded[2]
}
// console.log(attributes)
const credentialPolicies = status.policyResults?.results?.at(1)?.policies
const credential = credentialPolicies?.at(0)?.result?.credentialSubject
const html = \`<p>Todisteen tarkistuksen tila: <strong>\${status.verificationResult}</strong></p>
<table>
<tr><th>Hetu</th><td>\${attributes?.person_identifier_code}</td></tr>
<tr><th>Eläke</th><td>\${attributes?.Pension?.typeCode}</td></tr>
<tr><th>Alkamispäivä</th><td>\${attributes?.Pension?.startDate}</td></tr>
</table>
<pre>\${JSON.stringify(status, null, 2)}</pre>\`
c.innerHTML = html
c.ondblclick = function(e) {
this.classList.toggle('full')
}
const t = document.createElement('table')
let trs = \`<tr><th>Tarkastus</th><th>Tulos</th></tr>\`
for (const policy of presentationPolicies) {
trs += \`<tr><td>Verifiable Presentation: \${policy.description}</td><td><strong>\${policy.is_success}</strong></td></tr>\`
}
for (const policy of credentialPolicies) {
trs += \`<tr><td>Verifiable Credentials: \${policy.description}</td><td><strong>\${policy.is_success}</strong></td></tr>\`
}
t.innerHTML = trs
c.appendChild(t)
}
}
}
timer = setInterval(checkStatus, ${pollingInterval * 1000} )
</script>
</body>
</html>`)
}
function renderCredential(sdjwt) {
console.log(sdjwt)
const disclosures = sdjwt.split('~')
disclosures.splice(0, 1) // discard jwt
const attributes = {}
for (const d of disclosures) {
const decoded = JSON.parse(atob(d))
attributes[decoded[1]] = decoded[2]
}
const html = `<table>
<tr><th>Hetu</th><td>${attributes?.person_identifier_code}</td></tr>
<tr><th>Eläke</th><td>${attributes?.Pension?.typeCode}</td></tr>
<tr><th>Alkamispäivä</th><td>${attributes?.Pension?.startDate}</td></tr>
</table>`
return html
}
async function showSuccess(id, res) {
const status = await getStatus(id)
console.log(JSON.stringify(status, null, 2))
const presentationPolicies = status.policyResults?.results?.at(0)?.policies
const sdjwt = presentationPolicies?.at(0)?.result?.vp?.verifiableCredential?.at(0)
let html
if (sdjwt) {
html = `<h2>Tiedot:</h2>\n${renderCredential(sdjwt)}`
}
else {
html = `<h2>VIRHE:</h2>\n<pre>${JSON.stringify(status, null, 1)}</pre>`
}
console.log(id, status)
res.setHeader("Content-Type", "text/html")
res.writeHead(200)
res.end(`<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<style>
table {
max-width: 30em;
margin: 1em auto;
}
pre, th, td {
text-align: left;
}
</style>
<body style="text-align: center;">
<h1>Tiedot tulivat perille!</h1>
<p>Todisteen tarkistuksen tila: <strong>${status.verificationResult}</strong></p>
${html}
</body>
</html>`)
}
async function getStatus(id) {
if (!states[id]) {
return false
}
const statusUrl = `${config.verifier_api}/openid4vc/session/${states[id]}`
const resp = await fetch(statusUrl, { headers: apiHeaders })
// console.log(statusUrl, resp.status)
if (resp.status != 200) {
console.error(JSON.stringify(await resp.text(), null, 1))
return false
}
const verificationStatus = await resp.json()
// console.log(statusUrl, resp.status, JSON.stringify(verificationStatus, null, 1))
return verificationStatus
}
const handleRequests = async function (req, res) {
const fullUrl = new URL(config.verifier_base + req.url)
let id = fullUrl.searchParams.get('id')
console.log(fullUrl.pathname, id)
switch (fullUrl.pathname) {
case '/error':
res.setHeader("Content-Type", "text/plain")
res.writeHead(500)
res.end(`Virhe käsiteltäessä tapahtumaa ${id}`)
return false
case '/success':
await showSuccess(id, res)
return false
case '/status':
const status = await getStatus(id)
if (!status) {
res.setHeader("Content-Type", "text/plain")
res.writeHead(500)
res.end(`Virhe käsiteltäessä tapahtumaa ${id}`)
}
res.setHeader("Content-Type", "application/json")
res.writeHead(200)
res.end(JSON.stringify(status))
return false
}
if (req.url !== '/') {
res.setHeader("Content-Type", "text/plain")
res.writeHead(404)
res.end(`Not Found`)
return false
}
await showRequest(res)
}
const server = createServer(handleRequests)
server.listen(config.verifier_port, config.server_host, () => {
console.log(`Server is running on http://${config.server_host}:${config.verifier_port}`)
})