@latex-kit/sign 0.0.0-stage → 0.6.0

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/stamp.js ADDED
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.stampSigner = stampSigner;
4
+ exports.addCertificate = addCertificate;
5
+ // Puts a signer's signature and date into the PDF, and adds the certificate page.
6
+ const pdf_lib_1 = require("pdf-lib");
7
+ const longDate = (iso) => new Date(iso).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' });
8
+ async function stampSigner(pdfBytes, fields, who, { signaturePng, signedAt, values = {} }) {
9
+ const pdf = await pdf_lib_1.PDFDocument.load(pdfBytes);
10
+ const font = await pdf.embedFont(pdf_lib_1.StandardFonts.Helvetica);
11
+ const image = signaturePng ? await pdf.embedPng(signaturePng) : null;
12
+ const italic = await pdf.embedFont(pdf_lib_1.StandardFonts.HelveticaOblique);
13
+ /** Text set on the box's bottom edge, shrunk if it would run past the box. */
14
+ const write = (page, f, text, fnt, size = 10) => {
15
+ const fit = Math.min(size, f.height - 2, (size * (f.width - 4)) / Math.max(1, fnt.widthOfTextAtSize(text, size)));
16
+ page.drawText(text, { x: f.x + 2, y: f.y + 3, size: Math.max(5, fit), font: fnt, color: (0, pdf_lib_1.rgb)(0, 0, 0) });
17
+ };
18
+ for (const [i, f] of fields.entries()) {
19
+ if (f.who !== who)
20
+ continue;
21
+ const page = pdf.getPage(f.page - 1);
22
+ if (f.type === 'text')
23
+ write(page, f, values[i], font);
24
+ else if (f.type === 'initials')
25
+ write(page, f, values[i], italic, 14);
26
+ else if (f.type === 'signature' && image) {
27
+ // fit inside the box, keeping the drawing's shape, resting on the line
28
+ const scale = Math.min(f.width / image.width, f.height / image.height);
29
+ page.drawImage(image, { x: f.x + 2, y: f.y, width: image.width * scale, height: image.height * scale });
30
+ }
31
+ else if (f.type === 'date') {
32
+ write(page, f, longDate(signedAt), font);
33
+ }
34
+ }
35
+ return pdf.save();
36
+ }
37
+ /** Appends a page listing who signed, when, from where, and the file hashes. */
38
+ async function addCertificate(pdfBytes, envelope) {
39
+ const pdf = await pdf_lib_1.PDFDocument.load(pdfBytes);
40
+ const font = await pdf.embedFont(pdf_lib_1.StandardFonts.Helvetica);
41
+ const bold = await pdf.embedFont(pdf_lib_1.StandardFonts.HelveticaBold);
42
+ const page = pdf.addPage([612, 792]);
43
+ let y = 730;
44
+ const line = (text, { f = font, size = 9, gap = 13 } = {}) => {
45
+ page.drawText(String(text).slice(0, 110), { x: 54, y, size, font: f });
46
+ y -= gap;
47
+ };
48
+ line('Signing certificate', { f: bold, size: 16, gap: 24 });
49
+ line(`Document: ${envelope.title}`);
50
+ line(`Envelope: ${envelope.id}`);
51
+ line(`Sent for signing: ${envelope.createdAt}`);
52
+ line(`SHA-256 of the document before signing: ${envelope.sha256Original}`, { gap: 22 });
53
+ for (const s of envelope.signers) {
54
+ line(`${s.name} (${s.who})`, { f: bold, size: 11, gap: 15 });
55
+ line(`Email the signing link was issued to: ${s.email}`);
56
+ line(`Signed: ${s.signedAt} (UTC)`);
57
+ line(`IP address: ${s.ip}`);
58
+ line(`Browser: ${s.userAgent}`);
59
+ const l = (s.location || {});
60
+ 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'})`}`);
61
+ for (const [label, v] of Object.entries(s.values || {}))
62
+ line(`Typed in "${label}": ${v}`);
63
+ line(`Identity: opened with a private link and a one-time access code`);
64
+ line(`Agreed to the signing terms, version ${s.consent?.termsVersion} (SHA-256 ${String(s.consent?.termsSha256).slice(0, 16)}…)`);
65
+ line(`SHA-256 before this signature: ${s.sha256Before}`);
66
+ line(`SHA-256 after this signature: ${s.sha256After}`, { gap: 22 });
67
+ }
68
+ y -= 6;
69
+ line('Signing terms each signer agreed to', { f: bold, size: 10, gap: 14 });
70
+ for (const t of envelope.signers[0]?.consent?.text || [])
71
+ for (const part of wrap(t, 108))
72
+ line(part, { size: 8, gap: 11 });
73
+ y -= 6;
74
+ line('The final file hash and this record are sealed by the signing server; `latex-kit-sign verify` checks them.', { size: 8 });
75
+ return pdf.save();
76
+ }
77
+ function wrap(text, width) {
78
+ const out = [];
79
+ let cur = '';
80
+ for (const word of text.split(' ')) {
81
+ if ((cur + ' ' + word).trim().length > width) {
82
+ out.push(cur);
83
+ cur = word;
84
+ }
85
+ else
86
+ cur = (cur + ' ' + word).trim();
87
+ }
88
+ if (cur)
89
+ out.push(cur);
90
+ return out;
91
+ }
package/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/store.js ADDED
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.codeMatches = exports.pdfPath = exports.MAX_CODE_TRIES = exports.sha256 = exports.dataDir = void 0;
4
+ exports.createEnvelope = createEnvelope;
5
+ exports.save = save;
6
+ exports.load = load;
7
+ exports.findByToken = findByToken;
8
+ exports.listEnvelopes = listEnvelopes;
9
+ exports.reissue = reissue;
10
+ exports.seal = seal;
11
+ exports.verifyEnvelope = verifyEnvelope;
12
+ const crypto_1 = require("crypto");
13
+ const fs_1 = require("fs");
14
+ const path_1 = require("path");
15
+ /** Where envelopes live: LATEX_KIT_SIGN_DATA, else `.latex-kit-sign/` in the current folder. */
16
+ const dataDir = () => process.env.LATEX_KIT_SIGN_DATA || (0, path_1.join)(process.cwd(), '.latex-kit-sign');
17
+ exports.dataDir = dataDir;
18
+ const sha256 = (bytes) => (0, crypto_1.createHash)('sha256').update(bytes).digest('hex');
19
+ exports.sha256 = sha256;
20
+ const codeHash = (code, salt) => (0, crypto_1.scryptSync)(String(code), salt, 32).toString('hex');
21
+ const same = (a, b) => a.length === b.length && (0, crypto_1.timingSafeEqual)(Buffer.from(a), Buffer.from(b));
22
+ exports.MAX_CODE_TRIES = 5;
23
+ /**
24
+ * Make an envelope. Returns it with `secrets`: each signer's link token and
25
+ * access code. This is the only time they exist in clear; hand them out.
26
+ */
27
+ function createEnvelope({ pdfPath, fields, signers, title, days = 14, ordered = false }) {
28
+ const inFields = [...new Set(fields.map((f) => f.who))];
29
+ for (const who of inFields)
30
+ if (!signers[who])
31
+ throw new Error(`no signer given for "${who}"`);
32
+ // the order the caller listed them in, which is the signing order when `ordered`
33
+ const roles = Object.keys(signers).filter((who) => inFields.includes(who));
34
+ const id = (0, crypto_1.randomBytes)(8).toString('hex');
35
+ const dir = (0, path_1.join)((0, exports.dataDir)(), id);
36
+ (0, fs_1.mkdirSync)(dir, { recursive: true, mode: 0o700 });
37
+ const pdf = (0, fs_1.readFileSync)(pdfPath);
38
+ (0, fs_1.writeFileSync)((0, path_1.join)(dir, 'original.pdf'), pdf);
39
+ (0, fs_1.writeFileSync)((0, path_1.join)(dir, 'current.pdf'), pdf);
40
+ const now = new Date();
41
+ const secrets = roles.map((who) => ({ who, token: (0, crypto_1.randomBytes)(24).toString('base64url'), code: String((0, crypto_1.randomInt)(0, 1_000_000)).padStart(6, '0') }));
42
+ const envelope = {
43
+ id,
44
+ title: title || (0, path_1.basename)(pdfPath, '.pdf'),
45
+ createdAt: now.toISOString(),
46
+ expiresAt: new Date(now.getTime() + days * 86_400_000).toISOString(),
47
+ sha256Original: (0, exports.sha256)(pdf),
48
+ ordered,
49
+ fields,
50
+ signers: secrets.map(({ who, token, code }) => ({
51
+ who,
52
+ name: signers[who].name,
53
+ email: signers[who].email,
54
+ tokenHash: (0, exports.sha256)(token),
55
+ codeHash: codeHash(code, id + who),
56
+ failedCodes: 0,
57
+ signedAt: null,
58
+ })),
59
+ events: [{ at: now.toISOString(), what: 'created' }],
60
+ completedAt: null,
61
+ declinedAt: null,
62
+ };
63
+ save(envelope);
64
+ return { envelope, secrets };
65
+ }
66
+ /** Written to a temporary file and renamed, so a crash never leaves half a record. */
67
+ function save(envelope) {
68
+ const file = (0, path_1.join)((0, exports.dataDir)(), envelope.id, 'envelope.json');
69
+ (0, fs_1.writeFileSync)(`${file}.tmp`, JSON.stringify(envelope, null, 2) + '\n', { mode: 0o600 });
70
+ (0, fs_1.renameSync)(`${file}.tmp`, file);
71
+ }
72
+ const pdfPath = (envelope, which = 'current') => (0, path_1.join)((0, exports.dataDir)(), envelope.id, `${which}.pdf`);
73
+ exports.pdfPath = pdfPath;
74
+ function load(id) {
75
+ const file = (0, path_1.join)((0, exports.dataDir)(), id, 'envelope.json');
76
+ return /^[0-9a-f]{16}$/.test(id) && (0, fs_1.existsSync)(file) ? JSON.parse((0, fs_1.readFileSync)(file, 'utf8')) : null;
77
+ }
78
+ /** The envelope and signer a signing link belongs to. */
79
+ function findByToken(token) {
80
+ if (!(0, fs_1.existsSync)((0, exports.dataDir)()))
81
+ return null;
82
+ const hash = (0, exports.sha256)(token);
83
+ for (const id of (0, fs_1.readdirSync)((0, exports.dataDir)())) {
84
+ const envelope = load(id);
85
+ const signer = envelope?.signers.find((s) => same(s.tokenHash, hash));
86
+ if (envelope && signer)
87
+ return { envelope, signer };
88
+ }
89
+ return null;
90
+ }
91
+ /** Everyone's envelopes, newest first. */
92
+ function listEnvelopes() {
93
+ if (!(0, fs_1.existsSync)((0, exports.dataDir)()))
94
+ return [];
95
+ return (0, fs_1.readdirSync)((0, exports.dataDir)())
96
+ .map(load)
97
+ .filter((e) => !!e)
98
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
99
+ }
100
+ /**
101
+ * A fresh link and code for one signer who has not signed: the old ones stop
102
+ * working, a lock from wrong codes is cleared, and the expiry starts again.
103
+ */
104
+ function reissue(id, who, days = 14) {
105
+ const envelope = load(id);
106
+ const signer = envelope?.signers.find((s) => s.who === who);
107
+ if (!envelope || !signer)
108
+ throw new Error('no such envelope or signer');
109
+ if (signer.signedAt)
110
+ throw new Error(`${signer.name} has already signed`);
111
+ if (envelope.declinedAt)
112
+ throw new Error('this document was declined');
113
+ const token = (0, crypto_1.randomBytes)(24).toString('base64url');
114
+ const code = String((0, crypto_1.randomInt)(0, 1_000_000)).padStart(6, '0');
115
+ Object.assign(signer, { tokenHash: (0, exports.sha256)(token), codeHash: codeHash(code, id + who), failedCodes: 0 });
116
+ envelope.expiresAt = new Date(Date.now() + days * 86_400_000).toISOString();
117
+ envelope.events.push({ at: new Date().toISOString(), what: 'reissued', who });
118
+ save(envelope);
119
+ return { envelope, secret: { who, token, code } };
120
+ }
121
+ const codeMatches = (envelope, signer, code) => same(signer.codeHash, codeHash(code, envelope.id + signer.who));
122
+ exports.codeMatches = codeMatches;
123
+ // --- the seal: proof the finished file and its audit record have not changed since ---
124
+ function key() {
125
+ const file = process.env.LATEX_KIT_SIGN_KEY || (0, path_1.join)((0, exports.dataDir)(), 'seal-key.pem');
126
+ if (!(0, fs_1.existsSync)(file)) {
127
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(file), { recursive: true });
128
+ (0, fs_1.writeFileSync)(file, (0, crypto_1.generateKeyPairSync)('ed25519').privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 });
129
+ (0, fs_1.chmodSync)(file, 0o600);
130
+ }
131
+ return (0, crypto_1.createPrivateKey)((0, fs_1.readFileSync)(file));
132
+ }
133
+ /** What the seal covers: the hashes, and each signer's audit facts. */
134
+ const sealed = (e) => JSON.stringify({
135
+ id: e.id, title: e.title, sha256Original: e.sha256Original, sha256Final: e.sha256Final, completedAt: e.completedAt,
136
+ 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 })),
137
+ });
138
+ function seal(envelope) {
139
+ const k = key();
140
+ const record = {
141
+ algorithm: 'ed25519',
142
+ publicKey: (0, crypto_1.createPublicKey)(k).export({ type: 'spki', format: 'pem' }),
143
+ signature: (0, crypto_1.sign)(null, Buffer.from(sealed(envelope)), k).toString('base64'),
144
+ sealedAt: new Date().toISOString(),
145
+ };
146
+ (0, fs_1.writeFileSync)((0, path_1.join)((0, exports.dataDir)(), envelope.id, 'seal.json'), JSON.stringify(record, null, 2) + '\n', { mode: 0o600 });
147
+ return record;
148
+ }
149
+ /** Checks a finished envelope: the PDF still has the recorded hash, and the record still matches its seal. */
150
+ function verifyEnvelope(id, pdfFile) {
151
+ const envelope = load(id);
152
+ if (!envelope)
153
+ return { ok: false, problems: ['no such envelope'] };
154
+ const problems = [];
155
+ if (!envelope.completedAt)
156
+ problems.push('not everyone has signed yet');
157
+ const sealFile = (0, path_1.join)((0, exports.dataDir)(), id, 'seal.json');
158
+ if (!(0, fs_1.existsSync)(sealFile))
159
+ problems.push('no seal');
160
+ else {
161
+ const s = JSON.parse((0, fs_1.readFileSync)(sealFile, 'utf8'));
162
+ if (!(0, crypto_1.verify)(null, Buffer.from(sealed(envelope)), (0, crypto_1.createPublicKey)(s.publicKey), Buffer.from(s.signature, 'base64')))
163
+ problems.push('the audit record was changed after it was sealed');
164
+ if ((0, crypto_1.createPublicKey)(key()).export({ type: 'spki', format: 'pem' }) !== s.publicKey)
165
+ problems.push("sealed with a key that is not this server's");
166
+ }
167
+ const file = pdfFile || (0, exports.pdfPath)(envelope);
168
+ if ((0, exports.sha256)((0, fs_1.readFileSync)(file)) !== envelope.sha256Final)
169
+ problems.push(`${file} is not the file that was signed (hash differs)`);
170
+ if ((0, exports.sha256)((0, fs_1.readFileSync)((0, exports.pdfPath)(envelope, 'original'))) !== envelope.sha256Original)
171
+ problems.push('the stored original was changed');
172
+ for (let i = 1; i < envelope.signers.length; i++) {
173
+ const order = [...envelope.signers].filter((s) => s.signedAt).sort((a, b) => a.signedAt.localeCompare(b.signedAt));
174
+ if (order[i] && order[i].sha256Before !== order[i - 1].sha256After)
175
+ problems.push('the chain of signatures is broken');
176
+ }
177
+ return { ok: problems.length === 0, problems, envelope };
178
+ }
package/terms.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * What a signer agrees to. The exact text and its version are stored with each
3
+ * signature, so changing the wording means changing the version.
4
+ */
5
+ export interface Terms {
6
+ version: string;
7
+ text: string[];
8
+ }
9
+ export declare const TERMS: Terms;
package/terms.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TERMS = void 0;
4
+ exports.TERMS = {
5
+ version: '2026-11-26',
6
+ text: [
7
+ 'I agree to sign this document electronically, and that my electronic signature is as valid as a handwritten one.',
8
+ 'I have read the whole document. I can download a copy now and after signing.',
9
+ 'I understand that the time, my IP address, my browser, and my location (if I allow it) are recorded with my signature.',
10
+ ],
11
+ };
package/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/types.js ADDED
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FIELD_TYPES = void 0;
4
+ exports.FIELD_TYPES = ['signature', 'date', 'initials', 'text'];