-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
252 lines (212 loc) · 5.92 KB
/
server.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
import snakecaseKeys from "snakecase-keys";
import camelcaseKeys from "camelcase-keys";
import { wrapDocument } from "@govtechsg/open-attestation";
import { encryptString, decryptString } from "@govtechsg/oa-encryption";
import Ajv from "ajv";
import express from "express";
import helmet from "helmet";
import fs from "node:fs/promises";
import fsSync from "node:fs";
import gracefulShutdown from "http-graceful-shutdown";
import {
bufferToDataURL,
createPDFBufferFromImage,
createQRCodeBuffer,
} from "./qrcode.js";
import { loadImage } from "@napi-rs/canvas";
import { getQuickJS } from "quickjs-emscripten";
import { dataTransform } from "./data-transform.js";
import { sha256 } from "js-sha256";
function hash(data) {
return sha256.create().update(data).hex("hex");
}
const QuickJS = await getQuickJS();
const CONFIG_FILE = "server-config.json";
if (!fsSync.existsSync(CONFIG_FILE)) {
console.error("server-config.json not found");
process.exit(1);
}
const cfg = JSON.parse(await fs.readFile(CONFIG_FILE, "utf8"));
const app = express();
let QRCODE_BACKGROUND_IMAGE = null;
if ("qrcode" in cfg) {
QRCODE_BACKGROUND_IMAGE = await loadImage(cfg.qrcode);
}
app.use(helmet());
app.use(express.json({ limit: Number.Infinity }));
app.use(express.urlencoded({ extended: false, limit: Number.Infinity }));
app.disable("x-powered-by");
async function decryptHandler({ req, res, next, version }) {
try {
const { document_key, encrypted_document } = req.body;
let rawString;
if (version === 1) {
rawString = decryptString({
...camelcaseKeys(encrypted_document),
key: document_key,
});
} else {
rawString = decryptString({
...encrypted_document,
key: document_key,
});
}
const data = JSON.parse(rawString);
res.json(data);
} catch (e) {
next(e);
}
}
async function encryptHandler({ req, res, next, version }) {
try {
const body = req.body;
const documentKey = body.document_key;
if (!("data" in body) || typeof body.data !== "object") {
res.status(400).json({ message: "INVALID_DATA" });
return;
}
if (documentKey != null && typeof documentKey !== "string") {
res.status(400).json({ message: "INVALID_DOCUMENT_KEY" });
return;
}
const ajv = new Ajv();
const validate = ajv.compile(cfg.schema);
const valid = validate(body.data);
if (!valid) {
res.status(400).json({
message: "INVALID_DATA",
errors: validate.errors,
});
return;
}
const documentData = {
...body.data,
...cfg.template,
};
if ("identity" in cfg) {
try {
const { factory } = cfg.identity;
const num = dataTransform(QuickJS, factory, body.data);
if (num != null) {
documentData.$identity = {
number: hash(num),
};
}
} catch (e) {
res.status(400).json({
message: "INVALID_DATA",
errors: [{ message: e.message }],
});
return;
}
}
const wrappedDocument = wrapDocument(documentData);
const signature = wrappedDocument.signature;
const documentId = body.data[cfg.id_field];
const rawString = JSON.stringify(wrappedDocument);
const { key, ...parts } = encryptString(rawString, documentKey);
if (version === 1) {
res.json({
document_id: documentId,
document_signature: snakecaseKeys(signature),
document_key: key,
encrypted_document: snakecaseKeys(parts),
});
return;
}
res.json({
document_id: documentId,
document_signature: signature,
document_key: key,
encrypted_document: parts,
});
} catch (e) {
next(e);
}
}
async function qrcodeHandler({ req, res, next }) {
try {
if (QRCODE_BACKGROUND_IMAGE == null) {
res.status(400).json({
message:
"server-config.json is outdated. Please contact the support team.",
});
return;
}
let { qrcode_type, document_ref, document_key } = req.body;
if (typeof qrcode_type !== "string") {
res.status(400).json({
message: "qrcode_type is required.",
});
}
qrcode_type = qrcode_type.toLowerCase();
if (qrcode_type !== "png" && qrcode_type !== "pdf") {
res.status(400).json({
message: "invalid qrcode_type. Only pdf or png is allowed!",
});
return;
}
if (typeof document_ref !== "string") {
res.status(400).json({
message: "document_ref is invalid!",
});
return;
}
if (typeof document_key !== "string") {
res.status(400).json({
message: "document_key is invalid!",
});
return;
}
const baseUrl = cfg.template.issuers[0].url;
const url = new URL(`/verify/${document_ref}`, baseUrl);
url.searchParams.set("key", document_key);
let qrcode_data = null;
if (qrcode_type === "png") {
qrcode_data = bufferToDataURL(
createQRCodeBuffer(url.href, QRCODE_BACKGROUND_IMAGE),
"image/png",
);
}
if (qrcode_type === "pdf") {
qrcode_data = bufferToDataURL(
await createPDFBufferFromImage(
createQRCodeBuffer(url.href, QRCODE_BACKGROUND_IMAGE),
[QRCODE_BACKGROUND_IMAGE.width, QRCODE_BACKGROUND_IMAGE.height],
),
"application/pdf",
);
}
if (qrcode_data == null) {
res.status(400).json({ message: "Failed to create the QR code image." });
return;
}
res.json({
qrcode_data,
url: url.href,
});
} catch (e) {
next(e);
}
}
app.post("/api/decrypt-document", async (req, res, next) => {
await decryptHandler({ req, res, next, version: 0 });
});
app.post("/api/encrypt-document", async (req, res, next) => {
await encryptHandler({ req, res, next, version: 0 });
});
app.post("/api/v1/decrypt-document", async (req, res, next) => {
await decryptHandler({ req, res, next, version: 1 });
});
app.post("/api/v1/encrypt-document", async (req, res, next) => {
await encryptHandler({ req, res, next, version: 1 });
});
app.post("/api/v1/qrcode", async (req, res, next) => {
await qrcodeHandler({ req, res, next });
});
app.post("/api/qrcode", async (req, res, next) => {
await qrcodeHandler({ req, res, next });
});
const port = Number.parseInt(process.env.PORT) || 80;
app.listen(port, () => console.info(`http://0.0.0.0:${port}`));
gracefulShutdown(app);