@corbet-labs/cink 0.1.1 → 0.1.3

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.
@@ -0,0 +1,105 @@
1
+ # Functional Source License, Version 1.1, ALv2 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-ALv2
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 Julian Y. Richard Corbet
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
package/README.md CHANGED
@@ -1,27 +1,103 @@
1
- # @corbet-labs/cink
1
+ # cink
2
2
 
3
- Handwritten signature image rendering for formal correspondence. Pure port
4
- of the [cink](https://github.com/corbet-labs/cink) Rust crate: zero
5
- dependencies, zero Node APIs, synchronous, no I/O. Pixels, not
6
- signatures — no cryptography, no identity, no legal ceremony.
3
+ **Prepare handwritten signature images for correspondence.**
7
4
 
8
- ```ts
9
- import { normalize, signatureSize, imageSnippet } from '@corbet-labs/cink';
5
+ [![crates.io](https://img.shields.io/crates/v/cink.svg)](https://crates.io/crates/cink) [![npm](https://img.shields.io/npm/v/@corbet-labs/cink.svg)](https://www.npmjs.com/package/@corbet-labs/cink) [![Rust API](https://docs.rs/cink/badge.svg)](https://docs.rs/cink)
10
6
 
11
- const img = normalize(dataUrl); // null when unusable
12
- const [w, h] = signatureSize(img, 31.5, 120);
13
- const snippet = imageSnippet('/signature.png', h, w === 31.5 ? undefined : w);
7
+ Recognize PNG, JPEG, and SVG input, inspect raster dimensions, calculate an aspect-preserving size, and generate a Typst image call. Runs without an image-decoding library.
8
+
9
+ ```js
10
+ import { imageSnippet } from '@corbet-labs/cink';
11
+
12
+ imageSnippet('/signature.png', 31.5);
13
+ // #image("/signature.png", height: 31.5pt)
14
+ ```
15
+
16
+ ## Install
17
+
18
+ | Environment | Command |
19
+ | --- | --- |
20
+ | Rust / Cargo | `cargo add cink` |
21
+ | Node.js / npm | `npm install @corbet-labs/cink` |
22
+ | pnpm | `pnpm add @corbet-labs/cink` |
23
+ | Yarn | `yarn add @corbet-labs/cink` |
24
+ | Bun | `bun add @corbet-labs/cink` |
25
+ | Deno | `deno add npm:@corbet-labs/cink` |
26
+
27
+ The 0.1.3 JavaScript distribution includes compiled ESM, CommonJS,
28
+ TypeScript declarations, and a standalone browser module. Node.js 20+ is
29
+ supported; no TypeScript loader is required.
30
+
31
+ ```js
32
+ // CommonJS
33
+ const { imageSnippet } = require('@corbet-labs/cink');
34
+ ```
35
+
36
+ ```html
37
+ <script type="module">
38
+ import { imageSnippet } from 'https://cdn.jsdelivr.net/npm/@corbet-labs/cink@0.1.3/dist/browser.js';
39
+ console.log(imageSnippet('/signature.png', 31.5));
40
+ </script>
41
+ ```
42
+
43
+ Python wheels, source distributions, and CLI instructions are in the
44
+ [installation guide](https://github.com/corbet-labs/cink/blob/main/docs/installation.md).
45
+ JSR publication and Typst availability are listed there explicitly.
46
+
47
+ ## Rust
48
+
49
+ ```rust
50
+ use cink::image_snippet;
51
+
52
+ assert_eq!(image_snippet("/signature.png", 31.5, None), "#image(\"/signature.png\", height: 31.5pt)");
14
53
  ```
15
54
 
16
- PNG and JPEG dimensions are read from headers, never decoded; SVG passes
17
- through dimension-less. WebP, GIF, corrupt, and empty inputs are rejected.
18
- Oversized rasters are reported (`exceedsLimits`, `scaleToFit`), never
19
- silently resampled.
55
+ ## Python
56
+
57
+ ```python
58
+ from cink import image_snippet
59
+
60
+ assert image_snippet("/signature.png", 31.5) == '#image("/signature.png", height: 31.5pt)'
61
+ ```
62
+
63
+ ## API
64
+
65
+ | JavaScript / Python or Rust | Purpose |
66
+ | --- | --- |
67
+ | `normalize` | Recognize a base64 image or data URL |
68
+ | `exceedsLimits` / `exceeds_limits` | Check a raster pixel budget |
69
+ | `scaleToFit` / `scale_to_fit` | Calculate a downscaling factor |
70
+ | `signatureSize` / `signature_size` | Fit dimensions to a point size |
71
+ | `imageSnippet` / `image_snippet` | Generate a Typst image call |
72
+
73
+ Base64 input uses the standard alphabet, required padding, and canonical trailing bits; embedded whitespace is rejected.
74
+
75
+ PNG and JPEG dimensions are read from headers; this is not a full raster integrity check. SVG passes through without sanitization or known dimensions. Unrecognized headers and unsupported formats return `null`/`None`. Nonpositive, nonfinite, and unrepresentable requested sizes return `null`/`None`. Resampling and placement belong to the caller. These are handwriting images, not cryptographic or electronic signatures.
76
+
77
+ ## Correspondence family
78
+
79
+ | Library | Responsibility |
80
+ | --- | --- |
81
+ | [cletter](https://github.com/corbet-labs/cletter) | Compose the correspondence helpers |
82
+ | [cgreet](https://github.com/corbet-labs/cgreet) | German salutations and titles |
83
+ | [cfarewell](https://github.com/corbet-labs/cfarewell) | Locale-specific closings |
84
+ | [cdate](https://github.com/corbet-labs/cdate) | Calendar-date formatting |
85
+ | [cink](https://github.com/corbet-labs/cink) | Handwritten signature images |
86
+
87
+
88
+ ## Development
89
+
90
+ Behavior is defined by [the locale tables](https://github.com/corbet-labs/cink/tree/main/tables)
91
+ and [shared conformance vectors](https://github.com/corbet-labs/cink/tree/main/tests/vectors).
92
+ Rust, JavaScript, and Python run the same vectors. Selected CI checks exercise
93
+ installed JavaScript tarballs, Python wheels and command-line entrypoints, and
94
+ Typst packages. Release validation records the actual runtime and platform;
95
+ Linux results do not establish native Windows or macOS coverage.
96
+ All five Rust crates forbid unsafe code in their own source.
20
97
 
21
- Run `bun ./scripts/conformance.mts` and `tsc --noEmit -p ./tsconfig.json`
22
- before pushing.
98
+ See [the release guide](https://github.com/corbet-labs/cink/blob/main/docs/releasing.md)
99
+ for generation, verification, and publication commands.
23
100
 
24
101
  ## License
25
102
 
26
- FSL-1.1-ALv2. Each published version becomes available under Apache-2.0
27
- two years after publication.
103
+ FSL-1.1-ALv2. Each release becomes available under Apache-2.0 two years after publication. See [the full license](https://github.com/corbet-labs/cink/blob/main/LICENSES/FSL-1.1-ALv2.txt) for permitted use.
@@ -0,0 +1,195 @@
1
+ // src/generated/tables.ts
2
+ var DEFAULTS = { max_pixels: 1600, formats: ["png", "jpeg", "svg"] };
3
+
4
+ // src/index.ts
5
+ var defaults = DEFAULTS;
6
+ function defaultMaxPixels() {
7
+ return defaults.max_pixels;
8
+ }
9
+ function supportedFormats() {
10
+ return [...defaults.formats].sort();
11
+ }
12
+ var PNG_MAGIC = [137, 80, 78, 71, 13, 10, 26, 10];
13
+ function pngDimensions(bytes) {
14
+ if (bytes.length < 33)
15
+ return null;
16
+ for (let i = 0;i < 8; i++)
17
+ if (bytes[i] !== PNG_MAGIC[i])
18
+ return null;
19
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
20
+ if (view.getUint32(8) !== 13)
21
+ return null;
22
+ if (view.getUint32(12) !== 1229472850)
23
+ return null;
24
+ const width = view.getUint32(16);
25
+ const height = view.getUint32(20);
26
+ if (width === 0 || height === 0 || width > 2147483647 || height > 2147483647)
27
+ return null;
28
+ const depth = bytes[24];
29
+ const color = bytes[25];
30
+ const validDepth = color === 0 ? [1, 2, 4, 8, 16].includes(depth) : color === 3 ? [1, 2, 4, 8].includes(depth) : [2, 4, 6].includes(color) && [8, 16].includes(depth);
31
+ if (!validDepth || bytes[26] !== 0 || bytes[27] !== 0 || bytes[28] > 1)
32
+ return null;
33
+ return [width, height];
34
+ }
35
+ var SOF_MARKERS = new Set([
36
+ 192,
37
+ 193,
38
+ 194,
39
+ 195,
40
+ 197,
41
+ 198,
42
+ 199,
43
+ 201,
44
+ 202,
45
+ 203,
46
+ 205,
47
+ 206,
48
+ 207
49
+ ]);
50
+ function jpegDimensions(bytes) {
51
+ if (bytes.length < 2 || bytes[0] !== 255 || bytes[1] !== 216)
52
+ return null;
53
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
54
+ let pos = 2;
55
+ while (pos < bytes.length) {
56
+ if (bytes[pos] !== 255)
57
+ return null;
58
+ while (pos < bytes.length && bytes[pos] === 255)
59
+ pos++;
60
+ if (pos >= bytes.length)
61
+ return null;
62
+ const marker = bytes[pos];
63
+ pos++;
64
+ if (marker === 1)
65
+ continue;
66
+ if (marker === 0 || marker >= 208 && marker <= 218)
67
+ return null;
68
+ if (pos + 2 > bytes.length)
69
+ return null;
70
+ const len = view.getUint16(pos);
71
+ if (len < 2 || len > bytes.length - pos)
72
+ return null;
73
+ if (SOF_MARKERS.has(marker)) {
74
+ if (len < 8)
75
+ return null;
76
+ const components = bytes[pos + 7];
77
+ if (components === 0 || len !== 8 + 3 * components)
78
+ return null;
79
+ const height = view.getUint16(pos + 3);
80
+ const width = view.getUint16(pos + 5);
81
+ if (width === 0 || height === 0)
82
+ return null;
83
+ return [width, height];
84
+ }
85
+ pos += len;
86
+ }
87
+ return null;
88
+ }
89
+ function sniff(bytes) {
90
+ if (bytes.length >= 8 && PNG_MAGIC.every((b, i) => bytes[i] === b)) {
91
+ const dims = pngDimensions(bytes);
92
+ if (dims === null)
93
+ return null;
94
+ return { mime: "png", width: dims[0], height: dims[1], bytes };
95
+ }
96
+ if (bytes.length >= 2 && bytes[0] === 255 && bytes[1] === 216) {
97
+ const dims = jpegDimensions(bytes);
98
+ if (dims === null)
99
+ return null;
100
+ return { mime: "jpeg", width: dims[0], height: dims[1], bytes };
101
+ }
102
+ let start = 0;
103
+ while (start < bytes.length && [9, 10, 12, 13, 32].includes(bytes[start]))
104
+ start++;
105
+ const head = String.fromCharCode(...bytes.slice(start, start + 4));
106
+ if (head === "<svg")
107
+ return { mime: "svg", width: null, height: null, bytes };
108
+ return null;
109
+ }
110
+ function decodeBase64(payload) {
111
+ if (payload === "")
112
+ return null;
113
+ try {
114
+ const text = atob(payload);
115
+ if (btoa(text) !== payload)
116
+ return null;
117
+ const bytes = new Uint8Array(text.length);
118
+ for (let i = 0;i < text.length; i++)
119
+ bytes[i] = text.charCodeAt(i);
120
+ return bytes.length > 0 ? bytes : null;
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+ function normalize(input) {
126
+ let payload = input;
127
+ const comma = input.indexOf(",");
128
+ if (comma >= 0 && input.startsWith("data:")) {
129
+ const meta = input.slice(0, comma);
130
+ if (!meta.endsWith(";base64"))
131
+ return null;
132
+ payload = input.slice(comma + 1);
133
+ }
134
+ const bytes = decodeBase64(payload);
135
+ if (bytes === null)
136
+ return null;
137
+ return sniff(bytes);
138
+ }
139
+ function exceedsLimits(image, maxPixels) {
140
+ if (image.width === null || image.height === null)
141
+ return false;
142
+ return image.width * image.height > maxPixels;
143
+ }
144
+ function scaleToFit(image, maxPixels) {
145
+ if (image.width === null || image.height === null)
146
+ return 1;
147
+ const pixels = image.width * image.height;
148
+ if (pixels <= maxPixels)
149
+ return 1;
150
+ return Math.sqrt(maxPixels / pixels);
151
+ }
152
+ function signatureSize(image, heightPt, maxWidthPt) {
153
+ if (image.width === null || image.height === null || !Number.isInteger(image.width) || !Number.isInteger(image.height) || image.width <= 0 || image.height <= 0 || image.width > 4294967295 || image.height > 4294967295 || !Number.isFinite(heightPt) || heightPt <= 0 || maxWidthPt !== undefined && (!Number.isFinite(maxWidthPt) || maxWidthPt <= 0))
154
+ return null;
155
+ const ratio = image.width / image.height;
156
+ const natural = heightPt * ratio;
157
+ let width = natural;
158
+ let height = heightPt;
159
+ if (maxWidthPt !== undefined && natural > maxWidthPt) {
160
+ width = maxWidthPt;
161
+ height = maxWidthPt / ratio;
162
+ }
163
+ return Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0 ? [width, height] : null;
164
+ }
165
+ function escapePath(path) {
166
+ return path.replace(/["\\\u0000-\u001f\u007f-\u009f]/g, (character) => {
167
+ if (character === '"')
168
+ return "\\\"";
169
+ if (character === "\\")
170
+ return "\\\\";
171
+ if (character === `
172
+ `)
173
+ return "\\n";
174
+ if (character === "\r")
175
+ return "\\r";
176
+ if (character === "\t")
177
+ return "\\t";
178
+ return `\\u{${character.charCodeAt(0).toString(16)}}`;
179
+ });
180
+ }
181
+ function imageSnippet(path, heightPt, widthPt) {
182
+ const safe = escapePath(path);
183
+ if (widthPt === undefined)
184
+ return `#image("${safe}", height: ${heightPt}pt)`;
185
+ return `#image("${safe}", height: ${heightPt}pt, width: ${widthPt}pt)`;
186
+ }
187
+ export {
188
+ supportedFormats,
189
+ signatureSize,
190
+ scaleToFit,
191
+ normalize,
192
+ imageSnippet,
193
+ exceedsLimits,
194
+ defaultMaxPixels
195
+ };
package/dist/index.cjs ADDED
@@ -0,0 +1,237 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ function __accessProp(key) {
6
+ return this[key];
7
+ }
8
+ var __toCommonJS = (from) => {
9
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
10
+ if (entry)
11
+ return entry;
12
+ entry = __defProp({}, "__esModule", { value: true });
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (var key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(entry, key))
16
+ __defProp(entry, key, {
17
+ get: __accessProp.bind(from, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ __moduleCache.set(from, entry);
22
+ return entry;
23
+ };
24
+ var __moduleCache;
25
+ var __returnValue = (v) => v;
26
+ function __exportSetter(name, newValue) {
27
+ this[name] = __returnValue.bind(null, newValue);
28
+ }
29
+ var __export = (target, all) => {
30
+ for (var name in all)
31
+ __defProp(target, name, {
32
+ get: all[name],
33
+ enumerable: true,
34
+ configurable: true,
35
+ set: __exportSetter.bind(all, name)
36
+ });
37
+ };
38
+
39
+ // src/index.ts
40
+ var exports_src = {};
41
+ __export(exports_src, {
42
+ supportedFormats: () => supportedFormats,
43
+ signatureSize: () => signatureSize,
44
+ scaleToFit: () => scaleToFit,
45
+ normalize: () => normalize,
46
+ imageSnippet: () => imageSnippet,
47
+ exceedsLimits: () => exceedsLimits,
48
+ defaultMaxPixels: () => defaultMaxPixels
49
+ });
50
+ module.exports = __toCommonJS(exports_src);
51
+
52
+ // src/generated/tables.ts
53
+ var DEFAULTS = { max_pixels: 1600, formats: ["png", "jpeg", "svg"] };
54
+
55
+ // src/index.ts
56
+ var defaults = DEFAULTS;
57
+ function defaultMaxPixels() {
58
+ return defaults.max_pixels;
59
+ }
60
+ function supportedFormats() {
61
+ return [...defaults.formats].sort();
62
+ }
63
+ var PNG_MAGIC = [137, 80, 78, 71, 13, 10, 26, 10];
64
+ function pngDimensions(bytes) {
65
+ if (bytes.length < 33)
66
+ return null;
67
+ for (let i = 0;i < 8; i++)
68
+ if (bytes[i] !== PNG_MAGIC[i])
69
+ return null;
70
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
71
+ if (view.getUint32(8) !== 13)
72
+ return null;
73
+ if (view.getUint32(12) !== 1229472850)
74
+ return null;
75
+ const width = view.getUint32(16);
76
+ const height = view.getUint32(20);
77
+ if (width === 0 || height === 0 || width > 2147483647 || height > 2147483647)
78
+ return null;
79
+ const depth = bytes[24];
80
+ const color = bytes[25];
81
+ const validDepth = color === 0 ? [1, 2, 4, 8, 16].includes(depth) : color === 3 ? [1, 2, 4, 8].includes(depth) : [2, 4, 6].includes(color) && [8, 16].includes(depth);
82
+ if (!validDepth || bytes[26] !== 0 || bytes[27] !== 0 || bytes[28] > 1)
83
+ return null;
84
+ return [width, height];
85
+ }
86
+ var SOF_MARKERS = new Set([
87
+ 192,
88
+ 193,
89
+ 194,
90
+ 195,
91
+ 197,
92
+ 198,
93
+ 199,
94
+ 201,
95
+ 202,
96
+ 203,
97
+ 205,
98
+ 206,
99
+ 207
100
+ ]);
101
+ function jpegDimensions(bytes) {
102
+ if (bytes.length < 2 || bytes[0] !== 255 || bytes[1] !== 216)
103
+ return null;
104
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
105
+ let pos = 2;
106
+ while (pos < bytes.length) {
107
+ if (bytes[pos] !== 255)
108
+ return null;
109
+ while (pos < bytes.length && bytes[pos] === 255)
110
+ pos++;
111
+ if (pos >= bytes.length)
112
+ return null;
113
+ const marker = bytes[pos];
114
+ pos++;
115
+ if (marker === 1)
116
+ continue;
117
+ if (marker === 0 || marker >= 208 && marker <= 218)
118
+ return null;
119
+ if (pos + 2 > bytes.length)
120
+ return null;
121
+ const len = view.getUint16(pos);
122
+ if (len < 2 || len > bytes.length - pos)
123
+ return null;
124
+ if (SOF_MARKERS.has(marker)) {
125
+ if (len < 8)
126
+ return null;
127
+ const components = bytes[pos + 7];
128
+ if (components === 0 || len !== 8 + 3 * components)
129
+ return null;
130
+ const height = view.getUint16(pos + 3);
131
+ const width = view.getUint16(pos + 5);
132
+ if (width === 0 || height === 0)
133
+ return null;
134
+ return [width, height];
135
+ }
136
+ pos += len;
137
+ }
138
+ return null;
139
+ }
140
+ function sniff(bytes) {
141
+ if (bytes.length >= 8 && PNG_MAGIC.every((b, i) => bytes[i] === b)) {
142
+ const dims = pngDimensions(bytes);
143
+ if (dims === null)
144
+ return null;
145
+ return { mime: "png", width: dims[0], height: dims[1], bytes };
146
+ }
147
+ if (bytes.length >= 2 && bytes[0] === 255 && bytes[1] === 216) {
148
+ const dims = jpegDimensions(bytes);
149
+ if (dims === null)
150
+ return null;
151
+ return { mime: "jpeg", width: dims[0], height: dims[1], bytes };
152
+ }
153
+ let start = 0;
154
+ while (start < bytes.length && [9, 10, 12, 13, 32].includes(bytes[start]))
155
+ start++;
156
+ const head = String.fromCharCode(...bytes.slice(start, start + 4));
157
+ if (head === "<svg")
158
+ return { mime: "svg", width: null, height: null, bytes };
159
+ return null;
160
+ }
161
+ function decodeBase64(payload) {
162
+ if (payload === "")
163
+ return null;
164
+ try {
165
+ const text = atob(payload);
166
+ if (btoa(text) !== payload)
167
+ return null;
168
+ const bytes = new Uint8Array(text.length);
169
+ for (let i = 0;i < text.length; i++)
170
+ bytes[i] = text.charCodeAt(i);
171
+ return bytes.length > 0 ? bytes : null;
172
+ } catch {
173
+ return null;
174
+ }
175
+ }
176
+ function normalize(input) {
177
+ let payload = input;
178
+ const comma = input.indexOf(",");
179
+ if (comma >= 0 && input.startsWith("data:")) {
180
+ const meta = input.slice(0, comma);
181
+ if (!meta.endsWith(";base64"))
182
+ return null;
183
+ payload = input.slice(comma + 1);
184
+ }
185
+ const bytes = decodeBase64(payload);
186
+ if (bytes === null)
187
+ return null;
188
+ return sniff(bytes);
189
+ }
190
+ function exceedsLimits(image, maxPixels) {
191
+ if (image.width === null || image.height === null)
192
+ return false;
193
+ return image.width * image.height > maxPixels;
194
+ }
195
+ function scaleToFit(image, maxPixels) {
196
+ if (image.width === null || image.height === null)
197
+ return 1;
198
+ const pixels = image.width * image.height;
199
+ if (pixels <= maxPixels)
200
+ return 1;
201
+ return Math.sqrt(maxPixels / pixels);
202
+ }
203
+ function signatureSize(image, heightPt, maxWidthPt) {
204
+ if (image.width === null || image.height === null || !Number.isInteger(image.width) || !Number.isInteger(image.height) || image.width <= 0 || image.height <= 0 || image.width > 4294967295 || image.height > 4294967295 || !Number.isFinite(heightPt) || heightPt <= 0 || maxWidthPt !== undefined && (!Number.isFinite(maxWidthPt) || maxWidthPt <= 0))
205
+ return null;
206
+ const ratio = image.width / image.height;
207
+ const natural = heightPt * ratio;
208
+ let width = natural;
209
+ let height = heightPt;
210
+ if (maxWidthPt !== undefined && natural > maxWidthPt) {
211
+ width = maxWidthPt;
212
+ height = maxWidthPt / ratio;
213
+ }
214
+ return Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0 ? [width, height] : null;
215
+ }
216
+ function escapePath(path) {
217
+ return path.replace(/["\\\u0000-\u001f\u007f-\u009f]/g, (character) => {
218
+ if (character === '"')
219
+ return "\\\"";
220
+ if (character === "\\")
221
+ return "\\\\";
222
+ if (character === `
223
+ `)
224
+ return "\\n";
225
+ if (character === "\r")
226
+ return "\\r";
227
+ if (character === "\t")
228
+ return "\\t";
229
+ return `\\u{${character.charCodeAt(0).toString(16)}}`;
230
+ });
231
+ }
232
+ function imageSnippet(path, heightPt, widthPt) {
233
+ const safe = escapePath(path);
234
+ if (widthPt === undefined)
235
+ return `#image("${safe}", height: ${heightPt}pt)`;
236
+ return `#image("${safe}", height: ${heightPt}pt, width: ${widthPt}pt)`;
237
+ }
package/dist/index.js ADDED
@@ -0,0 +1,195 @@
1
+ // src/generated/tables.ts
2
+ var DEFAULTS = { max_pixels: 1600, formats: ["png", "jpeg", "svg"] };
3
+
4
+ // src/index.ts
5
+ var defaults = DEFAULTS;
6
+ function defaultMaxPixels() {
7
+ return defaults.max_pixels;
8
+ }
9
+ function supportedFormats() {
10
+ return [...defaults.formats].sort();
11
+ }
12
+ var PNG_MAGIC = [137, 80, 78, 71, 13, 10, 26, 10];
13
+ function pngDimensions(bytes) {
14
+ if (bytes.length < 33)
15
+ return null;
16
+ for (let i = 0;i < 8; i++)
17
+ if (bytes[i] !== PNG_MAGIC[i])
18
+ return null;
19
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
20
+ if (view.getUint32(8) !== 13)
21
+ return null;
22
+ if (view.getUint32(12) !== 1229472850)
23
+ return null;
24
+ const width = view.getUint32(16);
25
+ const height = view.getUint32(20);
26
+ if (width === 0 || height === 0 || width > 2147483647 || height > 2147483647)
27
+ return null;
28
+ const depth = bytes[24];
29
+ const color = bytes[25];
30
+ const validDepth = color === 0 ? [1, 2, 4, 8, 16].includes(depth) : color === 3 ? [1, 2, 4, 8].includes(depth) : [2, 4, 6].includes(color) && [8, 16].includes(depth);
31
+ if (!validDepth || bytes[26] !== 0 || bytes[27] !== 0 || bytes[28] > 1)
32
+ return null;
33
+ return [width, height];
34
+ }
35
+ var SOF_MARKERS = new Set([
36
+ 192,
37
+ 193,
38
+ 194,
39
+ 195,
40
+ 197,
41
+ 198,
42
+ 199,
43
+ 201,
44
+ 202,
45
+ 203,
46
+ 205,
47
+ 206,
48
+ 207
49
+ ]);
50
+ function jpegDimensions(bytes) {
51
+ if (bytes.length < 2 || bytes[0] !== 255 || bytes[1] !== 216)
52
+ return null;
53
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
54
+ let pos = 2;
55
+ while (pos < bytes.length) {
56
+ if (bytes[pos] !== 255)
57
+ return null;
58
+ while (pos < bytes.length && bytes[pos] === 255)
59
+ pos++;
60
+ if (pos >= bytes.length)
61
+ return null;
62
+ const marker = bytes[pos];
63
+ pos++;
64
+ if (marker === 1)
65
+ continue;
66
+ if (marker === 0 || marker >= 208 && marker <= 218)
67
+ return null;
68
+ if (pos + 2 > bytes.length)
69
+ return null;
70
+ const len = view.getUint16(pos);
71
+ if (len < 2 || len > bytes.length - pos)
72
+ return null;
73
+ if (SOF_MARKERS.has(marker)) {
74
+ if (len < 8)
75
+ return null;
76
+ const components = bytes[pos + 7];
77
+ if (components === 0 || len !== 8 + 3 * components)
78
+ return null;
79
+ const height = view.getUint16(pos + 3);
80
+ const width = view.getUint16(pos + 5);
81
+ if (width === 0 || height === 0)
82
+ return null;
83
+ return [width, height];
84
+ }
85
+ pos += len;
86
+ }
87
+ return null;
88
+ }
89
+ function sniff(bytes) {
90
+ if (bytes.length >= 8 && PNG_MAGIC.every((b, i) => bytes[i] === b)) {
91
+ const dims = pngDimensions(bytes);
92
+ if (dims === null)
93
+ return null;
94
+ return { mime: "png", width: dims[0], height: dims[1], bytes };
95
+ }
96
+ if (bytes.length >= 2 && bytes[0] === 255 && bytes[1] === 216) {
97
+ const dims = jpegDimensions(bytes);
98
+ if (dims === null)
99
+ return null;
100
+ return { mime: "jpeg", width: dims[0], height: dims[1], bytes };
101
+ }
102
+ let start = 0;
103
+ while (start < bytes.length && [9, 10, 12, 13, 32].includes(bytes[start]))
104
+ start++;
105
+ const head = String.fromCharCode(...bytes.slice(start, start + 4));
106
+ if (head === "<svg")
107
+ return { mime: "svg", width: null, height: null, bytes };
108
+ return null;
109
+ }
110
+ function decodeBase64(payload) {
111
+ if (payload === "")
112
+ return null;
113
+ try {
114
+ const text = atob(payload);
115
+ if (btoa(text) !== payload)
116
+ return null;
117
+ const bytes = new Uint8Array(text.length);
118
+ for (let i = 0;i < text.length; i++)
119
+ bytes[i] = text.charCodeAt(i);
120
+ return bytes.length > 0 ? bytes : null;
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+ function normalize(input) {
126
+ let payload = input;
127
+ const comma = input.indexOf(",");
128
+ if (comma >= 0 && input.startsWith("data:")) {
129
+ const meta = input.slice(0, comma);
130
+ if (!meta.endsWith(";base64"))
131
+ return null;
132
+ payload = input.slice(comma + 1);
133
+ }
134
+ const bytes = decodeBase64(payload);
135
+ if (bytes === null)
136
+ return null;
137
+ return sniff(bytes);
138
+ }
139
+ function exceedsLimits(image, maxPixels) {
140
+ if (image.width === null || image.height === null)
141
+ return false;
142
+ return image.width * image.height > maxPixels;
143
+ }
144
+ function scaleToFit(image, maxPixels) {
145
+ if (image.width === null || image.height === null)
146
+ return 1;
147
+ const pixels = image.width * image.height;
148
+ if (pixels <= maxPixels)
149
+ return 1;
150
+ return Math.sqrt(maxPixels / pixels);
151
+ }
152
+ function signatureSize(image, heightPt, maxWidthPt) {
153
+ if (image.width === null || image.height === null || !Number.isInteger(image.width) || !Number.isInteger(image.height) || image.width <= 0 || image.height <= 0 || image.width > 4294967295 || image.height > 4294967295 || !Number.isFinite(heightPt) || heightPt <= 0 || maxWidthPt !== undefined && (!Number.isFinite(maxWidthPt) || maxWidthPt <= 0))
154
+ return null;
155
+ const ratio = image.width / image.height;
156
+ const natural = heightPt * ratio;
157
+ let width = natural;
158
+ let height = heightPt;
159
+ if (maxWidthPt !== undefined && natural > maxWidthPt) {
160
+ width = maxWidthPt;
161
+ height = maxWidthPt / ratio;
162
+ }
163
+ return Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0 ? [width, height] : null;
164
+ }
165
+ function escapePath(path) {
166
+ return path.replace(/["\\\u0000-\u001f\u007f-\u009f]/g, (character) => {
167
+ if (character === '"')
168
+ return "\\\"";
169
+ if (character === "\\")
170
+ return "\\\\";
171
+ if (character === `
172
+ `)
173
+ return "\\n";
174
+ if (character === "\r")
175
+ return "\\r";
176
+ if (character === "\t")
177
+ return "\\t";
178
+ return `\\u{${character.charCodeAt(0).toString(16)}}`;
179
+ });
180
+ }
181
+ function imageSnippet(path, heightPt, widthPt) {
182
+ const safe = escapePath(path);
183
+ if (widthPt === undefined)
184
+ return `#image("${safe}", height: ${heightPt}pt)`;
185
+ return `#image("${safe}", height: ${heightPt}pt, width: ${widthPt}pt)`;
186
+ }
187
+ export {
188
+ supportedFormats,
189
+ signatureSize,
190
+ scaleToFit,
191
+ normalize,
192
+ imageSnippet,
193
+ exceedsLimits,
194
+ defaultMaxPixels
195
+ };
@@ -0,0 +1,2 @@
1
+ export declare const PACKAGE_VERSION: string;
2
+ export declare const DEFAULTS: unknown;
@@ -0,0 +1,42 @@
1
+ export interface Defaults {
2
+ max_pixels: number;
3
+ formats: string[];
4
+ }
5
+ export type ImageMime = 'png' | 'jpeg' | 'svg';
6
+ export interface DecodedImage {
7
+ mime: ImageMime;
8
+ width: number | null;
9
+ height: number | null;
10
+ bytes: Uint8Array;
11
+ }
12
+ /** Default oversize threshold in pixels, from `tables/defaults.json`. */
13
+ export declare function defaultMaxPixels(): number;
14
+ /** Accepted image formats, from `tables/defaults.json`. */
15
+ export declare function supportedFormats(): string[];
16
+ /**
17
+ * Recognize a signature image given as a `data:` URL or raw canonical base64.
18
+ * Required padding must be present; whitespace and nonzero unused bits are rejected.
19
+ * Returns `null` for empty, undecodable, corrupt, or unsupported inputs.
20
+ */
21
+ export declare function normalize(input: string): DecodedImage | null;
22
+ /**
23
+ * Whether the raster exceeds a pixel budget. Dimension-less formats (SVG)
24
+ * scale without loss and never exceed.
25
+ */
26
+ export declare function exceedsLimits(image: DecodedImage, maxPixels: number): boolean;
27
+ /**
28
+ * Linear scale factor that fits the image into a pixel budget, never
29
+ * above 1.0 (never upscales). The caller resamples and re-submits.
30
+ */
31
+ export declare function scaleToFit(image: DecodedImage, maxPixels: number): number;
32
+ /**
33
+ * Point size for a target height, preserving aspect ratio, clamped to an
34
+ * optional maximum width. Returns `null` for missing or invalid dimensions,
35
+ * nonpositive/nonfinite point sizes, or a nonrepresentable result.
36
+ */
37
+ export declare function signatureSize(image: DecodedImage, heightPt: number, maxWidthPt?: number): [number, number] | null;
38
+ /**
39
+ * Typst `#image` call for a sized signature. Width is emitted only when a
40
+ * max-width clamp applied; layout and placement stay with the caller.
41
+ */
42
+ export declare function imageSnippet(path: string, heightPt: number, widthPt?: number): string;
@@ -0,0 +1,42 @@
1
+ export interface Defaults {
2
+ max_pixels: number;
3
+ formats: string[];
4
+ }
5
+ export type ImageMime = 'png' | 'jpeg' | 'svg';
6
+ export interface DecodedImage {
7
+ mime: ImageMime;
8
+ width: number | null;
9
+ height: number | null;
10
+ bytes: Uint8Array;
11
+ }
12
+ /** Default oversize threshold in pixels, from `tables/defaults.json`. */
13
+ export declare function defaultMaxPixels(): number;
14
+ /** Accepted image formats, from `tables/defaults.json`. */
15
+ export declare function supportedFormats(): string[];
16
+ /**
17
+ * Recognize a signature image given as a `data:` URL or raw canonical base64.
18
+ * Required padding must be present; whitespace and nonzero unused bits are rejected.
19
+ * Returns `null` for empty, undecodable, corrupt, or unsupported inputs.
20
+ */
21
+ export declare function normalize(input: string): DecodedImage | null;
22
+ /**
23
+ * Whether the raster exceeds a pixel budget. Dimension-less formats (SVG)
24
+ * scale without loss and never exceed.
25
+ */
26
+ export declare function exceedsLimits(image: DecodedImage, maxPixels: number): boolean;
27
+ /**
28
+ * Linear scale factor that fits the image into a pixel budget, never
29
+ * above 1.0 (never upscales). The caller resamples and re-submits.
30
+ */
31
+ export declare function scaleToFit(image: DecodedImage, maxPixels: number): number;
32
+ /**
33
+ * Point size for a target height, preserving aspect ratio, clamped to an
34
+ * optional maximum width. Returns `null` for missing or invalid dimensions,
35
+ * nonpositive/nonfinite point sizes, or a nonrepresentable result.
36
+ */
37
+ export declare function signatureSize(image: DecodedImage, heightPt: number, maxWidthPt?: number): [number, number] | null;
38
+ /**
39
+ * Typst `#image` call for a sized signature. Width is emitted only when a
40
+ * max-width clamp applied; layout and placement stay with the caller.
41
+ */
42
+ export declare function imageSnippet(path: string, heightPt: number, widthPt?: number): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@corbet-labs/cink",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Handwritten signature image rendering for correspondence. Pixels, not signatures. Mirrors the cink Rust crate release line.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "publishConfig": {
@@ -9,26 +9,62 @@
9
9
  },
10
10
  "repository": {
11
11
  "type": "git",
12
- "url": "https://github.com/corbet-labs/cink.git",
12
+ "url": "git+https://github.com/corbet-labs/cink.git",
13
13
  "directory": "js/@corbet-labs/cink"
14
14
  },
15
15
  "type": "module",
16
- "main": "./src/index.ts",
17
- "types": "./src/index.ts",
16
+ "main": "./dist/index.cjs",
17
+ "types": "./dist/types/index.d.ts",
18
18
  "exports": {
19
- ".": "./src/index.ts"
19
+ ".": {
20
+ "import": {
21
+ "types": "./dist/types/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "require": {
25
+ "types": "./dist/types/index.d.cts",
26
+ "default": "./dist/index.cjs"
27
+ },
28
+ "default": "./dist/index.js"
29
+ },
30
+ "./browser": {
31
+ "types": "./dist/types/index.d.ts",
32
+ "default": "./dist/browser.js"
33
+ },
34
+ "./package.json": "./package.json"
20
35
  },
21
36
  "files": [
37
+ "dist/**/*",
22
38
  "src/**/*",
23
- "README.md"
39
+ "README.md",
40
+ "LICENSES/**/*"
24
41
  ],
25
42
  "scripts": {
26
- "prepack": "bash ./scripts/sync-assets.sh",
43
+ "prepack": "bun run build",
27
44
  "conformance": "bun ./scripts/conformance.mts",
28
- "typecheck": "tsc --noEmit -p ./tsconfig.json"
45
+ "typecheck": "tsc --noEmit -p ./tsconfig.json",
46
+ "build": "bun ./scripts/build.mjs"
29
47
  },
30
48
  "devDependencies": {
31
49
  "@types/node": "25.8.0",
32
50
  "typescript": "6.0.3"
33
- }
51
+ },
52
+ "module": "./dist/index.js",
53
+ "unpkg": "./dist/browser.js",
54
+ "jsdelivr": "./dist/browser.js",
55
+ "sideEffects": false,
56
+ "engines": {
57
+ "node": ">=20"
58
+ },
59
+ "homepage": "https://github.com/corbet-labs/cink#readme",
60
+ "bugs": {
61
+ "url": "https://github.com/corbet-labs/cink/issues"
62
+ },
63
+ "keywords": [
64
+ "i18n",
65
+ "correspondence",
66
+ "typescript",
67
+ "rust",
68
+ "cink"
69
+ ]
34
70
  }
@@ -1,3 +1,3 @@
1
1
  // GENERATED by scripts/sync-assets.sh — do not edit.
2
- export const PACKAGE_VERSION = "0.1.1";
3
- export const DEFAULTS = {"max_pixels": 1600, "formats": ["png", "jpeg", "svg"]};
2
+ export const PACKAGE_VERSION: string = "0.1.3";
3
+ export const DEFAULTS: unknown = {"max_pixels": 1600, "formats": ["png", "jpeg", "svg"]};
package/src/index.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  * in `tables/README.md`; `tests/vectors/*.json` with fixtures in
10
10
  * `tests/fixtures/` is the shared conformance suite.
11
11
  */
12
- import { DEFAULTS } from './generated/tables.js';
12
+ import { DEFAULTS } from './generated/tables.ts';
13
13
 
14
14
  export interface Defaults {
15
15
  max_pixels: number;
@@ -40,14 +40,20 @@ export function supportedFormats(): string[] {
40
40
  const PNG_MAGIC = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
41
41
 
42
42
  function pngDimensions(bytes: Uint8Array): [number, number] | null {
43
- if (bytes.length < 24) return null;
43
+ if (bytes.length < 33) return null;
44
44
  for (let i = 0; i < 8; i++) if (bytes[i] !== PNG_MAGIC[i]) return null;
45
45
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
46
46
  if (view.getUint32(8) !== 13) return null;
47
47
  if (view.getUint32(12) !== 0x49484452) return null;
48
48
  const width = view.getUint32(16);
49
49
  const height = view.getUint32(20);
50
- if (width === 0 || height === 0) return null;
50
+ if (width === 0 || height === 0 || width > 0x7fffffff || height > 0x7fffffff) return null;
51
+ const depth = bytes[24];
52
+ const color = bytes[25];
53
+ const validDepth = color === 0 ? [1, 2, 4, 8, 16].includes(depth)
54
+ : color === 3 ? [1, 2, 4, 8].includes(depth)
55
+ : [2, 4, 6].includes(color) && [8, 16].includes(depth);
56
+ if (!validDepth || bytes[26] !== 0 || bytes[27] !== 0 || bytes[28] > 1) return null;
51
57
  return [width, height];
52
58
  }
53
59
 
@@ -60,22 +66,25 @@ function jpegDimensions(bytes: Uint8Array): [number, number] | null {
60
66
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
61
67
  let pos = 2;
62
68
  while (pos < bytes.length) {
69
+ if (bytes[pos] !== 0xff) return null;
63
70
  while (pos < bytes.length && bytes[pos] === 0xff) pos++;
64
71
  if (pos >= bytes.length) return null;
65
72
  const marker = bytes[pos];
66
73
  pos++;
74
+ if (marker === 0x01) continue;
75
+ if (marker === 0x00 || (marker >= 0xd0 && marker <= 0xda)) return null;
76
+ if (pos + 2 > bytes.length) return null;
77
+ const len = view.getUint16(pos);
78
+ if (len < 2 || len > bytes.length - pos) return null;
67
79
  if (SOF_MARKERS.has(marker)) {
68
- if (pos + 7 > bytes.length) return null;
80
+ if (len < 8) return null;
81
+ const components = bytes[pos + 7];
82
+ if (components === 0 || len !== 8 + 3 * components) return null;
69
83
  const height = view.getUint16(pos + 3);
70
84
  const width = view.getUint16(pos + 5);
71
85
  if (width === 0 || height === 0) return null;
72
86
  return [width, height];
73
87
  }
74
- if (marker === 0xd9 || marker === 0xda) return null;
75
- if (marker === 0x00 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;
76
- if (pos + 2 > bytes.length) return null;
77
- const len = view.getUint16(pos);
78
- if (len < 2) return null;
79
88
  pos += len;
80
89
  }
81
90
  return null;
@@ -93,7 +102,7 @@ function sniff(bytes: Uint8Array): DecodedImage | null {
93
102
  return { mime: 'jpeg', width: dims[0], height: dims[1], bytes };
94
103
  }
95
104
  let start = 0;
96
- while (start < bytes.length && /\s/.test(String.fromCharCode(bytes[start]))) start++;
105
+ while (start < bytes.length && [9, 10, 12, 13, 32].includes(bytes[start])) start++;
97
106
  const head = String.fromCharCode(...bytes.slice(start, start + 4));
98
107
  if (head === '<svg') return { mime: 'svg', width: null, height: null, bytes };
99
108
  return null;
@@ -103,6 +112,8 @@ function decodeBase64(payload: string): Uint8Array | null {
103
112
  if (payload === '') return null;
104
113
  try {
105
114
  const text = atob(payload);
115
+ // Rust STANDARD accepts only canonical base64, including required padding.
116
+ if (btoa(text) !== payload) return null;
106
117
  const bytes = new Uint8Array(text.length);
107
118
  for (let i = 0; i < text.length; i++) bytes[i] = text.charCodeAt(i);
108
119
  return bytes.length > 0 ? bytes : null;
@@ -112,7 +123,8 @@ function decodeBase64(payload: string): Uint8Array | null {
112
123
  }
113
124
 
114
125
  /**
115
- * Validate a signature image given as a `data:` URL or raw base64.
126
+ * Recognize a signature image given as a `data:` URL or raw canonical base64.
127
+ * Required padding must be present; whitespace and nonzero unused bits are rejected.
116
128
  * Returns `null` for empty, undecodable, corrupt, or unsupported inputs.
117
129
  */
118
130
  export function normalize(input: string): DecodedImage | null {
@@ -120,7 +132,7 @@ export function normalize(input: string): DecodedImage | null {
120
132
  const comma = input.indexOf(',');
121
133
  if (comma >= 0 && input.startsWith('data:')) {
122
134
  const meta = input.slice(0, comma);
123
- if (!meta.includes(';base64')) return null;
135
+ if (!meta.endsWith(';base64')) return null;
124
136
  payload = input.slice(comma + 1);
125
137
  }
126
138
  const bytes = decodeBase64(payload);
@@ -150,25 +162,41 @@ export function scaleToFit(image: DecodedImage, maxPixels: number): number {
150
162
 
151
163
  /**
152
164
  * Point size for a target height, preserving aspect ratio, clamped to an
153
- * optional maximum width. Returns `null` when the image carries no
154
- * dimensions: the caller must size it.
165
+ * optional maximum width. Returns `null` for missing or invalid dimensions,
166
+ * nonpositive/nonfinite point sizes, or a nonrepresentable result.
155
167
  */
156
168
  export function signatureSize(
157
169
  image: DecodedImage,
158
170
  heightPt: number,
159
171
  maxWidthPt?: number,
160
172
  ): [number, number] | null {
161
- if (image.width === null || image.height === null) return null;
162
- const natural = (heightPt * image.width) / image.height;
173
+ if (image.width === null || image.height === null
174
+ || !Number.isInteger(image.width) || !Number.isInteger(image.height)
175
+ || image.width <= 0 || image.height <= 0
176
+ || image.width > 0xffffffff || image.height > 0xffffffff
177
+ || !Number.isFinite(heightPt) || heightPt <= 0
178
+ || (maxWidthPt !== undefined && (!Number.isFinite(maxWidthPt) || maxWidthPt <= 0))) return null;
179
+ const ratio = image.width / image.height;
180
+ const natural = heightPt * ratio;
181
+ let width = natural;
182
+ let height = heightPt;
163
183
  if (maxWidthPt !== undefined && natural > maxWidthPt) {
164
- const scale = maxWidthPt / natural;
165
- return [maxWidthPt, heightPt * scale];
184
+ width = maxWidthPt;
185
+ height = maxWidthPt / ratio;
166
186
  }
167
- return [natural, heightPt];
187
+ return Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0
188
+ ? [width, height] : null;
168
189
  }
169
190
 
170
191
  function escapePath(path: string): string {
171
- return path.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
192
+ return path.replace(/["\\\u0000-\u001f\u007f-\u009f]/g, (character) => {
193
+ if (character === '"') return '\\"';
194
+ if (character === '\\') return '\\\\';
195
+ if (character === '\n') return '\\n';
196
+ if (character === '\r') return '\\r';
197
+ if (character === '\t') return '\\t';
198
+ return `\\u{${character.charCodeAt(0).toString(16)}}`;
199
+ });
172
200
  }
173
201
 
174
202
  /**