@latex-kit/sign 0.0.0-stage → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +23 -0
- package/README.md +131 -2
- package/cli.d.ts +2 -0
- package/cli.js +179 -0
- package/esm/cli.d.ts +2 -0
- package/esm/cli.js +173 -0
- package/esm/guide.d.ts +29 -0
- package/esm/guide.js +90 -0
- package/esm/index.d.ts +6 -0
- package/esm/index.js +6 -0
- package/esm/server.d.ts +21 -0
- package/esm/server.js +290 -0
- package/esm/stamp.d.ts +12 -0
- package/esm/stamp.js +87 -0
- package/esm/store.d.ts +61 -0
- package/esm/store.js +163 -0
- package/esm/terms.d.ts +9 -0
- package/esm/terms.js +8 -0
- package/esm/types.d.ts +86 -0
- package/esm/types.js +1 -0
- package/guide.d.ts +29 -0
- package/guide.js +94 -0
- package/index.d.ts +6 -0
- package/index.js +22 -0
- package/package.json +47 -3
- package/server.d.ts +21 -0
- package/server.js +294 -0
- package/stamp.d.ts +12 -0
- package/stamp.js +91 -0
- package/store.d.ts +61 -0
- package/store.js +178 -0
- package/terms.d.ts +9 -0
- package/terms.js +11 -0
- package/types.d.ts +86 -0
- package/types.js +4 -0
package/esm/server.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Server } from 'http';
|
|
2
|
+
import { FormField } from './types';
|
|
3
|
+
/** Checks boxes drawn in the placing page before they are written to disk. */
|
|
4
|
+
export type PageSize = {
|
|
5
|
+
width: number;
|
|
6
|
+
height: number;
|
|
7
|
+
};
|
|
8
|
+
export declare function cleanFields(input: unknown, pageSizes: PageSize[]): FormField[];
|
|
9
|
+
/**
|
|
10
|
+
* The placing page: draw boxes on any PDF and save them beside it.
|
|
11
|
+
* `sessions` maps a random key to a session; the CLI makes one per run.
|
|
12
|
+
*/
|
|
13
|
+
export interface PlacingSession {
|
|
14
|
+
pdf: string;
|
|
15
|
+
/** Where saving writes the boxes. */
|
|
16
|
+
fieldsFile: string;
|
|
17
|
+
pageSizes: PageSize[];
|
|
18
|
+
}
|
|
19
|
+
export declare function createSignServer({ placing }?: {
|
|
20
|
+
placing?: Map<string, PlacingSession>;
|
|
21
|
+
}): Server;
|
package/esm/server.js
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
// The signing server. No framework: a handful of routes over http.
|
|
2
|
+
//
|
|
3
|
+
// GET /api/sign/:token what this signer needs: title, terms, their boxes
|
|
4
|
+
// GET /api/sign/:token/pdf the document as it stands
|
|
5
|
+
// POST /api/sign/:token { signaturePng, agreed: true, location, values } -> stamps and records
|
|
6
|
+
// POST /api/sign/:token/decline { reason } -> nobody can sign after that
|
|
7
|
+
// GET /api/place/:key[/pdf] the placing page's PDF and saved boxes; PUT saves them
|
|
8
|
+
// GET /sign/:token, /place/:key the pages (from @latex-kit/sign-web)
|
|
9
|
+
//
|
|
10
|
+
// Every /api/sign call needs the signer's access code in the x-access-code header.
|
|
11
|
+
// The audit facts (IP address, browser, time) are taken here, on the server,
|
|
12
|
+
// never from what the browser says about itself. Location is the exception: only
|
|
13
|
+
// the browser knows it, so it is recorded as "reported by the browser".
|
|
14
|
+
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
|
15
|
+
import { createServer } from 'http';
|
|
16
|
+
import { dirname, extname, join, normalize } from 'path';
|
|
17
|
+
import { addCertificate, stampSigner } from './stamp';
|
|
18
|
+
import { codeMatches, findByToken, load, MAX_CODE_TRIES, pdfPath, save, seal, sha256 } from './store';
|
|
19
|
+
import { TERMS } from './terms';
|
|
20
|
+
import { FIELD_TYPES } from './types';
|
|
21
|
+
/** The built pages: LATEX_KIT_SIGN_WEB, else the @latex-kit/sign-web package. */
|
|
22
|
+
function webDir() {
|
|
23
|
+
if (process.env.LATEX_KIT_SIGN_WEB)
|
|
24
|
+
return process.env.LATEX_KIT_SIGN_WEB;
|
|
25
|
+
try {
|
|
26
|
+
return join(dirname(require.resolve('@latex-kit/sign-web/package.json')), 'dist');
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png' };
|
|
33
|
+
// The signing link is the secret, so it must not leak in a Referer header or sit in a cache;
|
|
34
|
+
// and the page must not be framed by another site.
|
|
35
|
+
const headers = {
|
|
36
|
+
'referrer-policy': 'no-referrer',
|
|
37
|
+
'cache-control': 'no-store',
|
|
38
|
+
'x-content-type-options': 'nosniff',
|
|
39
|
+
'x-frame-options': 'DENY',
|
|
40
|
+
'content-security-policy': "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; worker-src 'self' blob:; frame-ancestors 'none'",
|
|
41
|
+
'permissions-policy': 'geolocation=(self)',
|
|
42
|
+
};
|
|
43
|
+
class HttpError extends Error {
|
|
44
|
+
status;
|
|
45
|
+
extra;
|
|
46
|
+
constructor(status, message, extra) {
|
|
47
|
+
super(message);
|
|
48
|
+
this.status = status;
|
|
49
|
+
this.extra = extra;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const json = (res, status, body) => {
|
|
53
|
+
res.writeHead(status, { ...headers, 'content-type': 'application/json' });
|
|
54
|
+
res.end(JSON.stringify(body));
|
|
55
|
+
};
|
|
56
|
+
const fail = (status, message, extra) => new HttpError(status, message, extra);
|
|
57
|
+
/** Behind a proxy we trust (LEGAL_KIT_SIGN_TRUST_PROXY=1), the first forwarded address; else the socket's. */
|
|
58
|
+
function clientIp(req) {
|
|
59
|
+
const fwd = req.headers['x-forwarded-for'];
|
|
60
|
+
if (process.env.LEGAL_KIT_SIGN_TRUST_PROXY === '1' && fwd)
|
|
61
|
+
return String(fwd).split(',')[0].trim();
|
|
62
|
+
return req.socket.remoteAddress ?? 'unknown';
|
|
63
|
+
}
|
|
64
|
+
async function body(req, limit = 1_500_000) {
|
|
65
|
+
const chunks = [];
|
|
66
|
+
let size = 0;
|
|
67
|
+
for await (const c of req) {
|
|
68
|
+
size += c.length;
|
|
69
|
+
if (size > limit)
|
|
70
|
+
throw fail(413, 'That is too large.');
|
|
71
|
+
chunks.push(c);
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
throw fail(400, 'Could not read the request.');
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
// One change to an envelope at a time, so two requests cannot both sign.
|
|
81
|
+
const queues = new Map();
|
|
82
|
+
function oneAtATime(id, work) {
|
|
83
|
+
const next = (queues.get(id) || Promise.resolve()).then(work, work);
|
|
84
|
+
queues.set(id, next.catch(() => { }));
|
|
85
|
+
return next;
|
|
86
|
+
}
|
|
87
|
+
const event = (envelope, req, what, more = {}) => envelope.events.push({ at: new Date().toISOString(), what, ip: clientIp(req), ...more });
|
|
88
|
+
/** Is this link still usable, and did the caller give the right access code? */
|
|
89
|
+
function gate(req, { envelope, signer }) {
|
|
90
|
+
if (envelope.declinedAt)
|
|
91
|
+
throw fail(410, 'This document was declined, so it can no longer be signed.');
|
|
92
|
+
if (!signer.signedAt && new Date(envelope.expiresAt) < new Date())
|
|
93
|
+
throw fail(410, 'This signing link has expired. Ask the sender for a new one.');
|
|
94
|
+
if (signer.failedCodes >= MAX_CODE_TRIES)
|
|
95
|
+
throw fail(423, 'Too many wrong codes. This link is locked; ask the sender for a new one.');
|
|
96
|
+
const code = req.headers['x-access-code'];
|
|
97
|
+
const waitingFor = envelope.ordered && !signer.signedAt && envelope.signers.slice(0, envelope.signers.indexOf(signer)).find((s) => !s.signedAt);
|
|
98
|
+
if (!code)
|
|
99
|
+
throw fail(401, 'Enter your access code.', { needCode: true });
|
|
100
|
+
if (!codeMatches(envelope, signer, String(code))) {
|
|
101
|
+
signer.failedCodes += 1;
|
|
102
|
+
event(envelope, req, 'wrong code', { who: signer.who });
|
|
103
|
+
save(envelope);
|
|
104
|
+
const left = MAX_CODE_TRIES - signer.failedCodes;
|
|
105
|
+
throw fail(left ? 401 : 423, left ? `That code is not right. ${left} ${left === 1 ? 'try' : 'tries'} left.` : 'Too many wrong codes. This link is locked.', { needCode: true });
|
|
106
|
+
}
|
|
107
|
+
if (waitingFor)
|
|
108
|
+
throw fail(409, `It is not your turn yet: ${waitingFor.name} signs first. You will be able to sign once they have.`);
|
|
109
|
+
}
|
|
110
|
+
const view = ({ envelope, signer }) => ({
|
|
111
|
+
title: envelope.title,
|
|
112
|
+
terms: TERMS,
|
|
113
|
+
expiresAt: envelope.expiresAt,
|
|
114
|
+
signer: { who: signer.who, name: signer.name, email: signer.email, signedAt: signer.signedAt },
|
|
115
|
+
// `index` is the field's place in the envelope: typed values are sent back under it
|
|
116
|
+
fields: envelope.fields.map((f, index) => ({ ...f, index })).filter((f) => f.who === signer.who),
|
|
117
|
+
others: envelope.signers.filter((s) => s !== signer).map((s) => ({ who: s.who, name: s.name, signed: Boolean(s.signedAt) })),
|
|
118
|
+
completed: Boolean(envelope.completedAt),
|
|
119
|
+
});
|
|
120
|
+
/** Only what we expect: a real position, or a short note on why there is none. */
|
|
121
|
+
function cleanLocation(l) {
|
|
122
|
+
const n = (v, lo, hi) => typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi;
|
|
123
|
+
if (l && n(l.latitude, -90, 90) && n(l.longitude, -180, 180))
|
|
124
|
+
return { latitude: l.latitude, longitude: l.longitude, accuracyMeters: n(l.accuracy, 0, 1e7) ? Math.round(l.accuracy) : null, source: 'reported by the browser' };
|
|
125
|
+
const why = ['denied', 'unavailable', 'timeout', 'unsupported'].includes(l?.declined) ? l.declined : 'not given';
|
|
126
|
+
return { declined: why };
|
|
127
|
+
}
|
|
128
|
+
async function sign(req, found) {
|
|
129
|
+
const { envelope, signer } = found;
|
|
130
|
+
if (signer.signedAt)
|
|
131
|
+
throw fail(409, 'You have already signed this document.');
|
|
132
|
+
const input = await body(req);
|
|
133
|
+
if (input.agreed !== true || input.termsVersion !== TERMS.version)
|
|
134
|
+
throw fail(400, 'You need to agree to the terms shown before signing.');
|
|
135
|
+
const m = /^data:image\/png;base64,([A-Za-z0-9+/=]+)$/.exec(input.signaturePng || '');
|
|
136
|
+
const png = m && Buffer.from(m[1], 'base64');
|
|
137
|
+
const mustDraw = envelope.fields.some((f) => f.who === signer.who && f.type === 'signature');
|
|
138
|
+
if (mustDraw && (!png || png.length < 67 || png.readUInt32BE(0) !== 0x89504e47))
|
|
139
|
+
throw fail(400, 'A drawn or typed signature is required.');
|
|
140
|
+
// what the signer typed into their text and initials boxes; every one is required
|
|
141
|
+
const values = {};
|
|
142
|
+
const typed = {};
|
|
143
|
+
for (const [i, f] of envelope.fields.entries()) {
|
|
144
|
+
if (f.who !== signer.who || (f.type !== 'text' && f.type !== 'initials'))
|
|
145
|
+
continue;
|
|
146
|
+
const v = String(input.values?.[i] ?? '').trim();
|
|
147
|
+
if (!v || v.length > (f.type === 'initials' ? 6 : 200))
|
|
148
|
+
throw fail(400, f.type === 'initials' ? 'Please type your initials in every initials box.' : 'Please fill in every text box.');
|
|
149
|
+
if (!/^[\x20-\x7e\xa0-\xff]+$/.test(v))
|
|
150
|
+
throw fail(400, 'Only Latin letters, numbers and punctuation can be typed into a box for now.');
|
|
151
|
+
values[i] = v;
|
|
152
|
+
typed[`${f.label || f.type} (page ${f.page})`] = v;
|
|
153
|
+
}
|
|
154
|
+
const before = readFileSync(pdfPath(envelope));
|
|
155
|
+
const signedAt = new Date().toISOString();
|
|
156
|
+
let after;
|
|
157
|
+
try {
|
|
158
|
+
after = Buffer.from(await stampSigner(before, envelope.fields, signer.who, { signaturePng: mustDraw ? png : null, signedAt, values }));
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
throw fail(400, 'That signature image could not be read. Please draw it again.');
|
|
162
|
+
}
|
|
163
|
+
Object.assign(signer, {
|
|
164
|
+
signedAt,
|
|
165
|
+
ip: clientIp(req),
|
|
166
|
+
userAgent: String(req.headers['user-agent'] || '').slice(0, 300),
|
|
167
|
+
consent: { agreed: true, termsVersion: TERMS.version, termsSha256: sha256(TERMS.text.join('\n')), text: TERMS.text },
|
|
168
|
+
location: cleanLocation(input.location),
|
|
169
|
+
values: typed,
|
|
170
|
+
accessCodeUsed: true,
|
|
171
|
+
sha256Before: sha256(before),
|
|
172
|
+
sha256After: sha256(after),
|
|
173
|
+
});
|
|
174
|
+
event(envelope, req, 'signed', { who: signer.who });
|
|
175
|
+
if (envelope.signers.every((s) => s.signedAt)) {
|
|
176
|
+
envelope.completedAt = new Date().toISOString();
|
|
177
|
+
after = Buffer.from(await addCertificate(after, envelope));
|
|
178
|
+
envelope.sha256Final = sha256(after);
|
|
179
|
+
event(envelope, req, 'completed');
|
|
180
|
+
}
|
|
181
|
+
writeFileSync(pdfPath(envelope), after);
|
|
182
|
+
save(envelope);
|
|
183
|
+
if (envelope.completedAt)
|
|
184
|
+
seal(envelope);
|
|
185
|
+
return view(found);
|
|
186
|
+
}
|
|
187
|
+
async function decline(req, found) {
|
|
188
|
+
const { envelope, signer } = found;
|
|
189
|
+
if (signer.signedAt || envelope.completedAt)
|
|
190
|
+
throw fail(409, 'You have already signed this document.');
|
|
191
|
+
const input = await body(req);
|
|
192
|
+
envelope.declinedAt = new Date().toISOString();
|
|
193
|
+
envelope.declinedBy = { who: signer.who, reason: String(input.reason || '').slice(0, 500) };
|
|
194
|
+
event(envelope, req, 'declined', { who: signer.who });
|
|
195
|
+
save(envelope);
|
|
196
|
+
return { declined: true };
|
|
197
|
+
}
|
|
198
|
+
function page(res, path) {
|
|
199
|
+
const dist = webDir();
|
|
200
|
+
let file = dist ? normalize(join(dist, path)) : '';
|
|
201
|
+
if (dist && (!file.startsWith(dist) || !existsSync(file) || !extname(file)))
|
|
202
|
+
file = join(dist, 'index.html');
|
|
203
|
+
if (!dist || !existsSync(file)) {
|
|
204
|
+
res.writeHead(503, { 'content-type': 'text/plain' });
|
|
205
|
+
res.end('The signing pages are not built. Install @latex-kit/sign-web, or in the latex-kit repo run: pnpm --filter @latex-kit/sign-web build');
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const html = extname(file) === '.html';
|
|
209
|
+
res.writeHead(200, { ...headers, 'cache-control': html ? 'no-store' : 'public, max-age=31536000, immutable', 'content-type': types[extname(file)] || 'application/octet-stream' });
|
|
210
|
+
res.end(readFileSync(file));
|
|
211
|
+
}
|
|
212
|
+
export function cleanFields(input, pageSizes) {
|
|
213
|
+
if (!Array.isArray(input) || input.length > 500)
|
|
214
|
+
throw fail(400, 'Expected a list of fields.');
|
|
215
|
+
return input.map((f) => {
|
|
216
|
+
const size = pageSizes[f.page - 1];
|
|
217
|
+
const ok = (v) => typeof v === 'number' && Number.isFinite(v);
|
|
218
|
+
if (!size || !FIELD_TYPES.includes(f.type) || !/^[\w-]{1,40}$/.test(f.who || '') || ![f.x, f.y, f.width, f.height].every(ok))
|
|
219
|
+
throw fail(400, 'A field is not valid.');
|
|
220
|
+
if (f.width < 4 || f.height < 4 || f.x < 0 || f.y < 0 || f.x + f.width > size.width + 1 || f.y + f.height > size.height + 1)
|
|
221
|
+
throw fail(400, 'A field is off the page.');
|
|
222
|
+
const r = (v) => Math.round(v * 100) / 100;
|
|
223
|
+
const label = typeof f.label === 'string' && f.label.trim() ? { label: f.label.trim().slice(0, 60) } : {};
|
|
224
|
+
return { type: f.type, who: f.who, ...label, page: f.page, x: r(f.x), y: r(f.y), width: r(f.width), height: r(f.height) };
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
async function place(req, res, sessions, key, rest) {
|
|
228
|
+
const s = sessions.get(key);
|
|
229
|
+
if (!s)
|
|
230
|
+
throw fail(404, 'This placing session is not open. Start it again from the command line.');
|
|
231
|
+
if (rest === '/pdf') {
|
|
232
|
+
res.writeHead(200, { ...headers, 'content-type': 'application/pdf' });
|
|
233
|
+
res.end(readFileSync(s.pdf));
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
if (req.method === 'PUT') {
|
|
237
|
+
const fields = cleanFields((await body(req)).fields, s.pageSizes);
|
|
238
|
+
writeFileSync(s.fieldsFile, JSON.stringify(fields, null, 2) + '\n');
|
|
239
|
+
return json(res, 200, { saved: fields.length, file: s.fieldsFile });
|
|
240
|
+
}
|
|
241
|
+
json(res, 200, { title: s.pdf.split('/').pop(), types: FIELD_TYPES, fields: existsSync(s.fieldsFile) ? JSON.parse(readFileSync(s.fieldsFile, 'utf8')) : [] });
|
|
242
|
+
}
|
|
243
|
+
export function createSignServer({ placing = new Map() } = {}) {
|
|
244
|
+
return createServer(async (req, res) => {
|
|
245
|
+
try {
|
|
246
|
+
const url = new URL(req.url ?? '/', 'http://x');
|
|
247
|
+
const pl = /^\/api\/place\/([\w-]{20,64})(\/pdf)?$/.exec(url.pathname);
|
|
248
|
+
if (pl)
|
|
249
|
+
return await place(req, res, placing, pl[1], pl[2]);
|
|
250
|
+
const api = /^\/api\/sign\/([\w-]{20,64})(\/pdf|\/decline)?$/.exec(url.pathname);
|
|
251
|
+
if (!api) {
|
|
252
|
+
if (url.pathname.startsWith('/api/'))
|
|
253
|
+
throw fail(404, 'This signing link is not valid.');
|
|
254
|
+
return page(res, url.pathname);
|
|
255
|
+
}
|
|
256
|
+
const first = findByToken(api[1]);
|
|
257
|
+
if (!first)
|
|
258
|
+
throw fail(404, 'This signing link is not valid.');
|
|
259
|
+
const result = await oneAtATime(first.envelope.id, async () => {
|
|
260
|
+
// read again inside the queue: an earlier request may have changed it
|
|
261
|
+
const envelope = load(first.envelope.id);
|
|
262
|
+
const found = { envelope, signer: envelope.signers.find((s) => s.who === first.signer.who) };
|
|
263
|
+
gate(req, found);
|
|
264
|
+
if (api[2] === '/pdf')
|
|
265
|
+
return { pdf: readFileSync(pdfPath(envelope)) };
|
|
266
|
+
if (api[2] === '/decline' && req.method === 'POST')
|
|
267
|
+
return decline(req, found);
|
|
268
|
+
if (req.method === 'POST')
|
|
269
|
+
return sign(req, found);
|
|
270
|
+
if (req.method !== 'GET')
|
|
271
|
+
throw fail(405, 'Not allowed.');
|
|
272
|
+
event(envelope, req, 'opened', { who: found.signer.who });
|
|
273
|
+
save(envelope);
|
|
274
|
+
return view(found);
|
|
275
|
+
});
|
|
276
|
+
if (result.pdf) {
|
|
277
|
+
res.writeHead(200, { ...headers, 'content-type': 'application/pdf' });
|
|
278
|
+
res.end(result.pdf);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
json(res, 200, result);
|
|
282
|
+
}
|
|
283
|
+
catch (e) {
|
|
284
|
+
const known = e instanceof HttpError ? e : null;
|
|
285
|
+
if (!known)
|
|
286
|
+
console.error(e);
|
|
287
|
+
json(res, known?.status ?? 500, { error: known ? known.message : 'Something went wrong.', ...(known?.extra ?? {}) });
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
}
|
package/esm/stamp.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Envelope, FormField } from './types';
|
|
2
|
+
/** Stamps every box that belongs to `who`. Returns the new PDF bytes. */
|
|
3
|
+
export interface StampInput {
|
|
4
|
+
/** A PNG of the drawn or typed signature; null when the signer has no signature box. */
|
|
5
|
+
signaturePng: Uint8Array | null;
|
|
6
|
+
signedAt: string;
|
|
7
|
+
/** What was typed into text and initials boxes, by the field's index. */
|
|
8
|
+
values?: Record<number, string>;
|
|
9
|
+
}
|
|
10
|
+
export declare function stampSigner(pdfBytes: Uint8Array, fields: FormField[], who: string, { signaturePng, signedAt, values }: StampInput): Promise<Uint8Array>;
|
|
11
|
+
/** Appends a page listing who signed, when, from where, and the file hashes. */
|
|
12
|
+
export declare function addCertificate(pdfBytes: Uint8Array, envelope: Envelope): Promise<Uint8Array>;
|
package/esm/stamp.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Puts a signer's signature and date into the PDF, and adds the certificate page.
|
|
2
|
+
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
|
|
3
|
+
const longDate = (iso) => new Date(iso).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' });
|
|
4
|
+
export async function stampSigner(pdfBytes, fields, who, { signaturePng, signedAt, values = {} }) {
|
|
5
|
+
const pdf = await PDFDocument.load(pdfBytes);
|
|
6
|
+
const font = await pdf.embedFont(StandardFonts.Helvetica);
|
|
7
|
+
const image = signaturePng ? await pdf.embedPng(signaturePng) : null;
|
|
8
|
+
const italic = await pdf.embedFont(StandardFonts.HelveticaOblique);
|
|
9
|
+
/** Text set on the box's bottom edge, shrunk if it would run past the box. */
|
|
10
|
+
const write = (page, f, text, fnt, size = 10) => {
|
|
11
|
+
const fit = Math.min(size, f.height - 2, (size * (f.width - 4)) / Math.max(1, fnt.widthOfTextAtSize(text, size)));
|
|
12
|
+
page.drawText(text, { x: f.x + 2, y: f.y + 3, size: Math.max(5, fit), font: fnt, color: rgb(0, 0, 0) });
|
|
13
|
+
};
|
|
14
|
+
for (const [i, f] of fields.entries()) {
|
|
15
|
+
if (f.who !== who)
|
|
16
|
+
continue;
|
|
17
|
+
const page = pdf.getPage(f.page - 1);
|
|
18
|
+
if (f.type === 'text')
|
|
19
|
+
write(page, f, values[i], font);
|
|
20
|
+
else if (f.type === 'initials')
|
|
21
|
+
write(page, f, values[i], italic, 14);
|
|
22
|
+
else if (f.type === 'signature' && image) {
|
|
23
|
+
// fit inside the box, keeping the drawing's shape, resting on the line
|
|
24
|
+
const scale = Math.min(f.width / image.width, f.height / image.height);
|
|
25
|
+
page.drawImage(image, { x: f.x + 2, y: f.y, width: image.width * scale, height: image.height * scale });
|
|
26
|
+
}
|
|
27
|
+
else if (f.type === 'date') {
|
|
28
|
+
write(page, f, longDate(signedAt), font);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return pdf.save();
|
|
32
|
+
}
|
|
33
|
+
/** Appends a page listing who signed, when, from where, and the file hashes. */
|
|
34
|
+
export async function addCertificate(pdfBytes, envelope) {
|
|
35
|
+
const pdf = await PDFDocument.load(pdfBytes);
|
|
36
|
+
const font = await pdf.embedFont(StandardFonts.Helvetica);
|
|
37
|
+
const bold = await pdf.embedFont(StandardFonts.HelveticaBold);
|
|
38
|
+
const page = pdf.addPage([612, 792]);
|
|
39
|
+
let y = 730;
|
|
40
|
+
const line = (text, { f = font, size = 9, gap = 13 } = {}) => {
|
|
41
|
+
page.drawText(String(text).slice(0, 110), { x: 54, y, size, font: f });
|
|
42
|
+
y -= gap;
|
|
43
|
+
};
|
|
44
|
+
line('Signing certificate', { f: bold, size: 16, gap: 24 });
|
|
45
|
+
line(`Document: ${envelope.title}`);
|
|
46
|
+
line(`Envelope: ${envelope.id}`);
|
|
47
|
+
line(`Sent for signing: ${envelope.createdAt}`);
|
|
48
|
+
line(`SHA-256 of the document before signing: ${envelope.sha256Original}`, { gap: 22 });
|
|
49
|
+
for (const s of envelope.signers) {
|
|
50
|
+
line(`${s.name} (${s.who})`, { f: bold, size: 11, gap: 15 });
|
|
51
|
+
line(`Email the signing link was issued to: ${s.email}`);
|
|
52
|
+
line(`Signed: ${s.signedAt} (UTC)`);
|
|
53
|
+
line(`IP address: ${s.ip}`);
|
|
54
|
+
line(`Browser: ${s.userAgent}`);
|
|
55
|
+
const l = (s.location || {});
|
|
56
|
+
line(`Location: ${l.latitude !== undefined ? `${l.latitude.toFixed(5)}, ${l.longitude.toFixed(5)} (within ${l.accuracyMeters ?? '?'} m, reported by the browser)` : `not recorded (${l.declined || 'not given'})`}`);
|
|
57
|
+
for (const [label, v] of Object.entries(s.values || {}))
|
|
58
|
+
line(`Typed in "${label}": ${v}`);
|
|
59
|
+
line(`Identity: opened with a private link and a one-time access code`);
|
|
60
|
+
line(`Agreed to the signing terms, version ${s.consent?.termsVersion} (SHA-256 ${String(s.consent?.termsSha256).slice(0, 16)}…)`);
|
|
61
|
+
line(`SHA-256 before this signature: ${s.sha256Before}`);
|
|
62
|
+
line(`SHA-256 after this signature: ${s.sha256After}`, { gap: 22 });
|
|
63
|
+
}
|
|
64
|
+
y -= 6;
|
|
65
|
+
line('Signing terms each signer agreed to', { f: bold, size: 10, gap: 14 });
|
|
66
|
+
for (const t of envelope.signers[0]?.consent?.text || [])
|
|
67
|
+
for (const part of wrap(t, 108))
|
|
68
|
+
line(part, { size: 8, gap: 11 });
|
|
69
|
+
y -= 6;
|
|
70
|
+
line('The final file hash and this record are sealed by the signing server; `latex-kit-sign verify` checks them.', { size: 8 });
|
|
71
|
+
return pdf.save();
|
|
72
|
+
}
|
|
73
|
+
function wrap(text, width) {
|
|
74
|
+
const out = [];
|
|
75
|
+
let cur = '';
|
|
76
|
+
for (const word of text.split(' ')) {
|
|
77
|
+
if ((cur + ' ' + word).trim().length > width) {
|
|
78
|
+
out.push(cur);
|
|
79
|
+
cur = word;
|
|
80
|
+
}
|
|
81
|
+
else
|
|
82
|
+
cur = (cur + ' ' + word).trim();
|
|
83
|
+
}
|
|
84
|
+
if (cur)
|
|
85
|
+
out.push(cur);
|
|
86
|
+
return out;
|
|
87
|
+
}
|
package/esm/store.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { Envelope, FormField, Secret } from './types';
|
|
2
|
+
/** Where envelopes live: LATEX_KIT_SIGN_DATA, else `.latex-kit-sign/` in the current folder. */
|
|
3
|
+
export declare const dataDir: () => string;
|
|
4
|
+
export declare const sha256: (bytes: string | Uint8Array) => string;
|
|
5
|
+
export declare const MAX_CODE_TRIES = 5;
|
|
6
|
+
export interface CreateOptions {
|
|
7
|
+
/** A PDF, from latex-kit or anywhere else. */
|
|
8
|
+
pdfPath: string;
|
|
9
|
+
/** Its boxes: the `.form.json` beside it, or ones drawn with `place`. */
|
|
10
|
+
fields: FormField[];
|
|
11
|
+
/** Every `who` in the fields needs one. Their order is the signing order when `ordered`. */
|
|
12
|
+
signers: Record<string, {
|
|
13
|
+
name: string;
|
|
14
|
+
email: string;
|
|
15
|
+
}>;
|
|
16
|
+
title?: string;
|
|
17
|
+
/** How long the links work. Default 14. */
|
|
18
|
+
days?: number;
|
|
19
|
+
ordered?: boolean;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Make an envelope. Returns it with `secrets`: each signer's link token and
|
|
23
|
+
* access code. This is the only time they exist in clear; hand them out.
|
|
24
|
+
*/
|
|
25
|
+
export declare function createEnvelope({ pdfPath, fields, signers, title, days, ordered }: CreateOptions): {
|
|
26
|
+
envelope: Envelope;
|
|
27
|
+
secrets: Secret[];
|
|
28
|
+
};
|
|
29
|
+
/** Written to a temporary file and renamed, so a crash never leaves half a record. */
|
|
30
|
+
export declare function save(envelope: Envelope): void;
|
|
31
|
+
export declare const pdfPath: (envelope: Envelope, which?: "current" | "original") => string;
|
|
32
|
+
export declare function load(id: string): Envelope | null;
|
|
33
|
+
/** The envelope and signer a signing link belongs to. */
|
|
34
|
+
export declare function findByToken(token: string): {
|
|
35
|
+
envelope: Envelope;
|
|
36
|
+
signer: Envelope['signers'][number];
|
|
37
|
+
} | null;
|
|
38
|
+
/** Everyone's envelopes, newest first. */
|
|
39
|
+
export declare function listEnvelopes(): Envelope[];
|
|
40
|
+
/**
|
|
41
|
+
* A fresh link and code for one signer who has not signed: the old ones stop
|
|
42
|
+
* working, a lock from wrong codes is cleared, and the expiry starts again.
|
|
43
|
+
*/
|
|
44
|
+
export declare function reissue(id: string, who: string, days?: number): {
|
|
45
|
+
envelope: Envelope;
|
|
46
|
+
secret: Secret;
|
|
47
|
+
};
|
|
48
|
+
export declare const codeMatches: (envelope: Envelope, signer: Envelope["signers"][number], code: string) => boolean;
|
|
49
|
+
export interface Seal {
|
|
50
|
+
algorithm: 'ed25519';
|
|
51
|
+
publicKey: string;
|
|
52
|
+
signature: string;
|
|
53
|
+
sealedAt: string;
|
|
54
|
+
}
|
|
55
|
+
export declare function seal(envelope: Envelope): Seal;
|
|
56
|
+
/** Checks a finished envelope: the PDF still has the recorded hash, and the record still matches its seal. */
|
|
57
|
+
export declare function verifyEnvelope(id: string, pdfFile?: string): {
|
|
58
|
+
ok: boolean;
|
|
59
|
+
problems: string[];
|
|
60
|
+
envelope?: Envelope;
|
|
61
|
+
};
|
package/esm/store.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, randomInt, scryptSync, sign as edSign, timingSafeEqual, verify as edVerify } from 'crypto';
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'fs';
|
|
3
|
+
import { basename, dirname, join } from 'path';
|
|
4
|
+
/** Where envelopes live: LATEX_KIT_SIGN_DATA, else `.latex-kit-sign/` in the current folder. */
|
|
5
|
+
export const dataDir = () => process.env.LATEX_KIT_SIGN_DATA || join(process.cwd(), '.latex-kit-sign');
|
|
6
|
+
export const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
7
|
+
const codeHash = (code, salt) => scryptSync(String(code), salt, 32).toString('hex');
|
|
8
|
+
const same = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
9
|
+
export const MAX_CODE_TRIES = 5;
|
|
10
|
+
/**
|
|
11
|
+
* Make an envelope. Returns it with `secrets`: each signer's link token and
|
|
12
|
+
* access code. This is the only time they exist in clear; hand them out.
|
|
13
|
+
*/
|
|
14
|
+
export function createEnvelope({ pdfPath, fields, signers, title, days = 14, ordered = false }) {
|
|
15
|
+
const inFields = [...new Set(fields.map((f) => f.who))];
|
|
16
|
+
for (const who of inFields)
|
|
17
|
+
if (!signers[who])
|
|
18
|
+
throw new Error(`no signer given for "${who}"`);
|
|
19
|
+
// the order the caller listed them in, which is the signing order when `ordered`
|
|
20
|
+
const roles = Object.keys(signers).filter((who) => inFields.includes(who));
|
|
21
|
+
const id = randomBytes(8).toString('hex');
|
|
22
|
+
const dir = join(dataDir(), id);
|
|
23
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
24
|
+
const pdf = readFileSync(pdfPath);
|
|
25
|
+
writeFileSync(join(dir, 'original.pdf'), pdf);
|
|
26
|
+
writeFileSync(join(dir, 'current.pdf'), pdf);
|
|
27
|
+
const now = new Date();
|
|
28
|
+
const secrets = roles.map((who) => ({ who, token: randomBytes(24).toString('base64url'), code: String(randomInt(0, 1_000_000)).padStart(6, '0') }));
|
|
29
|
+
const envelope = {
|
|
30
|
+
id,
|
|
31
|
+
title: title || basename(pdfPath, '.pdf'),
|
|
32
|
+
createdAt: now.toISOString(),
|
|
33
|
+
expiresAt: new Date(now.getTime() + days * 86_400_000).toISOString(),
|
|
34
|
+
sha256Original: sha256(pdf),
|
|
35
|
+
ordered,
|
|
36
|
+
fields,
|
|
37
|
+
signers: secrets.map(({ who, token, code }) => ({
|
|
38
|
+
who,
|
|
39
|
+
name: signers[who].name,
|
|
40
|
+
email: signers[who].email,
|
|
41
|
+
tokenHash: sha256(token),
|
|
42
|
+
codeHash: codeHash(code, id + who),
|
|
43
|
+
failedCodes: 0,
|
|
44
|
+
signedAt: null,
|
|
45
|
+
})),
|
|
46
|
+
events: [{ at: now.toISOString(), what: 'created' }],
|
|
47
|
+
completedAt: null,
|
|
48
|
+
declinedAt: null,
|
|
49
|
+
};
|
|
50
|
+
save(envelope);
|
|
51
|
+
return { envelope, secrets };
|
|
52
|
+
}
|
|
53
|
+
/** Written to a temporary file and renamed, so a crash never leaves half a record. */
|
|
54
|
+
export function save(envelope) {
|
|
55
|
+
const file = join(dataDir(), envelope.id, 'envelope.json');
|
|
56
|
+
writeFileSync(`${file}.tmp`, JSON.stringify(envelope, null, 2) + '\n', { mode: 0o600 });
|
|
57
|
+
renameSync(`${file}.tmp`, file);
|
|
58
|
+
}
|
|
59
|
+
export const pdfPath = (envelope, which = 'current') => join(dataDir(), envelope.id, `${which}.pdf`);
|
|
60
|
+
export function load(id) {
|
|
61
|
+
const file = join(dataDir(), id, 'envelope.json');
|
|
62
|
+
return /^[0-9a-f]{16}$/.test(id) && existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : null;
|
|
63
|
+
}
|
|
64
|
+
/** The envelope and signer a signing link belongs to. */
|
|
65
|
+
export function findByToken(token) {
|
|
66
|
+
if (!existsSync(dataDir()))
|
|
67
|
+
return null;
|
|
68
|
+
const hash = sha256(token);
|
|
69
|
+
for (const id of readdirSync(dataDir())) {
|
|
70
|
+
const envelope = load(id);
|
|
71
|
+
const signer = envelope?.signers.find((s) => same(s.tokenHash, hash));
|
|
72
|
+
if (envelope && signer)
|
|
73
|
+
return { envelope, signer };
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
/** Everyone's envelopes, newest first. */
|
|
78
|
+
export function listEnvelopes() {
|
|
79
|
+
if (!existsSync(dataDir()))
|
|
80
|
+
return [];
|
|
81
|
+
return readdirSync(dataDir())
|
|
82
|
+
.map(load)
|
|
83
|
+
.filter((e) => !!e)
|
|
84
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A fresh link and code for one signer who has not signed: the old ones stop
|
|
88
|
+
* working, a lock from wrong codes is cleared, and the expiry starts again.
|
|
89
|
+
*/
|
|
90
|
+
export function reissue(id, who, days = 14) {
|
|
91
|
+
const envelope = load(id);
|
|
92
|
+
const signer = envelope?.signers.find((s) => s.who === who);
|
|
93
|
+
if (!envelope || !signer)
|
|
94
|
+
throw new Error('no such envelope or signer');
|
|
95
|
+
if (signer.signedAt)
|
|
96
|
+
throw new Error(`${signer.name} has already signed`);
|
|
97
|
+
if (envelope.declinedAt)
|
|
98
|
+
throw new Error('this document was declined');
|
|
99
|
+
const token = randomBytes(24).toString('base64url');
|
|
100
|
+
const code = String(randomInt(0, 1_000_000)).padStart(6, '0');
|
|
101
|
+
Object.assign(signer, { tokenHash: sha256(token), codeHash: codeHash(code, id + who), failedCodes: 0 });
|
|
102
|
+
envelope.expiresAt = new Date(Date.now() + days * 86_400_000).toISOString();
|
|
103
|
+
envelope.events.push({ at: new Date().toISOString(), what: 'reissued', who });
|
|
104
|
+
save(envelope);
|
|
105
|
+
return { envelope, secret: { who, token, code } };
|
|
106
|
+
}
|
|
107
|
+
export const codeMatches = (envelope, signer, code) => same(signer.codeHash, codeHash(code, envelope.id + signer.who));
|
|
108
|
+
// --- the seal: proof the finished file and its audit record have not changed since ---
|
|
109
|
+
function key() {
|
|
110
|
+
const file = process.env.LATEX_KIT_SIGN_KEY || join(dataDir(), 'seal-key.pem');
|
|
111
|
+
if (!existsSync(file)) {
|
|
112
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
113
|
+
writeFileSync(file, generateKeyPairSync('ed25519').privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 });
|
|
114
|
+
chmodSync(file, 0o600);
|
|
115
|
+
}
|
|
116
|
+
return createPrivateKey(readFileSync(file));
|
|
117
|
+
}
|
|
118
|
+
/** What the seal covers: the hashes, and each signer's audit facts. */
|
|
119
|
+
const sealed = (e) => JSON.stringify({
|
|
120
|
+
id: e.id, title: e.title, sha256Original: e.sha256Original, sha256Final: e.sha256Final, completedAt: e.completedAt,
|
|
121
|
+
signers: e.signers.map((s) => ({ who: s.who, name: s.name, email: s.email, signedAt: s.signedAt, ip: s.ip, userAgent: s.userAgent, consent: s.consent, location: s.location, values: s.values, sha256Before: s.sha256Before, sha256After: s.sha256After })),
|
|
122
|
+
});
|
|
123
|
+
export function seal(envelope) {
|
|
124
|
+
const k = key();
|
|
125
|
+
const record = {
|
|
126
|
+
algorithm: 'ed25519',
|
|
127
|
+
publicKey: createPublicKey(k).export({ type: 'spki', format: 'pem' }),
|
|
128
|
+
signature: edSign(null, Buffer.from(sealed(envelope)), k).toString('base64'),
|
|
129
|
+
sealedAt: new Date().toISOString(),
|
|
130
|
+
};
|
|
131
|
+
writeFileSync(join(dataDir(), envelope.id, 'seal.json'), JSON.stringify(record, null, 2) + '\n', { mode: 0o600 });
|
|
132
|
+
return record;
|
|
133
|
+
}
|
|
134
|
+
/** Checks a finished envelope: the PDF still has the recorded hash, and the record still matches its seal. */
|
|
135
|
+
export function verifyEnvelope(id, pdfFile) {
|
|
136
|
+
const envelope = load(id);
|
|
137
|
+
if (!envelope)
|
|
138
|
+
return { ok: false, problems: ['no such envelope'] };
|
|
139
|
+
const problems = [];
|
|
140
|
+
if (!envelope.completedAt)
|
|
141
|
+
problems.push('not everyone has signed yet');
|
|
142
|
+
const sealFile = join(dataDir(), id, 'seal.json');
|
|
143
|
+
if (!existsSync(sealFile))
|
|
144
|
+
problems.push('no seal');
|
|
145
|
+
else {
|
|
146
|
+
const s = JSON.parse(readFileSync(sealFile, 'utf8'));
|
|
147
|
+
if (!edVerify(null, Buffer.from(sealed(envelope)), createPublicKey(s.publicKey), Buffer.from(s.signature, 'base64')))
|
|
148
|
+
problems.push('the audit record was changed after it was sealed');
|
|
149
|
+
if (createPublicKey(key()).export({ type: 'spki', format: 'pem' }) !== s.publicKey)
|
|
150
|
+
problems.push("sealed with a key that is not this server's");
|
|
151
|
+
}
|
|
152
|
+
const file = pdfFile || pdfPath(envelope);
|
|
153
|
+
if (sha256(readFileSync(file)) !== envelope.sha256Final)
|
|
154
|
+
problems.push(`${file} is not the file that was signed (hash differs)`);
|
|
155
|
+
if (sha256(readFileSync(pdfPath(envelope, 'original'))) !== envelope.sha256Original)
|
|
156
|
+
problems.push('the stored original was changed');
|
|
157
|
+
for (let i = 1; i < envelope.signers.length; i++) {
|
|
158
|
+
const order = [...envelope.signers].filter((s) => s.signedAt).sort((a, b) => a.signedAt.localeCompare(b.signedAt));
|
|
159
|
+
if (order[i] && order[i].sha256Before !== order[i - 1].sha256After)
|
|
160
|
+
problems.push('the chain of signatures is broken');
|
|
161
|
+
}
|
|
162
|
+
return { ok: problems.length === 0, problems, envelope };
|
|
163
|
+
}
|
package/esm/terms.d.ts
ADDED
package/esm/terms.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const TERMS = {
|
|
2
|
+
version: '2026-11-26',
|
|
3
|
+
text: [
|
|
4
|
+
'I agree to sign this document electronically, and that my electronic signature is as valid as a handwritten one.',
|
|
5
|
+
'I have read the whole document. I can download a copy now and after signing.',
|
|
6
|
+
'I understand that the time, my IP address, my browser, and my location (if I allow it) are recorded with my signature.',
|
|
7
|
+
],
|
|
8
|
+
};
|