@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 ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2026 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,132 @@
1
- # Temporary Holding Version
1
+ # @latex-kit/sign
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/latex-kit/actions/workflows/ci.yml">
9
+ <img height="20" src="https://github.com/constructive-io/latex-kit/actions/workflows/ci.yml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/latex-kit/blob/main/LICENSE">
12
+ <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/@latex-kit/sign">
15
+ <img height="20" src="https://img.shields.io/npm/v/@latex-kit/sign.svg"/>
16
+ </a>
17
+ </p>
18
+
19
+ <p align="center">Get a PDF signed: a signing page, a sealed audit trail, and a placement guide for other signing apps.</p>
20
+
21
+
22
+ > **Status: new.** It works end to end and is tested, but it has not been reviewed by a lawyer or run in production. Read [Limits](#limits) before putting a real agreement through it.
23
+
24
+ ```sh
25
+ npm install @latex-kit/sign
26
+ ```
27
+
28
+ ## Two files in, a signed PDF out
29
+
30
+ Everything works from two files: a PDF, and a `.form.json` beside it saying where its boxes are.
31
+
32
+ | You have | Do this |
33
+ |---|---|
34
+ | A latex-kit document whose template marks where to sign | `latex-kit build`. `\signature` blocks mark themselves; `\formfield[type=signature,who=buyer]{…}` marks your own. The build writes `<document>.form.json` |
35
+ | Any other PDF | `latex-kit-sign place file.pdf`: draw the boxes on it in the browser, save |
36
+ | Both files, from anywhere | `send` to use this signer, or `guide` to sign through another app |
37
+
38
+ Nothing here needs LaTeX. The only link to latex-kit is the shape of `.form.json`: a list of `{ type, who, page, x, y, width, height }` in PDF points, from the bottom-left corner of the page. `type` is `signature`, `date`, `initials` or `text`.
39
+
40
+ ## Sign with this package
41
+
42
+ ```sh
43
+ latex-kit build --final # writes out/nda/nda.pdf and nda.form.json
44
+ latex-kit-sign send out/nda/nda.pdf \
45
+ --signer 'discloser=Avery Example <avery@example.test>' \
46
+ --signer 'recipient=Sam Sample <sam@example.test>'
47
+ latex-kit-sign serve
48
+ ```
49
+
50
+ `send` prints, once, a private link and a 6-digit access code for each signer. It does not email anyone: you send the link and the code, by different routes.
51
+
52
+ The signer opens the link and enters the code. The page shows the real PDF with a box on each of their spots. They draw or type a signature, fill any text boxes, and press Finish. A popover shows the signing terms to agree to; then the browser asks to share their location, which they can refuse and still sign. The server stamps the PDF and records the audit facts. When everyone has signed, a certificate page is added and the result is sealed.
53
+
54
+ ### What is recorded for each signer
55
+
56
+ | Fact | Where it comes from |
57
+ |---|---|
58
+ | Time signed | The server's clock |
59
+ | IP address, browser | The server, from the connection. Set `LATEX_KIT_SIGN_TRUST_PROXY=1` only behind your own proxy |
60
+ | Location | The browser, if the signer allows it; otherwise the refusal is recorded. It is the signer's device reporting on itself: supporting detail, not proof |
61
+ | Agreement to the terms | The exact text, its version and its hash |
62
+ | Identity | That the private link and the access code were both used |
63
+ | What they typed | The contents of their text and initials boxes |
64
+ | SHA-256 before and after | Each signature's "before" is the previous one's "after", back to the untouched original |
65
+
66
+ ### Protections
67
+
68
+ - **Links and codes are stored only as hashes.** A copy of the data folder cannot be used to sign.
69
+ - **Five wrong codes lock a link.** Links expire (14 days by default, `--days`). `reissue` replaces a lost, locked or expired link; the old one stops working.
70
+ - **One change at a time per envelope**, so two requests cannot both sign.
71
+ - **The seal.** When complete, the final file's hash and the audit record are signed with the server's Ed25519 key. `verify` fails if the PDF, the record, or the stored original changed afterwards.
72
+ - **Signing order.** With `send --ordered`, each link opens only once the signer before has signed.
73
+ - **A signer can decline**, which stops everyone.
74
+ - **The signing link is kept out of Referer headers and caches**, and the page cannot be framed.
75
+
76
+ ## Sign with another app
77
+
78
+ ```sh
79
+ latex-kit-sign guide out/nda/nda.pdf
80
+ ```
81
+
82
+ This writes `nda.guide.pdf`: the same pages with a numbered yellow box on every spot, and a last page listing each box's page, signer and position from the top-left corner, as a share of the page and in inches. `nda.guide.json` holds the same list as data.
83
+
84
+ Upload the plain PDF to the signing app and place the fields from the guide. It is for a person, or an agent working the app's screen, who would otherwise guess where the boxes go. Never send the guide copy itself for signature.
85
+
86
+ ## Commands
87
+
88
+ ```
89
+ latex-kit-sign place <any.pdf> draw boxes on a PDF (this machine only)
90
+ latex-kit-sign send <document.pdf> --signer who="Name <email>" … [--days 14] [--ordered]
91
+ latex-kit-sign serve [--port 8787]
92
+ latex-kit-sign list
93
+ latex-kit-sign status <envelope>
94
+ latex-kit-sign reissue <envelope> <who>
95
+ latex-kit-sign verify <envelope> [signed.pdf]
96
+ latex-kit-sign guide <document.pdf>… | --all <folder>
97
+ ```
98
+
99
+ | Environment | |
100
+ |---|---|
101
+ | `LATEX_KIT_SIGN_DATA` | Where envelopes live. Default `./.latex-kit-sign`. Never commit it |
102
+ | `LATEX_KIT_SIGN_KEY` | The seal key file. Default `<data>/seal-key.pem`. Back it up |
103
+ | `LATEX_KIT_SIGN_URL` | The address signers reach, printed in links |
104
+ | `LATEX_KIT_SIGN_TRUST_PROXY` | `1` to take the signer's IP from `X-Forwarded-For` |
105
+
106
+ ## As a library
107
+
108
+ ```ts
109
+ import { createEnvelope, createSignServer, verifyEnvelope, writeGuide } from '@latex-kit/sign';
110
+
111
+ const { envelope, secrets } = createEnvelope({ pdfPath, fields, signers: { buyer: { name, email } } });
112
+ createSignServer().listen(8787);
113
+ ```
114
+
115
+ ## Limits
116
+
117
+ - **The access code is only as good as how you deliver it.** Nothing here sends email or texts, and there is no login.
118
+ - **The seal is this package's own, not a standard PDF signature.** A PDF reader will not show the file as signed; checking needs `verify` and the stored record.
119
+ - **Four kinds of box:** signature, date, initials and typed text. Typed text is limited to Latin letters, because the PDF's built-in font cannot draw others.
120
+ - **No reminders.** Nobody is told when their turn comes.
121
+ - **Storage is files on one machine**, with no backups and no HTTPS of its own. Put it behind a proxy that provides HTTPS before anyone outside uses it; browsers only offer location on HTTPS or localhost.
122
+ - **Not legal advice.** Whether an electronic signature made this way is acceptable for a given agreement is a legal question.
123
+
124
+ ## Credits
125
+
126
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
127
+
128
+ ## Disclaimer
129
+
130
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
131
+
132
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export declare function main(args: string[]): Promise<void>;
package/cli.js ADDED
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.main = main;
8
+ const crypto_1 = require("crypto");
9
+ const fs_1 = require("fs");
10
+ const minimist_1 = __importDefault(require("minimist"));
11
+ const path_1 = require("path");
12
+ const pdf_lib_1 = require("pdf-lib");
13
+ const guide_1 = require("./guide");
14
+ const server_1 = require("./server");
15
+ const store_1 = require("./store");
16
+ const USAGE = `latex-kit-sign: get a PDF signed
17
+
18
+ Everything works from two files: a PDF, and <name>.form.json saying where its
19
+ boxes are. latex-kit build writes the second one for templates that mark where
20
+ to sign; for any other PDF, draw the boxes with "place".
21
+
22
+ latex-kit-sign place <any.pdf>
23
+ Draw the boxes on a PDF in the browser. Saving writes <name>.form.json.
24
+ Only this machine can reach the page.
25
+
26
+ latex-kit-sign send <document.pdf> --signer who="Name <email>" [--signer …]
27
+ Make an envelope. Prints, once, each signer's private link and 6-digit
28
+ access code. It does not email anyone: send the link and the code
29
+ yourself, by different routes.
30
+ --days <n> how long the links work (default 14)
31
+ --ordered signers sign in the order given; each waits for the one before
32
+
33
+ latex-kit-sign serve
34
+ Serve the signing page and its API.
35
+
36
+ latex-kit-sign list
37
+ latex-kit-sign status <envelope>
38
+ latex-kit-sign reissue <envelope> <who> [--days <n>]
39
+ A fresh link and code; the old ones stop working.
40
+ latex-kit-sign verify <envelope> [signed.pdf]
41
+ Check a finished envelope: the PDF's hash, the chain of signatures, the seal.
42
+
43
+ latex-kit-sign guide <document.pdf>… | --all <folder>
44
+ For placing fields by hand in another signing app: writes <name>.guide.pdf
45
+ (the pages with numbered yellow boxes and a position list) and .guide.json.
46
+
47
+ Options
48
+ --port <n> for serve and place (default 8787)
49
+ --fields <f> read boxes from this file instead of <name>.form.json
50
+
51
+ Environment
52
+ LATEX_KIT_SIGN_DATA where envelopes live (default ./.latex-kit-sign)
53
+ LATEX_KIT_SIGN_KEY the seal key file (default <data>/seal-key.pem)
54
+ LATEX_KIT_SIGN_URL the address signers reach, printed in links
55
+ LATEX_KIT_SIGN_TRUST_PROXY=1 take the signer's IP from X-Forwarded-For
56
+ `;
57
+ function fail(message) {
58
+ console.error(message);
59
+ process.exit(1);
60
+ }
61
+ /** The boxes for a PDF: --fields, else <name>.form.json, else <name>.fields.json. */
62
+ function fieldsFor(pdf, option) {
63
+ const candidates = option ? [option] : [pdf.replace(/\.pdf$/i, '.form.json'), pdf.replace(/\.pdf$/i, '.fields.json')];
64
+ const found = candidates.find((f) => (0, fs_1.existsSync)(f));
65
+ if (!found)
66
+ fail(`no boxes for ${pdf}: expected ${candidates.join(' or ')}. Draw them with: latex-kit-sign place ${pdf}`);
67
+ return found;
68
+ }
69
+ async function main(args) {
70
+ const argv = (0, minimist_1.default)(args, { string: ['signer', 'port', 'days', 'all', 'fields'], boolean: ['ordered', 'help'], alias: { h: 'help' } });
71
+ const [cmd, ...rest] = argv._.map(String);
72
+ const port = Number(argv.port || 8787);
73
+ const base = process.env.LATEX_KIT_SIGN_URL || `http://localhost:${port}`;
74
+ const days = Number(argv.days || 14);
75
+ const show = (envelope, s) => console.log(` ${s.who.padEnd(12)} ${envelope.signers.find((x) => x.who === s.who).name}\n link: ${base}/sign/${s.token}\n code: ${s.code}`);
76
+ if (!cmd || argv.help) {
77
+ console.log(USAGE);
78
+ return;
79
+ }
80
+ if (cmd === 'send') {
81
+ const pdf = rest[0];
82
+ if (!pdf || !(0, fs_1.existsSync)(pdf))
83
+ fail('send needs a PDF');
84
+ const signers = {};
85
+ for (const s of [].concat(argv.signer ?? [])) {
86
+ const m = /^([\w.-]+)=(.+?)\s*<(.+@.+)>$/.exec(s);
87
+ if (!m)
88
+ fail(`--signer wants who="Name <email>", got: ${s}`);
89
+ signers[m[1]] = { name: m[2], email: m[3] };
90
+ }
91
+ const fields = JSON.parse((0, fs_1.readFileSync)(fieldsFor(pdf, argv.fields), 'utf8'));
92
+ let made;
93
+ try {
94
+ made = (0, store_1.createEnvelope)({ pdfPath: pdf, fields, signers, days, ordered: Boolean(argv.ordered) });
95
+ }
96
+ catch (e) {
97
+ fail(`${e.message}. The boxes name: ${[...new Set(fields.map((f) => f.who))].join(', ')}`);
98
+ }
99
+ const { envelope, secrets } = made;
100
+ console.log(`envelope ${envelope.id}: ${envelope.title} (links work until ${envelope.expiresAt.slice(0, 10)})`);
101
+ if (envelope.ordered)
102
+ console.log('They sign in this order; each link opens once the signer before has signed.');
103
+ console.log('These links and codes are shown once and not stored. Send each code by a different route than its link.');
104
+ for (const s of secrets)
105
+ show(envelope, s);
106
+ }
107
+ else if (cmd === 'reissue') {
108
+ try {
109
+ const { envelope, secret } = (0, store_1.reissue)(rest[0] ?? '', rest[1] ?? '', days);
110
+ console.log(`new link and code for ${secret.who}; the old ones no longer work (links now work until ${envelope.expiresAt.slice(0, 10)})`);
111
+ show(envelope, secret);
112
+ }
113
+ catch (e) {
114
+ fail(e.message);
115
+ }
116
+ }
117
+ else if (cmd === 'list') {
118
+ for (const e of (0, store_1.listEnvelopes)()) {
119
+ const state = e.declinedAt ? 'declined' : e.completedAt ? 'complete' : `${e.signers.filter((s) => s.signedAt).length}/${e.signers.length} signed`;
120
+ console.log(`${e.id} ${e.createdAt.slice(0, 10)} ${state.padEnd(12)} ${e.title}`);
121
+ }
122
+ }
123
+ else if (cmd === 'serve') {
124
+ (0, server_1.createSignServer)().listen(port, () => console.log(`signing page on http://localhost:${port}`));
125
+ }
126
+ else if (cmd === 'place') {
127
+ const pdf = rest[0] && (0, path_1.resolve)(rest[0]);
128
+ if (!pdf || !(0, fs_1.existsSync)(pdf))
129
+ fail('place needs a PDF');
130
+ const pageSizes = (await pdf_lib_1.PDFDocument.load((0, fs_1.readFileSync)(pdf))).getPages().map((p) => p.getSize());
131
+ const key = (0, crypto_1.randomBytes)(18).toString('base64url');
132
+ const fieldsFile = argv.fields ? (0, path_1.resolve)(argv.fields) : pdf.replace(/\.pdf$/i, '.form.json');
133
+ // only this machine can reach the placing page
134
+ (0, server_1.createSignServer)({ placing: new Map([[key, { pdf, fieldsFile, pageSizes }]]) }).listen(port, '127.0.0.1', () => {
135
+ console.log(`draw the fields here: http://localhost:${port}/place/${key}\nsaving writes ${fieldsFile}\npress Ctrl-C when done`);
136
+ });
137
+ }
138
+ else if (cmd === 'status') {
139
+ const e = (0, store_1.load)(rest[0] ?? '');
140
+ if (!e)
141
+ fail('no such envelope');
142
+ console.log(`${e.title}: ${e.declinedAt ? `declined by ${e.declinedBy?.who}` : e.completedAt ? 'complete' : 'waiting'}`);
143
+ for (const s of e.signers)
144
+ console.log(` ${s.who.padEnd(12)} ${s.name}: ${s.signedAt ? `signed ${s.signedAt} from ${s.ip}` : s.failedCodes >= 5 ? 'locked (wrong codes)' : 'not yet'}`);
145
+ for (const ev of e.events)
146
+ console.log(` ${ev.at} ${ev.what}${ev.who ? ` (${ev.who})` : ''}${ev.ip ? ` ${ev.ip}` : ''}`);
147
+ }
148
+ else if (cmd === 'verify') {
149
+ const r = (0, store_1.verifyEnvelope)(rest[0] ?? '', rest[1]);
150
+ console.log(r.ok ? `ok: ${r.envelope.title} is the file that was signed, and its record is intact` : `PROBLEMS:\n ${r.problems.join('\n ')}`);
151
+ if (!r.ok)
152
+ process.exit(1);
153
+ }
154
+ else if (cmd === 'guide') {
155
+ const dir = argv.all;
156
+ const pdfs = dir
157
+ ? (0, fs_1.readdirSync)(dir, { recursive: true })
158
+ .filter((f) => f.endsWith('.form.json'))
159
+ .map((f) => (0, path_1.join)(dir, f.replace(/\.form\.json$/, '.pdf')))
160
+ .filter((f) => (0, fs_1.existsSync)(f))
161
+ : rest;
162
+ if (!pdfs.length)
163
+ fail('guide needs PDFs with a .form.json beside them');
164
+ for (const pdf of pdfs) {
165
+ const { out, count } = await (0, guide_1.writeGuide)(pdf, fieldsFor(pdf, dir ? undefined : argv.fields));
166
+ if (!dir)
167
+ console.log(`${out}: ${count} fields`);
168
+ }
169
+ if (dir)
170
+ console.log(`guide: wrote ${pdfs.length} .guide.pdf files under ${dir}`);
171
+ }
172
+ else {
173
+ console.log(USAGE);
174
+ process.exit(1);
175
+ }
176
+ }
177
+ if (require.main === module) {
178
+ main(process.argv.slice(2)).catch((e) => fail(e instanceof Error ? e.message : String(e)));
179
+ }
package/esm/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export declare function main(args: string[]): Promise<void>;
package/esm/cli.js ADDED
@@ -0,0 +1,173 @@
1
+ #!/usr/bin/env node
2
+ import { randomBytes } from 'crypto';
3
+ import { existsSync, readdirSync, readFileSync } from 'fs';
4
+ import minimist from 'minimist';
5
+ import { join, resolve } from 'path';
6
+ import { PDFDocument } from 'pdf-lib';
7
+ import { writeGuide } from './guide';
8
+ import { createSignServer } from './server';
9
+ import { createEnvelope, listEnvelopes, load, reissue, verifyEnvelope } from './store';
10
+ const USAGE = `latex-kit-sign: get a PDF signed
11
+
12
+ Everything works from two files: a PDF, and <name>.form.json saying where its
13
+ boxes are. latex-kit build writes the second one for templates that mark where
14
+ to sign; for any other PDF, draw the boxes with "place".
15
+
16
+ latex-kit-sign place <any.pdf>
17
+ Draw the boxes on a PDF in the browser. Saving writes <name>.form.json.
18
+ Only this machine can reach the page.
19
+
20
+ latex-kit-sign send <document.pdf> --signer who="Name <email>" [--signer …]
21
+ Make an envelope. Prints, once, each signer's private link and 6-digit
22
+ access code. It does not email anyone: send the link and the code
23
+ yourself, by different routes.
24
+ --days <n> how long the links work (default 14)
25
+ --ordered signers sign in the order given; each waits for the one before
26
+
27
+ latex-kit-sign serve
28
+ Serve the signing page and its API.
29
+
30
+ latex-kit-sign list
31
+ latex-kit-sign status <envelope>
32
+ latex-kit-sign reissue <envelope> <who> [--days <n>]
33
+ A fresh link and code; the old ones stop working.
34
+ latex-kit-sign verify <envelope> [signed.pdf]
35
+ Check a finished envelope: the PDF's hash, the chain of signatures, the seal.
36
+
37
+ latex-kit-sign guide <document.pdf>… | --all <folder>
38
+ For placing fields by hand in another signing app: writes <name>.guide.pdf
39
+ (the pages with numbered yellow boxes and a position list) and .guide.json.
40
+
41
+ Options
42
+ --port <n> for serve and place (default 8787)
43
+ --fields <f> read boxes from this file instead of <name>.form.json
44
+
45
+ Environment
46
+ LATEX_KIT_SIGN_DATA where envelopes live (default ./.latex-kit-sign)
47
+ LATEX_KIT_SIGN_KEY the seal key file (default <data>/seal-key.pem)
48
+ LATEX_KIT_SIGN_URL the address signers reach, printed in links
49
+ LATEX_KIT_SIGN_TRUST_PROXY=1 take the signer's IP from X-Forwarded-For
50
+ `;
51
+ function fail(message) {
52
+ console.error(message);
53
+ process.exit(1);
54
+ }
55
+ /** The boxes for a PDF: --fields, else <name>.form.json, else <name>.fields.json. */
56
+ function fieldsFor(pdf, option) {
57
+ const candidates = option ? [option] : [pdf.replace(/\.pdf$/i, '.form.json'), pdf.replace(/\.pdf$/i, '.fields.json')];
58
+ const found = candidates.find((f) => existsSync(f));
59
+ if (!found)
60
+ fail(`no boxes for ${pdf}: expected ${candidates.join(' or ')}. Draw them with: latex-kit-sign place ${pdf}`);
61
+ return found;
62
+ }
63
+ export async function main(args) {
64
+ const argv = minimist(args, { string: ['signer', 'port', 'days', 'all', 'fields'], boolean: ['ordered', 'help'], alias: { h: 'help' } });
65
+ const [cmd, ...rest] = argv._.map(String);
66
+ const port = Number(argv.port || 8787);
67
+ const base = process.env.LATEX_KIT_SIGN_URL || `http://localhost:${port}`;
68
+ const days = Number(argv.days || 14);
69
+ const show = (envelope, s) => console.log(` ${s.who.padEnd(12)} ${envelope.signers.find((x) => x.who === s.who).name}\n link: ${base}/sign/${s.token}\n code: ${s.code}`);
70
+ if (!cmd || argv.help) {
71
+ console.log(USAGE);
72
+ return;
73
+ }
74
+ if (cmd === 'send') {
75
+ const pdf = rest[0];
76
+ if (!pdf || !existsSync(pdf))
77
+ fail('send needs a PDF');
78
+ const signers = {};
79
+ for (const s of [].concat(argv.signer ?? [])) {
80
+ const m = /^([\w.-]+)=(.+?)\s*<(.+@.+)>$/.exec(s);
81
+ if (!m)
82
+ fail(`--signer wants who="Name <email>", got: ${s}`);
83
+ signers[m[1]] = { name: m[2], email: m[3] };
84
+ }
85
+ const fields = JSON.parse(readFileSync(fieldsFor(pdf, argv.fields), 'utf8'));
86
+ let made;
87
+ try {
88
+ made = createEnvelope({ pdfPath: pdf, fields, signers, days, ordered: Boolean(argv.ordered) });
89
+ }
90
+ catch (e) {
91
+ fail(`${e.message}. The boxes name: ${[...new Set(fields.map((f) => f.who))].join(', ')}`);
92
+ }
93
+ const { envelope, secrets } = made;
94
+ console.log(`envelope ${envelope.id}: ${envelope.title} (links work until ${envelope.expiresAt.slice(0, 10)})`);
95
+ if (envelope.ordered)
96
+ console.log('They sign in this order; each link opens once the signer before has signed.');
97
+ console.log('These links and codes are shown once and not stored. Send each code by a different route than its link.');
98
+ for (const s of secrets)
99
+ show(envelope, s);
100
+ }
101
+ else if (cmd === 'reissue') {
102
+ try {
103
+ const { envelope, secret } = reissue(rest[0] ?? '', rest[1] ?? '', days);
104
+ console.log(`new link and code for ${secret.who}; the old ones no longer work (links now work until ${envelope.expiresAt.slice(0, 10)})`);
105
+ show(envelope, secret);
106
+ }
107
+ catch (e) {
108
+ fail(e.message);
109
+ }
110
+ }
111
+ else if (cmd === 'list') {
112
+ for (const e of listEnvelopes()) {
113
+ const state = e.declinedAt ? 'declined' : e.completedAt ? 'complete' : `${e.signers.filter((s) => s.signedAt).length}/${e.signers.length} signed`;
114
+ console.log(`${e.id} ${e.createdAt.slice(0, 10)} ${state.padEnd(12)} ${e.title}`);
115
+ }
116
+ }
117
+ else if (cmd === 'serve') {
118
+ createSignServer().listen(port, () => console.log(`signing page on http://localhost:${port}`));
119
+ }
120
+ else if (cmd === 'place') {
121
+ const pdf = rest[0] && resolve(rest[0]);
122
+ if (!pdf || !existsSync(pdf))
123
+ fail('place needs a PDF');
124
+ const pageSizes = (await PDFDocument.load(readFileSync(pdf))).getPages().map((p) => p.getSize());
125
+ const key = randomBytes(18).toString('base64url');
126
+ const fieldsFile = argv.fields ? resolve(argv.fields) : pdf.replace(/\.pdf$/i, '.form.json');
127
+ // only this machine can reach the placing page
128
+ createSignServer({ placing: new Map([[key, { pdf, fieldsFile, pageSizes }]]) }).listen(port, '127.0.0.1', () => {
129
+ console.log(`draw the fields here: http://localhost:${port}/place/${key}\nsaving writes ${fieldsFile}\npress Ctrl-C when done`);
130
+ });
131
+ }
132
+ else if (cmd === 'status') {
133
+ const e = load(rest[0] ?? '');
134
+ if (!e)
135
+ fail('no such envelope');
136
+ console.log(`${e.title}: ${e.declinedAt ? `declined by ${e.declinedBy?.who}` : e.completedAt ? 'complete' : 'waiting'}`);
137
+ for (const s of e.signers)
138
+ console.log(` ${s.who.padEnd(12)} ${s.name}: ${s.signedAt ? `signed ${s.signedAt} from ${s.ip}` : s.failedCodes >= 5 ? 'locked (wrong codes)' : 'not yet'}`);
139
+ for (const ev of e.events)
140
+ console.log(` ${ev.at} ${ev.what}${ev.who ? ` (${ev.who})` : ''}${ev.ip ? ` ${ev.ip}` : ''}`);
141
+ }
142
+ else if (cmd === 'verify') {
143
+ const r = verifyEnvelope(rest[0] ?? '', rest[1]);
144
+ console.log(r.ok ? `ok: ${r.envelope.title} is the file that was signed, and its record is intact` : `PROBLEMS:\n ${r.problems.join('\n ')}`);
145
+ if (!r.ok)
146
+ process.exit(1);
147
+ }
148
+ else if (cmd === 'guide') {
149
+ const dir = argv.all;
150
+ const pdfs = dir
151
+ ? readdirSync(dir, { recursive: true })
152
+ .filter((f) => f.endsWith('.form.json'))
153
+ .map((f) => join(dir, f.replace(/\.form\.json$/, '.pdf')))
154
+ .filter((f) => existsSync(f))
155
+ : rest;
156
+ if (!pdfs.length)
157
+ fail('guide needs PDFs with a .form.json beside them');
158
+ for (const pdf of pdfs) {
159
+ const { out, count } = await writeGuide(pdf, fieldsFor(pdf, dir ? undefined : argv.fields));
160
+ if (!dir)
161
+ console.log(`${out}: ${count} fields`);
162
+ }
163
+ if (dir)
164
+ console.log(`guide: wrote ${pdfs.length} .guide.pdf files under ${dir}`);
165
+ }
166
+ else {
167
+ console.log(USAGE);
168
+ process.exit(1);
169
+ }
170
+ }
171
+ if (require.main === module) {
172
+ main(process.argv.slice(2)).catch((e) => fail(e instanceof Error ? e.message : String(e)));
173
+ }
package/esm/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/esm/guide.js ADDED
@@ -0,0 +1,90 @@
1
+ // A companion to a plain PDF for anyone (or any agent) placing fields by hand in
2
+ // another signing app such as DocuSign or Dropbox Sign:
3
+ //
4
+ // <name>.guide.pdf the same pages with a numbered yellow box on every spot,
5
+ // and a last page listing each box's position
6
+ // <name>.guide.json the same list as data
7
+ //
8
+ // You upload the plain PDF to the signing app, and use the guide as the picture
9
+ // of where each field goes. Positions are from the TOP-LEFT corner of the page,
10
+ // the way signing apps and screens measure, and are given as a share of the page
11
+ // so they hold at any zoom.
12
+ import { readFileSync, writeFileSync } from 'fs';
13
+ import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
14
+ const pct = (n) => Math.round(n * 1000) / 10;
15
+ const inch = (pt) => Math.round((pt / 72) * 100) / 100;
16
+ /** The placement list: one entry per box, numbered in reading order. */
17
+ export function placements(fields, pageSizes) {
18
+ return [...fields]
19
+ .sort((a, b) => a.page - b.page || b.y - a.y || a.x - b.x)
20
+ .map((f, i) => {
21
+ const { width: W, height: H } = pageSizes[f.page - 1];
22
+ const top = H - f.y - f.height;
23
+ return {
24
+ number: i + 1,
25
+ type: f.type,
26
+ signer: f.who,
27
+ page: f.page,
28
+ fromTopLeft: {
29
+ percent: { left: pct(f.x / W), top: pct(top / H), width: pct(f.width / W), height: pct(f.height / H) },
30
+ inches: { left: inch(f.x), top: inch(top), width: inch(f.width), height: inch(f.height) },
31
+ points: { left: f.x, top: Math.round(top * 100) / 100, width: f.width, height: f.height },
32
+ },
33
+ };
34
+ });
35
+ }
36
+ export async function writeGuide(pdfFile, fieldsFile = pdfFile.replace(/\.pdf$/i, '.form.json')) {
37
+ const fields = JSON.parse(readFileSync(fieldsFile, 'utf8'));
38
+ const pdf = await PDFDocument.load(readFileSync(pdfFile));
39
+ const font = await pdf.embedFont(StandardFonts.HelveticaBold);
40
+ const plain = await pdf.embedFont(StandardFonts.Helvetica);
41
+ const sizes = pdf.getPages().map((p) => p.getSize());
42
+ const list = placements(fields, sizes);
43
+ const yellow = rgb(1, 0.85, 0.1);
44
+ const edge = rgb(0.8, 0.45, 0);
45
+ for (const p of list) {
46
+ const f = p.fromTopLeft.points;
47
+ const page = pdf.getPage(p.page - 1);
48
+ const y = sizes[p.page - 1].height - f.top - f.height;
49
+ page.drawRectangle({ x: f.left, y, width: f.width, height: f.height, color: yellow, opacity: 0.5, borderColor: edge, borderWidth: 1.2 });
50
+ page.drawCircle({ x: f.left + 9, y: y + f.height / 2, size: 7.5, color: edge });
51
+ 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: rgb(1, 1, 1) });
52
+ page.drawText(`${p.type.toUpperCase()} · ${p.signer}`, { x: f.left + 21, y: y + f.height / 2 - 3, size: 8.5, font, color: rgb(0.35, 0.2, 0) });
53
+ // a banner at the top of any page that has boxes, so the page is easy to find
54
+ 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 });
55
+ }
56
+ // the list, on its own last page
57
+ const page = pdf.addPage([612, 792]);
58
+ let y = 740;
59
+ const line = (text, { f = plain, size = 9, gap = 13, x = 48 } = {}) => {
60
+ page.drawText(text, { x, y, size, font: f });
61
+ y -= gap;
62
+ };
63
+ line('Field placement guide', { f: font, size: 16, gap: 22 });
64
+ const intro = [
65
+ 'This file is a picture of where the fields go. Upload the PLAIN PDF (without yellow boxes) to the signing app,',
66
+ 'then add one field for each numbered box below, on the page shown, assigned to the signer shown.',
67
+ 'Positions are measured from the TOP-LEFT corner of the page to the top-left corner of the box.',
68
+ 'Percentages are of the page width (left, width) and page height (top, height), so they hold at any zoom.',
69
+ `The document has ${sizes.length} pages before this one; this guide page is not part of it.`,
70
+ ];
71
+ for (const t of intro)
72
+ line(t);
73
+ y -= 8;
74
+ const cols = [48, 70, 140, 225, 262, 318, 372, 430, 492];
75
+ const row = (cells, f = plain) => {
76
+ cells.forEach((c, i) => page.drawText(String(c), { x: cols[i], y, size: 8.5, font: f }));
77
+ y -= 13;
78
+ };
79
+ row(['#', 'Field', 'Signer', 'Page', 'Left %', 'Top %', 'Width %', 'Height %', 'Left, top (in)'], font);
80
+ for (const p of list) {
81
+ const c = p.fromTopLeft;
82
+ 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}`]);
83
+ }
84
+ y -= 8;
85
+ line("After placing, compare the signing app's preview with the yellow boxes in this file before sending.", { size: 8.5 });
86
+ const out = pdfFile.replace(/\.pdf$/, '.guide.pdf');
87
+ writeFileSync(out, await pdf.save());
88
+ writeFileSync(pdfFile.replace(/\.pdf$/, '.guide.json'), JSON.stringify({ document: pdfFile.split('/').pop(), pages: sizes.length, pageSizePoints: sizes[0], fields: list }, null, 2) + '\n');
89
+ return { out, count: list.length };
90
+ }
package/esm/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from './guide';
2
+ export * from './server';
3
+ export * from './stamp';
4
+ export * from './store';
5
+ export * from './terms';
6
+ export * from './types';
package/esm/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from './guide';
2
+ export * from './server';
3
+ export * from './stamp';
4
+ export * from './store';
5
+ export * from './terms';
6
+ export * from './types';