@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/types.d.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A spot in a PDF for someone to fill in. Lengths are PDF points (1/72 inch);
|
|
3
|
+
* `x` and `y` are the box's bottom-left corner, from the bottom-left corner of
|
|
4
|
+
* the page. This is the shape `latex-kit build` writes to `<document>.form.json`.
|
|
5
|
+
*/
|
|
6
|
+
export interface FormField {
|
|
7
|
+
type: FieldType | string;
|
|
8
|
+
/** The party that fills it in. */
|
|
9
|
+
who: string;
|
|
10
|
+
/** For typed text: what to type here. */
|
|
11
|
+
label?: string;
|
|
12
|
+
/** From 1. */
|
|
13
|
+
page: number;
|
|
14
|
+
x: number;
|
|
15
|
+
y: number;
|
|
16
|
+
width: number;
|
|
17
|
+
height: number;
|
|
18
|
+
}
|
|
19
|
+
export type FieldType = 'signature' | 'date' | 'initials' | 'text';
|
|
20
|
+
export declare const FIELD_TYPES: FieldType[];
|
|
21
|
+
/** Where the signer was, as their browser reported it, or why there is no position. */
|
|
22
|
+
export type SignerLocation = {
|
|
23
|
+
latitude: number;
|
|
24
|
+
longitude: number;
|
|
25
|
+
accuracyMeters: number | null;
|
|
26
|
+
source: 'reported by the browser';
|
|
27
|
+
} | {
|
|
28
|
+
declined: string;
|
|
29
|
+
};
|
|
30
|
+
export interface Consent {
|
|
31
|
+
agreed: true;
|
|
32
|
+
termsVersion: string;
|
|
33
|
+
termsSha256: string;
|
|
34
|
+
text: string[];
|
|
35
|
+
}
|
|
36
|
+
export interface Signer {
|
|
37
|
+
who: string;
|
|
38
|
+
name: string;
|
|
39
|
+
email: string;
|
|
40
|
+
/** Only hashes of the link and code are kept. */
|
|
41
|
+
tokenHash: string;
|
|
42
|
+
codeHash: string;
|
|
43
|
+
failedCodes: number;
|
|
44
|
+
signedAt: string | null;
|
|
45
|
+
ip?: string;
|
|
46
|
+
userAgent?: string;
|
|
47
|
+
consent?: Consent;
|
|
48
|
+
location?: SignerLocation;
|
|
49
|
+
/** What they typed into text and initials boxes, by label. */
|
|
50
|
+
values?: Record<string, string>;
|
|
51
|
+
accessCodeUsed?: boolean;
|
|
52
|
+
sha256Before?: string;
|
|
53
|
+
sha256After?: string;
|
|
54
|
+
}
|
|
55
|
+
export interface EnvelopeEvent {
|
|
56
|
+
at: string;
|
|
57
|
+
what: string;
|
|
58
|
+
who?: string;
|
|
59
|
+
ip?: string;
|
|
60
|
+
}
|
|
61
|
+
/** One document sent for signing. */
|
|
62
|
+
export interface Envelope {
|
|
63
|
+
id: string;
|
|
64
|
+
title: string;
|
|
65
|
+
createdAt: string;
|
|
66
|
+
expiresAt: string;
|
|
67
|
+
sha256Original: string;
|
|
68
|
+
sha256Final?: string;
|
|
69
|
+
/** Signers sign in the order listed; each waits for the one before. */
|
|
70
|
+
ordered: boolean;
|
|
71
|
+
fields: FormField[];
|
|
72
|
+
signers: Signer[];
|
|
73
|
+
events: EnvelopeEvent[];
|
|
74
|
+
completedAt: string | null;
|
|
75
|
+
declinedAt: string | null;
|
|
76
|
+
declinedBy?: {
|
|
77
|
+
who: string;
|
|
78
|
+
reason: string;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** A signer's link token and access code. They exist in clear only when issued. */
|
|
82
|
+
export interface Secret {
|
|
83
|
+
who: string;
|
|
84
|
+
token: string;
|
|
85
|
+
code: string;
|
|
86
|
+
}
|
package/esm/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const FIELD_TYPES = ['signature', 'date', 'initials', 'text'];
|
package/guide.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { FormField } from './types';
|
|
2
|
+
type Box = {
|
|
3
|
+
left: number;
|
|
4
|
+
top: number;
|
|
5
|
+
width: number;
|
|
6
|
+
height: number;
|
|
7
|
+
};
|
|
8
|
+
/** One box to place, measured from the top-left corner of its page. */
|
|
9
|
+
export interface Placement {
|
|
10
|
+
number: number;
|
|
11
|
+
type: string;
|
|
12
|
+
signer: string;
|
|
13
|
+
page: number;
|
|
14
|
+
fromTopLeft: {
|
|
15
|
+
percent: Box;
|
|
16
|
+
inches: Box;
|
|
17
|
+
points: Box;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/** The placement list: one entry per box, numbered in reading order. */
|
|
21
|
+
export declare function placements(fields: FormField[], pageSizes: {
|
|
22
|
+
width: number;
|
|
23
|
+
height: number;
|
|
24
|
+
}[]): Placement[];
|
|
25
|
+
export declare function writeGuide(pdfFile: string, fieldsFile?: string): Promise<{
|
|
26
|
+
out: string;
|
|
27
|
+
count: number;
|
|
28
|
+
}>;
|
|
29
|
+
export {};
|
package/guide.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.placements = placements;
|
|
4
|
+
exports.writeGuide = writeGuide;
|
|
5
|
+
// A companion to a plain PDF for anyone (or any agent) placing fields by hand in
|
|
6
|
+
// another signing app such as DocuSign or Dropbox Sign:
|
|
7
|
+
//
|
|
8
|
+
// <name>.guide.pdf the same pages with a numbered yellow box on every spot,
|
|
9
|
+
// and a last page listing each box's position
|
|
10
|
+
// <name>.guide.json the same list as data
|
|
11
|
+
//
|
|
12
|
+
// You upload the plain PDF to the signing app, and use the guide as the picture
|
|
13
|
+
// of where each field goes. Positions are from the TOP-LEFT corner of the page,
|
|
14
|
+
// the way signing apps and screens measure, and are given as a share of the page
|
|
15
|
+
// so they hold at any zoom.
|
|
16
|
+
const fs_1 = require("fs");
|
|
17
|
+
const pdf_lib_1 = require("pdf-lib");
|
|
18
|
+
const pct = (n) => Math.round(n * 1000) / 10;
|
|
19
|
+
const inch = (pt) => Math.round((pt / 72) * 100) / 100;
|
|
20
|
+
/** The placement list: one entry per box, numbered in reading order. */
|
|
21
|
+
function placements(fields, pageSizes) {
|
|
22
|
+
return [...fields]
|
|
23
|
+
.sort((a, b) => a.page - b.page || b.y - a.y || a.x - b.x)
|
|
24
|
+
.map((f, i) => {
|
|
25
|
+
const { width: W, height: H } = pageSizes[f.page - 1];
|
|
26
|
+
const top = H - f.y - f.height;
|
|
27
|
+
return {
|
|
28
|
+
number: i + 1,
|
|
29
|
+
type: f.type,
|
|
30
|
+
signer: f.who,
|
|
31
|
+
page: f.page,
|
|
32
|
+
fromTopLeft: {
|
|
33
|
+
percent: { left: pct(f.x / W), top: pct(top / H), width: pct(f.width / W), height: pct(f.height / H) },
|
|
34
|
+
inches: { left: inch(f.x), top: inch(top), width: inch(f.width), height: inch(f.height) },
|
|
35
|
+
points: { left: f.x, top: Math.round(top * 100) / 100, width: f.width, height: f.height },
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
async function writeGuide(pdfFile, fieldsFile = pdfFile.replace(/\.pdf$/i, '.form.json')) {
|
|
41
|
+
const fields = JSON.parse((0, fs_1.readFileSync)(fieldsFile, 'utf8'));
|
|
42
|
+
const pdf = await pdf_lib_1.PDFDocument.load((0, fs_1.readFileSync)(pdfFile));
|
|
43
|
+
const font = await pdf.embedFont(pdf_lib_1.StandardFonts.HelveticaBold);
|
|
44
|
+
const plain = await pdf.embedFont(pdf_lib_1.StandardFonts.Helvetica);
|
|
45
|
+
const sizes = pdf.getPages().map((p) => p.getSize());
|
|
46
|
+
const list = placements(fields, sizes);
|
|
47
|
+
const yellow = (0, pdf_lib_1.rgb)(1, 0.85, 0.1);
|
|
48
|
+
const edge = (0, pdf_lib_1.rgb)(0.8, 0.45, 0);
|
|
49
|
+
for (const p of list) {
|
|
50
|
+
const f = p.fromTopLeft.points;
|
|
51
|
+
const page = pdf.getPage(p.page - 1);
|
|
52
|
+
const y = sizes[p.page - 1].height - f.top - f.height;
|
|
53
|
+
page.drawRectangle({ x: f.left, y, width: f.width, height: f.height, color: yellow, opacity: 0.5, borderColor: edge, borderWidth: 1.2 });
|
|
54
|
+
page.drawCircle({ x: f.left + 9, y: y + f.height / 2, size: 7.5, color: edge });
|
|
55
|
+
page.drawText(String(p.number), { x: f.left + (p.number > 9 ? 4.4 : 6.6), y: y + f.height / 2 - 3, size: 8.5, font, color: (0, pdf_lib_1.rgb)(1, 1, 1) });
|
|
56
|
+
page.drawText(`${p.type.toUpperCase()} · ${p.signer}`, { x: f.left + 21, y: y + f.height / 2 - 3, size: 8.5, font, color: (0, pdf_lib_1.rgb)(0.35, 0.2, 0) });
|
|
57
|
+
// a banner at the top of any page that has boxes, so the page is easy to find
|
|
58
|
+
page.drawText(`GUIDE COPY: do not send this file. Page ${p.page} has fields.`, { x: 36, y: sizes[p.page - 1].height - 18, size: 8, font, color: edge });
|
|
59
|
+
}
|
|
60
|
+
// the list, on its own last page
|
|
61
|
+
const page = pdf.addPage([612, 792]);
|
|
62
|
+
let y = 740;
|
|
63
|
+
const line = (text, { f = plain, size = 9, gap = 13, x = 48 } = {}) => {
|
|
64
|
+
page.drawText(text, { x, y, size, font: f });
|
|
65
|
+
y -= gap;
|
|
66
|
+
};
|
|
67
|
+
line('Field placement guide', { f: font, size: 16, gap: 22 });
|
|
68
|
+
const intro = [
|
|
69
|
+
'This file is a picture of where the fields go. Upload the PLAIN PDF (without yellow boxes) to the signing app,',
|
|
70
|
+
'then add one field for each numbered box below, on the page shown, assigned to the signer shown.',
|
|
71
|
+
'Positions are measured from the TOP-LEFT corner of the page to the top-left corner of the box.',
|
|
72
|
+
'Percentages are of the page width (left, width) and page height (top, height), so they hold at any zoom.',
|
|
73
|
+
`The document has ${sizes.length} pages before this one; this guide page is not part of it.`,
|
|
74
|
+
];
|
|
75
|
+
for (const t of intro)
|
|
76
|
+
line(t);
|
|
77
|
+
y -= 8;
|
|
78
|
+
const cols = [48, 70, 140, 225, 262, 318, 372, 430, 492];
|
|
79
|
+
const row = (cells, f = plain) => {
|
|
80
|
+
cells.forEach((c, i) => page.drawText(String(c), { x: cols[i], y, size: 8.5, font: f }));
|
|
81
|
+
y -= 13;
|
|
82
|
+
};
|
|
83
|
+
row(['#', 'Field', 'Signer', 'Page', 'Left %', 'Top %', 'Width %', 'Height %', 'Left, top (in)'], font);
|
|
84
|
+
for (const p of list) {
|
|
85
|
+
const c = p.fromTopLeft;
|
|
86
|
+
row([p.number, p.type, p.signer, p.page, c.percent.left, c.percent.top, c.percent.width, c.percent.height, `${c.inches.left}, ${c.inches.top}`]);
|
|
87
|
+
}
|
|
88
|
+
y -= 8;
|
|
89
|
+
line("After placing, compare the signing app's preview with the yellow boxes in this file before sending.", { size: 8.5 });
|
|
90
|
+
const out = pdfFile.replace(/\.pdf$/, '.guide.pdf');
|
|
91
|
+
(0, fs_1.writeFileSync)(out, await pdf.save());
|
|
92
|
+
(0, fs_1.writeFileSync)(pdfFile.replace(/\.pdf$/, '.guide.json'), JSON.stringify({ document: pdfFile.split('/').pop(), pages: sizes.length, pageSizePoints: sizes[0], fields: list }, null, 2) + '\n');
|
|
93
|
+
return { out, count: list.length };
|
|
94
|
+
}
|
package/index.d.ts
ADDED
package/index.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./guide"), exports);
|
|
18
|
+
__exportStar(require("./server"), exports);
|
|
19
|
+
__exportStar(require("./stamp"), exports);
|
|
20
|
+
__exportStar(require("./store"), exports);
|
|
21
|
+
__exportStar(require("./terms"), exports);
|
|
22
|
+
__exportStar(require("./types"), exports);
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@latex-kit/sign",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.6.1",
|
|
4
|
+
"description": "Get a PDF signed: a signing page, an audit trail with a sealed record, and a placement guide for other signing apps",
|
|
5
|
+
"author": "Constructive <developers@constructive.io>",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"module": "esm/index.js",
|
|
8
|
+
"types": "index.d.ts",
|
|
9
|
+
"homepage": "https://github.com/constructive-io/latex-kit",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public",
|
|
13
|
+
"directory": "dist"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/constructive-io/latex-kit"
|
|
18
|
+
},
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/constructive-io/latex-kit/issues"
|
|
21
|
+
},
|
|
22
|
+
"bin": {
|
|
23
|
+
"latex-kit-sign": "cli.js"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"minimist": "^1.2.8",
|
|
27
|
+
"pdf-lib": "^1.17.1",
|
|
28
|
+
"@latex-kit/sign-web": "0.6.1"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/minimist": "^1.2.5",
|
|
32
|
+
"makage": "^0.8.0"
|
|
33
|
+
},
|
|
34
|
+
"keywords": [
|
|
35
|
+
"latex-kit",
|
|
36
|
+
"pdf",
|
|
37
|
+
"esign",
|
|
38
|
+
"signature",
|
|
39
|
+
"audit-trail"
|
|
40
|
+
],
|
|
41
|
+
"scripts": {
|
|
42
|
+
"copy": "makage assets",
|
|
43
|
+
"clean": "makage clean",
|
|
44
|
+
"build": "makage build",
|
|
45
|
+
"build:dev": "makage build --dev",
|
|
46
|
+
"lint": "eslint . --fix",
|
|
47
|
+
"test": "jest",
|
|
48
|
+
"test:watch": "jest --watch"
|
|
49
|
+
}
|
|
6
50
|
}
|
package/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/server.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.cleanFields = cleanFields;
|
|
4
|
+
exports.createSignServer = createSignServer;
|
|
5
|
+
// The signing server. No framework: a handful of routes over http.
|
|
6
|
+
//
|
|
7
|
+
// GET /api/sign/:token what this signer needs: title, terms, their boxes
|
|
8
|
+
// GET /api/sign/:token/pdf the document as it stands
|
|
9
|
+
// POST /api/sign/:token { signaturePng, agreed: true, location, values } -> stamps and records
|
|
10
|
+
// POST /api/sign/:token/decline { reason } -> nobody can sign after that
|
|
11
|
+
// GET /api/place/:key[/pdf] the placing page's PDF and saved boxes; PUT saves them
|
|
12
|
+
// GET /sign/:token, /place/:key the pages (from @latex-kit/sign-web)
|
|
13
|
+
//
|
|
14
|
+
// Every /api/sign call needs the signer's access code in the x-access-code header.
|
|
15
|
+
// The audit facts (IP address, browser, time) are taken here, on the server,
|
|
16
|
+
// never from what the browser says about itself. Location is the exception: only
|
|
17
|
+
// the browser knows it, so it is recorded as "reported by the browser".
|
|
18
|
+
const fs_1 = require("fs");
|
|
19
|
+
const http_1 = require("http");
|
|
20
|
+
const path_1 = require("path");
|
|
21
|
+
const stamp_1 = require("./stamp");
|
|
22
|
+
const store_1 = require("./store");
|
|
23
|
+
const terms_1 = require("./terms");
|
|
24
|
+
const types_1 = require("./types");
|
|
25
|
+
/** The built pages: LATEX_KIT_SIGN_WEB, else the @latex-kit/sign-web package. */
|
|
26
|
+
function webDir() {
|
|
27
|
+
if (process.env.LATEX_KIT_SIGN_WEB)
|
|
28
|
+
return process.env.LATEX_KIT_SIGN_WEB;
|
|
29
|
+
try {
|
|
30
|
+
return (0, path_1.join)((0, path_1.dirname)(require.resolve('@latex-kit/sign-web/package.json')), 'dist');
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png' };
|
|
37
|
+
// The signing link is the secret, so it must not leak in a Referer header or sit in a cache;
|
|
38
|
+
// and the page must not be framed by another site.
|
|
39
|
+
const headers = {
|
|
40
|
+
'referrer-policy': 'no-referrer',
|
|
41
|
+
'cache-control': 'no-store',
|
|
42
|
+
'x-content-type-options': 'nosniff',
|
|
43
|
+
'x-frame-options': 'DENY',
|
|
44
|
+
'content-security-policy': "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; worker-src 'self' blob:; frame-ancestors 'none'",
|
|
45
|
+
'permissions-policy': 'geolocation=(self)',
|
|
46
|
+
};
|
|
47
|
+
class HttpError extends Error {
|
|
48
|
+
status;
|
|
49
|
+
extra;
|
|
50
|
+
constructor(status, message, extra) {
|
|
51
|
+
super(message);
|
|
52
|
+
this.status = status;
|
|
53
|
+
this.extra = extra;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const json = (res, status, body) => {
|
|
57
|
+
res.writeHead(status, { ...headers, 'content-type': 'application/json' });
|
|
58
|
+
res.end(JSON.stringify(body));
|
|
59
|
+
};
|
|
60
|
+
const fail = (status, message, extra) => new HttpError(status, message, extra);
|
|
61
|
+
/** Behind a proxy we trust (LEGAL_KIT_SIGN_TRUST_PROXY=1), the first forwarded address; else the socket's. */
|
|
62
|
+
function clientIp(req) {
|
|
63
|
+
const fwd = req.headers['x-forwarded-for'];
|
|
64
|
+
if (process.env.LEGAL_KIT_SIGN_TRUST_PROXY === '1' && fwd)
|
|
65
|
+
return String(fwd).split(',')[0].trim();
|
|
66
|
+
return req.socket.remoteAddress ?? 'unknown';
|
|
67
|
+
}
|
|
68
|
+
async function body(req, limit = 1_500_000) {
|
|
69
|
+
const chunks = [];
|
|
70
|
+
let size = 0;
|
|
71
|
+
for await (const c of req) {
|
|
72
|
+
size += c.length;
|
|
73
|
+
if (size > limit)
|
|
74
|
+
throw fail(413, 'That is too large.');
|
|
75
|
+
chunks.push(c);
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
throw fail(400, 'Could not read the request.');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
// One change to an envelope at a time, so two requests cannot both sign.
|
|
85
|
+
const queues = new Map();
|
|
86
|
+
function oneAtATime(id, work) {
|
|
87
|
+
const next = (queues.get(id) || Promise.resolve()).then(work, work);
|
|
88
|
+
queues.set(id, next.catch(() => { }));
|
|
89
|
+
return next;
|
|
90
|
+
}
|
|
91
|
+
const event = (envelope, req, what, more = {}) => envelope.events.push({ at: new Date().toISOString(), what, ip: clientIp(req), ...more });
|
|
92
|
+
/** Is this link still usable, and did the caller give the right access code? */
|
|
93
|
+
function gate(req, { envelope, signer }) {
|
|
94
|
+
if (envelope.declinedAt)
|
|
95
|
+
throw fail(410, 'This document was declined, so it can no longer be signed.');
|
|
96
|
+
if (!signer.signedAt && new Date(envelope.expiresAt) < new Date())
|
|
97
|
+
throw fail(410, 'This signing link has expired. Ask the sender for a new one.');
|
|
98
|
+
if (signer.failedCodes >= store_1.MAX_CODE_TRIES)
|
|
99
|
+
throw fail(423, 'Too many wrong codes. This link is locked; ask the sender for a new one.');
|
|
100
|
+
const code = req.headers['x-access-code'];
|
|
101
|
+
const waitingFor = envelope.ordered && !signer.signedAt && envelope.signers.slice(0, envelope.signers.indexOf(signer)).find((s) => !s.signedAt);
|
|
102
|
+
if (!code)
|
|
103
|
+
throw fail(401, 'Enter your access code.', { needCode: true });
|
|
104
|
+
if (!(0, store_1.codeMatches)(envelope, signer, String(code))) {
|
|
105
|
+
signer.failedCodes += 1;
|
|
106
|
+
event(envelope, req, 'wrong code', { who: signer.who });
|
|
107
|
+
(0, store_1.save)(envelope);
|
|
108
|
+
const left = store_1.MAX_CODE_TRIES - signer.failedCodes;
|
|
109
|
+
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 });
|
|
110
|
+
}
|
|
111
|
+
if (waitingFor)
|
|
112
|
+
throw fail(409, `It is not your turn yet: ${waitingFor.name} signs first. You will be able to sign once they have.`);
|
|
113
|
+
}
|
|
114
|
+
const view = ({ envelope, signer }) => ({
|
|
115
|
+
title: envelope.title,
|
|
116
|
+
terms: terms_1.TERMS,
|
|
117
|
+
expiresAt: envelope.expiresAt,
|
|
118
|
+
signer: { who: signer.who, name: signer.name, email: signer.email, signedAt: signer.signedAt },
|
|
119
|
+
// `index` is the field's place in the envelope: typed values are sent back under it
|
|
120
|
+
fields: envelope.fields.map((f, index) => ({ ...f, index })).filter((f) => f.who === signer.who),
|
|
121
|
+
others: envelope.signers.filter((s) => s !== signer).map((s) => ({ who: s.who, name: s.name, signed: Boolean(s.signedAt) })),
|
|
122
|
+
completed: Boolean(envelope.completedAt),
|
|
123
|
+
});
|
|
124
|
+
/** Only what we expect: a real position, or a short note on why there is none. */
|
|
125
|
+
function cleanLocation(l) {
|
|
126
|
+
const n = (v, lo, hi) => typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi;
|
|
127
|
+
if (l && n(l.latitude, -90, 90) && n(l.longitude, -180, 180))
|
|
128
|
+
return { latitude: l.latitude, longitude: l.longitude, accuracyMeters: n(l.accuracy, 0, 1e7) ? Math.round(l.accuracy) : null, source: 'reported by the browser' };
|
|
129
|
+
const why = ['denied', 'unavailable', 'timeout', 'unsupported'].includes(l?.declined) ? l.declined : 'not given';
|
|
130
|
+
return { declined: why };
|
|
131
|
+
}
|
|
132
|
+
async function sign(req, found) {
|
|
133
|
+
const { envelope, signer } = found;
|
|
134
|
+
if (signer.signedAt)
|
|
135
|
+
throw fail(409, 'You have already signed this document.');
|
|
136
|
+
const input = await body(req);
|
|
137
|
+
if (input.agreed !== true || input.termsVersion !== terms_1.TERMS.version)
|
|
138
|
+
throw fail(400, 'You need to agree to the terms shown before signing.');
|
|
139
|
+
const m = /^data:image\/png;base64,([A-Za-z0-9+/=]+)$/.exec(input.signaturePng || '');
|
|
140
|
+
const png = m && Buffer.from(m[1], 'base64');
|
|
141
|
+
const mustDraw = envelope.fields.some((f) => f.who === signer.who && f.type === 'signature');
|
|
142
|
+
if (mustDraw && (!png || png.length < 67 || png.readUInt32BE(0) !== 0x89504e47))
|
|
143
|
+
throw fail(400, 'A drawn or typed signature is required.');
|
|
144
|
+
// what the signer typed into their text and initials boxes; every one is required
|
|
145
|
+
const values = {};
|
|
146
|
+
const typed = {};
|
|
147
|
+
for (const [i, f] of envelope.fields.entries()) {
|
|
148
|
+
if (f.who !== signer.who || (f.type !== 'text' && f.type !== 'initials'))
|
|
149
|
+
continue;
|
|
150
|
+
const v = String(input.values?.[i] ?? '').trim();
|
|
151
|
+
if (!v || v.length > (f.type === 'initials' ? 6 : 200))
|
|
152
|
+
throw fail(400, f.type === 'initials' ? 'Please type your initials in every initials box.' : 'Please fill in every text box.');
|
|
153
|
+
if (!/^[\x20-\x7e\xa0-\xff]+$/.test(v))
|
|
154
|
+
throw fail(400, 'Only Latin letters, numbers and punctuation can be typed into a box for now.');
|
|
155
|
+
values[i] = v;
|
|
156
|
+
typed[`${f.label || f.type} (page ${f.page})`] = v;
|
|
157
|
+
}
|
|
158
|
+
const before = (0, fs_1.readFileSync)((0, store_1.pdfPath)(envelope));
|
|
159
|
+
const signedAt = new Date().toISOString();
|
|
160
|
+
let after;
|
|
161
|
+
try {
|
|
162
|
+
after = Buffer.from(await (0, stamp_1.stampSigner)(before, envelope.fields, signer.who, { signaturePng: mustDraw ? png : null, signedAt, values }));
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
throw fail(400, 'That signature image could not be read. Please draw it again.');
|
|
166
|
+
}
|
|
167
|
+
Object.assign(signer, {
|
|
168
|
+
signedAt,
|
|
169
|
+
ip: clientIp(req),
|
|
170
|
+
userAgent: String(req.headers['user-agent'] || '').slice(0, 300),
|
|
171
|
+
consent: { agreed: true, termsVersion: terms_1.TERMS.version, termsSha256: (0, store_1.sha256)(terms_1.TERMS.text.join('\n')), text: terms_1.TERMS.text },
|
|
172
|
+
location: cleanLocation(input.location),
|
|
173
|
+
values: typed,
|
|
174
|
+
accessCodeUsed: true,
|
|
175
|
+
sha256Before: (0, store_1.sha256)(before),
|
|
176
|
+
sha256After: (0, store_1.sha256)(after),
|
|
177
|
+
});
|
|
178
|
+
event(envelope, req, 'signed', { who: signer.who });
|
|
179
|
+
if (envelope.signers.every((s) => s.signedAt)) {
|
|
180
|
+
envelope.completedAt = new Date().toISOString();
|
|
181
|
+
after = Buffer.from(await (0, stamp_1.addCertificate)(after, envelope));
|
|
182
|
+
envelope.sha256Final = (0, store_1.sha256)(after);
|
|
183
|
+
event(envelope, req, 'completed');
|
|
184
|
+
}
|
|
185
|
+
(0, fs_1.writeFileSync)((0, store_1.pdfPath)(envelope), after);
|
|
186
|
+
(0, store_1.save)(envelope);
|
|
187
|
+
if (envelope.completedAt)
|
|
188
|
+
(0, store_1.seal)(envelope);
|
|
189
|
+
return view(found);
|
|
190
|
+
}
|
|
191
|
+
async function decline(req, found) {
|
|
192
|
+
const { envelope, signer } = found;
|
|
193
|
+
if (signer.signedAt || envelope.completedAt)
|
|
194
|
+
throw fail(409, 'You have already signed this document.');
|
|
195
|
+
const input = await body(req);
|
|
196
|
+
envelope.declinedAt = new Date().toISOString();
|
|
197
|
+
envelope.declinedBy = { who: signer.who, reason: String(input.reason || '').slice(0, 500) };
|
|
198
|
+
event(envelope, req, 'declined', { who: signer.who });
|
|
199
|
+
(0, store_1.save)(envelope);
|
|
200
|
+
return { declined: true };
|
|
201
|
+
}
|
|
202
|
+
function page(res, path) {
|
|
203
|
+
const dist = webDir();
|
|
204
|
+
let file = dist ? (0, path_1.normalize)((0, path_1.join)(dist, path)) : '';
|
|
205
|
+
if (dist && (!file.startsWith(dist) || !(0, fs_1.existsSync)(file) || !(0, path_1.extname)(file)))
|
|
206
|
+
file = (0, path_1.join)(dist, 'index.html');
|
|
207
|
+
if (!dist || !(0, fs_1.existsSync)(file)) {
|
|
208
|
+
res.writeHead(503, { 'content-type': 'text/plain' });
|
|
209
|
+
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');
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const html = (0, path_1.extname)(file) === '.html';
|
|
213
|
+
res.writeHead(200, { ...headers, 'cache-control': html ? 'no-store' : 'public, max-age=31536000, immutable', 'content-type': types[(0, path_1.extname)(file)] || 'application/octet-stream' });
|
|
214
|
+
res.end((0, fs_1.readFileSync)(file));
|
|
215
|
+
}
|
|
216
|
+
function cleanFields(input, pageSizes) {
|
|
217
|
+
if (!Array.isArray(input) || input.length > 500)
|
|
218
|
+
throw fail(400, 'Expected a list of fields.');
|
|
219
|
+
return input.map((f) => {
|
|
220
|
+
const size = pageSizes[f.page - 1];
|
|
221
|
+
const ok = (v) => typeof v === 'number' && Number.isFinite(v);
|
|
222
|
+
if (!size || !types_1.FIELD_TYPES.includes(f.type) || !/^[\w-]{1,40}$/.test(f.who || '') || ![f.x, f.y, f.width, f.height].every(ok))
|
|
223
|
+
throw fail(400, 'A field is not valid.');
|
|
224
|
+
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)
|
|
225
|
+
throw fail(400, 'A field is off the page.');
|
|
226
|
+
const r = (v) => Math.round(v * 100) / 100;
|
|
227
|
+
const label = typeof f.label === 'string' && f.label.trim() ? { label: f.label.trim().slice(0, 60) } : {};
|
|
228
|
+
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) };
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
async function place(req, res, sessions, key, rest) {
|
|
232
|
+
const s = sessions.get(key);
|
|
233
|
+
if (!s)
|
|
234
|
+
throw fail(404, 'This placing session is not open. Start it again from the command line.');
|
|
235
|
+
if (rest === '/pdf') {
|
|
236
|
+
res.writeHead(200, { ...headers, 'content-type': 'application/pdf' });
|
|
237
|
+
res.end((0, fs_1.readFileSync)(s.pdf));
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (req.method === 'PUT') {
|
|
241
|
+
const fields = cleanFields((await body(req)).fields, s.pageSizes);
|
|
242
|
+
(0, fs_1.writeFileSync)(s.fieldsFile, JSON.stringify(fields, null, 2) + '\n');
|
|
243
|
+
return json(res, 200, { saved: fields.length, file: s.fieldsFile });
|
|
244
|
+
}
|
|
245
|
+
json(res, 200, { title: s.pdf.split('/').pop(), types: types_1.FIELD_TYPES, fields: (0, fs_1.existsSync)(s.fieldsFile) ? JSON.parse((0, fs_1.readFileSync)(s.fieldsFile, 'utf8')) : [] });
|
|
246
|
+
}
|
|
247
|
+
function createSignServer({ placing = new Map() } = {}) {
|
|
248
|
+
return (0, http_1.createServer)(async (req, res) => {
|
|
249
|
+
try {
|
|
250
|
+
const url = new URL(req.url ?? '/', 'http://x');
|
|
251
|
+
const pl = /^\/api\/place\/([\w-]{20,64})(\/pdf)?$/.exec(url.pathname);
|
|
252
|
+
if (pl)
|
|
253
|
+
return await place(req, res, placing, pl[1], pl[2]);
|
|
254
|
+
const api = /^\/api\/sign\/([\w-]{20,64})(\/pdf|\/decline)?$/.exec(url.pathname);
|
|
255
|
+
if (!api) {
|
|
256
|
+
if (url.pathname.startsWith('/api/'))
|
|
257
|
+
throw fail(404, 'This signing link is not valid.');
|
|
258
|
+
return page(res, url.pathname);
|
|
259
|
+
}
|
|
260
|
+
const first = (0, store_1.findByToken)(api[1]);
|
|
261
|
+
if (!first)
|
|
262
|
+
throw fail(404, 'This signing link is not valid.');
|
|
263
|
+
const result = await oneAtATime(first.envelope.id, async () => {
|
|
264
|
+
// read again inside the queue: an earlier request may have changed it
|
|
265
|
+
const envelope = (0, store_1.load)(first.envelope.id);
|
|
266
|
+
const found = { envelope, signer: envelope.signers.find((s) => s.who === first.signer.who) };
|
|
267
|
+
gate(req, found);
|
|
268
|
+
if (api[2] === '/pdf')
|
|
269
|
+
return { pdf: (0, fs_1.readFileSync)((0, store_1.pdfPath)(envelope)) };
|
|
270
|
+
if (api[2] === '/decline' && req.method === 'POST')
|
|
271
|
+
return decline(req, found);
|
|
272
|
+
if (req.method === 'POST')
|
|
273
|
+
return sign(req, found);
|
|
274
|
+
if (req.method !== 'GET')
|
|
275
|
+
throw fail(405, 'Not allowed.');
|
|
276
|
+
event(envelope, req, 'opened', { who: found.signer.who });
|
|
277
|
+
(0, store_1.save)(envelope);
|
|
278
|
+
return view(found);
|
|
279
|
+
});
|
|
280
|
+
if (result.pdf) {
|
|
281
|
+
res.writeHead(200, { ...headers, 'content-type': 'application/pdf' });
|
|
282
|
+
res.end(result.pdf);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
json(res, 200, result);
|
|
286
|
+
}
|
|
287
|
+
catch (e) {
|
|
288
|
+
const known = e instanceof HttpError ? e : null;
|
|
289
|
+
if (!known)
|
|
290
|
+
console.error(e);
|
|
291
|
+
json(res, known?.status ?? 500, { error: known ? known.message : 'Something went wrong.', ...(known?.extra ?? {}) });
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
}
|
package/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>;
|