-
Notifications
You must be signed in to change notification settings - Fork 31
/
server.ts
578 lines (490 loc) · 17.4 KB
/
server.ts
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
import axios from 'axios';
import cors from 'cors';
import express from 'express';
import base64url from 'base64url';
import base64 from 'base-64';
import { JWT } from 'jose';
import * as crypto from 'crypto';
import qs from 'querystring';
import OperationType from '@decentralized-identity/sidetree/dist/lib/core/enums/OperationType';
import AnchoredOperationModel from '@decentralized-identity/sidetree/dist/lib/core/models/AnchoredOperationModel';
import Did from '@decentralized-identity/sidetree/dist/lib/core/versions/latest/Did';
import DocumentComposer from '@decentralized-identity/sidetree/dist/lib/core/versions/latest/DocumentComposer';
import OperationProcessor from '@decentralized-identity/sidetree/dist/lib/core/versions/latest/OperationProcessor';
import { generateEncryptionKey, generateSigningKey, keyGenerators } from './keys-server';
import exampleDr from './fixtures/diagnostic-report.json'
import { VerifierState } from './VerifierState';
import { generateDid, verifyJws, encryptFor } from './dids';
import { issuerReducer, prepareSiopRequest, issueVcsToHolder, parseSiopResponse, CredentialGenerationDetals } from './VerifierLogic';
import * as s1 from '@decentralized-identity/sidetree/dist/lib/core/versions/latest/protocol-parameters.json';
import * as s2 from '@decentralized-identity/sidetree/dist/lib/bitcoin/protocol-parameters.json';
const app = express();
app.use(express.raw({ type: 'application/x-www-form-urlencoded', limit: '5000kb' }));
app.use(express.json({ type: 'application/json', limit: '5000kb'}));
app.use(express.json({ type: 'application/fhir+json', limit: '5000kb'}));
app.use(express.json({ type: 'application/json+fhir', limit: '5000kb'}));
app.use(cors());
const port = 8080; // default port to listen
const fhirBase = 'https://hapi.fhir.org/baseR4';
async function resolveDid(did: string) {
const parsedDid = await Did.create(did, 'ion');
const operationWithMockedAnchorTime: AnchoredOperationModel = {
didUniqueSuffix: parsedDid.uniqueSuffix,
type: OperationType.Create,
transactionTime: 0,
transactionNumber: 0,
operationIndex: 0,
operationBuffer: parsedDid.createOperation.operationBuffer
};
const processor = new OperationProcessor();
const newDidState = await processor.apply(operationWithMockedAnchorTime, undefined);
const document = DocumentComposer.transformToExternalDocument(newDidState, did);
return document;
}
const client = {
get: async (url: string) => (await axios.get(fhirBase + '/' + url)).data
};
type VerifierResponse = VerifierState["siopResponse"]
const siopCache: Record<string, {
ttl: number,
siopStateAfterRequest: VerifierState["siopRequest"],
siopStateAfterResponse: Promise<VerifierState["siopResponse"]>,
responseDeferred: {
pending: boolean,
resolve: (r: VerifierResponse) => undefined;
reject: (any) => undefined;
}
}> = {};
const vcCache: Record<string, {
ttl: number,
vcs: string[]
}> = {};
const ttlMs = 1000 * 60 * 15; // 15 minute ttl
function enforceTtl(cache: Record<string, { ttl: number }>) {
const now = new Date().getTime();
Object.entries(cache).forEach(([k, { ttl }]) => {
if (ttl < now) {
delete cache[k];
}
});
}
/*
setInterval(() => {
enforceTtl(siopCache);
enforceTtl(vcCache)
}, 1000 * 60);
*/
const didConfig = '.well-known/did-configuration.json';
app.get('/' + didConfig, async (req, res, err) => {
try {
const issued = Math.round(new Date().getTime() / 1000 - 10 * 60); // ten minutes ago
const expires = Math.round(new Date().getTime() / 1000 + 10 * 60); // ten minutes from now
const response = {
"@context": "https://identity.foundation/.well-known/contexts/did-configuration-v0.0.jsonld",
"entries": [
await issuerState.sk.sign({
kid: issuerState.did + '#signing-key-1',
}, {
sub: issuerState.did,
iss: issuerState.did,
nbf: issued,
exp: expires,
vc: {
"@context": [
"https://www.w3.org/2018/credentials/v1",
"https://identity.foundation/.well-known/contexts/did-configuration-v0.0.jsonld"],
issuer: issuerState.did,
issuanceDate: new Date(issued * 1000).toISOString(),
expirationDate: new Date(expires * 1000).toISOString(),
type: [
"VerifiableCredential",
"DomainLinkageCredential"
],
credentialSubject: {
id: issuerState.did,
origin: new URL(issuerState.config.serverBase).origin,
}
}
})
]};
res.json(response)
}
catch (e) {
err(e);
}
});
const smartConfig = '.well-known/smart-configuration';
app.get('/api/fhir/' + smartConfig, (req, res) => {
const fullUrl = issuerState.config.serverBase;
const urlFor = relativePath => fullUrl + '/fhir/' + relativePath;
res.json({
'authorization_endpoint': urlFor('$authorize'),
'token_endpoint': urlFor('$token'),
'token_endpoint_auth_methods_supported': ['client_secret_basic'],
'scopes_supported': ['launch/patient', 'patient/*.*', 'user/*.*', 'offline_access'],
'response_types_supported': ['code', 'refresh_token'],
'capabilities': ['launch-ehr', 'client-public', 'client-confidential-symmetric', 'context-ehr-patient']
});
});
const SAMPLE_PATIENT_ID = 'sample-123';
const generateSamplePatientId = () => crypto.randomBytes(8).toString('hex')
app.get('/api/fhir/[\$]authorize', (req, res) => {
const state = req.query.state as string;
const redirectUri = req.query.redirect_uri as string;
const scope = req.query.scope as string;
res.redirect(redirectUri + '?' + qs.encode({
state,
code: JSON.stringify({
patient: generateSamplePatientId(),
scope
})
}));
});
app.post('/api/fhir/[\$]token', (req, res) => {
const { code } = qs.parse(req.body.toString());
const authorizeState = JSON.parse(code as string);
res.json({
'access_token': base64url.encode(crypto.randomBytes(32)),
'token_type': 'bearer',
'expires_in': 3600,
...authorizeState
});
});
const patientToSiopResponse = {};
app.get('/api/fhir/Patient/:patientID/[\$]HealthWallet.connect', async (req, res, err) => {
try {
await dispatchToIssuer(prepareSiopRequest(issuerState));
patientToSiopResponse[req.params.patientID] = issuerState.siopRequest.siopRequestPayload.state;
const openidUrl = issuerState.siopRequest.siopRequestQrCodeUrl;
res.json({
'resourceType': 'Parameters',
'parameter': [{
'name': 'openidUrl',
'valueUri': openidUrl
}]
});
} catch (e) {
err(e);
}
});
async function getVcsForPatient(patientId, details: CredentialGenerationDetals = {
type: 'https://healthwallet.cards#covid19',
presentationContext: 'https://healthwallet.cards#presentation-context-online',
identityClaims: null,
encryptVc: false
}) {
const state = patientToSiopResponse[patientId];
if (!state || siopCache[state].responseDeferred.pending){
throw new OperationOutcomeError("no-did-bound", `No SIOP request has been completed for patient ${patientId}`)
}
const siopResponse = await siopCache[state].siopStateAfterResponse;
const id_token = siopResponse.idTokenRaw;
const withResponse = await issuerReducer(issuerState, await parseSiopResponse(id_token, issuerState));
const afterIssued = await issuerReducer(withResponse, await issueVcsToHolder(withResponse, details));
const vcs = afterIssued.issuedCredentials
return vcs;
}
app.get('/api/fhir/DiagnosticReport', async (req, res, err) => {
try {
// TODO if we need to handle >1 result, remove [0].
// But might just phase this out in favor of $HealthWallet.issueVc
const vc = await getVcsForPatient(req.query.patient)[0];
const fullUrl = issuerState.config.serverBase;
res.json({
resourceType: 'Bundle',
entry: [{
fullUrl: `${fullUrl}/fhir/DiagnosticReport/${exampleDr.id}`,
search: {
mode: "match"
},
resource: {
meta: {
tag: [{
system: "https://healthwallet.cards",
code: "covid19"
}]
},
extension: vc ? [{
"url": "https://healthwallet.cards#vc-attachment",
"valueAttachment": {
"title": "COVID-19 Card for online presentation",
"data": base64.encode(vc)
}
}] : undefined,
...exampleDr,
}
}]
})
} catch (e) {
err(e);
}
});
class OperationOutcomeError extends Error {
public code: string;
public display: string;
constructor(code: string, display: string) {
super();
this.code = code;
this.display = display;
}
}
app.post('/api/fhir/Patient/:patientID/[\$]HealthWallet.issueVc', async (req, res, err) => {
try {
const requestBody = (req.body || {})
if (typeof req.body !== "object"){
throw "No request body found"
}
const requestedCredentialType: string[] = (requestBody.parameter || [])
.filter(p => p.name === 'credentialType')
.map(p => p.valueUri);
if (!requestedCredentialType.length){
throw "No credentialType found in the Parameters"
}
const requestedPresentationContext = (requestBody.parameter || [])
.filter(p => p.name === 'presentationContext')
.map(p => p.valueUri)[0]
if (!requestedPresentationContext){
throw "No presentationContext found in the Parameters"
}
const requestedCredentialIdentityClaims = (requestBody.parameter || [])
.filter(p => p.name === 'includeIdentityClaim')
.map(p => p.valueString)
const requestedEncryptionKeyId = (requestBody.parameter || [])
.filter(p => p.name === 'encryptForKeyId')
.map(p => p.valueString)
if (requestedEncryptionKeyId.length > 0 && requestedEncryptionKeyId[0][0] !== "#") {
throw "Requested encryption key ID must start with '#', e.g., '#encryption-key-1'.";
}
const encryptVc = requestedEncryptionKeyId.length === 1;
let vcs = [];
for (const vcType of requestedCredentialType) {
const newVcs = await getVcsForPatient(req.params.patientID, {
type: vcType,
presentationContext: requestedPresentationContext,
identityClaims: requestedCredentialIdentityClaims.length > 0 ? requestedCredentialIdentityClaims : null,
encryptVc,
encryptVcForKeyId: encryptVc ? requestedEncryptionKeyId[0] : undefined
});
if (!newVcs.length) {
throw "No VC Available matching requested claims, or VC generation failed";
}
vcs = [...vcs, ...newVcs]
}
res.json({
'resourceType': 'Parameters',
'parameter': vcs.map(vc => ({
'name': 'verifiableCredential',
'valueAttachment': {
"data": base64.encode(vc)
}
}))
});
} catch (e) {
err(e);
}
});
const initializeIssuer = async (): Promise<VerifierState> => {
const ek = await generateEncryptionKey();
const sk = await generateSigningKey();
const uk = await generateSigningKey();
const rk = await generateSigningKey();
const did = await generateDid({
encryptionPublicJwk: ek.publicJwk,
signingPublicJwk: sk.publicJwk,
recoveryPublicJwk: rk.publicJwk,
updatePublicJwk: uk.publicJwk,
domains: [new URL(process.env.SERVER_BASE).origin]
});
return {
config: {
serverBase: process.env.SERVER_BASE,
claimsRequired: [],
role: 'issuer',
responseMode: 'form_post',
skipVcPostToServer: true,
postRequest: async (url, body) => {
return new Promise(resolve => {
siopBegin({ body }, { json: resolve });
});
},
keyGenerators
},
ek,
sk,
did: did.did,
didDebugging: did
};
};
let issuerState: VerifierState | null = null;
initializeIssuer().then(i => issuerState = i);
const dispatchToIssuer = async (ePromise) => {
const e = await ePromise;
issuerState = await issuerReducer(issuerState, e);
};
const siopBegin = async (req, res, err?) => {
try {
const id: string = (JWT.decode(req.body.siopRequest) as any).state;
let responseResolve;
let responseReject;
siopCache[id] = {
siopStateAfterRequest: {
siopRequestPayloadSigned: req.body.siopRequest,
siopRequestPayload: null,
siopRequestQrCodeUrl: null,
siopResponsePollingUrl: null
},
siopStateAfterResponse: new Promise((resolveFn, rejectFn) => {
responseResolve = (...args) => {
siopCache[id].responseDeferred.pending = false;
resolveFn(...args);
};
responseReject = (...args) => {
siopCache[id].responseDeferred.pending = false;
rejectFn(...args);
};
}),
responseDeferred: {
pending: true,
resolve: responseResolve,
reject: responseReject
},
ttl: new Date().getTime() + ttlMs
};
res.json({
responsePollingUrl: `/siop/${id}/response`,
...siopCache[id]
});
} catch (e){
err && err(e);
}
};
app.post('/api/siop/begin', siopBegin);
app.get('/api/siop/:id/response', async (req, res, err) => {
try {
const r = await siopCache[req.params.id].siopStateAfterResponse;
res.send({
state: req.params.id,
id_token: r.idTokenRaw
});
} catch(e) {
err(e);
}
});
app.get('/api/siop/:id', async (req, res, err) => {
try {
const r = siopCache[req.params.id].siopStateAfterRequest;
res.send(r.siopRequestPayloadSigned);
} catch (e) {
err(e);
}
});
app.post('/api/siop', async (req, res, err) => {
try {
const body = qs.parse(req.body.toString());
const state = body.state as string;
const idTokenRaw = body.id_token as string;
siopCache[state].responseDeferred.resolve({
idTokenRaw,
idTokenDecrypted: null,
idTokenPayload: null
});
res.send('Received SIOP Response');
} catch(e) {
err(e);
}
});
app.get('/api/did/:did', async (req, res, err) => {
try {
const didLong = decodeURIComponent(req.params.did);
const didDoc = await resolveDid(didLong);
res.json(didDoc.didDocument);
} catch (e) {
err(e)
}
});
app.post('/api/lab/vcs/:did', async (req, res, err) => {
try {
const did = decodeURIComponent(req.params.did);
const vcs = req.body.vcs;
const entry = {
vcs,
ttl: new Date().getTime() + ttlMs
};
vcCache[did] = entry;
res.send('Received VC for DID');
} catch (e) {
err(e);
}
});
app.get('/api/lab/vcs/:did', async (req, res, err) => {
try {
const did = decodeURIComponent(req.params.did);
res.json(vcCache[did]);
} catch (e) {
err(e);
}
});
app.get('/api/test/did-doc', async (req, res, err) => {
try {
const did = issuerState.did;
const didDoc = await resolveDid(did);
res.json(didDoc.didDocument);
} catch (e) {
err(e);
}
});
app.get('/api/test/did-debug', (req, res) => {
res.json(issuerState.didDebugging);
});
app.post('/api/test/validate-jws', async (req, res, err) => {
try {
const jws = req.body.toString()
const jwsVerified = await verifyJws(jws, keyGenerators);
res.json(jwsVerified)
} catch (e) {
err(e);
}
});
app.post('/api/test/validate-jwe', async (req, res, err) => {
try {
const jwe = req.body.toString()
const jwsVerified = await issuerState.ek.decrypt(jwe);
res.json(jwsVerified)
} catch (e) {
err(e);
}
});
app.post('/api/test/encrypt-for-did', async (req, res, err) => {
try {
const did = req.body.did;
const payload = req.body.payload;
const encrypted = await encryptFor(JSON.stringify(payload), did, keyGenerators, req.body.encryptForKeyId);
res.json(encrypted)
} catch (e) {
err(e);
}
});
app.use(express.static('dist/static', {
extensions: ['html']
}));
app.use(function(err, req, res, next) {
console.error(err)
res.status(500).json({
"resourceType": "OperationOutcome",
"issue": [{
"severity": "error",
"code": "processing",
"diagnostics": err + "\n" + err.message + "\n" + err.stack,
"details": {
coding: err.code ? [{
"system": "https://healthwallet.cards",
"code": err.code,
"display": err.display
}] : undefined
},
}]});
})
// start the Express server
app.listen(port, () => {
console.log(`server started at http://localhost:${port}`);
});